@svgrid/mcp 3.0.40 → 3.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/data.js CHANGED
@@ -3245,7 +3245,7 @@ export const examples = [
3245
3245
  "title": "Base Supabase",
3246
3246
  "category": "Base",
3247
3247
  "blurb": "517. Base on Supabase, live Two people on one Supabase project, side by side: each window is its own `<SvBase>` with its own client. Change a task on one side and the other",
3248
- "source": "<script lang=\"ts\">\n /**\n * 517. Base on Supabase, live\n * ---------------------------\n * Two people on one Supabase project, side by side: each window is its own\n * `<SvBase>` with its own client. Change a task on one side and the other\n * shows it a moment later, through Supabase Realtime.\n *\n * Each table is `baseSource(createSupabaseDataSource(...))`, with\n * `realtime` from `createSupabaseRealtime`. A task's project is the\n * `project_id` foreign key; the Projects table's Tasks field is worked out\n * from it. A new record gets its id from the database (a uuid), and the\n * base keeps the one it gave the row in the page, so nothing jumps.\n *\n * Turn a window offline and edit there: the request fails, the base puts\n * the cell back and says why. Back online, it reads the tables again.\n *\n * The project here is in the page (`shared/mock-supabase.ts`), so the demo\n * needs no account. With a real one, the only change is the client:\n * const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY)\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseSource, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { createSupabaseDataSource, createSupabaseRealtime, type EntitySchema } from '@svgrid/enterprise'\n import { usePeople } from '../shared/base-people'\n import { createMockProject, createMockSupabase } from '../shared/mock-supabase'\n\n enableBase()\n usePeople()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n // The database both windows share.\n const project = createMockProject({\n projects: [\n { id: 'p1', name: 'Website relaunch', owner: 'u1' },\n { id: 'p2', name: 'Customer portal', owner: 'u2' },\n ],\n tasks: [\n { id: 't1', name: 'Wireframes', status: 'Done', assignee: 'u1', due: day(-6), project_id: 'p1' },\n { id: 't2', name: 'Visual design', status: 'In progress', assignee: 'u3', due: day(2), project_id: 'p1' },\n { id: 't3', name: 'CMS migration', status: 'Todo', assignee: 'u2', due: day(9), project_id: 'p1' },\n { id: 't4', name: 'Sign-in with SSO', status: 'In progress', assignee: 'u4', due: day(4), project_id: 'p2' },\n { id: 't5', name: 'Invoices page', status: 'Todo', assignee: 'u2', due: day(12), project_id: 'p2' },\n { id: 't6', name: 'Accessibility audit', status: 'Todo', assignee: null, due: day(15), project_id: null },\n ],\n })\n\n // What the Supabase source reads of each table: its columns and key.\n const SCHEMAS: Record<string, EntitySchema> = {\n tasks: {\n name: 'tasks',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'status', type: 'text' },\n { field: 'assignee', type: 'text' },\n { field: 'due', type: 'date' },\n { field: 'project_id', type: 'text' },\n ],\n },\n projects: {\n name: 'projects',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'owner', type: 'text' },\n ],\n },\n }\n\n const STATUS = [\n { value: 'Todo', color: '#64748b' },\n { value: 'In progress', color: '#2563eb' },\n { value: 'Blocked', color: '#dc2626' },\n { value: 'Done', color: '#16a34a' },\n ]\n\n class Win {\n tables = $state.raw<BaseTable[]>([])\n offline = $state(false)\n requests = $state<string[]>([])\n reconnect = new Set<() => void>()\n who: string\n constructor(who: string) {\n this.who = who\n }\n }\n\n /**\n * One person's window: a client of the shared project and the base's\n * tables on it. The table ids differ per window only because both bases\n * are on one page; in an app they are just 'tasks' and 'projects'.\n */\n function open(who: string, prefix: string): Win {\n const win = new Win(who)\n const client = createMockSupabase(project, {\n offline: () => win.offline,\n onRequest: (line) => {\n win.requests = [line, ...win.requests].slice(0, 3)\n },\n })\n const source = (table: string, links = {}) =>\n baseSource(createSupabaseDataSource({ client: client as never, table, schema: SCHEMAS[table]! }), {\n links,\n // Supabase makes the key: a new row is inserted without the page's id.\n serverIds: true,\n realtime: (onChange) => {\n win.reconnect.add(onChange)\n const live = createSupabaseRealtime({ client: client as never, table, onChange })\n return () => {\n win.reconnect.delete(onChange)\n live.unsubscribe()\n }\n },\n })\n win.tables = [\n {\n id: `${prefix}tasks`,\n name: 'Tasks',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Task', width: 170, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 120, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'project', header: 'Project', width: 150, fieldType: 'link', fieldProps: { table: `${prefix}projects`, multiple: false, inverse: 'tasks' } },\n { field: 'assignee', header: 'Assignee', width: 140, fieldType: 'user' },\n { field: 'due', header: 'Due', width: 120, fieldType: 'date' },\n ],\n views: [\n { id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } },\n { id: 'board', name: 'Board', type: 'kanban', stackBy: 'status' },\n ],\n source: source('tasks', { project: { column: 'project_id' } }),\n props: { rowAdder: { label: 'Add task', defaults: () => ({ status: 'Todo' }) } },\n },\n {\n id: `${prefix}projects`,\n name: 'Projects',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Project', width: 170, fieldType: 'text' },\n { field: 'owner', header: 'Owner', width: 140, fieldType: 'user' },\n { field: 'tasks', header: 'Tasks', width: 260, fieldType: 'link', fieldProps: { table: `${prefix}tasks`, multiple: true, inverse: 'project' } },\n ],\n source: source('projects'),\n },\n ]\n return win\n }\n\n const windows = [open('Ana', 'a-'), open('Ben', 'b-')]\n\n function setOffline(win: Win, offline: boolean) {\n win.offline = offline\n // Back online, a realtime client reconnects and the base reads again.\n if (!offline) for (const on of win.reconnect) on()\n }\n</script>\n\n<section class=\"sbase\">\n {#each windows as win (win.who)}\n <div class=\"sbase-win\" class:is-offline={win.offline}>\n <header class=\"sbase-bar\">\n <span class=\"sbase-dots\" aria-hidden=\"true\"><i></i><i></i><i></i></span>\n <span class=\"sbase-who\">{win.who}'s browser</span>\n <label class=\"sbase-net\">\n <input type=\"checkbox\" checked={win.offline} onchange={(e) => setOffline(win, e.currentTarget.checked)} />\n Offline\n </label>\n </header>\n <div class=\"sbase-body\">\n <SvBase bind:tables={win.tables} editable sortable showRowNumbers showRowSelection={false} rowHeight={34} containerHeight=\"100%\" columnAdder={false} automations={false} />\n </div>\n <footer class=\"sbase-req\" aria-label={`${win.who}'s last requests`}>\n {#each win.requests as r, i (i)}<code>{r}</code>{/each}\n </footer>\n </div>\n {/each}\n <SvToaster />\n</section>\n\n<style>\n .sbase { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; flex: 1; min-height: 520px; }\n @media (max-width: 900px) { .sbase { grid-template-columns: 1fr; } }\n .sbase-win {\n display: flex; flex-direction: column; min-width: 0; min-height: 480px; overflow: hidden;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px); background: var(--sg-bg, #fff);\n }\n .sbase-win.is-offline { border-color: var(--sg-danger, #dc2626); }\n .sbase-bar {\n display: flex; align-items: center; gap: 10px; height: 34px; padding: 0 10px; font-size: 12px;\n color: var(--sg-muted, #64748b); background: var(--sg-header-bg, var(--sg-bg, #fff)); border-bottom: 1px solid var(--sg-border, #e2e8f0);\n }\n .sbase-dots { display: inline-flex; gap: 5px; }\n .sbase-dots i { width: 9px; height: 9px; border-radius: 50%; background: color-mix(in srgb, var(--sg-fg, #0f172a) 18%, transparent); }\n .sbase-who { flex: 1; font-weight: 600; color: var(--sg-fg, #0f172a); }\n .sbase-net { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; }\n .sbase-net input { accent-color: var(--sg-danger, #dc2626); }\n .sbase-body { flex: 1; min-height: 0; display: flex; flex-direction: column; }\n .sbase-req {\n display: flex; flex-direction: column; gap: 2px; min-height: 52px; padding: 6px 10px; box-sizing: border-box;\n border-top: 1px solid var(--sg-border, #e2e8f0); font-size: 11px; color: var(--sg-muted, #64748b);\n }\n .sbase-req code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }\n</style>\n"
3248
+ "source": "<script lang=\"ts\">\n /**\n * 517. Base on Supabase, live\n * ---------------------------\n * Two people on one Supabase project, side by side: each window is its own\n * `<SvBase>` with its own client. Change a task on one side and the other\n * shows it a moment later, through Supabase Realtime.\n *\n * Each table is `baseSource(createSupabaseDataSource(...))`, with\n * `realtime` from `createSupabaseRealtime`. A task's project is the\n * `project_id` foreign key; the Projects table's Tasks field is worked out\n * from it. A new record gets its id from the database (a uuid), and the\n * base keeps the one it gave the row in the page, so nothing jumps.\n *\n * Turn a window offline and edit there: the request fails, the base puts\n * the cell back and says why. Back online, it reads the tables again.\n *\n * The project here is in the page (`shared/mock-supabase.ts`), so the demo\n * needs no account. With a real one, the only change is the client:\n * const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY)\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseSource, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { createSupabaseDataSource, createSupabaseRealtime, type EntitySchema } from '@svgrid/enterprise'\n import { usePeople } from '../shared/base-people'\n import { createMockProject, createMockSupabase } from '../shared/mock-supabase'\n\n enableBase()\n usePeople()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n // The database both windows share.\n const project = createMockProject({\n projects: [\n { id: 'p1', name: 'Website relaunch', owner: 'u1' },\n { id: 'p2', name: 'Customer portal', owner: 'u2' },\n ],\n tasks: [\n { id: 't1', name: 'Wireframes', status: 'Done', assignee: 'u1', due: day(-6), project_id: 'p1' },\n { id: 't2', name: 'Visual design', status: 'In progress', assignee: 'u3', due: day(2), project_id: 'p1' },\n { id: 't3', name: 'CMS migration', status: 'Todo', assignee: 'u2', due: day(9), project_id: 'p1' },\n { id: 't4', name: 'Sign-in with SSO', status: 'In progress', assignee: 'u4', due: day(4), project_id: 'p2' },\n { id: 't5', name: 'Invoices page', status: 'Todo', assignee: 'u2', due: day(12), project_id: 'p2' },\n { id: 't6', name: 'Accessibility audit', status: 'Todo', assignee: null, due: day(15), project_id: null },\n ],\n })\n\n // What the Supabase source reads of each table: its columns and key.\n const SCHEMAS: Record<string, EntitySchema> = {\n tasks: {\n name: 'tasks',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'status', type: 'text' },\n { field: 'assignee', type: 'text' },\n { field: 'due', type: 'date' },\n { field: 'project_id', type: 'text' },\n ],\n },\n projects: {\n name: 'projects',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'owner', type: 'text' },\n ],\n },\n }\n\n const STATUS = [\n { value: 'Todo', color: '#64748b' },\n { value: 'In progress', color: '#2563eb' },\n { value: 'Blocked', color: '#dc2626' },\n { value: 'Done', color: '#16a34a' },\n ]\n\n class Win {\n tables = $state.raw<BaseTable[]>([])\n offline = $state(false)\n requests = $state<string[]>([])\n reconnect = new Set<() => void>()\n who: string\n constructor(who: string) {\n this.who = who\n }\n }\n\n /**\n * One person's window: a client of the shared project and the base's\n * tables on it. The table ids differ per window only because both bases\n * are on one page; in an app they are just 'tasks' and 'projects'.\n */\n function open(who: string, prefix: string): Win {\n const win = new Win(who)\n const client = createMockSupabase(project, {\n offline: () => win.offline,\n onRequest: (line) => {\n win.requests = [line, ...win.requests].slice(0, 3)\n },\n })\n const source = (table: string, links = {}) =>\n baseSource(createSupabaseDataSource({ client: client as never, table, schema: SCHEMAS[table]! }), {\n links,\n // Supabase makes the key: a new row is inserted without the page's id.\n serverIds: true,\n realtime: (onChange) => {\n win.reconnect.add(onChange)\n const live = createSupabaseRealtime({ client: client as never, table, onChange })\n return () => {\n win.reconnect.delete(onChange)\n live.unsubscribe()\n }\n },\n })\n win.tables = [\n {\n id: `${prefix}tasks`,\n name: 'Tasks',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Task', width: 170, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 120, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'project', header: 'Project', width: 150, fieldType: 'link', fieldProps: { table: `${prefix}projects`, multiple: false, inverse: 'tasks' } },\n { field: 'assignee', header: 'Assignee', width: 140, fieldType: 'user' },\n { field: 'due', header: 'Due', width: 120, fieldType: 'date' },\n ],\n views: [\n { id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } },\n { id: 'board', name: 'Board', type: 'kanban', stackBy: 'status' },\n ],\n source: source('tasks', { project: { column: 'project_id' } }),\n props: { rowAdder: { label: 'Add task', defaults: () => ({ status: 'Todo' }) } },\n },\n {\n id: `${prefix}projects`,\n name: 'Projects',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Project', width: 170, fieldType: 'text' },\n { field: 'owner', header: 'Owner', width: 140, fieldType: 'user' },\n { field: 'tasks', header: 'Tasks', width: 260, fieldType: 'link', fieldProps: { table: `${prefix}tasks`, multiple: true, inverse: 'project' } },\n ],\n source: source('projects'),\n },\n ]\n return win\n }\n\n const windows = [open('Ana', 'a-'), open('Ben', 'b-')]\n\n function setOffline(win: Win, offline: boolean) {\n win.offline = offline\n // Back online, a realtime client reconnects and the base reads again.\n if (!offline) for (const on of win.reconnect) on()\n }\n</script>\n\n<section class=\"sbase\">\n {#each windows as win (win.who)}\n <div class=\"sbase-win\" class:is-offline={win.offline}>\n <header class=\"sbase-bar\">\n <span class=\"sbase-dots\" aria-hidden=\"true\"><i></i><i></i><i></i></span>\n <span class=\"sbase-who\">{win.who}'s browser</span>\n <label class=\"sbase-net\">\n <input type=\"checkbox\" checked={win.offline} onchange={(e) => setOffline(win, e.currentTarget.checked)} />\n Offline\n </label>\n </header>\n <div class=\"sbase-body\">\n <!-- Each window is half the page: keep the grid down to 400px, cards on a phone. -->\n <SvBase bind:tables={win.tables} editable sortable showRowNumbers showRowSelection={false} rowHeight={34} containerHeight=\"100%\" columnAdder={false} automations={false} phoneLayout={400} />\n </div>\n <footer class=\"sbase-req\" aria-label={`${win.who}'s last requests`}>\n {#each win.requests as r, i (i)}<code>{r}</code>{/each}\n </footer>\n </div>\n {/each}\n <SvToaster />\n</section>\n\n<style>\n .sbase { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; flex: 1; min-height: 520px; }\n @media (max-width: 900px) { .sbase { grid-template-columns: 1fr; } }\n .sbase-win {\n display: flex; flex-direction: column; min-width: 0; min-height: 480px; overflow: hidden;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px); background: var(--sg-bg, #fff);\n }\n .sbase-win.is-offline { border-color: var(--sg-danger, #dc2626); }\n .sbase-bar {\n display: flex; align-items: center; gap: 10px; height: 34px; padding: 0 10px; font-size: 12px;\n color: var(--sg-muted, #64748b); background: var(--sg-header-bg, var(--sg-bg, #fff)); border-bottom: 1px solid var(--sg-border, #e2e8f0);\n }\n .sbase-dots { display: inline-flex; gap: 5px; }\n .sbase-dots i { width: 9px; height: 9px; border-radius: 50%; background: color-mix(in srgb, var(--sg-fg, #0f172a) 18%, transparent); }\n .sbase-who { flex: 1; font-weight: 600; color: var(--sg-fg, #0f172a); }\n .sbase-net { display: inline-flex; align-items: center; gap: 5px; cursor: pointer; }\n .sbase-net input { accent-color: var(--sg-danger, #dc2626); }\n .sbase-body { flex: 1; min-height: 0; display: flex; flex-direction: column; }\n .sbase-req {\n display: flex; flex-direction: column; gap: 2px; min-height: 52px; padding: 6px 10px; box-sizing: border-box;\n border-top: 1px solid var(--sg-border, #e2e8f0); font-size: 11px; color: var(--sg-muted, #64748b);\n }\n .sbase-req code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }\n</style>\n"
3249
3249
  },
3250
3250
  {
3251
3251
  "id": "518-base-rest-api",
@@ -4143,6 +4143,46 @@ export const examples = [
4143
4143
  "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",
4144
4144
  "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"
4145
4145
  },
4146
+ {
4147
+ "id": "705-base-undo-redo",
4148
+ "path": "examples/src/demos/705-base-undo-redo.svelte",
4149
+ "title": "Base Undo Redo",
4150
+ "category": "Base",
4151
+ "blurb": "705. SvGrid Base: undo and redo Ctrl+Z undoes what was done to a table, in the order it was done: a cell edit, a paste, a record added or deleted, a field added, changed or",
4152
+ "source": "<script lang=\"ts\">\n /**\n * 705. SvGrid Base: undo and redo\n * -------------------------------\n * Ctrl+Z undoes what was done to a table, in the order it was done: a cell\n * edit, a paste, a record added or deleted, a field added, changed or\n * deleted. Ctrl+Shift+Z or Ctrl+Y redoes it. The Undo and Redo buttons at\n * the end of the tab bar say what the next press will do (\"Undo delete 2\n * records\").\n *\n * Undoing a deleted record puts it back where it was and brings its links\n * back: delete a task and its project stops listing it; undo, and the\n * project lists it again. Each table keeps its own history while you look\n * at another one.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const STATUS = [\n { value: 'Todo', color: '#94a3b8' },\n { value: 'In progress', color: '#2d7ff9' },\n { value: 'Blocked', color: '#f82b60' },\n { value: 'Done', color: '#20c933' },\n ]\n const TASKS: Array<[string, string, string, string, number]> = [\n ['Write the launch brief', 'p1', 'Done', 'u1', 3],\n ['Design the pricing page', 'p1', 'In progress', 'u3', 8],\n ['Record the product video', 'p1', 'Todo', 'u5', 6],\n ['Migrate invoices to the new schema', 'p2', 'Blocked', 'u2', 13],\n ['Backfill customer ids', 'p2', 'In progress', 'u4', 5],\n ['Load test the export job', 'p2', 'Todo', 'u2', 4],\n ['Interview three design partners', 'p3', 'Done', 'u6', 6],\n ['Summarize the interviews', 'p3', 'Todo', 'u6', 2],\n ]\n const tasks = TASKS.map(([task, project, status, owner, hours], i) => ({ id: `t${i + 1}`, task, project: [project], status, owner, hours }))\n const projects = [\n { id: 'p1', name: 'Website launch', lead: 'u1' },\n { id: 'p2', name: 'Billing migration', lead: 'u2' },\n { id: 'p3', name: 'Customer research', lead: 'u6' },\n ].map((p) => ({ ...p, tasks: tasks.filter((t) => t.project[0] === p.id).map((t) => t.id) }))\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'undo-tasks',\n name: 'Tasks',\n primaryField: 'task',\n data: tasks,\n columns: [\n { field: 'task', header: 'Task', width: 280, fieldType: 'text' },\n { field: 'project', header: 'Project', width: 190, fieldType: 'link', fieldProps: { table: 'undo-projects', multiple: false, inverse: 'tasks' } },\n { field: 'status', header: 'Status', width: 130, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'owner', header: 'Owner', width: 160, fieldType: 'user' },\n { field: 'hours', header: 'Estimate (h)', width: 120, fieldType: 'number', fieldProps: { format: 'integer' } },\n ],\n views: [{ id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } }],\n props: { rowAdder: { label: 'Add task', defaults: () => ({ status: 'Todo' }) } },\n },\n {\n id: 'undo-projects',\n name: 'Projects',\n primaryField: 'name',\n data: projects,\n columns: [\n { field: 'name', header: 'Project', width: 220, fieldType: 'text' },\n { field: 'lead', header: 'Lead', width: 160, fieldType: 'user' },\n { field: 'tasks', header: 'Tasks', width: 360, fieldType: 'link', fieldProps: { table: 'undo-tasks', multiple: true, inverse: 'project' } },\n { field: 'hours', header: 'Hours', width: 110, fieldType: 'rollup', fieldProps: { linkField: 'tasks', field: 'hours', aggregation: 'SUM' } },\n ],\n views: [{ id: 'all', name: 'All projects', type: 'grid' }],\n },\n ])\n</script>\n\n<section class=\"base-demo\">\n <p class=\"base-demo-tip\">\n Edit a few cells, delete a task (right-click a row, Delete record), delete a field from its header menu, then press\n <kbd>Ctrl</kbd>+<kbd>Z</kbd> until everything is back. The arrows at the top right show what the next undo and redo will do.\n </p>\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n selectionBar={['selectAll', 'editFields', 'deleteRows']}\n columnAdder\n fieldMenu\n />\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .base-demo-tip { margin: 0; font-size: 13px; line-height: 1.5; color: var(--sg-muted, #64748b); }\n .base-demo-tip kbd {\n padding: 1px 5px; font: inherit; font-size: 12px; border-radius: 4px;\n border: 1px solid var(--sg-border, #e2e8f0); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); color: var(--sg-fg, #0f172a);\n }\n</style>\n"
4153
+ },
4154
+ {
4155
+ "id": "706-base-trash",
4156
+ "path": "examples/src/demos/706-base-trash.svelte",
4157
+ "title": "Base Trash",
4158
+ "category": "Base",
4159
+ "blurb": "706. SvGrid Base: trash and restore Deleted records, fields and tables go to the trash, not away. The trash button at the end of the tab bar says how many items it holds; it lists",
4160
+ "source": "<script lang=\"ts\">\n /**\n * 706. SvGrid Base: trash and restore\n * -----------------------------------\n * Deleted records, fields and tables go to the trash, not away. The trash\n * button at the end of the tab bar says how many items it holds; it lists\n * them newest first with who deleted them and when, and Restore puts one\n * back: a record in its table at the place it had, with its links; a field\n * with its values; a table as a tab. Items stay 30 days (`trashDays`).\n *\n * The trash is plain data (`bind:trash`), so an app stores it with the\n * tables. This one starts with three items other people deleted earlier:\n * a deal, a field and a whole table. Delete something yourself, then use\n * Restore in the notice, or open the trash.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable, type BaseTrashItem } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const ago = (days: number, hours = 0) => new Date(Date.now() - days * 86_400_000 - hours * 3_600_000).toISOString()\n const STAGE = [\n { value: 'Lead', color: '#94a3b8' },\n { value: 'Qualified', color: '#2d7ff9' },\n { value: 'Proposal', color: '#8b46ff' },\n { value: 'Won', color: '#20c933' },\n { value: 'Lost', color: '#f82b60' },\n ]\n const DEALS: Array<[string, string, string, number, string]> = [\n ['Northwind renewal', 'a1', 'Proposal', 48000, 'u2'],\n ['Contoso pilot', 'a2', 'Qualified', 12000, 'u1'],\n ['Fabrikam expansion', 'a3', 'Won', 96000, 'u4'],\n ['Litware onboarding', 'a4', 'Lead', 8000, 'u3'],\n ['Northwind support plan', 'a1', 'Lead', 6000, 'u2'],\n ]\n const deals = DEALS.map(([deal, account, stage, amount, owner], i) => ({ id: `d${i + 1}`, deal, account: [account], stage, amount, owner, region: ['EMEA', 'NA', 'NA', 'APAC', 'EMEA'][i] }))\n const accounts = [\n { id: 'a1', name: 'Northwind Traders', industry: 'Retail' },\n { id: 'a2', name: 'Contoso', industry: 'Manufacturing' },\n { id: 'a3', name: 'Fabrikam', industry: 'Finance' },\n { id: 'a4', name: 'Litware', industry: 'Software' },\n ].map((a) => ({ ...a, deals: deals.filter((d) => d.account[0] === a.id).map((d) => d.id) }))\n\n const dealColumns = [\n { field: 'deal', header: 'Deal', width: 240, fieldType: 'text' },\n { field: 'account', header: 'Account', width: 200, fieldType: 'link', fieldProps: { table: 'trash-accounts', multiple: false, inverse: 'deals' } },\n { field: 'stage', header: 'Stage', width: 130, fieldType: 'singleSelect', fieldProps: { options: STAGE } },\n { field: 'amount', header: 'Amount', width: 130, fieldType: 'number', fieldProps: { format: 'currency', symbol: '$', precision: 0 } },\n { field: 'owner', header: 'Owner', width: 160, fieldType: 'user' },\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'trash-deals',\n name: 'Deals',\n primaryField: 'deal',\n data: deals,\n columns: dealColumns,\n views: [{ id: 'pipeline', name: 'Pipeline', type: 'grid', color: { mode: 'field', field: 'stage' } }],\n props: { rowAdder: { label: 'Add deal', defaults: () => ({ stage: 'Lead' }) } },\n },\n {\n id: 'trash-accounts',\n name: 'Accounts',\n primaryField: 'name',\n data: accounts,\n columns: [\n { field: 'name', header: 'Account', width: 220, fieldType: 'text' },\n { field: 'industry', header: 'Industry', width: 150, fieldType: 'text' },\n { field: 'deals', header: 'Deals', width: 320, fieldType: 'link', fieldProps: { table: 'trash-deals', multiple: true, inverse: 'account' } },\n ],\n views: [{ id: 'all', name: 'All accounts', type: 'grid' }],\n },\n ])\n\n // What other people deleted before you opened the base.\n let trash = $state<BaseTrashItem[]>([\n {\n id: 'seed-deal',\n kind: 'record',\n table: 'trash-deals',\n index: 2,\n row: { id: 'd9', deal: 'Adventure Works trial', account: [], stage: 'Lost', amount: 4000, owner: 'u5', region: 'NA' },\n deletedAt: ago(0, 3),\n deletedBy: 'u5',\n },\n {\n id: 'seed-field',\n kind: 'field',\n table: 'trash-deals',\n index: 5,\n column: { field: 'region', header: 'Region', width: 120, fieldType: 'singleSelect', fieldProps: { options: [{ value: 'EMEA', color: '#2d7ff9' }, { value: 'NA', color: '#20c933' }, { value: 'APAC', color: '#ff6f2c' }] } },\n deletedAt: ago(1, 2),\n deletedBy: 'u2',\n },\n {\n id: 'seed-table',\n kind: 'table',\n index: 2,\n table: {\n id: 'trash-leads',\n name: 'Old leads',\n primaryField: 'name',\n columns: [\n { field: 'name', header: 'Lead', width: 220, fieldType: 'text' },\n { field: 'source', header: 'Source', width: 140, fieldType: 'text' },\n { field: 'email', header: 'Email', width: 220, fieldType: 'email' },\n ],\n data: [\n { id: 'l1', name: 'Tailspin Toys', source: 'Webinar', email: 'buyers@tailspin.example' },\n { id: 'l2', name: 'Wide World Importers', source: 'Referral', email: 'ops@wwi.example' },\n { id: 'l3', name: 'Proseware', source: 'Trade show', email: 'hello@proseware.example' },\n ],\n views: [{ id: 'all', name: 'All leads', type: 'grid' }],\n },\n deletedAt: ago(5),\n deletedBy: 'u4',\n },\n ])\n</script>\n\n<section class=\"base-demo\">\n <p class=\"base-demo-tip\">\n The trash at the top right holds {trash.length} {trash.length === 1 ? 'item' : 'items'}. Open it to restore the deal, the Region field or the Old leads table, or delete\n a deal yourself (right-click, Delete record) and press Restore in the notice.\n </p>\n <SvBase\n bind:tables\n bind:trash\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n selectionBar={['selectAll', 'editFields', 'deleteRows']}\n columnAdder\n fieldMenu\n />\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .base-demo-tip { margin: 0; font-size: 13px; line-height: 1.5; color: var(--sg-muted, #64748b); }\n</style>\n"
4161
+ },
4162
+ {
4163
+ "id": "707-base-airtable-import",
4164
+ "path": "examples/src/demos/707-base-airtable-import.svelte",
4165
+ "title": "Base Airtable Import",
4166
+ "category": "Base",
4167
+ "blurb": "707. SvGrid Base: open an Airtable base The JSON in the panel is what Airtable's Web API returns for a small launch-planning base: the schema (GET /v0/meta/bases/{baseId}/tables)",
4168
+ "source": "<script lang=\"ts\">\n /**\n * 707. SvGrid Base: open an Airtable base\n * ---------------------------------------\n * The JSON in the panel is what Airtable's Web API returns for a small\n * launch-planning base: the schema (GET /v0/meta/bases/{baseId}/tables)\n * and the records of its two tables. \"Open as a base\" passes it to\n * `baseFromAirtable` and opens the result in `<SvBase>`.\n *\n * Launches and Tasks link both ways. Selects keep their colors, the\n * collaborators become the page's people (matched by email here, with the\n * `userId` option), Hours is a rollup over the tasks, Launch owner a\n * lookup, and the formulas read `{fldXXX}` references that the import turns\n * into field names. Age reads CREATED_TIME(), which becomes the\n * table's Created field. Status changed reads LAST_MODIFIED_TIME({Status}):\n * the import adds a Last modified time field that watches Status, empty\n * until a status changes, since the API does not say when one last did.\n *\n * Pitch, an AI text field, becomes a Base AI field with the same prompt\n * ({Name} in place of the field id); its generated values come over as\n * they are, and new ones need the AI provider the app sets. The report\n * lists that, the field the import added, a list view, and the settings the\n * schema does not include, such as the field a board stacks by. Edit the\n * JSON (rename a field, change a formula, add a choice) and open it again.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseFromAirtable, enableBase, setFieldUsers, type AirtableImport, type BaseTable } from '@svgrid/enterprise/base'\n import { PEOPLE, usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n const stamp = (offset: number) => `${day(offset)}T09:30:00.000Z`\n\n // Collaborators as the API returns them.\n const ana = { id: 'usrA1b2C3d4E5f6G7', email: 'ana@example.com', name: 'Ana Ruiz' }\n const ben = { id: 'usrB2c3D4e5F6g7H8', email: 'ben@example.com', name: 'Ben Okafor' }\n const cleo = { id: 'usrC3d4E5f6G7h8I9', email: 'cleo@example.com', name: 'Cleo Park' }\n const dev = { id: 'usrD4e5F6g7H8i9J0', email: 'dev@example.com', name: 'Dev Shah' }\n\n const schema = {\n tables: [\n {\n id: 'tblLaunches',\n name: 'Launches',\n primaryFieldId: 'fldLaunchName',\n fields: [\n { id: 'fldLaunchName', name: 'Launch', type: 'singleLineText' },\n {\n id: 'fldLaunchStage', name: 'Stage', type: 'singleSelect',\n options: { choices: [{ id: 'selPlan', name: 'Planning', color: 'blueLight2' }, { id: 'selBuild', name: 'Building', color: 'yellowLight2' }, { id: 'selShip', name: 'Shipped', color: 'greenLight2' }] },\n },\n { id: 'fldLaunchOwner', name: 'Owner', type: 'singleCollaborator', options: {} },\n { id: 'fldLaunchDate', name: 'Launch date', type: 'date', options: { dateFormat: { name: 'friendly', format: 'LL' } } },\n { id: 'fldLaunchTasks', name: 'Tasks', type: 'multipleRecordLinks', options: { linkedTableId: 'tblTasks', inverseLinkFieldId: 'fldTaskLaunch', prefersSingleRecordLink: false, isReversed: false } },\n { id: 'fldLaunchHours', name: 'Hours', type: 'rollup', options: { recordLinkFieldId: 'fldLaunchTasks', fieldIdInLinkedTable: 'fldTaskHours', isValid: true, result: { type: 'number', options: { precision: 1 } } } },\n { id: 'fldLaunchCount', name: 'Task count', type: 'count', options: { recordLinkFieldId: 'fldLaunchTasks', isValid: true } },\n {\n id: 'fldLaunchLeft', name: 'Days left', type: 'formula',\n options: { formula: 'IF({fldLaunchStage} = \"Shipped\", BLANK(), DATETIME_DIFF({fldLaunchDate}, TODAY(), \"days\"))', isValid: true, referencedFieldIds: ['fldLaunchStage', 'fldLaunchDate'], result: { type: 'number', options: { precision: 0 } } },\n },\n {\n id: 'fldLaunchAge', name: 'Age', type: 'formula',\n options: { formula: 'DATETIME_DIFF(TODAY(), CREATED_TIME(), \"days\") & \" days\"', isValid: true, referencedFieldIds: [], result: { type: 'singleLineText' } },\n },\n { id: 'fldLaunchPitch', name: 'Pitch', type: 'aiText', options: { prompt: ['Write a one-line pitch for ', { field: { fieldId: 'fldLaunchName' } }], referencedFieldIds: ['fldLaunchName'] } },\n { id: 'fldLaunchCreated', name: 'Created', type: 'createdTime', options: { result: { type: 'dateTime', options: { dateFormat: { name: 'friendly' }, timeFormat: { name: '24hour' }, timeZone: 'client' } } } },\n ],\n views: [\n { id: 'viwLaunchGrid', name: 'All launches', type: 'grid' },\n { id: 'viwLaunchBoard', name: 'By stage', type: 'kanban' },\n { id: 'viwLaunchCal', name: 'Launch calendar', type: 'calendar' },\n { id: 'viwLaunchList', name: 'Phone list', type: 'list' },\n ],\n },\n {\n id: 'tblTasks',\n name: 'Tasks',\n primaryFieldId: 'fldTaskName',\n fields: [\n { id: 'fldTaskName', name: 'Task', type: 'singleLineText' },\n { id: 'fldTaskLaunch', name: 'Launch', type: 'multipleRecordLinks', options: { linkedTableId: 'tblLaunches', inverseLinkFieldId: 'fldLaunchTasks', prefersSingleRecordLink: true, isReversed: false } },\n {\n id: 'fldTaskStatus', name: 'Status', type: 'singleSelect',\n options: { choices: [{ id: 'selTodo', name: 'To do', color: 'grayLight2' }, { id: 'selDoing', name: 'Doing', color: 'cyanLight2' }, { id: 'selDone', name: 'Done', color: 'greenBright' }] },\n },\n { id: 'fldTaskPeople', name: 'Assignees', type: 'multipleCollaborators', options: {} },\n { id: 'fldTaskHours', name: 'Hours', type: 'number', options: { precision: 1 } },\n { id: 'fldTaskDue', name: 'Due', type: 'date', options: { dateFormat: { name: 'iso', format: 'YYYY-MM-DD' } } },\n { id: 'fldTaskPriority', name: 'Priority', type: 'rating', options: { max: 3, icon: 'flag', color: 'redBright' } },\n { id: 'fldTaskOwner', name: 'Launch owner', type: 'multipleLookupValues', options: { recordLinkFieldId: 'fldTaskLaunch', fieldIdInLinkedTable: 'fldLaunchOwner', isValid: true, result: { type: 'singleCollaborator' } } },\n {\n id: 'fldTaskLate', name: 'Late', type: 'formula',\n options: { formula: 'IF(AND({fldTaskStatus} != \"Done\", IS_BEFORE({fldTaskDue}, TODAY())), \"Late\", \"\")', isValid: true, referencedFieldIds: ['fldTaskStatus', 'fldTaskDue'], result: { type: 'singleLineText' } },\n },\n {\n id: 'fldTaskMoved', name: 'Status changed', type: 'formula',\n options: { formula: 'DATETIME_FORMAT(LAST_MODIFIED_TIME({fldTaskStatus}), \"MMM D\")', isValid: true, referencedFieldIds: ['fldTaskStatus'], result: { type: 'singleLineText' } },\n },\n ],\n views: [\n { id: 'viwTaskGrid', name: 'All tasks', type: 'grid' },\n { id: 'viwTaskBoard', name: 'Board', type: 'kanban' },\n { id: 'viwTaskTimeline', name: 'Due dates', type: 'timeline' },\n { id: 'viwTaskForm', name: 'Request a task', type: 'form' },\n ],\n },\n ],\n }\n\n // [id, launch, stage, owner, launch date, created (days ago)]\n const LAUNCHES: Array<[string, string, string, typeof ana, number, number]> = [\n ['recL1', 'Mobile app 2.0', 'Building', ana, 12, 40],\n ['recL2', 'Usage-based pricing', 'Planning', ben, 34, 18],\n ['recL3', 'EU data region', 'Shipped', cleo, -6, 75],\n ['recL4', 'Partner portal', 'Building', dev, 21, 26],\n ]\n // [id, task, launch, status, assignees, hours, due (days from today), priority]\n const TASKS: Array<[string, string, string, string, Array<typeof ana>, number, number, number]> = [\n ['recT1', 'Offline sync', 'recL1', 'Doing', [ana, dev], 32, 4, 3],\n ['recT2', 'App store screenshots', 'recL1', 'To do', [cleo], 6, 9, 1],\n ['recT3', 'Push notification opt-in', 'recL1', 'Done', [dev], 10, -3, 2],\n ['recT4', 'Metering service', 'recL2', 'Doing', [ben], 40, 14, 3],\n ['recT5', 'Pricing page copy', 'recL2', 'To do', [cleo, ben], 8, 20, 2],\n ['recT6', 'Frankfurt cluster', 'recL3', 'Done', [cleo], 50, -12, 3],\n ['recT7', 'DPA update', 'recL3', 'Done', [ana], 4, -9, 1],\n ['recT8', 'Partner sign-up flow', 'recL4', 'Doing', [dev, ana], 18, -1, 3],\n ['recT9', 'Revenue share report', 'recL4', 'To do', [ben], 12, 15, 2],\n ]\n const records = {\n tblLaunches: {\n records: LAUNCHES.map(([id, name, stage, owner, date, created]) => ({\n id,\n createdTime: stamp(-created),\n fields: {\n Launch: name,\n Stage: stage,\n Owner: owner,\n 'Launch date': day(date),\n Tasks: TASKS.filter((t) => t[2] === id).map((t) => t[0]),\n Hours: TASKS.filter((t) => t[2] === id).reduce((s, t) => s + t[5], 0),\n 'Task count': TASKS.filter((t) => t[2] === id).length,\n Pitch: { state: 'generated', value: `${name}, ready when you are.`, isStale: false },\n Created: stamp(-created),\n },\n })),\n },\n tblTasks: {\n records: TASKS.map(([id, task, launch, status, people, hours, due, priority]) => ({\n id,\n createdTime: stamp(-30),\n fields: { Task: task, Launch: [launch], Status: status, Assignees: people, Hours: hours, Due: day(due), Priority: priority },\n })),\n },\n }\n\n let json = $state(JSON.stringify({ schema, records }, null, 2))\n let parseError = $state('')\n let result = $state.raw<AirtableImport | null>(null)\n let tables = $state.raw<BaseTable[]>([])\n // A new import opens a new base.\n let opened = $state(0)\n let showJson = $state(true)\n\n const byEmail = new Map(PEOPLE.map((p) => [p.email, p.id]))\n\n function open() {\n let input: { schema?: unknown; records?: unknown }\n try {\n input = JSON.parse(json)\n } catch (e) {\n parseError = e instanceof Error ? e.message : 'Not valid JSON'\n return\n }\n parseError = ''\n const r = baseFromAirtable(input.schema as Parameters<typeof baseFromAirtable>[0], (input.records ?? {}) as Parameters<typeof baseFromAirtable>[1], {\n // The page's people, by email; anyone else keeps the Airtable id.\n userId: (c) => (c.email ? byEmail.get(c.email) : undefined) ?? c.id,\n })\n // The people user fields choose from are page-wide: add the new ones, keep the rest.\n const extra = r.users.filter((u) => !PEOPLE.some((p) => p.id === u.id))\n if (extra.length) setFieldUsers([...PEOPLE, ...extra])\n result = r\n tables = r.tables\n opened += 1\n }\n\n const recordCount = $derived(result ? result.tables.reduce((s, t) => s + t.data.length, 0) : 0)\n const KIND_LABEL: Record<string, string> = { field: 'Field type', formula: 'Formula', view: 'View', link: 'Link', setting: 'Setting' }\n\n open()\n</script>\n\n<section class=\"base-demo\">\n <div class=\"at-bar\">\n <button type=\"button\" class=\"at-open\" onclick={open}>Open as a base</button>\n <button type=\"button\" class=\"at-toggle\" aria-expanded={showJson} onclick={() => (showJson = !showJson)}>\n {showJson ? 'Hide' : 'Show'} the Airtable JSON\n </button>\n {#if result}\n <span class=\"at-sum\">\n {result.tables.length} tables, {recordCount} records, {result.users.length} people, {result.report.length} notes\n </span>\n {/if}\n </div>\n\n {#if showJson}\n <div class=\"at-panels\">\n <label class=\"at-json\">\n <span class=\"at-head\">Schema and records, as the Web API returns them</span>\n <textarea bind:value={json} spellcheck=\"false\" aria-invalid={parseError ? 'true' : undefined}></textarea>\n {#if parseError}<span class=\"at-error\" role=\"alert\">{parseError}</span>{/if}\n </label>\n <div class=\"at-report\">\n <span class=\"at-head\">What did not carry over as it was</span>\n {#if result && result.report.length}\n <ul>\n {#each result.report as item, i (i)}\n <li>\n <span class=\"at-kind at-kind-{item.kind}\">{KIND_LABEL[item.kind]}</span>\n <b>{item.table} / {item.name}</b>\n <span class=\"at-msg\">{item.message}</span>\n </li>\n {/each}\n </ul>\n {:else}\n <p class=\"at-none\">Everything mapped.</p>\n {/if}\n </div>\n </div>\n {/if}\n\n <div class=\"at-base\">\n {#key opened}\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n {/key}\n </div>\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .at-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; font-size: 13px; color: var(--sg-fg, #0f172a); }\n .at-open {\n height: 32px; padding: 0 14px; border: 0; border-radius: var(--sg-radius, 6px);\n background: var(--sg-accent, #2563eb); color: var(--sg-on-accent, #fff); font: inherit; font-weight: 600; cursor: pointer;\n }\n .at-toggle {\n height: 32px; padding: 0 12px; border: 1px solid var(--sg-border, #cbd5e1); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: inherit; cursor: pointer;\n }\n .at-sum { color: var(--sg-muted, #64748b); }\n .at-panels { flex: 0 0 auto; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; height: 260px; }\n .at-json, .at-report {\n display: flex; flex-direction: column; gap: 6px; min-height: 0; padding: 10px 12px;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px);\n background: var(--sg-header-bg, var(--sg-bg, #fff)); color: var(--sg-fg, #0f172a);\n }\n .at-head { font-size: 12px; font-weight: 600; color: var(--sg-muted, #64748b); }\n .at-json textarea {\n flex: 1; min-height: 0; resize: none; padding: 8px; border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n }\n .at-json textarea[aria-invalid='true'] { border-color: var(--sg-danger, #dc2626); }\n .at-error { font-size: 12px; color: var(--sg-danger, #dc2626); }\n .at-report ul { list-style: none; margin: 0; padding: 0; overflow: auto; font-size: 12.5px; }\n .at-report li { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; padding: 6px 0; border-top: 1px solid var(--sg-border, #e2e8f0); }\n .at-report li:first-child { border-top: 0; }\n .at-msg { flex-basis: 100%; color: var(--sg-muted, #64748b); }\n .at-kind {\n padding: 1px 6px; border-radius: 999px; font-size: 11px; font-weight: 600;\n border: 1px solid var(--sg-border, #e2e8f0); color: var(--sg-muted, #64748b);\n }\n .at-kind-formula, .at-kind-field { border-color: var(--sg-danger, #dc2626); color: var(--sg-danger, #dc2626); }\n .at-none { margin: 0; color: var(--sg-muted, #64748b); }\n .at-base { flex: 1 1 auto; min-height: 380px; display: flex; flex-direction: column; }\n @media (max-width: 720px) {\n .at-panels { grid-template-columns: minmax(0, 1fr); height: auto; }\n .at-json textarea { height: 200px; flex: none; }\n .at-report ul { max-height: 220px; }\n }\n</style>\n"
4169
+ },
4170
+ {
4171
+ "id": "708-base-formula-compat",
4172
+ "path": "examples/src/demos/708-base-formula-compat.svelte",
4173
+ "title": "Base Formula Compat",
4174
+ "category": "Base",
4175
+ "blurb": "708. SvGrid Base: Airtable formulas A formula playground and the list of every function in Airtable's formula reference, with what a Base formula does with each.",
4176
+ "source": "<script lang=\"ts\">\n /**\n * 708. SvGrid Base: Airtable formulas\n * -----------------------------------\n * A formula playground and the list of every function in Airtable's\n * formula reference, with what a Base formula does with each.\n *\n * Orders has a Result field whose formula is the one in the box above the\n * base. Pick an Airtable-style example or type your own: the column works\n * it out for every order as you type, and a formula that does not compile\n * says why under the box (its cells show #ERROR). The examples use the\n * functions Base added for Airtable: WORKDAY_DIFF, DATETIME_FORMAT with\n * SET_TIMEZONE, REGEX_REPLACE, ARRAYSLICE, WEEKNUM, RECORD_ID. The last\n * example calls CREATED_TIME(), which Base does not have.\n *\n * The Airtable functions tab is `airtableFormulaSupport()`: each function,\n * its group, and Supported, Supported with a difference or Not supported,\n * read from FORMULA_FUNCTIONS. Search it from the view bar, or switch to\n * the board grouped by status.\n */\n import { FormulaError, SvBase, airtableFormulaSupport, enableBase, formulaError, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const day = (offset: number, hour?: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n if (hour == null) return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n d.setHours(hour, 15, 0, 0)\n return d.toISOString()\n }\n\n const EXAMPLES: Array<{ label: string; formula: string }> = [\n { label: 'Working days to ship', formula: 'WORKDAY_DIFF({Placed}, {Shipped})' },\n { label: 'Day it was placed', formula: 'DATETIME_FORMAT({Placed}, \"dddd, MMMM Do [at] h:mm A\")' },\n { label: 'Placed, Tokyo time', formula: 'DATETIME_FORMAT(SET_TIMEZONE({Placed}, \"Asia/Tokyo\"), \"MMM D, HH:mm Z\")' },\n { label: 'Order size', formula: 'IF({Amount} >= 1000, \"Large\", IF({Amount} >= 250, \"Medium\", \"Small\"))' },\n { label: 'Email domain', formula: 'REGEX_REPLACE({Email}, \"^.*@\", \"\")' },\n { label: 'Unit price, rounded up', formula: 'ROUNDUP({Amount} / {Qty}, 1)' },\n { label: 'Next step', formula: 'SWITCH({Status}, \"Waiting\", \"Pack it\", \"Packed\", \"Ship it\", \"Done\")' },\n { label: 'First two tags', formula: 'ARRAYJOIN(ARRAYSLICE({Tags}, 1, 2), \" + \")' },\n { label: 'Week placed', formula: '\"W\" & WEEKNUM({Placed}, \"Monday\") & \" \" & YEAR({Placed})' },\n { label: 'Ship by (3 working days)', formula: 'WORKDAY({Placed}, 3)' },\n { label: 'Order link', formula: '\"https://example.com/orders/\" & ENCODE_URL_COMPONENT({Order}) & \"?r=\" & RECORD_ID()' },\n { label: 'Age (not in Base)', formula: 'DATETIME_DIFF(TODAY(), CREATED_TIME(), \"days\")' },\n ]\n\n const STATUS = [\n { value: 'Waiting', color: '#ffeab6' },\n { value: 'Packed', color: '#d0f0fd' },\n { value: 'Shipped', color: '#d1f7c4' },\n ]\n const TAGS = [\n { value: 'Rush', color: '#ffdce5' },\n { value: 'Gift', color: '#ede2fe' },\n { value: 'Wholesale', color: '#cfdfff' },\n { value: 'Repeat', color: '#c2f5e9' },\n ]\n // [order, customer, email, placed (days ago, hour), shipped (days after placed), amount, qty, status, tags]\n const ORDERS: Array<[string, string, string, [number, number], number | null, number, number, string, string[]]> = [\n ['SO-1041', 'Northwind Traders', 'buyer@northwind.example', [-12, 9], 3, 1840, 24, 'Shipped', ['Wholesale', 'Repeat']],\n ['SO-1042', 'Fabrikam', 'orders@fabrikam.example', [-10, 14], 6, 312.5, 5, 'Shipped', ['Rush']],\n ['SO-1043', 'Tailspin Toys', 'ops@tailspin.example', [-8, 11], 2, 96, 12, 'Shipped', ['Gift', 'Rush', 'Repeat']],\n ['SO-1044', 'Contoso', 'purchasing@contoso.example', [-5, 16], null, 4210, 60, 'Packed', ['Wholesale']],\n ['SO-1045', 'Adventure Works', 'hello@adventure.example', [-3, 10], null, 640, 8, 'Packed', []],\n ['SO-1046', 'Litware', 'it@litware.example', [-2, 8], null, 189.9, 3, 'Waiting', ['Gift']],\n ['SO-1047', 'Proseware', 'team@proseware.example', [-1, 19], null, 1275, 15, 'Waiting', ['Repeat', 'Rush']],\n ]\n const orders = ORDERS.map(([order, customer, email, [placed, hour], ship, amount, qty, status, tags], i) => ({\n id: `rec${String(i + 1).padStart(3, '0')}`,\n order,\n customer,\n email,\n placed: day(placed, hour),\n shipped: ship == null ? null : day(placed + ship),\n amount,\n qty,\n status,\n tags,\n }))\n\n const ORDER_COLUMNS: Array<Record<string, any>> = [\n { field: 'order', header: 'Order', width: 110, fieldType: 'text' },\n { field: 'customer', header: 'Customer', width: 170, fieldType: 'text' },\n { field: 'result', header: 'Result', width: 260, fieldType: 'formula', fieldProps: { formula: EXAMPLES[0]!.formula, result: 'auto' } },\n { field: 'placed', header: 'Placed', width: 180, fieldType: 'date', fieldProps: { time: true, dateFormat: 'friendly' } },\n { field: 'shipped', header: 'Shipped', width: 150, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'amount', header: 'Amount', width: 120, fieldType: 'number', fieldProps: { format: 'currency', precision: 2 } },\n { field: 'qty', header: 'Qty', width: 80, fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'status', header: 'Status', width: 120, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'tags', header: 'Tags', width: 200, fieldType: 'multiSelect', fieldProps: { options: TAGS } },\n { field: 'email', header: 'Email', width: 220, fieldType: 'email' },\n ]\n\n // The functions tab: what airtableFormulaSupport() says, never typed here.\n const LABEL = { supported: 'Supported', different: 'Supported with a difference', unsupported: 'Not supported' } as const\n const support = airtableFormulaSupport()\n const functions = support.map((f) => ({ id: f.name, name: f.name, group: f.group, status: LABEL[f.status], note: f.note }))\n const counts = {\n supported: support.filter((f) => f.status === 'supported').length,\n different: support.filter((f) => f.status === 'different').length,\n unsupported: support.filter((f) => f.status === 'unsupported').length,\n }\n\n let formula = $state(EXAMPLES[0]!.formula)\n let picked = $state(EXAMPLES[0]!.formula)\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'fc-orders',\n name: 'Orders',\n primaryField: 'order',\n data: orders,\n columns: ORDER_COLUMNS,\n views: [{ id: 'all', name: 'All orders', type: 'grid' }],\n props: { rowAdder: { label: 'Add order', defaults: () => ({ placed: day(0, 9), status: 'Waiting', qty: 1, tags: [] }) } },\n },\n {\n id: 'fc-functions',\n name: 'Airtable functions',\n primaryField: 'name',\n data: functions,\n columns: [\n { field: 'name', header: 'Function', width: 210, fieldType: 'text' },\n {\n field: 'status', header: 'SvGrid Base', width: 210, fieldType: 'singleSelect',\n fieldProps: { options: [{ value: LABEL.supported, color: '#d1f7c4' }, { value: LABEL.different, color: '#ffeab6' }, { value: LABEL.unsupported, color: '#ffdce5' }] },\n },\n {\n field: 'group', header: 'Group', width: 120, fieldType: 'singleSelect',\n fieldProps: { options: ['Text', 'Logical', 'Numeric', 'Date', 'Array', 'Record'].map((value) => ({ value })) },\n },\n { field: 'note', header: 'Notes', width: 520, fieldType: 'longText' },\n ],\n views: [\n { id: 'by-group', name: 'By group', type: 'grid', state: { grouping: ['group'] } },\n { id: 'by-status', name: 'By status', type: 'kanban', stackBy: 'status' },\n ],\n props: { editable: false },\n },\n ])\n\n /** The Result field's formula is the box's: the column works it out again. */\n function setFormula(next: string) {\n formula = next\n tables = tables.map((t) =>\n t.id !== 'fc-orders' ? t : { ...t, columns: t.columns.map((c) => (c.field === 'result' ? { ...c, fieldProps: { ...c.fieldProps, formula: next } } : c)) },\n )\n }\n function pick(next: string) {\n picked = next\n setFormula(next)\n }\n\n // The message the field editor would show: {Name} is another field of Orders, by header or key.\n const keys = new Map(ORDER_COLUMNS.filter((c) => c.field !== 'result').flatMap((c) => [[c.field, c.field], [c.header.toLowerCase(), c.field]]))\n const resolve = (name: string) => {\n const n = name.trim().toLowerCase()\n if (n === 'result') throw new FormulaError('A formula cannot read its own field {Result}')\n return keys.get(n) ?? null\n }\n const error = $derived(formula.trim() ? formulaError(formula, resolve) : null)\n</script>\n\n<section class=\"base-demo\">\n <div class=\"fc-bar\">\n <label class=\"fc-pick\">\n <span>Example</span>\n <select value={picked} onchange={(e) => pick(e.currentTarget.value)}>\n {#each EXAMPLES as ex (ex.formula)}\n <option value={ex.formula}>{ex.label}</option>\n {/each}\n </select>\n </label>\n <label class=\"fc-formula\">\n <span>Result =</span>\n <input\n value={formula}\n oninput={(e) => setFormula(e.currentTarget.value)}\n spellcheck=\"false\"\n aria-invalid={error ? 'true' : undefined}\n aria-describedby=\"fc-status\"\n />\n </label>\n <p id=\"fc-status\" class=\"fc-status\" class:fc-bad={!!error} role=\"status\">\n {#if error}\n {error}\n {:else}\n Of {support.length} Airtable functions: {counts.supported} supported, {counts.different} with a difference, {counts.unsupported} not supported.\n {/if}\n </p>\n </div>\n\n <div class=\"fc-base\">\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n fieldMenu\n />\n </div>\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .fc-bar {\n flex: 0 0 auto; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 10px 12px;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px);\n background: var(--sg-header-bg, var(--sg-bg, #fff)); color: var(--sg-fg, #0f172a); font-size: 13px;\n }\n .fc-pick, .fc-formula { display: flex; align-items: center; gap: 8px; }\n .fc-pick span, .fc-formula span { font-weight: 600; color: var(--sg-muted, #64748b); white-space: nowrap; }\n .fc-formula { flex: 1 1 360px; min-width: 0; }\n .fc-pick select, .fc-formula input {\n height: 32px; padding: 0 8px; border: 1px solid var(--sg-input-border, var(--sg-border, #cbd5e1)); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: inherit;\n }\n .fc-formula input { flex: 1; min-width: 0; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; }\n .fc-formula input[aria-invalid='true'] { border-color: var(--sg-danger, #dc2626); }\n .fc-status { flex-basis: 100%; margin: 0; color: var(--sg-muted, #64748b); }\n .fc-status.fc-bad { color: var(--sg-danger, #dc2626); }\n .fc-base { flex: 1 1 auto; min-height: 380px; display: flex; flex-direction: column; }\n</style>\n"
4177
+ },
4178
+ {
4179
+ "id": "709-base-import-csv-excel",
4180
+ "path": "examples/src/demos/709-base-import-csv-excel.svelte",
4181
+ "title": "Base Import Csv Excel",
4182
+ "category": "Base",
4183
+ "blurb": "709. SvGrid Base: import CSV or Excel A CSV, TSV, Excel (.xlsx) or JSON file goes into a base two ways: - as a new table (the list of tables, \"Import a file as a table\"): each",
4184
+ "source": "<script lang=\"ts\">\n /**\n * 709. SvGrid Base: import CSV or Excel\n * -------------------------------------\n * A CSV, TSV, Excel (.xlsx) or JSON file goes into a base two ways:\n *\n * - as a new table (the list of tables, \"Import a file as a table\"): each\n * column becomes a field typed from its values. \"$1,200\" makes a\n * currency, \"yes / no\" a checkbox, dates a date, an email column an\n * email, a column that repeats a few values a single select with a\n * color per value. The dialog shows each guess and lets you change it.\n * - as records of the shown table (the table's menu, \"Import records from\n * a file\"): each column of the file goes to the field it names, matched\n * by name; new select values become options.\n *\n * The file is read in the page and the import is one undo step. The two\n * buttons below hand the base a sample file through `openImport(mode, file)`,\n * the same dialog the menus open.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const STAGE = [\n { value: 'New', color: '#94a3b8' },\n { value: 'Contacted', color: '#2d7ff9' },\n { value: 'Customer', color: '#20c933' },\n ]\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'import-contacts',\n name: 'Contacts',\n primaryField: 'name',\n data: [\n { id: 'c1', name: 'Mara Lindqvist', company: 'Northwind Traders', email: 'mara@northwind.example', stage: 'Customer', subscribed: true },\n { id: 'c2', name: 'Tomas Reyes', company: 'Contoso', email: 'tomas@contoso.example', stage: 'Contacted', subscribed: false },\n ],\n columns: [\n { field: 'name', header: 'Name', width: 200, fieldType: 'text' },\n { field: 'company', header: 'Company', width: 190, fieldType: 'text' },\n { field: 'email', header: 'Email', width: 230, fieldType: 'email' },\n { field: 'stage', header: 'Stage', width: 130, fieldType: 'singleSelect', fieldProps: { options: STAGE } },\n { field: 'subscribed', header: 'Subscribed', width: 110, fieldType: 'checkbox' },\n ],\n views: [{ id: 'all', name: 'All contacts', type: 'grid', color: { mode: 'field', field: 'stage' } }],\n },\n ])\n\n // A sign-up export whose columns are named like the table's fields, in another order, with one extra column.\n const CONTACTS_CSV = `Email,Name,Company,Stage,Subscribed,Signed up from\npriya@fabrikam.example,Priya Nair,Fabrikam,New,yes,Webinar\nli.wei@litware.example,Li Wei,Litware,Contacted,no,Pricing page\nsam@tailspin.example,Sam Okoro,Tailspin Toys,Trial,yes,Referral\nines@proseware.example,Ines Duarte,Proseware,New,yes,Webinar\n`\n // An inventory sheet for a new table: a currency, a number, a checkbox, a date, a select.\n const PRODUCTS_TSV = [\n ['Product', 'SKU', 'Category', 'Price', 'In stock', 'Reorder', 'Last counted', 'Supplier email'],\n ['Standing desk', 'DSK-120', 'Furniture', '$649.00', '14', 'no', '2026-10-28', 'orders@deskco.example'],\n ['Monitor arm', 'ARM-02', 'Accessories', '$89.00', '3', 'yes', '2026-10-28', 'sales@mounts.example'],\n ['Task chair', 'CHR-77', 'Furniture', '$329.00', '9', 'no', '2026-10-27', 'orders@deskco.example'],\n ['Desk lamp', 'LMP-10', 'Lighting', '$45.50', '0', 'yes', '2026-10-27', 'hello@lumen.example'],\n ['Cable tray', 'CBL-04', 'Accessories', '$24.00', '41', 'no', '2026-10-26', 'sales@mounts.example'],\n ['Footrest', 'FTR-01', 'Furniture', '$59.00', '6', 'no', '2026-10-26', 'orders@deskco.example'],\n ['Webcam light', 'LMP-22', 'Lighting', '$39.00', '2', 'yes', '2026-10-25', 'hello@lumen.example'],\n ].map((r) => r.join('\\t')).join('\\n')\n\n let base = $state<ReturnType<typeof SvBase> | null>(null)\n const file = (text: string, name: string, type: string) => new File([text], name, { type })\n\n function importContacts() {\n base?.openImport('append', file(CONTACTS_CSV, 'signups.csv', 'text/csv'))\n }\n function importProducts() {\n base?.openImport('new', file(PRODUCTS_TSV, 'products.tsv', 'text/tab-separated-values'))\n }\n</script>\n\n<section class=\"base-demo\">\n <div class=\"base-demo-bar\">\n <button type=\"button\" class=\"base-demo-btn\" onclick={importContacts}>Import signups.csv into Contacts</button>\n <button type=\"button\" class=\"base-demo-btn\" onclick={importProducts}>Import products.tsv as a new table</button>\n <span class=\"base-demo-tip\">Or use your own file: the table menu (▾ next to Contacts) or the list of tables.</span>\n </div>\n <SvBase\n bind:this={base}\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .base-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }\n .base-demo-btn {\n height: 32px; padding: 0 12px; font: inherit; font-size: 13px; cursor: pointer; border-radius: var(--sg-radius, 6px);\n color: var(--sg-fg, #0f172a); background: var(--sg-bg, #fff); border: 1px solid var(--sg-border, #e2e8f0);\n }\n .base-demo-btn:hover { border-color: var(--sg-accent, #2563eb); }\n .base-demo-tip { font-size: 13px; color: var(--sg-muted, #64748b); }\n</style>\n"
4185
+ },
4146
4186
  {
4147
4187
  "id": "71-submit-validation",
4148
4188
  "path": "examples/src/demos/71-submit-validation.svelte",
@@ -4151,6 +4191,86 @@ export const examples = [
4151
4191
  "blurb": "71. Submit-time validation Different from per-keystroke validation (demo 24). Here the user edits freely and clicks \"Submit\" - the grid then runs a row-level",
4152
4192
  "source": "<script lang=\"ts\">\n /**\n * 71. Submit-time validation\n * --------------------------\n * Different from per-keystroke validation (demo 24). Here the user\n * edits freely and clicks \"Submit\" - the grid then runs a row-level\n * validator. Invalid rows are highlighted and listed in an errors\n * panel; the form blocks submission until every row passes.\n *\n * Pattern: keep a `pending` map of unresolved edits; on Submit, run\n * the validator against the in-memory rows, derive `errors`, and only\n * push the payload to \"the server\" when `errors.length === 0`.\n */\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n type GridColumns,\n } from '@svgrid/grid'\n\n type Lead = {\n id: string\n company: string\n email: string\n phone: string\n revenue: number\n status: 'new' | 'contacted' | 'qualified'\n }\n\n let rows = $state<Lead[]>([\n { id: 'L-001', company: 'Acme Corp', email: 'sales@acme.io', phone: '+1 555 0101', revenue: 250_000, status: 'new' },\n { id: 'L-002', company: '', email: 'tim@globex', phone: '5551111', revenue: 0, status: 'new' },\n { id: 'L-003', company: 'Initech', email: 'peter@initech.com', phone: '+1 555 4488', revenue: -100, status: 'contacted' },\n { id: 'L-004', company: 'Umbrella', email: 'jill', phone: '+44 20 7000', revenue: 1_400_000,status: 'qualified' },\n { id: 'L-005', company: 'Stark Inc.', email: 'tony@stark.com', phone: '+1 555 7777', revenue: 9_900_000,status: 'qualified' },\n ])\n\n type Issue = { rowId: string; rowIndex: number; field: keyof Lead; message: string }\n let errors = $state<Issue[]>([])\n let submitted = $state<string | null>(null)\n\n /** Row-level rules. Return one Issue per failed field. */\n function validate(row: Lead, ix: number): Issue[] {\n const out: Issue[] = []\n if (!row.company.trim())\n out.push({ rowId: row.id, rowIndex: ix, field: 'company', message: 'Company is required' })\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(row.email))\n out.push({ rowId: row.id, rowIndex: ix, field: 'email', message: 'Email is malformed' })\n if (row.phone.replace(/\\D/g, '').length < 7)\n out.push({ rowId: row.id, rowIndex: ix, field: 'phone', message: 'Phone needs at least 7 digits' })\n if (!Number.isFinite(row.revenue) || row.revenue < 0)\n out.push({ rowId: row.id, rowIndex: ix, field: 'revenue', message: 'Revenue cannot be negative' })\n return out\n }\n\n function submit() {\n submitted = null\n const all: Issue[] = []\n rows.forEach((r, i) => all.push(...validate(r, i)))\n errors = all\n if (all.length === 0) {\n submitted = `Submitted ${rows.length} leads successfully at ${new Date().toLocaleTimeString()}`\n }\n }\n function reset() { errors = []; submitted = null }\n\n const errorsByRowId = $derived(() => {\n const m = new Map<string, Set<string>>()\n for (const e of errors) {\n if (!m.has(e.rowId)) m.set(e.rowId, new Set())\n m.get(e.rowId)!.add(e.field as string)\n }\n return m\n })\n\n const features = tableFeatures({ rowSortingFeature })\n\n const columns: GridColumns<Lead> = [\n { field: 'id', header: 'Lead', editorType: 'text', width: 90 },\n {\n field: 'company', header: 'Company', editorType: 'text', width: 180,\n cellClass: (ctx) =>\n errorsByRowId().get(ctx.row.original.id)?.has('company') ? 'cell-invalid' : '',\n },\n {\n field: 'email', header: 'Email', editorType: 'text', width: 200,\n cellClass: (ctx) =>\n errorsByRowId().get(ctx.row.original.id)?.has('email') ? 'cell-invalid' : '',\n },\n {\n field: 'phone', header: 'Phone', editorType: 'text', width: 150,\n cellClass: (ctx) =>\n errorsByRowId().get(ctx.row.original.id)?.has('phone') ? 'cell-invalid' : '',\n },\n {\n field: 'revenue', header: 'Revenue', editorType: 'number', width: 160,\n format: { type: 'currency', currency: 'USD', options: { maximumFractionDigits: 0 } },\n cellClass: (ctx) =>\n errorsByRowId().get(ctx.row.original.id)?.has('revenue') ? 'cell-invalid' : '',\n },\n { field: 'status', header: 'Status', editorType: 'list', width: 140,\n editorOptions: ['new', 'contacted', 'qualified'] },\n ]\n</script>\n\n<section class=\"flex flex-col flex-1 min-h-0 gap-3\">\n <div class=\"flex flex-wrap items-center gap-2 text-sm shrink-0\">\n <button type=\"button\" onclick={submit}\n class=\"sv-btn-primary rounded-md px-3 py-1.5 font-medium\"\n >Submit all leads</button>\n <button type=\"button\" onclick={reset}\n class=\"sv-btn rounded-md px-3 py-1.5\"\n >Clear errors</button>\n {#if submitted}\n <span class=\"text-emerald-600 dark:text-emerald-400 text-xs\">✓ {submitted}</span>\n {/if}\n </div>\n\n {#if errors.length > 0}\n <div role=\"alert\" aria-live=\"polite\"\n class=\"rounded-md border border-rose-300 bg-rose-50 dark:border-rose-800 dark:bg-rose-950/30 px-3 py-2 text-sm shrink-0\">\n <div class=\"font-medium text-rose-700 dark:text-rose-300 mb-1\">\n Fix {errors.length} issue{errors.length === 1 ? '' : 's'} before submitting:\n </div>\n <ul class=\"list-disc list-inside text-rose-700/90 dark:text-rose-300/90 max-h-28 overflow-auto\">\n {#each errors as e (`${e.rowId}-${e.field}`)}\n <li>\n <code>{e.rowId}</code>\n <span class=\"sv-sep\">·</span>\n <strong>{e.field}</strong>: {e.message}\n </li>\n {/each}\n </ul>\n </div>\n {/if}\n\n <div class=\"flex-1 min-h-0\">\n <SvGrid responsive={true}\n columnResize\n data={rows}\n columns={columns}\n features={features}\n filterMode=\"none\"\n selectionMode=\"cell\"\n showRowNumbers={false}\n enableInlineEditing={true}\n enableCellSelection={true}\n rowHeight={36}\n containerHeight=\"100%\"\n fitColumns={true}\n />\n </div>\n</section>\n\n<style>\n /* Toolbar chrome tracks the grid theme; the rose invalid-cell tint below\n is a validation signal, so it stays fixed. */\n .sv-btn-primary {\n border: 1px solid var(--sg-accent, #4f46e5);\n background: var(--sg-accent, #4f46e5);\n color: var(--sg-on-accent, #fff);\n }\n .sv-btn-primary:hover { filter: brightness(1.08); }\n .sv-btn {\n border: 1px solid var(--sg-border, #cbd5e1);\n background: var(--sg-bg, #fff);\n color: var(--sg-fg, #0f172a);\n }\n .sv-btn:hover { background: var(--sg-row-hover-bg, #f8fafc); }\n .sv-sep { color: var(--sg-muted, #64748b); }\n\n :global(td.cell-invalid) {\n background: rgba(244, 63, 94, 0.12);\n box-shadow: inset 0 0 0 1px #f43f5e;\n }\n</style>\n"
4153
4193
  },
4194
+ {
4195
+ "id": "710-base-personal-locked-views",
4196
+ "path": "examples/src/demos/710-base-personal-locked-views.svelte",
4197
+ "title": "Base Personal Locked Views",
4198
+ "category": "Base",
4199
+ "blurb": "710. SvGrid Base: personal views, locked views, protected fields What a team needs once several people share a base: - A personal view (`personal: userId`) is listed only for the person it",
4200
+ "source": "<script lang=\"ts\">\n /**\n * 710. SvGrid Base: personal views, locked views, protected fields\n * ----------------------------------------------------------------\n * What a team needs once several people share a base:\n *\n * - A personal view (`personal: userId`) is listed only for the person it\n * belongs to, under \"My views\". \"Create\" in the views menu has a\n * \"Personal view: only I see it\" box. Switch \"Signed in as\" below: Ana\n * and Ben each see their own.\n * - A locked view (`locked: true`) keeps its filter, sorts, groups, hidden\n * fields and colors as saved. Its settings buttons are off and the bar\n * says who locked it; records can still be edited. A sort from a column\n * header lasts until the view is shown again, and the bar offers Reset.\n * The lock button in the views menu locks or unlocks a view; `lockViews`\n * says who may (here Ana and Ben, not Cleo).\n * - A protected field (`fieldProps.editors`) takes edits from the people\n * listed only. Priority here is Ana's and Ben's to set: signed in as\n * Cleo, its header shows a lock and its cells and the record view are\n * read-only. Edit field > Who can edit its values sets the list.\n *\n * `onTablesChange` hands the views back with every change, so the app\n * stores them with the table, the personal ones with their owner.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, setCurrentUser, type BaseTable } from '@svgrid/enterprise/base'\n import { PEOPLE, usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const STATUS = [\n { value: 'Todo', color: '#94a3b8' },\n { value: 'In progress', color: '#2d7ff9' },\n { value: 'In review', color: '#8b46ff' },\n { value: 'Done', color: '#20c933' },\n ]\n const PRIORITY = [\n { value: 'High', color: '#f82b60' },\n { value: 'Medium', color: '#fcb400' },\n { value: 'Low', color: '#94a3b8' },\n ]\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n const TASKS: Array<[string, string, string, string, number]> = [\n ['Quarterly board deck', 'u2', 'In progress', 'High', 3],\n ['Hiring plan for Q1', 'u2', 'Todo', 'High', 9],\n ['Refresh the onboarding emails', 'u1', 'In review', 'Medium', 1],\n ['Fix the invoice PDF footer', 'u1', 'In progress', 'High', 2],\n ['Update the pricing FAQ', 'u1', 'Todo', 'Low', 12],\n ['Customer advisory board invites', 'u3', 'Todo', 'Medium', 6],\n ['Close the September books', 'u4', 'Done', 'High', -4],\n ['Vendor security review', 'u3', 'In progress', 'Medium', 5],\n ['Plan the team offsite', 'u2', 'Todo', 'Low', 20],\n ['Renew the SOC 2 report', 'u4', 'In review', 'High', 4],\n ]\n const ana = PEOPLE[0]!.id\n const ben = PEOPLE[1]!.id\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'views-tasks',\n name: 'Team tasks',\n primaryField: 'task',\n data: TASKS.map(([task, owner, status, priority, due], i) => ({ id: `t${i + 1}`, task, owner, status, priority, due: day(due) })),\n columns: [\n { field: 'task', header: 'Task', width: 280, fieldType: 'text' },\n { field: 'owner', header: 'Owner', width: 160, fieldType: 'user' },\n { field: 'status', header: 'Status', width: 130, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'priority', header: 'Priority', width: 140, fieldType: 'singleSelect', fieldProps: { options: PRIORITY, editors: [ana, ben] } },\n { field: 'due', header: 'Due', width: 140, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n ],\n views: [\n { id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } },\n {\n id: 'leadership',\n name: 'Leadership report',\n type: 'grid',\n locked: true,\n lockedBy: ben,\n color: { mode: 'field', field: 'priority' },\n state: {\n advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'priority', kind: 'select', op: 'is', value: 'High' }] },\n grouping: ['status'],\n sorting: [{ id: 'due', desc: false }],\n },\n },\n { id: 'board', name: 'Status board', type: 'kanban', stackBy: 'status' },\n {\n id: 'ana-mine',\n name: 'My open tasks',\n type: 'grid',\n personal: ana,\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'owner', kind: 'select', op: 'is', value: '@me' },\n { column: 'status', kind: 'select', op: 'isNot', value: 'Done' },\n ],\n },\n sorting: [{ id: 'due', desc: false }],\n },\n },\n {\n id: 'ben-hiring',\n name: 'Ben: by due date',\n type: 'grid',\n personal: ben,\n state: { sorting: [{ id: 'due', desc: false }], hiddenColumns: ['priority'] },\n },\n ],\n },\n ])\n\n // Who is signed in: whose personal views show, and whether they may lock views.\n const SIGNED_IN = PEOPLE.slice(0, 3)\n let who = $state(ana)\n const canLock = $derived(who === ana || who === ben)\n function signIn(id: string) {\n who = id\n setCurrentUser(PEOPLE.find((p) => p.id === id) ?? null)\n }\n const views = $derived(tables[0]?.views ?? [])\n const mine = $derived(views.filter((v) => v.personal === who).length)\n</script>\n\n<section class=\"base-demo\">\n <div class=\"base-demo-bar\">\n <span class=\"base-demo-label\">Signed in as</span>\n <div class=\"base-demo-seg\" role=\"radiogroup\" aria-label=\"Signed in as\">\n {#each SIGNED_IN as p (p.id)}\n <button type=\"button\" role=\"radio\" aria-checked={who === p.id} class:is-on={who === p.id} onclick={() => signIn(p.id)}>{p.name}</button>\n {/each}\n </div>\n <span class=\"base-demo-tip\">\n {mine ? `${mine} personal ${mine === 1 ? 'view' : 'views'} under My views` : 'No personal views yet'}; {canLock ? 'may lock and unlock views' : 'cannot lock or unlock views'}; {canLock ? 'can set Priority' : 'sees Priority read-only'}. Open \"Leadership report\" to see a locked view.\n </span>\n </div>\n {#key who}\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n lockViews={canLock}\n />\n {/key}\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .base-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }\n .base-demo-label { font-size: 13px; color: var(--sg-muted, #64748b); }\n .base-demo-seg { display: inline-flex; padding: 2px; border-radius: var(--sg-radius, 6px); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); }\n .base-demo-seg button {\n height: 28px; padding: 0 10px; border: 0; border-radius: calc(var(--sg-radius, 6px) - 2px); background: none;\n color: var(--sg-muted, #64748b); font: inherit; font-size: 13px; cursor: pointer;\n }\n .base-demo-seg button.is-on { background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); box-shadow: 0 0 0 1px var(--sg-border, #e2e8f0); }\n .base-demo-tip { font-size: 13px; color: var(--sg-muted, #64748b); }\n</style>\n"
4201
+ },
4202
+ {
4203
+ "id": "711-base-form-logic",
4204
+ "path": "examples/src/demos/711-base-form-logic.svelte",
4205
+ "title": "Base Form Logic",
4206
+ "category": "Base",
4207
+ "blurb": "711. SvGrid Base: form logic A support request form whose fields follow the answers, and links that open it filled in.",
4208
+ "source": "<script lang=\"ts\">\n /**\n * 711. SvGrid Base: form logic\n * ----------------------------\n * A support request form whose fields follow the answers, and links that\n * open it filled in.\n *\n * Conditional fields (`conditions` on SvBaseForm, `formConditions` on a\n * form view), each a view bar filter over the other answers:\n * - Company size shows when Account type is Business;\n * - App version shows for a Bug, Invoice number for Billing, and \"Tell us\n * more\" for Other;\n * - \"What is blocked?\" shows when \"Blocking my work\" is checked.\n * A hidden field is not required and is not sent: pick Bug, type a\n * version, switch to Billing and submit; the record has no version.\n *\n * Prefilled links: each button builds a link with `formPrefillLink` and\n * hands it to the form as `prefill`, the way a page passes\n * `?prefill_<Field name>=value` from its URL. `hide_<Field name>=true`\n * keeps a filled field out of sight and still sends it. Sent requests land\n * in the table on the right.\n */\n import { SvBase, SvBaseForm, enableBase, formPrefillLink, type FieldFilter } from '@svgrid/enterprise/base'\n\n enableBase()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n const TYPES = [{ value: 'Personal', color: '#94a3b8' }, { value: 'Business', color: '#2d7ff9' }]\n const SIZES = [{ value: '1-10' }, { value: '11-50' }, { value: '51-200' }, { value: '200+' }]\n const TOPICS = [\n { value: 'Bug', color: '#f82b60' },\n { value: 'Billing', color: '#fcb400' },\n { value: 'Feature request', color: '#20c933' },\n { value: 'Other', color: '#8b46ff' },\n ]\n const STATUS = [{ value: 'New', color: '#18bfff' }, { value: 'Open', color: '#fcb400' }, { value: 'Closed', color: '#94a3b8' }]\n\n const columns = [\n { field: 'name', header: 'Name', width: 160, fieldType: 'text' },\n { field: 'email', header: 'Email', width: 200, fieldType: 'email' },\n { field: 'account', header: 'Account type', width: 130, fieldType: 'singleSelect', fieldProps: { options: TYPES } },\n { field: 'size', header: 'Company size', width: 130, fieldType: 'singleSelect', fieldProps: { options: SIZES } },\n { field: 'topic', header: 'Topic', width: 140, fieldType: 'singleSelect', fieldProps: { options: TOPICS } },\n { field: 'version', header: 'App version', width: 120, fieldType: 'text', description: 'Settings > About shows it.' },\n { field: 'invoice', header: 'Invoice number', width: 140, fieldType: 'text' },\n { field: 'other', header: 'Tell us more', width: 220, fieldType: 'longText' },\n { field: 'blocking', header: 'Blocking my work', width: 140, fieldType: 'checkbox' },\n { field: 'impact', header: 'What is blocked?', width: 220, fieldType: 'longText' },\n { field: 'message', header: 'Message', width: 280, fieldType: 'longText' },\n // The team's fields. The form leaves them out.\n { field: 'status', header: 'Status', width: 110, fieldType: 'singleSelect', fieldProps: { options: STATUS, default: 'New' } },\n { field: 'received', header: 'Received', width: 130, fieldType: 'date', fieldProps: { dateFormat: 'friendly', defaultToday: true } },\n ]\n\n const data = [\n { id: 'r1', name: 'Lena Fischer', email: 'lena@northwind.example', account: 'Business', size: '51-200', topic: 'Billing', invoice: 'INV-20418', message: 'We were charged twice in October.', status: 'Open', received: day(-3) },\n { id: 'r2', name: 'Tom Reyes', email: 'tom.reyes@example.com', account: 'Personal', topic: 'Bug', version: '4.2.0', blocking: true, impact: 'Exports to PDF', message: 'The export button spins forever.', status: 'New', received: day(-1) },\n { id: 'r3', name: 'Priya Nair', email: 'priya@lumen.example', account: 'Business', size: '11-50', topic: 'Feature request', message: 'A dark theme for the mobile app, please.', status: 'Closed', received: day(-6) },\n ]\n\n const is = (column: string, value: string): FieldFilter => ({ kind: 'fieldFilter', conjunction: 'and', conditions: [{ column, kind: 'select', op: 'is', value }] })\n const conditions: Record<string, FieldFilter> = {\n size: is('account', 'Business'),\n version: is('topic', 'Bug'),\n invoice: is('topic', 'Billing'),\n other: is('topic', 'Other'),\n impact: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'blocking', kind: 'checkbox', op: 'is', value: true }] },\n }\n const FIELDS = ['name', 'email', 'account', 'size', 'topic', 'version', 'invoice', 'other', 'blocking', 'impact', 'message']\n\n // Where the form would live; the links below open it.\n const PAGE = 'https://support.example.com/request'\n const EXAMPLES: Array<{ id: string; label: string; values: Record<string, unknown>; hide?: string[] }> = [\n { id: 'blank', label: 'Blank form', values: {} },\n { id: 'billing', label: 'From the billing page', values: { topic: 'Billing', account: 'Business' }, hide: ['topic'] },\n { id: 'crash', label: 'From the crash dialog', values: { topic: 'Bug', version: '4.2.1', blocking: true }, hide: ['topic', 'version'] },\n { id: 'partner', label: 'From a partner email', values: { name: 'Sam Okoro', email: 'sam@brightline.example', account: 'Business', size: '51-200', topic: 'Other' } },\n ]\n\n let chosen = $state('blank')\n let api = $state.raw<any>(null)\n let copied = $state(false)\n\n const example = $derived(EXAMPLES.find((e) => e.id === chosen) ?? EXAMPLES[0]!)\n const link = $derived(formPrefillLink(PAGE, example.values, columns, { hide: example.hide }))\n\n const rowId = (r: { id: string }) => r.id\n function ready(a: unknown) {\n api = a\n }\n function choose(id: string) {\n chosen = id\n copied = false\n }\n async function copy() {\n try {\n await navigator.clipboard.writeText(link)\n copied = true\n } catch {\n copied = false\n }\n }\n</script>\n\n<section class=\"flogic\">\n <div class=\"flogic-form\">\n {#if api}\n <SvBaseForm\n {api}\n fields={FIELDS}\n required={['name', 'email', 'topic', 'size', 'version', 'invoice', 'other']}\n {conditions}\n prefill={link}\n title=\"Contact support\"\n description=\"We answer within one working day.\"\n submitLabel=\"Send request\"\n />\n {/if}\n </div>\n\n <div class=\"flogic-side\">\n <div class=\"flogic-links\">\n <div class=\"flogic-picks\" role=\"group\" aria-label=\"Open the form from a link\">\n {#each EXAMPLES as e (e.id)}\n <button type=\"button\" class=\"flogic-pick\" class:is-on={e.id === chosen} aria-pressed={e.id === chosen} onclick={() => choose(e.id)}>{e.label}</button>\n {/each}\n </div>\n <div class=\"flogic-link\">\n <code>{link}</code>\n <button type=\"button\" class=\"flogic-copy\" onclick={copy}>{copied ? 'Copied' : 'Copy link'}</button>\n </div>\n </div>\n\n <div class=\"flogic-table\">\n <SvBase\n {data}\n {columns}\n primaryField=\"name\"\n getRowId={rowId}\n editable\n sortable\n showRowNumbers\n expandRows\n rowHeight={36}\n containerHeight=\"100%\"\n onApiReady={ready}\n />\n </div>\n </div>\n</section>\n\n<style>\n .flogic {\n display: grid; grid-template-columns: minmax(320px, 440px) minmax(0, 1fr); gap: 12px;\n flex: 1; min-height: 600px; height: 100%; color: var(--sg-fg, #0f172a); font-family: var(--sg-font, inherit);\n }\n .flogic-form {\n min-height: 0; overflow: hidden;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px);\n }\n .flogic-side { display: flex; flex-direction: column; gap: 12px; min-width: 0; min-height: 0; }\n .flogic-links {\n display: flex; flex-direction: column; gap: 10px; padding: 10px 12px;\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius-lg, 10px);\n background: var(--sg-header-bg, var(--sg-bg, #fff));\n }\n .flogic-picks { display: flex; flex-wrap: wrap; gap: 6px; }\n .flogic-pick, .flogic-copy {\n height: 30px; padding: 0 12px; border: 1px solid var(--sg-border, #cbd5e1); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: inherit; font-size: 13px; cursor: pointer;\n }\n .flogic-pick.is-on { border-color: var(--sg-accent, #2563eb); color: var(--sg-accent, #2563eb); font-weight: 600; }\n .flogic-link { display: flex; align-items: flex-start; gap: 8px; }\n .flogic-link code {\n flex: 1; min-width: 0; padding: 6px 8px; overflow-wrap: anywhere;\n border-radius: var(--sg-radius, 6px); background: var(--sg-bg, #fff); border: 1px solid var(--sg-border, #e2e8f0);\n font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--sg-muted, #64748b);\n }\n .flogic-copy { flex: 0 0 auto; background: var(--sg-accent, #2563eb); border-color: var(--sg-accent, #2563eb); color: var(--sg-accent-fg, #fff); font-weight: 600; }\n .flogic-table { flex: 1 1 auto; min-height: 320px; display: flex; flex-direction: column; }\n @media (max-width: 860px) {\n .flogic { grid-template-columns: minmax(0, 1fr); height: auto; }\n .flogic-form { height: 640px; }\n .flogic-table { height: 420px; flex: 0 0 auto; }\n }\n</style>\n"
4209
+ },
4210
+ {
4211
+ "id": "712-base-mentions",
4212
+ "path": "examples/src/demos/712-base-mentions.svelte",
4213
+ "title": "Base Mentions",
4214
+ "category": "Base",
4215
+ "blurb": "712. SvGrid Base: @mentions and notifications A content review base: articles, their writer and editor, and the discussion on each one. Open a record (the expand button on a row, or a",
4216
+ "source": "<script lang=\"ts\">\n /**\n * 712. SvGrid Base: @mentions and notifications\n * ---------------------------------------------\n * A content review base: articles, their writer and editor, and the\n * discussion on each one. Open a record (the expand button on a row, or a\n * notification) and type `@` in the comment box: the people of the base are\n * listed, narrowed as you type; Up, Down and Enter pick one. The comment\n * keeps the mention as `@[Name](userId)`, so it is drawn as a chip with the\n * person's current name.\n *\n * The comment store's `onMention` hook runs once per comment that mentions\n * someone, with the comment, the people, the record and the grid api. Here\n * it fills an inbox per person and shows a toast where an app would send an\n * email or a chat message. Switch \"Signed in as\" to read someone else's\n * inbox; the comments you write are then theirs.\n */\n import { SvToaster, toast } from '@svgrid/grid'\n import {\n SvBase,\n enableBase,\n getCurrentUser,\n getFieldUsers,\n mentionIds,\n mentionText,\n mentionToken,\n openRecord,\n setCurrentUser,\n setRecordComments,\n type BaseTable,\n type FieldUser,\n type MentionEvent,\n type RecordComment,\n type RecordCommentStore,\n } from '@svgrid/enterprise/base'\n import { PEOPLE, usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const TABLE = 'review-articles'\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n const STATUS = [\n { value: 'Draft', color: '#94a3b8' },\n { value: 'In review', color: '#2d7ff9' },\n { value: 'Changes requested', color: '#fcb400' },\n { value: 'Approved', color: '#20c933' },\n { value: 'Published', color: '#8b46ff' },\n ]\n\n const articles = [\n { id: 'a1', title: 'Pricing page rewrite', status: 'In review', writer: 'u2', editor: 'u3', due: day(2), words: 1200 },\n { id: 'a2', title: 'Release notes: November', status: 'Draft', writer: 'u6', editor: 'u1', due: day(5), words: 650 },\n { id: 'a3', title: 'How we cut page load in half', status: 'Changes requested', writer: 'u4', editor: 'u5', due: day(1), words: 1800 },\n { id: 'a4', title: 'Customer story: a logistics team', status: 'Approved', writer: 'u7', editor: 'u3', due: day(-1), words: 1400 },\n { id: 'a5', title: 'Getting started guide', status: 'In review', writer: 'u5', editor: 'u8', due: day(3), words: 2300 },\n { id: 'a6', title: 'Security FAQ', status: 'Published', writer: 'u8', editor: 'u1', due: day(-6), words: 900 },\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: TABLE,\n name: 'Articles',\n primaryField: 'title',\n data: articles,\n columns: [\n { field: 'title', header: 'Article', width: 280, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 170, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'writer', header: 'Writer', width: 150, fieldType: 'user' },\n { field: 'editor', header: 'Editor', width: 150, fieldType: 'user' },\n { field: 'due', header: 'Due', width: 130, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'words', header: 'Words', width: 100, fieldType: 'number', fieldProps: { format: 'integer' } },\n ],\n views: [\n { id: 'all', name: 'All articles', type: 'grid' },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n ],\n props: { rowAdder: { label: 'Add article', defaults: () => ({ status: 'Draft', due: day(7) }) } },\n },\n ])\n\n // ---- Notifications ---------------------------------------------------------\n type Note = { id: string; to: string; from?: string; rowId: string; record: string; text: string; at: number; read: boolean }\n\n const person = (id: string | undefined) => getFieldUsers().find((u) => u.id === id)\n const nameOf = (id: string | undefined) => person(id)?.name ?? 'Someone'\n const titleOf = (rowId: string) => String(articles.find((a) => a.id === rowId)?.title ?? 'a record')\n // The comment as an email would carry it: each mention as @Name.\n const plain = (text: string) => mentionText(text, (id) => person(id)?.name)\n\n /** What the hook sends: one notification per person mentioned, except the author. */\n const notesFor = (comment: RecordComment, mentioned: ReadonlyArray<FieldUser>, record: string): Note[] =>\n mentioned\n .filter((p) => p.id !== comment.by)\n .map((p) => ({ id: `${comment.id}-${p.id}`, to: p.id, from: comment.by, rowId: comment.rowId, record, text: comment.text, at: comment.at, read: false }))\n\n // ---- Comments: kept in this page, seeded with a discussion -----------------\n const at = (minutesAgo: number) => Date.now() - minutesAgo * 60_000\n const who = (id: string) => PEOPLE.find((p) => p.id === id)!\n const m = (id: string) => mentionToken(who(id))\n const SEED: RecordComment[] = [\n { id: 's1', rowId: 'a1', tableId: TABLE, by: 'u2', at: at(190), text: `${m('u3')} can you check the plan table against the billing export before Friday?` },\n { id: 's2', rowId: 'a1', tableId: TABLE, by: 'u3', at: at(120), text: `Numbers match. ${m('u1')} the annual discount line needs legal to sign off.` },\n { id: 's3', rowId: 'a1', tableId: TABLE, by: 'u1', at: at(45), text: `Sent to legal. ${m('u2')} hold the publish until they reply.` },\n { id: 's4', rowId: 'a3', tableId: TABLE, by: 'u5', at: at(300), text: `The chart in the second section has no units. ${m('u4')} can you add them?` },\n { id: 's5', rowId: 'a3', tableId: TABLE, by: 'u4', at: at(80), text: `Added. ${m('u5')} ${m('u1')} ready for another pass.` },\n { id: 's6', rowId: 'a5', tableId: TABLE, by: 'u8', at: at(30), text: `Screenshots still show the old theme. ${m('u5')} I can retake them tomorrow.` },\n ].map((c) => ({ ...c, mentions: mentionIds(c.text) }))\n\n // By table and record. Other bases on the page keep theirs here too.\n const keyOf = (rowId: string, tableId?: string) => `${tableId ?? ''}/${rowId}`\n const seeded: Record<string, RecordComment[]> = {}\n for (const c of SEED) (seeded[keyOf(c.rowId, c.tableId)] ??= []).push(c)\n let comments = $state.raw(seeded)\n\n // What the seeded comments sent, newest first; the older ones already read.\n let notes = $state<Note[]>(\n SEED.flatMap((c) => notesFor(c, (c.mentions ?? []).map(who), titleOf(c.rowId)))\n .map((n) => ({ ...n, read: n.at < at(100) }))\n .sort((a, b) => b.at - a.at),\n )\n let api = $state<unknown>(null)\n\n const store: RecordCommentStore = {\n list: (rowId, _api, { tableId }) => comments[keyOf(rowId, tableId)] ?? [],\n add: (rowId, comment, _api, { tableId }) => {\n comments = { ...comments, [keyOf(rowId, tableId)]: [...(comments[keyOf(rowId, tableId)] ?? []), comment] }\n },\n // Once per comment that mentions someone. An app would send the emails here.\n onMention: (e: MentionEvent) => {\n if (e.tableId !== TABLE) return\n const fresh = notesFor(e.comment, e.mentioned, String(e.record?.title ?? titleOf(e.rowId)))\n notes = [...fresh, ...notes]\n for (const n of fresh) {\n const to = person(n.to)\n toast.info(`Emailed ${to?.name ?? 'Someone'}${to?.email ? ` (${to.email})` : ''}: mentioned on \"${n.record}\"`)\n }\n },\n }\n $effect(() => {\n setRecordComments(store)\n return () => setRecordComments(null)\n })\n\n // ---- Signed in as ----------------------------------------------------------\n const me = $derived(getCurrentUser())\n const inbox = $derived(notes.filter((n) => n.to === me?.id))\n const unread = $derived(inbox.filter((n) => !n.read).length)\n\n function signIn(id: string) {\n setCurrentUser(PEOPLE.find((p) => p.id === id) ?? null)\n }\n function show(n: Note) {\n notes = notes.map((x) => (x.id === n.id ? { ...x, read: true } : x))\n if (api) openRecord({ api, rowId: n.rowId, focus: 'comment' })\n }\n const onApiReady = (a: unknown) => (api = a)\n const markAllRead = () => (notes = notes.map((n) => (n.to === me?.id ? { ...n, read: true } : n)))\n const when = (t: number) => {\n const min = Math.round((Date.now() - t) / 60_000)\n return min < 1 ? 'just now' : min < 60 ? `${min} min ago` : `${Math.round(min / 60)} h ago`\n }\n</script>\n\n<section class=\"mentions-demo\">\n <div class=\"mentions-base\">\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n {onApiReady}\n />\n </div>\n <aside class=\"mentions-inbox\" aria-label=\"Notifications\">\n <label class=\"mentions-who\">\n <span>Signed in as</span>\n <select value={me?.id ?? ''} onchange={(e) => signIn(e.currentTarget.value)}>\n {#each PEOPLE as p (p.id)}\n <option value={p.id}>{p.name}</option>\n {/each}\n </select>\n </label>\n <div class=\"mentions-head\">\n <h3>Notifications</h3>\n {#if unread}<span class=\"mentions-count\" aria-label={`${unread} unread`}>{unread}</span>{/if}\n <button type=\"button\" class=\"mentions-link\" disabled={!unread} onclick={markAllRead}>Mark all read</button>\n </div>\n <ul class=\"mentions-list\">\n {#each inbox as n (n.id)}\n <li>\n <button type=\"button\" class=\"mentions-note\" class:is-unread={!n.read} onclick={() => show(n)}>\n <span class=\"mentions-line\"><strong>{nameOf(n.from)}</strong> mentioned you on <strong>{n.record}</strong></span>\n <span class=\"mentions-text\">{plain(n.text)}</span>\n <span class=\"mentions-meta\">{when(n.at)} - emailed to {me?.email}</span>\n </button>\n </li>\n {:else}\n <li class=\"mentions-empty\">Nothing for {me?.name ?? 'you'} yet. Mention them in a comment.</li>\n {/each}\n </ul>\n </aside>\n <SvToaster />\n</section>\n\n<style>\n .mentions-demo { display: flex; gap: 12px; flex: 1; min-height: 480px; height: 100%; }\n .mentions-base { display: flex; flex-direction: column; flex: 1; min-width: 0; }\n .mentions-inbox {\n display: flex; flex-direction: column; gap: 10px; width: 300px; flex: none; padding: 12px; overflow: auto;\n color: var(--sg-fg); background: var(--sg-bg); border: 1px solid var(--sg-border); border-radius: var(--sg-radius, 6px);\n }\n .mentions-who { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--sg-muted); }\n .mentions-who select {\n height: 32px; padding: 0 8px; font: inherit; font-size: 13px; color: var(--sg-fg); background: var(--sg-bg);\n border: 1px solid var(--sg-border); border-radius: var(--sg-radius, 6px);\n }\n .mentions-head { display: flex; align-items: center; gap: 8px; }\n .mentions-head h3 { margin: 0; font-size: 14px; }\n .mentions-count {\n min-width: 20px; padding: 0 6px; border-radius: 999px; font-size: 12px; font-weight: 600; line-height: 20px; text-align: center;\n color: var(--sg-bg); background: var(--sg-fg);\n }\n .mentions-link { margin-inline-start: auto; padding: 0; border: 0; background: none; font: inherit; font-size: 12px; color: var(--sg-fg); text-decoration: underline; cursor: pointer; }\n .mentions-link:disabled { color: var(--sg-muted); text-decoration: none; cursor: default; }\n .mentions-list { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; }\n .mentions-note {\n display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 8px 10px; text-align: start; font: inherit; font-size: 12px;\n color: var(--sg-fg); background: var(--sg-bg); border: 1px solid var(--sg-border); border-radius: var(--sg-radius, 6px); cursor: pointer;\n }\n .mentions-note.is-unread { border-inline-start: 3px solid var(--sg-fg); background: color-mix(in srgb, var(--sg-fg) 4%, var(--sg-bg)); }\n .mentions-note:hover { border-color: var(--sg-muted); }\n .mentions-text { color: var(--sg-muted); overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; }\n .mentions-meta { font-size: 11px; color: var(--sg-muted); }\n .mentions-empty { font-size: 12px; color: var(--sg-muted); }\n @media (max-width: 760px) {\n .mentions-demo { flex-direction: column; }\n .mentions-inbox { width: auto; }\n }\n</style>\n"
4217
+ },
4218
+ {
4219
+ "id": "713-base-phone-layout",
4220
+ "path": "examples/src/demos/713-base-phone-layout.svelte",
4221
+ "title": "Base Phone Layout",
4222
+ "category": "Base",
4223
+ "blurb": "713. SvGrid Base: phone layout The same base at three widths. Narrower than 600px (the base's own width, not the window's; `phoneLayout` changes it), a grid view shows",
4224
+ "source": "<script lang=\"ts\">\n /**\n * 713. SvGrid Base: phone layout\n * ------------------------------\n * The same base at three widths. Narrower than 600px (the base's own\n * width, not the window's; `phoneLayout` changes it), a grid view shows\n * each record as a card: its name and the next four fields the view shows,\n * in the view's filter and sort. A tap opens the record, and \"+\" adds one.\n * The view bar keeps its icons, the tab bar its tabs, and on a phone the\n * opened record fills the screen.\n *\n * Kanban, calendar, gallery and form views are already made of cards and\n * work as they are; the field visits below have a board by status.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n import { housePhoto } from '../shared/gallery-art'\n\n enableBase()\n usePeople()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n const STATUS = [\n { value: 'Scheduled', color: '#2d7ff9' },\n { value: 'On site', color: '#fcb400' },\n { value: 'Needs parts', color: '#f82b60' },\n { value: 'Done', color: '#20c933' },\n ]\n const JOB = [\n { value: 'Boiler service', color: '#ff6f2c' },\n { value: 'Leak', color: '#2d7ff9' },\n { value: 'Install', color: '#8b46ff' },\n { value: 'Inspection', color: '#20c933' },\n ]\n const VISITS: Array<[string, string, string, string, string, number, number]> = [\n ['14 Harbour Lane', 'Boiler service', 'On site', 'u2', 'Pressure drops overnight; customer home after 2pm.', 0, 1],\n ['9 Mill Street, flat 3', 'Leak', 'Scheduled', 'u4', 'Water under the kitchen sink. Key with the neighbour at no. 11.', 0, 2],\n ['221 Quarry Road', 'Install', 'Needs parts', 'u2', 'Wrong valve delivered; new one ordered for Thursday.', 1, 1],\n ['3 Orchard Close', 'Inspection', 'Scheduled', 'u5', 'Annual gas safety check for the landlord.', 1, 2],\n ['58 Station Approach', 'Boiler service', 'Scheduled', 'u4', 'Error code F28 on the display.', 2, 1],\n ['7 Willow Court', 'Leak', 'Done', 'u5', 'Replaced the compression fitting under the bath.', -1, 2],\n ['102 Bridge Road', 'Install', 'Scheduled', 'u2', 'New radiator in the back bedroom, customer supplies it.', 3, 1],\n ['16 Kiln Yard', 'Inspection', 'Done', 'u4', 'Passed. Certificate emailed.', -2, 2],\n ]\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'phone-visits',\n name: 'Visits',\n primaryField: 'address',\n data: VISITS.map(([address, job, status, tech, notes, when, floors], i) => ({\n id: `v${i + 1}`,\n address,\n job,\n status,\n tech,\n date: day(when),\n notes,\n photos: [{ id: `p${i + 1}`, name: 'front.svg', url: housePhoto(i + 2, floors === 2 ? 2 : 1), type: 'image/svg+xml' }],\n })),\n columns: [\n { field: 'address', header: 'Address', width: 220, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 130, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'date', header: 'Visit', width: 140, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'tech', header: 'Technician', width: 160, fieldType: 'user' },\n { field: 'job', header: 'Job', width: 140, fieldType: 'singleSelect', fieldProps: { options: JOB } },\n { field: 'notes', header: 'Notes', width: 300, fieldType: 'longText' },\n { field: 'photos', header: 'Photos', width: 140, fieldType: 'attachment' },\n ],\n views: [\n {\n id: 'today',\n name: 'Upcoming visits',\n type: 'grid',\n color: { mode: 'field', field: 'status' },\n state: {\n advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'isNot', value: 'Done' }] },\n sorting: [{ id: 'date', desc: false }],\n },\n },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n { id: 'all', name: 'All visits', type: 'grid' },\n ],\n props: { rowAdder: { label: 'Add visit', defaults: () => ({ status: 'Scheduled', date: day(1) }) } },\n },\n ])\n\n const WIDTHS = [\n { id: 'phone', label: 'Phone', width: 390 },\n { id: 'tablet', label: 'Tablet', width: 768 },\n { id: 'desktop', label: 'Desktop', width: 0 },\n ]\n let size = $state('phone')\n const width = $derived(WIDTHS.find((w) => w.id === size)?.width ?? 0)\n</script>\n\n<section class=\"base-demo\">\n <div class=\"base-demo-bar\">\n <div class=\"base-demo-seg\" role=\"radiogroup\" aria-label=\"Screen width\">\n {#each WIDTHS as w (w.id)}\n <button type=\"button\" role=\"radio\" aria-checked={size === w.id} class:is-on={size === w.id} onclick={() => (size = w.id)}>{w.label}{w.width ? ` (${w.width}px)` : ''}</button>\n {/each}\n </div>\n <span class=\"base-demo-tip\">{width && width < 600 ? 'Records as cards: tap one to open it, + adds a visit.' : 'Wider than 600px: the grid.'}</span>\n </div>\n <div class=\"base-demo-stage\" class:is-device={width > 0}>\n <div class=\"base-demo-device\" style:width={width ? `${width}px` : '100%'}>\n <SvBase\n bind:tables\n editable\n sortable\n expandRows\n showRowNumbers={width === 0}\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n fieldMenu\n />\n </div>\n </div>\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 640px; height: 100%; gap: 10px; }\n .base-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }\n .base-demo-seg { display: inline-flex; padding: 2px; border-radius: var(--sg-radius, 6px); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); }\n .base-demo-seg button {\n height: 28px; padding: 0 10px; border: 0; border-radius: calc(var(--sg-radius, 6px) - 2px); background: none;\n color: var(--sg-muted, #64748b); font: inherit; font-size: 13px; cursor: pointer;\n }\n .base-demo-seg button.is-on { background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); box-shadow: 0 0 0 1px var(--sg-border, #e2e8f0); }\n .base-demo-tip { font-size: 13px; color: var(--sg-muted, #64748b); }\n .base-demo-stage { flex: 1; min-height: 0; display: flex; justify-content: center; }\n .base-demo-stage.is-device { padding: 8px 0; background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); border-radius: var(--sg-radius-lg, 10px); }\n .base-demo-device { max-width: 100%; height: 100%; min-height: 560px; }\n .is-device .base-demo-device { max-height: 760px; box-shadow: 0 0 0 8px var(--sg-fg, #0f172a); border-radius: 18px; overflow: hidden; }\n</style>\n"
4225
+ },
4226
+ {
4227
+ "id": "714-base-web-component",
4228
+ "path": "examples/src/demos/714-base-web-component.svelte",
4229
+ "title": "Base Web Component",
4230
+ "category": "Base",
4231
+ "blurb": "714. SvGrid Base: the <sv-base> web component SvGrid Base as a custom element, for a page or an app with no Svelte in it: React, Vue, Angular, or a plain `<script>` tag. Everything below the",
4232
+ "source": "<script lang=\"ts\">\n /**\n * 714. SvGrid Base: the <sv-base> web component\n * ---------------------------------------------\n * SvGrid Base as a custom element, for a page or an app with no Svelte in\n * it: React, Vue, Angular, or a plain `<script>` tag. Everything below the\n * import is plain DOM code, the same calls a non-Svelte page makes: create\n * the element, set its attributes, assign `tables`, `users` and\n * `currentUser` as properties, and listen to `tableschange`.\n *\n * Edit a cell, add a record, a field, a view or a table: every change\n * arrives as one `tableschange` event with the whole list, which is what\n * an app stores. The log names what changed. \"Load the seed data\" assigns\n * a fresh list, which the element loads in place of the edited one.\n *\n * The code block is what a page with no build step writes.\n */\n import { onMount } from 'svelte'\n import '@svgrid/enterprise/wc/base'\n import type { SvBaseElement, SvBaseTable } from '@svgrid/enterprise/wc/base'\n import { PEOPLE } from '../shared/base-people'\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n const STATUS = [\n { value: 'To do', color: '#94a3b8' },\n { value: 'Doing', color: '#2d7ff9' },\n { value: 'Done', color: '#20c933' },\n ]\n\n /** A fresh copy each time: the element owns the list it is given. */\n function seed(): SvBaseTable[] {\n return [\n {\n id: 'wc-tasks',\n name: 'Tasks',\n primaryField: 'title',\n columns: [\n { field: 'title', header: 'Task', width: 240, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 120, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'owner', header: 'Owner', width: 150, fieldType: 'user' },\n { field: 'due', header: 'Due', width: 160, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'milestone', header: 'Milestone', width: 170, fieldType: 'link', fieldProps: { table: 'wc-milestones', multiple: false, inverse: 'tasks' } },\n ],\n data: [\n { id: 't1', title: 'Draft the launch post', status: 'Doing', owner: 'u1', due: day(2), milestone: ['m1'] },\n { id: 't2', title: 'Record the product tour', status: 'To do', owner: 'u3', due: day(5), milestone: ['m1'] },\n { id: 't3', title: 'Pricing page review', status: 'Done', owner: 'u2', due: day(-1), milestone: ['m2'] },\n { id: 't4', title: 'Email the beta list', status: 'To do', owner: 'u4', due: day(8), milestone: ['m2'] },\n ],\n views: [\n { id: 'all', name: 'All tasks', type: 'grid' },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n ],\n },\n {\n id: 'wc-milestones',\n name: 'Milestones',\n primaryField: 'name',\n columns: [\n { field: 'name', header: 'Milestone', width: 200, fieldType: 'text' },\n { field: 'date', header: 'Date', width: 130, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'tasks', header: 'Tasks', width: 320, fieldType: 'link', fieldProps: { table: 'wc-tasks', multiple: true, inverse: 'milestone' } },\n ],\n data: [\n { id: 'm1', name: 'Public beta', date: day(7), tasks: ['t1', 't2'] },\n { id: 'm2', name: 'General availability', date: day(21), tasks: ['t3', 't4'] },\n ],\n },\n ]\n }\n\n // What each table looked like at the last event, to say what changed.\n type Snapshot = { name: string; fields: string; views: string; data: string; records: number }\n const snap = (t: SvBaseTable): Snapshot => ({\n name: t.name,\n fields: JSON.stringify(t.columns),\n views: JSON.stringify(t.views ?? []),\n data: JSON.stringify(t.data),\n records: t.data.length,\n })\n let seen = new Map<string, Snapshot>()\n const remember = (list: SvBaseTable[]) => (seen = new Map(list.map((t) => [t.id, snap(t)])))\n\n function describe(list: SvBaseTable[]): string {\n const parts: string[] = []\n for (const t of list) {\n const was = seen.get(t.id)\n const now = snap(t)\n if (!was) { parts.push(`table \"${t.name}\" added`); continue }\n if (was.name !== now.name) parts.push(`\"${was.name}\" renamed to \"${now.name}\"`)\n if (was.fields !== now.fields) parts.push(`${t.name}: fields`)\n if (was.views !== now.views) parts.push(`${t.name}: views`)\n if (was.records !== now.records) parts.push(`${t.name}: ${now.records} records`)\n else if (was.data !== now.data) parts.push(`${t.name}: a record changed`)\n }\n for (const [id, was] of seen) if (!list.some((t) => t.id === id)) parts.push(`table \"${was.name}\" deleted`)\n remember(list)\n return parts.join(', ') || 'same content'\n }\n\n type Entry = { id: number; time: string; event: string; text: string }\n let log = $state<Entry[]>([])\n let n = 0\n function note(event: string, text: string) {\n const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })\n log = [{ id: ++n, time, event, text }, ...log].slice(0, 12)\n }\n\n let host: HTMLDivElement\n let base: SvBaseElement | null = null\n\n function load() {\n const tables = seed()\n remember(tables)\n if (base) base.tables = tables\n note('tables', 'assigned a fresh list')\n }\n\n onMount(() => {\n // Plain DOM from here on.\n const el = document.createElement('sv-base') as SvBaseElement\n for (const name of ['editable', 'sortable', 'show-row-numbers', 'column-adder', 'field-menu', 'expand-rows']) el.setAttribute(name, '')\n el.setAttribute('height', '440')\n el.users = PEOPLE\n el.currentUser = PEOPLE[0]!\n el.addEventListener('tableschange', (e) => note('tableschange', describe((e as CustomEvent<SvBaseTable[]>).detail)))\n el.addEventListener('ready', () => note('ready', 'a table\\'s grid is up; el.api is its api'))\n base = el\n load()\n host.append(el)\n return () => {\n el.remove()\n base = null\n }\n })\n\n const SNIPPET = `<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@svgrid/enterprise/dist/wc/sv-base-element.js\"><\\/script>\n\n<sv-base id=\"base\" height=\"440\" editable sortable show-row-numbers\n column-adder field-menu expand-rows></sv-base>\n\n<script type=\"module\">\n const base = document.getElementById('base')\n base.users = [{ id: 'u1', name: 'Ana Ruiz' }, { id: 'u2', name: 'Ben Okafor' }]\n base.currentUser = base.users[0]\n base.tables = [\n {\n id: 'tasks', name: 'Tasks', primaryField: 'title',\n columns: [\n { field: 'title', header: 'Task', fieldType: 'text' },\n { field: 'owner', header: 'Owner', fieldType: 'user' },\n { field: 'due', header: 'Due', fieldType: 'date' },\n ],\n data: [{ id: 't1', title: 'Draft the launch post', owner: 'u1', due: '2026-11-04' }],\n },\n ]\n // Every change, with the whole list: store it.\n base.addEventListener('tableschange', (e) => {\n localStorage.setItem('base', JSON.stringify(e.detail))\n })\n<\\/script>`\n</script>\n\n<section class=\"wcb-demo\">\n <div class=\"wcb-host\" bind:this={host}></div>\n <div class=\"wcb-panels\">\n <div class=\"wcb-panel\">\n <div class=\"wcb-head\">\n <h3>Events</h3>\n <button type=\"button\" class=\"wcb-btn\" onclick={load}>Load the seed data</button>\n </div>\n {#if log.length}\n <ol class=\"wcb-log\">\n {#each log as entry (entry.id)}\n <li>\n <span class=\"wcb-time\">{entry.time}</span>\n <code>{entry.event}</code>\n <span>{entry.text}</span>\n </li>\n {/each}\n </ol>\n {:else}\n <p class=\"wcb-empty\">Edit a cell to see a tableschange event.</p>\n {/if}\n </div>\n <div class=\"wcb-panel\">\n <div class=\"wcb-head\"><h3>The same page in plain HTML</h3></div>\n <pre class=\"wcb-code\">{SNIPPET}</pre>\n </div>\n </div>\n</section>\n\n<style>\n .wcb-demo { display: flex; flex-direction: column; gap: 12px; flex: 1; min-height: 480px; }\n .wcb-host { min-width: 0; }\n .wcb-panels { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); gap: 12px; }\n .wcb-panel {\n display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px;\n color: var(--sg-fg); background: var(--sg-bg); border: 1px solid var(--sg-border); border-radius: var(--sg-radius, 6px);\n }\n .wcb-head { display: flex; align-items: center; gap: 8px; }\n .wcb-head h3 { margin: 0; font-size: 14px; }\n .wcb-btn {\n margin-inline-start: auto; height: 28px; padding: 0 10px; font: inherit; font-size: 12px; cursor: pointer;\n color: var(--sg-fg); background: var(--sg-bg); border: 1px solid var(--sg-border); border-radius: var(--sg-radius, 6px);\n }\n .wcb-btn:hover { border-color: var(--sg-muted); }\n .wcb-btn:focus-visible { outline: 2px solid var(--sg-focus-ring); outline-offset: 1px; }\n .wcb-log { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; max-height: 260px; overflow: auto; font-size: 12px; }\n .wcb-log li { display: flex; flex-wrap: wrap; gap: 6px; align-items: baseline; }\n .wcb-log code { font-size: 11px; padding: 0 4px; border-radius: 4px; background: color-mix(in srgb, var(--sg-fg) 6%, var(--sg-bg)); }\n .wcb-time { color: var(--sg-muted); font-variant-numeric: tabular-nums; }\n .wcb-empty { margin: 0; font-size: 12px; color: var(--sg-muted); }\n .wcb-code {\n margin: 0; padding: 10px; max-height: 260px; overflow: auto; font-size: 11px; line-height: 1.5; white-space: pre;\n color: var(--sg-fg); background: color-mix(in srgb, var(--sg-fg) 4%, var(--sg-bg)); border-radius: var(--sg-radius, 6px);\n }\n @media (max-width: 760px) {\n .wcb-panels { grid-template-columns: minmax(0, 1fr); }\n }\n</style>\n"
4233
+ },
4234
+ {
4235
+ "id": "715-base-checklist-color-time",
4236
+ "path": "examples/src/demos/715-base-checklist-color-time.svelte",
4237
+ "title": "Base Checklist Color Time",
4238
+ "category": "Base",
4239
+ "blurb": "715. SvGrid Base: checklist, color and time of day fields Three field types on a table of conference sessions. Prep is a checklist: the cell shows how many items are done and a bar.",
4240
+ "source": "<script lang=\"ts\">\n /**\n * 715. SvGrid Base: checklist, color and time of day fields\n * ----------------------------------------------------------\n * Three field types on a table of conference sessions.\n *\n * Prep is a checklist: the cell shows how many items are done and a bar.\n * Click it to tick, add, rename, drag or delete items. It sorts by the\n * share done, and the second view filters for sessions not complete yet.\n *\n * Track is a color: a swatch and the hex code. The editor offers the 40\n * option colors and a box for a hex code; a paste reads #rgb, #rrggbb,\n * rgb() or a CSS name such as \"navy\".\n *\n * Starts and Ends are times of day with no date, stored as 'HH:MM'. Starts\n * shows a 12-hour clock, Ends a 24-hour one. Type \"9:30 am\", \"14:05\" or\n * \"2pm\"; Up and Down in the editor move by 15 minutes.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const steps = (done: number, ...names: string[]) => names.map((text, i) => ({ id: `s${i}`, text, done: i < done }))\n const SESSIONS: Array<[string, string, string, string, string, ReturnType<typeof steps>]> = [\n ['Opening keynote', '#2d7ff9', '09:00', '09:45', 'u1', steps(4, 'Slides final', 'Speaker briefed', 'Mic check', 'Livestream link')],\n ['Runes in practice', '#20c933', '10:00', '10:40', 'u3', steps(2, 'Slides final', 'Demo repo tagged', 'Mic check')],\n ['Grids at a million rows', '#8b46ff', '10:00', '10:40', 'u4', steps(1, 'Slides final', 'Benchmark rerun', 'Laptop on venue wifi', 'Mic check')],\n ['Lunch', '#fcb400', '12:00', '13:00', 'u6', steps(1, 'Dietary list sent', 'Count confirmed')],\n ['Forms without a library', '#20c933', '13:15', '13:55', 'u2', steps(0, 'Slides final', 'Mic check')],\n ['Accessible tables', '#ff6f2c', '14:00', '14:40', 'u5', steps(3, 'Slides final', 'Screen reader demo', 'Captions file')],\n ['Shipping a design system', '#8b46ff', '15:30', '16:10', 'u7', steps(1, 'Slides final', 'Figma file shared', 'Mic check')],\n ['Closing panel', '#2d7ff9', '16:30', '17:15', 'u8', steps(0, 'Panelists confirmed', 'Questions collected', 'Mic check')],\n ]\n const data = SESSIONS.map(([session, track, starts, ends, host, prep], i) => ({ id: `e${i + 1}`, session, track, starts, ends, host, prep }))\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'conf-sessions',\n name: 'Sessions',\n primaryField: 'session',\n data,\n columns: [\n { field: 'session', header: 'Session', width: 240, fieldType: 'text' },\n { field: 'track', header: 'Track', width: 130, fieldType: 'color' },\n { field: 'starts', header: 'Starts', width: 110, fieldType: 'timeOfDay', fieldProps: { timeFormat: '12hour' } },\n { field: 'ends', header: 'Ends', width: 100, fieldType: 'timeOfDay', fieldProps: { timeFormat: '24hour' } },\n { field: 'prep', header: 'Prep', width: 170, fieldType: 'checklist' },\n { field: 'host', header: 'Host', width: 160, fieldType: 'user' },\n ],\n views: [\n { id: 'agenda', name: 'Agenda', type: 'grid', state: { sorting: [{ id: 'starts', desc: false }] } },\n {\n id: 'open-prep',\n name: 'Prep not done',\n type: 'grid',\n state: {\n sorting: [{ id: 'prep', desc: false }],\n advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'prep', kind: 'checklist', op: 'notAllDone' }] },\n },\n },\n ],\n props: { rowAdder: { label: 'Add session' } },\n },\n ])\n</script>\n\n<section class=\"base-demo\">\n <p class=\"base-demo-tip\">\n Click a Prep cell to tick or add items, double-click a Track to pick a color, or select a Starts cell and type <kbd>2pm</kbd>.\n Copy a Prep cell and paste it into another: it copies as <code>[x] item [ ] item</code>.\n </p>\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .base-demo-tip { margin: 0; font-size: 13px; line-height: 1.5; color: var(--sg-muted, #64748b); }\n .base-demo-tip kbd,\n .base-demo-tip code {\n padding: 1px 5px; font: inherit; font-size: 12px; border-radius: 4px;\n border: 1px solid var(--sg-border, #e2e8f0); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); color: var(--sg-fg, #0f172a);\n }\n</style>\n"
4241
+ },
4242
+ {
4243
+ "id": "716-base-ai-field",
4244
+ "path": "examples/src/demos/716-base-ai-field.svelte",
4245
+ "title": "Base Ai Field",
4246
+ "category": "Base",
4247
+ "blurb": "716. SvGrid Base: AI fields An AI field (`fieldType: 'ai'`) holds a value a model writes for each record from a prompt that names the record's fields:",
4248
+ "source": "<script lang=\"ts\">\n /**\n * 716. SvGrid Base: AI fields\n * ---------------------------\n * An AI field (`fieldType: 'ai'`) holds a value a model writes for each\n * record from a prompt that names the record's fields:\n * \"Write a one-line pitch for {Name}, aimed at {Audience}, that mentions\n * {Key feature}.\" The answer is stored in the record, so it sorts, filters\n * and exports like typed text, and anyone can edit it by hand.\n *\n * - The spark in a cell generates that record; the column menu has\n * \"Generate for all\". Requests run three at a time.\n * - Pitch has `auto` on: change a product's Audience or Key feature and its\n * pitch is written again. Price band has it off, so it changes only when\n * asked, and it picks one of its options (`output: 'singleSelect'`).\n * - A failed request shows its message in the cell (the product with no Key\n * feature fails here on purpose). Values go through the grid's edit path:\n * Ctrl+Z undoes a generated value like a typed one.\n *\n * The model here is a stand-in that writes from templates, so the demo runs\n * without a key. A real one is a function from a request to the model's text,\n * registered once with `setAIProvider` from `@svgrid/grid`. Keep the key on\n * your server:\n *\n * setAIProvider(async ({ prompt, maxOutputTokens, signal }) => {\n * const res = await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ prompt, maxOutputTokens }), signal })\n * return (await res.json()).text\n * })\n */\n import { getAIProvider, setAIProvider, type AIProvider } from '@svgrid/grid'\n import { SvBase, enableBase, generateAIField, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n\n // ---- The stand-in model ---------------------------------------------------------\n\n const OPENERS = ['Built for', 'Made for', 'Ready for']\n const pick = (list: string[], seed: string) => list[[...seed].reduce((n, c) => n + c.charCodeAt(0), 0) % list.length]!\n\n const demoProvider: AIProvider = async (req) => {\n await new Promise((r) => setTimeout(r, 400 + Math.random() * 500))\n if (req.signal?.aborted) throw new DOMException('Cancelled', 'AbortError')\n const ask = /Instruction:\\n([\\s\\S]*?)\\n\\n/.exec(req.prompt)?.[1] ?? ''\n const pitch = /pitch for (.*), aimed at (.*), that mentions (.*)\\.$/.exec(ask)\n if (pitch) {\n const [, name, audience, feature] = pitch\n if (!feature!.trim()) throw new Error('Key feature is empty: nothing to build the pitch on')\n return JSON.stringify({ value: `${pick(OPENERS, name!)} ${audience!.toLowerCase()}: the ${name} brings ${feature!.toLowerCase()}.` })\n }\n // \"at $189.00\", or however the locale writes it: the whole units are enough here.\n const price = /price band fits .* at \\D*(\\d+)/.exec(ask)\n if (price) {\n const n = Number(price[1])\n return JSON.stringify({ value: n < 80 ? 'Budget' : n < 200 ? 'Mid-range' : 'Premium' })\n }\n return JSON.stringify({ value: ask.slice(0, 80) })\n }\n\n // Registered before the base draws, so its cells see a provider; the\n // gallery's previous one comes back when the demo closes.\n const previous = getAIProvider()\n setAIProvider(demoProvider)\n $effect(() => () => setAIProvider(previous))\n\n // ---- The base -------------------------------------------------------------------\n\n const AUDIENCE = [\n { value: 'Hikers', color: '#16a34a' },\n { value: 'Trail runners', color: '#ea580c' },\n { value: 'Commuters', color: '#2563eb' },\n { value: 'Climbers', color: '#7c3aed' },\n ]\n const BANDS = [\n { value: 'Budget', color: '#94a3b8' },\n { value: 'Mid-range', color: '#0ea5e9' },\n { value: 'Premium', color: '#a855f7' },\n ]\n const PRODUCTS: Array<[string, string, string, number]> = [\n ['Ridge 40 pack', 'Hikers', 'A frame that carries 15 kg without shoulder strain', 189],\n ['Fellrunner vest', 'Trail runners', 'Two soft flasks at the chest', 95],\n ['Metro shell', 'Commuters', 'Taped seams and a hood that fits over a helmet', 229],\n ['Crag chalk bag', 'Climbers', 'A brush loop and a drawstring that closes one-handed', 29],\n ['Summit trekking poles', 'Hikers', 'Carbon shafts at 230 g a pair', 149],\n ['Night loop headlamp', 'Trail runners', '', 59],\n ['Commute pannier', 'Commuters', 'Clips on and off the rack in one move', 119],\n ['Belay gloves', 'Climbers', 'Leather palms that last through rope burn', 45],\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'ai-products',\n name: 'Products',\n primaryField: 'name',\n data: PRODUCTS.map(([name, audience, feature, price], i) => ({ id: `p${i + 1}`, name, audience, feature, price })),\n columns: [\n { field: 'name', header: 'Name', width: 180, fieldType: 'text' },\n { field: 'audience', header: 'Audience', width: 130, fieldType: 'singleSelect', fieldProps: { options: AUDIENCE } },\n { field: 'feature', header: 'Key feature', width: 210, fieldType: 'text' },\n {\n field: 'pitch', header: 'Pitch', width: 300, fieldType: 'ai',\n fieldProps: { prompt: 'Write a one-line pitch for {Name}, aimed at {Audience}, that mentions {Key feature}.', output: 'text', auto: true },\n description: 'Written by a model from Name, Audience and Key feature.',\n },\n { field: 'price', header: 'Price', width: 100, fieldType: 'number', fieldProps: { format: 'currency', precision: 2 } },\n {\n field: 'band', header: 'Price band', width: 130, fieldType: 'ai',\n fieldProps: { prompt: 'Which price band fits {Name} at {Price}?', output: 'singleSelect', options: BANDS, auto: false },\n },\n ],\n views: [{ id: 'all', name: 'All products', type: 'grid' }],\n },\n ])\n\n let api: unknown = null\n const onApiReady = (a: unknown) => (api = a)\n let busy = $state(false)\n let result = $state('')\n\n async function generateAll() {\n if (!api || busy) return\n busy = true\n result = ''\n try {\n const run = await generateAIField(api, 'pitch', 'all')\n result = `${run.written} written${run.failed ? `, ${run.failed} failed` : ''}`\n } finally {\n busy = false\n }\n }\n</script>\n\n<section class=\"aif-demo\">\n <div class=\"aif-bar\">\n <button type=\"button\" class=\"aif-run\" onclick={() => void generateAll()} disabled={busy}>{busy ? 'Generating...' : 'Generate all pitches'}</button>\n <span class=\"aif-result\" aria-live=\"polite\">{result}</span>\n <p class=\"aif-tip\">Then change a product's Audience: its pitch is written again. Price band changes only from its spark or column menu.</p>\n </div>\n <SvBase\n bind:tables\n {onApiReady}\n editable\n sortable\n showRowNumbers\n expandRows\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n</section>\n\n<style>\n .aif-demo { display: flex; flex-direction: column; flex: 1; min-height: 480px; height: 100%; gap: 10px; }\n .aif-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; font-size: 13px; }\n .aif-run {\n height: 32px; padding: 0 14px; border: 0; border-radius: var(--sg-radius, 6px);\n background: var(--sg-accent, #2563eb); color: var(--sg-accent-fg, #fff); font: inherit; font-weight: 600; cursor: pointer;\n }\n .aif-run:disabled { opacity: 0.6; cursor: default; }\n .aif-result { color: var(--sg-fg, #0f172a); }\n .aif-tip { flex: 1 1 260px; margin: 0; line-height: 1.5; color: var(--sg-muted, #64748b); }\n</style>\n"
4249
+ },
4250
+ {
4251
+ "id": "717-base-read-only-share",
4252
+ "path": "examples/src/demos/717-base-read-only-share.svelte",
4253
+ "title": "Base Read Only Share",
4254
+ "category": "Base",
4255
+ "blurb": "717. SvGrid Base: a read-only share The same tables twice: as the team edits them, and as a client sees them through a share link. `readOnly` turns every way to change the base off:",
4256
+ "source": "<script lang=\"ts\">\n /**\n * 717. SvGrid Base: a read-only share\n * -----------------------------------\n * The same tables twice: as the team edits them, and as a client sees them\n * through a share link. `readOnly` turns every way to change the base off:\n * cells, the record view, card drags, calendar drags, the record and field\n * menus, \"+ Add\", the tab bar's table menu, import, trash, undo and the\n * comment box. A form view is not shared.\n *\n * The client can still switch tables and views, search, filter, sort,\n * group and open records. What they change in a view stays in their page;\n * the app's `onTablesChange` never hears of it.\n *\n * Comments are kept by table id and record id, not by base, so a comment\n * the team writes shows in the client's link too (read, with no box to\n * answer). An app that saves comments hands its store to\n * `setRecordComments`, and both read from that.\n *\n * `readOnly={{ hideFields: ['budget'] }}` leaves Budget out, and with it\n * the fields that would show it: the rollup of it on Clients and the\n * formula that reads it. Hiding is for display; a share of something\n * secret is a copy the server builds without it.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const STATUS = [\n { value: 'Planned', color: '#94a3b8' },\n { value: 'In progress', color: '#2d7ff9' },\n { value: 'Review', color: '#ff9f0a' },\n { value: 'Done', color: '#20c933' },\n ]\n const PROJECTS: Array<[string, string, string, string, number, string, string]> = [\n ['Spring campaign site', 'c1', 'In progress', 'u1', 18000, '2026-11-04', '2026-11-21'],\n ['Product photo shoot', 'c1', 'Planned', 'u3', 6500, '2026-11-12', '2026-11-14'],\n ['Checkout redesign', 'c2', 'Review', 'u2', 24000, '2026-10-27', '2026-11-10'],\n ['Loyalty app onboarding', 'c2', 'In progress', 'u5', 14500, '2026-11-02', '2026-11-28'],\n ['Annual report layout', 'c3', 'Done', 'u6', 9000, '2026-10-06', '2026-10-31'],\n ['Brand guidelines refresh', 'c3', 'Planned', 'u4', 11000, '2026-11-17', '2026-12-05'],\n ]\n const projects = PROJECTS.map(([name, client, status, lead, budget, start, end], i) => ({ id: `pr${i + 1}`, name, client: [client], status, lead, budget, start, end }))\n const clients = [\n { id: 'c1', name: 'Northwind Outdoors', contact: 'Ana Ruiz' },\n { id: 'c2', name: 'Fabrikam Retail', contact: 'Ben Okafor' },\n { id: 'c3', name: 'Litware Foundation', contact: 'Farah Haddad' },\n ].map((c) => ({ ...c, projects: projects.filter((p) => p.client[0] === c.id).map((p) => p.id) }))\n\n // The team's tables. Edit them, then look at the shared link: it shows the change.\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'share-projects',\n name: 'Projects',\n primaryField: 'name',\n data: projects,\n columns: [\n { field: 'name', header: 'Project', width: 230, fieldType: 'text' },\n { field: 'client', header: 'Client', width: 180, fieldType: 'link', fieldProps: { table: 'share-clients', multiple: false, inverse: 'projects' } },\n { field: 'status', header: 'Status', width: 130, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'lead', header: 'Lead', width: 150, fieldType: 'user' },\n { field: 'start', header: 'Start', width: 120, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'end', header: 'Due', width: 120, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'budget', header: 'Budget', width: 120, fieldType: 'currency', fieldProps: { precision: 0 } },\n { field: 'weekly', header: 'Per week', width: 120, fieldType: 'formula', fieldProps: { formula: 'ROUND({Budget} / 4, 0)' } },\n ],\n views: [\n { id: 'all', name: 'All projects', type: 'grid', color: { mode: 'field', field: 'status' } },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n { id: 'calendar', name: 'Schedule', type: 'calendar', dateField: 'start', endField: 'end', color: { mode: 'field', field: 'status' } },\n { id: 'brief', name: 'New project brief', type: 'form' },\n ],\n },\n {\n id: 'share-clients',\n name: 'Clients',\n primaryField: 'name',\n data: clients,\n columns: [\n { field: 'name', header: 'Client', width: 210, fieldType: 'text' },\n { field: 'contact', header: 'Contact', width: 160, fieldType: 'text' },\n { field: 'projects', header: 'Projects', width: 320, fieldType: 'link', fieldProps: { table: 'share-projects', multiple: true, inverse: 'client' } },\n { field: 'total', header: 'Total budget', width: 140, fieldType: 'rollup', fieldProps: { linkField: 'projects', field: 'budget', aggregation: 'SUM' } },\n ],\n views: [{ id: 'all', name: 'All clients', type: 'grid' }],\n },\n ])\n\n let mode = $state<'edit' | 'share'>('share')\n let hideBudget = $state(true)\n // The app's own record of saves: a client's view changes never land here.\n let saves = $state(0)\n</script>\n\n<section class=\"share-demo\">\n <div class=\"share-demo-bar\">\n <div class=\"share-demo-switch\" role=\"group\" aria-label=\"Show the base as\">\n <button type=\"button\" aria-pressed={mode === 'edit'} onclick={() => (mode = 'edit')}>Team (editing)</button>\n <button type=\"button\" aria-pressed={mode === 'share'} onclick={() => (mode = 'share')}>Client (share link)</button>\n </div>\n {#if mode === 'share'}\n <label class=\"share-demo-check\"><input type=\"checkbox\" bind:checked={hideBudget} /> Hide Budget from the client</label>\n {/if}\n <span class=\"share-demo-saves\" aria-live=\"polite\">Share link onTablesChange: {saves} {saves === 1 ? 'call' : 'calls'}</span>\n </div>\n <p class=\"share-demo-tip\">\n {#if mode === 'share'}\n Try to change something: double-click a cell, drag a card on By status, right-click a record. Sorting, filtering and switching views work, and stay in this page.\n {:else}\n Edit a status or a date here, or open a record and comment on it, then switch to the client's link: it shows the change and the comment.\n {/if}\n </p>\n {#key mode === 'share' ? `share-${hideBudget}` : 'edit'}\n {#if mode === 'share'}\n <SvBase\n {tables}\n readOnly={hideBudget ? { hideFields: ['budget'] } : true}\n onTablesChange={() => (saves += 1)}\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n fieldMenu\n />\n {:else}\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n {/if}\n {/key}\n <SvToaster />\n</section>\n\n<style>\n .share-demo { display: flex; flex-direction: column; flex: 1; min-height: 520px; height: 100%; gap: 10px; }\n .share-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; font-size: 13px; color: var(--sg-fg, #0f172a); }\n .share-demo-switch { display: inline-flex; padding: 2px; border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius, 6px); background: var(--sg-muted-bg, var(--sg-header-bg, #f8fafc)); }\n .share-demo-switch button {\n height: 28px; padding: 0 12px; border: 0; border-radius: calc(var(--sg-radius, 6px) - 2px);\n background: none; color: var(--sg-muted, #64748b); font: inherit; cursor: pointer;\n }\n .share-demo-switch button[aria-pressed='true'] { background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font-weight: 600; box-shadow: 0 0 0 1px var(--sg-border, #e2e8f0); }\n .share-demo-switch button:focus-visible { outline: 2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb)); outline-offset: -2px; }\n .share-demo-check { display: inline-flex; align-items: center; gap: 6px; }\n .share-demo-check input { accent-color: var(--sg-accent, #2563eb); }\n .share-demo-saves { margin-left: auto; font-size: 12px; color: var(--sg-muted, #64748b); font-variant-numeric: tabular-nums; }\n .share-demo-tip { margin: 0; font-size: 13px; line-height: 1.5; color: var(--sg-muted, #64748b); }\n</style>\n"
4257
+ },
4258
+ {
4259
+ "id": "718-base-search-all-tables",
4260
+ "path": "examples/src/demos/718-base-search-all-tables.svelte",
4261
+ "title": "Base Search All Tables",
4262
+ "category": "Base",
4263
+ "blurb": "718. SvGrid Base: search across tables The box in the tab bar searches every table of the base, not only the one on screen. It reads each field the way its cell shows it: a deal's",
4264
+ "source": "<script lang=\"ts\">\n /**\n * 718. SvGrid Base: search across tables\n * --------------------------------------\n * The box in the tab bar searches every table of the base, not only the\n * one on screen. It reads each field the way its cell shows it: a deal's\n * stage by its label, an owner by name, a close date as written, a contact's\n * company by the company's name. Results come grouped by table, five per\n * table with a count of the rest, the words marked and the field they\n * matched in. Up and Down pick one, Enter opens it in its own table.\n *\n * Ctrl+K (or \"/\" outside the grid) puts the cursor in the box.\n *\n * The same search runs without the box: `searchBase(tables, query)`\n * returns the groups, shown here under the base for the query typed in the\n * box beside it.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, searchBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const COMPANIES: Array<[string, string, string]> = [\n ['Northwind Outdoors', 'Retail', 'Denver'],\n ['Fabrikam Retail', 'Retail', 'Chicago'],\n ['Litware Foundation', 'Nonprofit', 'Boston'],\n ['Contoso Pharma', 'Health', 'Basel'],\n ['Adatum Logistics', 'Logistics', 'Rotterdam'],\n ['Tailspin Air', 'Travel', 'Seattle'],\n ['Wingtip Toys', 'Retail', 'Austin'],\n ['Proseware Labs', 'Software', 'Berlin'],\n ['Lucerne Publishing', 'Media', 'Zurich'],\n ['Margie Travel', 'Travel', 'Lisbon'],\n ['Alpine Ski House', 'Hospitality', 'Innsbruck'],\n ['Coho Winery', 'Food', 'Napa'],\n ]\n const FIRST = ['Maya', 'Jonas', 'Priya', 'Lucas', 'Sofía', 'Omar', 'Hannah', 'Kenji', 'Amélie', 'Diego', 'Noor', 'Erik', 'Lena', 'Tomás', 'Yara']\n const LAST = ['Lindqvist', 'Moreau', 'Natarajan', 'Becker', 'Okoye', 'Haddad', 'García', 'Novak', 'Tanaka', 'Brennan']\n const ROLES = ['Buyer', 'CFO', 'Head of Ops', 'IT lead', 'Marketing lead', 'Founder']\n const STAGES = [\n { value: 'lead', label: 'Lead', color: '#94a3b8' },\n { value: 'qualified', label: 'Qualified', color: '#2d7ff9' },\n { value: 'proposal', label: 'Proposal sent', color: '#ff9f0a' },\n { value: 'won', label: 'Closed won', color: '#20c933' },\n { value: 'lost', label: 'Closed lost', color: '#f82b60' },\n ]\n const DEALS = ['Annual renewal', 'Pilot', 'Fleet tracking rollout', 'Data migration', 'Support upgrade', 'New region launch', 'Seasonal campaign', 'Analytics add-on']\n\n const companies = COMPANIES.map(([name, industry, city], i) => ({ id: `co${i + 1}`, name, industry, city, contacts: [] as string[], deals: [] as string[] }))\n const contacts = Array.from({ length: 30 }, (_, i) => {\n const company = companies[i % companies.length]!\n const name = `${FIRST[i % FIRST.length]} ${LAST[(i * 7) % LAST.length]}`\n const c = { id: `ct${i + 1}`, name, role: ROLES[i % ROLES.length], email: `${name.toLowerCase().normalize('NFD').replace(/\\p{M}/gu, '').replace(' ', '.')}@${company.name.split(' ')[0]!.toLowerCase()}.example`, company: [company.id] }\n company.contacts.push(c.id)\n return c\n })\n const deals = Array.from({ length: 24 }, (_, i) => {\n const company = companies[(i * 5) % companies.length]!\n const d = {\n id: `dl${i + 1}`,\n name: `${company.name.split(' ')[0]} ${DEALS[i % DEALS.length]}`,\n company: [company.id],\n stage: STAGES[i % STAGES.length]!.value,\n owner: `u${(i % 6) + 1}`,\n amount: 4000 + ((i * 3779) % 60) * 1000,\n close: `2026-${String(10 + (i % 3)).padStart(2, '0')}-${String(1 + ((i * 11) % 28)).padStart(2, '0')}`,\n notes: i % 4 === 0 ? 'Waiting on procurement to sign the order form.' : i % 4 === 1 ? 'Asked for a security review before the pilot.' : '',\n }\n company.deals.push(d.id)\n return d\n })\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'search-deals',\n name: 'Deals',\n primaryField: 'name',\n data: deals,\n columns: [\n { field: 'name', header: 'Deal', width: 240, fieldType: 'text' },\n { field: 'company', header: 'Company', width: 180, fieldType: 'link', fieldProps: { table: 'search-companies', multiple: false, inverse: 'deals' } },\n { field: 'stage', header: 'Stage', width: 140, fieldType: 'singleSelect', fieldProps: { options: STAGES } },\n { field: 'owner', header: 'Owner', width: 150, fieldType: 'user' },\n { field: 'amount', header: 'Amount', width: 120, fieldType: 'currency', fieldProps: { precision: 0 } },\n { field: 'close', header: 'Close date', width: 140, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'notes', header: 'Notes', width: 300, fieldType: 'longText' },\n ],\n views: [{ id: 'all', name: 'All deals', type: 'grid', color: { mode: 'field', field: 'stage' } }],\n },\n {\n id: 'search-contacts',\n name: 'Contacts',\n primaryField: 'name',\n data: contacts,\n columns: [\n { field: 'name', header: 'Name', width: 190, fieldType: 'text' },\n { field: 'role', header: 'Role', width: 140, fieldType: 'text' },\n { field: 'email', header: 'Email', width: 260, fieldType: 'email' },\n { field: 'company', header: 'Company', width: 190, fieldType: 'link', fieldProps: { table: 'search-companies', multiple: false, inverse: 'contacts' } },\n ],\n views: [{ id: 'all', name: 'All contacts', type: 'grid' }],\n },\n {\n id: 'search-companies',\n name: 'Companies',\n primaryField: 'name',\n data: companies,\n columns: [\n { field: 'name', header: 'Company', width: 200, fieldType: 'text' },\n { field: 'industry', header: 'Industry', width: 130, fieldType: 'text' },\n { field: 'city', header: 'City', width: 120, fieldType: 'text' },\n { field: 'contacts', header: 'Contacts', width: 260, fieldType: 'link', fieldProps: { table: 'search-contacts', multiple: true, inverse: 'company' } },\n { field: 'deals', header: 'Deals', width: 260, fieldType: 'link', fieldProps: { table: 'search-deals', multiple: true, inverse: 'company' } },\n ],\n views: [{ id: 'all', name: 'All companies', type: 'grid' }],\n },\n ])\n\n // The headless search, for the line under the base.\n let query = $state('proposal')\n const found = $derived(searchBase(tables, query))\n</script>\n\n<section class=\"search-demo\">\n <p class=\"search-demo-tip\">\n Press <kbd>Ctrl</kbd>+<kbd>K</kbd> and try <em>northwind</em>, <em>proposal</em>, <em>ana</em>, <em>security</em> or <em>tomas</em>: a stage, an owner, a note, a contact with an accent. Enter opens the record in its table.\n </p>\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n fieldMenu\n />\n <div class=\"search-demo-headless\">\n <label>\n <code>searchBase(tables, </code><input bind:value={query} aria-label=\"Query for searchBase\" /><code>)</code>\n </label>\n <span>\n {#each found as g, i (g.table)}{i ? ', ' : ''}{g.name}: {g.total}{:else}no records{/each}\n </span>\n </div>\n <SvToaster />\n</section>\n\n<style>\n .search-demo { display: flex; flex-direction: column; flex: 1; min-height: 520px; height: 100%; gap: 10px; }\n .search-demo-tip { margin: 0; font-size: 13px; line-height: 1.5; color: var(--sg-muted, #64748b); }\n .search-demo-tip kbd {\n padding: 1px 5px; font: inherit; font-size: 12px; border-radius: 4px;\n border: 1px solid var(--sg-border, #e2e8f0); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); color: var(--sg-fg, #0f172a);\n }\n .search-demo-headless { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; font-size: 12px; color: var(--sg-muted, #64748b); }\n .search-demo-headless label { display: inline-flex; align-items: center; gap: 2px; }\n .search-demo-headless code { font-size: 12px; color: var(--sg-fg, #0f172a); }\n .search-demo-headless input {\n width: 110px; height: 24px; padding: 0 6px; box-sizing: border-box; font: inherit; color: var(--sg-fg, #0f172a);\n border: 1px solid var(--sg-border, #e2e8f0); border-radius: 4px; background: var(--sg-bg, #fff);\n }\n</style>\n"
4265
+ },
4266
+ {
4267
+ "id": "719-base-list-view",
4268
+ "path": "examples/src/demos/719-base-list-view.svelte",
4269
+ "title": "Base List View",
4270
+ "category": "Base",
4271
+ "blurb": "719. SvGrid Base: list view A product feedback base read as a list: one entry per record, its name in bold and three fields under it, so long titles stay readable on a",
4272
+ "source": "<script lang=\"ts\">\n /**\n * 719. SvGrid Base: list view\n * ---------------------------\n * A product feedback base read as a list: one entry per record, its name\n * in bold and three fields under it, so long titles stay readable on a\n * narrow screen. The list takes the view's filter, sort and groups from the\n * grid underneath: \"By area\" groups by Area and sorts by Votes, \"Planned\"\n * is filtered to one status. A group header folds its records.\n *\n * Click a record or press Enter to open it; Up and Down move, Home and End\n * jump. \"Customize list\" in the view bar picks the fields under the name\n * (kept in the view as `listFields`). Switch to the phone width to see the\n * same list at 390px.\n */\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n const AREA = [\n { value: 'Reports', color: '#2d7ff9' },\n { value: 'Mobile app', color: '#8b46ff' },\n { value: 'Billing', color: '#fcb400' },\n { value: 'Integrations', color: '#20c933' },\n ]\n const STATUS = [\n { value: 'New', color: '#94a3b8' },\n { value: 'Under review', color: '#2d7ff9' },\n { value: 'Planned', color: '#8b46ff' },\n { value: 'Shipped', color: '#20c933' },\n ]\n const FEEDBACK: Array<[string, string, string, number, string, number, string]> = [\n ['Schedule a report to go out every Monday morning', 'Reports', 'Planned', 48, 'Northwind Freight', -12, 'u2'],\n ['Export a filtered report to PDF with our logo on it', 'Reports', 'Under review', 31, 'Bluebird Clinics', -6, 'u3'],\n ['Offline mode for drivers who lose signal on rural routes', 'Mobile app', 'Planned', 57, 'Northwind Freight', -20, 'u4'],\n ['Scan a barcode to find the record instead of typing the code', 'Mobile app', 'New', 12, 'Harbor Supply', -2, ''],\n ['Pay invoices by bank transfer, not only by card', 'Billing', 'Shipped', 40, 'Atlas Legal', -45, 'u5'],\n ['Show VAT on its own line on every invoice', 'Billing', 'Under review', 22, 'Kestrel Studio', -8, 'u5'],\n ['Two-way sync with the accounting system we already use', 'Integrations', 'Under review', 64, 'Atlas Legal', -15, 'u2'],\n ['Post to a team chat channel when a deal is won', 'Integrations', 'New', 9, 'Kestrel Studio', -1, ''],\n ['Dark mode for the mobile app at night shifts', 'Mobile app', 'Shipped', 35, 'Bluebird Clinics', -60, 'u4'],\n ['Compare this quarter with the last one in the same chart', 'Reports', 'New', 18, 'Harbor Supply', -3, ''],\n ['A webhook when a record changes, with the old and new values', 'Integrations', 'Planned', 27, 'Northwind Freight', -9, 'u3'],\n ['Let the finance team see invoices without edit rights', 'Billing', 'New', 6, 'Atlas Legal', -1, ''],\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'list-feedback',\n name: 'Feedback',\n primaryField: 'title',\n data: FEEDBACK.map(([title, area, status, votes, customer, when, owner], i) => ({\n id: `f${i + 1}`,\n title,\n area,\n status,\n votes,\n customer,\n submitted: day(when),\n owner: owner || null,\n })),\n columns: [\n { field: 'title', header: 'Feedback', width: 360, fieldType: 'text' },\n { field: 'status', header: 'Status', width: 140, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'votes', header: 'Votes', width: 90, fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'customer', header: 'Customer', width: 170, fieldType: 'text' },\n { field: 'area', header: 'Area', width: 140, fieldType: 'singleSelect', fieldProps: { options: AREA } },\n { field: 'submitted', header: 'Submitted', width: 130, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'owner', header: 'Owner', width: 150, fieldType: 'user' },\n ],\n views: [\n {\n id: 'by-area',\n name: 'By area',\n type: 'list',\n listFields: ['status', 'votes', 'customer'],\n state: { sorting: [{ id: 'area', desc: false }, { id: 'votes', desc: true }], grouping: ['area'], hiddenColumns: [], advancedFilter: null },\n },\n {\n id: 'planned',\n name: 'Planned',\n type: 'list',\n listFields: ['area', 'owner', 'submitted'],\n state: {\n sorting: [{ id: 'votes', desc: true }],\n grouping: [],\n hiddenColumns: [],\n advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'is', value: 'Planned' }] },\n },\n },\n { id: 'all', name: 'All feedback', type: 'grid' },\n ],\n props: { rowAdder: { label: 'Add feedback', defaults: () => ({ status: 'New', votes: 1, submitted: day(0) }) } },\n },\n ])\n\n let phone = $state(false)\n</script>\n\n<section class=\"base-demo\">\n <div class=\"base-demo-bar\">\n <div class=\"base-demo-seg\" role=\"radiogroup\" aria-label=\"Width\">\n <button type=\"button\" role=\"radio\" aria-checked={!phone} class:is-on={!phone} onclick={() => (phone = false)}>Desktop</button>\n <button type=\"button\" role=\"radio\" aria-checked={phone} class:is-on={phone} onclick={() => (phone = true)}>Phone (390px)</button>\n </div>\n <span class=\"base-demo-tip\">Click a record or press Enter to open it. Up and Down move.</span>\n </div>\n <div class=\"base-demo-stage\" class:is-device={phone}>\n <div class=\"base-demo-device\" style:width={phone ? '390px' : '100%'}>\n <SvBase bind:tables editable sortable expandRows showRowNumbers rowHeight={40} containerHeight=\"100%\" fieldMenu />\n </div>\n </div>\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 620px; height: 100%; gap: 10px; }\n .base-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }\n .base-demo-seg { display: inline-flex; padding: 2px; border-radius: var(--sg-radius, 6px); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); }\n .base-demo-seg button {\n height: 28px; padding: 0 10px; border: 0; border-radius: calc(var(--sg-radius, 6px) - 2px); background: none;\n color: var(--sg-muted, #64748b); font: inherit; font-size: 13px; cursor: pointer;\n }\n .base-demo-seg button.is-on { background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); box-shadow: 0 0 0 1px var(--sg-border, #e2e8f0); }\n .base-demo-tip { font-size: 13px; color: var(--sg-muted, #64748b); }\n .base-demo-stage { flex: 1; min-height: 0; display: flex; justify-content: center; }\n .base-demo-stage.is-device { padding: 8px 0; background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); border-radius: var(--sg-radius-lg, 10px); }\n .base-demo-device { max-width: 100%; height: 100%; min-height: 560px; }\n .is-device .base-demo-device { max-height: 720px; box-shadow: 0 0 0 8px var(--sg-fg, #0f172a); border-radius: 18px; overflow: hidden; }\n</style>\n"
4273
+ },
4154
4274
  {
4155
4275
  "id": "72-graphql-adapter",
4156
4276
  "path": "examples/src/demos/72-graphql-adapter.svelte",
@@ -4159,6 +4279,22 @@ export const examples = [
4159
4279
  "blurb": "72. GraphQL adapter - server-side sort + filter + page Wires the grid to a GraphQL endpoint. Whenever the user sorts, filters, or pages, the grid hands the state to the consumer via the",
4160
4280
  "source": "<script lang=\"ts\">\n /**\n * 72. GraphQL adapter - server-side sort + filter + page\n * -----------------------------------------------------\n * Wires the grid to a GraphQL endpoint. Whenever the user sorts,\n * filters, or pages, the grid hands the state to the consumer via the\n * `externalSort` / `externalFilter` callbacks; we build a typed GraphQL\n * query from that state, send it, and re-set `data` from the response.\n *\n * The endpoint here is a mock in-process resolver so the demo runs\n * stand-alone; swap `runQuery` for `fetch('/graphql', ...)` against\n * your own backend and the rest of the wiring is unchanged.\n */\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n type GridColumns,\n type SvGridApi,\n } from '@svgrid/grid'\n import { makeOrders, type Order } from '../shared/seed'\n\n const ALL_ORDERS = makeOrders(2500)\n\n // ---- Mock GraphQL resolver --------------------------------------------\n type Sort = { field: string; dir: 'asc' | 'desc' }\n type Filter = { field: string; op: 'contains' | 'eq' | 'gt' | 'lt'; value: string }\n type OrdersQuery = {\n page: number; pageSize: number\n sort?: Sort\n filters?: Filter[]\n }\n type OrdersResult = {\n items: Order[]\n total: number\n elapsedMs: number\n }\n\n /** \"Backend\". Pretends to be GraphQL: receives a typed query and returns rows. */\n async function runQuery(q: OrdersQuery): Promise<OrdersResult> {\n const started = performance.now()\n // Realistic 150-300ms server hop.\n await new Promise((r) => setTimeout(r, 150 + Math.random() * 150))\n\n let working = ALL_ORDERS.slice()\n for (const f of q.filters ?? []) {\n working = working.filter((row) => {\n const v = (row as Record<string, unknown>)[f.field]\n switch (f.op) {\n case 'contains': return String(v ?? '').toLowerCase().includes(f.value.toLowerCase())\n case 'eq': return String(v ?? '') === f.value\n case 'gt': return Number(v) > Number(f.value)\n case 'lt': return Number(v) < Number(f.value)\n }\n })\n }\n if (q.sort) {\n const { field, dir } = q.sort\n const sign = dir === 'desc' ? -1 : 1\n working = working.slice().sort((a, b) => {\n const av = (a as Record<string, unknown>)[field]\n const bv = (b as Record<string, unknown>)[field]\n if (typeof av === 'number' && typeof bv === 'number') return sign * (av - bv)\n return sign * String(av ?? '').localeCompare(String(bv ?? ''))\n })\n }\n const total = working.length\n const start = (q.page - 1) * q.pageSize\n const items = working.slice(start, start + q.pageSize)\n return { items, total, elapsedMs: performance.now() - started }\n }\n\n /** Pretty-print the equivalent GraphQL doc for the side panel. */\n function toGraphQLDoc(q: OrdersQuery): string {\n const args: string[] = [`page: ${q.page}`, `pageSize: ${q.pageSize}`]\n if (q.sort) args.push(`sort: { field: \"${q.sort.field}\", dir: ${q.sort.dir.toUpperCase()} }`)\n if (q.filters?.length) {\n const lines = q.filters.map((f) => ` { field: \"${f.field}\", op: ${f.op.toUpperCase()}, value: \"${f.value}\" }`).join(',\\n')\n args.push(`filters: [\\n${lines}\\n ]`)\n }\n return `query OrdersPage {\\n orders(\\n ${args.join(',\\n ')}\\n ) {\\n total\\n items {\\n orderId company product sellDate quantity price country\\n }\\n }\\n}`\n }\n\n // ---- Component state --------------------------------------------------\n const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n let api = $state<SvGridApi<typeof features, Order> | null>(null)\n\n let rows = $state<Order[]>([])\n let total = $state(0)\n let page = $state(1)\n const pageSize = 25\n let sort = $state<Sort | undefined>(undefined)\n let filters = $state<Filter[]>([])\n let loading = $state(false)\n let lastDoc = $state<string>('')\n let lastElapsed = $state<number>(0)\n\n async function refresh() {\n loading = true\n const q: OrdersQuery = { page, pageSize, sort, filters: filters.length ? filters : undefined }\n lastDoc = toGraphQLDoc(q)\n const res = await runQuery(q)\n rows = res.items\n total = res.total\n lastElapsed = Math.round(res.elapsedMs)\n loading = false\n }\n\n // Initial load.\n $effect(() => { void refresh() })\n\n // ---- Grid wiring ------------------------------------------------------\n function onSortChange(clauses: Array<{ id: string; desc: boolean }>) {\n sort = clauses[0]\n ? { field: clauses[0].id, dir: clauses[0].desc ? 'desc' : 'asc' }\n : undefined\n page = 1\n void refresh()\n }\n function onFiltersChange(payload: {\n global: string\n columns: Array<{ id: string; operator: string; value: string }>\n }) {\n const out: Filter[] = []\n for (const c of payload.columns) {\n if (!c.value) continue\n const op: Filter['op'] = c.operator === 'equals' ? 'eq'\n : c.operator === 'greaterThan' ? 'gt'\n : c.operator === 'lessThan' ? 'lt'\n : 'contains'\n out.push({ field: c.id, op, value: c.value })\n }\n filters = out\n page = 1\n void refresh()\n }\n\n const totalPages = $derived(Math.max(1, Math.ceil(total / pageSize)))\n\n const columns: GridColumns<Order> = [\n { field: 'orderId', header: 'Order ID', editorType: 'text', width: 140 },\n { field: 'company', header: 'Company', editorType: 'text', width: 180 },\n { field: 'product', header: 'Product', editorType: 'text', width: 180 },\n { field: 'sellDate', header: 'Sell date',editorType: 'date', width: 130,\n format: { type: 'date', pattern: 'y-m-d' } },\n { field: 'quantity', header: 'Qty', editorType: 'number', width: 90 },\n { field: 'price', header: 'Price', editorType: 'number', width: 130,\n format: { type: 'currency', currency: 'USD' } },\n { field: 'country', header: 'Country', editorType: 'text', width: 110 },\n ]\n</script>\n\n<section class=\"flex flex-col flex-1 min-h-0 gap-3\">\n <div class=\"flex flex-wrap items-center gap-2 text-sm shrink-0\">\n <span class=\"font-medium\">\n {total.toLocaleString()} rows · page {page} of {totalPages}\n </span>\n {#if loading}<span class=\"text-amber-600 dark:text-amber-400\">Fetching…</span>\n {:else}<span class=\"text-emerald-600 dark:text-emerald-400\">✓ {lastElapsed} ms</span>{/if}\n\n <div class=\"ml-auto inline-flex items-center gap-1\">\n <button type=\"button\" disabled={page <= 1}\n onclick={() => { page = Math.max(1, page - 1); void refresh() }}\n class=\"gql-btn rounded-md border px-2 py-1 disabled:opacity-40\"\n >‹ Prev</button>\n <button type=\"button\" disabled={page >= totalPages}\n onclick={() => { page = Math.min(totalPages, page + 1); void refresh() }}\n class=\"gql-btn rounded-md border px-2 py-1 disabled:opacity-40\"\n >Next ›</button>\n </div>\n </div>\n\n <div class=\"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px] gap-4 flex-1 min-h-0\">\n <div class=\"flex-1 min-h-0 min-w-0\">\n <SvGrid responsive={true}\n columnResize\n data={rows}\n columns={columns}\n features={features}\n filterMode=\"menu\"\n externalSort={true}\n externalFilter={true}\n selectionMode=\"cell\"\n showRowNumbers={true}\n enableInlineEditing={false}\n enableCellSelection={true}\n rowHeight={32}\n containerHeight=\"100%\"\n fitColumns={true}\n onApiReady={(next) => (api = next)}\n onSortingChange={onSortChange}\n onFiltersChange={onFiltersChange}\n />\n </div>\n\n <aside class=\"flex flex-col gap-2 min-h-0\">\n <header class=\"flex items-baseline justify-between shrink-0\">\n <div class=\"gql-label text-xs uppercase tracking-wide\">Last GraphQL query</div>\n <div class=\"gql-meta text-[10px]\">round-trip {lastElapsed} ms</div>\n </header>\n <pre class=\"gql-doc flex-1 min-h-0 overflow-auto text-[11px] leading-snug border rounded p-3\">{lastDoc}</pre>\n </aside>\n </div>\n</section>\n\n<style>\n /* Pager + query panel chrome track the active grid theme. */\n .gql-btn {\n border-color: var(--sg-border, #cbd5e1);\n background: var(--sg-bg, #ffffff);\n color: var(--sg-fg, #0f172a);\n }\n .gql-label { color: var(--sg-muted, #64748b); }\n .gql-meta { color: var(--sg-muted, #94a3b8); }\n .gql-doc {\n border-color: var(--sg-border, #e2e8f0);\n background: var(--sg-bg-subtle, var(--sg-header-bg, #f8fafc));\n color: var(--sg-fg, #0f172a);\n }\n</style>\n"
4161
4281
  },
4282
+ {
4283
+ "id": "720-base-inbox-view",
4284
+ "path": "examples/src/demos/720-base-inbox-view.svelte",
4285
+ "title": "Base Inbox View",
4286
+ "category": "Base",
4287
+ "blurb": "720. SvGrid Base: inbox view A support queue as an inbox: the tickets on the left, newest first by Received (`inboxDateField`), the picked one on the right with its fields,",
4288
+ "source": "<script lang=\"ts\">\n /**\n * 720. SvGrid Base: inbox view\n * ----------------------------\n * A support queue as an inbox: the tickets on the left, newest first by\n * Received (`inboxDateField`), the picked one on the right with its fields,\n * to read and edit in place. The view's filter applies: Solved tickets are\n * left out.\n *\n * The tickets live in a small in-page database read through `baseSource`.\n * Teammates change it from elsewhere: a few seconds after the page opens\n * Cleo, Dev and Elena move some tickets and a new one arrives, and \"A\n * teammate changes a ticket\" does it again. The base reads the change and\n * marks the record unread: bold, with a dot, and what changed listed on top\n * of the record, credited from the Last changed by field. Picking a ticket\n * marks it read; \"Mark all read\" marks the rest.\n *\n * Down or j picks the next ticket, Up or k the previous, Enter opens the\n * full record with its comments. Narrower than 640px the inbox shows the\n * list, then the ticket with a way back.\n */\n import { onMount } from 'svelte'\n import { SvToaster, type ServerDataSource } from '@svgrid/grid'\n import { SvBase, baseSource, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n type Row = Record<string, unknown>\n const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString()\n const STATUS = [\n { value: 'New', color: '#2d7ff9' },\n { value: 'Open', color: '#fcb400' },\n { value: 'Waiting on customer', color: '#8b46ff' },\n { value: 'Solved', color: '#20c933' },\n ]\n const PRIORITY = [\n { value: 'Urgent', color: '#f82b60' },\n { value: 'High', color: '#ff6f2c' },\n { value: 'Normal', color: '#94a3b8' },\n ]\n const TICKETS: Array<[string, string, string, string, string, number, string]> = [\n ['Invoice shows the wrong company address', 'billing@atlaslegal.example', 'Open', 'Normal', 'u2', 35, 'Our new address has been in the account settings since March, but the October invoice still has the old one.'],\n ['Cannot sign in after the password reset', 'ops@northwind.example', 'New', 'Urgent', '', 50, 'The reset link works, then the sign-in page says the password is wrong. Three people on the team have the same problem.'],\n ['CSV export cuts off long notes', 'data@harborsupply.example', 'Open', 'High', 'u4', 95, 'Notes longer than about 250 characters end in the middle of a word in the exported file.'],\n ['How do I add a teammate as read-only?', 'hello@kestrel.example', 'Waiting on customer', 'Normal', 'u5', 160, 'We want our accountant to see the invoices but not change anything.'],\n ['Charged twice for November', 'finance@bluebird.example', 'Open', 'High', 'u2', 240, 'Two identical charges on the card statement, a minute apart.'],\n ['Report builder is slow with a year of data', 'ops@northwind.example', 'Open', 'Normal', 'u4', 380, 'Opening the yearly report takes about forty seconds; a quarter is fine.'],\n ['Please add a Monday digest email', 'hello@kestrel.example', 'New', 'Normal', '', 600, 'A short summary of last week would save us a meeting.'],\n ['Webhook retries flood our endpoint', 'dev@atlaslegal.example', 'Waiting on customer', 'High', 'u3', 900, 'After a timeout we got the same event 40 times in a minute.'],\n ['Thanks for the quick fix yesterday', 'finance@bluebird.example', 'Solved', 'Normal', 'u5', 1500, 'The import works again. Closing this from our side.'],\n ]\n\n // ---- The database: tickets kept in this page, read and written like a real one --------\n const store = new Map<string, Row>(\n TICKETS.map(([subject, customer, status, priority, assignee, ago, message], i) => [\n `t${i + 1}`,\n { id: `t${i + 1}`, subject, customer, status, priority, assignee: assignee || null, received: minutesAgo(ago), message, modified_by: 'u1' },\n ]),\n )\n const ds: ServerDataSource<Row> = {\n async getRows() {\n return { rows: [...store.values()].map((r) => ({ ...r })), rowCount: store.size }\n },\n async createRow(input) {\n const row = { ...input }\n store.set(String(row.id), row)\n return { ...row }\n },\n async updateRow(id, patch) {\n store.set(String(id), { ...store.get(String(id)), ...patch })\n return { ...store.get(String(id))! }\n },\n async deleteRow(id) {\n store.delete(String(id))\n },\n }\n // What the base listens to: a database's realtime channel would call these.\n const listeners = new Set<() => void>()\n const realtime = (onChange: () => void) => {\n listeners.add(onChange)\n return () => listeners.delete(onChange)\n }\n\n const notSolved = { kind: 'fieldFilter' as const, conjunction: 'and' as const, conditions: [{ column: 'status', kind: 'select' as const, op: 'isNot' as const, value: 'Solved' }] }\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'inbox-tickets',\n name: 'Tickets',\n primaryField: 'subject',\n data: [],\n columns: [\n { field: 'subject', header: 'Subject', width: 300, fieldType: 'text' },\n { field: 'customer', header: 'Customer', width: 210, fieldType: 'email' },\n { field: 'status', header: 'Status', width: 170, fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'priority', header: 'Priority', width: 110, fieldType: 'singleSelect', fieldProps: { options: PRIORITY } },\n { field: 'assignee', header: 'Assignee', width: 150, fieldType: 'user' },\n { field: 'received', header: 'Received', width: 170, fieldType: 'date', fieldProps: { dateFormat: 'friendly', time: true } },\n { field: 'message', header: 'Message', width: 320, fieldType: 'longText' },\n { field: 'modified_by', header: 'Last changed by', width: 150, fieldType: 'lastModifiedBy' },\n ],\n views: [\n {\n id: 'inbox',\n name: 'Inbox',\n type: 'inbox',\n inboxDateField: 'received',\n listFields: ['customer', 'status', 'priority'],\n state: { sorting: [], grouping: [], hiddenColumns: [], advancedFilter: notSolved },\n },\n { id: 'all', name: 'All tickets', type: 'grid', state: { sorting: [{ id: 'received', desc: true }], grouping: [], hiddenColumns: [], advancedFilter: null } },\n ],\n source: baseSource(ds, { realtime }),\n props: { rowAdder: { label: 'Add ticket', defaults: () => ({ status: 'New', priority: 'Normal', received: new Date().toISOString() }) } },\n },\n ])\n\n // ---- Teammates, changing tickets from elsewhere -------------------------------------\n const CHANGES: Array<(n: number) => void> = [\n () => patch('t2', { status: 'Open', assignee: 'u3', modified_by: 'u3' }),\n () => patch('t5', { status: 'Waiting on customer', priority: 'Normal', modified_by: 'u2' }),\n (n) =>\n store.set(`n${n}`, {\n id: `n${n}`,\n subject: 'Mobile app crashes when opening a photo',\n customer: 'field@harborsupply.example',\n status: 'New',\n priority: 'Urgent',\n assignee: null,\n received: new Date().toISOString(),\n message: 'Since this morning the app closes as soon as a photo attachment is tapped.',\n modified_by: 'u4',\n }),\n () => patch('t3', { priority: 'Urgent', assignee: 'u5', modified_by: 'u5' }),\n () => patch('t6', { status: 'Waiting on customer', modified_by: 'u4' }),\n () => patch('t4', { status: 'Open', message: 'They replied: read-only for one person, the accountant.', modified_by: 'u5' }),\n ]\n let next = 0\n function patch(id: string, values: Row) {\n const row = store.get(id)\n if (row) store.set(id, { ...row, ...values })\n }\n /** One teammate's change, then the database tells its listeners. */\n function teammate() {\n const change = CHANGES[next % CHANGES.length]!\n next += 1\n change(next)\n for (const on of listeners) on()\n }\n onMount(() => {\n // The first changes land once the base has read the tickets.\n const timers = [1500, 1800, 2100].map((ms) => setTimeout(teammate, ms))\n return () => timers.forEach(clearTimeout)\n })\n\n let phone = $state(false)\n</script>\n\n<section class=\"base-demo\">\n <div class=\"base-demo-bar\">\n <button type=\"button\" class=\"base-demo-btn\" onclick={teammate}>A teammate changes a ticket</button>\n <div class=\"base-demo-seg\" role=\"radiogroup\" aria-label=\"Width\">\n <button type=\"button\" role=\"radio\" aria-checked={!phone} class:is-on={!phone} onclick={() => (phone = false)}>Desktop</button>\n <button type=\"button\" role=\"radio\" aria-checked={phone} class:is-on={phone} onclick={() => (phone = true)}>Phone (390px)</button>\n </div>\n <span class=\"base-demo-tip\">j and k move through the tickets; Enter opens one in full.</span>\n </div>\n <div class=\"base-demo-stage\" class:is-device={phone}>\n <div class=\"base-demo-device\" style:width={phone ? '390px' : '100%'}>\n <SvBase bind:tables editable sortable expandRows showRowNumbers rowHeight={40} containerHeight=\"100%\" fieldMenu />\n </div>\n </div>\n <SvToaster />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 620px; height: 100%; gap: 10px; }\n .base-demo-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }\n .base-demo-btn {\n height: 32px; padding: 0 12px; border: 1px solid var(--sg-border, #e2e8f0); border-radius: var(--sg-radius, 6px);\n background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); font: inherit; font-size: 13px; cursor: pointer;\n }\n .base-demo-btn:focus-visible { outline: 2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb)); outline-offset: 2px; }\n .base-demo-seg { display: inline-flex; padding: 2px; border-radius: var(--sg-radius, 6px); background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); }\n .base-demo-seg button {\n height: 28px; padding: 0 10px; border: 0; border-radius: calc(var(--sg-radius, 6px) - 2px); background: none;\n color: var(--sg-muted, #64748b); font: inherit; font-size: 13px; cursor: pointer;\n }\n .base-demo-seg button.is-on { background: var(--sg-bg, #fff); color: var(--sg-fg, #0f172a); box-shadow: 0 0 0 1px var(--sg-border, #e2e8f0); }\n .base-demo-tip { font-size: 13px; color: var(--sg-muted, #64748b); }\n .base-demo-stage { flex: 1; min-height: 0; display: flex; justify-content: center; }\n .base-demo-stage.is-device { padding: 8px 0; background: color-mix(in srgb, var(--sg-fg, #0f172a) 7%, transparent); border-radius: var(--sg-radius-lg, 10px); }\n .base-demo-device { max-width: 100%; height: 100%; min-height: 560px; }\n .is-device .base-demo-device { max-height: 720px; box-shadow: 0 0 0 8px var(--sg-fg, #0f172a); border-radius: 18px; overflow: hidden; }\n</style>\n"
4289
+ },
4290
+ {
4291
+ "id": "721-base-dashboard",
4292
+ "path": "examples/src/demos/721-base-dashboard.svelte",
4293
+ "title": "Base Dashboard",
4294
+ "category": "Base",
4295
+ "blurb": "721. SvGrid Base: dashboard view A sales base with three tables (Deals, Accounts, Activities) and a dashboard view on Deals that sums up all three. Each tile reads one",
4296
+ "source": "<script lang=\"ts\">\n /**\n * 721. SvGrid Base: dashboard view\n * --------------------------------\n * A sales base with three tables (Deals, Accounts, Activities) and a\n * dashboard view on Deals that sums up all three. Each tile reads one\n * table with its own filter: the open pipeline and what was won as money,\n * the share of deals won, the pipeline by stage, accounts by industry,\n * the biggest open deals, and the activities due in the next seven days.\n *\n * \"Edit dashboard\" adds a tile (a number, a chart, a list of records or a\n * progress bar), edits or removes one, sets its size and moves it by drag\n * or with the arrows. The tiles are saved on the view, so they come back\n * with `tables`. Change a deal in the \"All deals\" view and the tiles\n * follow; a record in a list tile opens in its own table. Click a number\n * or progress tile, or a bar or slice of a chart, to list the records\n * behind it and open one.\n */\n import { SvBase, enableBase, type BaseTable, type FieldFilter } from '@svgrid/enterprise/base'\n import { usePeople } from '../shared/base-people'\n\n enableBase()\n usePeople()\n\n const STAGES = [\n { value: 'Lead', color: '#94a3b8' },\n { value: 'Qualified', color: '#18bfff' },\n { value: 'Proposal', color: '#2d7ff9' },\n { value: 'Negotiation', color: '#fcb400' },\n { value: 'Won', color: '#20c933' },\n { value: 'Lost', color: '#f82b60' },\n ]\n const INDUSTRIES = [\n { value: 'Wholesale', color: '#ff6f2c' },\n { value: 'Manufacturing', color: '#2d7ff9' },\n { value: 'Software', color: '#8b46ff' },\n { value: 'Retail', color: '#fcb400' },\n { value: 'Healthcare', color: '#20c933' },\n ]\n const KINDS = [\n { value: 'Call', color: '#18bfff' },\n { value: 'Email', color: '#8b46ff' },\n { value: 'Meeting', color: '#ff6f2c' },\n ]\n // Dates around today, so \"due this week\" always has something in it.\n const day = (n: number) => {\n const d = new Date()\n d.setDate(d.getDate() + n)\n return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`\n }\n\n // ---- Sample records -------------------------------------------------------\n\n const ACCOUNTS: Array<[string, string, number]> = [\n ['Northwind Traders', 'Wholesale', 420],\n ['Contoso', 'Manufacturing', 2600],\n ['Fabrikam', 'Software', 880],\n ['Adventure Works', 'Retail', 310],\n ['Tailspin Toys', 'Retail', 140],\n ['Litware', 'Healthcare', 560],\n ['Proseware', 'Software', 95],\n ]\n const PRODUCTS = ['Platform license', 'Team plan', 'Renewal', 'Expansion', 'Pilot']\n const STAGE_OF = [0, 1, 2, 3, 4, 2, 1, 3, 0, 5, 2, 4, 1, 3, 2, 0, 4, 3, 1, 2, 5, 4]\n const deals = STAGE_OF.map((s, i) => {\n const acct = i % ACCOUNTS.length\n return {\n id: `d${i + 1}`,\n deal: `${ACCOUNTS[acct]![0]}: ${PRODUCTS[(i + Math.floor(i / ACCOUNTS.length)) % PRODUCTS.length]}`,\n account: [`a${acct + 1}`],\n stage: STAGES[s]!.value,\n owner: ['u1', 'u2', 'u4', 'u7'][i % 4]!,\n value: 8000 + ((i * 7919) % 60) * 1500,\n close: day(((i * 5) % 70) - 20),\n }\n })\n const accounts = ACCOUNTS.map(([name, industry, employees], i) => ({\n id: `a${i + 1}`,\n name,\n industry,\n employees,\n deals: deals.filter((d) => d.account[0] === `a${i + 1}`).map((d) => d.id),\n }))\n const ACTIVITIES: Array<[string, string, number, boolean]> = [\n ['Call Contoso about the security review', 'Call', 0, false],\n ['Send the Fabrikam proposal', 'Email', 1, false],\n ['Pricing call with Northwind', 'Meeting', 2, false],\n ['Demo for Litware clinical team', 'Meeting', 3, false],\n ['Follow up on the Proseware pilot', 'Email', 5, false],\n ['Renewal check-in with Adventure Works', 'Call', 6, false],\n ['Quarterly review with Tailspin', 'Meeting', 12, false],\n ['Thank-you note to Contoso', 'Email', -2, true],\n ['Kickoff call with Litware', 'Call', -5, true],\n ]\n const activities = ACTIVITIES.map(([subject, kind, due, done], i) => ({ id: `act${i + 1}`, subject, kind, owner: ['u1', 'u2', 'u4', 'u7'][i % 4]!, due: day(due), done }))\n\n // ---- The dashboard's filters -------------------------------------------------\n\n const OPEN: FieldFilter = { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'stage', kind: 'select', op: 'isNoneOf', value: ['Won', 'Lost'] }] }\n const WON: FieldFilter = { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'stage', kind: 'select', op: 'is', value: 'Won' }] }\n const DUE_THIS_WEEK: FieldFilter = {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'due', kind: 'date', op: 'isWithin', value: { span: 'nextWeek' } },\n { column: 'done', kind: 'checkbox', op: 'is', value: false },\n ],\n }\n\n // ---- The base ---------------------------------------------------------------\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'dash-deals',\n name: 'Deals',\n primaryField: 'deal',\n data: deals,\n columns: [\n { id: 'deal', field: 'deal', header: 'Deal', width: 260, fieldType: 'text' },\n { id: 'account', field: 'account', header: 'Account', width: 180, fieldType: 'link', fieldProps: { table: 'dash-accounts', multiple: false, inverse: 'deals' } },\n { id: 'stage', field: 'stage', header: 'Stage', width: 130, fieldType: 'singleSelect', fieldProps: { options: STAGES } },\n { id: 'owner', field: 'owner', header: 'Owner', width: 160, fieldType: 'user' },\n { id: 'value', field: 'value', header: 'Value', width: 130, fieldType: 'number', fieldProps: { format: 'currency', symbol: '$', precision: 0, summary: 'sum' } },\n { id: 'close', field: 'close', header: 'Close date', width: 150, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n ],\n views: [\n {\n id: 'overview',\n name: 'Sales overview',\n type: 'dashboard',\n dashboard: [\n { id: 'pipeline', kind: 'number', title: 'Open pipeline', aggregation: 'sum', field: 'value', filter: OPEN, caption: 'Quarter target $600,000' },\n { id: 'won', kind: 'number', title: 'Won', aggregation: 'sum', field: 'value', filter: WON },\n { id: 'avg', kind: 'number', title: 'Average open deal', aggregation: 'avg', field: 'value', filter: OPEN },\n { id: 'rate', kind: 'progress', title: 'Deals won', filter: WON },\n { id: 'by-stage', kind: 'chart', title: 'Pipeline by stage', chart: { kind: 'bar', x: 'stage', y: 'value' } },\n { id: 'due', kind: 'list', title: 'Activities due this week', table: 'dash-activities', filter: DUE_THIS_WEEK, sortBy: 'due', limit: 6 },\n { id: 'industry', kind: 'chart', title: 'Accounts by industry', table: 'dash-accounts', chart: { kind: 'donut', x: 'industry' } },\n { id: 'top', kind: 'list', title: 'Biggest open deals', filter: OPEN, sortBy: 'value', sortDesc: true, limit: 6 },\n ],\n },\n { id: 'deals', name: 'All deals', type: 'grid', color: { mode: 'field', field: 'stage' }, state: { sorting: [{ id: 'value', desc: true }] } },\n { id: 'pipeline', name: 'Pipeline', type: 'kanban', stackBy: 'stage' },\n ],\n props: { rowAdder: { label: 'Add deal', defaults: () => ({ stage: 'Lead' }) } },\n },\n {\n id: 'dash-accounts',\n name: 'Accounts',\n primaryField: 'name',\n data: accounts,\n columns: [\n { id: 'name', field: 'name', header: 'Account', width: 220, fieldType: 'text' },\n { id: 'industry', field: 'industry', header: 'Industry', width: 150, fieldType: 'singleSelect', fieldProps: { options: INDUSTRIES } },\n { id: 'deals', field: 'deals', header: 'Deals', width: 280, fieldType: 'link', fieldProps: { table: 'dash-deals', multiple: true, inverse: 'account' } },\n { id: 'pipeline', field: 'pipeline', header: 'Deal value', width: 150, fieldType: 'rollup', fieldProps: { linkField: 'deals', field: 'value', aggregation: 'SUM' } },\n { id: 'employees', field: 'employees', header: 'Employees', width: 120, fieldType: 'number', fieldProps: { format: 'integer' } },\n ],\n views: [{ id: 'accounts', name: 'All accounts', type: 'grid' }],\n props: { rowAdder: { label: 'Add account' } },\n },\n {\n id: 'dash-activities',\n name: 'Activities',\n primaryField: 'subject',\n data: activities,\n columns: [\n { id: 'subject', field: 'subject', header: 'Activity', width: 300, fieldType: 'text' },\n { id: 'kind', field: 'kind', header: 'Type', width: 120, fieldType: 'singleSelect', fieldProps: { options: KINDS } },\n { id: 'owner', field: 'owner', header: 'Owner', width: 160, fieldType: 'user' },\n { id: 'due', field: 'due', header: 'Due', width: 150, fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { id: 'done', field: 'done', header: 'Done', width: 90, fieldType: 'checkbox' },\n ],\n views: [{ id: 'activities', name: 'All activities', type: 'grid', state: { sorting: [{ id: 'due', desc: false }] } }],\n props: { rowAdder: { label: 'Add activity', defaults: () => ({ done: false }) } },\n },\n ])\n</script>\n\n<section class=\"base-demo\">\n <SvBase\n bind:tables\n editable\n sortable\n showRowNumbers\n expandRows\n rowNumberWidth={64}\n showRowSelection={false}\n rowHeight={40}\n containerHeight=\"100%\"\n columnAdder\n fieldMenu\n />\n</section>\n\n<style>\n .base-demo { display: flex; flex-direction: column; flex: 1; min-height: 560px; height: 100%; }\n</style>\n"
4297
+ },
4162
4298
  {
4163
4299
  "id": "73-chartjs-sync",
4164
4300
  "path": "examples/src/demos/73-chartjs-sync.svelte",
@@ -5012,7 +5148,7 @@ export const docs = [
5012
5148
  "path": "docs/help/base/ai-agents.md",
5013
5149
  "title": "Let an AI agent work in your base",
5014
5150
  "section": "SvGrid Base",
5015
- "markdown": "# Let an AI agent work in your base\n\nAn agent can do the first pass on a table your team works in: categorize the\nnew records, set a priority, draft a reply. The hard part is not the edit.\nIt is what comes after: seeing what the agent touched, what each field held\nbefore, and having a person make the final call.\n\nThis tutorial builds that on a support inbox. The tickets live in a Supabase\ntable; SvGrid Base shows them to your team; Claude Code, connected through\nthe Supabase MCP server, triages them. Every change the agent makes shows up\nin the base with its name on it, and people review it from a \"Needs review\"\nview.\n\n> Video: An AI agent and your team, one table: Claude Code, Supabase and SvGrid Base (https://www.youtube.com/watch?v=HNMV1rTaDzE)\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThe same thing in the page, with Postgres running in the browser and a\nstand-in agent (keyword rules, so it needs no model or key). Press \"Run the\ntriage agent\", then open a ticket:\n\n<div data-docs-demo=\"700-base-ai-triage\" data-height=\"900\"></div>\n\n## 1. Make the table\n\nRun this in the Supabase SQL editor. `updated_by` is the column the base reads\nto say who changed a row; the agent writes its own id there, and the base\nwrites the signed-in user's.\n\n```sql\ncreate table public.tickets (\n id text primary key,\n subject text not null default '',\n customer text,\n message text,\n received timestamptz default now(),\n category text,\n priority text default 'Normal',\n reply text,\n review text,\n updated_by text\n);\n\nalter table public.tickets enable row level security;\ncreate policy \"team reads tickets\" on public.tickets for select to authenticated using (true);\ncreate policy \"team updates tickets\" on public.tickets for update to authenticated using (true) with check (true);\n\n-- The base hears every change through Realtime.\nalter publication supabase_realtime add table public.tickets;\n```\n\nThe policies let users signed in through Supabase Auth read and update the\ntable, which is what your team does from the base. The agent does not go\nthrough them: the MCP server works with your project's own access.\n\n## 2. Show it as a base\n\nThe quickest start is `baseFromSupabase`, which reads the table and builds the\nfields. A text column named `updated_by`, `modified_by` or `last_modified_by`\nbecomes a **Last modified by** field, and `created_by` a **Created by** field:\n\n```ts\nimport { baseFromSupabase } from '@svgrid/enterprise/base'\nimport type { SupabaseClientLike, SupabaseRealtimeClientLike } from '@svgrid/enterprise'\n\n// Your supabase-js client: createClient(url, key).\ndeclare const supabase: SupabaseClientLike & SupabaseRealtimeClientLike\ndeclare const url: string\ndeclare const key: string\n\nconst tables = await baseFromSupabase({ client: supabase, url, key, tables: ['tickets'] })\n```\n\nFor the inbox you want selects with fixed options, a review view and an\nApprove button, so here the table is written out. The `source` is the same\nSupabase table, with Realtime:\n\n```ts\nimport { baseSource, type BaseTable } from '@svgrid/enterprise/base'\nimport {\n createSupabaseDataSource,\n createSupabaseRealtime,\n type EntitySchema,\n type SupabaseClientLike,\n type SupabaseRealtimeClientLike,\n} from '@svgrid/enterprise'\n\n// Your supabase-js client: createClient(url, key).\ndeclare const client: SupabaseClientLike & SupabaseRealtimeClientLike\n\nconst schema: EntitySchema = {\n name: 'tickets',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n ...['subject', 'customer', 'message', 'category', 'priority', 'reply', 'review', 'updated_by'].map((field) => ({ field, type: 'text' as const })),\n { field: 'received', type: 'datetime' },\n ],\n}\n\nconst options = (values: string[]) => values.map((value) => ({ value }))\n\nexport const tables: BaseTable[] = [\n {\n id: 'tickets',\n name: 'Tickets',\n primaryField: 'subject',\n data: [],\n columns: [\n { field: 'subject', header: 'Subject', fieldType: 'text' },\n { field: 'category', header: 'Category', fieldType: 'singleSelect', fieldProps: { options: options(['Billing', 'Bug', 'Account', 'Feature request']) } },\n { field: 'priority', header: 'Priority', fieldType: 'singleSelect', fieldProps: { options: options(['Urgent', 'High', 'Normal', 'Low']) } },\n { field: 'review', header: 'Review', fieldType: 'singleSelect', fieldProps: { options: options(['Needs review', 'Approved']) } },\n { field: 'updated_by', header: 'Last changed by', fieldType: 'lastModifiedBy' },\n { field: 'approve', header: 'Approve', fieldType: 'button', fieldProps: { label: 'Approve' } },\n { field: 'reply', header: 'Draft reply', fieldType: 'longText' },\n { field: 'customer', header: 'Customer', fieldType: 'email' },\n { field: 'message', header: 'Message', fieldType: 'longText' },\n { field: 'received', header: 'Received', fieldType: 'date', fieldProps: { dateFormat: 'friendly', time: true } },\n ],\n views: [\n { id: 'inbox', name: 'Inbox', type: 'grid', state: { sorting: [{ id: 'received', desc: true }] } },\n {\n id: 'review',\n name: 'Needs review',\n type: 'grid',\n state: { advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'review', kind: 'select', op: 'is', value: 'Needs review' }] } },\n },\n ],\n automations: [\n {\n id: 'approve',\n name: 'Approve the triage',\n enabled: true,\n trigger: { type: 'button', field: 'approve' },\n actions: [{ type: 'updateRecord', values: { review: 'Approved' } }],\n },\n ],\n source: baseSource(createSupabaseDataSource({ client, table: 'tickets', schema }), {\n realtime: (onChange) => createSupabaseRealtime({ client, table: 'tickets', onChange }),\n }),\n },\n]\n```\n\nThe page puts it on screen:\n\n```svelte\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n let { tables }: { tables: BaseTable[] } = $props()\n</script>\n\n<SvBase bind:tables editable showRowNumbers expandRows containerHeight={640} />\n<SvToaster />\n```\n\n## 3. Give the agent a name\n\nThe base names whoever is in `updated_by` from its people list. Add the agent\nto it, with an avatar, next to your team, and say who is signed in so your own\nedits are credited to you:\n\n```ts\nimport { setCurrentUser, setFieldUsers } from '@svgrid/enterprise/base'\n\nsetFieldUsers([\n { id: 'u1', name: 'Ana Ruiz', email: 'ana@example.com' },\n { id: 'u2', name: 'Ben Okafor', email: 'ben@example.com' },\n { id: 'agent', name: 'Triage agent', avatarUrl: '/agent.svg' },\n])\nsetCurrentUser({ id: 'u1', name: 'Ana Ruiz' })\n```\n\nAn id the list does not have shows as \"Someone\"; a change with no\n`updated_by` at all as \"Someone else\".\n\n## 4. Connect Claude Code to the database\n\nThe Supabase MCP server gives Claude Code an `execute_sql` tool on your\nproject. Create a personal access token under Account, Access tokens in the\nSupabase dashboard, keep it in your environment as `SUPABASE_ACCESS_TOKEN`,\nand scope the server to the one project:\n\n```json\n{\n \"mcpServers\": {\n \"supabase\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@supabase/mcp-server-supabase@0.14.0\", \"--project-ref=your-project-ref\"]\n }\n }\n}\n```\n\nThe token can act on your whole Supabase account. Keep it out of the\nrepository and revoke it when the agent no longer needs it.\n\n## 5. Give it the instruction\n\nSave the JSON above as `mcp.json` and run Claude Code with only the SQL tool\nallowed. The instruction goes in on standard input:\n\n```bash\necho \"Triage the new support tickets in public.tickets (review is null). Read them first. Then triage them one at a time: one execute_sql call per ticket, each a single UPDATE that sets category (Billing, Bug, Account or Feature request), priority (Urgent, High, Normal or Low), reply (a one-sentence draft reply to the customer), review = 'Needs review' and updated_by = 'agent'.\" \\\n | claude -p --mcp-config mcp.json --strict-mcp-config --allowedTools mcp__supabase__execute_sql\n```\n\nTwo parts of the instruction matter to the base. `updated_by = 'agent'` is\nwhat puts the agent's name on its changes. `review = 'Needs review'` is what\nputs each ticket in the review view. One UPDATE per ticket is optional; it\nmakes the changes arrive one by one instead of all at once.\n\n## 6. Watch the changes land\n\nEach UPDATE reaches the base through Realtime. Until someone opens the\nrecord:\n\n- the cells the agent changed are tinted;\n- the row number has a dot; hover it for \"Triage agent changed this record\n just now\";\n- the view bar counts the records, \"10 changed by Triage agent\"; a click on\n the count marks them all seen.\n\nOpen a ticket and its activity lists each change, the value before crossed\nout and the value now: \"Triage agent changed Priority: Normal → High\".\nOpening it clears its marks. The marks and the activity live in the page:\nafter a reload the base shows the records as they are, without them.\n\n## 7. Review and approve\n\nSwitch to **Needs review**. Where you disagree, change the field: your edit is\nwritten to the same table with `updated_by` set to you, and the record's\nactivity shows it under your name, after the agent's. Press **Approve** on\nthe rest: the automation sets Review to Approved and the ticket leaves the\nview.\n\n## Next\n\n- [Review what an agent changed](./review-queue.md): the same review on any\n database, a toast for each batch of changes, and an agent of your own.\n- [Keep a base in a database](./data.md#changes-made-elsewhere): how changes\n made elsewhere are read and marked.\n- [Automations](./automations.md): more than one button.\n"
5151
+ "markdown": "# Let an AI agent work in your base\n\nAn agent can do the first pass on a table your team works in: categorize the\nnew records, set a priority, draft a reply. The hard part is not the edit.\nIt is what comes after: seeing what the agent touched, what each field held\nbefore, and having a person make the final call.\n\nThis tutorial builds that on a support inbox. The tickets live in a Supabase\ntable; SvGrid Base shows them to your team; Claude Code, connected through\nthe Supabase MCP server, triages them. Every change the agent makes shows up\nin the base with its name on it, and people review it from a \"Needs review\"\nview.\n\n> Video: An AI agent and your team, one table: Claude Code, Supabase and SvGrid Base (https://www.youtube.com/watch?v=HNMV1rTaDzE)\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThe same thing in the page, with Postgres running in the browser and a\nstand-in agent (keyword rules, so it needs no model or key). Press \"Run the\ntriage agent\", then open a ticket:\n\n<div data-docs-demo=\"700-base-ai-triage\" data-height=\"900\"></div>\n\n## 1. Make the table\n\nRun this in the Supabase SQL editor. `updated_by` is the column the base reads\nto say who changed a row; the agent writes its own id there, and the base\nwrites the signed-in user's.\n\n```sql\ncreate table public.tickets (\n id text primary key,\n subject text not null default '',\n customer text,\n message text,\n received timestamptz default now(),\n category text,\n priority text default 'Normal',\n reply text,\n review text,\n updated_by text\n);\n\nalter table public.tickets enable row level security;\ncreate policy \"team reads tickets\" on public.tickets for select to authenticated using (true);\ncreate policy \"team updates tickets\" on public.tickets for update to authenticated using (true) with check (true);\n\n-- The base hears every change through Realtime.\nalter publication supabase_realtime add table public.tickets;\n```\n\nThe policies let users signed in through Supabase Auth read and update the\ntable, which is what your team does from the base. The agent does not go\nthrough them: the MCP server works with your project's own access.\n\n## 2. Show it as a base\n\nThe quickest start is `baseFromSupabase`, which reads the table and builds the\nfields. A text column named `updated_by`, `modified_by` or `last_modified_by`\nbecomes a **Last modified by** field, and `created_by` a **Created by** field:\n\n```ts\nimport { baseFromSupabase } from '@svgrid/enterprise/base'\nimport type { SupabaseClientLike, SupabaseRealtimeClientLike } from '@svgrid/enterprise'\n\n// Your supabase-js client: createClient(url, key).\ndeclare const supabase: SupabaseClientLike & SupabaseRealtimeClientLike\ndeclare const url: string\ndeclare const key: string\n\nconst tables = await baseFromSupabase({ client: supabase, url, key, tables: ['tickets'] })\n```\n\nFor the inbox you want selects with fixed options, a review view and an\nApprove button, so here the table is written out. The `source` is the same\nSupabase table, with Realtime:\n\n```ts\nimport { baseSource, type BaseTable } from '@svgrid/enterprise/base'\nimport {\n createSupabaseDataSource,\n createSupabaseRealtime,\n type EntitySchema,\n type SupabaseClientLike,\n type SupabaseRealtimeClientLike,\n} from '@svgrid/enterprise'\n\n// Your supabase-js client: createClient(url, key).\ndeclare const client: SupabaseClientLike & SupabaseRealtimeClientLike\n\nconst schema: EntitySchema = {\n name: 'tickets',\n idField: 'id',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n ...['subject', 'customer', 'message', 'category', 'priority', 'reply', 'review', 'updated_by'].map((field) => ({ field, type: 'text' as const })),\n { field: 'received', type: 'datetime' },\n ],\n}\n\nconst options = (values: string[]) => values.map((value) => ({ value }))\n\nexport const tables: BaseTable[] = [\n {\n id: 'tickets',\n name: 'Tickets',\n primaryField: 'subject',\n data: [],\n columns: [\n { field: 'subject', header: 'Subject', fieldType: 'text' },\n { field: 'category', header: 'Category', fieldType: 'singleSelect', fieldProps: { options: options(['Billing', 'Bug', 'Account', 'Feature request']) } },\n { field: 'priority', header: 'Priority', fieldType: 'singleSelect', fieldProps: { options: options(['Urgent', 'High', 'Normal', 'Low']) } },\n { field: 'review', header: 'Review', fieldType: 'singleSelect', fieldProps: { options: options(['Needs review', 'Approved']) } },\n { field: 'updated_by', header: 'Last changed by', fieldType: 'lastModifiedBy' },\n { field: 'approve', header: 'Approve', fieldType: 'button', fieldProps: { label: 'Approve' } },\n { field: 'reply', header: 'Draft reply', fieldType: 'longText' },\n { field: 'customer', header: 'Customer', fieldType: 'email' },\n { field: 'message', header: 'Message', fieldType: 'longText' },\n { field: 'received', header: 'Received', fieldType: 'date', fieldProps: { dateFormat: 'friendly', time: true } },\n ],\n views: [\n { id: 'inbox', name: 'Inbox', type: 'grid', state: { sorting: [{ id: 'received', desc: true }] } },\n {\n id: 'review',\n name: 'Needs review',\n type: 'grid',\n state: { advancedFilter: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'review', kind: 'select', op: 'is', value: 'Needs review' }] } },\n },\n ],\n automations: [\n {\n id: 'approve',\n name: 'Approve the triage',\n enabled: true,\n trigger: { type: 'button', field: 'approve' },\n actions: [{ type: 'updateRecord', values: { review: 'Approved' } }],\n },\n ],\n source: baseSource(createSupabaseDataSource({ client, table: 'tickets', schema }), {\n realtime: (onChange) => createSupabaseRealtime({ client, table: 'tickets', onChange }),\n }),\n },\n]\n```\n\nThe page puts it on screen:\n\n```svelte\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n let { tables }: { tables: BaseTable[] } = $props()\n</script>\n\n<SvBase bind:tables editable showRowNumbers expandRows containerHeight={640} />\n<SvToaster />\n```\n\n## 3. Give the agent a name\n\nThe base names whoever is in `updated_by` from its people list. Add the agent\nto it, with an avatar, next to your team, and say who is signed in so your own\nedits are credited to you:\n\n```ts\nimport { setCurrentUser, setFieldUsers } from '@svgrid/enterprise/base'\n\nsetFieldUsers([\n { id: 'u1', name: 'Ana Ruiz', email: 'ana@example.com' },\n { id: 'u2', name: 'Ben Okafor', email: 'ben@example.com' },\n { id: 'agent', name: 'Triage agent', avatarUrl: '/agent.svg' },\n])\nsetCurrentUser({ id: 'u1', name: 'Ana Ruiz' })\n```\n\nAn id the list does not have shows as \"Someone\"; a change with no\n`updated_by` at all as \"Someone else\".\n\n## 4. Connect Claude Code to the database\n\nThe Supabase MCP server gives Claude Code an `execute_sql` tool on your\nproject. Create a personal access token under Account, Access tokens in the\nSupabase dashboard, keep it in your environment as `SUPABASE_ACCESS_TOKEN`,\nand scope the server to the one project:\n\n```json\n{\n \"mcpServers\": {\n \"supabase\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@supabase/mcp-server-supabase@0.14.0\", \"--project-ref=your-project-ref\"]\n }\n }\n}\n```\n\nThe token can act on your whole Supabase account. Keep it out of the\nrepository and revoke it when the agent no longer needs it.\n\n## 5. Give it the instruction\n\nSave the JSON above as `mcp.json` and run Claude Code with only the SQL tool\nallowed. The instruction goes in on standard input:\n\n```bash\necho \"Triage the new support tickets in public.tickets (review is null). Read them first. Then triage them one at a time: one execute_sql call per ticket, each a single UPDATE that sets category (Billing, Bug, Account or Feature request), priority (Urgent, High, Normal or Low), reply (a one-sentence draft reply to the customer), review = 'Needs review' and updated_by = 'agent'.\" \\\n | claude -p --mcp-config mcp.json --strict-mcp-config --allowedTools mcp__supabase__execute_sql\n```\n\nTwo parts of the instruction matter to the base. `updated_by = 'agent'` is\nwhat puts the agent's name on its changes. `review = 'Needs review'` is what\nputs each ticket in the review view. One UPDATE per ticket is optional; it\nmakes the changes arrive one by one instead of all at once.\n\n## 6. Watch the changes land\n\nEach UPDATE reaches the base through Realtime. Until someone opens the\nrecord:\n\n- the cells the agent changed are tinted;\n- the row number has a dot; hover it for \"Triage agent changed this record\n just now\";\n- the view bar counts the records, \"10 changed by Triage agent\"; a click on\n the count marks them all seen.\n\nOpen a ticket and its activity lists each change, the value before crossed\nout and the value now: \"Triage agent changed Priority: Normal → High\".\nOpening it clears its marks. The marks and the activity live in the page:\nafter a reload the base shows the records as they are, without them.\n\n## 7. Review and approve\n\nSwitch to **Needs review**. Where you disagree, change the field: your edit is\nwritten to the same table with `updated_by` set to you, and the record's\nactivity shows it under your name, after the agent's. Press **Approve** on\nthe rest: the automation sets Review to Approved and the ticket leaves the\nview.\n\n## AI fields\n\nThe agent above works from outside the base. An AI field works from inside\nit: a field whose value a model writes for each record, from a prompt that\nnames the record's other fields.\n\n<div data-docs-demo=\"716-base-ai-field\" data-height=\"620\"></div>\n\nThe answer is stored in the record, like a typed value. It sorts, filters,\nexports and shows in footers without calling the model again, and anyone\nallowed to edit the field can change it by hand.\n\n```ts\nimport { setAIProvider } from '@svgrid/grid'\nimport type { BaseTable } from '@svgrid/enterprise/base'\n\n// Once, at startup: a function from the request to the model's text.\n// The key stays on your server; /api/ai calls the model with it.\nsetAIProvider(async ({ prompt, maxOutputTokens, signal }) => {\n const res = await fetch('/api/ai', { method: 'POST', body: JSON.stringify({ prompt, maxOutputTokens }), signal })\n return (await res.json()).text\n})\n\nexport const products: BaseTable = {\n id: 'products',\n name: 'Products',\n primaryField: 'name',\n data: [{ id: 'p1', name: 'Ridge 40 pack', audience: 'Hikers', feature: 'A frame that carries 15 kg' }],\n columns: [\n { field: 'name', header: 'Name', fieldType: 'text' },\n { field: 'audience', header: 'Audience', fieldType: 'singleSelect', fieldProps: { options: [{ value: 'Hikers' }, { value: 'Climbers' }] } },\n { field: 'feature', header: 'Key feature', fieldType: 'text' },\n {\n field: 'pitch',\n header: 'Pitch',\n fieldType: 'ai',\n fieldProps: { prompt: 'Write a one-line pitch for {Name}, aimed at {Audience}, that mentions {Key feature}.' },\n },\n ],\n}\n```\n\n`setAIProvider`, `getAIProvider` and `mockAIProvider` are the free AI helpers\nof `@svgrid/grid`; the field uses whatever provider the app registered. The\nprovider gets the prompt with each `{Field name}` replaced by the value as\nits cell shows it (a select's label, a person's name, a formatted date), and\nan instruction to answer with JSON, `{\"value\": ...}`.\n\n| `fieldProps` | Default | What it does |\n| --- | --- | --- |\n| `prompt` | `''` | The instruction, with `{Field name}` (a header or a field key) for the record's values. The field editor shows an unknown name or the field's own name as an error, as it does for a formula, and will not save it. Renaming a field renames it in the prompt. |\n| `output` | `'text'` | `'text'` stores text (edited as long text). `'singleSelect'` asks the model to pick one of `options` and refuses any other answer. `'number'` stores a number, shown with `precision` decimal places. |\n| `auto` | `true` | Generate again when a field the prompt names is edited in that record, in the page where the edit is made (see [Changes from the database](#changes-from-the-database)). Off, the value changes only when someone asks. A record whose named fields are all empty is skipped. |\n| `options` | `[]` | The options of a `'singleSelect'` output, as a select field's. |\n\nHow it behaves:\n\n- Each cell has a button that generates that record. With `fieldMenu`, the\n column menu has **Generate for N empty records** and\n **Generate for all N records**, and **Stop generating** while some wait.\n- Requests run three at a time over the page; `setAIFieldConcurrency(n)`\n changes that. A waiting or running cell shows a spinner. A failed one\n shows the error message (the model's error, or an answer that is not one\n of the options) until it is generated again or edited.\n- Values are written through the grid's edit path, as a typed edit is:\n Ctrl+Z undoes one, `onCellValueChange` hears it, last modified fields are\n stamped and another AI field whose prompt names this one follows. The\n active cell and the selection stay where the person left them, and a\n value that arrives while someone is editing a cell waits for that edit to\n end.\n- A protected field is generated only for the people allowed to edit it;\n for others the button is not shown and a call from code fails with a\n message, before any request is made.\n- Without a provider, an empty cell says \"No AI provider\" and the button's\n title says to call `setAIProvider()`.\n- A grid taken off the page (the component unmounted) drops its waiting\n requests and aborts the running ones through the request's `signal`.\n\nFrom code:\n\n```ts\nimport { cancelAIField, generateAIField } from '@svgrid/enterprise/base'\n\ndeclare const api: unknown // from <SvBase onApiReady>\n\n// 'empty' (the default), 'all', or a list of record ids.\nconst { written, failed } = await generateAIField(api, 'pitch', 'all')\ncancelAIField(api, 'pitch')\n```\n\n### Changes from the database\n\nAn `auto` generation starts in the page where the edit was made. On a table\nwith a `source`, that page writes the new value to the database like any\nother edit, and every other page with the base open receives it through\n`realtime` as a change of its own. Those pages never call the model for it:\nwith ten people looking at a table, one edit costs one request.\n\nA change made outside any `<SvBase>` (a server job, a script, a database\nconsole, an agent) has no page that generated it, so its records keep their\nold value. To generate them, call `regenerateAIFields` from `onRemoteChange`\nin one page:\n\n```ts\nimport { regenerateAIFields, type BaseRemoteChange } from '@svgrid/enterprise/base'\n\ndeclare const api: unknown // from <SvBase onApiReady>\n\n// <SvBase {tables} {onApiReady} onRemoteChange={generateForImports} />\nfunction generateForImports(changes: BaseRemoteChange[]) {\n // Rows the nightly import wrote. Edits from other pages were generated there.\n void regenerateAIFields(api, changes.filter((c) => c.record.updated_by === 'import'))\n}\n```\n\nIt applies the rule an edit in the grid follows: for an update, each `auto`\nfield whose prompt names a field that moved, unless the change wrote that\nAI field itself; for an insert, the record's empty AI fields. Deletes,\nfields with `auto` off and records of a table the grid does not show are\nskipped. The values are written through the grid, so they reach the\ndatabase and the other pages, and the page does not hear its own write.\n\nCall it in one page only, or for changes a filter picks out (an author, a\nservice account). If every open page calls it for every change, each one\nasks the model and writes, and the last answer wins. The other choice is to\ngenerate on the server: your job calls the model and writes the value with\nthe record.\n\n## Next\n\n- [Review what an agent changed](./review-queue.md): the same review on any\n database, a toast for each batch of changes, and an agent of your own.\n- [Keep a base in a database](./data.md#changes-made-elsewhere): how changes\n made elsewhere are read and marked.\n- [Automations](./automations.md): more than one button.\n"
5016
5152
  },
5017
5153
  {
5018
5154
  "slug": "help/base/automations",
@@ -5026,7 +5162,7 @@ export const docs = [
5026
5162
  "path": "docs/help/base/collaboration.md",
5027
5163
  "title": "People, comments and files",
5028
5164
  "section": "SvGrid Base",
5029
- "markdown": "# People, comments and files\n\nA tracker one person fills in needs a status column and little else. Once a\nteam uses it, people want to see who a task is assigned to, who changed the\nstatus and when, a thread of comments on the task, and the mockups attached\nto it, kept somewhere that survives a reload. This page adds those to the\ntask tracker from [Build a project tracker](./start.md).\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nIn the demo, double-click a candidate's card on the pipeline (or switch to\n\"All candidates\" and press Space on a row), change the Stage, leave a\ncomment, and watch the Activity column on the right of the record.\n\nThe base cannot know who your users are or where your files and comments\nlive. You tell it with four calls in the browser; the change log needs\nnothing:\n\n![Your users table goes to setFieldUsers and the session to setCurrentUser, which feed user cells, created by, last modified by and comment authors; setRecordComments connects the record view's Activity to your comments endpoint; setAttachmentUploader sends files to your storage through a presigned URL; the activity log is kept in the page](/docs-media/base-collaboration.svg)\n\nEach step below works on its own.\n\n## 1. List the people\n\nUser fields pick from one list of people that you hand to the base. A person\nis a `FieldUser`:\n\n```ts\nimport { setFieldUsers, type FieldUser } from '@svgrid/enterprise/base'\n\nconst team: FieldUser[] = [\n { id: 'u1', name: 'Ana Ruiz', email: 'ana@example.com', avatarUrl: 'https://cdn.example.com/ana.jpg' },\n { id: 'u2', name: 'Ben Okafor', email: 'ben@example.com' },\n { id: 'u3', name: 'Cleo Park', email: 'cleo@example.com' },\n]\n\n// In the browser only; step 2 shows where in SvelteKit.\nsetFieldUsers(team)\n```\n\nGive the tasks a `user` field for the owner and one with `multiple` for\nreviewers. The cell stores ids, never names, so renaming a person renames\nthem everywhere:\n\n```ts\nconst columns = [\n { field: 'task', header: 'Task', fieldType: 'text' },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'assignee', header: 'Assignee', fieldType: 'user' },\n { field: 'reviewers', header: 'Reviewers', fieldType: 'user', fieldProps: { multiple: true } },\n]\n\nconst data = [\n { id: 't1', task: 'Write the brief', status: 'Todo', assignee: 'u1', reviewers: ['u2', 'u3'] },\n { id: 't2', task: 'Pick the fonts', status: 'In progress', assignee: 'u2', reviewers: [] },\n]\n```\n\nA cell draws an avatar and the name. With several people it overlaps up to\nfour avatars and writes the first name with a count: \"Ben Okafor +1\".\n`avatarUrl` is used when it is an `http(s):`, `blob:` or `data:image` URL;\nanything else, or no URL, draws the initials on a color worked out from the\nname, so a person keeps the same color on every page. An id that is not in\nthe list shows as the id itself.\n\nEditing a user cell opens a panel with a \"Find a person\" box and the people\nfrom the list, each with their avatar; typing filters them. If the list is\nempty the panel says \"No people (setFieldUsers)\". Text pasted or filled into\na user cell is matched against each person's id, name and email, ignoring\ncase; a multiple field takes them comma-separated and drops repeats. A name\nthat matches nobody stays as typed, so check pasted data. Copying a user cell\nwrites the names, so a copy and paste between records keeps the people.\n`fieldProps.default` takes an id for new rows. The field reference has the\n[user field's properties](../fields.md#declare-columns-by-type).\n\nA Kanban view can stack by a single user field (`stackBy: 'assignee'`): one\nlane per person in the list, plus \"Uncategorized\" while some task has nobody.\nDragging a card to a lane reassigns the task through the grid's edit path,\nso it counts as an edit.\n\n## 2. Say who is signed in\n\n`setCurrentUser` names the person using the page. Several things read it:\n\n- `createdBy` fills new rows with their id, and `lastModifiedBy` writes it\n on every edit it watches.\n- Each comment is saved with their id as `by`.\n- Each change in a record's activity is noted with their id.\n- A filter condition with the value `'@me'` (`ME`) matches them.\n- Your own code can read it with `getCurrentUser()`.\n\nIn SvelteKit the session is on the server, so load the person and the team\nin a layout and hand both to the base in the browser:\n\n```ts\n// src/routes/(app)/+layout.server.ts\nimport { redirect } from '@sveltejs/kit'\nimport type { LayoutServerLoad } from './$types'\nimport { db } from '$lib/server/db'\n\nexport const load: LayoutServerLoad = async ({ locals }) => {\n if (!locals.user) redirect(303, '/login')\n const team = await db.query(\n 'select id, name, email, avatar_url as \"avatarUrl\" from users where team_id = $1 order by name',\n [locals.user.teamId],\n )\n return { me: { id: locals.user.id, name: locals.user.name }, team: team.rows }\n}\n```\n\n```svelte\n<!-- src/routes/(app)/+layout.svelte -->\n<script lang=\"ts\">\n import type { Snippet } from 'svelte'\n import { setCurrentUser, setFieldUsers, type FieldUser } from '@svgrid/enterprise/base'\n\n let { data, children }: { data: { me: FieldUser; team: FieldUser[] }; children: Snippet } = $props()\n\n // Again when the data changes: a sign-in as someone else.\n $effect.pre(() => {\n setFieldUsers(data.team)\n setCurrentUser(data.me)\n })\n</script>\n\n{@render children()}\n```\n\nThe four setters on this page write state shared by the whole module, so\ncall them in the browser only: an `$effect` as here (it does not run during\nserver rendering), `onMount`, or behind `browser` from `$app/environment`.\nCalled at the top of a component's `<script>`, they would also run on the\nserver and hand one request's team and user to the next. Cells and pickers\nread both values reactively, so the base can draw before they arrive. The signed-in person does not have to be in the team list for\ntheir name to show, but they only appear in the picker if they are.\n\nNow add who made each task and when, and give a new task to whoever adds it:\n\n```ts\nimport { getCurrentUser, type BaseTable } from '@svgrid/enterprise/base'\n\nconst tasks: BaseTable = {\n id: 'tasks',\n name: 'Tasks',\n primaryField: 'task',\n data,\n columns: [\n ...columns,\n { field: 'createdBy', header: 'Created by', fieldType: 'createdBy' },\n { field: 'createdAt', header: 'Created', fieldType: 'createdTime', fieldProps: { dateFormat: 'friendly' } },\n ],\n props: {\n rowAdder: { label: 'Add task', defaults: () => ({ status: 'Todo', assignee: getCurrentUser()?.id ?? null }) },\n },\n}\n```\n\nBoth fields are read-only. Every record the base makes gets the current user\nand the time: \"+ Add row\", a form, the record menu, \"+ Add a card\" on a\nKanban, a calendar day. Last modified fields start out the same way. Rows\nyou load keep whatever your database sends.\n\nOn sign-out, call `closeRecord()`, then `setCurrentUser(null)` and\n`setFieldUsers([])`.\n\n## 3. Add a \"My tasks\" view\n\nA filter condition on a user field compares it with a person's id. The value\n`'@me'` (exported as `ME`) stands for whoever is signed in when the filter\nruns, so one view works for everyone:\n\n```ts\nimport { ME, type FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n {\n id: 'mine',\n name: 'My tasks',\n type: 'grid',\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'or',\n conditions: [\n { column: 'assignee', kind: 'select', op: 'is', value: ME },\n { column: 'reviewers', kind: 'multi', op: 'hasAnyOf', value: [ME] },\n ],\n },\n },\n },\n { id: 'all', name: 'All tasks', type: 'grid' },\n]\n```\n\nIn the Filter panel the person picker lists \"Me\" first, so users can build\nthe same view themselves. The condition reads \"Assignee is me\".\n\nA single user field filters with the select operators (`is`, `isNot`,\n`isAnyOf`, `isNoneOf`), a multiple one with `hasAnyOf`, `hasAllOf`,\n`isExactly` and `hasNoneOf`; both also have `isEmpty` and `isNotEmpty`.\nCreated by and last modified by filter the same way, so \"Created by is me\"\nworks too. The [filter conditions](../fields.md#filter-conditions) table\nlists them all.\n\nThe view stores `'@me'`, not an id, so it can be saved with the other views\n(`onViewsChange`, or the `views` inside `onTablesChange`) and Ben sees his own\ntasks when he opens it.\n\n## 4. Open a record\n\n`expandRows` with `showRowNumbers` turns the row number into a checkbox and an\nexpand button:\n\n```svelte\n<SvBase bind:tables editable showRowNumbers expandRows onTablesChange={save} />\n```\n\nA record opens from the expand button, from Space on a selected cell (not a\ncheckbox cell, and only with `expandRows`), from \"Expand record\" in the\nright-click menu, from a gallery card, from a double click (or F2) on a\nKanban card, from a calendar event and from a Gantt task.\n\n![A candidate open as a record: each field with its type icon on the left, and the Activity column on the right with \"Ana Ruiz changed Stage\" to Offer, her comment below it and the comment box](/docs-media/base-collaboration.png)\n\nThe record shows:\n\n- The primary field as the title.\n- Every field with its type icon and name, drawn as its cell draws it. A click\n opens the cell's own editor; the value is written through the grid's edit\n path, so undo, validation, `onCellValueChange` and last-modified fields work\n the same as in the cell. Read-only fields say \"read-only\".\n- Fields hidden in the view, folded under \"Show N hidden fields\" and marked\n \"hidden in the grid\". They are read-only here.\n- Activity on the right: changes and comments, oldest first, with \"just now\",\n \"5 minutes ago\", \"3 hours ago\" or the date. The box under them takes a\n comment; Ctrl+Enter (Cmd+Enter) or Comment sends it. A base without\n `editable` still takes comments.\n- Previous and next buttons that step through the rows in the view's order,\n and \"3 of 12\".\n\nA record with comments shows how many by its row number (the pointer over the\nrow swaps the count for the checkbox and expand button) and as a badge on its\nKanban card. The card's badge opens the record with the comment box focused,\nas does \"Comment\" in the right-click menu of a row or a card.\n\nOn a narrow screen the activity moves under the fields. If an edit makes the\nrecord leave the view's filter, the record says \"This row is not in the\ngrid's view any more.\" and the footer \"Not in view (12 records)\". Previous\nand next still work: they move to the records that were before and after it.\n\nApp code opens a record with the grid api that `onApiReady` hands it:\n\n```ts\nimport { openRecord, closeRecord } from '@svgrid/enterprise/base'\n\nlet api: unknown\n// <SvBase ... onApiReady={(a) => (api = a)} />\n\nopenRecord({ api, rowId: 't1' })\nopenRecord({ api, rowId: 't1', focus: 'comment' }) // with the comment box focused\ncloseRecord(api)\n```\n\n`closeRecord()` closes whatever record is open, from anywhere: call it on\nsign-out or when the route changes. `closeRecord(api)` closes it only when it\nis open on that grid. A custom field type's `cell` component gets the grid\nas `ctrl` (with `row.id`), and `openRecord({ ctrl, rowId })` takes that too.\nA button field's `fieldProps.onClick` receives `{ row, rowId, columnId, api }`,\nso a button can open its own record.\n\n## 5. Keep comments in your backend\n\nWithout a store, comments live in memory and are gone on reload. A comment is\na `RecordComment`, and a store is two functions:\n\n```ts {nocheck}\nexport type RecordComment = { id: string; rowId: string; tableId?: string; text: string; at: number; by?: string }\n\nexport type RecordCommentContext = { tableId?: string; api: unknown }\n\nexport type RecordCommentStore = {\n list: (rowId: string, api: unknown, context: RecordCommentContext) => ReadonlyArray<RecordComment>\n add: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void\n}\n```\n\n`rowId` is the record's id (its `id`, or the table's `getRowId`). In\n`<SvBase tables>`, `context.tableId` (and the comment's `tableId`) names the\ntable, so Tasks `1` and Milestones `1` are two records; with one table it is\nundefined. `at` is milliseconds since 1970, `by` the id of the person who was\nsigned in. The record view makes `id`, `at` and `by` itself and calls `add`.\nA store written for `list(rowId, api)` and `add(rowId, comment, api)` still\nworks.\n\nBoth functions are synchronous, and `list` runs often: for the open record,\nand for every row the grid draws (with `expandRows`) and every Kanban card,\nto show the comment count. So fetch a whole table's comments once into reactive state and answer\nfrom it. Because `list` runs inside the base's reactive code, the counts and\nthe record draw again when the fetch lands:\n\n```ts\n// src/lib/comments.svelte.ts\nimport { browser } from '$app/environment'\nimport { toast } from '@svgrid/grid'\nimport { setRecordComments, type RecordComment, type RecordCommentStore } from '@svgrid/enterprise/base'\n\ntype ByRecord = Record<string, ReadonlyArray<RecordComment>>\n\n// Each table's comments by record id, fetched once per table.\nlet byTable = $state.raw<Record<string, ByRecord>>({})\nconst asked = new Set<string>()\n\nfunction put(table: string, rowId: string, list: ReadonlyArray<RecordComment>) {\n byTable = { ...byTable, [table]: { ...byTable[table], [rowId]: list } }\n}\n\nasync function load(table: string) {\n asked.add(table)\n const res = await fetch(`/api/comments?table=${encodeURIComponent(table)}`)\n if (!res.ok) return void asked.delete(table)\n const grouped: Record<string, RecordComment[]> = {}\n for (const c of (await res.json()) as RecordComment[]) (grouped[c.rowId] ??= []).push(c)\n byTable = { ...byTable, [table]: grouped }\n}\n\nconst store: RecordCommentStore = {\n list(rowId, _api, { tableId = '' }) {\n if (!asked.has(tableId)) void load(tableId)\n return byTable[tableId]?.[rowId] ?? []\n },\n add(rowId, comment, _api, { tableId = '' }) {\n const mine = () => byTable[tableId]?.[rowId] ?? []\n // Shown at once; the server's copy replaces it, or it goes away again.\n put(tableId, rowId, [...mine(), comment])\n fetch('/api/comments', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ id: comment.id, tableId, rowId, text: comment.text }),\n })\n .then(async (res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n const saved = (await res.json()) as RecordComment\n put(tableId, rowId, mine().map((c) => (c.id === comment.id ? saved : c)))\n })\n .catch(() => {\n put(tableId, rowId, mine().filter((c) => c.id !== comment.id))\n toast.error('Your comment was not saved')\n })\n },\n}\n\n// On the server this cache would be shared by every request.\nif (browser) setRecordComments(store)\n```\n\nImport the file once, in the page that shows the base. The failure notice\nneeds one `<SvToaster />` from `@svgrid/grid` in the app.\n`setRecordComments(null)` goes back to memory. For a table with a very large\ndiscussion, have the endpoint return counts per record and fetch a record's\ncomments when it opens.\n\nThe endpoint takes the author and the time from the server, never from the\nrequest body:\n\n```ts\n// src/routes/api/comments/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport type { RequestHandler } from './$types'\nimport { db } from '$lib/server/db'\n\nexport const GET: RequestHandler = async ({ url, locals }) => {\n if (!locals.user) error(401, 'Sign in first')\n const tableId = url.searchParams.get('table') ?? ''\n // `at` is a bigint column; the cast hands it back as a number, not a string.\n const { rows } = await db.query(\n 'select id, table_id as \"tableId\", row_id as \"rowId\", text, at::float8 as at, author as \"by\" from comments where team_id = $1 and table_id = $2 order by at',\n [locals.user.teamId, tableId],\n )\n return json(rows)\n}\n\nexport const POST: RequestHandler = async ({ request, locals }) => {\n if (!locals.user) error(401, 'Sign in first')\n const body = (await request.json()) as { id?: unknown; tableId?: unknown; rowId?: unknown; text?: unknown }\n const text = String(body.text ?? '').trim().slice(0, 4000)\n if (typeof body.id !== 'string' || typeof body.rowId !== 'string' || !text) error(400, 'Bad comment')\n const tableId = typeof body.tableId === 'string' ? body.tableId : ''\n const comment = { id: body.id, tableId, rowId: body.rowId, text, at: Date.now(), by: locals.user.id }\n await db.query(\n 'insert into comments (id, team_id, table_id, row_id, text, at, author) values ($1, $2, $3, $4, $5, $6, $7)',\n [comment.id, locals.user.teamId, comment.tableId, comment.rowId, comment.text, comment.at, comment.by],\n )\n return json(comment, { status: 201 })\n}\n```\n\nThe activity names the author from the people list: a `by` that is not in\n`setFieldUsers` (and is not the current user) shows as \"Someone\", and a\ncomment with no `by` shows as \"You\". Keep people who left the team in the\nlist, or return their name from your own data.\n\nComments other people add show once the cache changes. To see them while the\nbase is open, call `put` from your realtime channel or a poll.\n\n## 6. Upload files\n\nAn attachment cell holds an array of `Attachment`: `id`, `url`, `name`,\n`type` (the MIME type), and optional `size`, `width`, `height` and\n`thumbnailUrl` (a smaller image the cell uses instead of `url`). The\n[attachments section](../fields.md#attachments) of the field reference has\nan example value.\n\nWithout an uploader, added files stay in the page as `blob:` URLs and are\ngone on reload. `setAttachmentUploader` sets the function every attachment\ncolumn uses. It gets the `File` and an `AttachmentUploadContext`: `row` (the\nrecord), `columnId`, a `signal` that aborts when the user removes the file\nor closes the dialog, and `onProgress(fraction)` with a value from 0 to 1.\nIt returns the attachment.\n\nThis one asks your server for a presigned URL and sends the bytes straight\nto object storage. It uses `XMLHttpRequest` because `fetch` reports no upload\nprogress:\n\n```ts\n// src/lib/uploads.ts\nimport { browser } from '$app/environment'\nimport { setAttachmentUploader, type AttachmentUploader } from '@svgrid/enterprise/base'\n\nconst upload: AttachmentUploader = async (file, { columnId, signal, onProgress }) => {\n const res = await fetch('/api/uploads', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ name: file.name, type: file.type, size: file.size, columnId }),\n signal,\n })\n if (!res.ok) throw new Error(res.status === 413 ? 'File is too large' : `Upload refused (${res.status})`)\n const { id, uploadUrl, fileUrl } = (await res.json()) as { id: string; uploadUrl: string; fileUrl: string }\n\n await new Promise<void>((resolve, reject) => {\n const xhr = new XMLHttpRequest()\n xhr.open('PUT', uploadUrl)\n xhr.setRequestHeader('content-type', file.type || 'application/octet-stream')\n xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total)\n xhr.onload = () => (xhr.status < 300 ? resolve() : reject(new Error(`Storage said ${xhr.status}`)))\n xhr.onerror = () => reject(new Error('Network error'))\n xhr.onabort = () => reject(new Error('Cancelled'))\n signal.addEventListener('abort', () => xhr.abort(), { once: true })\n xhr.send(file)\n })\n\n return { id, url: fileUrl, name: file.name, type: file.type, size: file.size }\n}\n\nif (browser) setAttachmentUploader(upload)\n```\n\nThe message of the error you throw is what the user reads on the failed tile,\nnext to Retry and Remove, so write it for them.\n\nThe server checks the user and the size, signs a URL for one key, and keeps\na row per file:\n\n```ts\n// src/routes/api/uploads/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport type { RequestHandler } from './$types'\nimport { db } from '$lib/server/db'\nimport { presignPut } from '$lib/server/storage'\n\nconst MAX = 25 * 1024 * 1024\n\nexport const POST: RequestHandler = async ({ request, locals, url }) => {\n if (!locals.user) error(401, 'Sign in first')\n const { name, type, size } = (await request.json()) as { name: string; type: string; size: number }\n if (!(size > 0 && size <= MAX)) error(413, 'File is too large')\n const id = crypto.randomUUID()\n const safe = String(name).replace(/[^\\w.-]+/g, '_')\n const key = `${locals.user.teamId}/${id}/${safe}`\n await db.query('insert into files (id, team_id, key, type) values ($1, $2, $3, $4)', [id, locals.user.teamId, key, type])\n return json({ id, uploadUrl: await presignPut(key, type), fileUrl: `${url.origin}/api/files/${id}/${safe}` })\n}\n```\n\n`fileUrl` points at your app, not at the bucket. A presigned read URL\nexpires, and a cell keeps its URL for as long as the record exists. Serve\n`/api/files/[id]/[name]` with a `GET` that checks the user and the team,\nlooks up the key by `id` and answers `redirect(303, signedReadUrl)`:\nthumbnails, the preview and Download all follow the redirect, and old records\nkeep working.\n\nThe URL is absolute and ends in the file name for the sake of copy and\npaste. Copying an attachment cell writes the files' URLs, and a paste\nattaches each `http(s)` URL it finds, taking the name from the path and the\ntype from its extension. A relative URL would show fine in the cell but be\ndropped on paste, and a URL without the name would come back as a file named\nby its id, an image drawn as a chip.\n\nThe column limits what the dialog takes with\n[`AttachmentFieldProps`](../fields.md#attachments): `accept` (as for\n`<input accept>`, such as `'image/*,.pdf'`), `maxFiles` (default 20) and\n`maxSize` in bytes (default 25 MB). A file over a limit is listed under the\ntiles with the reason, such as \"At most 1 file\", \"Larger than 2 MB\" or \"Not\nan accepted type\". A URL added in the dialog, and text pasted into a cell,\nare checked the same way, their type read from the extension: what fails is\ndropped, the rest is kept. The field editor offers `accept` and `maxFiles`;\n`maxSize` is set in code:\n\n```ts\nconst photo = {\n field: 'photo',\n header: 'Photo',\n fieldType: 'attachment',\n fieldProps: { accept: 'image/*', maxFiles: 1, maxSize: 2 * 1024 * 1024 },\n}\n```\n\n`fieldProps.upload` sets an uploader for one column instead of the app's.\n\n### What the user sees\n\nThe cell shows images as thumbnails and other files as chips with the\nextension and the name, as many as the column width holds, then \"+N\". Enter\nor a double click opens the dialog: add files with \"Add files\", by dropping,\nby pasting files, or by pasting a URL into \"or paste a URL\". Each upload is a\ntile with its percent and a bar; Done reads \"Uploading 2...\" and stays\ndisabled until they finish. Tiles can be dragged to reorder, or moved with\nAlt+Left and Alt+Right; Delete removes one. Cancel or Escape leaves the cell\nas it was and aborts the uploads still running.\n\nFiles can also be dropped straight on a cell. Each one uploads on its own,\nwith a thin progress bar along the bottom of the cell, and the ones that\nupload are written to the cell in one edit. A file over a limit shows in a\n\"Not added\" toast and an upload that throws in an \"Upload failed\" toast, each\nwith the file name and the reason; the others still land. The toasts need\nthe same `<SvToaster />` as the comment store. Uploads still running when the\ncell goes away (scrolled out, or the table switched) are aborted through\n`signal`.\n\nEnter on a tile, or a click on its picture, opens the preview: images inline,\nPDFs in an iframe, anything else as its name with a Download link. Left and\nRight step through the files. For the PDF frame your storage has to send\n`application/pdf` and allow the page to frame it.\n\n## 7. Track who changed what\n\n`lastModifiedTime` and `lastModifiedBy` change on every edit to the record by\ndefault. With `watch: 'specific'` they change only when one of `watchFields`\ndoes, which turns them into \"status changed at\" and \"status changed by\":\n\n```ts\nconst stamps = [\n { field: 'updatedAt', header: 'Last modified', fieldType: 'lastModifiedTime', fieldProps: { dateFormat: 'friendly' } },\n { field: 'statusAt', header: 'Status changed', fieldType: 'lastModifiedTime', fieldProps: { watch: 'specific', watchFields: ['status'] } },\n { field: 'statusBy', header: 'Status changed by', fieldType: 'lastModifiedBy', fieldProps: { watch: 'specific', watchFields: ['status'] } },\n]\n```\n\n`watchFields` holds column ids: the column's `id`, or its `field` when it has\nnone. The time is an ISO string; the person is the current user's id. With\nnobody signed in, the time still moves and the person stays as it was. A\ncommit that leaves the value as it was (an editor opened and closed with\nEnter) is not an edit: nothing is stamped and `onCellValueChange` does not\nfire. An automation's `updateRecord` moves the time but not the person.\n\nThe stamp is written into the row before `onCellValueChange` fires, so the\nevent's `row` already holds it. If you save cell by cell, the event names\nonly the edited column: send the stamps along, or have the server write\n`updated_at` and `updated_by` from its own clock and session, which a\nbrowser cannot fake. With `onTablesChange` or a table `source` ([Keep a base\nin a database](./data.md)) the stamps travel with the rest of the row.\n\n## The activity log\n\nEvery edit through the grid is noted for the record: a typed value, a paste,\na fill, a clear, a checkbox click, a card dragged to another lane, an edit in\nthe record view, files added in the dialog or dropped on a cell. Each note\nholds the time, the current user's id, the column and the new value, and the\nrecord view writes it as \"Ana Ruiz changed Status\" over the value as the cell\nshows it, or \"(cleared)\". A field an automation's `updateRecord` sets is\nnoted under the automation's name: \"Automation: Done ticks the box changed\nDone\".\n\nA change someone else made in the database, read in through a table's\n`realtime` source, is noted too, under the name in the record's\n`lastModifiedBy` field, with the value before it: \"Triage agent changed\nPriority\", Low → Urgent. Until the record is opened, its changed cells are\ntinted and its row number has a dot. See [Changes made\nelsewhere](./data.md#changes-made-elsewhere).\n\nThe log lives in memory and keeps the latest 50 changes of each record. In\n`<SvBase tables>` it is kept by base, table and record id, so it survives\nswitching tabs; with one table it is kept per grid. It is not exported, and\nit is gone after a reload. Changes made by your code replacing `tables` or\n`data` are not noted.\n\nIf the team needs a history that lasts, record it yourself from\n`onCellValueChange` (`columnId`, `oldValue`, `newValue`, `row`) on the\nserver, where you know who is signed in.\n\n## The record menu\n\nRight-click a record in a base's grid:\n\n| Item | What it does |\n| --- | --- |\n| Expand record | Opens the record, with or without `expandRows` |\n| Comment | Opens the record with the comment box focused |\n| Insert record above, Insert record below | A new record beside this one with the values of the fields the view groups by, so it stays in the group; editing starts on its first field |\n| Duplicate record | A copy below, with lists copied; autonumber, created and last modified fields get fresh values |\n| Copy, Paste | The grid's own cell copy and paste |\n| Delete record | Asks \"Delete record?\" (\"Write the brief is deleted, and its links from other records go with it.\"), then removes it and fires `onRowsDelete` |\n\nWithout `editable`, only Expand record, Comment and Copy show. A new record\nfrom the menu is made the way \"+ Add row\" makes one: the `rowAdder` defaults,\na new id, the next autonumber, the current user in created by, and `onRowAdd`\nfired, so a table with a database writes it. The grid scrolls to it. A Kanban\ncard's right-click menu has Expand record and Comment, and with `editable`\n\"Move to\" a lane, Duplicate record and Delete record. Passing your own\n`contextMenu` to `SvBase` replaces the grid's menu.\n\n## Pitfalls\n\n- **No current user, no author.** Without `setCurrentUser`, new rows get\n `null` in created by, and an edit leaves last modified by as it was, so\n the field names whoever edited last while signed in.\n- **People are page-wide.** `setFieldUsers` and `setCurrentUser` set one list\n and one person for every base on the page. Two bases for two teams on one\n page share them.\n- **Records need real ids.** Comments and the activity are keyed by row id:\n each record's `id`, or `getRowId`. With one table a record without an `id`\n falls back to its index, so its comments move to another record when a row\n above it is deleted. In `<SvBase tables>` every record without an `id`\n shares the id `''`, and with it one thread. Give every record an id.\n- **Your store tells tables apart by id only.** In memory, each `<SvBase>`\n keeps its own comments and activity, even when two bases on one page use\n the same table ids. Your comment store gets the table id and nothing about\n the base: if two bases share one store and their table ids, key the store\n by something of your own as well. With `serverIds: true` a new record\n keeps the page's id until the table loads again; re-key its comments when\n the insert returns.\n- **`'@me'` is whoever runs the filter.** Before `setCurrentUser` it\n matches no one; the grid filters again once a user is set. In an\n automation's condition it is the person whose edit set it off, and on the\n server runner, where nobody is signed in, it matches no one.\n- **A URL's type is its extension.** Under `accept: 'image/*'` a URL with no\n extension is refused, and a URL's size is checked only when it is known.\n The browser checks are for the user; check types and sizes on the server\n too.\n- **Storage keeps what the cell drops.** Removing a file, Cancel after an\n upload finished, or deleting the record leaves the object in the bucket.\n Clean up on the server, for example files no record has pointed at for a\n day.\n- **`fieldProps.upload` does not survive JSON.** A function in a column is\n lost when you store columns in a database through `onTablesChange`. Use\n `setAttachmentUploader` and branch on `columnId` instead.\n\n## Next\n\n- [Linked records](./linked-records.md): tasks that point at milestones,\n people that point at teams, and the records that link back.\n- [Formulas](./formulas.md): fields worked out from other fields.\n- [Views](./views.md): grids, boards, calendars and galleries over the same\n records.\n- [Forms](./forms.md): let people outside the team add records.\n- [Your own field type](./custom-field-type.md): a cell of your own, with the\n grid's `ctrl` to open records from it.\n- [Automations](./automations.md): tell the assignee when a task is blocked.\n"
5165
+ "markdown": "# People, comments and files\n\nA tracker one person fills in needs a status column and little else. Once a\nteam uses it, people want to see who a task is assigned to, who changed the\nstatus and when, a thread of comments on the task, and the mockups attached\nto it, kept somewhere that survives a reload. This page adds those to the\ntask tracker from [Build a project tracker](./start.md).\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nIn the demo, double-click a candidate's card on the pipeline (or switch to\n\"All candidates\" and press Space on a row), change the Stage, leave a\ncomment, and watch the Activity column on the right of the record.\n\nThe base cannot know who your users are or where your files and comments\nlive. You tell it with four calls in the browser; the change log needs\nnothing:\n\n![Your users table goes to setFieldUsers and the session to setCurrentUser, which feed user cells, created by, last modified by and comment authors; setRecordComments connects the record view's Activity to your comments endpoint; setAttachmentUploader sends files to your storage through a presigned URL; the activity log is kept in the page](/docs-media/base-collaboration.svg)\n\nEach step below works on its own.\n\n## 1. List the people\n\nUser fields pick from one list of people that you hand to the base. A person\nis a `FieldUser`:\n\n```ts\nimport { setFieldUsers, type FieldUser } from '@svgrid/enterprise/base'\n\nconst team: FieldUser[] = [\n { id: 'u1', name: 'Ana Ruiz', email: 'ana@example.com', avatarUrl: 'https://cdn.example.com/ana.jpg' },\n { id: 'u2', name: 'Ben Okafor', email: 'ben@example.com' },\n { id: 'u3', name: 'Cleo Park', email: 'cleo@example.com' },\n]\n\n// In the browser only; step 2 shows where in SvelteKit.\nsetFieldUsers(team)\n```\n\nGive the tasks a `user` field for the owner and one with `multiple` for\nreviewers. The cell stores ids, never names, so renaming a person renames\nthem everywhere:\n\n```ts\nconst columns = [\n { field: 'task', header: 'Task', fieldType: 'text' },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'assignee', header: 'Assignee', fieldType: 'user' },\n { field: 'reviewers', header: 'Reviewers', fieldType: 'user', fieldProps: { multiple: true } },\n]\n\nconst data = [\n { id: 't1', task: 'Write the brief', status: 'Todo', assignee: 'u1', reviewers: ['u2', 'u3'] },\n { id: 't2', task: 'Pick the fonts', status: 'In progress', assignee: 'u2', reviewers: [] },\n]\n```\n\nA cell draws an avatar and the name. With several people it overlaps up to\nfour avatars and writes the first name with a count: \"Ben Okafor +1\".\n`avatarUrl` is used when it is an `http(s):`, `blob:` or `data:image` URL;\nanything else, or no URL, draws the initials on a color worked out from the\nname, so a person keeps the same color on every page. An id that is not in\nthe list shows as the id itself.\n\nEditing a user cell opens a panel with a \"Find a person\" box and the people\nfrom the list, each with their avatar; typing filters them. If the list is\nempty the panel says \"No people (setFieldUsers)\". Text pasted or filled into\na user cell is matched against each person's id, name and email, ignoring\ncase; a multiple field takes them comma-separated and drops repeats. A name\nthat matches nobody stays as typed, so check pasted data. Copying a user cell\nwrites the names, so a copy and paste between records keeps the people.\n`fieldProps.default` takes an id for new rows. The field reference has the\n[user field's properties](../fields.md#declare-columns-by-type).\n\nA Kanban view can stack by a single user field (`stackBy: 'assignee'`): one\nlane per person in the list, plus \"Uncategorized\" while some task has nobody.\nDragging a card to a lane reassigns the task through the grid's edit path,\nso it counts as an edit.\n\n## 2. Say who is signed in\n\n`setCurrentUser` names the person using the page. Several things read it:\n\n- `createdBy` fills new rows with their id, and `lastModifiedBy` writes it\n on every edit it watches.\n- Each comment is saved with their id as `by`.\n- Each change in a record's activity is noted with their id.\n- A filter condition with the value `'@me'` (`ME`) matches them.\n- Your own code can read it with `getCurrentUser()`.\n\nIn SvelteKit the session is on the server, so load the person and the team\nin a layout and hand both to the base in the browser:\n\n```ts\n// src/routes/(app)/+layout.server.ts\nimport { redirect } from '@sveltejs/kit'\nimport type { LayoutServerLoad } from './$types'\nimport { db } from '$lib/server/db'\n\nexport const load: LayoutServerLoad = async ({ locals }) => {\n if (!locals.user) redirect(303, '/login')\n const team = await db.query(\n 'select id, name, email, avatar_url as \"avatarUrl\" from users where team_id = $1 order by name',\n [locals.user.teamId],\n )\n return { me: { id: locals.user.id, name: locals.user.name }, team: team.rows }\n}\n```\n\n```svelte\n<!-- src/routes/(app)/+layout.svelte -->\n<script lang=\"ts\">\n import type { Snippet } from 'svelte'\n import { setCurrentUser, setFieldUsers, type FieldUser } from '@svgrid/enterprise/base'\n\n let { data, children }: { data: { me: FieldUser; team: FieldUser[] }; children: Snippet } = $props()\n\n // Again when the data changes: a sign-in as someone else.\n $effect.pre(() => {\n setFieldUsers(data.team)\n setCurrentUser(data.me)\n })\n</script>\n\n{@render children()}\n```\n\nThe four setters on this page write state shared by the whole module, so\ncall them in the browser only: an `$effect` as here (it does not run during\nserver rendering), `onMount`, or behind `browser` from `$app/environment`.\nCalled at the top of a component's `<script>`, they would also run on the\nserver and hand one request's team and user to the next. Cells and pickers\nread both values reactively, so the base can draw before they arrive. The signed-in person does not have to be in the team list for\ntheir name to show, but they only appear in the picker if they are.\n\nNow add who made each task and when, and give a new task to whoever adds it:\n\n```ts\nimport { getCurrentUser, type BaseTable } from '@svgrid/enterprise/base'\n\nconst tasks: BaseTable = {\n id: 'tasks',\n name: 'Tasks',\n primaryField: 'task',\n data,\n columns: [\n ...columns,\n { field: 'createdBy', header: 'Created by', fieldType: 'createdBy' },\n { field: 'createdAt', header: 'Created', fieldType: 'createdTime', fieldProps: { dateFormat: 'friendly' } },\n ],\n props: {\n rowAdder: { label: 'Add task', defaults: () => ({ status: 'Todo', assignee: getCurrentUser()?.id ?? null }) },\n },\n}\n```\n\nBoth fields are read-only. Every record the base makes gets the current user\nand the time: \"+ Add row\", a form, the record menu, \"+ Add a card\" on a\nKanban, a calendar day. Last modified fields start out the same way. Rows\nyou load keep whatever your database sends.\n\nOn sign-out, call `closeRecord()`, then `setCurrentUser(null)` and\n`setFieldUsers([])`.\n\n## 3. Add a \"My tasks\" view\n\nA filter condition on a user field compares it with a person's id. The value\n`'@me'` (exported as `ME`) stands for whoever is signed in when the filter\nruns, so one view works for everyone:\n\n```ts\nimport { ME, type FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n {\n id: 'mine',\n name: 'My tasks',\n type: 'grid',\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'or',\n conditions: [\n { column: 'assignee', kind: 'select', op: 'is', value: ME },\n { column: 'reviewers', kind: 'multi', op: 'hasAnyOf', value: [ME] },\n ],\n },\n },\n },\n { id: 'all', name: 'All tasks', type: 'grid' },\n]\n```\n\nIn the Filter panel the person picker lists \"Me\" first, so users can build\nthe same view themselves. The condition reads \"Assignee is me\".\n\nA single user field filters with the select operators (`is`, `isNot`,\n`isAnyOf`, `isNoneOf`), a multiple one with `hasAnyOf`, `hasAllOf`,\n`isExactly` and `hasNoneOf`; both also have `isEmpty` and `isNotEmpty`.\nCreated by and last modified by filter the same way, so \"Created by is me\"\nworks too. The [filter conditions](../fields.md#filter-conditions) table\nlists them all.\n\nThe view stores `'@me'`, not an id, so it can be saved with the other views\n(`onViewsChange`, or the `views` inside `onTablesChange`) and Ben sees his own\ntasks when he opens it.\n\n## 4. Open a record\n\n`expandRows` with `showRowNumbers` turns the row number into a checkbox and an\nexpand button:\n\n```svelte\n<SvBase bind:tables editable showRowNumbers expandRows onTablesChange={save} />\n```\n\nA record opens from the expand button, from Space on a selected cell (not a\ncheckbox cell, and only with `expandRows`), from \"Expand record\" in the\nright-click menu, from a gallery card, from a double click (or F2) on a\nKanban card, from a calendar event and from a Gantt task.\n\n![A candidate open as a record: each field with its type icon on the left, and the Activity column on the right with \"Ana Ruiz changed Stage\" to Offer, her comment below it and the comment box](/docs-media/base-collaboration.png)\n\nThe record shows:\n\n- The primary field as the title.\n- Every field with its type icon and name, drawn as its cell draws it. A click\n opens the cell's own editor; the value is written through the grid's edit\n path, so undo, validation, `onCellValueChange` and last-modified fields work\n the same as in the cell. Read-only fields say \"read-only\".\n- Fields hidden in the view, folded under \"Show N hidden fields\" and marked\n \"hidden in the grid\". They are read-only here.\n- Activity on the right: changes and comments, oldest first, with \"just now\",\n \"5 minutes ago\", \"3 hours ago\" or the date. The box under them takes a\n comment; Ctrl+Enter (Cmd+Enter) or Comment sends it. A base without\n `editable` still takes comments.\n- Previous and next buttons that step through the rows in the view's order,\n and \"3 of 12\".\n\nA record with comments shows how many by its row number (the pointer over the\nrow swaps the count for the checkbox and expand button) and as a badge on its\nKanban card. The card's badge opens the record with the comment box focused,\nas does \"Comment\" in the right-click menu of a row or a card.\n\nOn a narrow screen the activity moves under the fields. If an edit makes the\nrecord leave the view's filter, the record says \"This row is not in the\ngrid's view any more.\" and the footer \"Not in view (12 records)\". Previous\nand next still work: they move to the records that were before and after it.\n\nApp code opens a record with the grid api that `onApiReady` hands it:\n\n```ts\nimport { openRecord, closeRecord } from '@svgrid/enterprise/base'\n\nlet api: unknown\n// <SvBase ... onApiReady={(a) => (api = a)} />\n\nopenRecord({ api, rowId: 't1' })\nopenRecord({ api, rowId: 't1', focus: 'comment' }) // with the comment box focused\ncloseRecord(api)\n```\n\n`closeRecord()` closes whatever record is open, from anywhere: call it on\nsign-out or when the route changes. `closeRecord(api)` closes it only when it\nis open on that grid. A custom field type's `cell` component gets the grid\nas `ctrl` (with `row.id`), and `openRecord({ ctrl, rowId })` takes that too.\nA button field's `fieldProps.onClick` receives `{ row, rowId, columnId, api }`,\nso a button can open its own record.\n\n## 5. Keep comments in your backend\n\nWithout a store, comments live in memory and are gone on reload. In\n`<SvBase tables>` they are kept by table id and record id for the whole\npage, so two bases that show the same table, or a base mounted again, show\nthe same comments. Give unrelated bases on one page different table ids.\nWith one table (`data` and `columns`) they are kept per grid. A comment is\na `RecordComment`, and a store is two functions:\n\n```ts {nocheck}\nexport type RecordComment = { id: string; rowId: string; tableId?: string; text: string; at: number; by?: string; mentions?: string[] }\n\nexport type RecordCommentContext = { tableId?: string; api: unknown }\n\nexport type RecordCommentStore = {\n list: (rowId: string, api: unknown, context: RecordCommentContext) => ReadonlyArray<RecordComment>\n add: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void\n onMention?: (event: MentionEvent) => void\n}\n```\n\n`rowId` is the record's id (its `id`, or the table's `getRowId`). In\n`<SvBase tables>`, `context.tableId` (and the comment's `tableId`) names the\ntable, so Tasks `1` and Milestones `1` are two records; with one table it is\nundefined. `at` is milliseconds since 1970, `by` the id of the person who was\nsigned in. The record view makes `id`, `at` and `by` itself and calls `add`.\nA store written for `list(rowId, api)` and `add(rowId, comment, api)` still\nworks.\n\nBoth functions are synchronous, and `list` runs often: for the open record,\nand for every row the grid draws (with `expandRows`) and every Kanban card,\nto show the comment count. So fetch a whole table's comments once into reactive state and answer\nfrom it. Because `list` runs inside the base's reactive code, the counts and\nthe record draw again when the fetch lands:\n\n```ts\n// src/lib/comments.svelte.ts\nimport { browser } from '$app/environment'\nimport { toast } from '@svgrid/grid'\nimport { setRecordComments, type RecordComment, type RecordCommentStore } from '@svgrid/enterprise/base'\n\ntype ByRecord = Record<string, ReadonlyArray<RecordComment>>\n\n// Each table's comments by record id, fetched once per table.\nlet byTable = $state.raw<Record<string, ByRecord>>({})\nconst asked = new Set<string>()\n\nfunction put(table: string, rowId: string, list: ReadonlyArray<RecordComment>) {\n byTable = { ...byTable, [table]: { ...byTable[table], [rowId]: list } }\n}\n\nasync function load(table: string) {\n asked.add(table)\n const res = await fetch(`/api/comments?table=${encodeURIComponent(table)}`)\n if (!res.ok) return void asked.delete(table)\n const grouped: Record<string, RecordComment[]> = {}\n for (const c of (await res.json()) as RecordComment[]) (grouped[c.rowId] ??= []).push(c)\n byTable = { ...byTable, [table]: grouped }\n}\n\nconst store: RecordCommentStore = {\n list(rowId, _api, { tableId = '' }) {\n if (!asked.has(tableId)) void load(tableId)\n return byTable[tableId]?.[rowId] ?? []\n },\n add(rowId, comment, _api, { tableId = '' }) {\n const mine = () => byTable[tableId]?.[rowId] ?? []\n // Shown at once; the server's copy replaces it, or it goes away again.\n put(tableId, rowId, [...mine(), comment])\n fetch('/api/comments', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ id: comment.id, tableId, rowId, text: comment.text }),\n })\n .then(async (res) => {\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n const saved = (await res.json()) as RecordComment\n put(tableId, rowId, mine().map((c) => (c.id === comment.id ? saved : c)))\n })\n .catch(() => {\n put(tableId, rowId, mine().filter((c) => c.id !== comment.id))\n toast.error('Your comment was not saved')\n })\n },\n}\n\n// On the server this cache would be shared by every request.\nif (browser) setRecordComments(store)\n```\n\nImport the file once, in the page that shows the base. The failure notice\nneeds one `<SvToaster />` from `@svgrid/grid` in the app.\n`setRecordComments(null)` goes back to memory. For a table with a very large\ndiscussion, have the endpoint return counts per record and fetch a record's\ncomments when it opens.\n\nThe endpoint takes the author and the time from the server, never from the\nrequest body:\n\n```ts\n// src/routes/api/comments/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport type { RequestHandler } from './$types'\nimport { db } from '$lib/server/db'\n\nexport const GET: RequestHandler = async ({ url, locals }) => {\n if (!locals.user) error(401, 'Sign in first')\n const tableId = url.searchParams.get('table') ?? ''\n // `at` is a bigint column; the cast hands it back as a number, not a string.\n const { rows } = await db.query(\n 'select id, table_id as \"tableId\", row_id as \"rowId\", text, at::float8 as at, author as \"by\" from comments where team_id = $1 and table_id = $2 order by at',\n [locals.user.teamId, tableId],\n )\n return json(rows)\n}\n\nexport const POST: RequestHandler = async ({ request, locals }) => {\n if (!locals.user) error(401, 'Sign in first')\n const body = (await request.json()) as { id?: unknown; tableId?: unknown; rowId?: unknown; text?: unknown }\n const text = String(body.text ?? '').trim().slice(0, 4000)\n if (typeof body.id !== 'string' || typeof body.rowId !== 'string' || !text) error(400, 'Bad comment')\n const tableId = typeof body.tableId === 'string' ? body.tableId : ''\n const comment = { id: body.id, tableId, rowId: body.rowId, text, at: Date.now(), by: locals.user.id }\n await db.query(\n 'insert into comments (id, team_id, table_id, row_id, text, at, author) values ($1, $2, $3, $4, $5, $6, $7)',\n [comment.id, locals.user.teamId, comment.tableId, comment.rowId, comment.text, comment.at, comment.by],\n )\n return json(comment, { status: 201 })\n}\n```\n\nThe activity names the author from the people list: a `by` that is not in\n`setFieldUsers` (and is not the current user) shows as \"Someone\", and a\ncomment with no `by` shows as \"You\". Keep people who left the team in the\nlist, or return their name from your own data.\n\nComments other people add show once the cache changes. To see them while the\nbase is open, call `put` from your realtime channel or a poll.\n\n### Mentions\n\nTyping `@` in the comment box lists the people from `setFieldUsers`, narrowed\nby the letters after it (the start of any word of a name, or of an email).\nUp and Down move through the list, Enter or Tab picks, Escape closes the\nlist and leaves the record open. An `@` inside a word, as in an email\naddress, does not open it.\n\nA mention is kept in the comment's `text` as a token, and its id in\n`mentions`:\n\n```ts {nocheck}\n{ text: 'Numbers match. @[Ana Ruiz](u1) can you get legal to sign off?', mentions: ['u1'] }\n```\n\nThe record view draws the token as a chip with the person's avatar and their\nname from the people list today, so renaming someone renames their mentions.\nA person no longer in the list shows with the name written in the token. The\nrest of the text is drawn as text, never as HTML. `mentionText(text)` turns\nthe tokens back into `@Ana Ruiz` for an email or a chat message, and\n`mentionIds(text)` reads the ids, for a server that does not trust the\n`mentions` the browser sent.\n\nTo send notifications, give the store an `onMention` hook, or call\n`setMentionHandler` (it works with the in-memory default too). Each runs once\nper comment that mentions someone, after `add`:\n\n```ts\nimport { mentionText, setMentionHandler, type MentionEvent } from '@svgrid/enterprise/base'\n\nsetMentionHandler((e: MentionEvent) => {\n // e.comment, e.mentioned (FieldUser[]), e.rowId, e.tableId, e.record, e.api\n const to = e.mentioned.filter((p) => p.id !== e.comment.by && p.email).map((p) => p.email)\n if (!to.length) return\n void fetch('/api/notify', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ to, record: e.record?.task, text: mentionText(e.comment.text) }),\n })\n})\n```\n\n`mentioned` lists each person once, in the order they first appear,\nincluding the author when they mention themselves. Someone not in\n`setFieldUsers` comes with the name written in the token. A hook that throws\nis logged, and the comment stays. When your comments endpoint already saves\n`mentions`, sending from the server, where the author is known, is the safer\nplace for the email.\n\n<div data-docs-demo=\"712-base-mentions\" data-height=\"640\"></div>\n\n## 6. Upload files\n\nAn attachment cell holds an array of `Attachment`: `id`, `url`, `name`,\n`type` (the MIME type), and optional `size`, `width`, `height` and\n`thumbnailUrl` (a smaller image the cell uses instead of `url`). The\n[attachments section](../fields.md#attachments) of the field reference has\nan example value.\n\nWithout an uploader, added files stay in the page as `blob:` URLs and are\ngone on reload. `setAttachmentUploader` sets the function every attachment\ncolumn uses. It gets the `File` and an `AttachmentUploadContext`: `row` (the\nrecord), `columnId`, a `signal` that aborts when the user removes the file\nor closes the dialog, and `onProgress(fraction)` with a value from 0 to 1.\nIt returns the attachment.\n\nThis one asks your server for a presigned URL and sends the bytes straight\nto object storage. It uses `XMLHttpRequest` because `fetch` reports no upload\nprogress:\n\n```ts\n// src/lib/uploads.ts\nimport { browser } from '$app/environment'\nimport { setAttachmentUploader, type AttachmentUploader } from '@svgrid/enterprise/base'\n\nconst upload: AttachmentUploader = async (file, { columnId, signal, onProgress }) => {\n const res = await fetch('/api/uploads', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ name: file.name, type: file.type, size: file.size, columnId }),\n signal,\n })\n if (!res.ok) throw new Error(res.status === 413 ? 'File is too large' : `Upload refused (${res.status})`)\n const { id, uploadUrl, fileUrl } = (await res.json()) as { id: string; uploadUrl: string; fileUrl: string }\n\n await new Promise<void>((resolve, reject) => {\n const xhr = new XMLHttpRequest()\n xhr.open('PUT', uploadUrl)\n xhr.setRequestHeader('content-type', file.type || 'application/octet-stream')\n xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(e.loaded / e.total)\n xhr.onload = () => (xhr.status < 300 ? resolve() : reject(new Error(`Storage said ${xhr.status}`)))\n xhr.onerror = () => reject(new Error('Network error'))\n xhr.onabort = () => reject(new Error('Cancelled'))\n signal.addEventListener('abort', () => xhr.abort(), { once: true })\n xhr.send(file)\n })\n\n return { id, url: fileUrl, name: file.name, type: file.type, size: file.size }\n}\n\nif (browser) setAttachmentUploader(upload)\n```\n\nThe message of the error you throw is what the user reads on the failed tile,\nnext to Retry and Remove, so write it for them.\n\nThe server checks the user and the size, signs a URL for one key, and keeps\na row per file:\n\n```ts\n// src/routes/api/uploads/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport type { RequestHandler } from './$types'\nimport { db } from '$lib/server/db'\nimport { presignPut } from '$lib/server/storage'\n\nconst MAX = 25 * 1024 * 1024\n\nexport const POST: RequestHandler = async ({ request, locals, url }) => {\n if (!locals.user) error(401, 'Sign in first')\n const { name, type, size } = (await request.json()) as { name: string; type: string; size: number }\n if (!(size > 0 && size <= MAX)) error(413, 'File is too large')\n const id = crypto.randomUUID()\n const safe = String(name).replace(/[^\\w.-]+/g, '_')\n const key = `${locals.user.teamId}/${id}/${safe}`\n await db.query('insert into files (id, team_id, key, type) values ($1, $2, $3, $4)', [id, locals.user.teamId, key, type])\n return json({ id, uploadUrl: await presignPut(key, type), fileUrl: `${url.origin}/api/files/${id}/${safe}` })\n}\n```\n\n`fileUrl` points at your app, not at the bucket. A presigned read URL\nexpires, and a cell keeps its URL for as long as the record exists. Serve\n`/api/files/[id]/[name]` with a `GET` that checks the user and the team,\nlooks up the key by `id` and answers `redirect(303, signedReadUrl)`:\nthumbnails, the preview and Download all follow the redirect, and old records\nkeep working.\n\nThe URL is absolute and ends in the file name for the sake of copy and\npaste. Copying an attachment cell writes the files' URLs, and a paste\nattaches each `http(s)` URL it finds, taking the name from the path and the\ntype from its extension. A relative URL would show fine in the cell but be\ndropped on paste, and a URL without the name would come back as a file named\nby its id, an image drawn as a chip.\n\nThe column limits what the dialog takes with\n[`AttachmentFieldProps`](../fields.md#attachments): `accept` (as for\n`<input accept>`, such as `'image/*,.pdf'`), `maxFiles` (default 20) and\n`maxSize` in bytes (default 25 MB). A file over a limit is listed under the\ntiles with the reason, such as \"At most 1 file\", \"Larger than 2 MB\" or \"Not\nan accepted type\". A URL added in the dialog, and text pasted into a cell,\nare checked the same way, their type read from the extension: what fails is\ndropped, the rest is kept. The field editor offers `accept` and `maxFiles`;\n`maxSize` is set in code:\n\n```ts\nconst photo = {\n field: 'photo',\n header: 'Photo',\n fieldType: 'attachment',\n fieldProps: { accept: 'image/*', maxFiles: 1, maxSize: 2 * 1024 * 1024 },\n}\n```\n\n`fieldProps.upload` sets an uploader for one column instead of the app's.\n\n### What the user sees\n\nThe cell shows images as thumbnails and other files as chips with the\nextension and the name, as many as the column width holds, then \"+N\". Enter\nor a double click opens the dialog: add files with \"Add files\", by dropping,\nby pasting files, or by pasting a URL into \"or paste a URL\". Each upload is a\ntile with its percent and a bar; Done reads \"Uploading 2...\" and stays\ndisabled until they finish. Tiles can be dragged to reorder, or moved with\nAlt+Left and Alt+Right; Delete removes one. Cancel or Escape leaves the cell\nas it was and aborts the uploads still running.\n\nFiles can also be dropped straight on a cell. Each one uploads on its own,\nwith a thin progress bar along the bottom of the cell, and the ones that\nupload are written to the cell in one edit. A file over a limit shows in a\n\"Not added\" toast and an upload that throws in an \"Upload failed\" toast, each\nwith the file name and the reason; the others still land. The toasts need\nthe same `<SvToaster />` as the comment store. Uploads still running when the\ncell goes away (scrolled out, or the table switched) are aborted through\n`signal`.\n\nEnter on a tile, or a click on its picture, opens the preview: images inline,\nPDFs in an iframe, anything else as its name with a Download link. Left and\nRight step through the files. For the PDF frame your storage has to send\n`application/pdf` and allow the page to frame it.\n\n## 7. Track who changed what\n\n`lastModifiedTime` and `lastModifiedBy` change on every edit to the record by\ndefault. With `watch: 'specific'` they change only when one of `watchFields`\ndoes, which turns them into \"status changed at\" and \"status changed by\":\n\n```ts\nconst stamps = [\n { field: 'updatedAt', header: 'Last modified', fieldType: 'lastModifiedTime', fieldProps: { dateFormat: 'friendly' } },\n { field: 'statusAt', header: 'Status changed', fieldType: 'lastModifiedTime', fieldProps: { watch: 'specific', watchFields: ['status'] } },\n { field: 'statusBy', header: 'Status changed by', fieldType: 'lastModifiedBy', fieldProps: { watch: 'specific', watchFields: ['status'] } },\n]\n```\n\n`watchFields` holds column ids: the column's `id`, or its `field` when it has\nnone. The time is an ISO string; the person is the current user's id. With\nnobody signed in, the time still moves and the person stays as it was. A\ncommit that leaves the value as it was (an editor opened and closed with\nEnter) is not an edit: nothing is stamped and `onCellValueChange` does not\nfire. An automation's `updateRecord` moves the time but not the person.\n\nThe stamp is written into the row before `onCellValueChange` fires, so the\nevent's `row` already holds it. If you save cell by cell, the event names\nonly the edited column: send the stamps along, or have the server write\n`updated_at` and `updated_by` from its own clock and session, which a\nbrowser cannot fake. With `onTablesChange` or a table `source` ([Keep a base\nin a database](./data.md)) the stamps travel with the rest of the row.\n\n## Protected fields\n\nA protected field takes edits from the people it lists. Everyone else sees\nit read-only, with a lock after its name that says who can edit it:\n\n```ts\nconst columns = [\n { field: 'priority', header: 'Priority', fieldType: 'singleSelect', fieldProps: { options: PRIORITY, editors: ['u1', 'u2'] } },\n { field: 'approved', header: 'Approved', fieldType: 'checkbox', fieldProps: { editors: [] } },\n]\n```\n\n`editors` holds user ids, matched against `setCurrentUser`. An empty list\nmeans nobody can edit the values, and with nobody signed in a protected\nfield is read-only. In the base, Edit field > Who can edit its values sets\nthe list: \"Only these people\" starts with the person setting it, so they do\nnot lock themselves out. `protectFields={false}` on `<SvBase>` takes that\nchoice away from someone your app does not let change it.\n\nWhat the protection covers, for the person in front of the page:\n\n- typing, pasting, the fill handle, Delete, and the record view;\n- a board stacked by the field (its cards do not move) and a calendar or\n timeline whose dates it holds (its events do not drag);\n- an import into the table, which does not offer the field as a target.\n\nA field's name, type and options stay editable: protection is about the\nvalues. A new record still takes its group's value, so \"+\" on a group still\nadds a record to it, and a form fills the fields its author put on it.\n\nWith roles of your own, pass a check in place of the lists. It decides for\nevery field of every base on the page; `defaultCanEditField` is the\n`editors` check, to fall back on:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, defaultCanEditField, type CanEditField } from '@svgrid/enterprise/base'\n let { tables, role } = $props()\n // Admins edit everything; everyone else follows each field's editors.\n const canEditField: CanEditField = (field, user) => role === 'admin' || defaultCanEditField(field, user)\n</script>\n\n<SvBase bind:tables {canEditField} protectFields={role === 'admin'} editable />\n```\n\nThe browser enforces this. A base whose records live in a database still\nneeds the server to refuse a write to a protected field, as it would any\nwrite the person is not allowed.\n\n<div data-docs-demo=\"710-base-personal-locked-views\" data-height=\"620\"></div>\n\n## Share a base read-only\n\nFor people who may look but not change anything, such as a client opening a\nshare link your app serves, pass `readOnly`:\n\n```svelte\n<SvBase {tables} readOnly sortable expandRows fieldMenu />\n```\n\nWhat it closes:\n\n- cells and the record view: no typing, pasting, fill handle, Delete or\n checkbox clicks, and buttons do not run automations;\n- the record menu keeps Expand record and Copy; the field menu keeps Filter,\n Group, Hide and Color rows by this field;\n- no \"+ Add row\", no \"+\" column, no \"+\" on a group, and the selection bar\n drops Edit fields and Delete;\n- a board's cards do not move and its lanes add none; a calendar's or\n timeline's events do not drag, and a day picked adds no record;\n- the tab bar has no table menu, no renaming, no Add table, no import, no\n trash, no undo, and no Download as SQL; it shows a \"View only\" badge;\n- no Automations button, and scheduled automations do not run in the page;\n- comments are read, and the box to write one is gone;\n- form views are not shared.\n\nViewers still switch tables and views, search, filter, sort, group, and open\nrecords with their activity. What they change in a view (a sort, a filter,\na new view) stays in the page while it is open, also across table switches,\nand never reaches `onTablesChange` or a table's `source`.\n\nA share on the same page as the editing base (a preview, or the demo below)\nshows the comments written in the editor, with their counts on rows and\ncards: comments are kept by table id and record id, not by base. The\nchanges in a record's activity and the unseen marks stay with the base that\nnoted them. On a separate page, the share sees the comments your\n`setRecordComments` store returns; in-page comments do not travel between\nbrowsers.\n\nAn object picks what the share shows. Every list is optional:\n\n```svelte\n<SvBase\n {tables}\n readOnly={{\n tables: ['projects', 'clients'],\n views: ['all', 'board'],\n hideFields: ['budget', 'clients.notes'],\n }}\n/>\n```\n\n`tables` and `views` are ids; a table none of whose listed views exists\nshows its first view. `hideFields` takes a column id, which hides it in\nevery table, or `tableId.columnId`. The primary field always shows. A hidden\nfield takes along every field that would show what it holds: the formulas\nthat read it, a rollup or lookup of it in another table, and the lookups,\nrollups and counts of a link to a table the share leaves out.\n\nHiding is for display. A page handed the whole base still holds the hidden\nvalues in memory, so for anything secret build the shared copy on the server\nwith `sharedTables(tables, share)`, which also takes the hidden fields'\nvalues out of the records, and send only that.\n\n<div data-docs-demo=\"717-base-read-only-share\" data-height=\"620\"></div>\n\n## The activity log\n\nEvery edit through the grid is noted for the record: a typed value, a paste,\na fill, a clear, a checkbox click, a card dragged to another lane, an edit in\nthe record view, files added in the dialog or dropped on a cell. Each note\nholds the time, the current user's id, the column and the new value, and the\nrecord view writes it as \"Ana Ruiz changed Status\" over the value as the cell\nshows it, or \"(cleared)\". A field an automation's `updateRecord` sets is\nnoted under the automation's name: \"Automation: Done ticks the box changed\nDone\".\n\nA change someone else made in the database, read in through a table's\n`realtime` source, is noted too, under the name in the record's\n`lastModifiedBy` field, with the value before it: \"Triage agent changed\nPriority\", Low → Urgent. Until the record is opened, its changed cells are\ntinted and its row number has a dot. See [Changes made\nelsewhere](./data.md#changes-made-elsewhere).\n\nThe log lives in memory and keeps the latest 50 changes of each record. In\n`<SvBase tables>` it is kept by base, table and record id, so it survives\nswitching tabs; with one table it is kept per grid. It is not exported, and\nit is gone after a reload. Changes made by your code replacing `tables` or\n`data` are not noted.\n\nIf the team needs a history that lasts, record it yourself from\n`onCellValueChange` (`columnId`, `oldValue`, `newValue`, `row`) on the\nserver, where you know who is signed in.\n\n## The record menu\n\nRight-click a record in a base's grid:\n\n| Item | What it does |\n| --- | --- |\n| Expand record | Opens the record, with or without `expandRows` |\n| Comment | Opens the record with the comment box focused |\n| Insert record above, Insert record below | A new record beside this one with the values of the fields the view groups by, so it stays in the group; editing starts on its first field |\n| Duplicate record | A copy below, with lists copied; autonumber, created and last modified fields get fresh values |\n| Copy, Paste | The grid's own cell copy and paste |\n| Delete record | Asks \"Delete record?\" (\"Write the brief is deleted, and its links from other records go with it.\"), then removes it and fires `onRowsDelete` |\n\nWithout `editable`, only Expand record, Comment and Copy show. A new record\nfrom the menu is made the way \"+ Add row\" makes one: the `rowAdder` defaults,\na new id, the next autonumber, the current user in created by, and `onRowAdd`\nfired, so a table with a database writes it. The grid scrolls to it. A Kanban\ncard's right-click menu has Expand record and Comment, and with `editable`\n\"Move to\" a lane, Duplicate record and Delete record. Passing your own\n`contextMenu` to `SvBase` replaces the grid's menu.\n\n## Pitfalls\n\n- **No current user, no author.** Without `setCurrentUser`, new rows get\n `null` in created by, and an edit leaves last modified by as it was, so\n the field names whoever edited last while signed in.\n- **People are page-wide.** `setFieldUsers` and `setCurrentUser` set one list\n and one person for every base on the page. Two bases for two teams on one\n page share them.\n- **Records need real ids.** Comments and the activity are keyed by row id:\n each record's `id`, or `getRowId`. With one table a record without an `id`\n falls back to its index, so its comments move to another record when a row\n above it is deleted. In `<SvBase tables>` every record without an `id`\n shares the id `''`, and with it one thread. Give every record an id.\n- **Your store tells tables apart by id only.** In memory, each `<SvBase>`\n keeps its own comments and activity, even when two bases on one page use\n the same table ids. Your comment store gets the table id and nothing about\n the base: if two bases share one store and their table ids, key the store\n by something of your own as well. With `serverIds: true` a new record\n keeps the page's id until the table loads again; re-key its comments when\n the insert returns.\n- **`'@me'` is whoever runs the filter.** Before `setCurrentUser` it\n matches no one; the grid filters again once a user is set. In an\n automation's condition it is the person whose edit set it off, and on the\n server runner, where nobody is signed in, it matches no one.\n- **A URL's type is its extension.** Under `accept: 'image/*'` a URL with no\n extension is refused, and a URL's size is checked only when it is known.\n The browser checks are for the user; check types and sizes on the server\n too.\n- **Storage keeps what the cell drops.** Removing a file, Cancel after an\n upload finished, or deleting the record leaves the object in the bucket.\n Clean up on the server, for example files no record has pointed at for a\n day.\n- **`fieldProps.upload` does not survive JSON.** A function in a column is\n lost when you store columns in a database through `onTablesChange`. Use\n `setAttachmentUploader` and branch on `columnId` instead.\n\n## Next\n\n- [Linked records](./linked-records.md): tasks that point at milestones,\n people that point at teams, and the records that link back.\n- [Formulas](./formulas.md): fields worked out from other fields.\n- [Views](./views.md): grids, boards, calendars and galleries over the same\n records.\n- [Forms](./forms.md): let people outside the team add records.\n- [Your own field type](./custom-field-type.md): a cell of your own, with the\n grid's `ctrl` to open records from it.\n- [Automations](./automations.md): tell the assignee when a task is blocked.\n"
5030
5166
  },
5031
5167
  {
5032
5168
  "slug": "help/base/custom-field-type",
@@ -5047,14 +5183,14 @@ export const docs = [
5047
5183
  "path": "docs/help/base/forms.md",
5048
5184
  "title": "Collect records with forms",
5049
5185
  "section": "SvGrid Base",
5050
- "markdown": "# Collect records with forms\n\nA form view asks for some of a table's fields and adds a record when it is\nsent. Use it for records other people start: a bug report, an expense, a\njob application. This page builds a hiring tracker's application flow.\nCandidates apply through a form, the record lands in the Candidates table,\nand recruiters move it across a Kanban by stage.\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"680\"></div>\n\nIn the demo, pick the \"Apply\" view, fill in the form and press Submit, then\nswitch to \"Hiring pipeline\": the new candidate is a card in Applied.\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\n## 1. Declare the Candidates table\n\nKeep the fields in one module. The base imports them, and so do the public\npage and the server you build later on this page, so all three agree on\nfield ids and types.\n\n```ts\n// src/lib/hiring.ts\nimport type { BaseTable } from '@svgrid/enterprise/base'\n\nexport const STAGES = [\n { value: 'Applied', color: '#94a3b8' },\n { value: 'Phone screen', color: '#18bfff' },\n { value: 'Onsite', color: '#2d7ff9' },\n { value: 'Offer', color: '#fcb400' },\n { value: 'Hired', color: '#20c933' },\n { value: 'Rejected', color: '#f82b60' },\n]\nexport const SOURCES = [{ value: 'Careers page' }, { value: 'Referral' }, { value: 'Job board' }]\n\nexport const candidateColumns: BaseTable['columns'] = [\n { field: 'name', header: 'Candidate', fieldType: 'text' },\n { field: 'email', header: 'Email', fieldType: 'email' },\n { field: 'phone', header: 'Phone', fieldType: 'phone', description: 'With the country code.' },\n { field: 'role', header: 'Role', fieldType: 'link', fieldProps: { table: 'roles', multiple: false, inverse: 'candidates' } },\n {\n field: 'resume', header: 'Resume', fieldType: 'attachment',\n fieldProps: { accept: '.pdf,.doc,.docx', maxFiles: 1, maxSize: 10 * 1024 * 1024 },\n description: 'One PDF or Word file, up to 10 MB.',\n },\n { field: 'portfolio', header: 'Portfolio', fieldType: 'url', description: 'A site, a repository or a design portfolio.' },\n { field: 'years', header: 'Years of experience', fieldType: 'number', fieldProps: { format: 'integer', allowNegative: false } },\n { field: 'start', header: 'Earliest start', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'notes', header: 'Notes', fieldType: 'longText' },\n // The team's fields. The form leaves them out.\n { field: 'stage', header: 'Stage', fieldType: 'singleSelect', fieldProps: { options: STAGES, default: 'Applied' } },\n { field: 'source', header: 'Source', fieldType: 'singleSelect', fieldProps: { options: SOURCES } },\n { field: 'recruiter', header: 'Recruiter', fieldType: 'user' },\n { field: 'applied', header: 'Applied', fieldType: 'createdTime' },\n]\n\nexport const roleColumns: BaseTable['columns'] = [\n { field: 'name', header: 'Role', fieldType: 'text' },\n { field: 'candidates', header: 'Candidates', fieldType: 'link', fieldProps: { table: 'candidates', multiple: true, inverse: 'role' } },\n]\n\n/** What a candidate fills in, in order. */\nexport const APPLY_FIELDS: string[] = ['name', 'email', 'phone', 'role', 'resume', 'portfolio', 'years', 'start', 'notes']\n```\n\nThe form labels each field with the column's `header`, the type's icon in\nfront of it. A column's `description` is the help text: the form shows it in\nsmall grey type under the field, and the grid shows it on the info mark in\nthe header.\n\n## 2. Add the form view\n\nA form is a view, next to the pipeline and the grid:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, setFieldUsers, type BaseTable } from '@svgrid/enterprise/base'\n import { APPLY_FIELDS, candidateColumns, roleColumns } from '$lib/hiring'\n\n enableBase()\n setFieldUsers([{ id: 'u1', name: 'Ana Ruiz' }, { id: 'u2', name: 'Ben Okafor' }])\n\n let { candidates, roles }: { candidates: Record<string, unknown>[]; roles: Record<string, unknown>[] } = $props()\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'candidates',\n name: 'Candidates',\n primaryField: 'name',\n data: candidates,\n columns: candidateColumns,\n views: [\n { id: 'pipeline', name: 'Pipeline', type: 'kanban', stackBy: 'stage' },\n { id: 'all', name: 'All candidates', type: 'grid', color: { mode: 'field', field: 'stage' } },\n {\n id: 'apply',\n name: 'Apply',\n type: 'form',\n formFields: APPLY_FIELDS,\n formTitle: 'Join the team',\n formDescription: 'Tell us about yourself. We reply to every application within a week.',\n formRequired: ['name', 'email', 'role', 'resume'],\n formSubmitLabel: 'Send application',\n },\n ],\n },\n { id: 'roles', name: 'Roles', primaryField: 'name', data: roles, columns: roleColumns },\n ])\n</script>\n\n<SvBase bind:tables editable expandRows containerHeight={640} onTablesChange={(t) => console.log('save', t)} />\n```\n\nPick \"Apply\" in the view menu. The grid stays mounted underneath and the\nform covers it: a card with \"Join the team\" as the heading, the description\nunder it, and one box per field. A click on a box opens the editor the cell\nuses: the select panel for a select, the record picker for Role, the date\npicker for Earliest start, the attachment dialog for Resume, the number box\nfor Years of experience. Tab and Shift+Tab move to the next or previous\nfield from inside an editor.\n\n![The demo's Apply form view: Candidate filled in as Ana Ruiz, Email as ana@ with a red border and \"Not a valid email address\" under it after Submit, Role set to Product designer, Resume and Notes still empty.](/docs-media/base-forms.png)\n\nFor a form view, the view bar keeps the view menu and, when the base runs\nautomations, the Automations button. Hide fields, Filter, Sort, the record\ncount and search are gone.\n\nWithout `formFields`, the form asks for every field a person can fill in:\nthe primary field first, then the rest in the grid's column order, hidden\ncolumns included. Computed types (formula, lookup, rollup, count,\nautonumber, created and modified time and by, button), columns with\n`editable: false` and columns with a `fieldFn` are always left out, even\nwhen `formFields` names them. Without `formTitle`, the heading is the\nview's `name`.\n\n## 3. See what a sent form adds\n\n![What happens when a form is sent: the fields start with the defaults and each value goes through valueParser; Submit checks required fields, the email, URL and phone formats and the column's validate; the record gets its defaults and an id and is appended to the grid, then onRowAdd runs; onSubmit settles into Thank you or the error, and in a base it runs the \"A form is sent\" automations.](/docs-media/base-forms.svg)\n\nPress Submit and the form runs its checks first\n([What the form checks](#what-the-form-checks)). When they pass, it builds\nthe record the way the row adder builds a new row, from three layers, each\nwinning over the one before:\n\n1. Each field's own new-row value: a `fieldProps.default`, today for a date\n with `defaultToday`, the next autonumber, the created time, the current\n user for created by.\n2. The grid's `rowAdder.defaults()`. In a base, set it in the table's\n `props`.\n3. What the form's fields show.\n\nInside `<SvBase tables>` every new record also gets an `id`, even in a table\nwhose `props` set `rowAdder: false`.\n\nThe first two layers also fill the form when it opens: a field the form\nasks for starts with the value the new record would get, and the person\ncan change it. A field the form does not ask for still gets its value, so a\ncandidate who never sees Stage lands in Applied because of\n`default: 'Applied'`.\n\nThe record is appended to the grid, then the grid's `onRowAdd` fires with\nit, and with `tables` the base hands the whole list to `onTablesChange`:\n\n```svelte\n<SvBase bind:tables editable onRowAdd={(e: { row: Record<string, unknown> }) => console.log('new candidate', e.row)} />\n```\n\nThe form then shows \"Thank you\" and \"The record was added.\" with a \"Submit\nanother\" button, which starts a new record with the defaults again. A form\nview starts a new record each time it opens, so switching to another view\ndrops what was typed.\n\nA sent record holds values in the shapes the cells use:\n\n| Field type | Value |\n|---|---|\n| `text`, `longText`, `email`, `url`, `phone` | A string, as typed |\n| `number` | A number, rounded to the field's precision |\n| `date` without time | `'2026-11-02'` |\n| `singleSelect` | The option's `value` |\n| `link` | An array of record ids, also with `multiple: false`: `['r2']` |\n| `attachment` | An array of [attachments](../fields.md#attachments) |\n| `user` | The person's id |\n\nEach value goes through the same coercion and column `valueParser` as a\ncell edit, so a custom field type parses the same in a form. A field left\nblank is not in the record. A field that showed a default and was cleared\nis sent empty (`''`, `null` or `[]`, as its editor leaves it): the person\nremoved the default, so it does not come back.\n\n## 4. Put the form on a public page\n\nCandidates should not open your base. Give them a page that draws only the\nform and posts what they send to your server, while the team keeps working\nin the base.\n\n`SvBaseForm` is the form the view draws, as a component. It reads its fields\nfrom a grid through that grid's api, so the page mounts a grid with the\nCandidates columns and no rows, out of sight:\n\n```svelte\n<!-- src/routes/apply/+page.svelte -->\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n import { SvBaseForm, enableBase, registerLinkedTable } from '@svgrid/enterprise/base'\n import { APPLY_FIELDS, candidateColumns } from '$lib/hiring'\n\n enableBase()\n\n let { data }: { data: { roles: Array<{ id: string; name: string }> } } = $props()\n\n // The record picker for Role lists the open roles, and only those. In an\n // effect: it runs in the browser only (the list is page-wide, so a server\n // render must not set it for every visitor), and it unregisters on leave.\n $effect(() => registerLinkedTable({ id: 'roles', name: 'Roles', primaryField: 'name', rows: () => data.roles }))\n\n // Raw: the form finds the grid by the api object itself.\n let api = $state.raw<any>(null)\n\n // The form waits on the Promise: thanks when it resolves, the message when it rejects.\n async function send(row: Record<string, unknown>) {\n const res = await fetch('/apply', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(row),\n })\n if (!res.ok) throw new Error('Your application did not reach us. Press Send application again.')\n }\n</script>\n\n<div class=\"store\" aria-hidden=\"true\">\n <SvGrid data={[]} columns={candidateColumns} onApiReady={(a) => (api = a)} />\n</div>\n\n{#if api}\n <SvBaseForm\n {api}\n fields={APPLY_FIELDS}\n required={['name', 'email', 'role', 'resume']}\n title=\"Apply to Acme\"\n description=\"Tell us about yourself. We reply to every application within a week.\"\n submitLabel=\"Send application\"\n onSubmit={send}\n />\n{/if}\n\n<style>\n .store { position: absolute; width: 1px; height: 1px; overflow: hidden; visibility: hidden; }\n</style>\n```\n\n```ts\n// src/routes/apply/+page.server.ts\ndeclare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }\n\nexport async function load() {\n return { roles: await db.openRoles() }\n}\n```\n\nA required field shows a red asterisk after its label. Press \"Send\napplication\" with Email empty and its box turns red, with \"Email is\nrequired\" under it; nothing is sent. Type `ana@` and the line reads \"Not a\nvalid email address\". The message goes away as soon as the field gets a new\nvalue.\n\n`send` returns a Promise, so the form waits for the server, with the button\ndisabled. When the Promise resolves, the form shows \"Thank you\". When it\nrejects, the form takes the row back out of the hidden grid, keeps every\nfield as it was, and shows the error's message above the button; pressing\nthe button again sends the same record. An error with no message shows \"The\nrecord could not be sent. Try again.\" An `onSubmit` that returns nothing\nshows \"Thank you\" at once.\n\nThe form draws with the `--sg-*` tokens (`--sg-bg`, `--sg-fg`,\n`--sg-border`, `--sg-muted`, `--sg-accent`, `--sg-accent-fg`,\n`--sg-danger`, `--sg-font`), so the page's theme styles it.\n\n## 5. Prefill hidden values from the URL\n\nA job post links to `/apply?role=r2&source=Referral`. The candidate should\nnot pick the role again, and should never see Source. Read both in `load`,\ncheck them, and hand them to the hidden grid as its `rowAdder.defaults`:\nthe form starts every record from them, and what is typed wins over them.\nThis `load` replaces the one in step 4:\n\n```ts\n// src/routes/apply/+page.server.ts\nimport { SOURCES } from '$lib/hiring'\n\ndeclare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }\n\nexport async function load({ url }: { url: URL }) {\n const roles = await db.openRoles()\n const role = roles.find((r) => r.id === url.searchParams.get('role'))?.id ?? null\n const asked = url.searchParams.get('source')\n const source = SOURCES.some((s) => s.value === asked) ? asked : 'Careers page'\n return { roles, role, source }\n}\n```\n\nIn the page, leave the role out of the fields when the link named one, and\ngive the hidden grid the defaults. Source is not among the fields, so it\nstays hidden and still lands in the record. The rest of the page is as in\nstep 4:\n\n```svelte\n<script lang=\"ts\">\n import { APPLY_FIELDS } from '$lib/hiring'\n // ...the other imports, registerLinkedTable, api and send from step 4\n\n let { data }: { data: { roles: Array<{ id: string; name: string }>; role: string | null; source: string } } = $props()\n\n const fields = $derived(data.role ? APPLY_FIELDS.filter((f) => f !== 'role') : APPLY_FIELDS)\n const rowAdder = $derived({\n defaults: () => ({ source: data.source, ...(data.role ? { role: [data.role] } : {}) }),\n })\n</script>\n\n<div class=\"store\" aria-hidden=\"true\">\n <SvGrid data={[]} columns={candidateColumns} {rowAdder} onApiReady={(a) => (api = a)} />\n</div>\n\n{#if api}\n <SvBaseForm {api} {fields} required={['name', 'email', 'resume']} submitLabel=\"Send application\" onSubmit={send} />\n{/if}\n```\n\nA link value is an array of ids, so the default is `[data.role]`. Drop\n`'role'` from `required` too: a required id that is not among the fields is\nignored, but leaving it there reads as if the role were still asked for.\n\n## 6. Upload the resume\n\nWith no uploader, a file added in the form stays in the browser as a `blob:`\nURL, and the server receives a link it cannot open. Set an uploader on the\npublic page:\n\n```ts\nimport { setAttachmentUploader } from '@svgrid/enterprise/base'\n\nsetAttachmentUploader(async (file, { signal, onProgress }) => {\n const res = await fetch(`/apply/upload?name=${encodeURIComponent(file.name)}`, {\n method: 'PUT',\n body: file,\n signal,\n headers: { 'content-type': file.type || 'application/octet-stream' },\n })\n if (!res.ok) throw new Error(res.status === 413 ? 'Larger than 10 MB' : `Upload failed (${res.status})`)\n onProgress(1)\n const { url } = (await res.json()) as { url: string }\n return { id: url, url, name: file.name, type: file.type, size: file.size }\n})\n```\n\n```ts\n// src/routes/apply/upload/+server.ts\nimport { error, json } from '@sveltejs/kit'\n\n// Returns the stored file's URL, under https://files.example.com/resumes/.\ndeclare const storage: { put: (key: string, body: ArrayBuffer, type: string) => Promise<string> }\n\nconst TYPES = new Set([\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n])\n\nexport async function PUT({ request, url }: { request: Request; url: URL }) {\n const type = request.headers.get('content-type') ?? ''\n if (!TYPES.has(type)) error(415, 'Send a PDF or a Word file')\n const body = await request.arrayBuffer()\n if (body.byteLength > 10 * 1024 * 1024) error(413, 'Larger than 10 MB')\n const name = (url.searchParams.get('name') ?? 'resume').replace(/[^\\w.-]+/g, '_').slice(0, 100)\n return json({ url: await storage.put(`resumes/${crypto.randomUUID()}-${name}`, body, type) })\n}\n```\n\nClick the Resume box (\"Add files\") and the attachment dialog opens: pick,\ndrop or paste a file, or paste a URL. Before uploading, the dialog checks\nthe field's `maxFiles` (default 20), `maxSize` (default 25 MB) and\n`accept`, and lists each refused file with its name and the reason:\n\"At most 1 file\", \"Larger than 10 MB\", \"Not an accepted type\". A file added\nby URL gets the `maxFiles` and `accept` checks; its type comes from the\nname's extension, so with `accept: '.pdf,.doc,.docx'` a link to `cv.pdf` is\ntaken and a link with no extension is refused. A file that fails to upload\nstays in the dialog with Retry. The upload runs when the file is added, not\nwhen the form is sent, and Done waits for uploads still running.\n\nAn uploader for one column only goes in that column's `fieldProps.upload`;\nit wins over the app-wide one. Both get the file, an abort signal (aborted\nwhen the candidate removes the file or cancels the dialog), `onProgress`,\nthe column id and `row`, which in a form is what the fields show so far,\nwith no record id yet.\n\n## 7. Check it again on the server\n\nThe form's checks help a person filling it in. Anyone can post to `/apply`\nwithout it, so the endpoint checks every field again with the same\n`linkHref` the form uses for email, URL and phone, keeps only the fields a\ncandidate may set, and sets the team's fields itself:\n\n```ts\n// src/routes/apply/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport { linkHref } from '@svgrid/enterprise/base'\nimport { SOURCES } from '$lib/hiring'\nimport { automations } from '$lib/server/automations'\n\ndeclare const db: {\n roleIsOpen: (id: string) => Promise<boolean>\n insertCandidate: (row: Record<string, unknown>) => Promise<string>\n}\n\n// Where the upload endpoint in step 6 stores resumes.\nconst FILES = 'https://files.example.com/resumes/'\n\nexport async function POST({ request }: { request: Request }) {\n const body = (await request.json()) as Record<string, unknown>\n const text = (k: string, max = 200) => {\n const v = body[k]\n return typeof v === 'string' ? v.trim().slice(0, max) : ''\n }\n\n const name = text('name')\n if (!name) error(400, 'Candidate is required')\n const email = text('email')\n if (!linkHref('email', email)) error(400, 'Not a valid email address')\n const phone = text('phone', 40)\n if (phone && !linkHref('phone', phone)) error(400, 'Not a valid phone number')\n const portfolio = text('portfolio', 500)\n if (portfolio && !linkHref('url', portfolio)) error(400, 'Not a valid web address')\n\n const role = Array.isArray(body.role) ? String(body.role[0] ?? '') : ''\n if (!(await db.roleIsOpen(role))) error(400, 'Pick an open role')\n\n const resume = Array.isArray(body.resume) ? body.resume.slice(0, 1) : []\n if (!resume.length || !resume.every((a) => typeof a?.url === 'string' && a.url.startsWith(FILES))) error(400, 'Upload a resume')\n\n const years = body.years == null ? null : Number(body.years)\n if (years != null && !(Number.isInteger(years) && years >= 0 && years <= 60)) error(400, 'Years is not a whole number')\n\n const start = text('start', 10)\n if (start && !/^\\d{4}-\\d{2}-\\d{2}$/.test(start)) error(400, 'Earliest start is not a date')\n\n const source = SOURCES.some((s) => s.value === body.source) ? body.source : 'Careers page'\n\n const id = await db.insertCandidate({\n name, email, phone, role: [role], resume, portfolio, years, start, source,\n notes: text('notes', 5000),\n // Never from the request: these belong to the team.\n stage: 'Applied', recruiter: null, applied: new Date().toISOString(),\n })\n // Step 8: the \"A form is sent\" automations that run on the server.\n await automations.formSubmitted('candidates', id, 'apply')\n return json({ id })\n}\n```\n\nThe form shows the `error()` message only if `send` passes it on; the one\nin step 4 shows its own line for any failure.\n\nTo see new applications in the base without a reload, give the Candidates\ntable a `source` with `realtime`:\n[Keep a base in a database](./data.md#changes-made-elsewhere).\n\n## 8. Run an automation when a form is sent\n\nIn the Automations dialog the trigger is \"A form is sent\", with a Form\npicker: \"Any form of this table\" or one form view. In code it is\n`formSubmitted`, and `view` names the form:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nexport const candidateAutomations: BaseAutomation[] = [\n {\n id: 'new-application',\n name: 'Announce a new application',\n enabled: true,\n trigger: { type: 'formSubmitted', view: 'apply' },\n actions: [{ type: 'notify', message: 'New application from {Candidate}', severity: 'info' }],\n },\n {\n id: 'thank-you-email',\n name: 'Thank the candidate',\n enabled: true,\n runOn: 'server',\n trigger: { type: 'formSubmitted', view: 'apply' },\n actions: [\n {\n type: 'email',\n to: '{Email}',\n subject: 'We got your application',\n body: 'Hi {Candidate}, thank you for applying. We reply within a week.',\n },\n ],\n },\n]\n```\n\nPut them on the table (`automations: candidateAutomations`) and add one\n`<SvToaster />` from `@svgrid/grid` for the notice. In the base, a form view\nsends its record to the table's automations with the view's `id`. They need\n`<SvBase tables>`: with `data` and `columns` a form still adds records, but\nno automation runs.\n\nThe public page has no base and no browser runner, so the endpoint in step 7\ntells the [automation server](./automations.md#on-the-server) after the\ninsert. The view id there is whatever string your automations name. Only\nautomations with `runOn: 'server'` run on the server. If it has not seen\nthe record yet, it reads the table again first, and that reading also runs\nthe table's \"A record is created\" server automations for the new record.\n\n## SvBaseForm props\n\n| Prop | Type | Default | What it does |\n|---|---|---|---|\n| `api` | grid api | required | The api of the grid the record is added to, from its `onApiReady`. Nothing draws until that grid has drawn once. |\n| `fields` | `ReadonlyArray<string>` | every field a person can fill in | Column ids, in order. An id that is not such a field is skipped. |\n| `required` | `ReadonlyArray<string>` | `[]` | Column ids that must have a value before the record is added. |\n| `title` | `string` | `'New record'` | The heading. |\n| `description` | `string` | `''` | The line under the heading. |\n| `submitLabel` | `string` | `'Submit'` | The button's text. |\n| `defaults` | `() => Record<string, unknown>` | | Values each record from this form starts with. The grid's `rowAdder.defaults()` wins over them. Called once per record. `<SvBase tables>` passes one that gives an `id`. |\n| `onSubmit` | `(row: Record<string, unknown>) => void \\| Promise<unknown>` | | Called after the row was appended to the grid and the grid's `onRowAdd` ran. A Promise keeps the button disabled until it settles: resolved shows \"Thank you\", rejected takes the row back out of the grid, keeps the fields and shows the error's message. |\n\n## Form view keys\n\n| Key | Read as |\n|---|---|\n| `type` | `'form'` |\n| `name` | The view's name in the menu; the heading when there is no `formTitle` |\n| `formFields` | The fields it asks for, in order |\n| `formTitle` | The heading |\n| `formDescription` | The line under it |\n| `formRequired` | Column ids that must have a value, as `required` on `SvBaseForm` |\n| `formSubmitLabel` | The button's text (default `'Submit'`) |\n\nA record the view sends reaches `onRowAdd`, `onTablesChange` and the\n`formSubmitted` automations, which get the view's `id`.\n\n## What the form checks\n\n- **Required**: empty means no value, an empty string or an empty list. A\n checkbox that is off and a number that is 0 count as filled. The message\n is \"{header} is required\".\n- **Number and duration**: the editor refuses text that is not a number\n (\"Not a number\") and a negative where `allowNegative: false` (\"Negative\n numbers are not allowed\"), and keeps the box open. A click outside the\n box while it shows the error drops what was typed. A value is rounded to\n the field's precision.\n- **Attachment**: `maxFiles`, `maxSize` and `accept`, file by file, before\n uploading. A file added by URL is checked against `maxFiles` and `accept`\n (by the name's extension); its size is not known, so `maxSize` does not\n apply.\n- **Email, URL, phone**: on submit, a value must be one the cell can link:\n an address for `mailto:`, an http or https address (a bare host such as\n `svgrid.com/docs` counts), or 3 to 20 digits with an optional leading `+`\n and spaces, dots, dashes or parentheses. The messages are \"Not a valid\n email address\", \"Not a valid web address\" and \"Not a valid phone number\".\n An empty field is not checked.\n- **The column's `validate`**: on submit, the form calls it as the grid\n does, with `value`, `row` (what the fields show), `rowIndex: -1` and\n `column`. `false` shows \"{header} is not valid\"; a string shows that\n string. It runs on empty fields too, and it blocks the submit even\n without `rejectInvalid`.\n- **Select**: only the field's options. Text that matches none shows \"No\n option matches\"; a form never offers \"Add option\".\n- **Link**: only records of the linked table, plus `Create \"...\"` for the\n typed name when that table has `create`.\n\nA failed check shows its message under the field and nothing is sent. The\nmessage goes away when that field gets a new value.\n\n## Pitfalls\n\n- **\"Thank you\" waits only for a Promise.** If `onSubmit` posts but does\n not return the Promise (or throw), the form thanks the person before the\n server answers. Return it, as `send` in step 4 does.\n- **A rejected `onSubmit` comes after `onRowAdd`.** On a rejection the form\n takes the row back out of the grid, but anything your `onRowAdd` did with\n it stays done. Save in one of the two, not both.\n- **Automatic values come from the browser.** On the public page the hidden\n grid has no rows, so an autonumber is always 1, and a created time is the\n visitor's clock. Set them on the server.\n- **One form sets off two triggers.** In `<SvBase tables>`, a sent form runs\n the \"A record is created\" automations, then the \"A form is sent\" ones. An\n automation on each that does the same thing does it twice.\n- **Uploads outlive abandoned forms.** A file is uploaded when it is added,\n so a candidate who adds a resume and leaves leaves a file behind. Remove\n stored files no record points to.\n\n## Next\n\n- [Automations](./automations.md): the other triggers, and the server\n runner the public page reports to.\n- [Keep a base in a database](./data.md): give Candidates a source so\n applications show up for the team.\n- [Saved views](./views.md): the Kanban the recruiters work in, its stacks\n and colors.\n- [Linked records](./linked-records.md): the Role link and the Candidates\n list on each role.\n- [Field types](../fields.md#declare-columns-by-type): every type's\n `fieldProps`, including `default` and `defaultToday`.\n"
5186
+ "markdown": "# Collect records with forms\n\nA form view asks for some of a table's fields and adds a record when it is\nsent. Use it for records other people start: a bug report, an expense, a\njob application. This page builds a hiring tracker's application flow.\nCandidates apply through a form, the record lands in the Candidates table,\nand recruiters move it across a Kanban by stage.\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"680\"></div>\n\nIn the demo, pick the \"Apply\" view, fill in the form and press Submit, then\nswitch to \"Hiring pipeline\": the new candidate is a card in Applied.\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\n## 1. Declare the Candidates table\n\nKeep the fields in one module. The base imports them, and so do the public\npage and the server you build later on this page, so all three agree on\nfield ids and types.\n\n```ts\n// src/lib/hiring.ts\nimport type { BaseTable } from '@svgrid/enterprise/base'\n\nexport const STAGES = [\n { value: 'Applied', color: '#94a3b8' },\n { value: 'Phone screen', color: '#18bfff' },\n { value: 'Onsite', color: '#2d7ff9' },\n { value: 'Offer', color: '#fcb400' },\n { value: 'Hired', color: '#20c933' },\n { value: 'Rejected', color: '#f82b60' },\n]\nexport const SOURCES = [{ value: 'Careers page' }, { value: 'Referral' }, { value: 'Job board' }]\n\nexport const candidateColumns: BaseTable['columns'] = [\n { field: 'name', header: 'Candidate', fieldType: 'text' },\n { field: 'email', header: 'Email', fieldType: 'email' },\n { field: 'phone', header: 'Phone', fieldType: 'phone', description: 'With the country code.' },\n { field: 'role', header: 'Role', fieldType: 'link', fieldProps: { table: 'roles', multiple: false, inverse: 'candidates' } },\n {\n field: 'resume', header: 'Resume', fieldType: 'attachment',\n fieldProps: { accept: '.pdf,.doc,.docx', maxFiles: 1, maxSize: 10 * 1024 * 1024 },\n description: 'One PDF or Word file, up to 10 MB.',\n },\n { field: 'portfolio', header: 'Portfolio', fieldType: 'url', description: 'A site, a repository or a design portfolio.' },\n { field: 'years', header: 'Years of experience', fieldType: 'number', fieldProps: { format: 'integer', allowNegative: false } },\n { field: 'start', header: 'Earliest start', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'notes', header: 'Notes', fieldType: 'longText' },\n // The team's fields. The form leaves them out.\n { field: 'stage', header: 'Stage', fieldType: 'singleSelect', fieldProps: { options: STAGES, default: 'Applied' } },\n { field: 'source', header: 'Source', fieldType: 'singleSelect', fieldProps: { options: SOURCES } },\n { field: 'recruiter', header: 'Recruiter', fieldType: 'user' },\n { field: 'applied', header: 'Applied', fieldType: 'createdTime' },\n]\n\nexport const roleColumns: BaseTable['columns'] = [\n { field: 'name', header: 'Role', fieldType: 'text' },\n { field: 'candidates', header: 'Candidates', fieldType: 'link', fieldProps: { table: 'candidates', multiple: true, inverse: 'role' } },\n]\n\n/** What a candidate fills in, in order. */\nexport const APPLY_FIELDS: string[] = ['name', 'email', 'phone', 'role', 'resume', 'portfolio', 'years', 'start', 'notes']\n```\n\nThe form labels each field with the column's `header`, the type's icon in\nfront of it. A column's `description` is the help text: the form shows it in\nsmall grey type under the field, and the grid shows it on the info mark in\nthe header.\n\n## 2. Add the form view\n\nA form is a view, next to the pipeline and the grid:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, setFieldUsers, type BaseTable } from '@svgrid/enterprise/base'\n import { APPLY_FIELDS, candidateColumns, roleColumns } from '$lib/hiring'\n\n enableBase()\n setFieldUsers([{ id: 'u1', name: 'Ana Ruiz' }, { id: 'u2', name: 'Ben Okafor' }])\n\n let { candidates, roles }: { candidates: Record<string, unknown>[]; roles: Record<string, unknown>[] } = $props()\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'candidates',\n name: 'Candidates',\n primaryField: 'name',\n data: candidates,\n columns: candidateColumns,\n views: [\n { id: 'pipeline', name: 'Pipeline', type: 'kanban', stackBy: 'stage' },\n { id: 'all', name: 'All candidates', type: 'grid', color: { mode: 'field', field: 'stage' } },\n {\n id: 'apply',\n name: 'Apply',\n type: 'form',\n formFields: APPLY_FIELDS,\n formTitle: 'Join the team',\n formDescription: 'Tell us about yourself. We reply to every application within a week.',\n formRequired: ['name', 'email', 'role', 'resume'],\n formSubmitLabel: 'Send application',\n },\n ],\n },\n { id: 'roles', name: 'Roles', primaryField: 'name', data: roles, columns: roleColumns },\n ])\n</script>\n\n<SvBase bind:tables editable expandRows containerHeight={640} onTablesChange={(t) => console.log('save', t)} />\n```\n\nPick \"Apply\" in the view menu. The grid stays mounted underneath and the\nform covers it: a card with \"Join the team\" as the heading, the description\nunder it, and one box per field. A click on a box opens the editor the cell\nuses: the select panel for a select, the record picker for Role, the date\npicker for Earliest start, the attachment dialog for Resume, the number box\nfor Years of experience. Tab and Shift+Tab move to the next or previous\nfield from inside an editor.\n\n![The demo's Apply form view: Candidate filled in as Ana Ruiz, Email as ana@ with a red border and \"Not a valid email address\" under it after Submit, Role set to Product designer, Resume and Notes still empty.](/docs-media/base-forms.png)\n\nFor a form view, the view bar keeps the view menu and, when the base runs\nautomations, the Automations button. Hide fields, Filter, Sort, the record\ncount and search are gone.\n\nWithout `formFields`, the form asks for every field a person can fill in:\nthe primary field first, then the rest in the grid's column order, hidden\ncolumns included. Computed types (formula, lookup, rollup, count,\nautonumber, created and modified time and by, button), columns with\n`editable: false` and columns with a `fieldFn` are always left out, even\nwhen `formFields` names them. Without `formTitle`, the heading is the\nview's `name`.\n\n## 3. See what a sent form adds\n\n![What happens when a form is sent: the fields start with the defaults and each value goes through valueParser; Submit checks required fields, the email, URL and phone formats and the column's validate; the record gets its defaults and an id and is appended to the grid, then onRowAdd runs; onSubmit settles into Thank you or the error, and in a base it runs the \"A form is sent\" automations.](/docs-media/base-forms.svg)\n\nPress Submit and the form runs its checks first\n([What the form checks](#what-the-form-checks)). When they pass, it builds\nthe record the way the row adder builds a new row, from three layers, each\nwinning over the one before:\n\n1. Each field's own new-row value: a `fieldProps.default`, today for a date\n with `defaultToday`, the next autonumber, the created time, the current\n user for created by.\n2. The grid's `rowAdder.defaults()`. In a base, set it in the table's\n `props`.\n3. What the form's fields show.\n\nInside `<SvBase tables>` every new record also gets an `id`, even in a table\nwhose `props` set `rowAdder: false`.\n\nThe first two layers also fill the form when it opens: a field the form\nasks for starts with the value the new record would get, and the person\ncan change it. A field the form does not ask for still gets its value, so a\ncandidate who never sees Stage lands in Applied because of\n`default: 'Applied'`.\n\nThe record is appended to the grid, then the grid's `onRowAdd` fires with\nit, and with `tables` the base hands the whole list to `onTablesChange`:\n\n```svelte\n<SvBase bind:tables editable onRowAdd={(e: { row: Record<string, unknown> }) => console.log('new candidate', e.row)} />\n```\n\nThe form then shows \"Thank you\" and \"The record was added.\" with a \"Submit\nanother\" button, which starts a new record with the defaults again. A form\nview starts a new record each time it opens, so switching to another view\ndrops what was typed.\n\nA sent record holds values in the shapes the cells use:\n\n| Field type | Value |\n|---|---|\n| `text`, `longText`, `email`, `url`, `phone` | A string, as typed |\n| `number` | A number, rounded to the field's precision |\n| `date` without time | `'2026-11-02'` |\n| `singleSelect` | The option's `value` |\n| `link` | An array of record ids, also with `multiple: false`: `['r2']` |\n| `attachment` | An array of [attachments](../fields.md#attachments) |\n| `user` | The person's id |\n\nEach value goes through the same coercion and column `valueParser` as a\ncell edit, so a custom field type parses the same in a form. A field left\nblank is not in the record. A field that showed a default and was cleared\nis sent empty (`''`, `null` or `[]`, as its editor leaves it): the person\nremoved the default, so it does not come back.\n\n## 4. Put the form on a public page\n\nCandidates should not open your base. Give them a page that draws only the\nform and posts what they send to your server, while the team keeps working\nin the base.\n\n`SvBaseForm` is the form the view draws, as a component. It reads its fields\nfrom a grid through that grid's api, so the page mounts a grid with the\nCandidates columns and no rows, out of sight:\n\n```svelte\n<!-- src/routes/apply/+page.svelte -->\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n import { SvBaseForm, enableBase, registerLinkedTable } from '@svgrid/enterprise/base'\n import { APPLY_FIELDS, candidateColumns } from '$lib/hiring'\n\n enableBase()\n\n let { data }: { data: { roles: Array<{ id: string; name: string }> } } = $props()\n\n // The record picker for Role lists the open roles, and only those. In an\n // effect: it runs in the browser only (the list is page-wide, so a server\n // render must not set it for every visitor), and it unregisters on leave.\n $effect(() => registerLinkedTable({ id: 'roles', name: 'Roles', primaryField: 'name', rows: () => data.roles }))\n\n // Raw: the form finds the grid by the api object itself.\n let api = $state.raw<any>(null)\n\n // The form waits on the Promise: thanks when it resolves, the message when it rejects.\n async function send(row: Record<string, unknown>) {\n const res = await fetch('/apply', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(row),\n })\n if (!res.ok) throw new Error('Your application did not reach us. Press Send application again.')\n }\n</script>\n\n<div class=\"store\" aria-hidden=\"true\">\n <SvGrid data={[]} columns={candidateColumns} onApiReady={(a) => (api = a)} />\n</div>\n\n{#if api}\n <SvBaseForm\n {api}\n fields={APPLY_FIELDS}\n required={['name', 'email', 'role', 'resume']}\n title=\"Apply to Acme\"\n description=\"Tell us about yourself. We reply to every application within a week.\"\n submitLabel=\"Send application\"\n onSubmit={send}\n />\n{/if}\n\n<style>\n .store { position: absolute; width: 1px; height: 1px; overflow: hidden; visibility: hidden; }\n</style>\n```\n\n```ts\n// src/routes/apply/+page.server.ts\ndeclare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }\n\nexport async function load() {\n return { roles: await db.openRoles() }\n}\n```\n\nA required field shows a red asterisk after its label. Press \"Send\napplication\" with Email empty and its box turns red, with \"Email is\nrequired\" under it; nothing is sent. Type `ana@` and the line reads \"Not a\nvalid email address\". The message goes away as soon as the field gets a new\nvalue.\n\n`send` returns a Promise, so the form waits for the server, with the button\ndisabled. When the Promise resolves, the form shows \"Thank you\". When it\nrejects, the form takes the row back out of the hidden grid, keeps every\nfield as it was, and shows the error's message above the button; pressing\nthe button again sends the same record. An error with no message shows \"The\nrecord could not be sent. Try again.\" An `onSubmit` that returns nothing\nshows \"Thank you\" at once.\n\nThe form draws with the `--sg-*` tokens (`--sg-bg`, `--sg-fg`,\n`--sg-border`, `--sg-muted`, `--sg-accent`, `--sg-accent-fg`,\n`--sg-danger`, `--sg-font`), so the page's theme styles it.\n\n## 5. Prefill hidden values from the URL\n\nA job post links to `/apply?role=r2&source=Referral`. The candidate should\nnot pick the role again, and should never see Source. Read both in `load`,\ncheck them, and hand them to the hidden grid as its `rowAdder.defaults`:\nthe form starts every record from them, and what is typed wins over them.\nThis `load` replaces the one in step 4:\n\n```ts\n// src/routes/apply/+page.server.ts\nimport { SOURCES } from '$lib/hiring'\n\ndeclare const db: { openRoles: () => Promise<Array<{ id: string; name: string }>> }\n\nexport async function load({ url }: { url: URL }) {\n const roles = await db.openRoles()\n const role = roles.find((r) => r.id === url.searchParams.get('role'))?.id ?? null\n const asked = url.searchParams.get('source')\n const source = SOURCES.some((s) => s.value === asked) ? asked : 'Careers page'\n return { roles, role, source }\n}\n```\n\nIn the page, leave the role out of the fields when the link named one, and\ngive the hidden grid the defaults. Source is not among the fields, so it\nstays hidden and still lands in the record. The rest of the page is as in\nstep 4:\n\n```svelte\n<script lang=\"ts\">\n import { APPLY_FIELDS } from '$lib/hiring'\n // ...the other imports, registerLinkedTable, api and send from step 4\n\n let { data }: { data: { roles: Array<{ id: string; name: string }>; role: string | null; source: string } } = $props()\n\n const fields = $derived(data.role ? APPLY_FIELDS.filter((f) => f !== 'role') : APPLY_FIELDS)\n const rowAdder = $derived({\n defaults: () => ({ source: data.source, ...(data.role ? { role: [data.role] } : {}) }),\n })\n</script>\n\n<div class=\"store\" aria-hidden=\"true\">\n <SvGrid data={[]} columns={candidateColumns} {rowAdder} onApiReady={(a) => (api = a)} />\n</div>\n\n{#if api}\n <SvBaseForm {api} {fields} required={['name', 'email', 'resume']} submitLabel=\"Send application\" onSubmit={send} />\n{/if}\n```\n\nA link value is an array of ids, so the default is `[data.role]`. Drop\n`'role'` from `required` too: a required id that is not among the fields is\nignored, but leaving it there reads as if the role were still asked for.\n\n## 6. Upload the resume\n\nWith no uploader, a file added in the form stays in the browser as a `blob:`\nURL, and the server receives a link it cannot open. Set an uploader on the\npublic page:\n\n```ts\nimport { setAttachmentUploader } from '@svgrid/enterprise/base'\n\nsetAttachmentUploader(async (file, { signal, onProgress }) => {\n const res = await fetch(`/apply/upload?name=${encodeURIComponent(file.name)}`, {\n method: 'PUT',\n body: file,\n signal,\n headers: { 'content-type': file.type || 'application/octet-stream' },\n })\n if (!res.ok) throw new Error(res.status === 413 ? 'Larger than 10 MB' : `Upload failed (${res.status})`)\n onProgress(1)\n const { url } = (await res.json()) as { url: string }\n return { id: url, url, name: file.name, type: file.type, size: file.size }\n})\n```\n\n```ts\n// src/routes/apply/upload/+server.ts\nimport { error, json } from '@sveltejs/kit'\n\n// Returns the stored file's URL, under https://files.example.com/resumes/.\ndeclare const storage: { put: (key: string, body: ArrayBuffer, type: string) => Promise<string> }\n\nconst TYPES = new Set([\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n])\n\nexport async function PUT({ request, url }: { request: Request; url: URL }) {\n const type = request.headers.get('content-type') ?? ''\n if (!TYPES.has(type)) error(415, 'Send a PDF or a Word file')\n const body = await request.arrayBuffer()\n if (body.byteLength > 10 * 1024 * 1024) error(413, 'Larger than 10 MB')\n const name = (url.searchParams.get('name') ?? 'resume').replace(/[^\\w.-]+/g, '_').slice(0, 100)\n return json({ url: await storage.put(`resumes/${crypto.randomUUID()}-${name}`, body, type) })\n}\n```\n\nClick the Resume box (\"Add files\") and the attachment dialog opens: pick,\ndrop or paste a file, or paste a URL. Before uploading, the dialog checks\nthe field's `maxFiles` (default 20), `maxSize` (default 25 MB) and\n`accept`, and lists each refused file with its name and the reason:\n\"At most 1 file\", \"Larger than 10 MB\", \"Not an accepted type\". A file added\nby URL gets the `maxFiles` and `accept` checks; its type comes from the\nname's extension, so with `accept: '.pdf,.doc,.docx'` a link to `cv.pdf` is\ntaken and a link with no extension is refused. A file that fails to upload\nstays in the dialog with Retry. The upload runs when the file is added, not\nwhen the form is sent, and Done waits for uploads still running.\n\nAn uploader for one column only goes in that column's `fieldProps.upload`;\nit wins over the app-wide one. Both get the file, an abort signal (aborted\nwhen the candidate removes the file or cancels the dialog), `onProgress`,\nthe column id and `row`, which in a form is what the fields show so far,\nwith no record id yet.\n\n## 7. Check it again on the server\n\nThe form's checks help a person filling it in. Anyone can post to `/apply`\nwithout it, so the endpoint checks every field again with the same\n`linkHref` the form uses for email, URL and phone, keeps only the fields a\ncandidate may set, and sets the team's fields itself:\n\n```ts\n// src/routes/apply/+server.ts\nimport { error, json } from '@sveltejs/kit'\nimport { linkHref } from '@svgrid/enterprise/base'\nimport { SOURCES } from '$lib/hiring'\nimport { automations } from '$lib/server/automations'\n\ndeclare const db: {\n roleIsOpen: (id: string) => Promise<boolean>\n insertCandidate: (row: Record<string, unknown>) => Promise<string>\n}\n\n// Where the upload endpoint in step 6 stores resumes.\nconst FILES = 'https://files.example.com/resumes/'\n\nexport async function POST({ request }: { request: Request }) {\n const body = (await request.json()) as Record<string, unknown>\n const text = (k: string, max = 200) => {\n const v = body[k]\n return typeof v === 'string' ? v.trim().slice(0, max) : ''\n }\n\n const name = text('name')\n if (!name) error(400, 'Candidate is required')\n const email = text('email')\n if (!linkHref('email', email)) error(400, 'Not a valid email address')\n const phone = text('phone', 40)\n if (phone && !linkHref('phone', phone)) error(400, 'Not a valid phone number')\n const portfolio = text('portfolio', 500)\n if (portfolio && !linkHref('url', portfolio)) error(400, 'Not a valid web address')\n\n const role = Array.isArray(body.role) ? String(body.role[0] ?? '') : ''\n if (!(await db.roleIsOpen(role))) error(400, 'Pick an open role')\n\n const resume = Array.isArray(body.resume) ? body.resume.slice(0, 1) : []\n if (!resume.length || !resume.every((a) => typeof a?.url === 'string' && a.url.startsWith(FILES))) error(400, 'Upload a resume')\n\n const years = body.years == null ? null : Number(body.years)\n if (years != null && !(Number.isInteger(years) && years >= 0 && years <= 60)) error(400, 'Years is not a whole number')\n\n const start = text('start', 10)\n if (start && !/^\\d{4}-\\d{2}-\\d{2}$/.test(start)) error(400, 'Earliest start is not a date')\n\n const source = SOURCES.some((s) => s.value === body.source) ? body.source : 'Careers page'\n\n const id = await db.insertCandidate({\n name, email, phone, role: [role], resume, portfolio, years, start, source,\n notes: text('notes', 5000),\n // Never from the request: these belong to the team.\n stage: 'Applied', recruiter: null, applied: new Date().toISOString(),\n })\n // Step 8: the \"A form is sent\" automations that run on the server.\n await automations.formSubmitted('candidates', id, 'apply')\n return json({ id })\n}\n```\n\nThe form shows the `error()` message only if `send` passes it on; the one\nin step 4 shows its own line for any failure.\n\nTo see new applications in the base without a reload, give the Candidates\ntable a `source` with `realtime`:\n[Keep a base in a database](./data.md#changes-made-elsewhere).\n\n## 8. Run an automation when a form is sent\n\nIn the Automations dialog the trigger is \"A form is sent\", with a Form\npicker: \"Any form of this table\" or one form view. In code it is\n`formSubmitted`, and `view` names the form:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nexport const candidateAutomations: BaseAutomation[] = [\n {\n id: 'new-application',\n name: 'Announce a new application',\n enabled: true,\n trigger: { type: 'formSubmitted', view: 'apply' },\n actions: [{ type: 'notify', message: 'New application from {Candidate}', severity: 'info' }],\n },\n {\n id: 'thank-you-email',\n name: 'Thank the candidate',\n enabled: true,\n runOn: 'server',\n trigger: { type: 'formSubmitted', view: 'apply' },\n actions: [\n {\n type: 'email',\n to: '{Email}',\n subject: 'We got your application',\n body: 'Hi {Candidate}, thank you for applying. We reply within a week.',\n },\n ],\n },\n]\n```\n\nPut them on the table (`automations: candidateAutomations`) and add one\n`<SvToaster />` from `@svgrid/grid` for the notice. In the base, a form view\nsends its record to the table's automations with the view's `id`. They need\n`<SvBase tables>`: with `data` and `columns` a form still adds records, but\nno automation runs.\n\nThe public page has no base and no browser runner, so the endpoint in step 7\ntells the [automation server](./automations.md#on-the-server) after the\ninsert. The view id there is whatever string your automations name. Only\nautomations with `runOn: 'server'` run on the server. If it has not seen\nthe record yet, it reads the table again first, and that reading also runs\nthe table's \"A record is created\" server automations for the new record.\n\n## Show a field only for some answers\n\n<div data-docs-demo=\"711-base-form-logic\" data-height=\"720\"></div>\n\nIn the demo, pick Bug as the Topic and App version appears; switch to\nBilling and it gives way to Invoice number. The buttons on the right open\nthe form from prefilled links.\n\nA field can wait for an answer before it shows. `conditions` maps a column id\nto a [view bar filter](./views.md) over the other answers, the same\n`FieldFilter` the Filter button saves. On a form view the key is\n`formConditions`:\n\n```ts\nimport type { FieldFilter } from '@svgrid/enterprise/base'\n\nconst is = (column: string, value: string): FieldFilter => ({\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [{ column, kind: 'select', op: 'is', value }],\n})\n\nconst apply = {\n id: 'apply',\n name: 'Apply',\n type: 'form',\n formFields: ['name', 'email', 'employment', 'company', 'reason', 'otherReason'],\n formRequired: ['name', 'email', 'company', 'otherReason'],\n formConditions: {\n company: is('employment', 'Employed'),\n otherReason: is('reason', 'Other'),\n },\n}\n```\n\nWith `SvBaseForm` it is `conditions={{ company: is('employment', 'Employed') }}`.\n\nThe form checks the conditions each time an answer changes. While a\nfield's condition does not hold:\n\n- the field is not drawn, and Tab skips it;\n- it is not required and not checked, so `formRequired` can name it;\n- what was typed in it is cleared, and a field whose condition reads it\n hides too;\n- the record does not get it, not even its `fieldProps.default`.\n\nWhen the field shows again it starts with the value a new record gets. A\ncondition reads the answers by column id; a field the form does not ask\nfor is read as the new record would have it.\n\n## Fill the form from a link\n\n`prefill` fills fields from a link, the convention people already paste\ninto emails: `?prefill_<Field name>=value`. The name is the field's\n`header` or its column id, URL-encoded. `hide_<Field name>=true` keeps a\nfilled field out of sight and still sends it:\n\n```\nhttps://example.com/apply?prefill_Role=Product%20designer&prefill_Source=Referral&hide_Role=true\n```\n\nOn a form view, `formPrefill: true` reads the page's own URL. On a page,\npass it to `SvBaseForm`:\n\n```svelte\n<SvBaseForm {api} fields={APPLY_FIELDS} prefill />\n<SvBaseForm {api} fields={APPLY_FIELDS} prefill={page.url.searchParams} />\n<SvBaseForm {api} fields={APPLY_FIELDS} prefill={{ Role: 'r2', Source: 'Referral' }} />\n```\n\n`prefill` takes `true` (the page's URL, nothing during a server render), a\nURL or query string, `URLSearchParams`, or values by field name or column\nid. When it changes to other answers, the form starts a new record.\n\nEach value is read the way a pasted cell is:\n\n| Field type | `prefill_` value |\n|---|---|\n| text, email, URL, phone | As written |\n| number, currency, percent | The number as typed, `1,200` included; text that is no number is dropped |\n| checkbox | `true`, `1`, `yes`, `on` check it; anything else unchecks it |\n| date | `2026-11-02` |\n| single select | An option's value or label, any case |\n| multiple select | Values or labels, comma-separated |\n| user | A person's id, name or email |\n| link | Record ids or names, comma-separated |\n\nAn option the select does not have, a person nobody is, or a record that\ndoes not exist is dropped: a link never adds an option. Files and computed\nfields cannot be filled. A link's value goes over the field's default.\n`hide_` works only on a field the link filled; if a hidden value fails a\ncheck on Submit, the field shows with its message.\n\n`formPrefillLink` builds such a link from values by column id:\n\n```ts\nimport { formPrefillLink } from '@svgrid/enterprise/base'\n\nformPrefillLink('https://example.com/apply', { role: ['r2'], source: 'Referral' }, candidateColumns, { hide: ['role'] })\n// https://example.com/apply?prefill_Role=r2&prefill_Source=Referral&hide_Role=true\n```\n\nWith the columns, each parameter carries the field's `header`. A list is\njoined with commas, a `Date` written as `YYYY-MM-DD`, and the base URL's own\nquery and `#hash` are kept.\n\nThe link is typed by whoever sends it. Check every value on the server as in\n[step 7](#7-check-it-again-on-the-server).\n\n## SvBaseForm props\n\n| Prop | Type | Default | What it does |\n|---|---|---|---|\n| `api` | grid api | required | The api of the grid the record is added to, from its `onApiReady`. Nothing draws until that grid has drawn once. |\n| `fields` | `ReadonlyArray<string>` | every field a person can fill in | Column ids, in order. An id that is not such a field is skipped. |\n| `required` | `ReadonlyArray<string>` | `[]` | Column ids that must have a value before the record is added. |\n| `title` | `string` | `'New record'` | The heading. |\n| `description` | `string` | `''` | The line under the heading. |\n| `submitLabel` | `string` | `'Submit'` | The button's text. |\n| `defaults` | `() => Record<string, unknown>` | | Values each record from this form starts with. The grid's `rowAdder.defaults()` wins over them. Called once per record. `<SvBase tables>` passes one that gives an `id`. |\n| `conditions` | `Record<string, FieldFilter>` | | Column id -> when that field shows. A hidden field is not required, not checked and not sent ([Show a field only for some answers](#show-a-field-only-for-some-answers)). |\n| `prefill` | `boolean \\| string \\| URLSearchParams \\| Record<string, unknown>` (`FormPrefill`) | | Answers to start with: `true` reads the page's URL, a string or `URLSearchParams` is read for `prefill_` and `hide_`, an object gives values by field name or column id ([Fill the form from a link](#fill-the-form-from-a-link)). |\n| `onSubmit` | `(row: Record<string, unknown>) => void \\| Promise<unknown>` | | Called after the row was appended to the grid and the grid's `onRowAdd` ran. A Promise keeps the button disabled until it settles: resolved shows \"Thank you\", rejected takes the row back out of the grid, keeps the fields and shows the error's message. |\n\n## Form view keys\n\n| Key | Read as |\n|---|---|\n| `type` | `'form'` |\n| `name` | The view's name in the menu; the heading when there is no `formTitle` |\n| `formFields` | The fields it asks for, in order |\n| `formTitle` | The heading |\n| `formDescription` | The line under it |\n| `formRequired` | Column ids that must have a value, as `required` on `SvBaseForm` |\n| `formSubmitLabel` | The button's text (default `'Submit'`) |\n| `formConditions` | Column id -> when that field shows, as `conditions` on `SvBaseForm` |\n| `formPrefill` | `true` fills fields from the page's URL, as `prefill` on `SvBaseForm` |\n\nA record the view sends reaches `onRowAdd`, `onTablesChange` and the\n`formSubmitted` automations, which get the view's `id`.\n\n## What the form checks\n\n- **Required**: empty means no value, an empty string or an empty list. A\n checkbox that is off and a number that is 0 count as filled. The message\n is \"{header} is required\".\n- **Number and duration**: the editor refuses text that is not a number\n (\"Not a number\") and a negative where `allowNegative: false` (\"Negative\n numbers are not allowed\"), and keeps the box open. A click outside the\n box while it shows the error drops what was typed. A value is rounded to\n the field's precision.\n- **Attachment**: `maxFiles`, `maxSize` and `accept`, file by file, before\n uploading. A file added by URL is checked against `maxFiles` and `accept`\n (by the name's extension); its size is not known, so `maxSize` does not\n apply.\n- **Email, URL, phone**: on submit, a value must be one the cell can link:\n an address for `mailto:`, an http or https address (a bare host such as\n `svgrid.com/docs` counts), or 3 to 20 digits with an optional leading `+`\n and spaces, dots, dashes or parentheses. The messages are \"Not a valid\n email address\", \"Not a valid web address\" and \"Not a valid phone number\".\n An empty field is not checked.\n- **The column's `validate`**: on submit, the form calls it as the grid\n does, with `value`, `row` (what the fields show), `rowIndex: -1` and\n `column`. `false` shows \"{header} is not valid\"; a string shows that\n string. It runs on empty fields too, and it blocks the submit even\n without `rejectInvalid`.\n- **Select**: only the field's options. Text that matches none shows \"No\n option matches\"; a form never offers \"Add option\".\n- **Link**: only records of the linked table, plus `Create \"...\"` for the\n typed name when that table has `create`.\n\nA failed check shows its message under the field and nothing is sent. The\nmessage goes away when that field gets a new value.\n\n## Pitfalls\n\n- **\"Thank you\" waits only for a Promise.** If `onSubmit` posts but does\n not return the Promise (or throw), the form thanks the person before the\n server answers. Return it, as `send` in step 4 does.\n- **A rejected `onSubmit` comes after `onRowAdd`.** On a rejection the form\n takes the row back out of the grid, but anything your `onRowAdd` did with\n it stays done. Save in one of the two, not both.\n- **Automatic values come from the browser.** On the public page the hidden\n grid has no rows, so an autonumber is always 1, and a created time is the\n visitor's clock. Set them on the server.\n- **One form sets off two triggers.** In `<SvBase tables>`, a sent form runs\n the \"A record is created\" automations, then the \"A form is sent\" ones. An\n automation on each that does the same thing does it twice.\n- **Uploads outlive abandoned forms.** A file is uploaded when it is added,\n so a candidate who adds a resume and leaves leaves a file behind. Remove\n stored files no record points to.\n\n## Next\n\n- [Automations](./automations.md): the other triggers, and the server\n runner the public page reports to.\n- [Keep a base in a database](./data.md): give Candidates a source so\n applications show up for the team.\n- [Saved views](./views.md): the Kanban the recruiters work in, its stacks\n and colors.\n- [Linked records](./linked-records.md): the Role link and the Candidates\n list on each role.\n- [Field types](../fields.md#declare-columns-by-type): every type's\n `fieldProps`, including `default` and `defaultToday`.\n"
5051
5187
  },
5052
5188
  {
5053
5189
  "slug": "help/base/formulas",
5054
5190
  "path": "docs/help/base/formulas.md",
5055
5191
  "title": "Computed fields with formulas",
5056
5192
  "section": "SvGrid Base",
5057
- "markdown": "# Computed fields with formulas\n\nA formula field works out its value from the other fields of the same\nrecord: a stock value from quantity and unit cost, a status from a reorder\nlevel, a date 90 days after the last count. Nobody types into it, and views,\nfooters, charts and automations read it like any other field.\n\n<div data-docs-demo=\"515-base-inventory\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThis page builds a small inventory: Items with a quantity, a unit cost and a\nreorder level, then a Suppliers table they link to. In the demo above,\nchange an item's Qty or Unit cost and Stock value and the footer total\nfollow.\n\n## 1. Start with the stored fields\n\nFormulas need something to read. Declare the Items table with the fields\npeople type in:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n\n const items = [\n { id: 1, item: 'Arc floor lamp', qty: 4, unitCost: 410, reorder: 5, audited: '2026-09-05' },\n { id: 2, item: 'Table lamp, black', qty: 9, unitCost: 160, reorder: 4, audited: '2026-09-21' },\n { id: 3, item: 'Stoneware mug, slate', qty: 48, unitCost: 18, reorder: 24, audited: '2026-10-02' },\n { id: 4, item: 'Espresso cup, forest', qty: 0, unitCost: 12, reorder: 12, audited: '2026-08-14' },\n { id: 5, item: 'Bookshelf speaker', qty: 2, unitCost: 380, reorder: 2, audited: '2026-09-30' },\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'items',\n name: 'Items',\n primaryField: 'item',\n data: items,\n columns: [\n { field: 'item', header: 'Item', fieldType: 'text' },\n { field: 'qty', header: 'Qty', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n { field: 'unitCost', header: 'Unit cost', fieldType: 'number', fieldProps: { format: 'currency', symbol: '$', precision: 2 } },\n { field: 'reorder', header: 'Reorder level', fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'audited', header: 'Last counted', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n ],\n views: [{ id: 'stock', name: 'Stock', type: 'grid' }],\n },\n ])\n</script>\n\n<SvBase bind:tables editable sortable summary columnAdder fieldMenu containerHeight={560} />\n```\n\n`summary` turns on the footer row; `columnAdder` and `fieldMenu` let people\nadd and edit fields, which step 8 uses.\n\n## 2. Add a formula field\n\nAdd one column to the list:\n\n```ts\nconst stockValue = {\n field: 'value',\n header: 'Stock value',\n fieldType: 'formula',\n fieldProps: { formula: '{Qty} * {Unit cost}', result: 'currency', precision: 2, summary: 'sum' },\n}\n```\n\nA field reference is a name in braces. It matches a field's header or its\n`field` key, ignoring case and the spaces around it, so `{Qty}`, `{qty}` and\n`{ QTY }` all read `qty`, and `{unitCost}` reads the same field as\n`{Unit cost}`.\n\nThe formula is compiled once into a function. Each time a cell, a sort or a\nfooter needs the value, that function runs on the record, and `result` and\n`precision` decide how the number is shown:\n\n![A formula field from text to cell: {Qty} * {Unit cost} compiles once into a function that reads qty and unitCost; each record runs it (Arc floor lamp 4 x 410 = 1640, shown as $1,640.00); a formula over a rollup works the rollup out when it reads it ($3,080.00 / 2 = $1,540.00); a formula that does not compile shows #ERROR, and a row with no number shows an empty cell.](/docs-media/base-formulas.svg)\n\nWhat you see:\n\n- Arc floor lamp shows `$1,640.00`, the espresso cups `$0.00`. The column is\n right-aligned because the result is a currency.\n- The footer shows the sum of the column, `$4,704.00`, formatted like the\n cells.\n- The cells are read-only. Edit Qty and the stock value changes as you\n commit the edit.\n- A form view leaves the field out: there is nothing to type.\n- The value is never stored in the record. A base kept in a database does\n not write it either (see [What is not written](./data.md#what-is-not-written)).\n\n[Format the result](#format-the-result) has the details of `result`,\n`precision` and `summary`.\n\n## 3. Branch with IF\n\nA status that says whether to reorder, and how many to order:\n\n```ts\nconst status = {\n field: 'status',\n header: 'Status',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} = 0, \"Out\", IF({Qty} <= {Reorder level}, \"Low\", \"OK\"))' },\n}\nconst toOrder = {\n field: 'toOrder',\n header: 'To order',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} <= {Reorder level}, {Reorder level} * 2 - {Qty}, 0)', result: 'number', precision: 0 },\n}\n```\n\nStatus reads Low for the lamp (4 is at or under 5), OK for the table lamp and\nthe mugs, Out for the espresso cups and Low for the speaker (2 is at its level\nof 2). To order shows 6, 0, 0, 24 and 2.\n\n`IF(condition, then, else)` works out only the branch it takes, so\n`IF({Qty} = 0, 0, 1000 / {Qty})` never divides by zero. Without the third\nargument the field is empty when the condition is false. `SWITCH` is lazy\nthe same way: only the result it returns is worked out.\n\nA comparison on its own is a value too: `{Qty} <= {Reorder level}` shows\n`true` or `false` in the cell.\n\n## 4. Join text\n\n`&` joins values into text:\n\n```text\n{Item} & \" (\" & {Qty} & \" in stock)\"\n```\n\ngives `Arc floor lamp (4 in stock)`. `CONCATENATE({Item}, \" x\", {Qty})` does\nthe same with a function: `Arc floor lamp x4`.\n\nNumbers join as plain numbers, without the format of the field they came\nfrom. `\"$\" & {Unit cost} * 1.15` gives `$471.49999999999994`; round first,\nand it gives `$471.5`:\n\n```text\n\"$\" & ROUND({Unit cost} * 1.15, 2)\n```\n\n`*` comes before `&`, so the multiplication needs no parentheses. An empty\nfield joins as nothing: an Arc floor lamp with no Qty shows\n`Arc floor lamp ( in stock)`.\n\n## 5. Work with dates\n\nWhen each item is due for its next count, and how long since the last one:\n\n```ts\nconst nextCount = {\n field: 'nextCount',\n header: 'Next count',\n fieldType: 'formula',\n fieldProps: { formula: 'DATEADD({Last counted}, 90, \"days\")', result: 'date', dateFormat: 'friendly' },\n}\nconst sinceCount = {\n field: 'sinceCount',\n header: 'Days since count',\n fieldType: 'formula',\n fieldProps: { formula: 'DATETIME_DIFF(TODAY(), {Last counted}, \"days\")', result: 'number', precision: 0 },\n}\n```\n\nNext count shows `December 4, 2026` for the lamp: `DATEADD` returns a date,\nand a date shows in the field's `dateFormat`. Days since count is 39 on\nOctober 14, 2026.\n\nA date field stores a day as text, `2026-09-05`. A formula reads it as that\nday at local midnight, the same way the cell shows it and the way `TODAY()`\nis, so `DAY`, `WEEKDAY` and `DATETIME_DIFF` give the same answer in every\ntime zone.\n\nOther text is a date only when it has a four-digit year and a separator:\n`\"October 5, 2026\"` and `\"10/05/2026\"` are dates, `\"1\"` and `\"12\"` are not,\nso `YEAR(\"1\")` is empty.\n\nTo put a date into text, turn it into `YYYY-MM-DD` with `DATESTR` first.\nJoined as it is, a date becomes a UTC timestamp such as\n`2026-12-03T22:00:00.000Z`:\n\n```text\n\"Count by \" & DATESTR(DATEADD({Last counted}, 90, \"days\"))\n```\n\ngives `Count by 2026-12-04`.\n\n`DATETIME_DIFF(a, b, unit)` is `a` minus `b`, cut to whole units, in\nseconds when there is no unit. `DATEADD(d, n, unit)` adds `n` units, days\nwhen there is no unit. Both take the same units:\n\n| Unit | Also written |\n|---|---|\n| `milliseconds` | `millisecond`, `ms` |\n| `seconds` | `second`, `s` |\n| `minutes` | `minute`, `m` |\n| `hours` | `hour`, `h` |\n| `days` | `day`, `d` |\n| `weeks` | `week`, `w` |\n| `months` | `month` |\n| `years` | `year`, `y` |\n\nCase does not matter, so `\"M\"` is minutes too. Days, weeks, months and years\ncount calendar days, so a daylight-saving change in between does not cut a\nday short. Adding months keeps the day inside the month: January 31 plus one\nmonth is February 28. A unit written in the formula that is not in the table\nis an error the editor shows; one read from a field gives an empty cell.\n\nTo test a date, compare it with another date:\n\n```text\nIF(DATEADD({Last counted}, 90, \"days\") < TODAY(), \"Count now\", \"\")\n```\n\nWhen one side is a date value (from `TODAY()`, `DATEADD` and the like), the\nother side is read as a date too, so `{Last counted} < TODAY()` works.\n`IS_BEFORE(a, b)` and `IS_AFTER(a, b)` read both sides as dates whatever\nthey are, and are false when either side is empty.\n\n## 6. Read another table\n\nAdd a Suppliers table and link each item to one. A formula cannot follow a\nlink by itself; a lookup brings the linked field into the record, and the\nformula reads the lookup.\n\n```ts\nconst suppliers = [\n { id: 's1', name: 'Lumen & Co', leadDays: 10, items: ['1', '2'] },\n { id: 's2', name: 'Kiln Ceramics', leadDays: 21, items: ['3', '4'] },\n { id: 's3', name: 'Signal Audio', leadDays: 7, items: ['5'] },\n]\n\n// Items: each row gets supplier: ['s1'] and so on, plus these columns.\nconst itemLinks = [\n { field: 'supplier', header: 'Supplier', fieldType: 'link', fieldProps: { table: 'suppliers', multiple: false, inverse: 'items' } },\n { field: 'supplierName', header: 'Supplier name', fieldType: 'lookup', fieldProps: { linkField: 'supplier', field: 'name' } },\n { field: 'leadTime', header: 'Lead time', fieldType: 'lookup', fieldProps: { linkField: 'supplier', field: 'leadDays' } },\n {\n field: 'reorderNote',\n header: 'Reorder note',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} <= {Reorder level}, \"Order \" & ({Reorder level} * 2 - {Qty}) & \" from \" & {Supplier name}, \"\")' },\n },\n {\n field: 'arrives',\n header: 'Arrives by',\n fieldType: 'formula',\n fieldProps: { formula: 'DATEADD(TODAY(), {Lead time}, \"days\")', result: 'date', dateFormat: 'friendly' },\n },\n]\n\nconst supplierTable = {\n id: 'suppliers',\n name: 'Suppliers',\n primaryField: 'name',\n data: suppliers,\n columns: [\n { field: 'name', header: 'Supplier', fieldType: 'text' },\n { field: 'leadDays', header: 'Lead time (days)', fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'items', header: 'Items', fieldType: 'link', fieldProps: { table: 'items', multiple: true, inverse: 'supplier' } },\n { field: 'itemCount', header: 'Item count', fieldType: 'count', fieldProps: { linkField: 'items' } },\n { field: 'stockValue', header: 'Stock value', fieldType: 'rollup', fieldProps: { linkField: 'items', field: 'value', aggregation: 'SUM' } },\n { field: 'avgValue', header: 'Average value', fieldType: 'formula', fieldProps: { formula: '{Stock value} / {Item count}', result: 'currency', precision: 2 } },\n ],\n}\n```\n\nReorder note reads `Order 6 from Lumen & Co` for the lamp. A lookup is a\nlist, one value per linked record: joined into text it reads as the values\nseparated by commas, and in arithmetic it adds them up, so `{Lead time}` is\n10 for the lamp. With no supplier the list is empty, which joins as nothing\nand counts as 0.\n\nIt works the other way too. The Suppliers rollup sums Stock value, a\nformula in Items, and shows `$3,080.00` for Lumen & Co in the formula's\nformat. Average value is a formula over that rollup and the count:\n`$1,540.00`. A supplier with no items divides by zero and shows an empty\ncell.\n\nRead the link field itself and you get record ids: `{Supplier}` is `s1`, not\nthe name. Use a lookup of the linked table's primary field for the name.\n[Tables and links](../fields.md#tables-and-links) has the rest of the link,\nlookup and rollup setup.\n\n## 7. Use the computed values\n\nA formula field sorts, filters, groups and colors rows by what it computes,\nand its footer summary reads the same values:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n { id: 'stock', name: 'Stock', type: 'grid', state: { grouping: ['status'], sorting: [{ id: 'value', desc: true }] } },\n {\n id: 'reorder',\n name: 'Reorder',\n type: 'grid',\n color: {\n mode: 'conditions',\n rules: [\n { color: '#f82b60', condition: { column: 'status', kind: 'text', op: 'is', value: 'Out' } },\n { color: '#fcb400', condition: { column: 'status', kind: 'text', op: 'is', value: 'Low' } },\n ],\n },\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'or',\n conditions: [\n { column: 'status', kind: 'text', op: 'is', value: 'Low' },\n { column: 'status', kind: 'text', op: 'is', value: 'Out' },\n ],\n },\n },\n },\n { id: 'value', name: 'Value by supplier', type: 'chart', chart: { kind: 'bar', x: 'supplier', y: 'value' } },\n]\n```\n\nStock groups the items by Status, highest value first in each group.\nReorder shows the three items that need ordering and colors the espresso\ncups red, the other two yellow. The chart adds up Stock value per supplier.\n\nIn the charts, a formula can be the value added up only when its `result`\nis `number`, `currency` or `percent`. Any formula can be the field a chart\ngroups by, and it groups by the computed value: a chart of Status has the\nbars Low, OK and Out. A date result groups by month, as a date field does.\nA lookup can group a chart too, one group per linked value.\n\nIn the view bar's filter, a formula field follows its `result`. `number`,\n`currency` and `percent` get `=`, `<`, `>=` and the other number operators;\n`date` gets is before, is within and the other date operators. With\n`result: 'auto'` the column's `cellDataType` decides (`'number'` or\n`'date'`), and without one the field gets the text operators (contains,\ndoes not contain, is, is not, is empty, is not empty). A condition written\nin code names its kind itself:\n`{ column: 'value', kind: 'number', op: 'gte', value: 1000 }`.\n\nAutomations see computed values as well. A condition on a formula fires\nwhen the formula's result starts to match, and `{Field name}` in a message\nis the formatted value. A token matches a header or a `field` key the way a\nformula does, ignoring case and outer spaces, so `{reorder note}` works too:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nconst lowStock: BaseAutomation = {\n id: 'low-stock',\n name: 'Low stock',\n enabled: true,\n trigger: { type: 'recordMatches' },\n condition: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'text', op: 'is', value: 'Low' }] },\n actions: [{ type: 'notify', message: '{Item}: {Reorder note}', severity: 'warning' }],\n}\n```\n\nThe [OKR template](./templates.md#okrs) does this with a number: its\n\"Target reached\" automation runs when Progress, a formula, reaches 1.\n\n## 8. Write a formula in the field editor\n\nPeople who use the base can add formulas without code. Press \"+\" after the\nlast column (or Edit field in a column's menu), name the field and pick\nFormula under \"Computed and automatic\". The editor shows:\n\n- **Formula**: a text box. As you type, a message under it says what is\n wrong (`No field named \"Unit price\"`, `Unknown function SUMM`) and the box\n is marked invalid.\n- A button for each other field. A click puts `{Field name}` where the cursor\n is.\n- **Functions**: shows the name of every function the formula can call\n (Hide functions closes the list).\n- **Format the result as**: As computed, Number, Currency, Percent or Date,\n then Precision for a number, currency or percent, Currency symbol for a\n currency, and Date format for a date.\n\n![The Add field dialog with Formula picked: the formula IF({Qty} = 0, \"Out\", IF({Qty} <= 3, \"Low\", \"OK\")) in the text box, a button for each field of the table, the list of functions, and Format the result as set to As computed.](/docs-media/base-formulas.png)\n\nWhile the message shows, Save (Create field for a new field) is disabled,\nand its tooltip repeats the message. A formula left empty can be saved: its\ncells stay empty until someone writes it.\n\nA formula cannot read its own field. The editor will not save\n`{Stock value} + 1` as the formula of Stock value, and the same formula\ndeclared in code shows `#ERROR` in every cell.\n\nThe formula is kept as `fieldProps.formula`; `onColumnAdd` and\n`onColumnChange` hand back the column list with it, ready to store (see\n[Create and edit fields](../fields.md#create-and-edit-fields)).\n\n## The formula language\n\n| Part | Written as | Notes |\n|---|---|---|\n| Field | `{Unit cost}` | A header or `field` key, any case |\n| Number | `12`, `0.5`, `.5` | No thousands separators |\n| Text | `\"Low\"` or `'Low'` | `\\` before a character keeps it: `\"say \\\"hi\\\"\"` |\n| True and false | `TRUE`, `FALSE` | Any case |\n| Function | `ROUND({Qty} * 1.1, 0)` | Any case: `round(...)` works |\n| Grouping | `( ... )` | |\n\nOperators, from the first applied to the last:\n\n| Operators | Does |\n|---|---|\n| `-` before a value | Negates it |\n| `*` `/` | Multiply, divide. Dividing by zero gives an empty value |\n| `+` `-` | Add, subtract |\n| `&` | Joins as text |\n| `=` `!=` `<>` `<` `>` `<=` `>=` | Compare; `<>` is the same as `!=` |\n\nThere is no `^` (use `POWER`), no `%` (use `MOD`) and no `==`.\n\nHow values turn into each other:\n\n- **In arithmetic**, an empty field is 0, `TRUE` is 1, text that is a number\n (`\"12\"`) is that number, and other text gives no number, so the cell is\n empty. A lookup's list adds up.\n- **In a comparison**, when either side is a date value both sides compare\n as dates: a stored `\"2026-09-05\"` is read as that day, and an empty or\n unreadable side matches nothing (only `!=` is true). When either side is a\n number, both compare as numbers: `{Qty} = \"4\"` is true. Otherwise they\n compare as text, exactly: `\"a\" = \"A\"` is false, and `\"10\" < \"9\"` is true.\n- **In IF, AND, OR and NOT**, empty, `FALSE` and 0 are false. Everything\n else is true, including the text `\"0\"` and `\"false\"`.\n\n## Functions\n\nThe editor's Functions list has the same names as `FORMULA_FUNCTIONS`.\nExamples use the lamp: Item `Arc floor lamp`, Qty 4, Unit cost 410, Reorder\nlevel 5, Last counted `2026-09-05`, Status `Low`.\n\n**Logic**\n\n| Function | Does | Example |\n|---|---|---|\n| `IF(cond, then, else)` | `then` when `cond` is true, else `else` (or empty) | `IF({Qty} > 3, \"many\", \"few\")` is `many` |\n| `AND(a, b, ...)` | True when every argument is true | `AND({Qty} > 0, {Qty} <= 5)` is true |\n| `OR(a, b, ...)` | True when any argument is true | `OR({Qty} = 0, {Qty} > 3)` is true |\n| `NOT(a)` | The opposite | `NOT({Qty} > 3)` is false |\n| `XOR(a, b, ...)` | True when an odd number of arguments are true | `XOR(TRUE, FALSE, TRUE)` is false |\n| `BLANK()` | An empty value | `IF({Qty} > 0, {Qty}, BLANK())` |\n| `SWITCH(v, m1, r1, ..., default)` | The result after the first match of `v`, compared as text; else the default or empty. Only that result is worked out | `SWITCH({Status}, \"Out\", \"Order now\", \"Low\", \"Order soon\", \"\")` is `Order soon` |\n\n**Text**\n\n| Function | Does | Example |\n|---|---|---|\n| `CONCATENATE(a, b, ...)` | Joins the arguments | `CONCATENATE({Item}, \" x\", {Qty})` is `Arc floor lamp x4` |\n| `LEN(t)` | Number of characters | `LEN({Item})` is 14 |\n| `UPPER(t)`, `LOWER(t)` | Changes case | `UPPER(LEFT({Item}, 3))` is `ARC` |\n| `TRIM(t)` | Drops spaces at both ends | `TRIM(\" bolt \")` is `bolt` |\n| `LEFT(t, n)` | First `n` characters (default 1) | `LEFT({Item}, 3)` is `Arc` |\n| `RIGHT(t, n)` | Last `n` characters (default 1) | `RIGHT({Item}, 4)` is `lamp` |\n| `MID(t, start, n)` | `n` characters from position `start` (1 is the first); without `n`, the rest | `MID({Item}, 5, 5)` is `floor`, `MID({Item}, 5)` is `floor lamp` |\n| `FIND(part, t, start)` | Position of `part` in `t`, 0 when missing; case matters | `FIND(\"lamp\", {Item})` is 11 |\n| `SUBSTITUTE(t, old, new)` | Replaces every `old` | `SUBSTITUTE({Item}, \" \", \"-\")` is `Arc-floor-lamp` |\n| `REPT(t, n)` | `t` repeated `n` times, at most 1000 | `REPT(\"*\", {Qty})` is `****` |\n| `T(v)` | `v` when it is text, else empty text | `T({Qty})` is empty |\n| `VALUE(t)` | The number in a text, ignoring other characters; empty when there is no digit | `VALUE(\"$1,200.50\")` is 1200.5, `VALUE(\"n/a\")` is empty |\n| `ARRAYJOIN(list, sep)` | A lookup's values joined by `sep` (default `, `), empty ones left out | `ARRAYJOIN({Supplier name}, \" / \")` |\n\n**Numbers**\n\n| Function | Does | Example |\n|---|---|---|\n| `SUM(a, b, ...)` | Adds; lists add up too | `SUM({Qty}, 2, 3)` is 9 |\n| `AVERAGE(a, b, ...)` | Mean of the values that are not empty | `AVERAGE(2, 4, \"\")` is 3 |\n| `MAX(...)`, `MIN(...)` | Largest, smallest; empty values ignored | `MAX(0, MIN(1, 1.4))` is 1 |\n| `COUNT(...)` | How many arguments are numbers | `COUNT(1, \"2\", 3)` is 2 |\n| `COUNTA(...)` | How many are not empty | `COUNTA(1, \"\", \"x\")` is 2 |\n| `ROUND(x, digits)` | Rounds; negative digits round to tens, hundreds | `ROUND(1234.5, -2)` is 1200 |\n| `ROUNDUP(x, digits)` | Rounds up | `ROUNDUP(2.41, 1)` is 2.5 |\n| `ROUNDDOWN(x, digits)` | Rounds down | `ROUNDDOWN(2.49, 1)` is 2.4 |\n| `INT(x)` | Rounds down to a whole number | `INT(-2.5)` is -3 |\n| `ABS(x)` | Drops the sign | `ABS(-3)` is 3 |\n| `MOD(x, d)` | Remainder, with the sign of `x` | `MOD(7, 3)` is 1, `MOD(-7, 3)` is -1 |\n| `POWER(x, p)` | `x` to the power `p` | `POWER(2, 10)` is 1024 |\n| `SQRT(x)` | Square root; empty for a negative | `SQRT(16)` is 4 |\n| `CEILING(x, s)`, `FLOOR(x, s)` | Up or down to a multiple of `s` (default 1) | `CEILING(2.1)` is 3, `CEILING(7, 5)` is 10, `FLOOR(2.37, 0.05)` is 2.35 |\n\n**Dates**\n\n| Function | Does | Example |\n|---|---|---|\n| `TODAY()` | Today at midnight, local time | `DATEADD(TODAY(), 7, \"days\")` |\n| `NOW()` | This moment | `NOW() > TODAY()` is true |\n| `YEAR(d)`, `MONTH(d)`, `DAY(d)` | Parts of a date; months count from 1 | `MONTH({Last counted})` is 9 |\n| `WEEKDAY(d)` | Day of the week, 0 for Sunday | `WEEKDAY({Last counted})` is 6 |\n| `DATEADD(d, n, unit)` | `d` plus `n` units (default days); units in [step 5](#5-work-with-dates) | `DATEADD({Last counted}, 2, \"weeks\")` is September 19, `DATEADD({Last counted}, 1, \"months\")` is October 5 |\n| `DATETIME_DIFF(a, b, unit)` | `a` minus `b` in whole units (default seconds) | `DATETIME_DIFF(\"2026-10-14\", {Last counted}, \"days\")` is 39, with `\"months\"` it is 1 |\n| `IS_BEFORE(a, b)`, `IS_AFTER(a, b)` | Compare two dates; false when either is empty | `IS_BEFORE({Last counted}, \"2026-10-01\")` is true |\n| `DATESTR(d)` | The date as `YYYY-MM-DD` text | `DATESTR(DATEADD({Last counted}, 90, \"days\"))` is `2026-12-04` |\n\n## Format the result\n\nThe formula computes a number, text, `true`/`false`, a date or a list.\n`fieldProps.result` says how the cell shows a number, and a date written as\ntext:\n\n| `result` | Shows | Other properties |\n|---|---|---|\n| `auto` (default, \"As computed\") | A number as is, rounded to 10 decimals: `1640` | |\n| `number` | 1640 as `1,640.0` | `precision` |\n| `currency` | 1640 as `$1,640.00` | `precision`, `symbol` (default `$`) |\n| `percent` | 0.4 as `40%` | `precision` |\n| `date` | Text written as a stored date (`2026-12-04` or `2026-12-04T10:30:00Z`) as a date; other text as it is | `dateFormat`: `local`, `friendly`, `us`, `european`, `iso` |\n\nWhatever `result` says, a date value (from `TODAY()`, `DATEADD`) shows as a\ndate in `dateFormat` (`local` without one), `true` and `false` show as those\nwords, and a list shows its values joined by commas. Text shows as it is.\nUnder `date`, only text in the stored-date form turns into a date, so\n`IF({Qty} = 0, \"Count now\", DATEADD({Last counted}, 90, \"days\"))` shows\n`Count now` or the date, and `\"1\"` stays `1`. A number with\n`result: 'date'` stays a number.\n\nSet `precision` (0 to 8) for a number, currency or percent. Without it the\ncell uses the number field's defaults: 1 decimal place for a number, 2 for a\ncurrency and 0 for a percent.\n\n`result` also decides the footer. With `number`, `currency` or `percent` the\nfooter offers Sum, Average, Median, Min, Max and Range; with `date` it\noffers Earliest date, Latest date and Date range (days); with `auto` only\nEmpty, Filled, Unique, Percent empty and Percent filled. Set `result` on any\nformula you want to add up, and keep the choice in `fieldProps.summary`, as\nin step 2 ([Summaries at the bottom](../fields.md#summaries-at-the-bottom)).\n\n## When a formula is wrong\n\nThere are two kinds of problem, and they show differently:\n\n- **The formula does not compile.** The field editor shows the message and\n will not save: `No field named \"Nope\"`, `Unknown function FOO`,\n `Unknown unit \"fortnights\" in DATEADD: ...`, `Expected \")\" at the end`,\n `The formula ends too early`, `Unclosed \"{\" at 1`, `Unclosed text at 1`,\n `Unexpected \"^\" at 7`, `A formula cannot read its own field {Stock value}`.\n Positions count characters from 1. A formula declared in code with a\n mistake, or one that stops compiling because a field it reads was deleted,\n shows `#ERROR` in every cell. Delete field in a column's menu asks first\n when formulas read the field, and names them: \"These formulas read it and\n will show #ERROR: Stock value, Status.\"\n- **It compiles, but a row gives no number.** Division by zero, `\"abc\" * 2`,\n `SQRT(-1)`: that cell is empty, and the other rows still compute.\n\n## Rename a field a formula reads\n\nRename \"Unit cost\" to \"Cost\" in the field editor and every other formula in\nthe table that reads `{Unit cost}` now reads `{Cost}`. Stock value keeps\nworking, and `onColumnChange` hands back the column list with the rewritten\nformulas, ready to store. Text inside quotes is left alone: `\"{Unit cost}\"`\nstays as it is.\n\nA reference to the `field` key needs no rewrite, because renaming changes\nthe header only: `{qty} * {unitCost}` keeps working whatever people call\nthe columns. When a header is also the key, as with \"Qty\" and `qty`, both\nspellings follow the new name, and both still read the field.\n\nOnly a rename made in the field editor rewrites formulas. Change a header\nin the columns you pass the grid and `{Unit cost}` names no field any more:\nthe formula shows `#ERROR` until you change it too.\n\n## Turn a formula into a stored field\n\nChange a formula field's type in the field editor, to Number or Single line\ntext for example, and each record stores the value the formula computed,\nconverted to the new type. Stock value to Number stores `1640` for the\nlamp; to Single line text it stores `\"1640\"`, not the formatted\n`$1,640.00`; a date result becomes `YYYY-MM-DD`. Before you save, the\neditor says \"Every value converts.\" or how many cells will be cleared or\ncut short. The\nvalues arrive in `onColumnChange` as `data`. A formula that did not\ncompile stores nothing. Lookups, rollups and counts convert the same way.\n\n## Formulas from code\n\nThe same parser is exported, for checking a formula in your own UI or\ncomputing a value outside the grid.\n\n| Export | What it is |\n|---|---|\n| `compileFormula(src, resolve)` | Returns `{ fn, refs }`, or throws `FormulaError` (an empty formula throws too) |\n| `formulaError(src, resolve)` | The message, or `null` when the formula compiles |\n| `FormulaError` | The error class, with the message the editor shows |\n| `FORMULA_FUNCTIONS` | Every function name, sorted |\n\n`resolve` turns a name from the braces into the row key it reads, or `null`\nfor no such field. `fn(row)` never throws: a problem gives `null`. `refs`\nlists the keys the formula reads.\n\n```ts\nimport { compileFormula, formulaError } from '@svgrid/enterprise/base'\n\nconst columns = [\n { field: 'qty', header: 'Qty' },\n { field: 'unitCost', header: 'Unit cost' },\n]\nconst resolve = (name: string) => {\n const n = name.trim().toLowerCase()\n const hit = columns.find((c) => c.header.toLowerCase() === n || c.field.toLowerCase() === n)\n return hit ? hit.field : null\n}\n\nformulaError('{Qty} * {Unit cost}', resolve) // null\nformulaError('{Qty} * {Unit price}', resolve) // 'No field named \"Unit price\"'\n\nconst { fn, refs } = compileFormula('{Qty} * {Unit cost}', resolve)\nfn({ qty: 4, unitCost: 410 }) // 1640\nrefs // ['qty', 'unitCost']\n```\n\nA formula box of your own, with the same message under it as the field\neditor:\n\n```svelte\n<script lang=\"ts\">\n import { formulaError, FORMULA_FUNCTIONS } from '@svgrid/enterprise/base'\n\n let { columns }: { columns: Array<{ field: string; header: string }> } = $props()\n let formula = $state('')\n\n const resolve = (name: string) => {\n const n = name.trim().toLowerCase()\n const hit = columns.find((c) => c.header.trim().toLowerCase() === n || c.field.toLowerCase() === n)\n return hit ? hit.field : null\n }\n const message = $derived(formula.trim() ? formulaError(formula, resolve) : null)\n</script>\n\n<textarea bind:value={formula} rows=\"3\" aria-invalid={!!message}></textarea>\n{#if message}<p class=\"formula-error\">{message}</p>{/if}\n<p class=\"formula-help\">{FORMULA_FUNCTIONS.join(', ')}</p>\n```\n\nOn the server, where formula values are not stored, compute them with the\nsame formula. A SvelteKit endpoint that totals the stock:\n\n```ts\n// src/routes/api/stock-value/+server.ts\nimport { json } from '@sveltejs/kit'\nimport { compileFormula, FormulaError } from '@svgrid/enterprise/base'\nimport { loadItems } from '$lib/server/items'\n\nconst keys: Record<string, string> = { qty: 'qty', 'unit cost': 'unitCost' }\nconst resolve = (name: string) => keys[name.trim().toLowerCase()] ?? null\n\nexport async function GET() {\n try {\n const { fn } = compileFormula('{Qty} * {Unit cost}', resolve)\n const items: Array<Record<string, unknown>> = await loadItems()\n const total = items.reduce((sum, row) => sum + Number(fn(row) ?? 0), 0)\n return json({ total })\n } catch (e) {\n if (e instanceof FormulaError) return json({ error: e.message }, { status: 400 })\n throw e\n }\n}\n```\n\nFor the text the cell shows, format included, fill the column the way the\ngrid does. `fillFieldColumn` gives back the column with its `fieldFn` and\n`formatter`:\n\n```ts\nimport { enableBase, fillFieldColumn } from '@svgrid/enterprise/base'\n\nenableBase()\n\nconst columns = [\n { field: 'qty', header: 'Qty', fieldType: 'number' },\n { field: 'unitCost', header: 'Unit cost', fieldType: 'number' },\n]\nconst value = { field: 'value', header: 'Stock value', fieldType: 'formula', fieldProps: { formula: '{Qty} * {Unit cost}', result: 'currency', precision: 2 } }\n\nconst filled = fillFieldColumn(value, columns)\nconst compute = filled.fieldFn as (row: Record<string, unknown>) => unknown\nconst show = filled.formatter as (c: { value: unknown }) => string\nshow({ value: compute({ qty: 4, unitCost: 410 }) }) // \"$1,640.00\" in an English locale\n```\n\n## How it runs\n\nA formula is parsed once, when its column is filled (on load and after any\nchange to the fields), into plain functions. Nothing is passed to `eval` or\n`Function`, so a formula a user types cannot run code.\n\nEach read runs those functions against the record, and nothing is cached\nbetween reads. A formula that reads another formula, a lookup, a rollup or\na count works that field out at the same moment, over the linked records\nwhere it has to. A chain that loops back on itself stops after a few steps\nand reads the stored record (empty) instead of hanging.\n\n## Pitfalls\n\n- **A date field holds a day, not a moment.** It reads as local midnight, so\n `{Last counted} = TODAY()` can be true but `{Last counted} = NOW()` never\n is.\n- **Two dates as text compare as text.** A stored date against another\n stored date, or against a date written in quotes\n (`{Last counted} < \"2026-10-01\"`), compares as text. That orders\n `YYYY-MM-DD` correctly, but an empty date is \"before\" every date. Use\n `IS_BEFORE` and `IS_AFTER`, or compare with a date value such as\n `TODAY()`, when empty dates should match nothing.\n- **A date joined with `&` is a UTC timestamp.** Wrap it in `DATESTR`.\n- **An empty number is 0.** `{Qty} = 0` is true for an item with no Qty, so\n step 3 calls it Out.\n- **Text comparisons are exact.** `=` and `SWITCH` care about case and\n spaces: `\"low\"` does not match `\"Low\"`.\n- **`\"m\"` is minutes.** So is `\"M\"`. Write `\"months\"` for months.\n\n## Next\n\n- [Linked records](./linked-records.md): links, lookups and rollups between\n tables, which formulas read.\n- [Views](./views.md): filters, sorts, groups and charts over computed\n fields.\n- [Automations](./automations.md): conditions and messages that use formula\n results.\n- [Your own field type](./custom-field-type.md): a computed type of your own\n when a formula is not enough.\n- [Field types](../fields.md#declare-columns-by-type): every type and its\n `fieldProps`.\n"
5193
+ "markdown": "# Computed fields with formulas\n\nA formula field works out its value from the other fields of the same\nrecord: a stock value from quantity and unit cost, a status from a reorder\nlevel, a date 90 days after the last count. Nobody types into it, and views,\nfooters, charts and automations read it like any other field.\n\n<div data-docs-demo=\"515-base-inventory\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThis page builds a small inventory: Items with a quantity, a unit cost and a\nreorder level, then a Suppliers table they link to. In the demo above,\nchange an item's Qty or Unit cost and Stock value and the footer total\nfollow.\n\n## 1. Start with the stored fields\n\nFormulas need something to read. Declare the Items table with the fields\npeople type in:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n\n const items = [\n { id: 1, item: 'Arc floor lamp', qty: 4, unitCost: 410, reorder: 5, audited: '2026-09-05' },\n { id: 2, item: 'Table lamp, black', qty: 9, unitCost: 160, reorder: 4, audited: '2026-09-21' },\n { id: 3, item: 'Stoneware mug, slate', qty: 48, unitCost: 18, reorder: 24, audited: '2026-10-02' },\n { id: 4, item: 'Espresso cup, forest', qty: 0, unitCost: 12, reorder: 12, audited: '2026-08-14' },\n { id: 5, item: 'Bookshelf speaker', qty: 2, unitCost: 380, reorder: 2, audited: '2026-09-30' },\n ]\n\n let tables = $state.raw<BaseTable[]>([\n {\n id: 'items',\n name: 'Items',\n primaryField: 'item',\n data: items,\n columns: [\n { field: 'item', header: 'Item', fieldType: 'text' },\n { field: 'qty', header: 'Qty', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n { field: 'unitCost', header: 'Unit cost', fieldType: 'number', fieldProps: { format: 'currency', symbol: '$', precision: 2 } },\n { field: 'reorder', header: 'Reorder level', fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'audited', header: 'Last counted', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n ],\n views: [{ id: 'stock', name: 'Stock', type: 'grid' }],\n },\n ])\n</script>\n\n<SvBase bind:tables editable sortable summary columnAdder fieldMenu containerHeight={560} />\n```\n\n`summary` turns on the footer row; `columnAdder` and `fieldMenu` let people\nadd and edit fields, which step 8 uses.\n\n## 2. Add a formula field\n\nAdd one column to the list:\n\n```ts\nconst stockValue = {\n field: 'value',\n header: 'Stock value',\n fieldType: 'formula',\n fieldProps: { formula: '{Qty} * {Unit cost}', result: 'currency', precision: 2, summary: 'sum' },\n}\n```\n\nA field reference is a name in braces. It matches a field's header or its\n`field` key, ignoring case and the spaces around it, so `{Qty}`, `{qty}` and\n`{ QTY }` all read `qty`, and `{unitCost}` reads the same field as\n`{Unit cost}`.\n\nThe formula is compiled once into a function. Each time a cell, a sort or a\nfooter needs the value, that function runs on the record, and `result` and\n`precision` decide how the number is shown:\n\n![A formula field from text to cell: {Qty} * {Unit cost} compiles once into a function that reads qty and unitCost; each record runs it (Arc floor lamp 4 x 410 = 1640, shown as $1,640.00); a formula over a rollup works the rollup out when it reads it ($3,080.00 / 2 = $1,540.00); a formula that does not compile shows #ERROR, and a row with no number shows an empty cell.](/docs-media/base-formulas.svg)\n\nWhat you see:\n\n- Arc floor lamp shows `$1,640.00`, the espresso cups `$0.00`. The column is\n right-aligned because the result is a currency.\n- The footer shows the sum of the column, `$4,704.00`, formatted like the\n cells.\n- The cells are read-only. Edit Qty and the stock value changes as you\n commit the edit.\n- A form view leaves the field out: there is nothing to type.\n- The value is never stored in the record. A base kept in a database does\n not write it either (see [What is not written](./data.md#what-is-not-written)).\n\n[Format the result](#format-the-result) has the details of `result`,\n`precision` and `summary`.\n\n## 3. Branch with IF\n\nA status that says whether to reorder, and how many to order:\n\n```ts\nconst status = {\n field: 'status',\n header: 'Status',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} = 0, \"Out\", IF({Qty} <= {Reorder level}, \"Low\", \"OK\"))' },\n}\nconst toOrder = {\n field: 'toOrder',\n header: 'To order',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} <= {Reorder level}, {Reorder level} * 2 - {Qty}, 0)', result: 'number', precision: 0 },\n}\n```\n\nStatus reads Low for the lamp (4 is at or under 5), OK for the table lamp and\nthe mugs, Out for the espresso cups and Low for the speaker (2 is at its level\nof 2). To order shows 6, 0, 0, 24 and 2.\n\n`IF(condition, then, else)` works out only the branch it takes, so\n`IF({Qty} = 0, 0, 1000 / {Qty})` never divides by zero. Without the third\nargument the field is empty when the condition is false. `SWITCH` is lazy\nthe same way: only the result it returns is worked out.\n\nA comparison on its own is a value too: `{Qty} <= {Reorder level}` shows\n`true` or `false` in the cell.\n\n## 4. Join text\n\n`&` joins values into text:\n\n```text\n{Item} & \" (\" & {Qty} & \" in stock)\"\n```\n\ngives `Arc floor lamp (4 in stock)`. `CONCATENATE({Item}, \" x\", {Qty})` does\nthe same with a function: `Arc floor lamp x4`.\n\nNumbers join as plain numbers, without the format of the field they came\nfrom. `\"$\" & {Unit cost} * 1.15` gives `$471.49999999999994`; round first,\nand it gives `$471.5`:\n\n```text\n\"$\" & ROUND({Unit cost} * 1.15, 2)\n```\n\n`*` comes before `&`, so the multiplication needs no parentheses. An empty\nfield joins as nothing: an Arc floor lamp with no Qty shows\n`Arc floor lamp ( in stock)`.\n\n## 5. Work with dates\n\nWhen each item is due for its next count, and how long since the last one:\n\n```ts\nconst nextCount = {\n field: 'nextCount',\n header: 'Next count',\n fieldType: 'formula',\n fieldProps: { formula: 'DATEADD({Last counted}, 90, \"days\")', result: 'date', dateFormat: 'friendly' },\n}\nconst sinceCount = {\n field: 'sinceCount',\n header: 'Days since count',\n fieldType: 'formula',\n fieldProps: { formula: 'DATETIME_DIFF(TODAY(), {Last counted}, \"days\")', result: 'number', precision: 0 },\n}\n```\n\nNext count shows `December 4, 2026` for the lamp: `DATEADD` returns a date,\nand a date shows in the field's `dateFormat`. Days since count is 39 on\nOctober 14, 2026.\n\nA date field stores a day as text, `2026-09-05`. A formula reads it as that\nday at local midnight, the same way the cell shows it and the way `TODAY()`\nis, so `DAY`, `WEEKDAY` and `DATETIME_DIFF` give the same answer in every\ntime zone.\n\nOther text is a date only when it has a four-digit year and a separator:\n`\"October 5, 2026\"` and `\"10/05/2026\"` are dates, `\"1\"` and `\"12\"` are not,\nso `YEAR(\"1\")` is empty.\n\nTo put a date into text, turn it into `YYYY-MM-DD` with `DATESTR` first.\nJoined as it is, a date becomes a UTC timestamp such as\n`2026-12-03T22:00:00.000Z`:\n\n```text\n\"Count by \" & DATESTR(DATEADD({Last counted}, 90, \"days\"))\n```\n\ngives `Count by 2026-12-04`.\n\n`DATETIME_DIFF(a, b, unit)` is `a` minus `b`, cut to whole units, in\nseconds when there is no unit. `DATEADD(d, n, unit)` adds `n` units, days\nwhen there is no unit. Both take the same units:\n\n| Unit | Also written |\n|---|---|\n| `milliseconds` | `millisecond`, `ms` |\n| `seconds` | `second`, `s` |\n| `minutes` | `minute`, `m` |\n| `hours` | `hour`, `h` |\n| `days` | `day`, `d` |\n| `weeks` | `week`, `w` |\n| `months` | `month` |\n| `years` | `year`, `y` |\n\nCase does not matter, so `\"M\"` is minutes too. Days, weeks, months and years\ncount calendar days, so a daylight-saving change in between does not cut a\nday short. Adding months keeps the day inside the month: January 31 plus one\nmonth is February 28. A unit written in the formula that is not in the table\nis an error the editor shows; one read from a field gives an empty cell.\n\nTo test a date, compare it with another date:\n\n```text\nIF(DATEADD({Last counted}, 90, \"days\") < TODAY(), \"Count now\", \"\")\n```\n\nWhen one side is a date value (from `TODAY()`, `DATEADD` and the like), the\nother side is read as a date too, so `{Last counted} < TODAY()` works.\n`IS_BEFORE(a, b)` and `IS_AFTER(a, b)` read both sides as dates whatever\nthey are, and are false when either side is empty.\n\n## 6. Read another table\n\nAdd a Suppliers table and link each item to one. A formula cannot follow a\nlink by itself; a lookup brings the linked field into the record, and the\nformula reads the lookup.\n\n```ts\nconst suppliers = [\n { id: 's1', name: 'Lumen & Co', leadDays: 10, items: ['1', '2'] },\n { id: 's2', name: 'Kiln Ceramics', leadDays: 21, items: ['3', '4'] },\n { id: 's3', name: 'Signal Audio', leadDays: 7, items: ['5'] },\n]\n\n// Items: each row gets supplier: ['s1'] and so on, plus these columns.\nconst itemLinks = [\n { field: 'supplier', header: 'Supplier', fieldType: 'link', fieldProps: { table: 'suppliers', multiple: false, inverse: 'items' } },\n { field: 'supplierName', header: 'Supplier name', fieldType: 'lookup', fieldProps: { linkField: 'supplier', field: 'name' } },\n { field: 'leadTime', header: 'Lead time', fieldType: 'lookup', fieldProps: { linkField: 'supplier', field: 'leadDays' } },\n {\n field: 'reorderNote',\n header: 'Reorder note',\n fieldType: 'formula',\n fieldProps: { formula: 'IF({Qty} <= {Reorder level}, \"Order \" & ({Reorder level} * 2 - {Qty}) & \" from \" & {Supplier name}, \"\")' },\n },\n {\n field: 'arrives',\n header: 'Arrives by',\n fieldType: 'formula',\n fieldProps: { formula: 'DATEADD(TODAY(), {Lead time}, \"days\")', result: 'date', dateFormat: 'friendly' },\n },\n]\n\nconst supplierTable = {\n id: 'suppliers',\n name: 'Suppliers',\n primaryField: 'name',\n data: suppliers,\n columns: [\n { field: 'name', header: 'Supplier', fieldType: 'text' },\n { field: 'leadDays', header: 'Lead time (days)', fieldType: 'number', fieldProps: { format: 'integer' } },\n { field: 'items', header: 'Items', fieldType: 'link', fieldProps: { table: 'items', multiple: true, inverse: 'supplier' } },\n { field: 'itemCount', header: 'Item count', fieldType: 'count', fieldProps: { linkField: 'items' } },\n { field: 'stockValue', header: 'Stock value', fieldType: 'rollup', fieldProps: { linkField: 'items', field: 'value', aggregation: 'SUM' } },\n { field: 'avgValue', header: 'Average value', fieldType: 'formula', fieldProps: { formula: '{Stock value} / {Item count}', result: 'currency', precision: 2 } },\n ],\n}\n```\n\nReorder note reads `Order 6 from Lumen & Co` for the lamp. A lookup is a\nlist, one value per linked record: joined into text it reads as the values\nseparated by commas, and in arithmetic it adds them up, so `{Lead time}` is\n10 for the lamp. With no supplier the list is empty, which joins as nothing\nand counts as 0.\n\nIt works the other way too. The Suppliers rollup sums Stock value, a\nformula in Items, and shows `$3,080.00` for Lumen & Co in the formula's\nformat. Average value is a formula over that rollup and the count:\n`$1,540.00`. A supplier with no items divides by zero and shows an empty\ncell.\n\nRead the link field itself and you get record ids: `{Supplier}` is `s1`, not\nthe name. Use a lookup of the linked table's primary field for the name.\n[Tables and links](../fields.md#tables-and-links) has the rest of the link,\nlookup and rollup setup.\n\n## 7. Use the computed values\n\nA formula field sorts, filters, groups and colors rows by what it computes,\nand its footer summary reads the same values:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n { id: 'stock', name: 'Stock', type: 'grid', state: { grouping: ['status'], sorting: [{ id: 'value', desc: true }] } },\n {\n id: 'reorder',\n name: 'Reorder',\n type: 'grid',\n color: {\n mode: 'conditions',\n rules: [\n { color: '#f82b60', condition: { column: 'status', kind: 'text', op: 'is', value: 'Out' } },\n { color: '#fcb400', condition: { column: 'status', kind: 'text', op: 'is', value: 'Low' } },\n ],\n },\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'or',\n conditions: [\n { column: 'status', kind: 'text', op: 'is', value: 'Low' },\n { column: 'status', kind: 'text', op: 'is', value: 'Out' },\n ],\n },\n },\n },\n { id: 'value', name: 'Value by supplier', type: 'chart', chart: { kind: 'bar', x: 'supplier', y: 'value' } },\n]\n```\n\nStock groups the items by Status, highest value first in each group.\nReorder shows the three items that need ordering and colors the espresso\ncups red, the other two yellow. The chart adds up Stock value per supplier.\n\nIn the charts, a formula can be the value added up only when its `result`\nis `number`, `currency` or `percent`. Any formula can be the field a chart\ngroups by, and it groups by the computed value: a chart of Status has the\nbars Low, OK and Out. A date result groups by month, as a date field does.\nA lookup can group a chart too, one group per linked value.\n\nIn the view bar's filter, a formula field follows its `result`. `number`,\n`currency` and `percent` get `=`, `<`, `>=` and the other number operators;\n`date` gets is before, is within and the other date operators. With\n`result: 'auto'` the column's `cellDataType` decides (`'number'` or\n`'date'`), and without one the field gets the text operators (contains,\ndoes not contain, is, is not, is empty, is not empty). A condition written\nin code names its kind itself:\n`{ column: 'value', kind: 'number', op: 'gte', value: 1000 }`.\n\nAutomations see computed values as well. A condition on a formula fires\nwhen the formula's result starts to match, and `{Field name}` in a message\nis the formatted value. A token matches a header or a `field` key the way a\nformula does, ignoring case and outer spaces, so `{reorder note}` works too:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nconst lowStock: BaseAutomation = {\n id: 'low-stock',\n name: 'Low stock',\n enabled: true,\n trigger: { type: 'recordMatches' },\n condition: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'text', op: 'is', value: 'Low' }] },\n actions: [{ type: 'notify', message: '{Item}: {Reorder note}', severity: 'warning' }],\n}\n```\n\nThe [OKR template](./templates.md#okrs) does this with a number: its\n\"Target reached\" automation runs when Progress, a formula, reaches 1.\n\n## 8. Write a formula in the field editor\n\nPeople who use the base can add formulas without code. Press \"+\" after the\nlast column (or Edit field in a column's menu), name the field and pick\nFormula under \"Computed and automatic\". The editor shows:\n\n- **Formula**: a text box. As you type, a message under it says what is\n wrong (`No field named \"Unit price\"`, `Unknown function SUMM`) and the box\n is marked invalid.\n- A button for each other field. A click puts `{Field name}` where the cursor\n is.\n- **Functions**: shows the name of every function the formula can call\n (Hide functions closes the list).\n- **Format the result as**: As computed, Number, Currency, Percent or Date,\n then Precision for a number, currency or percent, Currency symbol for a\n currency, and Date format for a date.\n\n![The Add field dialog with Formula picked: the formula IF({Qty} = 0, \"Out\", IF({Qty} <= 3, \"Low\", \"OK\")) in the text box, a button for each field of the table, the list of functions, and Format the result as set to As computed.](/docs-media/base-formulas.png)\n\nWhile the message shows, Save (Create field for a new field) is disabled,\nand its tooltip repeats the message. A formula left empty can be saved: its\ncells stay empty until someone writes it.\n\nA formula cannot read its own field. The editor will not save\n`{Stock value} + 1` as the formula of Stock value, and the same formula\ndeclared in code shows `#ERROR` in every cell.\n\nThe formula is kept as `fieldProps.formula`; `onColumnAdd` and\n`onColumnChange` hand back the column list with it, ready to store (see\n[Create and edit fields](../fields.md#create-and-edit-fields)).\n\n## The formula language\n\n| Part | Written as | Notes |\n|---|---|---|\n| Field | `{Unit cost}` | A header or `field` key, any case |\n| Number | `12`, `0.5`, `.5` | No thousands separators |\n| Text | `\"Low\"` or `'Low'` | `\\` before a character keeps it: `\"say \\\"hi\\\"\"` |\n| True and false | `TRUE`, `FALSE` | Any case |\n| Function | `ROUND({Qty} * 1.1, 0)` | Any case: `round(...)` works |\n| Grouping | `( ... )` | |\n\nOperators, from the first applied to the last:\n\n| Operators | Does |\n|---|---|\n| `-` before a value | Negates it |\n| `*` `/` | Multiply, divide. Dividing by zero gives an empty value |\n| `+` `-` | Add, subtract |\n| `&` | Joins as text |\n| `=` `!=` `<>` `<` `>` `<=` `>=` | Compare; `<>` is the same as `!=` |\n\nThere is no `^` (use `POWER`), no `%` (use `MOD`) and no `==`.\n\nHow values turn into each other:\n\n- **In arithmetic**, an empty field is 0, `TRUE` is 1, text that is a number\n (`\"12\"`) is that number, and other text gives no number, so the cell is\n empty. A lookup's list adds up.\n- **In a comparison**, when either side is a date value both sides compare\n as dates: a stored `\"2026-09-05\"` is read as that day, and an empty or\n unreadable side matches nothing (only `!=` is true). When either side is a\n number, both compare as numbers: `{Qty} = \"4\"` is true. Otherwise they\n compare as text, exactly: `\"a\" = \"A\"` is false, and `\"10\" < \"9\"` is true.\n- **In IF, AND, OR and NOT**, empty, `FALSE` and 0 are false. Everything\n else is true, including the text `\"0\"` and `\"false\"`.\n\n## Functions\n\nThe editor's Functions list has the same names as `FORMULA_FUNCTIONS`.\nExamples use the lamp: Item `Arc floor lamp`, Qty 4, Unit cost 410, Reorder\nlevel 5, Last counted `2026-09-05`, Status `Low`.\n\n**Logic**\n\n| Function | Does | Example |\n|---|---|---|\n| `IF(cond, then, else)` | `then` when `cond` is true, else `else` (or empty) | `IF({Qty} > 3, \"many\", \"few\")` is `many` |\n| `AND(a, b, ...)` | True when every argument is true | `AND({Qty} > 0, {Qty} <= 5)` is true |\n| `OR(a, b, ...)` | True when any argument is true | `OR({Qty} = 0, {Qty} > 3)` is true |\n| `NOT(a)` | The opposite | `NOT({Qty} > 3)` is false |\n| `XOR(a, b, ...)` | True when an odd number of arguments are true | `XOR(TRUE, FALSE, TRUE)` is false |\n| `BLANK()` | An empty value | `IF({Qty} > 0, {Qty}, BLANK())` |\n| `SWITCH(v, m1, r1, ..., default)` | The result after the first match of `v`, compared as text; else the default or empty. Only that result is worked out | `SWITCH({Status}, \"Out\", \"Order now\", \"Low\", \"Order soon\", \"\")` is `Order soon` |\n\n**Text**\n\n| Function | Does | Example |\n|---|---|---|\n| `CONCATENATE(a, b, ...)` | Joins the arguments | `CONCATENATE({Item}, \" x\", {Qty})` is `Arc floor lamp x4` |\n| `LEN(t)` | Number of characters | `LEN({Item})` is 14 |\n| `UPPER(t)`, `LOWER(t)` | Changes case | `UPPER(LEFT({Item}, 3))` is `ARC` |\n| `TRIM(t)` | Drops spaces at both ends | `TRIM(\" bolt \")` is `bolt` |\n| `LEFT(t, n)` | First `n` characters (default 1) | `LEFT({Item}, 3)` is `Arc` |\n| `RIGHT(t, n)` | Last `n` characters (default 1) | `RIGHT({Item}, 4)` is `lamp` |\n| `MID(t, start, n)` | `n` characters from position `start` (1 is the first); without `n`, the rest | `MID({Item}, 5, 5)` is `floor`, `MID({Item}, 5)` is `floor lamp` |\n| `FIND(part, t, start)` | Position of `part` in `t`, 0 when missing; case matters | `FIND(\"lamp\", {Item})` is 11 |\n| `SUBSTITUTE(t, old, new)` | Replaces every `old` | `SUBSTITUTE({Item}, \" \", \"-\")` is `Arc-floor-lamp` |\n| `REPT(t, n)` | `t` repeated `n` times, at most 1000 | `REPT(\"*\", {Qty})` is `****` |\n| `T(v)` | `v` when it is text, else empty text | `T({Qty})` is empty |\n| `VALUE(t)` | The number in a text, ignoring other characters; empty when there is no digit | `VALUE(\"$1,200.50\")` is 1200.5, `VALUE(\"n/a\")` is empty |\n| `ARRAYJOIN(list, sep)` | A lookup's values joined by `sep` (default `, `), empty ones left out | `ARRAYJOIN({Supplier name}, \" / \")` |\n\n**Numbers**\n\n| Function | Does | Example |\n|---|---|---|\n| `SUM(a, b, ...)` | Adds; lists add up too | `SUM({Qty}, 2, 3)` is 9 |\n| `AVERAGE(a, b, ...)` | Mean of the values that are not empty | `AVERAGE(2, 4, \"\")` is 3 |\n| `MAX(...)`, `MIN(...)` | Largest, smallest; empty values ignored | `MAX(0, MIN(1, 1.4))` is 1 |\n| `COUNT(...)` | How many arguments are numbers | `COUNT(1, \"2\", 3)` is 2 |\n| `COUNTA(...)` | How many are not empty | `COUNTA(1, \"\", \"x\")` is 2 |\n| `ROUND(x, digits)` | Rounds; negative digits round to tens, hundreds | `ROUND(1234.5, -2)` is 1200 |\n| `ROUNDUP(x, digits)` | Rounds away from zero | `ROUNDUP(2.41, 1)` is 2.5, `ROUNDUP(-2.41, 1)` is -2.5 |\n| `ROUNDDOWN(x, digits)` | Rounds toward zero | `ROUNDDOWN(2.49, 1)` is 2.4, `ROUNDDOWN(-2.49, 1)` is -2.4 |\n| `INT(x)` | Rounds down to a whole number | `INT(-2.5)` is -3 |\n| `ABS(x)` | Drops the sign | `ABS(-3)` is 3 |\n| `MOD(x, d)` | Remainder, with the sign of `x` | `MOD(7, 3)` is 1, `MOD(-7, 3)` is -1 |\n| `POWER(x, p)` | `x` to the power `p` | `POWER(2, 10)` is 1024 |\n| `SQRT(x)` | Square root; empty for a negative | `SQRT(16)` is 4 |\n| `CEILING(x, s)`, `FLOOR(x, s)` | Up or down to a multiple of `s` (default 1) | `CEILING(2.1)` is 3, `CEILING(7, 5)` is 10, `FLOOR(2.37, 0.05)` is 2.35 |\n\n**Dates**\n\n| Function | Does | Example |\n|---|---|---|\n| `TODAY()` | Today at midnight, local time | `DATEADD(TODAY(), 7, \"days\")` |\n| `NOW()` | This moment | `NOW() > TODAY()` is true |\n| `YEAR(d)`, `MONTH(d)`, `DAY(d)` | Parts of a date; months count from 1 | `MONTH({Last counted})` is 9 |\n| `WEEKDAY(d)` | Day of the week, 0 for Sunday | `WEEKDAY({Last counted})` is 6 |\n| `DATEADD(d, n, unit)` | `d` plus `n` units (default days); units in [step 5](#5-work-with-dates) | `DATEADD({Last counted}, 2, \"weeks\")` is September 19, `DATEADD({Last counted}, 1, \"months\")` is October 5 |\n| `DATETIME_DIFF(a, b, unit)` | `a` minus `b` in whole units (default seconds) | `DATETIME_DIFF(\"2026-10-14\", {Last counted}, \"days\")` is 39, with `\"months\"` it is 1 |\n| `IS_BEFORE(a, b)`, `IS_AFTER(a, b)` | Compare two dates; false when either is empty | `IS_BEFORE({Last counted}, \"2026-10-01\")` is true |\n| `DATESTR(d)` | The date as `YYYY-MM-DD` text | `DATESTR(DATEADD({Last counted}, 90, \"days\"))` is `2026-12-04` |\n\n**More functions**\n\nThese work as they do in the formula language of the hosted table\ndatabases most teams come from. What each one does, and where Base differs\n(regular expressions are JavaScript's, for one), is in the\n[formula functions table](../migrating-from-airtable.md#formula-functions).\n\n| Group | Functions |\n|---|---|\n| Text | `SEARCH`, `REPLACE`, `ENCODE_URL_COMPONENT`, `REGEX_MATCH`, `REGEX_EXTRACT`, `REGEX_REPLACE`; `SUBSTITUTE` takes which match to replace as a fourth argument |\n| Logic | `TRUE()`, `FALSE()`, `ERROR()`, `ISERROR(v)` |\n| Numbers | `EVEN`, `ODD`, `EXP`, `LOG`, `COUNTALL` |\n| Lists | `ARRAYCOMPACT`, `ARRAYFLATTEN`, `ARRAYUNIQUE`, `ARRAYSLICE` |\n| Dates | `HOUR`, `MINUTE`, `SECOND`, `WEEKNUM`, `IS_SAME`, `TIMESTR`, `DATETIME_FORMAT`, `DATETIME_PARSE`, `SET_LOCALE`, `SET_TIMEZONE`, `TONOW`, `FROMNOW`, `WORKDAY`, `WORKDAY_DIFF`; `WEEKDAY` takes the first day of the week, and `\"quarters\"` is a unit |\n| Record | `RECORD_ID()` |\n\n<div data-docs-demo=\"708-base-formula-compat\" data-height=\"640\"></div>\n\n## Format the result\n\nThe formula computes a number, text, `true`/`false`, a date or a list.\n`fieldProps.result` says how the cell shows a number, and a date written as\ntext:\n\n| `result` | Shows | Other properties |\n|---|---|---|\n| `auto` (default, \"As computed\") | A number as is, rounded to 10 decimals: `1640` | |\n| `number` | 1640 as `1,640.0` | `precision` |\n| `currency` | 1640 as `$1,640.00` | `precision`, `symbol` (default `$`) |\n| `percent` | 0.4 as `40%` | `precision` |\n| `date` | Text written as a stored date (`2026-12-04` or `2026-12-04T10:30:00Z`) as a date; other text as it is | `dateFormat`: `local`, `friendly`, `us`, `european`, `iso` |\n\nWhatever `result` says, a date value (from `TODAY()`, `DATEADD`) shows as a\ndate in `dateFormat` (`local` without one), `true` and `false` show as those\nwords, and a list shows its values joined by commas. Text shows as it is.\nUnder `date`, only text in the stored-date form turns into a date, so\n`IF({Qty} = 0, \"Count now\", DATEADD({Last counted}, 90, \"days\"))` shows\n`Count now` or the date, and `\"1\"` stays `1`. A number with\n`result: 'date'` stays a number.\n\nSet `precision` (0 to 8) for a number, currency or percent. Without it the\ncell uses the number field's defaults: 1 decimal place for a number, 2 for a\ncurrency and 0 for a percent.\n\n`result` also decides the footer. With `number`, `currency` or `percent` the\nfooter offers Sum, Average, Median, Min, Max and Range; with `date` it\noffers Earliest date, Latest date and Date range (days); with `auto` only\nEmpty, Filled, Unique, Percent empty and Percent filled. Set `result` on any\nformula you want to add up, and keep the choice in `fieldProps.summary`, as\nin step 2 ([Summaries at the bottom](../fields.md#summaries-at-the-bottom)).\n\n## When a formula is wrong\n\nThere are two kinds of problem, and they show differently:\n\n- **The formula does not compile.** The field editor shows the message and\n will not save: `No field named \"Nope\"`, `Unknown function FOO`,\n `Unknown unit \"fortnights\" in DATEADD: ...`, `Expected \")\" at the end`,\n `The formula ends too early`, `Unclosed \"{\" at 1`, `Unclosed text at 1`,\n `Unexpected \"^\" at 7`, `A formula cannot read its own field {Stock value}`.\n Positions count characters from 1. A formula declared in code with a\n mistake, or one that stops compiling because a field it reads was deleted,\n shows `#ERROR` in every cell. Delete field in a column's menu asks first\n when formulas read the field, and names them: \"These formulas read it and\n will show #ERROR: Stock value, Status.\"\n- **It compiles, but a row gives no number.** Division by zero, `\"abc\" * 2`,\n `SQRT(-1)`: that cell is empty, and the other rows still compute.\n\n## Rename a field a formula reads\n\nRename \"Unit cost\" to \"Cost\" in the field editor and every other formula in\nthe table that reads `{Unit cost}` now reads `{Cost}`. Stock value keeps\nworking, and `onColumnChange` hands back the column list with the rewritten\nformulas, ready to store. Text inside quotes is left alone: `\"{Unit cost}\"`\nstays as it is.\n\nA reference to the `field` key needs no rewrite, because renaming changes\nthe header only: `{qty} * {unitCost}` keeps working whatever people call\nthe columns. When a header is also the key, as with \"Qty\" and `qty`, both\nspellings follow the new name, and both still read the field.\n\nOnly a rename made in the field editor rewrites formulas. Change a header\nin the columns you pass the grid and `{Unit cost}` names no field any more:\nthe formula shows `#ERROR` until you change it too.\n\n## Turn a formula into a stored field\n\nChange a formula field's type in the field editor, to Number or Single line\ntext for example, and each record stores the value the formula computed,\nconverted to the new type. Stock value to Number stores `1640` for the\nlamp; to Single line text it stores `\"1640\"`, not the formatted\n`$1,640.00`; a date result becomes `YYYY-MM-DD`. Before you save, the\neditor says \"Every value converts.\" or how many cells will be cleared or\ncut short. The\nvalues arrive in `onColumnChange` as `data`. A formula that did not\ncompile stores nothing. Lookups, rollups and counts convert the same way.\n\n## Formulas from code\n\nThe same parser is exported, for checking a formula in your own UI or\ncomputing a value outside the grid.\n\n| Export | What it is |\n|---|---|\n| `compileFormula(src, resolve)` | Returns `{ fn, refs }`, or throws `FormulaError` (an empty formula throws too) |\n| `formulaError(src, resolve)` | The message, or `null` when the formula compiles |\n| `FormulaError` | The error class, with the message the editor shows |\n| `FORMULA_FUNCTIONS` | Every function name, sorted |\n\n`resolve` turns a name from the braces into the row key it reads, or `null`\nfor no such field. `fn(row)` never throws: a problem gives `null`. `refs`\nlists the keys the formula reads.\n\n```ts\nimport { compileFormula, formulaError } from '@svgrid/enterprise/base'\n\nconst columns = [\n { field: 'qty', header: 'Qty' },\n { field: 'unitCost', header: 'Unit cost' },\n]\nconst resolve = (name: string) => {\n const n = name.trim().toLowerCase()\n const hit = columns.find((c) => c.header.toLowerCase() === n || c.field.toLowerCase() === n)\n return hit ? hit.field : null\n}\n\nformulaError('{Qty} * {Unit cost}', resolve) // null\nformulaError('{Qty} * {Unit price}', resolve) // 'No field named \"Unit price\"'\n\nconst { fn, refs } = compileFormula('{Qty} * {Unit cost}', resolve)\nfn({ qty: 4, unitCost: 410 }) // 1640\nrefs // ['qty', 'unitCost']\n```\n\nA formula box of your own, with the same message under it as the field\neditor:\n\n```svelte\n<script lang=\"ts\">\n import { formulaError, FORMULA_FUNCTIONS } from '@svgrid/enterprise/base'\n\n let { columns }: { columns: Array<{ field: string; header: string }> } = $props()\n let formula = $state('')\n\n const resolve = (name: string) => {\n const n = name.trim().toLowerCase()\n const hit = columns.find((c) => c.header.trim().toLowerCase() === n || c.field.toLowerCase() === n)\n return hit ? hit.field : null\n }\n const message = $derived(formula.trim() ? formulaError(formula, resolve) : null)\n</script>\n\n<textarea bind:value={formula} rows=\"3\" aria-invalid={!!message}></textarea>\n{#if message}<p class=\"formula-error\">{message}</p>{/if}\n<p class=\"formula-help\">{FORMULA_FUNCTIONS.join(', ')}</p>\n```\n\nOn the server, where formula values are not stored, compute them with the\nsame formula. A SvelteKit endpoint that totals the stock:\n\n```ts\n// src/routes/api/stock-value/+server.ts\nimport { json } from '@sveltejs/kit'\nimport { compileFormula, FormulaError } from '@svgrid/enterprise/base'\nimport { loadItems } from '$lib/server/items'\n\nconst keys: Record<string, string> = { qty: 'qty', 'unit cost': 'unitCost' }\nconst resolve = (name: string) => keys[name.trim().toLowerCase()] ?? null\n\nexport async function GET() {\n try {\n const { fn } = compileFormula('{Qty} * {Unit cost}', resolve)\n const items: Array<Record<string, unknown>> = await loadItems()\n const total = items.reduce((sum, row) => sum + Number(fn(row) ?? 0), 0)\n return json({ total })\n } catch (e) {\n if (e instanceof FormulaError) return json({ error: e.message }, { status: 400 })\n throw e\n }\n}\n```\n\nFor the text the cell shows, format included, fill the column the way the\ngrid does. `fillFieldColumn` gives back the column with its `fieldFn` and\n`formatter`:\n\n```ts\nimport { enableBase, fillFieldColumn } from '@svgrid/enterprise/base'\n\nenableBase()\n\nconst columns = [\n { field: 'qty', header: 'Qty', fieldType: 'number' },\n { field: 'unitCost', header: 'Unit cost', fieldType: 'number' },\n]\nconst value = { field: 'value', header: 'Stock value', fieldType: 'formula', fieldProps: { formula: '{Qty} * {Unit cost}', result: 'currency', precision: 2 } }\n\nconst filled = fillFieldColumn(value, columns)\nconst compute = filled.fieldFn as (row: Record<string, unknown>) => unknown\nconst show = filled.formatter as (c: { value: unknown }) => string\nshow({ value: compute({ qty: 4, unitCost: 410 }) }) // \"$1,640.00\" in an English locale\n```\n\n## How it runs\n\nA formula is parsed once, when its column is filled (on load and after any\nchange to the fields), into plain functions. Nothing is passed to `eval` or\n`Function`, so a formula a user types cannot run code.\n\nEach read runs those functions against the record, and nothing is cached\nbetween reads. A formula that reads another formula, a lookup, a rollup or\na count works that field out at the same moment, over the linked records\nwhere it has to. A chain that loops back on itself stops after a few steps\nand reads the stored record (empty) instead of hanging.\n\n## Pitfalls\n\n- **A date field holds a day, not a moment.** It reads as local midnight, so\n `{Last counted} = TODAY()` can be true but `{Last counted} = NOW()` never\n is.\n- **Two dates as text compare as text.** A stored date against another\n stored date, or against a date written in quotes\n (`{Last counted} < \"2026-10-01\"`), compares as text. That orders\n `YYYY-MM-DD` correctly, but an empty date is \"before\" every date. Use\n `IS_BEFORE` and `IS_AFTER`, or compare with a date value such as\n `TODAY()`, when empty dates should match nothing.\n- **A date joined with `&` is a UTC timestamp.** Wrap it in `DATESTR`.\n- **An empty number is 0.** `{Qty} = 0` is true for an item with no Qty, so\n step 3 calls it Out.\n- **Text comparisons are exact.** `=` and `SWITCH` care about case and\n spaces: `\"low\"` does not match `\"Low\"`.\n- **`\"m\"` is minutes.** So is `\"M\"`. Write `\"months\"` for months.\n\n## Next\n\n- [Linked records](./linked-records.md): links, lookups and rollups between\n tables, which formulas read.\n- [Views](./views.md): filters, sorts, groups and charts over computed\n fields.\n- [Automations](./automations.md): conditions and messages that use formula\n results.\n- [Your own field type](./custom-field-type.md): a computed type of your own\n when a formula is not enough.\n- [Field types](../fields.md#declare-columns-by-type): every type and its\n `fieldProps`.\n"
5058
5194
  },
5059
5195
  {
5060
5196
  "slug": "help/base/linked-records",
@@ -5112,19 +5248,26 @@ export const docs = [
5112
5248
  "section": "SvGrid Base",
5113
5249
  "markdown": "# Ready-to-use bases\n\nEach base below is one `<SvBase>` with sample data: the fields, the saved\nviews and the forms a team would set up on day one. Open the source of any of\nthem, replace the sample rows with your own, and it is your app's tool.\n\nTo try one with nothing installed, open it full screen at\n[svgrid.com/base](https://svgrid.com/base); the bar at the top switches between\nthem.\n\nAll of them share the same parts, so what works in one works in all: the table\ntabs (where a base has more than one table), the view bar (Hide fields, Filter, Group, Sort, Color, Row height, search), the\nexpanded record with its changes and comments, Space on a row to open it,\n\"+ Add row\", the field editor, the selection bar for editing or deleting many\nrows at once, and dragging the pinned columns' edge.\n\n## Project tracker\n\nTwo tables, Tasks and Milestones. Tasks have a status, tags, an assignee,\ndates, an estimate, progress, a budget, files and a milestone; each milestone\nlists its tasks with their average progress and their budget. The\n[tutorial](./start.md) builds the task table step by step.\n\n## Content calendar\n\n<div data-docs-demo=\"511-base-content-calendar\" data-height=\"640\"></div>\n\nTwo tables, Posts and Campaigns. A post has a stage, channels, an author, a\npublish date, a cover image, a word count, a brief and its campaign; a\ncampaign lists its posts and adds up their words.\n\n- **Content plan:** the posts in publishing order, colored by stage, word\n counts summed in the footer.\n- **Pipeline:** a Kanban by stage; dragging a card moves the post along.\n- **Publishing calendar:** posts on their publish date; drag one to another\n day, or pick an empty day to schedule a new one.\n- **Covers:** a gallery of the cover images.\n- **Pitch an idea:** a form with the title, channels, author and brief.\n\n## Sales CRM\n\n<div data-docs-demo=\"512-base-sales-crm\" data-height=\"640\"></div>\n\nThree tables: Deals, Accounts and Contacts. A deal links to an account and a\ncontact and has a stage, an owner, a value, a probability, a close date, the\nnext step, a source and a priority. An account lists its deals and contacts\nand rolls up its pipeline value; a contact lists its deals.\n\n- **All deals:** biggest first, colored by stage; the footer sums the value\n and averages the probability.\n- **Pipeline:** a Kanban by stage.\n- **Closing calendar:** deals on their close date.\n- **Open deals by owner:** grouped by owner, Won and Lost filtered out; each\n group shows its own totals.\n- **New lead:** a form that starts a deal in the Lead stage.\n\nLinking a deal to an account lists it on the account, and the other way\nround. Hover a chip to preview the account, click it to open it (\"Open in\nAccounts\" goes there), and create a new account from the link picker.\n\n## Product roadmap\n\n<div data-docs-demo=\"513-base-product-roadmap\" data-height=\"640\"></div>\n\nTwo tables, Features and Feedback. A feature has a quarter, a status, teams,\na lead, impact, effort in days, start and target dates, customer votes and a\nspec link; each customer request links to the feature it is about, and the\nfeature counts them.\n\n- **Roadmap by quarter:** grouped by quarter, highest impact first, each\n group with its effort and votes; \"+\" in a group adds a feature to that\n quarter.\n- **Status board:** a Kanban by status.\n- **Timeline:** each feature from its start to its target date.\n- **Now:** in progress, in beta or blocked, by target date.\n- **Request a feature:** a form for anyone in the company.\n\n## Hiring tracker\n\n<div data-docs-demo=\"514-base-hiring-tracker\" data-height=\"640\"></div>\n\nTwo tables, Candidates and Roles. A candidate has a photo, a role, a stage, a\nrecruiter, a rating, the interview date, the salary ask, an email, a resume,\nthe source and notes; a role has its team, hiring manager and headcount, and\nlists its candidates.\n\n- **Hiring pipeline:** a Kanban by stage.\n- **All candidates:** best rated first, colored by stage.\n- **Faces:** a gallery of the photos.\n- **Interviews:** a calendar of interview dates.\n- **Apply:** the form a candidate fills in, with their resume.\n\n## Inventory\n\n<div data-docs-demo=\"515-base-inventory\" data-height=\"640\"></div>\n\nTwo tables, Items and Suppliers. An item has photos, a category, a location,\na supplier, the quantity, the unit cost, the stock value (a formula,\n`{Qty} * {Unit cost}`), the condition, who has it checked out, when it was\nlast counted and a barcode; a supplier lists its items and the units in\nstock.\n\n- **Stock by category:** grouped by category, the footer and each group\n summing quantity and value.\n- **Photos:** a gallery.\n- **By location:** a Kanban by location; dragging an item moves it.\n- **Reorder:** three or fewer in stock, red at zero and amber below four.\n- **Add an item:** a form.\n\n## Bug tracker\n\n<div data-docs-demo=\"520-base-bug-tracker\" data-height=\"640\"></div>\n\nTwo tables, Bugs and Releases. A bug has a severity, a status, the areas it\ntouches, who reported it and who is on it, the release it ships in, the\nsteps to reproduce, and when it was reported and fixed. A release lists its\nbugs and counts them.\n\n![Bug tracker: Bugs with Release, a link to one; Releases with Bugs, the field that links back.](/docs-media/base-template-bug-tracker.svg)\n\n- **Triage:** grouped by status, colored by severity.\n- **Board:** a Kanban by status.\n- **Critical now:** critical bugs that are not fixed.\n- **Bugs by area:** a bar chart.\n- **Report a bug:** the form anyone can fill in.\n\nAutomations: a critical bug that is not fixed turns red and raises a notice;\nsetting Status to Fixed stamps \"Fixed on\"; a bug from the form starts as\nNew; **Start** in the Fix column moves a bug to In progress.\n\n## Event planning\n\n<div data-docs-demo=\"521-base-event-planning\" data-height=\"640\"></div>\n\nThree tables: Events, Attendees and Checklist. An event has a date, a venue,\na status, an owner, a budget and a capacity; it counts who registered and\nworks out the seats left (`{Capacity} - {Registered}`). Attendees have a\nticket type and check in on the day; checklist items have a team and a due\ndate.\n\n![Event planning: Attendees link to one event; Events list attendees and checklist items; Checklist items link to one event.](/docs-media/base-template-event-planning.svg)\n\n- **Calendar:** events on their date, colored by status.\n- **Planning board:** a Kanban by status.\n- **Guest list:** attendees grouped by event.\n- **Tickets by type:** a donut.\n- **RSVP:** the form a guest fills in.\n\nAutomations: an event that turns Confirmed gets its checklist (three items\ncreated in Checklist and linked back to it); an event with no seats left\nturns red and raises a notice, also when the last seat goes from the\nAttendees table; a guest who RSVPs is told they are in.\n\n## OKRs\n\n<div data-docs-demo=\"522-base-okrs\" data-height=\"640\"></div>\n\nTwo tables, Key results and Objectives. A key result measures something from\na start value to a target; its progress is a formula,\n`MAX(0, MIN(1, ({Current} - {Start}) / ({Target} - {Start})))`, and its\nconfidence says whether it will get there. An objective has a quarter and an\nowner, and averages the progress of its key results with a rollup.\n\n![OKRs: Key results link to one objective; Objectives list their key results and average their progress.](/docs-media/base-template-okrs.svg)\n\n- **By objective:** key results grouped by objective, colored by confidence.\n- **Confidence:** a Kanban.\n- **Weekly check-in:** the numbers to update, least recently checked first.\n- **Progress by objective:** a bar chart of the rollup.\n\nAutomations: a key result that falls Off track turns red and raises a\nnotice; one that reaches its target is marked Achieved.\n\n## Expense approvals\n\n<div data-docs-demo=\"523-base-expenses\" data-height=\"640\"></div>\n\nTwo tables, Expenses and Budgets. An expense has an amount, a category, a\ndate, who spent it, a receipt, a status from Draft to Paid, and who approved\nit and when. A budget category lists its expenses, adds up what was spent\n(a rollup) and shows what is left (a formula over the rollup).\n\n![Expense approvals: Expenses link to one category; Budgets list their expenses, sum them, and work out what is left.](/docs-media/base-template-expenses.svg)\n\n- **This month:** newest first, colored by status, totals in the footer.\n- **Approvals:** a Kanban by status.\n- **Spend by category:** a pie of the amounts.\n- **Receipts:** a gallery.\n- **Submit an expense:** the form.\n\nAutomations: an expense over $1,000 goes to Needs approval; **Approve** in\nthe Review column approves it and records who and when; a rejected expense\nturns red; one sent with the form starts as Submitted; a category over its\nbudget raises a notice.\n\n## Employee onboarding\n\n<div data-docs-demo=\"524-base-onboarding\" data-height=\"640\"></div>\n\nThree tables: People, Checklist and Departments. A person has a photo, a\nrole, a department, a manager, a start date and a status; checklist items\nhave an owner (IT, HR or the manager) and a due date; departments list their\npeople and count them.\n\n![Employee onboarding: Checklist items link to one person; People link to one department and list their checklist; Departments list their people.](/docs-media/base-template-onboarding.svg)\n\n- **Pipeline:** a Kanban by status.\n- **Photo directory:** a gallery.\n- **Start dates:** a calendar.\n- **By department:** grouped by department.\n- **Add a new hire:** the form.\n\nAutomations: a new hire, from \"+ Add row\" or the form, gets a checklist:\nthree items for IT, HR and their manager, created in Checklist and linked\nback. Someone starting within a week has their start date colored, and\n**Activate** in the Ready column marks them Active.\n\n## Start from your own database\n\nEvery template here is also a database. `npm create @svgrid@latest my-base\n-- -t base` offers each one by name and writes it as SQL to `db/schema.sql`,\nwith its records, views and automations, on Postgres in the browser, your\nown Postgres or Supabase ([From a database to an app](./quick-start.md)):\n\n```bash\nnpm create @svgrid@latest my-base -- -t base --data supabase --sample bug-tracker\n```\n\nThe names: `project-tracker`, `sales-crm`, `content-calendar`,\n`product-roadmap`, `hiring-tracker`, `inventory`, `bug-tracker`,\n`event-planning`, `okrs`, `expenses`, `onboarding`. A base you changed\nhere goes the same way: \"All tables\", then **Download as SQL**.\n"
5114
5250
  },
5251
+ {
5252
+ "slug": "help/base/undo-trash-import",
5253
+ "path": "docs/help/base/undo-trash-import.md",
5254
+ "title": "Undo, the trash and importing files",
5255
+ "section": "SvGrid Base",
5256
+ "markdown": "# Undo, the trash and importing files\n\nThree things people reach for in their first week with a base: Ctrl+Z after\na slip, getting back a record someone deleted yesterday, and pulling in the\nspreadsheet they kept until now. All three work on `<SvBase tables>` with no\nsetup; this page says what each one does and how an app keeps it.\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\n## Undo and redo\n\nCtrl+Z (Cmd+Z on a Mac) undoes what was done to the shown table, in the\norder it was done. Ctrl+Shift+Z or Ctrl+Y redoes it. The keys work anywhere\nin the base, and also with nothing focused on the page (after a dialog\ncloses, or a click beside the base): then the base used last takes them. A\nkey typed in a field of your own page stays yours. One history holds:\n\n- cell edits, pastes and fills (the grid's own history);\n- records added, deleted or imported from a file;\n- fields added, changed (a new type, new options) or deleted.\n\nUndoing a deleted record puts it back at the place it had, and the links the\ndelete cleared come back too: delete a task and its project stops listing\nit; undo, and the project lists it again. The step restores the records of\nevery table the change touched.\n\nThe Undo and Redo buttons at the end of the tab bar say what the next press\ndoes (\"Undo delete 2 records\"). `undoRedo={false}` hides them; the keys still\nwork. Each table keeps its history while another table is shown, so going\nback to a table carries on where you left it. View settings (a filter, a\nsort) are not part of the history: a view keeps them as you leave it.\n\n<div data-docs-demo=\"705-base-undo-redo\" data-height=\"620\"></div>\n\n## The trash\n\nA deleted record, field or table goes to the trash. The trash button at the\nend of the tab bar shows how many items it holds and opens a list, newest\nfirst, with who deleted each one (`setCurrentUser`) and when. Restore puts an\nitem back:\n\n- a record in its table, at the place it had, with its links;\n- a field with its values (the values stay in the records while the field is\n in the trash);\n- a table as a tab, with the fields of other tables that linked to it made\n again from its side.\n\nThe notice that appears after a delete has a Restore button too. A record\nwhose table is in the trash waits until the table is restored; the dialog\nsays so.\n\nThe trash is plain data. Bind it and store it next to the tables:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, type BaseTable, type BaseTrashItem } from '@svgrid/enterprise/base'\n\n enableBase()\n let tables = $state.raw<BaseTable[]>(loadTables())\n let trash = $state<BaseTrashItem[]>(loadTrash())\n</script>\n\n<SvBase bind:tables bind:trash trashDays={30} editable onTablesChange={saveTables} onTrashChange={saveTrash} />\n```\n\nItems older than `trashDays` (30 by default, 0 for no limit) are dropped when\nthe base opens. `restoreItems(tables, items)` puts items back in code, for an\nadmin screen that restores from a stored trash.\n\n| `BaseTrashItem.kind` | Also holds |\n|---|---|\n| `'record'` | `table` (id), `row`, `index` |\n| `'field'` | `table` (id), `column`, `index` |\n| `'table'` | `table` (the whole `BaseTable`), `index` |\n\nEvery item has `id`, `deletedAt` (ISO time) and, when someone is signed in,\n`deletedBy` (a user id).\n\n<div data-docs-demo=\"706-base-trash\" data-height=\"620\"></div>\n\n## Import a CSV or Excel file\n\nThe tab bar's menus import a CSV, TSV, Excel (.xlsx) or JSON file. The file\nis read in the page; nothing is uploaded.\n\n- **As a new table** (the list of tables, \"Import a file as a table\"): each\n column becomes a field, the first one naming the records. The type comes\n from the column's values and the dialog shows each guess to change before\n the import.\n- **Into the shown table** (the table's menu, \"Import records from a file\"):\n each column goes to the field it names, matched by name or id in any case.\n A column that matches nothing is skipped unless you point it at a field. A\n value a select does not have becomes a new option.\n\n| Values in the column | Field type |\n|---|---|\n| `$1,200`, `€80.50` | Number as currency, with the symbol |\n| `25%` | Number as percent (0 to 100) |\n| `yes` / `no`, `true` / `false`, `x` | Checkbox |\n| `42`, `3.75` | Number (integer or decimal) |\n| `ana@example.com` | Email |\n| `https://...` | URL |\n| `2026-11-02`, `02/11/2026` | Date (with the time when there is one) |\n| `+1 415 555 0100` | Phone |\n| A few short values, repeated | Single select, a color per value |\n| `Design, Copy`, items repeated | Multiple select |\n| Long text or line breaks | Long text |\n| Anything else | Single line text |\n\nAn import into a table is one undo step. An app that already has a file (a\ndrop zone of its own, a download) opens the same dialog with it:\n\n```svelte\n<script lang=\"ts\">\n let base = $state<ReturnType<typeof SvBase> | null>(null)\n</script>\n\n<SvBase bind:this={base} bind:tables editable />\n<button onclick={() => base?.openImport('append', file)}>Import</button>\n```\n\n`openImport('new', file)` makes a new table from it. In code, without the\ndialog, `tableFromMatrix(rows, tables, name)` builds a table from a header row\nand rows of text, and `recordsFromMatrix(rows, table, matchColumns(header,\ntable))` turns them into records of an existing table. `fileImport={false}`\nremoves the menu items.\n\n<div data-docs-demo=\"709-base-import-csv-excel\" data-height=\"620\"></div>\n\n## Next\n\n- [Views for every team](./views.md): personal and locked views, and the\n layout on a phone.\n- [Collaboration](./collaboration.md): who is signed in, comments and\n @mentions.\n- [Keep a base in a database](./data.md): a restored or imported record is\n written back like any other change.\n"
5257
+ },
5115
5258
  {
5116
5259
  "slug": "help/base/views",
5117
5260
  "path": "docs/help/base/views.md",
5118
5261
  "title": "Views for every team",
5119
5262
  "section": "SvGrid Base",
5120
- "markdown": "# Views for every team\n\nOne table of records, many ways to look at it. Product reads the roadmap\ngrouped by quarter, engineering works off a status board, the leads check a\ntimeline, and anyone in the company files a request through a form. Each of\nthose is a saved view: a name, a type, and the filter, sorts, groups, hidden\nfields, row height and colors it had when someone last left it.\n\n![The Features table feeds six saved views: Roadmap by quarter (a grid grouped by Quarter, sorted by Impact, Lead hidden, row height 56, colored by Status), Now (a grid filtered to active work), Status board (a Kanban stacked by Status), Timeline (a calendar from Start to Target), Effort by team (a bar chart) and Request a feature (a form). onViewsChange hands the whole list to the app, which stores it and loads it back into bind:views.](/docs-media/base-views.svg)\n\n<div data-docs-demo=\"513-base-product-roadmap\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThis page builds the Features table of that roadmap one view at a time. Each\nstep adds to the `views` list from the step before and works on its own.\n\n## 1. The table\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, setFieldUsers, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n setFieldUsers([\n { id: 'u1', name: 'Ana Ruiz' },\n { id: 'u2', name: 'Ben Okafor' },\n { id: 'u3', name: 'Cleo Park' },\n ])\n\n type Feature = {\n id: number; feature: string; quarter: string; status: string; teams: string[]\n lead: string; impact: number; effort: number; start: string; target: string; votes: number\n }\n\n const QUARTERS = [\n { value: 'Q4 2026', color: '#2d7ff9' },\n { value: 'Q1 2027', color: '#18bfff' },\n { value: 'Later', color: '#94a3b8' },\n ]\n const STATUS = [\n { value: 'Planned', color: '#94a3b8' },\n { value: 'In progress', color: '#2d7ff9' },\n { value: 'In beta', color: '#8b46ff' },\n { value: 'Shipped', color: '#20c933' },\n { value: 'Blocked', color: '#f82b60' },\n ]\n const TEAMS = [\n { value: 'Web', color: '#2d7ff9' },\n { value: 'Mobile', color: '#ff6f2c' },\n { value: 'Platform', color: '#8b46ff' },\n ]\n\n let rows = $state.raw<Feature[]>([\n { id: 1, feature: 'Single sign-on with SAML', quarter: 'Q4 2026', status: 'In progress', teams: ['Platform'], lead: 'u2', impact: 5, effort: 12, start: '2026-10-05', target: '2026-11-13', votes: 182 },\n { id: 2, feature: 'Offline mode for the mobile app', quarter: 'Q4 2026', status: 'Blocked', teams: ['Mobile'], lead: 'u3', impact: 4, effort: 13, start: '2026-10-12', target: '2026-12-04', votes: 96 },\n { id: 3, feature: 'Dark mode', quarter: 'Q4 2026', status: 'Shipped', teams: ['Web'], lead: 'u1', impact: 2, effort: 4, start: '2026-10-01', target: '2026-10-16', votes: 154 },\n { id: 4, feature: 'Audit log export', quarter: 'Q1 2027', status: 'Planned', teams: ['Platform', 'Web'], lead: 'u1', impact: 3, effort: 5, start: '2027-01-11', target: '2027-01-29', votes: 41 },\n ])\n\n const columns = [\n { field: 'feature', header: 'Feature', width: 260, fieldType: 'text' },\n { field: 'quarter', header: 'Quarter', fieldType: 'singleSelect', fieldProps: { options: QUARTERS } },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'teams', header: 'Teams', fieldType: 'multiSelect', fieldProps: { options: TEAMS } },\n { field: 'lead', header: 'Lead', fieldType: 'user' },\n { field: 'impact', header: 'Impact', fieldType: 'rating', fieldProps: { max: 5 } },\n { field: 'effort', header: 'Effort (days)', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n { field: 'start', header: 'Start', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'target', header: 'Target', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'votes', header: 'Votes', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n ]\n\n let views = $state<FieldView[]>([{ id: 'all', name: 'All features', type: 'grid' }])\n</script>\n\n<SvBase data={rows} {columns} bind:views primaryField=\"feature\"\n editable sortable showRowNumbers expandRows summary containerHeight={640}\n rowAdder={{ label: 'Add feature', defaults: () => ({ id: Date.now(), status: 'Planned', quarter: 'Later', teams: [] }) }} />\n```\n\nThe view bar over the grid has \"All features\" on the left, then Hide\nfields, Filter, Group, Sort, Color and a row height button, and \"4 records\"\nwith a search button on the right. The footer row shows \"Sum 34\" under Effort\nand \"Sum 473\" under Votes, because those fields set `fieldProps.summary`.\n\nEvery view key that names a field (`stackBy`, `dateField`, a filter\ncondition's `column`, a chart's `x`) takes the column id. A column without an\n`id` uses its `field`, so in this table the two are the same.\n\n## 2. A roadmap grouped by quarter\n\nA view can start with settings. `state` is the grid's own state, the same\nobject `api.getState()` returns; `color` says how rows are colored.\n\n```ts\nconst roadmap: FieldView = {\n id: 'roadmap',\n name: 'Roadmap by quarter',\n type: 'grid',\n color: { mode: 'field', field: 'status' },\n rowHeight: 56,\n state: {\n grouping: ['quarter'],\n sorting: [{ id: 'quarter', desc: false }, { id: 'impact', desc: true }],\n hiddenColumns: ['lead'],\n },\n}\n```\n\nGroups and sorts share the grid's `sorting` list: a grouped field's\ndirection is an entry ahead of the sorts. The view bar writes them that way,\nso write them that way too. Here the bar reads \"1 hidden field\", \"Grouped by\n1 field\" and \"Sorted by 1 field\": the `quarter` entry belongs to the group,\nnot to Sort.\n\nEach group header shows \"Quarter\" over the option's pill, the number of\nrecords, the summaries the fields picked for that group (\"Effort (days) 29\",\n\"Votes 432\"), and \"+\" to add a feature that already has that quarter. Groups\ncome in the select's option order, not alphabetically. Group rows are at\nleast 52px tall so the field's name fits over the value; with\n`rowHeight: 56` they match the records. Each row has a status color stripe\non its row header. 56 is the row height menu's \"Medium\": from 48px, text and\nselect pills wrap.\n\n## 3. A view that starts filtered\n\nThe filter is the grid's advanced filter with its own kind, `fieldFilter`.\nPut it in `state.advancedFilter`:\n\n```ts\nimport { describeFieldFilter, type FieldFilter } from '@svgrid/enterprise/base'\n\nconst activeWork: FieldFilter = {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'status', kind: 'select', op: 'isAnyOf', value: ['In progress', 'In beta', 'Blocked'] },\n {\n conjunction: 'or',\n conditions: [\n { column: 'target', kind: 'date', op: 'isWithin', value: { span: 'nextDays', days: 30 } },\n { column: 'impact', kind: 'number', op: 'gte', value: 4 },\n ],\n },\n ],\n}\n\nconst now: FieldView = {\n id: 'now',\n name: 'Now',\n type: 'grid',\n state: { sorting: [{ id: 'target', desc: false }], advancedFilter: activeWork },\n}\n\nconst header = (id: string) => columns.find((c) => c.field === id)?.header ?? id\ndescribeFieldFilter(activeWork, header)\n// \"Status is any of In progress, In beta, Blocked and (Target is within the next 30 days or Impact ≥ 4)\"\n```\n\nThe Filter button reads \"Filtered by 3 fields\" (one field reads \"Filtered by\nStatus\") and the record count drops to what the filter keeps.\n`describeFieldFilter` writes a filter in the words the panel uses, for a page\nsubtitle or an audit line. It returns `\"every record\"` for a filter with no\ncomplete conditions.\n\nA condition is a field, an operator and a value; a group is one level deep.\n[Filters in code](#filters-in-code) below lists the operators per kind.\n\nOne view can serve every lead. `ME` (the string `'@me'`) in a person\ncondition stands for whoever `setCurrentUser` names when the filter runs; the\nFilter panel lists it as \"Me\", first among the people.\n\n```ts\nimport { ME, setCurrentUser } from '@svgrid/enterprise/base'\n\nsetCurrentUser({ id: 'u2', name: 'Ben Okafor' })\n\nconst mine: FieldView = {\n id: 'mine',\n name: 'My features',\n type: 'grid',\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [{ column: 'lead', kind: 'select', op: 'is', value: ME }],\n },\n },\n}\n```\n\nBen sees \"Single sign-on with SAML\"; Ana, signed in, sees her two. With\nnobody signed in the condition matches no one. `describeFieldFilter` writes\nit as \"Lead is me\".\n\n## 4. A status board\n\n```ts\nconst board: FieldView = { id: 'board', name: 'Status board', type: 'kanban', stackBy: 'status' }\n```\n\n![The roadmap's Status board: Planned, In progress, In beta and Shipped lanes of feature cards showing Quarter, Teams and Lead, with the right-click menu open on \"Single sign-on with SAML\": Expand record, Comment, Move to, Duplicate record, Delete record.](/docs-media/base-views.png)\n\n`stackBy` takes a single select or a user field that holds one person. You\nget one lane per option, in option order and color, plus \"Uncategorized\",\nwhich shows only while a record has no status. Stack by `lead` instead and\nthe lanes are the people from `setFieldUsers`.\n\nDrop a card in another lane and the status changes through the grid's edit\npath, so undo, validation and `onCellValueChange` all see it. \"+ Add a card\"\nadds a record already in that lane, named by the primary field.\n\nA card shows the record's name, then the next three fields the view shows,\nin column order (the stacked field left out), each drawn as its cell draws\nit. Hide a field in Hide fields and it leaves the cards; drag it up there to\nput it on them. Cards are read, not edited: a rating shows its stars\nbut does not take a click. Double-click a card or press F2 to open the\nrecord. Right-click it for its menu: Expand record, Comment, and, when the\nbase is `editable`, Move to (a submenu of the lanes), Duplicate record and\nDelete record, which asks \"Delete record?\" first. A card with comments shows\ntheir count; click it to open the record at its comment box.\n\n## 5. A timeline\n\n```ts\nconst timeline: FieldView = {\n id: 'timeline',\n name: 'Timeline',\n type: 'calendar',\n dateField: 'start',\n endField: 'target',\n color: { mode: 'field', field: 'status' },\n}\n```\n\nEach feature spans its start to its target date. A date field without a time\nshows as all-day events. Drag an event to move both dates; drag its edge to\nchange the target. The calendar's end is exclusive, so the record keeps the\nlast day: a feature dragged to cover the 19th to the 21st gets\n`target: '2026-10-21'`.\n\nWith only `dateField`, events move but cannot be resized. Pick a day (or a\nrange) on the calendar and a new record lands on it, opened with its name\nready to type. Colored by a single select, the events take the option colors\nand the options appear above the calendar as a legend that hides and shows\nthem.\n\nMoving and resizing need `editable` on the base. Without it the calendar is\nread-only.\n\n## 6. Effort by team\n\n```ts\nconst effort: FieldView = { id: 'effort', name: 'Effort by team', type: 'chart', chart: { kind: 'barH', x: 'teams', y: 'effort' } }\nconst mix: FieldView = { id: 'mix', name: 'Features per quarter', type: 'chart', chart: { kind: 'donut', x: 'quarter' } }\n```\n\nA chart groups the records the view shows by `x` and adds up `y` (or counts\nrecords when there is no `y`). `aggregation: 'avg'` averages instead of\nsumming. Kinds are `'bar'`, `'barH'`, `'line'`, `'pie'` and `'donut'`.\n\nHow `x` groups:\n\n- A single or multiple select keeps its options' order and colors. A\n multiple select counts a record in each of its options, so \"Audit log\n export\" adds 5 days to both Platform and Web.\n- A person or a linked record shows by name.\n- A date groups by month (\"Oct 2026\").\n- Records with no value go in an \"Empty\" bar, last.\n\nValues read as the summed field writes them, and a count as a whole number.\nThe series is labeled \"Sum of Effort (days)\", \"Average of ...\" or \"Records\".\nThe bar shows Filter, which narrows what is charted, and \"Customize chart\",\nwhose Type, Group by, Value and Combine (sum or average) are kept in `chart`.\nA chart view declared without `chart` draws \"Choose a field to chart in\nCustomize chart.\" until a field is picked there.\n\n## 7. A gallery of mockups\n\nAdd an attachment field, then a gallery view with it as the cover:\n\n```ts\nconst mockupField = { field: 'mockups', header: 'Mockups', fieldType: 'attachment' }\nconst gallery: FieldView = { id: 'mockups', name: 'Mockups', type: 'gallery', coverField: 'mockups' }\n```\n\nEach card shows the first image of `mockups`, the primary field as its title,\nthen the fields the grid shows, each drawn as its cell draws it. Hide a field\nin this view and it leaves the cards; drag fields in Hide fields to reorder\nthem. A click on a card opens the record. Without `coverField` the cards have\nno cover.\n\n## 8. A request form\n\n```ts\nconst request: FieldView = {\n id: 'request',\n name: 'Request a feature',\n type: 'form',\n formFields: ['feature', 'teams', 'impact'],\n formRequired: ['feature'],\n formTitle: 'Request a feature',\n formDescription: 'What should we build, and who is it for? Product reviews requests every Friday.',\n formSubmitLabel: 'Send request',\n}\n```\n\nThe form asks for the fields in `formFields` (column ids, in order), each with\nthe editor its cell uses. Without it, the form asks for every field a person\ncan fill in, the primary field first; computed fields are left out. A field\nin `formRequired` must be filled before the form sends. `formTitle` defaults\nto the view's name, `formSubmitLabel` to \"Submit\". A sent form adds a record\nthe way \"+ Add row\" does: `rowAdder.defaults` first, so a request starts as\nPlanned in Later, then what was typed, then `onRowAdd`. The bar shows only\nthe view switcher on a form.\n\nAll the views so far, in one list:\n\n```ts\nlet views = $state<FieldView[]>([roadmap, board, timeline, effort, now, mine, gallery, request])\n```\n\n## 9. Keep the views\n\n`onViewsChange` fires with the whole list when a view is created, renamed,\nduplicated or deleted, and about 400ms after the shown view's settings stop\nchanging. Switching views stores the one being left first. Store the list\nwherever the app stores things.\n\nIn the browser:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n const KEY = 'roadmap:views'\n const DEFAULT_VIEWS: FieldView[] = [{ id: 'all', name: 'All features', type: 'grid' }]\n\n function read<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key)\n return raw ? (JSON.parse(raw) as T) : fallback\n } catch {\n return fallback\n }\n }\n function write(key: string, value: unknown) {\n try {\n localStorage.setItem(key, JSON.stringify(value))\n } catch {\n // Private mode or a full quota: the views still work, unsaved.\n }\n }\n\n let views = $state<FieldView[]>(read(KEY, DEFAULT_VIEWS))\n let activeView = $state<string>(read(`${KEY}:active`, ''))\n\n $effect(() => write(`${KEY}:active`, activeView))\n</script>\n\n<SvBase data={rows} {columns} primaryField=\"feature\" editable\n bind:views bind:activeView onViewsChange={(v: FieldView[]) => write(KEY, v)} />\n```\n\nOn a server, decide who owns a list.\n\n- **Per user.** Each person keeps their own list, so one lead's filter does\n not change another's. Seed it from the team's defaults the first time.\n- **Shared.** One list per table that everyone reads. Write it only for the\n people you allow; for everyone else, keep their changes in memory or in\n their own list. A shared \"My features\" view built on `ME` still shows each\n person their own records.\n\n```ts\ntype Scope = 'me' | 'team'\n\nasync function loadViews(scope: Scope): Promise<FieldView[]> {\n const res = await fetch(`/api/tables/features/views?scope=${scope}`)\n return res.ok ? ((await res.json()) as FieldView[]) : DEFAULT_VIEWS\n}\n\nfunction saveViews(scope: Scope, next: FieldView[]) {\n void fetch(`/api/tables/features/views?scope=${scope}`, {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(next),\n })\n}\n```\n\n```svelte\n{#await loadViews('me') then loaded}\n <SvBase data={rows} {columns} primaryField=\"feature\" editable\n views={loaded} onViewsChange={(v: FieldView[]) => saveViews('me', v)} />\n{/await}\n```\n\nOr mount at once and swap the list in when it arrives. When `views` or\n`activeView` changes from outside and the shown view is not the one the grid\nhas, the bar applies it. It never stores the grid's settings into a view it\nhas not applied yet.\n\n```svelte\n<script lang=\"ts\">\n let views = $state<FieldView[]>(DEFAULT_VIEWS)\n let loaded = false\n loadViews('me').then((v) => {\n views = v\n loaded = true\n })\n</script>\n\n<SvBase data={rows} {columns} primaryField=\"feature\" editable\n bind:views onViewsChange={(v: FieldView[]) => loaded && saveViews('me', v)} />\n```\n\nThe `loaded` check matters: about 400ms after mount the bar stores the\ndefault view's settings, and that save must not replace the list on the\nserver before the real one is in.\n\nWith several tables (`<SvBase bind:tables>`), each table keeps its own\n`views`, and `onTablesChange` hands back the whole list of tables, views\nincluded.\n\n## View types and the keys they read\n\n| Type | Keys | View bar buttons |\n|---|---|---|\n| `'grid'` | `state`, `rowHeight`, `color` | Hide fields, Filter, Group, Sort, Color, Row height |\n| `'kanban'` | `stackBy`: a single select, or a user field with one person | Hide fields, Filter, Sort |\n| `'calendar'` | `dateField`, `endField` (optional), `color` | Hide fields, Filter, Sort, Color |\n| `'gantt'` | `dateField`, `endField`, `progressField`, `dependencyField`, `zoom`, `color` | Hide fields, Filter, Sort, Color, Customize timeline |\n| `'gallery'` | `coverField`: an attachment field | Hide fields, Filter, Sort |\n| `'chart'` | `chart`: `kind`, `x`, `y`, `aggregation` | Filter, Customize chart |\n| `'form'` | `formFields`, `formRequired`, `formTitle`, `formDescription`, `formSubmitLabel` | none |\n\nEvery type also keeps `state` (filter, sorts, groups, hidden fields, column\norder, widths, pinning) and switches with the grid's own state, so a filter\nset on the board is still there when you come back to it. The search text is\nnot part of it. The views menu's \"Create\" offers each type `SvBase` can show\nand greys out one the table cannot: a Kanban needs a single select, a\ncalendar a date field, a chart a field to group by. A new view starts with no\nfilter, sorts or groups and every field shown.\n`viewTypes={['grid', 'kanban', 'calendar']}` on `SvBase` limits what\n\"Create\" offers.\n\nA Gantt is a calendar with a task table beside the bars. It is offered once\nthe app has called `enableGanttView()` from `@svgrid/enterprise`. Its bars\ntake the view's colors, `progressField` is a percent field drawn as each\nbar's fill, and `dependencyField` is a link field to the same table naming\nwhat each record waits for, drawn as arrows.\n\n## The view bar, panel by panel\n\n- **Views menu** (the view's name): switch, rename, duplicate (\"Roadmap by\n quarter copy\") and delete. The last view cannot be deleted.\n- **Hide fields**: a switch per field, a search, hide all and show all, and\n drag to reorder. The primary field is always shown.\n- **Filter**: \"Where [field] [operator] [value]\" rows joined by \"and\" or\n \"or\", and condition groups. Each change filters at once. A condition still\n missing its value filters nothing.\n- **Group**: up to three fields, each with a direction.\n- **Sort**: fields in order, each with a direction labeled for its type (\"1\n → 9\", \"A → Z\", \"first → last\" for a single select). Attachment and button\n fields are not offered.\n- **Color**: None, Select field (a single select's option colors) or\n Conditions in order.\n- **Row height**: Short 34, Medium 56, Tall 88, Extra tall 128.\n `rowHeights` on `SvBase` or `SvBaseViewBar` sets the list.\n- **Search**: in a grid view, the grid's find bar (Ctrl+F) that marks every\n match. In a board, calendar or gallery, a \"Find a record\" box that narrows\n the records. Switching views clears it.\n\nA button with something set says so and is tinted. With `fieldMenu` on, each\ncolumn's menu adds \"Filter by this field\" and \"Group by this field\", which\nopen the bar's panel with the new condition or group in it.\n\n## Filters in code\n\n`filterKindOf(columnDef)` gives the kind a field filters as, and\n`operatorsFor(kind)` the operators the panel offers for it, in menu order.\n[Filter conditions](../fields.md#filter-conditions) maps each field type to\nits kind.\n\n| `kind` | `op` values | `value` |\n|---|---|---|\n| `'text'`, `'link'` | `contains`, `notContains`, `is`, `isNot` | a string; a link compares the linked records' names |\n| `'number'` | `eq`, `neq`, `lt`, `gt`, `lte`, `gte` | a number |\n| `'select'` | `is`, `isNot` | one option value, or a person's id (or `ME`) for a user field |\n| `'select'` | `isAnyOf`, `isNoneOf` | an array of them |\n| `'multi'` | `hasAnyOf`, `hasAllOf`, `isExactly`, `hasNoneOf` | an array of option values or ids |\n| `'checkbox'` | `is` | `true` or `false` |\n| `'date'` | `is`, `isBefore`, `isAfter`, `isOnOrBefore`, `isOnOrAfter` | `{ mode: 'today' }`, with `mode` also `'tomorrow'`, `'yesterday'`, `'oneWeekAgo'`, `'oneWeekFromNow'`, `'oneMonthAgo'`, `'oneMonthFromNow'`; or `{ mode: 'exactDate', date: '2026-11-01' }` |\n| `'date'` | `isWithin` | `{ span: 'pastWeek' }`, with `span` also `'pastMonth'`, `'pastYear'`, `'nextWeek'`, `'nextMonth'`, `'nextYear'`; or `{ span: 'pastDays', days: 14 }`, `{ span: 'nextDays', days: 14 }` |\n| `'files'` | `contains` (file name contains) | a string |\n\nEvery kind except checkbox also takes `isEmpty` and `isNotEmpty`, with no\nvalue. A few rules from the code:\n\n- An empty number cell is no number: it matches only `neq`.\n- Dates compare whole days. A bare `'2026-11-01'` is that day where the user\n is, and \"within the past week\" runs from 7 days ago to today.\n- A user condition holds the person's id (`'u2'`), not the name, or `ME`\n for whoever is signed in.\n- A link condition sets `table` to the linked table's id, so it can match\n records by name.\n\nSet a filter on the shown view with `api.setAdvancedFilter(filter)`; the\nview keeps it like one set in the panel.\n\n## Row colors: by field or by conditions\n\n```ts\nimport type { ColorSetting } from '@svgrid/enterprise/base'\n\nconst byStatus: ColorSetting = { mode: 'field', field: 'status' }\nconst byRisk: ColorSetting = {\n mode: 'conditions',\n rules: [\n { color: '#f82b60', condition: { column: 'status', kind: 'select', op: 'is', value: 'Blocked' } },\n { color: '#fcb400', condition: { column: 'target', kind: 'date', op: 'isBefore', value: { mode: 'today' } } },\n ],\n}\n```\n\nBy field, each row takes its option's color, and the row header's title says\nthe option, so the color is never the only signal. A multiple select colors\nby its first value. By conditions, the first rule that matches wins: a\nblocked feature is red even when it is also late. A condition is tested as\nthe filter tests it: on the value the cell shows, so a formula, lookup,\nrollup or count field works, and a condition still missing its value colors\nnothing. A calendar colors its events by a single select only; a Gantt's bars\ntake either kind.\n\nThe color is a 3px stripe on the row header, unless the `rowColor` prop on\n`SvBase` sets a `target` (`'bar'` or `'row'`): a view's colors use it too. A\nview without `color` shows the `rowColor` prop's colors until someone picks\ncolors for it in Color. `{ mode: 'none' }` turns the colors off in that view.\n\n## Summaries in the footer and in group headers\n\nWith `summary` on, a click on a field's footer cell picks its summary: sum,\naverage, median, min, max or range for numbers; checked, unchecked or percent\nchecked for a checkbox; earliest, latest or the date range in days for dates;\nempty, filled, unique, percent empty or percent filled for any field. The\nresult is written as the field writes values. The choice is stored in the\nfield's `fieldProps.summary` and reported through `onColumnChange`; see\n[Summaries at the bottom](../fields.md#summaries-at-the-bottom).\n\nGroup headers show the same summaries over that group's records. Both leave\nout records the filter hides, even in a collapsed group.\n\n## The view bar over your own grid\n\n`SvBaseViewBar` is the bar alone, for a page that lays out its own\n`<SvGrid>`:\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n import { SvBaseViewBar, enableBase, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n // Raw: the bar finds its grid by the api object itself, and a proxy is another object.\n let api = $state.raw<any>(null)\n let views = $state<FieldView[]>([\n { id: 'all', name: 'All features', type: 'grid' },\n { id: 'board', name: 'Status board', type: 'kanban', stackBy: 'status' },\n ])\n let activeView = $state('all')\n</script>\n\n{#if api}\n <SvBaseViewBar {api} bind:views bind:activeView\n rowHeights={[{ label: 'Compact', height: 32 }, { label: 'Roomy', height: 64 }]} />\n{/if}\n<SvGrid data={rows} {columns} primaryField=\"feature\" editable containerHeight={600}\n onApiReady={(a) => (api = a)} />\n```\n\nIts \"Create\" offers grid, Kanban and calendar (and Gantt once enabled). It\nloads the board, calendar and gallery renderers the first time a view of\nthat type is shown, and opens the record and the \"Delete record?\" question\nfor a card's menu. Chart and form views are drawn by `SvBase`, not by the\nbar, so leave them out of `viewTypes` here, or draw `SvBaseForm` yourself\nwhen a form view is active.\n\n## Pitfalls\n\n- **A new view from \"Create\" starts with `color: { mode: 'none' }`**, so it\n hides the `rowColor` prop's colors. A new calendar or Gantt is the\n exception: it starts colored by the first single select. Pick colors in\n Color, or declare the view in code without `color`.\n- **`color.field` is the data field; the other keys are column ids.** They\n differ only when a column sets an `id`.\n- **Summaries belong to the field, not the view.** Picking \"Average\" in one\n view changes every view's footer and group headers.\n- **Save views only after they load.** See the `loaded` check in step 9.\n\n## Next\n\n- [Linked records](./linked-records.md): link Features to Feedback and chart\n or filter by the linked names.\n- [Formulas](./formulas.md): computed fields a view can sort, group and chart\n by.\n- [Forms](./forms.md): required fields, the thank-you screen and forms\n outside the base.\n- [Collaboration](./collaboration.md): comments, people and who changed what.\n- [Automations](./automations.md): conditions written with this same filter.\n- [Keep a base in a database](./data.md): load the tables from Postgres,\n Supabase or your API and write every change back.\n"
5263
+ "markdown": "# Views for every team\n\nOne table of records, many ways to look at it. Product reads the roadmap\ngrouped by quarter, engineering works off a status board, the leads check a\ntimeline, and anyone in the company files a request through a form. Each of\nthose is a saved view: a name, a type, and the filter, sorts, groups, hidden\nfields, row height and colors it had when someone last left it.\n\n![The Features table feeds six saved views: Roadmap by quarter (a grid grouped by Quarter, sorted by Impact, Lead hidden, row height 56, colored by Status), Now (a grid filtered to active work), Status board (a Kanban stacked by Status), Timeline (a calendar from Start to Target), Effort by team (a bar chart) and Request a feature (a form). onViewsChange hands the whole list to the app, which stores it and loads it back into bind:views.](/docs-media/base-views.svg)\n\n<div data-docs-demo=\"513-base-product-roadmap\" data-height=\"680\"></div>\n\n> SvGrid Base is part of the **Suite edition** of `@svgrid/enterprise`. Without a key it runs with a watermark.\n\nThis page builds the Features table of that roadmap one view at a time. Each\nstep adds to the `views` list from the step before and works on its own.\n\n## 1. The table\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, setFieldUsers, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n setFieldUsers([\n { id: 'u1', name: 'Ana Ruiz' },\n { id: 'u2', name: 'Ben Okafor' },\n { id: 'u3', name: 'Cleo Park' },\n ])\n\n type Feature = {\n id: number; feature: string; quarter: string; status: string; teams: string[]\n lead: string; impact: number; effort: number; start: string; target: string; votes: number\n }\n\n const QUARTERS = [\n { value: 'Q4 2026', color: '#2d7ff9' },\n { value: 'Q1 2027', color: '#18bfff' },\n { value: 'Later', color: '#94a3b8' },\n ]\n const STATUS = [\n { value: 'Planned', color: '#94a3b8' },\n { value: 'In progress', color: '#2d7ff9' },\n { value: 'In beta', color: '#8b46ff' },\n { value: 'Shipped', color: '#20c933' },\n { value: 'Blocked', color: '#f82b60' },\n ]\n const TEAMS = [\n { value: 'Web', color: '#2d7ff9' },\n { value: 'Mobile', color: '#ff6f2c' },\n { value: 'Platform', color: '#8b46ff' },\n ]\n\n let rows = $state.raw<Feature[]>([\n { id: 1, feature: 'Single sign-on with SAML', quarter: 'Q4 2026', status: 'In progress', teams: ['Platform'], lead: 'u2', impact: 5, effort: 12, start: '2026-10-05', target: '2026-11-13', votes: 182 },\n { id: 2, feature: 'Offline mode for the mobile app', quarter: 'Q4 2026', status: 'Blocked', teams: ['Mobile'], lead: 'u3', impact: 4, effort: 13, start: '2026-10-12', target: '2026-12-04', votes: 96 },\n { id: 3, feature: 'Dark mode', quarter: 'Q4 2026', status: 'Shipped', teams: ['Web'], lead: 'u1', impact: 2, effort: 4, start: '2026-10-01', target: '2026-10-16', votes: 154 },\n { id: 4, feature: 'Audit log export', quarter: 'Q1 2027', status: 'Planned', teams: ['Platform', 'Web'], lead: 'u1', impact: 3, effort: 5, start: '2027-01-11', target: '2027-01-29', votes: 41 },\n ])\n\n const columns = [\n { field: 'feature', header: 'Feature', width: 260, fieldType: 'text' },\n { field: 'quarter', header: 'Quarter', fieldType: 'singleSelect', fieldProps: { options: QUARTERS } },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: STATUS } },\n { field: 'teams', header: 'Teams', fieldType: 'multiSelect', fieldProps: { options: TEAMS } },\n { field: 'lead', header: 'Lead', fieldType: 'user' },\n { field: 'impact', header: 'Impact', fieldType: 'rating', fieldProps: { max: 5 } },\n { field: 'effort', header: 'Effort (days)', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n { field: 'start', header: 'Start', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'target', header: 'Target', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'votes', header: 'Votes', fieldType: 'number', fieldProps: { format: 'integer', summary: 'sum' } },\n ]\n\n let views = $state<FieldView[]>([{ id: 'all', name: 'All features', type: 'grid' }])\n</script>\n\n<SvBase data={rows} {columns} bind:views primaryField=\"feature\"\n editable sortable showRowNumbers expandRows summary containerHeight={640}\n rowAdder={{ label: 'Add feature', defaults: () => ({ id: Date.now(), status: 'Planned', quarter: 'Later', teams: [] }) }} />\n```\n\nThe view bar over the grid has \"All features\" on the left, then Hide\nfields, Filter, Group, Sort, Color and a row height button, and \"4 records\"\nwith a search button on the right. The footer row shows \"Sum 34\" under Effort\nand \"Sum 473\" under Votes, because those fields set `fieldProps.summary`.\n\nEvery view key that names a field (`stackBy`, `dateField`, a filter\ncondition's `column`, a chart's `x`) takes the column id. A column without an\n`id` uses its `field`, so in this table the two are the same.\n\n## 2. A roadmap grouped by quarter\n\nA view can start with settings. `state` is the grid's own state, the same\nobject `api.getState()` returns; `color` says how rows are colored.\n\n```ts\nconst roadmap: FieldView = {\n id: 'roadmap',\n name: 'Roadmap by quarter',\n type: 'grid',\n color: { mode: 'field', field: 'status' },\n rowHeight: 56,\n state: {\n grouping: ['quarter'],\n sorting: [{ id: 'quarter', desc: false }, { id: 'impact', desc: true }],\n hiddenColumns: ['lead'],\n },\n}\n```\n\nGroups and sorts share the grid's `sorting` list: a grouped field's\ndirection is an entry ahead of the sorts. The view bar writes them that way,\nso write them that way too. Here the bar reads \"1 hidden field\", \"Grouped by\n1 field\" and \"Sorted by 1 field\": the `quarter` entry belongs to the group,\nnot to Sort.\n\nEach group header shows \"Quarter\" over the option's pill, the number of\nrecords, the summaries the fields picked for that group (\"Effort (days) 29\",\n\"Votes 432\"), and \"+\" to add a feature that already has that quarter. Groups\ncome in the select's option order, not alphabetically. Group rows are at\nleast 52px tall so the field's name fits over the value; with\n`rowHeight: 56` they match the records. Each row has a status color stripe\non its row header. 56 is the row height menu's \"Medium\": from 48px, text and\nselect pills wrap.\n\n## 3. A view that starts filtered\n\nThe filter is the grid's advanced filter with its own kind, `fieldFilter`.\nPut it in `state.advancedFilter`:\n\n```ts\nimport { describeFieldFilter, type FieldFilter } from '@svgrid/enterprise/base'\n\nconst activeWork: FieldFilter = {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'status', kind: 'select', op: 'isAnyOf', value: ['In progress', 'In beta', 'Blocked'] },\n {\n conjunction: 'or',\n conditions: [\n { column: 'target', kind: 'date', op: 'isWithin', value: { span: 'nextDays', days: 30 } },\n { column: 'impact', kind: 'number', op: 'gte', value: 4 },\n ],\n },\n ],\n}\n\nconst now: FieldView = {\n id: 'now',\n name: 'Now',\n type: 'grid',\n state: { sorting: [{ id: 'target', desc: false }], advancedFilter: activeWork },\n}\n\nconst header = (id: string) => columns.find((c) => c.field === id)?.header ?? id\ndescribeFieldFilter(activeWork, header)\n// \"Status is any of In progress, In beta, Blocked and (Target is within the next 30 days or Impact ≥ 4)\"\n```\n\nThe Filter button reads \"Filtered by 3 fields\" (one field reads \"Filtered by\nStatus\") and the record count drops to what the filter keeps.\n`describeFieldFilter` writes a filter in the words the panel uses, for a page\nsubtitle or an audit line. It returns `\"every record\"` for a filter with no\ncomplete conditions.\n\nA condition is a field, an operator and a value; a group is one level deep.\n[Filters in code](#filters-in-code) below lists the operators per kind.\n\nOne view can serve every lead. `ME` (the string `'@me'`) in a person\ncondition stands for whoever `setCurrentUser` names when the filter runs; the\nFilter panel lists it as \"Me\", first among the people.\n\n```ts\nimport { ME, setCurrentUser } from '@svgrid/enterprise/base'\n\nsetCurrentUser({ id: 'u2', name: 'Ben Okafor' })\n\nconst mine: FieldView = {\n id: 'mine',\n name: 'My features',\n type: 'grid',\n state: {\n advancedFilter: {\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [{ column: 'lead', kind: 'select', op: 'is', value: ME }],\n },\n },\n}\n```\n\nBen sees \"Single sign-on with SAML\"; Ana, signed in, sees her two. With\nnobody signed in the condition matches no one. `describeFieldFilter` writes\nit as \"Lead is me\".\n\n## 4. A status board\n\n```ts\nconst board: FieldView = { id: 'board', name: 'Status board', type: 'kanban', stackBy: 'status' }\n```\n\n![The roadmap's Status board: Planned, In progress, In beta and Shipped lanes of feature cards showing Quarter, Teams and Lead, with the right-click menu open on \"Single sign-on with SAML\": Expand record, Comment, Move to, Duplicate record, Delete record.](/docs-media/base-views.png)\n\n`stackBy` takes a single select or a user field that holds one person. You\nget one lane per option, in option order and color, plus \"Uncategorized\",\nwhich shows only while a record has no status. Stack by `lead` instead and\nthe lanes are the people from `setFieldUsers`.\n\nDrop a card in another lane and the status changes through the grid's edit\npath, so undo, validation and `onCellValueChange` all see it. \"+ Add a card\"\nadds a record already in that lane, named by the primary field.\n\nA card shows the record's name, then the next three fields the view shows,\nin column order (the stacked field left out), each drawn as its cell draws\nit. Hide a field in Hide fields and it leaves the cards; drag it up there to\nput it on them. Cards are read, not edited: a rating shows its stars\nbut does not take a click. Double-click a card or press F2 to open the\nrecord. Right-click it for its menu: Expand record, Comment, and, when the\nbase is `editable`, Move to (a submenu of the lanes), Duplicate record and\nDelete record, which asks \"Delete record?\" first. A card with comments shows\ntheir count; click it to open the record at its comment box.\n\n## 5. A timeline\n\n```ts\nconst timeline: FieldView = {\n id: 'timeline',\n name: 'Timeline',\n type: 'calendar',\n dateField: 'start',\n endField: 'target',\n color: { mode: 'field', field: 'status' },\n}\n```\n\nEach feature spans its start to its target date. A date field without a time\nshows as all-day events. Drag an event to move both dates; drag its edge to\nchange the target. The calendar's end is exclusive, so the record keeps the\nlast day: a feature dragged to cover the 19th to the 21st gets\n`target: '2026-10-21'`.\n\nWith only `dateField`, events move but cannot be resized. Pick a day (or a\nrange) on the calendar and a new record lands on it, opened with its name\nready to type. Colored by a single select, the events take the option colors\nand the options appear above the calendar as a legend that hides and shows\nthem.\n\nMoving and resizing need `editable` on the base. Without it the calendar is\nread-only.\n\n## 6. Effort by team\n\n```ts\nconst effort: FieldView = { id: 'effort', name: 'Effort by team', type: 'chart', chart: { kind: 'barH', x: 'teams', y: 'effort' } }\nconst mix: FieldView = { id: 'mix', name: 'Features per quarter', type: 'chart', chart: { kind: 'donut', x: 'quarter' } }\n```\n\nA chart groups the records the view shows by `x` and adds up `y` (or counts\nrecords when there is no `y`). `aggregation: 'avg'` averages instead of\nsumming. Kinds are `'bar'`, `'barH'`, `'line'`, `'pie'` and `'donut'`.\n\nHow `x` groups:\n\n- A single or multiple select keeps its options' order and colors. A\n multiple select counts a record in each of its options, so \"Audit log\n export\" adds 5 days to both Platform and Web.\n- A person or a linked record shows by name.\n- A date groups by month (\"Oct 2026\").\n- Records with no value go in an \"Empty\" bar, last.\n\nValues read as the summed field writes them, and a count as a whole number.\nThe series is labeled \"Sum of Effort (days)\", \"Average of ...\" or \"Records\".\nThe bar shows Filter, which narrows what is charted, and \"Customize chart\",\nwhose Type, Group by, Value and Combine (sum or average) are kept in `chart`.\nA chart view declared without `chart` draws \"Choose a field to chart in\nCustomize chart.\" until a field is picked there.\n\n## 7. A gallery of mockups\n\nAdd an attachment field, then a gallery view with it as the cover:\n\n```ts\nconst mockupField = { field: 'mockups', header: 'Mockups', fieldType: 'attachment' }\nconst gallery: FieldView = { id: 'mockups', name: 'Mockups', type: 'gallery', coverField: 'mockups' }\n```\n\nEach card shows the first image of `mockups`, the primary field as its title,\nthen the fields the grid shows, each drawn as its cell draws it. Hide a field\nin this view and it leaves the cards; drag fields in Hide fields to reorder\nthem. A click on a card opens the record. Without `coverField` the cards have\nno cover.\n\n## 8. A request form\n\n```ts\nconst request: FieldView = {\n id: 'request',\n name: 'Request a feature',\n type: 'form',\n formFields: ['feature', 'teams', 'impact'],\n formRequired: ['feature'],\n formTitle: 'Request a feature',\n formDescription: 'What should we build, and who is it for? Product reviews requests every Friday.',\n formSubmitLabel: 'Send request',\n}\n```\n\nThe form asks for the fields in `formFields` (column ids, in order), each with\nthe editor its cell uses. Without it, the form asks for every field a person\ncan fill in, the primary field first; computed fields are left out. A field\nin `formRequired` must be filled before the form sends. `formTitle` defaults\nto the view's name, `formSubmitLabel` to \"Submit\". A sent form adds a record\nthe way \"+ Add row\" does: `rowAdder.defaults` first, so a request starts as\nPlanned in Later, then what was typed, then `onRowAdd`. The bar shows only\nthe view switcher on a form.\n\nAll the views so far, in one list:\n\n```ts\nlet views = $state<FieldView[]>([roadmap, board, timeline, effort, now, mine, gallery, request])\n```\n\n## 9. A dashboard\n\n```ts\nconst OPEN: FieldFilter = { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'isNot', value: 'Shipped' }] }\nconst SHIPPED: FieldFilter = { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'is', value: 'Shipped' }] }\n\nconst overview: FieldView = {\n id: 'overview',\n name: 'Overview',\n type: 'dashboard',\n dashboard: [\n { id: 'open', kind: 'number', title: 'Open features', filter: OPEN },\n { id: 'days', kind: 'number', title: 'Days of work left', aggregation: 'sum', field: 'effort', filter: OPEN, caption: 'Team capacity 40 days' },\n { id: 'shipped', kind: 'progress', title: 'Shipped', filter: SHIPPED },\n { id: 'status', kind: 'chart', chart: { kind: 'bar', x: 'status' } },\n { id: 'wanted', kind: 'list', title: 'Most wanted', sortBy: 'votes', sortDesc: true, limit: 3 },\n ],\n}\n```\n\nA dashboard is a grid of tiles. Each tile reads the records of one table,\nkeeps the ones its `filter` matches (the same `FieldFilter` as a view's\nfilter), and shows one of four things:\n\n- **`'number'`** counts the records, or with `aggregation: 'sum' | 'avg' |\n 'min' | 'max'` and a number `field`, adds them up. The number is written the\n way the field writes it, so a currency field shows \"$42,000\". Here \"Open\n features\" reads 3 and \"Days of work left\" reads 30. `caption` is a line\n under the number.\n- **`'chart'`** takes a chart view's `chart` setting (`kind`, `x`, `y`,\n `aggregation`) and groups the tile's records the same way.\n- **`'list'`** shows the first `limit` records (5 by default) sorted by\n `sortBy`, with that field's value beside each name (\"Single sign-on with\n SAML 182\"); `detail` shows another field instead. A click opens the record.\n- **`'progress'`** shows how many of all the table's records match the filter:\n \"25%, 1 of 4 records\" for Shipped.\n\n`size` is `'1x1'`, `'2x1'` or `'2x2'` (columns by rows). A number or progress\ntile is `'1x1'` by default, a chart or list `'2x2'`. Below about 450px the\ntiles stack in one column. A tile without `title` is named after what it\nshows (\"Total Effort (days)\", \"Status is Shipped\").\n\nWith several tables (`<SvBase bind:tables>`), a tile's `table` names any\ntable of the base, so a dashboard on Deals can count Accounts and list the\nActivities due this week. A tile without `table` reads the table the view is\non. Its filter and fields are that table's.\n\nA number or progress tile is a button: a click, or Enter, lists the records\nit counts (\"Open the 3 records\") in a dialog, each with its name and a few\nof its fields. On a chart, a click on a bar or a slice lists the records in\nit: the records the tile's filter keeps that fall in that bucket. A click on a record in the dialog opens it, in its\nown table's tab when the tile reads another table. While the dashboard is\nbeing edited, the tiles open nothing.\n\n\"Edit dashboard\" at the top of the view adds a tile, and on each tile sets its\nsize, moves it (drag it, or the arrows), edits it in a dialog (kind, table,\nvalue, filter, title, size) or removes it. Every change is saved in the view's\n`dashboard` at once and reaches `onViewsChange` and `onTablesChange`. A locked\nview has no \"Edit dashboard\". The view bar shows only the view switcher on a\ndashboard.\n\n<div data-docs-demo=\"721-base-dashboard\" data-height=\"680\"></div>\n\n## 10. A list for the phone\n\n```ts\nconst list: FieldView = {\n id: 'list',\n name: 'Feature list',\n type: 'list',\n listFields: ['status', 'teams', 'votes'],\n state: { sorting: [{ id: 'quarter', desc: false }, { id: 'votes', desc: true }], grouping: ['quarter'], hiddenColumns: [], advancedFilter: null },\n}\n```\n\nA list shows one record per entry: the primary field in bold, and under it\nthe fields in `listFields` (column ids, in order), each drawn as its cell\ndraws it, so Status is a colored pill and Teams are tags. An empty value is\nleft out. Without `listFields` the list shows the next three fields the grid\nshows. Long names stay readable at phone width, where a grid would cut them.\n\nThe list keeps the view's filter, sorts and groups. Here it is grouped by\nQuarter: a header per quarter with the field's name, its value and the\nnumber of records, \"Quarter Q4 2026 3\", and a click on the header folds the\ngroup. Within each quarter the most voted feature comes first. Grouped by\nmore fields (`grouping: ['quarter', 'status']`), each quarter holds a header\nper status, indented under it, with its own count and its own fold.\n\nA click on a record, or Enter, opens it. The list is one tab stop: Up and\nDown move between records and group headers at every level, Home and End\njump, Left and Right fold and unfold a group, and Left on a record or a\nfolded group moves to the group it is in. A record someone else changed and nobody here\nopened yet has a dot before its name.\n\nThe view bar has Hide fields, Filter, Group, Sort and \"Customize list\", which\nturns the fields under the name on and off and saves them in `listFields`.\n\n<div data-docs-demo=\"719-base-list-view\" data-height=\"620\"></div>\n\n## 11. An inbox of changes\n\n```ts\nconst inbox: FieldView = {\n id: 'inbox',\n name: 'Inbox',\n type: 'inbox',\n inboxDateField: 'start',\n listFields: ['status', 'lead'],\n}\n```\n\nAn inbox shows the records on the left and the picked one on the right: its\nfields, each one editable in place with the editor its cell uses, and its\nlatest changes, \"Cleo Park changed Status: Planned → In progress\". \"Expand\"\nopens the full record with its comments.\n\nThe list is newest first by `inboxDateField` (a date field's column id), so\n\"Audit log export\", which starts on January 11, is on top.\nRecords without a date go last. Without `inboxDateField` the inbox keeps the\nview's sort. The view's filter applies either way.\n\nA record someone else changed and nobody here has opened is unread: its name\nis bold and it has a dot. The changes come from a table with a `source` that\nhears of writes made elsewhere ([Changes made\nelsewhere](./data.md#changes-made-elsewhere)). Picking a record marks it read,\nas opening it in any view does, and \"Mark all read\" marks the rest. The count\nat the top says \"2 unread\" or \"All read\".\n\nDown or j picks the next record and Up or k the previous one; Enter opens the\nfull record. Narrower than 640px the inbox shows the list, and a picked record\nfills it with a Back button (Escape goes back too).\n\nThe view bar has Hide fields, Filter, Sort and \"Customize inbox\": the date\nfield it lists by and the fields under each name. A field hidden in the view\nleaves the record on the right too.\n\n<div data-docs-demo=\"720-base-inbox-view\" data-height=\"620\"></div>\n\n## 12. Keep the views\n\n`onViewsChange` fires with the whole list when a view is created, renamed,\nduplicated or deleted, and about 400ms after the shown view's settings stop\nchanging. Switching views stores the one being left first. Store the list\nwherever the app stores things.\n\nIn the browser:\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n const KEY = 'roadmap:views'\n const DEFAULT_VIEWS: FieldView[] = [{ id: 'all', name: 'All features', type: 'grid' }]\n\n function read<T>(key: string, fallback: T): T {\n try {\n const raw = localStorage.getItem(key)\n return raw ? (JSON.parse(raw) as T) : fallback\n } catch {\n return fallback\n }\n }\n function write(key: string, value: unknown) {\n try {\n localStorage.setItem(key, JSON.stringify(value))\n } catch {\n // Private mode or a full quota: the views still work, unsaved.\n }\n }\n\n let views = $state<FieldView[]>(read(KEY, DEFAULT_VIEWS))\n let activeView = $state<string>(read(`${KEY}:active`, ''))\n\n $effect(() => write(`${KEY}:active`, activeView))\n</script>\n\n<SvBase data={rows} {columns} primaryField=\"feature\" editable\n bind:views bind:activeView onViewsChange={(v: FieldView[]) => write(KEY, v)} />\n```\n\nOn a server, decide who owns a list.\n\n- **Per user.** Each person keeps their own list, so one lead's filter does\n not change another's. Seed it from the team's defaults the first time.\n- **Shared.** One list per table that everyone reads. Write it only for the\n people you allow; for everyone else, keep their changes in memory or in\n their own list. A shared \"My features\" view built on `ME` still shows each\n person their own records.\n\n```ts\ntype Scope = 'me' | 'team'\n\nasync function loadViews(scope: Scope): Promise<FieldView[]> {\n const res = await fetch(`/api/tables/features/views?scope=${scope}`)\n return res.ok ? ((await res.json()) as FieldView[]) : DEFAULT_VIEWS\n}\n\nfunction saveViews(scope: Scope, next: FieldView[]) {\n void fetch(`/api/tables/features/views?scope=${scope}`, {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(next),\n })\n}\n```\n\n```svelte\n{#await loadViews('me') then loaded}\n <SvBase data={rows} {columns} primaryField=\"feature\" editable\n views={loaded} onViewsChange={(v: FieldView[]) => saveViews('me', v)} />\n{/await}\n```\n\nOr mount at once and swap the list in when it arrives. When `views` or\n`activeView` changes from outside and the shown view is not the one the grid\nhas, the bar applies it. It never stores the grid's settings into a view it\nhas not applied yet.\n\n```svelte\n<script lang=\"ts\">\n let views = $state<FieldView[]>(DEFAULT_VIEWS)\n let loaded = false\n loadViews('me').then((v) => {\n views = v\n loaded = true\n })\n</script>\n\n<SvBase data={rows} {columns} primaryField=\"feature\" editable\n bind:views onViewsChange={(v: FieldView[]) => loaded && saveViews('me', v)} />\n```\n\nThe `loaded` check matters: about 400ms after mount the bar stores the\ndefault view's settings, and that save must not replace the list on the\nserver before the real one is in.\n\nWith several tables (`<SvBase bind:tables>`), each table keeps its own\n`views`, and `onTablesChange` hands back the whole list of tables, views\nincluded.\n\n## Personal and locked views\n\nOnce several people share a table, two more keys on a view matter:\n\n```ts\nconst views: FieldView[] = [\n // Only Ana sees it, under \"My views\" in the views menu.\n { id: 'ana-open', name: 'My open tasks', type: 'grid', personal: 'u1', state: { /* ... */ } },\n // Everyone sees it; nobody changes its settings until someone unlocks it.\n { id: 'report', name: 'Leadership report', type: 'grid', locked: true, lockedBy: 'u2', state: { /* ... */ } },\n]\n```\n\n- **`personal: userId`** lists the view only for that person, read from\n `setCurrentUser`. With nobody signed in every view is listed. \"Create\" in\n the views menu has a \"Personal view: only I see it\" box once someone is\n signed in.\n- **`locked: true`** keeps the view's filter, sorts, groups, hidden fields,\n colors and row height as saved. Its settings buttons are off, nothing is\n saved into it, and the bar shows \"Locked\" with who locked it. A sort from a\n column header still works for the moment; the bar then says \"Locked, not\n saved\" with a Reset. Records stay editable. A locked view cannot be\n deleted, and a copy of it starts unlocked.\n\nThe lock button in the views menu locks the view as the grid shows it now,\nor unlocks it. `lockViews={false}` on `SvBase` removes it for people who may\nnot lock views. Both keys come back through `onViewsChange` and\n`onTablesChange`, so the app stores a personal view with its owner the same\nway as the others.\n\n<div data-docs-demo=\"710-base-personal-locked-views\" data-height=\"620\"></div>\n\n## On a phone\n\nWhen a table is narrower than 600px (its own width, not the window's), a\ngrid view shows each record as a card: the primary field, then the next four\nfields the view shows, in the view's filter and sort. A tap opens the\nrecord, \"+\" adds one, and on a phone screen the opened record fills it. The\nview bar keeps its icons and the tab bar its tabs. Kanban, calendar, gallery\nand form views stay as they are.\n\n`phoneLayout` on `SvBase` moves the breakpoint (`phoneLayout={480}`), turns\nthe cards on at every width (`true`) or keeps the grid (`false`).\n\n<div data-docs-demo=\"713-base-phone-layout\" data-height=\"720\"></div>\n\n## Search across tables\n\nThe view bar's search finds records in the view on screen. The box at the\nend of the tab bar searches every table of the base. With the focus in the\nbase, Ctrl+K puts the cursor in it, and so does \"/\" outside the grid and any\ntext box. Neither is taken from the rest of the page.\n\nIt reads a field the way its cell shows it: a single select by its option's\nlabel, a person by name, a date as the field writes it, a link by the names\nof the records it links to, a formula or lookup by its result. Numbers,\ncurrency, percents, durations, ratings, checkboxes, buttons, rollups and\ncounts are not searched. Case and accents do not count: \"tomas\" finds\n\"Tomás\".\n\nEvery word of the query has to be in the record, in one field or another.\nThe results are grouped by table, five records each with \"N more in Deals\"\nunder them, each with its name, the field the words were found in and the\nwords marked. Records rank by:\n\n1. the whole query in one field, before words spread over several;\n2. the primary field, before the others;\n3. a field that is the query, then one that starts with it, then one with a\n word that starts with it, then one that holds it anywhere.\n\nTables are listed by their best record. Up and Down move through the list,\nEnter or a click shows the record's table and opens the record, and Escape\ncloses the list, then clears the box. `search={false}` on `SvBase` leaves the\nbox out. A shared base (`readOnly`) keeps it, over the tables and fields the\nshare shows.\n\nThe same search runs without the box, for a command palette of your own or\non a server:\n\n```ts\nimport { searchBase } from '@svgrid/enterprise/base'\n\nconst groups = searchBase(tables, 'northwind proposal', { limit: 10 })\nfor (const g of groups) {\n console.log(g.name, g.total)\n for (const hit of g.hits) console.log(hit.rowId, hit.title, `${hit.fieldName}: ${hit.text}`, hit.marks)\n}\n```\n\nEach hit has the table and record ids, the record's name (`title`), the\nfield that matched (`field`, `fieldName`, `primary`), its text cut around\nthe match when it is long, and `marks`, the `[start, end)` spans of the\nwords in that text. `field: (table, column) => boolean` in the options picks\nthe fields to search. To open a hit in `SvBase`, show its table\n(`bind:activeTable`) and call `openRecord({ api, rowId })` once that table's\ngrid has called `onApiReady`; the box does this for you.\n\n<div data-docs-demo=\"718-base-search-all-tables\" data-height=\"620\"></div>\n\n## View types and the keys they read\n\n| Type | Keys | View bar buttons |\n|---|---|---|\n| `'grid'` | `state`, `rowHeight`, `color` | Hide fields, Filter, Group, Sort, Color, Row height |\n| `'kanban'` | `stackBy`: a single select, or a user field with one person | Hide fields, Filter, Sort |\n| `'calendar'` | `dateField`, `endField` (optional), `color` | Hide fields, Filter, Sort, Color |\n| `'gantt'` | `dateField`, `endField`, `progressField`, `dependencyField`, `zoom`, `color` | Hide fields, Filter, Sort, Color, Customize timeline |\n| `'gallery'` | `coverField`: an attachment field | Hide fields, Filter, Sort |\n| `'chart'` | `chart`: `kind`, `x`, `y`, `aggregation` | Filter, Customize chart |\n| `'list'` | `listFields`: the fields under each name | Hide fields, Filter, Group, Sort, Customize list |\n| `'inbox'` | `inboxDateField`: a date field, newest first; `listFields` | Hide fields, Filter, Sort, Customize inbox |\n| `'form'` | `formFields`, `formRequired`, `formTitle`, `formDescription`, `formSubmitLabel`, `formConditions`, `formPrefill` | none |\n| `'dashboard'` | `dashboard`: the tiles, in order | none |\n| any type | `personal`, `locked`, `lockedBy` | off while `locked` |\n\nEvery type also keeps `state` (filter, sorts, groups, hidden fields, column\norder, widths, pinning) and switches with the grid's own state, so a filter\nset on the board is still there when you come back to it. The search text is\nnot part of it. The views menu's \"Create\" offers each type `SvBase` can show\nand greys out one the table cannot: a Kanban needs a single select, a\ncalendar a date field, a chart a field to group by. A new view starts with no\nfilter, sorts or groups and every field shown.\n`viewTypes={['grid', 'kanban', 'calendar']}` on `SvBase` limits what\n\"Create\" offers.\n\nA Gantt is a calendar with a task table beside the bars. It is offered once\nthe app has called `enableGanttView()` from `@svgrid/enterprise`. Its bars\ntake the view's colors, `progressField` is a percent field drawn as each\nbar's fill, and `dependencyField` is a link field to the same table naming\nwhat each record waits for, drawn as arrows.\n\n## The view bar, panel by panel\n\n- **Views menu** (the view's name): switch, rename, duplicate (\"Roadmap by\n quarter copy\") and delete. The last view cannot be deleted.\n- **Hide fields**: a switch per field, a search, hide all and show all, and\n drag to reorder. The primary field is always shown.\n- **Filter**: \"Where [field] [operator] [value]\" rows joined by \"and\" or\n \"or\", and condition groups. Each change filters at once. A condition still\n missing its value filters nothing.\n- **Group**: up to three fields, each with a direction.\n- **Sort**: fields in order, each with a direction labeled for its type (\"1\n → 9\", \"A → Z\", \"first → last\" for a single select). Attachment and button\n fields are not offered.\n- **Color**: None, Select field (a single select's option colors) or\n Conditions in order.\n- **Row height**: Short 34, Medium 56, Tall 88, Extra tall 128.\n `rowHeights` on `SvBase` or `SvBaseViewBar` sets the list.\n- **Search**: in a grid view, the grid's find bar (Ctrl+F) that marks every\n match. In a board, calendar, gallery, list or inbox, a \"Find a record\" box\n that narrows the records. Switching views clears it.\n- **Search all tables**: the box in the tab bar (below).\n\nA button with something set says so and is tinted. With `fieldMenu` on, each\ncolumn's menu adds \"Filter by this field\" and \"Group by this field\", which\nopen the bar's panel with the new condition or group in it.\n\n## Filters in code\n\n`filterKindOf(columnDef)` gives the kind a field filters as, and\n`operatorsFor(kind)` the operators the panel offers for it, in menu order.\n[Filter conditions](../fields.md#filter-conditions) maps each field type to\nits kind.\n\n| `kind` | `op` values | `value` |\n|---|---|---|\n| `'text'`, `'link'` | `contains`, `notContains`, `is`, `isNot` | a string; a link compares the linked records' names |\n| `'number'` | `eq`, `neq`, `lt`, `gt`, `lte`, `gte` | a number |\n| `'select'` | `is`, `isNot` | one option value, or a person's id (or `ME`) for a user field |\n| `'select'` | `isAnyOf`, `isNoneOf` | an array of them |\n| `'multi'` | `hasAnyOf`, `hasAllOf`, `isExactly`, `hasNoneOf` | an array of option values or ids |\n| `'checkbox'` | `is` | `true` or `false` |\n| `'date'` | `is`, `isBefore`, `isAfter`, `isOnOrBefore`, `isOnOrAfter` | `{ mode: 'today' }`, with `mode` also `'tomorrow'`, `'yesterday'`, `'oneWeekAgo'`, `'oneWeekFromNow'`, `'oneMonthAgo'`, `'oneMonthFromNow'`; or `{ mode: 'exactDate', date: '2026-11-01' }` |\n| `'date'` | `isWithin` | `{ span: 'pastWeek' }`, with `span` also `'pastMonth'`, `'pastYear'`, `'nextWeek'`, `'nextMonth'`, `'nextYear'`; or `{ span: 'pastDays', days: 14 }`, `{ span: 'nextDays', days: 14 }` |\n| `'files'` | `contains` (file name contains) | a string |\n\nEvery kind except checkbox also takes `isEmpty` and `isNotEmpty`, with no\nvalue. A few rules from the code:\n\n- An empty number cell is no number: it matches only `neq`.\n- Dates compare whole days. A bare `'2026-11-01'` is that day where the user\n is, and \"within the past week\" runs from 7 days ago to today.\n- A user condition holds the person's id (`'u2'`), not the name, or `ME`\n for whoever is signed in.\n- A link condition sets `table` to the linked table's id, so it can match\n records by name.\n\nSet a filter on the shown view with `api.setAdvancedFilter(filter)`; the\nview keeps it like one set in the panel.\n\n## Row colors: by field or by conditions\n\n```ts\nimport type { ColorSetting } from '@svgrid/enterprise/base'\n\nconst byStatus: ColorSetting = { mode: 'field', field: 'status' }\nconst byRisk: ColorSetting = {\n mode: 'conditions',\n rules: [\n { color: '#f82b60', condition: { column: 'status', kind: 'select', op: 'is', value: 'Blocked' } },\n { color: '#fcb400', condition: { column: 'target', kind: 'date', op: 'isBefore', value: { mode: 'today' } } },\n ],\n}\n```\n\nBy field, each row takes its option's color, and the row header's title says\nthe option, so the color is never the only signal. A multiple select colors\nby its first value. By conditions, the first rule that matches wins: a\nblocked feature is red even when it is also late. A condition is tested as\nthe filter tests it: on the value the cell shows, so a formula, lookup,\nrollup or count field works, and a condition still missing its value colors\nnothing. A calendar colors its events by a single select only; a Gantt's bars\ntake either kind.\n\nThe color is a 3px stripe on the row header, unless the `rowColor` prop on\n`SvBase` sets a `target` (`'bar'` or `'row'`): a view's colors use it too. A\nview without `color` shows the `rowColor` prop's colors until someone picks\ncolors for it in Color. `{ mode: 'none' }` turns the colors off in that view.\n\n## Summaries in the footer and in group headers\n\nWith `summary` on, a click on a field's footer cell picks its summary: sum,\naverage, median, min, max or range for numbers; checked, unchecked or percent\nchecked for a checkbox; earliest, latest or the date range in days for dates;\nempty, filled, unique, percent empty or percent filled for any field. The\nresult is written as the field writes values. The choice is stored in the\nfield's `fieldProps.summary` and reported through `onColumnChange`; see\n[Summaries at the bottom](../fields.md#summaries-at-the-bottom).\n\nGroup headers show the same summaries over that group's records. Both leave\nout records the filter hides, even in a collapsed group.\n\n## The view bar over your own grid\n\n`SvBaseViewBar` is the bar alone, for a page that lays out its own\n`<SvGrid>`:\n\n```svelte\n<script lang=\"ts\">\n import { SvGrid } from '@svgrid/grid'\n import { SvBaseViewBar, enableBase, type FieldView } from '@svgrid/enterprise/base'\n\n enableBase()\n // Raw: the bar finds its grid by the api object itself, and a proxy is another object.\n let api = $state.raw<any>(null)\n let views = $state<FieldView[]>([\n { id: 'all', name: 'All features', type: 'grid' },\n { id: 'board', name: 'Status board', type: 'kanban', stackBy: 'status' },\n ])\n let activeView = $state('all')\n</script>\n\n{#if api}\n <SvBaseViewBar {api} bind:views bind:activeView\n rowHeights={[{ label: 'Compact', height: 32 }, { label: 'Roomy', height: 64 }]} />\n{/if}\n<SvGrid data={rows} {columns} primaryField=\"feature\" editable containerHeight={600}\n onApiReady={(a) => (api = a)} />\n```\n\nIts \"Create\" offers grid, Kanban and calendar (and Gantt once enabled). It\nloads the board, calendar and gallery renderers the first time a view of\nthat type is shown, and opens the record and the \"Delete record?\" question\nfor a card's menu. Chart and form views are drawn by `SvBase`, not by the\nbar, so leave them out of `viewTypes` here, or draw `SvBaseForm` yourself\nwhen a form view is active.\n\n## Pitfalls\n\n- **A new view from \"Create\" starts with `color: { mode: 'none' }`**, so it\n hides the `rowColor` prop's colors. A new calendar or Gantt is the\n exception: it starts colored by the first single select. Pick colors in\n Color, or declare the view in code without `color`.\n- **`color.field` is the data field; the other keys are column ids.** They\n differ only when a column sets an `id`.\n- **Summaries belong to the field, not the view.** Picking \"Average\" in one\n view changes every view's footer and group headers.\n- **Save views only after they load.** See the `loaded` check in step 12.\n\n## Next\n\n- [Linked records](./linked-records.md): link Features to Feedback and chart\n or filter by the linked names.\n- [Formulas](./formulas.md): computed fields a view can sort, group and chart\n by.\n- [Forms](./forms.md): required fields, the thank-you screen and forms\n outside the base.\n- [Collaboration](./collaboration.md): comments, people and who changed what.\n- [Automations](./automations.md): conditions written with this same filter.\n- [Keep a base in a database](./data.md): load the tables from Postgres,\n Supabase or your API and write every change back.\n"
5121
5264
  },
5122
5265
  {
5123
5266
  "slug": "help/benchmarks",
5124
5267
  "path": "docs/help/benchmarks.md",
5125
5268
  "title": "Performance benchmarks",
5126
5269
  "section": "Help",
5127
- "markdown": "# Performance benchmarks\n\nEvery number on this page is produced by a checked-in script:\n\n| Table | Command | Where it runs |\n| -------------------------- | --------------- | ------------- |\n| Bundle size | `pnpm size` | Node |\n| Sort / filter / group, memory | `pnpm bench` | Node |\n| First paint, scroll | `pnpm bench:dom` | Chromium |\n\nAn earlier version of this page published a table of timings that no\nscript produced, and told readers to reproduce them with a `pnpm bench`\ncommand that did not exist. Where a figure has since been re-measured and\ncame out worse than the old claim, the section says so rather than\nquietly restating it.\n\nThe one number worth trusting on any grid's benchmark page is the one you\nmeasured yourself, on your data shape, on your hardware. The\n[benchmark harness recipe](../recipes/benchmark-harness.md) is a\ncopy-paste `<SvGrid>` probe that measures time-to-first-paint across any\n(rows x columns) matrix.\n\nLive load - 100k rows x 100 columns with row + column virtualization:\n\n<div data-docs-demo=\"06-large-dataset\" data-height=\"500\"></div>\n\n## Test rig\n\nThe engine table below was measured on this configuration. Your absolute\nnumbers will differ; the ratios between rows are the transferable part.\n\n| Component | Spec |\n| --------- | ------------------------------------------------ |\n| Machine | Developer workstation, win32 x64. Not a dedicated bench rig |\n| Engine | Node v24.18.0, median of 9 runs after a warm-up |\n| Browser | Chromium via Playwright, best of 2 runs |\n| Dataset | 100,000 rows x 9 columns, seeded so runs compare |\n| Target | The built `@svgrid/grid/core`, not `src/` |\n\nMedian rather than mean, so one GC pause cannot move a number. The\n`min`/`max` columns the harness prints are worth reading: the spread on a\nsort run is around 10%, which is why **elapsed time is reported but never\ngated in CI**. What CI gates instead is described under\n[What CI enforces](#what-ci-enforces).\n\n## Bundle size\n\nProduction build, gzipped, Svelte excluded as a peer. The table is\ngenerated from `docs/_data/svgrid-size.json` by `node tools/sync-guide-facts.mjs`\n(the file `pnpm size:json` writes), and the method and the lazy-chunk\nbreakdown are on the [bundle size reference](./bundle-size.md). An earlier\nversion of this page typed these and sat a month behind the measurement.\n\n<!-- size:start -->\nRe-measured **30 Oct 2026** at `@svgrid/grid` 3.0.30 with the script that ships in the repo (`pnpm size:json`):\n\n| Target | Base JS (gzip) | CSS (gzip) | Loaded on demand |\n| --- | ---: | ---: | ---: |\n| Headless core (`createSvGrid`) | **3.2 KB** | - | - |\n| Headless subpath (`@svgrid/grid/core`) | **10.0 KB** | - | - |\n| Full render component (`<SvGrid>`) | **100.0 KB** | **11.3 KB** | **198.9 KB** |\n| Standalone chart (`<SvChart>`) | **71.9 KB** | - | **15.0 KB** |\n<!-- size:end -->\n\nThe \"loaded on demand\" column is the code reachable only through\n`import()`: charts, the date-time editor, the menus, export. Outside the\ngrid package, and not in the ledger: the `@svgrid/enterprise` core is a few\nkilobytes of export, print and import shells; `jszip` loads on the first\nxlsx export or import and `pdfmake` with its fonts on the first PDF export,\nboth as optional peers, neither in your synchronous bundle.\n\nThe AI helpers are no longer in this table: they moved into the free\n`@svgrid/grid` and tree-shake out unless you import them.\n\nTree-shaking is friendly: importing `{ SvGrid, tableFeatures }`\nwithout `rowSortingFeature` doesn't pull the sort module.\n\n## First paint\n\n**Measured.** Run `pnpm bench:dom`. Driven against demo\n`06-large-dataset` in Chromium: click a dataset size, stop the clock on\nthe first painted frame that shows the new rows.\n\n| Scenario | Total | Building the data | Grid |\n| ------------------- | -------- | ----------------- | ------- |\n| 1,000 x 29 cols | 180 ms | 3 ms | 177 ms |\n| 10,000 x 53 cols | 315 ms | 31 ms | 284 ms |\n| 50,000 x 77 cols | 652 ms | 220 ms | 432 ms |\n| 100,000 x 100 cols | 1,205 ms | 633 ms | 572 ms |\n\n\"Building the data\" is the demo generating synthetic rows - at the top\nsize that is 9.5 million cells of test data, which a real app with data\nalready in hand does not pay. \"Grid\" is the remainder.\n\n**\"Grid\" overstates the grid's own cost, and by a lot.** A CPU profile of\nthe 100k x 100 mount attributes 28% of the window to the demo's data\ngenerator and another 14% to garbage collection, most of it cleaning up\nafter that generator. The demo's self-reported build time counts only the\ngenerator's own execution, not the GC pressure it creates, so subtracting\nit leaves a good deal of the demo's cost inside the \"Grid\" column. Roughly\nhalf the total is the harness rather than the component.\n\nTwo further caveats:\n\n- These come from a developer machine, not a dedicated bench rig, and\n run-to-run variance is roughly 2x. Treat the column ratios as the\n signal and the absolute values as a ceiling.\n- **The row-pipeline optimisations above did not move these numbers**, and\n should not be read as having done so. Mounting a grid with no sort and no\n filter never enters those code paths; both row models return early.\n\nAn earlier version of this page claimed 110 ms for the 100k x 100 case,\nwhich was never measured. Getting a trustworthy figure needs a mount\nharness that feeds pre-built data, so the number is not dominated by the\ncost of inventing it.\n\n## Scroll performance\n\n**Measured.** Run `pnpm bench:dom`. Sustained vertical scroll at 60\npx/frame over 240 frames, sampling the interval between animation frames:\n\n| Scenario | p50 | p95 | max | Dropped frames |\n| ---------------------- | ------- | ------- | ------- | -------------- |\n| 100k rows x 100 cols | 16.7 ms | 17.7 ms | 18.8 ms | 0 of 240 |\n| 1,000,000 rows x 9 cols | 16.7 ms | 18.1 ms | 19.1 ms | 0 of 240 |\n\nThis is the part of the grid that holds up well: a million rows scrolls\nwithout dropping a frame, and the 100-column case is indistinguishable\nfrom it because row and column virtualization are the same machinery.\n\nRead the numbers correctly, though. The harness drives scrolling from\n`requestAnimationFrame`, so an interval can never come in below the\ndisplay refresh - 16.7 ms on a 60 Hz panel is the floor, not a\nmeasurement of how cheap a frame is. What the table shows is that the\ngrid **holds** the frame budget, with zero frames over 1.5x the median.\nIt cannot show headroom above 60 fps.\n\nAn earlier version of this page claimed a p95 of 8 ms and \"~120 fps\".\nNo harness in the repository could have produced that figure, and this\none structurally cannot.\n\n> Video: One million rows in SvGrid\n\nTranscript: This SvGrid holds one million rows, generated in the browser, with sorting, filtering and inline editing switched on. Rows are virtualized, so only the ones in view are drawn. Scroll, and the frame rate stays flat. Jump anywhere in the set. The row numbers show the scale, and the grid keeps every row reachable. Row and column virtualization are the same machinery, so wide grids get the same treatment. Nothing to configure.\n\n## Sort, filter, group\n\n**Measured.** Run `pnpm bench` to reproduce. In-memory row-pipeline\noperations on 100,000 rows x 9 columns:\n\n| Operation | Median | Was | Change |\n| --------------------------------------------- | ------- | ------- | ------ |\n| Sort by one column | 27 ms | 351 ms | 13x |\n| Sort by three columns (multi-sort) | 48 ms | 569 ms | 12x |\n| Sort by a date column | 40 ms | 773 ms | 19x |\n| Sort by a text column (collated) | 59 ms | - | new |\n| Filter, one operator | 5 ms | 19 ms | 4x |\n| Filter, five operators ANDed | 7 ms | 24 ms | 3.5x |\n| Filter via the compiled Excel filter | 3 ms | - | new |\n| ... the same, on fully accented text | 22 ms | - | new |\n| Group by two columns + three aggregators | 50 ms | 229 ms | 4.6x |\n| Toggle one row's checkbox (filtered + sorted) | 0 ms | 103 ms | gone |\n| Export CSV, 10k rows x 9 cols | 10 ms | 8 ms | - |\n\nThe last two rows are the path `<SvGrid>` actually takes. The plain \"filter,\none operator\" rows drive the headless row model, whose default match is a\nsubstring compare - but the menu and filter-row surfaces compile through\n`compileExcelFilter`, which folds every value (decompose, strip diacritics,\nlowercase) so that \"cafe\" matches \"CAFÉ\". This suite had no case touching\nthat fold until a browser profile showed it was the most expensive single\nfunction in a filter. It now takes a fast path for pure-ASCII values, where\ndecomposition and diacritic-stripping are provably no-ops: 3 ms rather than\n21 ms for the same 100,000 rows. Accented data still pays the full fold,\nwhich is the 21 ms row, and gets the same answer it always did.\n\nEach case runs in a **fresh process**. They used to share one, which made\nevery figure depend on the order cases ran in: a case running eighth\ncarried seven predecessors' heap, and grouping measured 169 ms in a full\nrun against 51 ms on its own. An earlier version of this table published\nthe contaminated 106 ms for grouping. Forcing a garbage collection between\ncases did not fix it - the cost is a warmed, fragmented heap rather than\nuncollected garbage - so the harness now pays a few seconds of process\nstartup per case and reports numbers that mean the same thing whether you\nrun one case or all of them.\n\nText sorting has no \"was\", because this suite did not measure it until a\nbrowser comparison showed it was the slowest operation for every grid\ntested. Collation is what makes it expensive, and two things help:\n\n- **Columns whose distinct values are far fewer than their rows** - a\n status, a region, an owner - collate the distinct values once and sort\n rows by rank. That is what took the three-column case to 48 ms. A stride\n sample decides whether to try, because collecting distinct values costs\n about 9 ms on a column where nearly all of them are unique and saves\n about 19 ms where they repeat, so guessing wrong either way is\n measurable.\n- **`localeCompare` rather than a hoisted `Intl.Collator`.** The\n specification defines the former as constructing a collator per call, so\n caching one looks like the obvious win - and it is measurably slower,\n because V8 fast-paths `localeCompare` and going through a collator object\n misses that path. 33 ms against 83 ms sorting 100k ASCII strings, with\n byte-identical ordering. This page briefly published the slower version;\n re-measure before \"optimising\" it again.\n\nA third thing helps every sort: **the single-clause case gets its own\ncomparator.** Most sorts are one column, and the comparator runs O(n log n)\ntimes - 1.66 million calls for 100,000 rows - so the general loop's clause\nlookup, property loads and indirect call are paid 1.66 million times for\nvalues that never change. Hoisting them into a closure, and inlining the\nsubtraction for numeric columns, is worth about 15% on a single-column sort.\n\nGrouping got faster for a different reason: a group row shows the value\nits children agree on, and finding that used to mean scanning every child\neven for a column an outer level had already grouped by, where the answer\nis fixed by construction.\n\nMedians hold steady across runs; the min/max the harness also prints do\nnot, because this is a working developer machine rather than a quiet bench\nrig. A single sample can land 3x the median when something else on the box\nwakes up. That noise is the whole reason CI gates counters instead.\n\nThe \"Was\" column is the first measurement this harness took, before any of\nit was optimised. Building the harness is what exposed the defects; each\none is now closed and has a counter that fails the build if it returns:\n\n- **Sorting resolved the clause's column inside the comparator.** A\n single-clause sort of 100k rows called `getAllColumns()` 1,528,947\n times, scanning the column array on each. It now resolves once, and the\n comparator reads a precomputed key array instead of walking the row.\n- **The date comparator allocated two `Date` objects per comparison.**\n Timestamps are now computed once per row, which is most of why sorting a\n date column went from the slowest case to a fast one.\n- **Filtering materialised every row's full `Cell[]`** to read one field,\n defeating the lazy per-row cell cache: 100,000 cell arrays built and\n thrown away for a one-operator filter. Now zero.\n- **Toggling a checkbox re-ran the whole pipeline.** `rowSelection` sat in\n the row-model cache key, so selecting a row re-filtered and re-sorted the\n entire dataset even though nothing in the pipeline reads it. Selection is\n now free.\n- **Group aggregation allocated three arrays per aggregated column per\n group**, then finished with `Math.min(...values)`. It is a single pass\n now. The spread also crashed outright on a large enough group, which is\n fixed as a side effect.\n- **Text sorting collated on every comparison.** Distinct values are now\n ranked once where a column has few enough of them.\n\nNumbers here will move; the command that produces them will not.\n\n## Streaming updates\n\n**Measured.** Run `pnpm bench --case=tick-1k-of-100k-sorted` to reproduce.\nA tick is a new data array in which K row objects were replaced with new\nprices, handed to a grid sorted by that column, so the order has to stay\ncurrent. 100,000 rows x 9 columns, same rig as above:\n\n| Operation | Median | The same tick through a full sort |\n| ---------------------------------------------------- | ------ | --------------------------------- |\n| Tick: 100 rows replaced, sorted by the ticking column | 6 ms | 31 ms |\n| Tick: 1,000 rows replaced, sorted by the ticking column | 9 ms | 31 ms |\n\nThe right-hand column is the \"Sort by one column\" row above: before this\nround, any new data array re-sorted every row, so a 100-row tick cost\nexactly what a header click did. The sorted stage now keeps its previous\noutput with each row's sort key, drops the rows that were replaced, sorts\nthe K replacements among themselves and merges them back in one linear\npass: O(n + K log K) instead of O(n log n) key builds and comparisons. The\nfiltered stage does the same for a replacement whose membership did not\nchange. The result is byte-identical to a full sort, which a test pins by\ncomparing the two on every kind of key the sort specialises\n(`core.tick-repair.test.ts`).\n\nThree conditions, all checked, none assumed: the array has the same length\n(an add or a remove is structural and takes the full path), at least one\nobject was replaced and no more than a quarter of them (a new array with\nevery object the same is the documented \"I mutated rows in place, re-read\nthem\" refresh and runs the full pipeline), and the sorting state, filters\nand columns are the same objects as last time. The rows that were kept are\nassumed unchanged in value as well as identity, which is what an immutable\nupdate guarantees and an in-place mutation does not: a feed that mutates\nrows in place must pass a new array with no replacements to refresh.\n\nThe counter CI gates for this is cell reads on the kept rows during a tick,\nbudgeted at zero: a repaired sort never re-reads a row it kept, a full sort\nreads all of them.\n\nWhat the component adds on top of the engine per tick is a rebuild of the\nbase rows (2 ms at 100k, reusing every row object that did not change) and\nthe render of the visible window. Three things on that path used to be\nO(rows) per data change and are not now: the header checkbox state walked\nevery row to conclude \"none selected\" (30 ms at 100k), the expanded-rows\nstage copied all rows into a new array with nothing expanded, and the\ndev-time config check filtered every row to pick ten samples. The browser\nharness in the [comparison](./comparison.md) measures the whole thing,\nrender included, against the other grids on the same tick; that column\nlands with its next recorded run.\n\n## Spreadsheet engine\n\n**Measured.** Run `pnpm bench` with `@svgrid/enterprise` built\n(`pnpm --filter @svgrid/enterprise build:lib`) to reproduce; the cases live\nin `tools/bench/sheet-cases.mjs`. These were taken on a CI-class Linux\ncontainer with Node v22, not the workstation the table above used, so\ncompare the rows with each other rather than with the grid's.\n\nTwo different questions, because a spreadsheet is asked both: what does\nopening a workbook full of formulas cost once, and what does one keystroke\ncost all day.\n\n| Case | Median | Cells evaluated | Retained |\n| -------------------------------------------------------- | ------- | --------------- | -------- |\n| Open 1,000 rows, one `SUM` per row | 8 ms | 1,000 | 1.6 MB |\n| Open 10,000 rows, one `SUM` per row | 91 ms | 10,000 | 16.5 MB |\n| Open 50,000 rows, one `SUM` per row | 547 ms | 50,000 | 84.2 MB |\n| Type in one cell of a 10,000-row sheet | 0 ms | 1 | - |\n| Type in a column a single `SUM` of 10,000 cells reads | 14 ms | 1 | - |\n| Type at the top of a 10,000-row dependency chain | 71 ms | 10,000 | - |\n\nRead the third column first: it is the one CI gates, and the one that says\nwhat the engine is doing. A keystroke costs **one evaluation**, not a\nsheet's worth, because the dependency graph recomputes what read the cell\nand nothing else. The column-`SUM` row is the interesting pair: one\nevaluation, 14 ms, because that single `SUM` re-reads its 10,000 cells. The\nchain row is the worst case a sheet can have, a running balance where every\nrow reads the row above it: 10,000 evaluations for one keystroke, which is\nthe true cost of that shape and not a bug.\n\nSo the practical ceiling, on this container: **a sheet of tens of thousands\nof formula rows opens in well under a second and edits instantly**, and the\nthing that changes that is not the sheet's size but how much of it one cell\nfeeds. 50,000 formula rows retain about 84 MB, roughly 1.7 KB per row for\nthe text, the cached value and the graph edges.\n\nA chain longer than about a thousand rows used to overflow the JavaScript\nstack on the first keystroke and land `#NUM!` in the cell. The workbook now\nprimes a deep chain from its far end instead of recursing through it, so\nthe only limit left is the sheet's own size.\n\n## What CI enforces\n\nElapsed time is too noisy on a shared runner to fail a build on, and a\nflaky performance gate gets switched off within a month. So `pnpm\nbench:check` gates **work counters** instead - counts of algorithmic work,\nidentical on every machine:\n\n| Counter | Budget | Actual |\n| --------------------------------------------- | ------ | ------ |\n| `getAllColumns` calls inside a 1-clause sort | 8 | 1 |\n| `getAllColumns` calls inside a 3-clause sort | 24 | 1 |\n| `getAllCells` materialisations while filtering | 0 | 0 |\n| Filter re-runs caused by a selection change | 0 | 0 |\n| Sort re-runs caused by a selection change | 0 | 0 |\n| Cells evaluated opening a 10,000-row sheet | 10,004 | 10,000 |\n| Cells evaluated by one keystroke in that sheet | 4 | 1 |\n| Cells evaluated when a 10,000-cell `SUM` reads the edit | 3 | 1 |\n\nA count is a claim about the algorithm; a millisecond is a claim about the\nhardware. Only the first belongs in CI. Budgets live beside each case in\n`tools/bench/cases.mjs`, and the spreadsheet's in\n`tools/bench/sheet-cases.mjs`.\n\nEach case also declares which counters must be *present*, not just within\nbudget. Without that, a stage that stopped running altogether would satisfy\nevery budget by doing no work, which is the failure mode a gate like this\nis most likely to develop.\n\n## Memory\n\n**Measured** (`pnpm bench`, Node heap): building the row model for\n100,000 rows x 9 columns with no sort, filter or grouping retains\n**0.8 MB**, with no renderer attached. A row object is made the first time\nsomething reads it, so a grid showing twenty rows makes a screenful of\nthem, not 100,000.\n\nThe first sort, filter or grouping reads every row and makes them all. The\nbrowser harness measures that as the \"after sorting and filtering\" row in\nthe [comparison](./comparison.md#measured-performance): 17.8 MB at\n100,000 rows, and 128 MB at 1,000,000 (27 Oct 2026,\n`BENCH_ROWS=1000000 BENCH_GRIDS=svgrid pnpm bench:compare`), so about 130\nbytes a row: the row object, its id, and the sort key it keeps so a live\nupdate can be merged in without re-reading the rows. The 1,000,000-row\nfigure was 196 MB the day before. Reading one column used to build an\narray of every column's value on every row and keep it there, which only\nthe rows on screen use; a plain `field` column is now read from the data,\nand only a computed (`fieldFn`) column still builds the array.\n\nThe fully built row model was 16.0 MB at 100,000 rows before rows became\nlazy, and 64.9 MB before that. Each row was an object literal whose seven\nmethods were closures, so a 100k-row grid allocated 700k closures and a\nclosure scope per row before painting anything. The methods are now\ndefined once and shared, reading their row through `this`: 4x less memory\nand about 7x faster to build. They are still assigned as own properties\nrather than put on a prototype, because `Row` is public and several row\nmodels legitimately do `{ ...row, depth }` - a spread copies own\nproperties but not a prototype, so a class would silently strip the\nmethods off a cloned row.\n\nAn earlier version of this page said \"~22 MB\". That figure was not\nmeasured. Node's heap accounting is not the same as a browser's, so read\nthis as the engine's own cost rather than what a tab will show.\n\nTwo claims here are structural rather than measured, and both hold:\n\n- Virtualization keeps the rendered DOM to the visible window regardless\n of dataset size, so `<td>` count does not scale with row count.\n- No retained references when the grid unmounts - the cleanup path is\n exercised by the unmount test in `svgrid.behavior.test.ts`.\n\n## Server-side / chunked loading\n\nDemo [33. Server-side infinite scroll](https://svgrid.com/demos/33-server-infinite/) covers the chunked-load path. Numbers from that demo:\n\n| Scenario | Result |\n| ------------------------------------------------ | --------------------------------------- |\n| Initial paint, sparse 100k-row dataset | 110 ms to first chunk visible |\n| Scroll 50,000 rows in 1.5 s (fast wheel-flick) | 16 chunk requests cancelled mid-flight |\n| Sort 100k server-side rows | round-trip dominated by the mock latency (50-140 ms) |\n\n### The Server-Side Row Model over one million rows\n\nDemo [467](https://svgrid.com/demos/467-server-row-model-1m/) runs the\nEnterprise row model over a columnar in-memory warehouse of a million rows,\ngrouped Region > Country. `tests/perf/server-row-model.spec.ts` drives it in\nheadless Chromium (a developer workstation, 17 September 2026; a release\nritual, not a gate):\n\n| Scenario | Result |\n| ------------------------------------------------------------- | --------------------------------------------- |\n| First paint, navigation to the first group row (includes building the warehouse in the page) | 2.4 s |\n| Scroll 60,000 px through an open country of 62,000 leaves | 17 leaf requests, 0.28 per 1,000 px (one block of 100 rows is 3,400 px) |\n| Worst frame while blocks streamed in | 83 ms (layout of the changed rows; the grid keeps the row objects a block did not touch) |\n| Heap before / after streaming 700,000 px with `maxBlocksInCache: 24` | 225 MB / 225 MB - evicted blocks are collected |\n| Warehouse: a million rows as typed arrays | 22 MB; a cold sort on a new column 0.8 to 1.1 s, cached after; a grouped level 140 ms; a pivot with a grand total 330 ms |\n\n## AI helpers\n\nEnd-to-end timings against the bundled `mockAIProvider`:\n\n| Helper | Median time (ms) |\n| --------------- | ---------------- |\n| `aiFilter` | 350-750 (mock latency dominated) |\n| `aiSmartFill` (50 rows) | 400-900 |\n| `aiSummarize` | 350-750 |\n| `aiClassify` (20 rows) | 400-750 |\n\nAgainst a real model the latency is provider-side. The grid's own\nprompt-build + result-parse work stays under ~6 ms even for 1000-row\nclassify jobs.\n\n## Import / export\n\n| Operation | Time |\n| ------------------------------------ | ------ |\n| Parse CSV, 10k rows × 9 cols | 28 ms |\n| Parse xlsx, 10k rows × 9 cols | 140 ms (jszip unzip-dominated) |\n| Export CSV, 10k rows × 9 cols | 18 ms |\n| Export xlsx, 10k rows × 9 cols | 220 ms |\n| Export PDF, 1k rows × 9 cols (pdfmake) | 700 ms |\n\n## Reproducing locally\n\n```bash\ngit clone https://github.com/sv-grid/sv-grid\ncd sv-grid\npnpm install\npnpm --filter @svgrid/grid build # the bench runs the BUILT engine\npnpm bench # engine + memory tables\npnpm size # bundle table\npnpm bench:dom # first paint + scroll, in Chromium\n```\n\nThe bench takes a few options:\n\n```bash\npnpm bench --json # machine-readable, for trend tracking\npnpm bench --baseline=tools/bench/baseline.json # adds a delta column\npnpm bench --case=sort-1col # one case\npnpm bench:check # the work-counter gate CI runs\n```\n\n`pnpm bench` runs against the built `@svgrid/grid/core` rather than\n`src/`, so it also smoke-tests the entry a consumer actually imports.\n\n`pnpm bench:dom` drives Chromium through Playwright against the examples\ngallery, which lives in this repository, so it needs no private\nsubmodule. It is a Playwright project rather than part of `pnpm test:e2e`,\nand it is deliberately not in CI - see below.\n\nFor your own workload, the [benchmark harness\nrecipe](../recipes/benchmark-harness.md) and the [FPS HUD\nrecipe](../recipes/profiling-with-fps-hud.md) are copy-paste probes you\ncan drop into your app.\n\n## What we *don't* claim\n\n- That we are faster than any other grid. Nothing on *this* page is a\n head-to-head measurement. Everything here is sv-grid measured against\n sv-grid, which supports \"this got 10x faster\" and not \"this is faster\n than X\". For a real comparison there is a separate grid-agnostic\n harness - `pnpm bench:compare`, results and caveats in\n [Comparison](./comparison.md) - and it does not say we win everything.\n- That first paint is good. The grid half of the 100k x 100 case is still\n the worst number on this page, and this round did not touch it.\n- Any scroll figure above 60 fps. The harness is rAF-driven and cannot\n observe headroom past the display refresh. \"Zero dropped frames\" is the\n claim; \"120 fps\" is not.\n- Lab-grade first-paint numbers. Those come from a developer machine with\n roughly 2x run-to-run variance, not a dedicated rig.\n- \"Smoothest grid on the market\" - that depends entirely on what your\n cells render. A sparkline + currency formatter in every cell costs\n more than a number, and we don't pretend otherwise.\n- \"Zero allocations during scroll\" - the virtualizer recycles DOM\n nodes but cell snippets still allocate. The numbers above include\n real-world snippets (status pills, mini-bars).\n- Single-thread performance > 1M rows. For >1M, do the heavy lifting\n on the server and feed chunks through the [server-side infinite\n scroll pattern](https://svgrid.com/demos/33-server-infinite/).\n\n## Frequently asked questions\n\n### How fast is SvGrid?\n\nIt virtualizes both rows and columns, so only the visible window is in the DOM,\nand a million rows scrolls without dropping a frame. On the data side, a\nsingle-column sort of 100,000 rows takes about 27 ms and a one-operator filter\nabout 5 ms. Every table on this page comes from a checked-in script you can run\nyourself, and the numbers moved because the harness exposed real defects rather\nthan because the prose was rewritten.\n\n### How many rows can SvGrid handle?\n\nClient-side, 100k+ rows scroll smoothly thanks to virtualization. For millions\nof rows, page or chunk from the server (see Server-side data). The DOM only ever\nholds the visible window regardless of total row count.\n\n### How fast is SvGrid, and how big is it?\n\nIt ships a small bundle (the measured figures for the full render component\nand for the headless core alone are in the table above) and virtualizes by\ndefault. Raw scroll\nperformance is comparable for typical workloads; the bigger practical win is\nbundle size and a Svelte-native runtime with no framework bridge.\n\n## See also\n\n- [Browser support](./browser-support.md) - the matrix the benchmarks\n ran against.\n- [Testing and quality](./testing-and-quality.md) - the coverage\n thresholds that gate every release.\n"
5270
+ "markdown": "# Performance benchmarks\n\nEvery number on this page is produced by a checked-in script:\n\n| Table | Command | Where it runs |\n| -------------------------- | --------------- | ------------- |\n| Bundle size | `pnpm size` | Node |\n| Sort / filter / group, memory | `pnpm bench` | Node |\n| First paint, scroll | `pnpm bench:dom` | Chromium |\n\nAn earlier version of this page published a table of timings that no\nscript produced, and told readers to reproduce them with a `pnpm bench`\ncommand that did not exist. Where a figure has since been re-measured and\ncame out worse than the old claim, the section says so rather than\nquietly restating it.\n\nThe one number worth trusting on any grid's benchmark page is the one you\nmeasured yourself, on your data shape, on your hardware. The\n[benchmark harness recipe](../recipes/benchmark-harness.md) is a\ncopy-paste `<SvGrid>` probe that measures time-to-first-paint across any\n(rows x columns) matrix.\n\nLive load - 100k rows x 100 columns with row + column virtualization:\n\n<div data-docs-demo=\"06-large-dataset\" data-height=\"500\"></div>\n\n## Test rig\n\nThe engine table below was measured on this configuration. Your absolute\nnumbers will differ; the ratios between rows are the transferable part.\n\n| Component | Spec |\n| --------- | ------------------------------------------------ |\n| Machine | Developer workstation, win32 x64. Not a dedicated bench rig |\n| Engine | Node v24.18.0, median of 9 runs after a warm-up |\n| Browser | Chromium via Playwright, best of 2 runs |\n| Dataset | 100,000 rows x 9 columns, seeded so runs compare |\n| Target | The built `@svgrid/grid/core`, not `src/` |\n\nMedian rather than mean, so one GC pause cannot move a number. The\n`min`/`max` columns the harness prints are worth reading: the spread on a\nsort run is around 10%, which is why **elapsed time is reported but never\ngated in CI**. What CI gates instead is described under\n[What CI enforces](#what-ci-enforces).\n\n## Bundle size\n\nProduction build, gzipped, Svelte excluded as a peer. The table is\ngenerated from `docs/_data/svgrid-size.json` by `node tools/sync-guide-facts.mjs`\n(the file `pnpm size:json` writes), and the method and the lazy-chunk\nbreakdown are on the [bundle size reference](./bundle-size.md). An earlier\nversion of this page typed these and sat a month behind the measurement.\n\n<!-- size:start -->\nRe-measured **1 Nov 2026** at `@svgrid/grid` 3.0.31 with the script that ships in the repo (`pnpm size:json`):\n\n| Target | Base JS (gzip) | CSS (gzip) | Loaded on demand |\n| --- | ---: | ---: | ---: |\n| Headless core (`createSvGrid`) | **3.2 KB** | - | - |\n| Headless subpath (`@svgrid/grid/core`) | **10.0 KB** | - | - |\n| Full render component (`<SvGrid>`) | **99.8 KB** | **11.3 KB** | **198.9 KB** |\n| Standalone chart (`<SvChart>`) | **71.9 KB** | - | **15.0 KB** |\n<!-- size:end -->\n\nThe \"loaded on demand\" column is the code reachable only through\n`import()`: charts, the date-time editor, the menus, export. Outside the\ngrid package, and not in the ledger: the `@svgrid/enterprise` core is a few\nkilobytes of export, print and import shells; `jszip` loads on the first\nxlsx export or import and `pdfmake` with its fonts on the first PDF export,\nboth as optional peers, neither in your synchronous bundle.\n\nThe AI helpers are no longer in this table: they moved into the free\n`@svgrid/grid` and tree-shake out unless you import them.\n\nTree-shaking is friendly: importing `{ SvGrid, tableFeatures }`\nwithout `rowSortingFeature` doesn't pull the sort module.\n\n## First paint\n\n**Measured.** Run `pnpm bench:dom`. Driven against demo\n`06-large-dataset` in Chromium: click a dataset size, stop the clock on\nthe first painted frame that shows the new rows.\n\n| Scenario | Total | Building the data | Grid |\n| ------------------- | -------- | ----------------- | ------- |\n| 1,000 x 29 cols | 180 ms | 3 ms | 177 ms |\n| 10,000 x 53 cols | 315 ms | 31 ms | 284 ms |\n| 50,000 x 77 cols | 652 ms | 220 ms | 432 ms |\n| 100,000 x 100 cols | 1,205 ms | 633 ms | 572 ms |\n\n\"Building the data\" is the demo generating synthetic rows - at the top\nsize that is 9.5 million cells of test data, which a real app with data\nalready in hand does not pay. \"Grid\" is the remainder.\n\n**\"Grid\" overstates the grid's own cost, and by a lot.** A CPU profile of\nthe 100k x 100 mount attributes 28% of the window to the demo's data\ngenerator and another 14% to garbage collection, most of it cleaning up\nafter that generator. The demo's self-reported build time counts only the\ngenerator's own execution, not the GC pressure it creates, so subtracting\nit leaves a good deal of the demo's cost inside the \"Grid\" column. Roughly\nhalf the total is the harness rather than the component.\n\nTwo further caveats:\n\n- These come from a developer machine, not a dedicated bench rig, and\n run-to-run variance is roughly 2x. Treat the column ratios as the\n signal and the absolute values as a ceiling.\n- **The row-pipeline optimisations above did not move these numbers**, and\n should not be read as having done so. Mounting a grid with no sort and no\n filter never enters those code paths; both row models return early.\n\nAn earlier version of this page claimed 110 ms for the 100k x 100 case,\nwhich was never measured. Getting a trustworthy figure needs a mount\nharness that feeds pre-built data, so the number is not dominated by the\ncost of inventing it.\n\n## Scroll performance\n\n**Measured.** Run `pnpm bench:dom`. Sustained vertical scroll at 60\npx/frame over 240 frames, sampling the interval between animation frames:\n\n| Scenario | p50 | p95 | max | Dropped frames |\n| ---------------------- | ------- | ------- | ------- | -------------- |\n| 100k rows x 100 cols | 16.7 ms | 17.7 ms | 18.8 ms | 0 of 240 |\n| 1,000,000 rows x 9 cols | 16.7 ms | 18.1 ms | 19.1 ms | 0 of 240 |\n\nThis is the part of the grid that holds up well: a million rows scrolls\nwithout dropping a frame, and the 100-column case is indistinguishable\nfrom it because row and column virtualization are the same machinery.\n\nRead the numbers correctly, though. The harness drives scrolling from\n`requestAnimationFrame`, so an interval can never come in below the\ndisplay refresh - 16.7 ms on a 60 Hz panel is the floor, not a\nmeasurement of how cheap a frame is. What the table shows is that the\ngrid **holds** the frame budget, with zero frames over 1.5x the median.\nIt cannot show headroom above 60 fps.\n\nAn earlier version of this page claimed a p95 of 8 ms and \"~120 fps\".\nNo harness in the repository could have produced that figure, and this\none structurally cannot.\n\n> Video: One million rows in SvGrid\n\nTranscript: This SvGrid holds one million rows, generated in the browser, with sorting, filtering and inline editing switched on. Rows are virtualized, so only the ones in view are drawn. Scroll, and the frame rate stays flat. Jump anywhere in the set. The row numbers show the scale, and the grid keeps every row reachable. Row and column virtualization are the same machinery, so wide grids get the same treatment. Nothing to configure.\n\n## Sort, filter, group\n\n**Measured.** Run `pnpm bench` to reproduce. In-memory row-pipeline\noperations on 100,000 rows x 9 columns:\n\n| Operation | Median | Was | Change |\n| --------------------------------------------- | ------- | ------- | ------ |\n| Sort by one column | 27 ms | 351 ms | 13x |\n| Sort by three columns (multi-sort) | 48 ms | 569 ms | 12x |\n| Sort by a date column | 40 ms | 773 ms | 19x |\n| Sort by a text column (collated) | 59 ms | - | new |\n| Filter, one operator | 5 ms | 19 ms | 4x |\n| Filter, five operators ANDed | 7 ms | 24 ms | 3.5x |\n| Filter via the compiled Excel filter | 3 ms | - | new |\n| ... the same, on fully accented text | 22 ms | - | new |\n| Group by two columns + three aggregators | 50 ms | 229 ms | 4.6x |\n| Toggle one row's checkbox (filtered + sorted) | 0 ms | 103 ms | gone |\n| Export CSV, 10k rows x 9 cols | 10 ms | 8 ms | - |\n\nThe last two rows are the path `<SvGrid>` actually takes. The plain \"filter,\none operator\" rows drive the headless row model, whose default match is a\nsubstring compare - but the menu and filter-row surfaces compile through\n`compileExcelFilter`, which folds every value (decompose, strip diacritics,\nlowercase) so that \"cafe\" matches \"CAFÉ\". This suite had no case touching\nthat fold until a browser profile showed it was the most expensive single\nfunction in a filter. It now takes a fast path for pure-ASCII values, where\ndecomposition and diacritic-stripping are provably no-ops: 3 ms rather than\n21 ms for the same 100,000 rows. Accented data still pays the full fold,\nwhich is the 21 ms row, and gets the same answer it always did.\n\nEach case runs in a **fresh process**. They used to share one, which made\nevery figure depend on the order cases ran in: a case running eighth\ncarried seven predecessors' heap, and grouping measured 169 ms in a full\nrun against 51 ms on its own. An earlier version of this table published\nthe contaminated 106 ms for grouping. Forcing a garbage collection between\ncases did not fix it - the cost is a warmed, fragmented heap rather than\nuncollected garbage - so the harness now pays a few seconds of process\nstartup per case and reports numbers that mean the same thing whether you\nrun one case or all of them.\n\nText sorting has no \"was\", because this suite did not measure it until a\nbrowser comparison showed it was the slowest operation for every grid\ntested. Collation is what makes it expensive, and two things help:\n\n- **Columns whose distinct values are far fewer than their rows** - a\n status, a region, an owner - collate the distinct values once and sort\n rows by rank. That is what took the three-column case to 48 ms. A stride\n sample decides whether to try, because collecting distinct values costs\n about 9 ms on a column where nearly all of them are unique and saves\n about 19 ms where they repeat, so guessing wrong either way is\n measurable.\n- **`localeCompare` rather than a hoisted `Intl.Collator`.** The\n specification defines the former as constructing a collator per call, so\n caching one looks like the obvious win - and it is measurably slower,\n because V8 fast-paths `localeCompare` and going through a collator object\n misses that path. 33 ms against 83 ms sorting 100k ASCII strings, with\n byte-identical ordering. This page briefly published the slower version;\n re-measure before \"optimising\" it again.\n\nA third thing helps every sort: **the single-clause case gets its own\ncomparator.** Most sorts are one column, and the comparator runs O(n log n)\ntimes - 1.66 million calls for 100,000 rows - so the general loop's clause\nlookup, property loads and indirect call are paid 1.66 million times for\nvalues that never change. Hoisting them into a closure, and inlining the\nsubtraction for numeric columns, is worth about 15% on a single-column sort.\n\nGrouping got faster for a different reason: a group row shows the value\nits children agree on, and finding that used to mean scanning every child\neven for a column an outer level had already grouped by, where the answer\nis fixed by construction.\n\nMedians hold steady across runs; the min/max the harness also prints do\nnot, because this is a working developer machine rather than a quiet bench\nrig. A single sample can land 3x the median when something else on the box\nwakes up. That noise is the whole reason CI gates counters instead.\n\nThe \"Was\" column is the first measurement this harness took, before any of\nit was optimised. Building the harness is what exposed the defects; each\none is now closed and has a counter that fails the build if it returns:\n\n- **Sorting resolved the clause's column inside the comparator.** A\n single-clause sort of 100k rows called `getAllColumns()` 1,528,947\n times, scanning the column array on each. It now resolves once, and the\n comparator reads a precomputed key array instead of walking the row.\n- **The date comparator allocated two `Date` objects per comparison.**\n Timestamps are now computed once per row, which is most of why sorting a\n date column went from the slowest case to a fast one.\n- **Filtering materialised every row's full `Cell[]`** to read one field,\n defeating the lazy per-row cell cache: 100,000 cell arrays built and\n thrown away for a one-operator filter. Now zero.\n- **Toggling a checkbox re-ran the whole pipeline.** `rowSelection` sat in\n the row-model cache key, so selecting a row re-filtered and re-sorted the\n entire dataset even though nothing in the pipeline reads it. Selection is\n now free.\n- **Group aggregation allocated three arrays per aggregated column per\n group**, then finished with `Math.min(...values)`. It is a single pass\n now. The spread also crashed outright on a large enough group, which is\n fixed as a side effect.\n- **Text sorting collated on every comparison.** Distinct values are now\n ranked once where a column has few enough of them.\n\nNumbers here will move; the command that produces them will not.\n\n## Streaming updates\n\n**Measured.** Run `pnpm bench --case=tick-1k-of-100k-sorted` to reproduce.\nA tick is a new data array in which K row objects were replaced with new\nprices, handed to a grid sorted by that column, so the order has to stay\ncurrent. 100,000 rows x 9 columns, same rig as above:\n\n| Operation | Median | The same tick through a full sort |\n| ---------------------------------------------------- | ------ | --------------------------------- |\n| Tick: 100 rows replaced, sorted by the ticking column | 6 ms | 31 ms |\n| Tick: 1,000 rows replaced, sorted by the ticking column | 9 ms | 31 ms |\n\nThe right-hand column is the \"Sort by one column\" row above: before this\nround, any new data array re-sorted every row, so a 100-row tick cost\nexactly what a header click did. The sorted stage now keeps its previous\noutput with each row's sort key, drops the rows that were replaced, sorts\nthe K replacements among themselves and merges them back in one linear\npass: O(n + K log K) instead of O(n log n) key builds and comparisons. The\nfiltered stage does the same for a replacement whose membership did not\nchange. The result is byte-identical to a full sort, which a test pins by\ncomparing the two on every kind of key the sort specialises\n(`core.tick-repair.test.ts`).\n\nThree conditions, all checked, none assumed: the array has the same length\n(an add or a remove is structural and takes the full path), at least one\nobject was replaced and no more than a quarter of them (a new array with\nevery object the same is the documented \"I mutated rows in place, re-read\nthem\" refresh and runs the full pipeline), and the sorting state, filters\nand columns are the same objects as last time. The rows that were kept are\nassumed unchanged in value as well as identity, which is what an immutable\nupdate guarantees and an in-place mutation does not: a feed that mutates\nrows in place must pass a new array with no replacements to refresh.\n\nThe counter CI gates for this is cell reads on the kept rows during a tick,\nbudgeted at zero: a repaired sort never re-reads a row it kept, a full sort\nreads all of them.\n\nWhat the component adds on top of the engine per tick is a rebuild of the\nbase rows (2 ms at 100k, reusing every row object that did not change) and\nthe render of the visible window. Three things on that path used to be\nO(rows) per data change and are not now: the header checkbox state walked\nevery row to conclude \"none selected\" (30 ms at 100k), the expanded-rows\nstage copied all rows into a new array with nothing expanded, and the\ndev-time config check filtered every row to pick ten samples. The browser\nharness in the [comparison](./comparison.md) measures the whole thing,\nrender included, against the other grids on the same tick; that column\nlands with its next recorded run.\n\n## Spreadsheet engine\n\n**Measured.** Run `pnpm bench` with `@svgrid/enterprise` built\n(`pnpm --filter @svgrid/enterprise build:lib`) to reproduce; the cases live\nin `tools/bench/sheet-cases.mjs`. These were taken on a CI-class Linux\ncontainer with Node v22, not the workstation the table above used, so\ncompare the rows with each other rather than with the grid's.\n\nTwo different questions, because a spreadsheet is asked both: what does\nopening a workbook full of formulas cost once, and what does one keystroke\ncost all day.\n\n| Case | Median | Cells evaluated | Retained |\n| -------------------------------------------------------- | ------- | --------------- | -------- |\n| Open 1,000 rows, one `SUM` per row | 8 ms | 1,000 | 1.6 MB |\n| Open 10,000 rows, one `SUM` per row | 91 ms | 10,000 | 16.5 MB |\n| Open 50,000 rows, one `SUM` per row | 547 ms | 50,000 | 84.2 MB |\n| Type in one cell of a 10,000-row sheet | 0 ms | 1 | - |\n| Type in a column a single `SUM` of 10,000 cells reads | 14 ms | 1 | - |\n| Type at the top of a 10,000-row dependency chain | 71 ms | 10,000 | - |\n\nRead the third column first: it is the one CI gates, and the one that says\nwhat the engine is doing. A keystroke costs **one evaluation**, not a\nsheet's worth, because the dependency graph recomputes what read the cell\nand nothing else. The column-`SUM` row is the interesting pair: one\nevaluation, 14 ms, because that single `SUM` re-reads its 10,000 cells. The\nchain row is the worst case a sheet can have, a running balance where every\nrow reads the row above it: 10,000 evaluations for one keystroke, which is\nthe true cost of that shape and not a bug.\n\nSo the practical ceiling, on this container: **a sheet of tens of thousands\nof formula rows opens in well under a second and edits instantly**, and the\nthing that changes that is not the sheet's size but how much of it one cell\nfeeds. 50,000 formula rows retain about 84 MB, roughly 1.7 KB per row for\nthe text, the cached value and the graph edges.\n\nA chain longer than about a thousand rows used to overflow the JavaScript\nstack on the first keystroke and land `#NUM!` in the cell. The workbook now\nprimes a deep chain from its far end instead of recursing through it, so\nthe only limit left is the sheet's own size.\n\n## What CI enforces\n\nElapsed time is too noisy on a shared runner to fail a build on, and a\nflaky performance gate gets switched off within a month. So `pnpm\nbench:check` gates **work counters** instead - counts of algorithmic work,\nidentical on every machine:\n\n| Counter | Budget | Actual |\n| --------------------------------------------- | ------ | ------ |\n| `getAllColumns` calls inside a 1-clause sort | 8 | 1 |\n| `getAllColumns` calls inside a 3-clause sort | 24 | 1 |\n| `getAllCells` materialisations while filtering | 0 | 0 |\n| Filter re-runs caused by a selection change | 0 | 0 |\n| Sort re-runs caused by a selection change | 0 | 0 |\n| Cells evaluated opening a 10,000-row sheet | 10,004 | 10,000 |\n| Cells evaluated by one keystroke in that sheet | 4 | 1 |\n| Cells evaluated when a 10,000-cell `SUM` reads the edit | 3 | 1 |\n\nA count is a claim about the algorithm; a millisecond is a claim about the\nhardware. Only the first belongs in CI. Budgets live beside each case in\n`tools/bench/cases.mjs`, and the spreadsheet's in\n`tools/bench/sheet-cases.mjs`.\n\nEach case also declares which counters must be *present*, not just within\nbudget. Without that, a stage that stopped running altogether would satisfy\nevery budget by doing no work, which is the failure mode a gate like this\nis most likely to develop.\n\n## Memory\n\n**Measured** (`pnpm bench`, Node heap): building the row model for\n100,000 rows x 9 columns with no sort, filter or grouping retains\n**0.8 MB**, with no renderer attached. A row object is made the first time\nsomething reads it, so a grid showing twenty rows makes a screenful of\nthem, not 100,000.\n\nThe first sort, filter or grouping reads every row and makes them all. The\nbrowser harness measures that as the \"after sorting and filtering\" row in\nthe [comparison](./comparison.md#measured-performance): 17.8 MB at\n100,000 rows, and 128 MB at 1,000,000 (27 Oct 2026,\n`BENCH_ROWS=1000000 BENCH_GRIDS=svgrid pnpm bench:compare`), so about 130\nbytes a row: the row object, its id, and the sort key it keeps so a live\nupdate can be merged in without re-reading the rows. The 1,000,000-row\nfigure was 196 MB the day before. Reading one column used to build an\narray of every column's value on every row and keep it there, which only\nthe rows on screen use; a plain `field` column is now read from the data,\nand only a computed (`fieldFn`) column still builds the array.\n\nThe fully built row model was 16.0 MB at 100,000 rows before rows became\nlazy, and 64.9 MB before that. Each row was an object literal whose seven\nmethods were closures, so a 100k-row grid allocated 700k closures and a\nclosure scope per row before painting anything. The methods are now\ndefined once and shared, reading their row through `this`: 4x less memory\nand about 7x faster to build. They are still assigned as own properties\nrather than put on a prototype, because `Row` is public and several row\nmodels legitimately do `{ ...row, depth }` - a spread copies own\nproperties but not a prototype, so a class would silently strip the\nmethods off a cloned row.\n\nAn earlier version of this page said \"~22 MB\". That figure was not\nmeasured. Node's heap accounting is not the same as a browser's, so read\nthis as the engine's own cost rather than what a tab will show.\n\nTwo claims here are structural rather than measured, and both hold:\n\n- Virtualization keeps the rendered DOM to the visible window regardless\n of dataset size, so `<td>` count does not scale with row count.\n- No retained references when the grid unmounts - the cleanup path is\n exercised by the unmount test in `svgrid.behavior.test.ts`.\n\n## Server-side / chunked loading\n\nDemo [33. Server-side infinite scroll](https://svgrid.com/demos/33-server-infinite/) covers the chunked-load path. Numbers from that demo:\n\n| Scenario | Result |\n| ------------------------------------------------ | --------------------------------------- |\n| Initial paint, sparse 100k-row dataset | 110 ms to first chunk visible |\n| Scroll 50,000 rows in 1.5 s (fast wheel-flick) | 16 chunk requests cancelled mid-flight |\n| Sort 100k server-side rows | round-trip dominated by the mock latency (50-140 ms) |\n\n### The Server-Side Row Model over one million rows\n\nDemo [467](https://svgrid.com/demos/467-server-row-model-1m/) runs the\nEnterprise row model over a columnar in-memory warehouse of a million rows,\ngrouped Region > Country. `tests/perf/server-row-model.spec.ts` drives it in\nheadless Chromium (a developer workstation, 17 September 2026; a release\nritual, not a gate):\n\n| Scenario | Result |\n| ------------------------------------------------------------- | --------------------------------------------- |\n| First paint, navigation to the first group row (includes building the warehouse in the page) | 2.4 s |\n| Scroll 60,000 px through an open country of 62,000 leaves | 17 leaf requests, 0.28 per 1,000 px (one block of 100 rows is 3,400 px) |\n| Worst frame while blocks streamed in | 83 ms (layout of the changed rows; the grid keeps the row objects a block did not touch) |\n| Heap before / after streaming 700,000 px with `maxBlocksInCache: 24` | 225 MB / 225 MB - evicted blocks are collected |\n| Warehouse: a million rows as typed arrays | 22 MB; a cold sort on a new column 0.8 to 1.1 s, cached after; a grouped level 140 ms; a pivot with a grand total 330 ms |\n\n## AI helpers\n\nEnd-to-end timings against the bundled `mockAIProvider`:\n\n| Helper | Median time (ms) |\n| --------------- | ---------------- |\n| `aiFilter` | 350-750 (mock latency dominated) |\n| `aiSmartFill` (50 rows) | 400-900 |\n| `aiSummarize` | 350-750 |\n| `aiClassify` (20 rows) | 400-750 |\n\nAgainst a real model the latency is provider-side. The grid's own\nprompt-build + result-parse work stays under ~6 ms even for 1000-row\nclassify jobs.\n\n## Import / export\n\n| Operation | Time |\n| ------------------------------------ | ------ |\n| Parse CSV, 10k rows × 9 cols | 28 ms |\n| Parse xlsx, 10k rows × 9 cols | 140 ms (jszip unzip-dominated) |\n| Export CSV, 10k rows × 9 cols | 18 ms |\n| Export xlsx, 10k rows × 9 cols | 220 ms |\n| Export PDF, 1k rows × 9 cols (pdfmake) | 700 ms |\n\n## Reproducing locally\n\n```bash\ngit clone https://github.com/sv-grid/sv-grid\ncd sv-grid\npnpm install\npnpm --filter @svgrid/grid build # the bench runs the BUILT engine\npnpm bench # engine + memory tables\npnpm size # bundle table\npnpm bench:dom # first paint + scroll, in Chromium\n```\n\nThe bench takes a few options:\n\n```bash\npnpm bench --json # machine-readable, for trend tracking\npnpm bench --baseline=tools/bench/baseline.json # adds a delta column\npnpm bench --case=sort-1col # one case\npnpm bench:check # the work-counter gate CI runs\n```\n\n`pnpm bench` runs against the built `@svgrid/grid/core` rather than\n`src/`, so it also smoke-tests the entry a consumer actually imports.\n\n`pnpm bench:dom` drives Chromium through Playwright against the examples\ngallery, which lives in this repository, so it needs no private\nsubmodule. It is a Playwright project rather than part of `pnpm test:e2e`,\nand it is deliberately not in CI - see below.\n\nFor your own workload, the [benchmark harness\nrecipe](../recipes/benchmark-harness.md) and the [FPS HUD\nrecipe](../recipes/profiling-with-fps-hud.md) are copy-paste probes you\ncan drop into your app.\n\n## What we *don't* claim\n\n- That we are faster than any other grid. Nothing on *this* page is a\n head-to-head measurement. Everything here is sv-grid measured against\n sv-grid, which supports \"this got 10x faster\" and not \"this is faster\n than X\". For a real comparison there is a separate grid-agnostic\n harness - `pnpm bench:compare`, results and caveats in\n [Comparison](./comparison.md) - and it does not say we win everything.\n- That first paint is good. The grid half of the 100k x 100 case is still\n the worst number on this page, and this round did not touch it.\n- Any scroll figure above 60 fps. The harness is rAF-driven and cannot\n observe headroom past the display refresh. \"Zero dropped frames\" is the\n claim; \"120 fps\" is not.\n- Lab-grade first-paint numbers. Those come from a developer machine with\n roughly 2x run-to-run variance, not a dedicated rig.\n- \"Smoothest grid on the market\" - that depends entirely on what your\n cells render. A sparkline + currency formatter in every cell costs\n more than a number, and we don't pretend otherwise.\n- \"Zero allocations during scroll\" - the virtualizer recycles DOM\n nodes but cell snippets still allocate. The numbers above include\n real-world snippets (status pills, mini-bars).\n- Single-thread performance > 1M rows. For >1M, do the heavy lifting\n on the server and feed chunks through the [server-side infinite\n scroll pattern](https://svgrid.com/demos/33-server-infinite/).\n\n## Frequently asked questions\n\n### How fast is SvGrid?\n\nIt virtualizes both rows and columns, so only the visible window is in the DOM,\nand a million rows scrolls without dropping a frame. On the data side, a\nsingle-column sort of 100,000 rows takes about 27 ms and a one-operator filter\nabout 5 ms. Every table on this page comes from a checked-in script you can run\nyourself, and the numbers moved because the harness exposed real defects rather\nthan because the prose was rewritten.\n\n### How many rows can SvGrid handle?\n\nClient-side, 100k+ rows scroll smoothly thanks to virtualization. For millions\nof rows, page or chunk from the server (see Server-side data). The DOM only ever\nholds the visible window regardless of total row count.\n\n### How fast is SvGrid, and how big is it?\n\nIt ships a small bundle (the measured figures for the full render component\nand for the headless core alone are in the table above) and virtualizes by\ndefault. Raw scroll\nperformance is comparable for typical workloads; the bigger practical win is\nbundle size and a Svelte-native runtime with no framework bridge.\n\n## See also\n\n- [Browser support](./browser-support.md) - the matrix the benchmarks\n ran against.\n- [Testing and quality](./testing-and-quality.md) - the coverage\n thresholds that gate every release.\n"
5128
5271
  },
5129
5272
  {
5130
5273
  "slug": "help/bolt-new",
@@ -5145,7 +5288,7 @@ export const docs = [
5145
5288
  "path": "docs/help/bundle-size.md",
5146
5289
  "title": "Bundle size",
5147
5290
  "section": "Help",
5148
- "markdown": "# Bundle size\n\nWhat SvGrid costs in your bundle, how to reproduce the number on your\nbranch, and what to do if size matters.\n\n## Measured\n\nThe table below is generated from `docs/_data/svgrid-size.json`, the file\n`pnpm size:json` writes; `node tools/sync-guide-facts.mjs` rewrites it and\n`tools/competitor-facts.test.ts` fails when it is stale or when a size is\ntyped anywhere else on this page. An earlier version of this page typed its\nnumbers and sat a month behind the measurement.\n\n<!-- size:start -->\nRe-measured **30 Oct 2026** at `@svgrid/grid` 3.0.30 with the script that ships in the repo (`pnpm size:json`):\n\n| Target | Base JS (gzip) | CSS (gzip) | Loaded on demand |\n| --- | ---: | ---: | ---: |\n| Headless core (`createSvGrid`) | **3.2 KB** | - | - |\n| Headless subpath (`@svgrid/grid/core`) | **10.0 KB** | - | - |\n| Full render component (`<SvGrid>`) | **100.0 KB** | **11.3 KB** | **198.9 KB** |\n| Standalone chart (`<SvChart>`) | **71.9 KB** | - | **15.0 KB** |\n<!-- size:end -->\n\nThe two headless rows measure different things on purpose. `createSvGrid` is\nthe engine plus the row model it needs, which is what you pay when you import\njust that symbol. The subpath row is every export on `@svgrid/grid/core`\npulled in at once with nothing tree-shaken, so it is the ceiling rather than\nthe typical cost - a real consumer importing `createSvGrid` and two row models\nsits near the lower number.\n\nSvelte is a peer dependency and is excluded from every figure. Builds are\nminified and gzipped at level 9.\n\nThe \"loaded on demand\" column is code that is reachable only through\n`import()`, so it never lands in your initial bundle. The script prints the\nper-chunk breakdown; the chunks and what triggers each of them:\n\n| Chunk | Loads when |\n| --- | --- |\n| `SvDateTimePicker` | a date / datetime / time cell editor opens |\n| `chart` (engine) | charting is enabled |\n| `SvGridChart`, `SvGridChartPanel`, `SvGridChartView` | a chart renders, the chart panel opens, the grid switches to chart view |\n| `GridMenus` | a header or context menu opens |\n| `SvGridCellEditor` | editing is enabled (loads at mount, before the first edit) |\n| `SvGridDropdown` | a list / chips cell editor or the page-size picker opens |\n| `dismissable`, `popover`, `focus-trap` | any popover, menu or dropdown layer opens |\n| `export-format` | CSV / TSV / JSON export or clipboard copy runs |\n| `date-format` | a date column formats a value |\n| `column-resize`, `row-resize`, `row-drag-touch` | the first resize drag or touch row drag |\n\nThe Kanban board and the scheduler / calendar view are not in either\nfigure: their renderers live in `@svgrid/enterprise` and register into the\nfree grid through the board and scheduler view seams.\n\n## Reproduce on your branch\n\n`measure-size.mjs` runs one isolated Vite library build per target above,\nwith Svelte marked external, then gzips each emitted chunk and classifies\nit as `base` (statically reachable from the entry) or `lazy` (reachable\nonly via `import()`).\n\n```bash\nnode packages/grid/scripts/measure-size.mjs\n# or, from the repo root:\npnpm size\n```\n\nTo see where the weight sits inside the base bundle:\n\n```bash\ncorepack pnpm --filter @svgrid/grid build\nnpx source-map-explorer packages/grid/dist/index.js\n```\n\nA treemap opens in your browser. Each block is a source file scaled by its\nbyte cost in the final bundle.\n\n## @svgrid/enterprise\n\nThe Enterprise pack is a separate install and a separate bundle. `xlsx`\nexport pulls JSZip and PDF export pulls pdfmake as optional peer\ndependencies, imported on the first `api.exportData(...)` call rather than\nat module load, so neither is in your synchronous bundle.\n\n## What to do if size matters\n\n1. **Use the headless engine for read-only views.** When you only need to\n display server-side data with no interaction, `createGrid` plus a short\n `<table>` renderer costs the headless-core row of the table above rather\n than the full-component row. See the\n [headless engine reference](../reference/headless-engine.md).\n2. **Register only the features you use.** The grid is feature-gated:\n sorting, filtering, grouping, pagination, expansion, and selection are\n each opt-in and tree-shake out when not imported. See the\n [features reference](../reference/features.md).\n3. **Let the lazy chunks stay lazy.** Charts, date/time editors, menus,\n and export already split themselves. Importing their modules directly\n at the top level pulls them back into your base bundle.\n4. **Code-split the Enterprise pack.** `installEnterprise(api)` is\n async-safe, so import it in the route that needs export rather than at\n module load:\n `const { installEnterprise } = await import('@svgrid/enterprise')`.\n\n## See also\n\n- [Features reference](../reference/features.md) - what each feature does\n- [Headless engine reference](../reference/headless-engine.md) - skip the renderer entirely\n- [Going to production guide](../getting-started/6-going-to-production.md)\n"
5291
+ "markdown": "# Bundle size\n\nWhat SvGrid costs in your bundle, how to reproduce the number on your\nbranch, and what to do if size matters.\n\n## Measured\n\nThe table below is generated from `docs/_data/svgrid-size.json`, the file\n`pnpm size:json` writes; `node tools/sync-guide-facts.mjs` rewrites it and\n`tools/competitor-facts.test.ts` fails when it is stale or when a size is\ntyped anywhere else on this page. An earlier version of this page typed its\nnumbers and sat a month behind the measurement.\n\n<!-- size:start -->\nRe-measured **1 Nov 2026** at `@svgrid/grid` 3.0.31 with the script that ships in the repo (`pnpm size:json`):\n\n| Target | Base JS (gzip) | CSS (gzip) | Loaded on demand |\n| --- | ---: | ---: | ---: |\n| Headless core (`createSvGrid`) | **3.2 KB** | - | - |\n| Headless subpath (`@svgrid/grid/core`) | **10.0 KB** | - | - |\n| Full render component (`<SvGrid>`) | **99.8 KB** | **11.3 KB** | **198.9 KB** |\n| Standalone chart (`<SvChart>`) | **71.9 KB** | - | **15.0 KB** |\n<!-- size:end -->\n\nThe two headless rows measure different things on purpose. `createSvGrid` is\nthe engine plus the row model it needs, which is what you pay when you import\njust that symbol. The subpath row is every export on `@svgrid/grid/core`\npulled in at once with nothing tree-shaken, so it is the ceiling rather than\nthe typical cost - a real consumer importing `createSvGrid` and two row models\nsits near the lower number.\n\nSvelte is a peer dependency and is excluded from every figure. Builds are\nminified and gzipped at level 9.\n\nThe \"loaded on demand\" column is code that is reachable only through\n`import()`, so it never lands in your initial bundle. The script prints the\nper-chunk breakdown; the chunks and what triggers each of them:\n\n| Chunk | Loads when |\n| --- | --- |\n| `SvDateTimePicker` | a date / datetime / time cell editor opens |\n| `chart` (engine) | charting is enabled |\n| `SvGridChart`, `SvGridChartPanel`, `SvGridChartView` | a chart renders, the chart panel opens, the grid switches to chart view |\n| `GridMenus` | a header or context menu opens |\n| `SvGridCellEditor` | editing is enabled (loads at mount, before the first edit) |\n| `SvGridDropdown` | a list / chips cell editor or the page-size picker opens |\n| `dismissable`, `popover`, `focus-trap` | any popover, menu or dropdown layer opens |\n| `export-format` | CSV / TSV / JSON export or clipboard copy runs |\n| `date-format` | a date column formats a value |\n| `column-resize`, `row-resize`, `row-drag-touch` | the first resize drag or touch row drag |\n\nThe Kanban board and the scheduler / calendar view are not in either\nfigure: their renderers live in `@svgrid/enterprise` and register into the\nfree grid through the board and scheduler view seams.\n\n## Reproduce on your branch\n\n`measure-size.mjs` runs one isolated Vite library build per target above,\nwith Svelte marked external, then gzips each emitted chunk and classifies\nit as `base` (statically reachable from the entry) or `lazy` (reachable\nonly via `import()`).\n\n```bash\nnode packages/grid/scripts/measure-size.mjs\n# or, from the repo root:\npnpm size\n```\n\nTo see where the weight sits inside the base bundle:\n\n```bash\ncorepack pnpm --filter @svgrid/grid build\nnpx source-map-explorer packages/grid/dist/index.js\n```\n\nA treemap opens in your browser. Each block is a source file scaled by its\nbyte cost in the final bundle.\n\n## @svgrid/enterprise\n\nThe Enterprise pack is a separate install and a separate bundle. `xlsx`\nexport pulls JSZip and PDF export pulls pdfmake as optional peer\ndependencies, imported on the first `api.exportData(...)` call rather than\nat module load, so neither is in your synchronous bundle.\n\n## What to do if size matters\n\n1. **Use the headless engine for read-only views.** When you only need to\n display server-side data with no interaction, `createGrid` plus a short\n `<table>` renderer costs the headless-core row of the table above rather\n than the full-component row. See the\n [headless engine reference](../reference/headless-engine.md).\n2. **Register only the features you use.** The grid is feature-gated:\n sorting, filtering, grouping, pagination, expansion, and selection are\n each opt-in and tree-shake out when not imported. See the\n [features reference](../reference/features.md).\n3. **Let the lazy chunks stay lazy.** Charts, date/time editors, menus,\n and export already split themselves. Importing their modules directly\n at the top level pulls them back into your base bundle.\n4. **Code-split the Enterprise pack.** `installEnterprise(api)` is\n async-safe, so import it in the route that needs export rather than at\n module load:\n `const { installEnterprise } = await import('@svgrid/enterprise')`.\n\n## See also\n\n- [Features reference](../reference/features.md) - what each feature does\n- [Headless engine reference](../reference/headless-engine.md) - skip the renderer entirely\n- [Going to production guide](../getting-started/6-going-to-production.md)\n"
5149
5292
  },
5150
5293
  {
5151
5294
  "slug": "help/cells/cell-components",
@@ -5460,7 +5603,7 @@ export const docs = [
5460
5603
  "path": "docs/help/comparison.md",
5461
5604
  "title": "Comparison: SvGrid vs AG Grid vs TanStack Table",
5462
5605
  "section": "Help",
5463
- "markdown": "\n# Comparison: SvGrid vs AG Grid vs TanStack Table\n\nThe three projects solve overlapping problems, and the right choice\ndepends on the framework you ship on, how much of the grid you want to\nbuild yourself, and your budget. Every number on this page is read from\nnpm or measured by a script in this repository on the date shown; the\nblock below is regenerated by `node tools/sync-guide-facts.mjs` and the\nper-competitor pages under [/compare/](https://svgrid.com/compare/) list\nthe sources for every feature claim.\n\n<!-- facts:start ag-grid,tanstack-table -->\n> **Facts, checked 12 Sep 2026.** `ag-grid-community` 36.1.0, MIT, last published 5 Aug 2026, 12,400,000 npm downloads in the 30 days to 10 Sep 2026. `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `ag-grid-community` 36.1.0 317.5 KB JS, no separate stylesheet (measured 12 Sep 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). AG Grid pricing, as its site states it: AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer (https://www.ag-grid.com/license-pricing/, read 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/), [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/).\n<!-- facts:end -->\n\n## TL;DR\n\n| Project | Lives in | Ships | Licence |\n| --------------------- | ---------------------------------------- | ---------------------------------------------------------- | ----------------------------------------- |\n| **SvGrid** | Svelte 5 | Headless core + Svelte render component + Enterprise pack | MIT (Community) / commercial (Enterprise) |\n| **AG Grid Community** | React, Angular, Vue, plain JS | Full grid + renderer; Svelte through community integrations | MIT |\n| **AG Grid Enterprise**| same | Adds the set filter, range selection, master/detail, tree, grouping, pivot, charts, Excel export, server-side row model | Commercial, per developer |\n| **TanStack Table** | React, Vue, Svelte, Solid, Qwik, Lit, JS | Headless engine **only**; the Svelte adapter is Svelte 5 | MIT |\n\nThe bundle sizes and prices are in the facts block above, with the date\nthey were read and the method behind the sizes.\n\n## When SvGrid is the right choice\n\n- You're on **Svelte 5** and want a grid that uses the runtime's idioms\n (snippets for cells, `$state` for data, `$derived` for aggregates) -\n not a React-port pretending to be Svelte.\n- You want a **headless core you can render yourself** AND a\n default-styled component for the 80% case. Most \"headless\" libraries\n make you write the markup; most \"monolith\" libraries make you fight\n the markup. SvGrid does both in one package.\n- You need **clean theming via CSS custom properties** and a documented\n `--sg-*` token surface, not a hard-coded class soup.\n- You ship under **strict CSP** (no `eval`, no `new Function`, no\n inline scripts). SvGrid runs clean; AG Grid Community does too.\n TanStack Table is engine-only so the question doesn't apply.\n- You want **SSR markup that is meaningful before hydration** (good\n first paint, SEO, SvelteKit `+page.server` integration). SvGrid +\n TanStack Table both qualify. AG Grid renders client-side.\n- You want the features AG Grid sells as Enterprise - the set filter,\n range selection, master/detail, tree data, grouping with aggregation,\n integrated charts, flat server-side infinite scroll - **in the MIT\n core**. (Server-side grouping, tree, pivot and transactions are\n Enterprise in both.)\n\n## When AG Grid is the right choice\n\n- You're on **React, Angular, or Vue**, not Svelte. SvGrid is\n Svelte-only, and ag-grid.com points Svelte users to community-built\n integrations rather than an official package.\n- You need a push-based **viewport row model** for a real-time trading\n blotter, where the server streams the visible window over a socket.\n SvGrid's server-side row model covers sort, filter, grouping, tree,\n pivot, transactions and select-all across unloaded rows, and its\n real-time page merges deltas into loaded rows, but it does not have the\n viewport model.\n- You need **custom tool panels**. SvGrid's tool panel is a fixed\n Columns + Filters pair. Custom filter components are covered by a\n column's `customFilter`.\n- You need **AG Charts** for maps, network graphs, 3D or a canvas renderer.\n SvGrid's chart is SVG with decimation, and it ships 29 types, a configurable\n axis model, synchronized charts, a financial toolkit with indicator panes\n and drawing tools, a builder and PDF export in the MIT core; it does not\n draw maps.\n- You want a vendor with **a decade of enterprise procurement paperwork**\n already on file.\n\n## When TanStack Table is the right choice\n\n- You want a **rendering-framework-agnostic engine** so the same\n business logic powers React + Svelte + Solid surfaces in your\n monorepo.\n- You're already in the TanStack ecosystem (Query, Router, Form,\n Virtual) and want one mental model.\n- You're happy writing **all the markup yourself** - the row recycling,\n the keyboard map, the ARIA roles, the focus management, the\n drag-to-resize. That's the cost of \"engine only\".\n\n## Feature parity at a glance\n\nYes: shipped in that edition. Partial: needs extra work or a companion\npackage. No: not available. The AG Grid columns follow ag-grid.com's\nCommunity vs Enterprise page and its Set Filter, Tree Data and CSV export\npages; the dated list of those sources is on the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page, and the\nTanStack sources on [SvGrid vs TanStack Table](https://svgrid.com/compare/tanstack-table/).\n\n| | SvGrid Community | SvGrid Enterprise | AG Grid Community | AG Grid Enterprise | TanStack Table |\n| ------------------------------- | ---------------- | ----------------- | ----------------- | ------------------ | -------------- |\n| Headless core (engine only) | Yes | Yes | No | No | Yes |\n| Default render component | Yes (Svelte 5) | Yes | Yes (each framework) | Yes | No |\n| Sort (multi-column) | Yes | Yes | Yes | Yes | Yes (engine) |\n| Filter menu (operator + facet) | Yes | Yes | Partial (text and number filters; the set filter is Enterprise) | Yes | No |\n| Filter row | Yes | Yes | Yes | Yes | No |\n| Pagination | Yes | Yes | Yes | Yes | Yes (engine) |\n| Grouping + aggregation | Yes | Yes | No (Enterprise) | Yes | Yes (engine) |\n| Tree / expand-collapse rows | Yes | Yes | No (Enterprise) | Yes | Yes (engine) |\n| Master/detail | Yes | Yes | No (Enterprise) | Yes | No |\n| Cell range selection + copy/paste | Yes | Yes | No (Enterprise) | Yes | No |\n| Fill handle | Yes | Yes | No (Enterprise) | Yes | No |\n| Inline editing (typed editors) | Yes | Yes | Yes | Yes | No |\n| Column virtualization | Yes | Yes | Yes | Yes | No |\n| Row virtualization | Yes | Yes | Yes | Yes | Partial (pair with TanStack Virtual) |\n| Column pinning (left/right) | Yes | Yes | Yes | Yes | No |\n| Column tool panel | Yes | Yes | No (Enterprise) | Yes | No |\n| Context menu | Yes | Yes | No (Enterprise) | Yes | No |\n| Fit-to-width with shrink | Yes | Yes | Partial | Yes | No |\n| WAI-ARIA grid pattern | Yes | Yes | Yes | Yes | No (your markup) |\n| Server-side data, flat (sort / filter / paging / infinite scroll) | Yes (built in) | Yes (built in) | Yes (infinite row model) | Yes (built in) | Partial (manual flags) |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | No (Enterprise) | Yes (built in) | No (Enterprise) | Yes (built in) | No |\n| Global search over server-side data | Yes (`filterModel.global`) | Yes | No (the quick filter is client-side only) | No | n/a |\n| CSP-clean (no eval, no inline) | Yes | Yes | Yes | Yes | n/a |\n| Meaningful SSR markup | Yes | Yes | No | No | depends on your markup |\n| CSV / TSV / JSON export | Yes | Yes | Yes (CSV) | Yes | No |\n| Excel (.xlsx) / PDF export | No | Yes | No | Yes (Excel) | No |\n| Print | No | Yes | No | No | No |\n| Excel / CSV import | No | Yes | No | No | No |\n| In-grid AI helpers (bring your own model) | Yes | Yes | No | No | No |\n| MCP server for AI assistants | Yes (`@svgrid/mcp`) | Yes | Yes (`ag-mcp`) | Yes | No (agent skills ship in the package) |\n| Pivot table | No | Yes | No | Yes | No (custom) |\n| Integrated charts | Yes (29 types, builder, financial toolkit) | Yes | No | Yes (AG Charts) | No |\n| Support response time | GitHub (best-effort) | 1 business day; 1h sev-1 on Enterprise | GitHub (best-effort) | no number published | GitHub; paid Enterprise Support offered |\n| Theming via CSS variables | Yes (`--sg-*`) | Yes | Yes (theme builder) | Yes | n/a |\n| Source button per demo | Yes (gallery) | Yes | No | No | No |\n\n## Bundle size\n\nThe facts block at the top of the page has the gzipped size of each\npackage, measured by the same method: each package built alone with Vite\nin library mode, minified, gzip level 9, Svelte external because it is a\npeer dependency. SvGrid's own number comes from `pnpm size:json`\n(`packages/grid/scripts/measure-size.mjs`), the competitors' from\n`pnpm competitors:measure`; both write `docs/_data` and the block is\nregenerated from there, so the page cannot quote a size nobody measured.\n\nWhat the SvGrid number contains: the whole render component -\nvirtualization, Excel-style filters, inline editing, grouping, tree,\nmaster/detail, cell selection and accessibility - in one import, plus a\nseparate stylesheet. Charts, date and time editors, menus and export split\ninto `import()` chunks that load on demand rather than shipping in the\ninitial bundle; the headless core on its own is a small fraction of the\nrender component, and `@svgrid/enterprise` features are separate subpath\nimports. The per-entry breakdown, including the headless core and the\nlazy chunks, is in the [bundle size reference](./bundle-size.md).\n\nWhat the AG Grid number contains: `createGrid` with every Community\nmodule registered and the Quartz theme, whose CSS ships inside the script\nunder the theming API, so there is no separate stylesheet to add. The\nTanStack number is the whole Svelte adapter with its engine: no\nvirtualizer, filter UI or editors, because a headless library has none.\n\n## Measured performance\n\nA vendor's own benchmark is worth nothing unless you can rerun it, so the\nharness is in the repository and takes an adapter per grid. Adding another\ngrid is about forty lines in `examples/src/bench/adapters.ts` and nothing\nelse.\n\n```bash\n# headless, prints the table and writes tests/perf/.last-compare.json\nBENCH_REPEATS=7 BENCH_GRIDS=svgrid,aggrid,svar,tanstack pnpm bench:compare\n\n# move that run into docs/_data/competitors.json, then regenerate this page\nnode tools/record-benchmarks.mjs && node tools/sync-guide-facts.mjs\n\n# or drive it by hand\npnpm --filter @svgrid/grid-example-gallery dev # then open /bench.html\n```\n\nEach operation is timed until the grid's DOM reflects it, plus one frame:\n\n- **Mount** - fresh container, create the grid, until rows are painted.\n- **Sort** - change the sort on one column, until the new order is painted.\n Text sorts `name` (tens of thousands of distinct values), numeric sorts\n `amount`.\n- **Filter** - apply a `contains` filter to one column.\n- **Scroll** - 180 frames at 60 px/frame, sampling frame intervals.\n\n### Results\n\nThe table is generated from the ledger by `tools/sync-guide-facts.mjs`;\nthe versions and the date are part of it.\n\n<!-- bench:start -->\nMeasured 28 Oct 2026 with `pnpm bench:compare` (tests/perf/compare.spec.ts, recorded by tools/record-benchmarks.mjs): 100,000 rows x 9 columns; 1000 x 520 px container, 32 px rows, 140 px columns, each grid with its default theme; fastest of 3 samples per operation, each grid in a fresh page; Chromium through Playwright, headless; win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig; tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up. Lower is better.\n\n| Operation | SvGrid | AG Grid Community | SVAR Svelte DataGrid | TanStack Table, minimal DOM |\n| --- | --- | --- | --- | --- |\n| Mount | 30.7 ms | 67 ms | 11.4 ms | 170.2 ms |\n| Sort, text column | 77.4 ms | 213.9 ms | 135.4 ms | 360.9 ms |\n| Sort, numeric column | 32.8 ms | 216.7 ms | 141.7 ms | 178.2 ms |\n| Filter, one column (indicative only, see below) | 34.5 ms | 148.8 ms | 26.1 ms | 51.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.5 ms | 34.6 ms | 34.3 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 259.2 ms | 152.2 ms | 563.4 ms |\n| Main-thread work per 60 px scroll step, mean | 3.5 ms | 4.5 ms | 3 ms | 2.9 ms |\n| Frames dropped while scrolling, of 180 | 0 | 0 | 0 | 0 |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 | 180 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 36 | 19 | 27 |\n| JS heap the grid adds, mounted, after GC | 5.7 MB | 42.1 MB | 2.3 MB | 109.9 MB |\n| JS heap the grid adds, after sorting and filtering, after GC | 17.6 MB | 26.2 MB | 3.9 MB | 113.3 MB |\n| Elements created per scroll frame | 0 | 30.1 | 16.8 | 18.7 |\n| Elements re-inserted per scroll frame (rows recycled) | 37.3 | 35.8 | 0 | 0 |\n\nVersions: `@svgrid/grid` 3.0.25, `ag-grid-community` 36.1.0, `wx-svelte-grid` 2.7.0, `@tanstack/svelte-table` 9.2.4.\n<!-- bench:end -->\n\nRead that as: **SvGrid sorts and keeps a live sort current faster than the\nother three, scrolling is level across all four, and SVAR is ahead on mount\nand memory** - it paints its first rows in under half of SvGrid's time and\nholds the least heap. Every grid scrolls at the display rate here, so the\np95 frame reads the same for all four; the work row under it is what a\nslower machine or a 120 Hz display would feel. There TanStack and SVAR do\nthe least per scroll step, about half a millisecond under SvGrid, and AG\nGrid the most. The row varies from run to run, so read the order of the\nfirst three as close, not settled. SvGrid makes its row objects the first time a\nsort or filter reads every row rather than at mount, which is why its two\nheap rows differ. The TanStack renderer pays for building a row object per\nrecord before it can draw anything. Anyone claiming a single headline\nnumber for a grid comparison is selling something.\n\n**The heap rows are the JS heap after a forced garbage collection, less the\nsame page with the data built and no grid,** so the 100,000 rows themselves\ncount against no one. The two DOM rows are counted over 60 untimed scroll\nframes after the timed ones. \"Created\" is elements that did not exist\nbefore; \"re-inserted\" is elements the grid already had and moved, which is\nhow a keyed list recycles a row from one end of the window to the other.\nSvGrid creates none and moves the two rows that cross the edge each frame;\na grid that rewrote its rows in place would score 0 on both.\n\n**The filter row is not a like-for-like comparison and is shown only because\nhiding a number we win looks worse than explaining it.** The grids' single-\ncolumn filter APIs differ: the harness drives AG Grid's quick filter, which\nsearches every column and is strictly more work than the single-column\n`contains` SvGrid performs, while SVAR and TanStack run a predicate over the\none column. Do not read a ratio into that row.\n\n**The TanStack column is an engine plus the least DOM an app could draw.**\nTanStack Table renders nothing, so its adapter draws the row model through\na fixed-height windowed table with no virtualizer library, no filter UI and\nno editors. Its mount and sort numbers include creating the engine's row\nobjects for every record; the grids around it do the same work inside their\nown models.\n\nSorting is where SvGrid's distance comes from, and it is not subtle: SvGrid\nresolves each sort clause once and precomputes a key array, and for a\ncolumn whose distinct values are far fewer than its rows it collates the\ndistinct values once and sorts by rank. Mounting is the other direction -\nsee the accounting in [benchmarks](./benchmarks.md).\n\nAt 1,000,000 rows the harness runs one grid per invocation\n(`BENCH_ROWS=1000000 BENCH_GRIDS=<one> BENCH_TICKS=30`); TanStack's\nadapter does not finish at that size. Those runs are not in the table\nbecause only a run that measured every grid together is comparable.\n\nTwo methodology notes, both of which were bugs in this harness before they\nwere notes, and both of which changed the numbers by more than any code\nchange did:\n\n- **Each grid runs in a fresh page.** They used to run one after another in\n the same one, where the first warmed the JIT, fragmented the heap and\n left a hundred thousand rows of garbage for the next. Back-to-back runs\n on an idle machine disagreed with themselves by a factor of two.\n That order effect is gone, but this workstation still varies by about\n 2x between whole runs taken minutes apart, for every grid at once, so\n compare the columns of one run and not one run against another.\n- **Operations are timed until the DOM changes, not for a fixed two\n frames.** The old fixed wait put a two-frame floor under every number -\n an operation that recomputed nothing at all measured the floor, and a\n mount whose rows were already in the DOM measured pure waiting - which\n flattered whichever grid was slower.\n- **Each figure is the fastest of the samples, not the median.** Noise\n only ever adds time, so the minimum is the cleanest estimate of what the\n machine can do, and medians on this box drifted by a third between\n consecutive runs - more than most of the differences being measured.\n Applied identically to every grid.\n\nWhat this table deliberately does not include:\n\n- **Features the grids do not measure the same way.** Grouping, pivot,\n editing and export all differ enough in shape that a single timing would\n compare two different amounts of work. The filter row above is the one\n case we publish anyway, labelled, rather than quietly dropping a result\n that happens to favour us.\n- **Any grid we cannot license for this.** The harness is grid-agnostic on\n purpose, but some commercial grids licence their software in ways that\n restrict using it to produce competitive claims. Where that is the case\n we do not ship an adapter, and we would rather have an obviously\n incomplete table than a legally dubious one. Run your own shortlist.\n- **Your workload.** One dataset shape, one machine, one browser, default\n configuration for every grid. If a grid decision rides on this, clone the\n harness and put your own data in it.\n\n## Migrating from AG Grid\n\nThe most common starting point. See\n[Migrating from AG Grid](./migrating-from-ag-grid.md) for a side-by-side\ntranslation of column defs, features, filtering, editing, and the\nimperative API. The example that guide is built around runs here:\n\n<div data-docs-demo=\"139-migration-from-ag-grid\" data-height=\"560\"></div>\n\n## Migrating from TanStack Table\n\nThe map is one-to-one - SvGrid's headless core speaks the vocabulary\nTanStack Table v9 introduced. The big differences:\n\n- Replace `createTable(opts)` with `createSvGrid(opts)`. Same state\n machine, same features object.\n- Replace the row-model factories with the same names from\n `@svgrid/grid`.\n- The render layer changes - TanStack hands you `FlexRender` + the\n row model; SvGrid lets you keep that headless approach OR drop in\n the default `<SvGrid>` component.\n\nThe headless demo below drives a plain `<table>` from `createSvGrid`, the\nway a TanStack app would:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\nAnd the same rows through the render component, which is the part TanStack\nleaves to you. The example runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Order = {\n id: number\n customer: string\n region: string\n status: string\n amount: number\n }\n\n const orders: Order[] = [\n { id: 1, customer: 'Ada Lovelace', region: 'EMEA', status: 'open', amount: 1240 },\n { id: 2, customer: 'Grace Hopper', region: 'AMER', status: 'shipped', amount: 860 },\n { id: 3, customer: 'Linus Torvalds', region: 'EMEA', status: 'closed', amount: 2210 },\n { id: 4, customer: 'Radia Perlman', region: 'APAC', status: 'open', amount: 430 },\n { id: 5, customer: 'Barbara Liskov', region: 'AMER', status: 'pending', amount: 1780 },\n ]\n\n let rows = $state<Order[]>(orders)\n\n const columns: GridColumns<Order> = [\n { field: 'customer', header: 'Customer', width: 180 },\n { field: 'region', header: 'Region', width: 110 },\n { field: 'status', header: 'Status', width: 110 },\n { field: 'amount', header: 'Amount', width: 120, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable selectable />\n```\n\n## Pricing\n\nSvGrid Community is MIT - free for commercial use, no attribution\nrequired at runtime. SvGrid Enterprise is a per-developer licence: $599\nper developer per year for the enterprise grid or $999 with the\nspreadsheet and Studio, both for unlimited applications; see\n<https://svgrid.com/pricing/> for what each tier adds.\n\nAG Grid Community is MIT. AG Grid Enterprise is priced per developer with\none year of updates; the figure ag-grid.com listed on the date we read it\nis in the facts block at the top of this page, and the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page carries the\nlink. Compare what each paid tier adds before comparing prices: most of\nwhat AG Grid sells as Enterprise is in SvGrid's free core.\n\nTanStack Table is MIT and sponsor-funded; tanstack.com offers paid\nEnterprise Support as private consulting.\n\n## Frequently asked questions\n\n### What is the best data grid for Svelte 5?\n\nFor a Svelte-5-native grid with a batteries-included render component, SvGrid is\nbuilt around runes and snippets. TanStack Table is a strong headless-only\nchoice if you want to build the DOM layer yourself across frameworks, and its\nv9 Svelte adapter targets Svelte 5. AG Grid is the most feature-complete but\nlives in React, Angular and Vue first and reaches Svelte through\ncommunity-built integrations.\n\n### Is SvGrid a good AG Grid alternative?\n\nYes, for Svelte projects. SvGrid is a fraction of AG Grid Community's\nmeasured size on a Svelte page (the facts block has both numbers and the\nmethod), is MIT-licensed for commercial use, and offers `@svgrid/enterprise`\nfor export, print, import and pivot at a per-developer price. On the\nbenchmark above it sorts a hundred-thousand-row column faster on both\ncolumn types and scrolls level; AG Grid mounts quicker. It does not match\nevery AG Grid Enterprise feature - see the\n[missing-features list](./missing-features.md) for the gaps.\n\n### SvGrid vs TanStack Table - which should I pick?\n\nPick SvGrid if you want virtualization, Excel-style filters, selection, and\ninline editing working out of the box on Svelte 5. Pick TanStack Table if you\nwant a framework-agnostic headless engine and are happy to build the rendering,\nvirtualization, and editing UI yourself. Both are MIT-licensed.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The `@tanstack/svelte-table` v9 line declares a Svelte 5 peer range\nand passes data through getters rather than stores; the facts block above\nshows the version read from npm. The earlier `createSvelteTable` constructor\nis gone in v9.\n\n### Does AG Grid have an MCP server like SvGrid?\n\nYes. `ag-mcp` (MIT) gives an assistant AG Grid's docs, examples and\nversion-specific upgrade prompts. `@svgrid/mcp` does the same for SvGrid\nand adds a code checker that validates props and imports against the real\nAPI surface, a scaffold tool and a preview. Neither is an in-grid feature;\nSvGrid's natural-language filter, smart fill and summarise helpers are, and\nthey ship free in `@svgrid/grid` with a model provider you register.\n\n### How big is the SvGrid bundle?\n\nThe facts block at the top of this page has the measured gzipped size of the\nfull `<SvGrid>` render component and its stylesheet, read from\n`docs/_data/svgrid-size.json`, which `pnpm size:json` writes. The\n[bundle size reference](./bundle-size.md) breaks it down by entry:\nthe headless core on its own, the core subpath, the charts, and the lazy\nchunks that load on demand.\n\n## See also\n\n- [Why headless?](../why-headless.md) - the design decision behind\n SvGrid's two-layer architecture.\n- [Migrating from AG Grid](./migrating-from-ag-grid.md) - the\n practical recipe.\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - the\n one-to-one API map.\n- [Benchmarks](./benchmarks.md) - how the numbers are produced and what\n they leave out.\n- [Enterprise feature pack](../enterprise/README.md) - what SvGrid charges for.\n- [Missing features](./missing-features.md) - the honest gap list\n versus AG Grid Enterprise.\n- [All comparisons](https://svgrid.com/compare/) - one page per grid, with\n dated sources for every claim.\n"
5606
+ "markdown": "\n# Comparison: SvGrid vs AG Grid vs TanStack Table\n\nThe three projects solve overlapping problems, and the right choice\ndepends on the framework you ship on, how much of the grid you want to\nbuild yourself, and your budget. Every number on this page is read from\nnpm or measured by a script in this repository on the date shown; the\nblock below is regenerated by `node tools/sync-guide-facts.mjs` and the\nper-competitor pages under [/compare/](https://svgrid.com/compare/) list\nthe sources for every feature claim.\n\n<!-- facts:start ag-grid,tanstack-table -->\n> **Facts, checked 12 Sep 2026.** `ag-grid-community` 36.1.0, MIT, last published 5 Aug 2026, 12,400,000 npm downloads in the 30 days to 10 Sep 2026. `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `ag-grid-community` 36.1.0 317.5 KB JS, no separate stylesheet (measured 12 Sep 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). AG Grid pricing, as its site states it: AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer (https://www.ag-grid.com/license-pricing/, read 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/), [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/).\n<!-- facts:end -->\n\n## TL;DR\n\n| Project | Lives in | Ships | Licence |\n| --------------------- | ---------------------------------------- | ---------------------------------------------------------- | ----------------------------------------- |\n| **SvGrid** | Svelte 5 | Headless core + Svelte render component + Enterprise pack | MIT (Community) / commercial (Enterprise) |\n| **AG Grid Community** | React, Angular, Vue, plain JS | Full grid + renderer; Svelte through community integrations | MIT |\n| **AG Grid Enterprise**| same | Adds the set filter, range selection, master/detail, tree, grouping, pivot, charts, Excel export, server-side row model | Commercial, per developer |\n| **TanStack Table** | React, Vue, Svelte, Solid, Qwik, Lit, JS | Headless engine **only**; the Svelte adapter is Svelte 5 | MIT |\n\nThe bundle sizes and prices are in the facts block above, with the date\nthey were read and the method behind the sizes.\n\n## When SvGrid is the right choice\n\n- You're on **Svelte 5** and want a grid that uses the runtime's idioms\n (snippets for cells, `$state` for data, `$derived` for aggregates) -\n not a React-port pretending to be Svelte.\n- You want a **headless core you can render yourself** AND a\n default-styled component for the 80% case. Most \"headless\" libraries\n make you write the markup; most \"monolith\" libraries make you fight\n the markup. SvGrid does both in one package.\n- You need **clean theming via CSS custom properties** and a documented\n `--sg-*` token surface, not a hard-coded class soup.\n- You ship under **strict CSP** (no `eval`, no `new Function`, no\n inline scripts). SvGrid runs clean; AG Grid Community does too.\n TanStack Table is engine-only so the question doesn't apply.\n- You want **SSR markup that is meaningful before hydration** (good\n first paint, SEO, SvelteKit `+page.server` integration). SvGrid +\n TanStack Table both qualify. AG Grid renders client-side.\n- You want the features AG Grid sells as Enterprise - the set filter,\n range selection, master/detail, tree data, grouping with aggregation,\n integrated charts, flat server-side infinite scroll - **in the MIT\n core**. (Server-side grouping, tree, pivot and transactions are\n Enterprise in both.)\n\n## When AG Grid is the right choice\n\n- You're on **React, Angular, or Vue**, not Svelte. SvGrid is\n Svelte-only, and ag-grid.com points Svelte users to community-built\n integrations rather than an official package.\n- You need a push-based **viewport row model** for a real-time trading\n blotter, where the server streams the visible window over a socket.\n SvGrid's server-side row model covers sort, filter, grouping, tree,\n pivot, transactions and select-all across unloaded rows, and its\n real-time page merges deltas into loaded rows, but it does not have the\n viewport model.\n- You need **custom tool panels**. SvGrid's tool panel is a fixed\n Columns + Filters pair. Custom filter components are covered by a\n column's `customFilter`.\n- You need **AG Charts** for maps, network graphs, 3D or a canvas renderer.\n SvGrid's chart is SVG with decimation, and it ships 29 types, a configurable\n axis model, synchronized charts, a financial toolkit with indicator panes\n and drawing tools, a builder and PDF export in the MIT core; it does not\n draw maps.\n- You want a vendor with **a decade of enterprise procurement paperwork**\n already on file.\n\n## When TanStack Table is the right choice\n\n- You want a **rendering-framework-agnostic engine** so the same\n business logic powers React + Svelte + Solid surfaces in your\n monorepo.\n- You're already in the TanStack ecosystem (Query, Router, Form,\n Virtual) and want one mental model.\n- You're happy writing **all the markup yourself** - the row recycling,\n the keyboard map, the ARIA roles, the focus management, the\n drag-to-resize. That's the cost of \"engine only\".\n\n## Feature parity at a glance\n\nYes: shipped in that edition. Partial: needs extra work or a companion\npackage. No: not available. The AG Grid columns follow ag-grid.com's\nCommunity vs Enterprise page and its Set Filter, Tree Data and CSV export\npages; the dated list of those sources is on the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page, and the\nTanStack sources on [SvGrid vs TanStack Table](https://svgrid.com/compare/tanstack-table/).\n\n| | SvGrid Community | SvGrid Enterprise | AG Grid Community | AG Grid Enterprise | TanStack Table |\n| ------------------------------- | ---------------- | ----------------- | ----------------- | ------------------ | -------------- |\n| Headless core (engine only) | Yes | Yes | No | No | Yes |\n| Default render component | Yes (Svelte 5) | Yes | Yes (each framework) | Yes | No |\n| Sort (multi-column) | Yes | Yes | Yes | Yes | Yes (engine) |\n| Filter menu (operator + facet) | Yes | Yes | Partial (text and number filters; the set filter is Enterprise) | Yes | No |\n| Filter row | Yes | Yes | Yes | Yes | No |\n| Pagination | Yes | Yes | Yes | Yes | Yes (engine) |\n| Grouping + aggregation | Yes | Yes | No (Enterprise) | Yes | Yes (engine) |\n| Tree / expand-collapse rows | Yes | Yes | No (Enterprise) | Yes | Yes (engine) |\n| Master/detail | Yes | Yes | No (Enterprise) | Yes | No |\n| Cell range selection + copy/paste | Yes | Yes | No (Enterprise) | Yes | No |\n| Fill handle | Yes | Yes | No (Enterprise) | Yes | No |\n| Inline editing (typed editors) | Yes | Yes | Yes | Yes | No |\n| Column virtualization | Yes | Yes | Yes | Yes | No |\n| Row virtualization | Yes | Yes | Yes | Yes | Partial (pair with TanStack Virtual) |\n| Column pinning (left/right) | Yes | Yes | Yes | Yes | No |\n| Column tool panel | Yes | Yes | No (Enterprise) | Yes | No |\n| Context menu | Yes | Yes | No (Enterprise) | Yes | No |\n| Fit-to-width with shrink | Yes | Yes | Partial | Yes | No |\n| WAI-ARIA grid pattern | Yes | Yes | Yes | Yes | No (your markup) |\n| Server-side data, flat (sort / filter / paging / infinite scroll) | Yes (built in) | Yes (built in) | Yes (infinite row model) | Yes (built in) | Partial (manual flags) |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | No (Enterprise) | Yes (built in) | No (Enterprise) | Yes (built in) | No |\n| Global search over server-side data | Yes (`filterModel.global`) | Yes | No (the quick filter is client-side only) | No | n/a |\n| CSP-clean (no eval, no inline) | Yes | Yes | Yes | Yes | n/a |\n| Meaningful SSR markup | Yes | Yes | No | No | depends on your markup |\n| CSV / TSV / JSON export | Yes | Yes | Yes (CSV) | Yes | No |\n| Excel (.xlsx) / PDF export | No | Yes | No | Yes (Excel) | No |\n| Print | No | Yes | No | No | No |\n| Excel / CSV import | No | Yes | No | No | No |\n| In-grid AI helpers (bring your own model) | Yes | Yes | No | No | No |\n| MCP server for AI assistants | Yes (`@svgrid/mcp`) | Yes | Yes (`ag-mcp`) | Yes | No (agent skills ship in the package) |\n| Pivot table | No | Yes | No | Yes | No (custom) |\n| Integrated charts | Yes (29 types, builder, financial toolkit) | Yes | No | Yes (AG Charts) | No |\n| Support response time | GitHub (best-effort) | 1 business day; 1h sev-1 on Enterprise | GitHub (best-effort) | no number published | GitHub; paid Enterprise Support offered |\n| Theming via CSS variables | Yes (`--sg-*`) | Yes | Yes (theme builder) | Yes | n/a |\n| Source button per demo | Yes (gallery) | Yes | No | No | No |\n\n## Bundle size\n\nThe facts block at the top of the page has the gzipped size of each\npackage, measured by the same method: each package built alone with Vite\nin library mode, minified, gzip level 9, Svelte external because it is a\npeer dependency. SvGrid's own number comes from `pnpm size:json`\n(`packages/grid/scripts/measure-size.mjs`), the competitors' from\n`pnpm competitors:measure`; both write `docs/_data` and the block is\nregenerated from there, so the page cannot quote a size nobody measured.\n\nWhat the SvGrid number contains: the whole render component -\nvirtualization, Excel-style filters, inline editing, grouping, tree,\nmaster/detail, cell selection and accessibility - in one import, plus a\nseparate stylesheet. Charts, date and time editors, menus and export split\ninto `import()` chunks that load on demand rather than shipping in the\ninitial bundle; the headless core on its own is a small fraction of the\nrender component, and `@svgrid/enterprise` features are separate subpath\nimports. The per-entry breakdown, including the headless core and the\nlazy chunks, is in the [bundle size reference](./bundle-size.md).\n\nWhat the AG Grid number contains: `createGrid` with every Community\nmodule registered and the Quartz theme, whose CSS ships inside the script\nunder the theming API, so there is no separate stylesheet to add. The\nTanStack number is the whole Svelte adapter with its engine: no\nvirtualizer, filter UI or editors, because a headless library has none.\n\n## Measured performance\n\nA vendor's own benchmark is worth nothing unless you can rerun it, so the\nharness is in the repository and takes an adapter per grid. Adding another\ngrid is about forty lines in `examples/src/bench/adapters.ts` and nothing\nelse.\n\n```bash\n# headless, prints the table and writes tests/perf/.last-compare.json\nBENCH_REPEATS=7 BENCH_GRIDS=svgrid,aggrid,svar,tanstack pnpm bench:compare\n\n# move that run into docs/_data/competitors.json, then regenerate this page\nnode tools/record-benchmarks.mjs && node tools/sync-guide-facts.mjs\n\n# or drive it by hand\npnpm --filter @svgrid/grid-example-gallery dev # then open /bench.html\n```\n\nEach operation is timed until the grid's DOM reflects it, plus one frame:\n\n- **Mount** - fresh container, create the grid, until rows are painted.\n- **Sort** - change the sort on one column, until the new order is painted.\n Text sorts `name` (tens of thousands of distinct values), numeric sorts\n `amount`.\n- **Filter** - apply a `contains` filter to one column.\n- **Scroll** - 180 frames at 60 px/frame, sampling frame intervals.\n\n### Results\n\nThe table is generated from the ledger by `tools/sync-guide-facts.mjs`;\nthe versions and the date are part of it.\n\n<!-- bench:start -->\nMeasured 28 Oct 2026 with `pnpm bench:compare` (tests/perf/compare.spec.ts, recorded by tools/record-benchmarks.mjs): 100,000 rows x 9 columns; 1000 x 520 px container, 32 px rows, 140 px columns, each grid with its default theme; fastest of 3 samples per operation, each grid in a fresh page; Chromium through Playwright, headless; win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig; tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up. Lower is better.\n\n| Operation | SvGrid | AG Grid Community | SVAR Svelte DataGrid | TanStack Table, minimal DOM |\n| --- | --- | --- | --- | --- |\n| Mount | 30.7 ms | 67 ms | 11.4 ms | 170.2 ms |\n| Sort, text column | 77.4 ms | 213.9 ms | 135.4 ms | 360.9 ms |\n| Sort, numeric column | 32.8 ms | 216.7 ms | 141.7 ms | 178.2 ms |\n| Filter, one column (indicative only, see below) | 34.5 ms | 148.8 ms | 26.1 ms | 51.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.5 ms | 34.6 ms | 34.3 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 259.2 ms | 152.2 ms | 563.4 ms |\n| Main-thread work per 60 px scroll step, mean | 3.5 ms | 4.5 ms | 3 ms | 2.9 ms |\n| Frames dropped while scrolling, of 180 | 0 | 0 | 0 | 0 |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 | 180 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 36 | 19 | 27 |\n| JS heap the grid adds, mounted, after GC | 5.7 MB | 42.1 MB | 2.3 MB | 109.9 MB |\n| JS heap the grid adds, after sorting and filtering, after GC | 17.6 MB | 26.2 MB | 3.9 MB | 113.3 MB |\n| Elements created per scroll frame | 0 | 30.1 | 16.8 | 18.7 |\n| Elements re-inserted per scroll frame (rows recycled) | 37.3 | 35.8 | 0 | 0 |\n\nVersions: `@svgrid/grid` 3.0.25, `ag-grid-community` 36.1.0, `wx-svelte-grid` 2.7.0, `@tanstack/svelte-table` 9.2.4.\n<!-- bench:end -->\n\nRead that as: **SvGrid sorts and keeps a live sort current faster than the\nother three, scrolling is level across all four, and SVAR is ahead on mount\nand memory** - it paints its first rows in under half of SvGrid's time and\nholds the least heap. Every grid scrolls at the display rate here, so the\np95 frame reads the same for all four; the work row under it is what a\nslower machine or a 120 Hz display would feel. There TanStack and SVAR do\nthe least per scroll step, about half a millisecond under SvGrid, and AG\nGrid the most. The row varies from run to run, so read the order of the\nfirst three as close, not settled. SvGrid makes its row objects the first time a\nsort or filter reads every row rather than at mount, which is why its two\nheap rows differ. The TanStack renderer pays for building a row object per\nrecord before it can draw anything. Anyone claiming a single headline\nnumber for a grid comparison is selling something.\n\n**The heap rows are the JS heap after a forced garbage collection, less the\nsame page with the data built and no grid,** so the 100,000 rows themselves\ncount against no one. The two DOM rows are counted over 60 untimed scroll\nframes after the timed ones. \"Created\" is elements that did not exist\nbefore; \"re-inserted\" is elements the grid already had and moved, which is\nhow a keyed list recycles a row from one end of the window to the other.\nSvGrid creates none and moves the two rows that cross the edge each frame;\na grid that rewrote its rows in place would score 0 on both.\n\n**The filter row is not a like-for-like comparison and is shown only because\nhiding a number we win looks worse than explaining it.** The grids' single-\ncolumn filter APIs differ: the harness drives AG Grid's quick filter, which\nsearches every column and is strictly more work than the single-column\n`contains` SvGrid performs, while SVAR and TanStack run a predicate over the\none column. Do not read a ratio into that row.\n\n**The TanStack column is an engine plus the least DOM an app could draw.**\nTanStack Table renders nothing, so its adapter draws the row model through\na fixed-height windowed table with no virtualizer library, no filter UI and\nno editors. Its mount and sort numbers include creating the engine's row\nobjects for every record; the grids around it do the same work inside their\nown models.\n\nSorting is where SvGrid's distance comes from, and it is not subtle: SvGrid\nresolves each sort clause once and precomputes a key array, and for a\ncolumn whose distinct values are far fewer than its rows it collates the\ndistinct values once and sorts by rank. Mounting is the other direction -\nsee the accounting in [benchmarks](./benchmarks.md).\n\nAt 1,000,000 rows the harness runs one grid per invocation\n(`BENCH_ROWS=1000000 BENCH_GRIDS=<one> BENCH_TICKS=30`); TanStack's\nadapter does not finish at that size. Those runs are not in the table\nbecause only a run that measured every grid together is comparable.\n\nTwo methodology notes, both of which were bugs in this harness before they\nwere notes, and both of which changed the numbers by more than any code\nchange did:\n\n- **Each grid runs in a fresh page.** They used to run one after another in\n the same one, where the first warmed the JIT, fragmented the heap and\n left a hundred thousand rows of garbage for the next. Back-to-back runs\n on an idle machine disagreed with themselves by a factor of two.\n That order effect is gone, but this workstation still varies by about\n 2x between whole runs taken minutes apart, for every grid at once, so\n compare the columns of one run and not one run against another.\n- **Operations are timed until the DOM changes, not for a fixed two\n frames.** The old fixed wait put a two-frame floor under every number -\n an operation that recomputed nothing at all measured the floor, and a\n mount whose rows were already in the DOM measured pure waiting - which\n flattered whichever grid was slower.\n- **Each figure is the fastest of the samples, not the median.** Noise\n only ever adds time, so the minimum is the cleanest estimate of what the\n machine can do, and medians on this box drifted by a third between\n consecutive runs - more than most of the differences being measured.\n Applied identically to every grid.\n\nWhat this table deliberately does not include:\n\n- **Features the grids do not measure the same way.** Grouping, pivot,\n editing and export all differ enough in shape that a single timing would\n compare two different amounts of work. The filter row above is the one\n case we publish anyway, labelled, rather than quietly dropping a result\n that happens to favour us.\n- **Any grid we cannot license for this.** The harness is grid-agnostic on\n purpose, but some commercial grids licence their software in ways that\n restrict using it to produce competitive claims. Where that is the case\n we do not ship an adapter, and we would rather have an obviously\n incomplete table than a legally dubious one. Run your own shortlist.\n- **Your workload.** One dataset shape, one machine, one browser, default\n configuration for every grid. If a grid decision rides on this, clone the\n harness and put your own data in it.\n\n## Migrating from AG Grid\n\nThe most common starting point. See\n[Migrating from AG Grid](./migrating-from-ag-grid.md) for a side-by-side\ntranslation of column defs, features, filtering, editing, and the\nimperative API. The example that guide is built around runs here:\n\n<div data-docs-demo=\"139-migration-from-ag-grid\" data-height=\"560\"></div>\n\n## Migrating from TanStack Table\n\nThe map is one-to-one - SvGrid's headless core speaks the vocabulary\nTanStack Table v9 introduced. The big differences:\n\n- Replace `createTable(opts)` with `createSvGrid(opts)`. Same state\n machine, same features object.\n- Replace the row-model factories with the same names from\n `@svgrid/grid`.\n- The render layer changes - TanStack hands you `FlexRender` + the\n row model; SvGrid lets you keep that headless approach OR drop in\n the default `<SvGrid>` component.\n\nThe headless demo below drives a plain `<table>` from `createSvGrid`, the\nway a TanStack app would:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\nAnd the same rows through the render component, which is the part TanStack\nleaves to you. The example runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Order = {\n id: number\n customer: string\n region: string\n status: string\n amount: number\n }\n\n const orders: Order[] = [\n { id: 1, customer: 'Ada Lovelace', region: 'EMEA', status: 'open', amount: 1240 },\n { id: 2, customer: 'Grace Hopper', region: 'AMER', status: 'shipped', amount: 860 },\n { id: 3, customer: 'Linus Torvalds', region: 'EMEA', status: 'closed', amount: 2210 },\n { id: 4, customer: 'Radia Perlman', region: 'APAC', status: 'open', amount: 430 },\n { id: 5, customer: 'Barbara Liskov', region: 'AMER', status: 'pending', amount: 1780 },\n ]\n\n let rows = $state<Order[]>(orders)\n\n const columns: GridColumns<Order> = [\n { field: 'customer', header: 'Customer', width: 180 },\n { field: 'region', header: 'Region', width: 110 },\n { field: 'status', header: 'Status', width: 110 },\n { field: 'amount', header: 'Amount', width: 120, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable selectable />\n```\n\n## Pricing\n\nSvGrid Community is MIT - free for commercial use, no attribution\nrequired at runtime. SvGrid Enterprise is a per-developer licence: $599\nper developer per year for the enterprise grid or $999 with the\nspreadsheet and Studio, both for unlimited applications; see\n<https://svgrid.com/pricing/> for what each tier adds.\n\nAG Grid Community is MIT. AG Grid Enterprise is priced per developer with\none year of updates; the figure ag-grid.com listed on the date we read it\nis in the facts block at the top of this page, and the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page carries the\nlink. Compare what each paid tier adds before comparing prices: most of\nwhat AG Grid sells as Enterprise is in SvGrid's free core.\n\nTanStack Table is MIT and sponsor-funded; tanstack.com offers paid\nEnterprise Support as private consulting.\n\n## Frequently asked questions\n\n### What is the best data grid for Svelte 5?\n\nFor a Svelte-5-native grid with a batteries-included render component, SvGrid is\nbuilt around runes and snippets. TanStack Table is a strong headless-only\nchoice if you want to build the DOM layer yourself across frameworks, and its\nv9 Svelte adapter targets Svelte 5. AG Grid is the most feature-complete but\nlives in React, Angular and Vue first and reaches Svelte through\ncommunity-built integrations.\n\n### Is SvGrid a good AG Grid alternative?\n\nYes, for Svelte projects. SvGrid is a fraction of AG Grid Community's\nmeasured size on a Svelte page (the facts block has both numbers and the\nmethod), is MIT-licensed for commercial use, and offers `@svgrid/enterprise`\nfor export, print, import and pivot at a per-developer price. On the\nbenchmark above it sorts a hundred-thousand-row column faster on both\ncolumn types and scrolls level; AG Grid mounts quicker. It does not match\nevery AG Grid Enterprise feature - see the\n[missing-features list](./missing-features.md) for the gaps.\n\n### SvGrid vs TanStack Table - which should I pick?\n\nPick SvGrid if you want virtualization, Excel-style filters, selection, and\ninline editing working out of the box on Svelte 5. Pick TanStack Table if you\nwant a framework-agnostic headless engine and are happy to build the rendering,\nvirtualization, and editing UI yourself. Both are MIT-licensed.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The `@tanstack/svelte-table` v9 line declares a Svelte 5 peer range\nand passes data through getters rather than stores; the facts block above\nshows the version read from npm. The earlier `createSvelteTable` constructor\nis gone in v9.\n\n### Does AG Grid have an MCP server like SvGrid?\n\nYes. `ag-mcp` (MIT) gives an assistant AG Grid's docs, examples and\nversion-specific upgrade prompts. `@svgrid/mcp` does the same for SvGrid\nand adds a code checker that validates props and imports against the real\nAPI surface, a scaffold tool and a preview. Neither is an in-grid feature;\nSvGrid's natural-language filter, smart fill and summarise helpers are, and\nthey ship free in `@svgrid/grid` with a model provider you register.\n\n### How big is the SvGrid bundle?\n\nThe facts block at the top of this page has the measured gzipped size of the\nfull `<SvGrid>` render component and its stylesheet, read from\n`docs/_data/svgrid-size.json`, which `pnpm size:json` writes. The\n[bundle size reference](./bundle-size.md) breaks it down by entry:\nthe headless core on its own, the core subpath, the charts, and the lazy\nchunks that load on demand.\n\n## See also\n\n- [Why headless?](../why-headless.md) - the design decision behind\n SvGrid's two-layer architecture.\n- [Migrating from AG Grid](./migrating-from-ag-grid.md) - the\n practical recipe.\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - the\n one-to-one API map.\n- [Benchmarks](./benchmarks.md) - how the numbers are produced and what\n they leave out.\n- [Enterprise feature pack](../enterprise/README.md) - what SvGrid charges for.\n- [Missing features](./missing-features.md) - the honest gap list\n versus AG Grid Enterprise.\n- [All comparisons](https://svgrid.com/compare/) - one page per grid, with\n dated sources for every claim.\n"
5464
5607
  },
5465
5608
  {
5466
5609
  "slug": "help/conditional-form-schema",
@@ -5586,7 +5729,7 @@ export const docs = [
5586
5729
  "path": "docs/help/fields.md",
5587
5730
  "title": "Field types",
5588
5731
  "section": "SvGrid Base",
5589
- "markdown": "# Field types\n\nA column can say what it is - a rating, a URL, a single select with colored\noptions, a list of files - with `fieldType`, and set that type's properties\nwith `fieldProps`. The type fills in the editor, the format and the\nalignment, and draws the cell when the type needs a cell of its own (stars,\nlinks, file thumbnails). The same module adds a \"+\" after the last column to\ncreate fields, a \"+ Add row\" line under the last row, status colors on the\nrow header, field actions in the column menu, and a view bar with saved grid,\nKanban, calendar, gallery and form views.\n\n<div data-docs-demo=\"504-project-tracker\" data-height=\"620\"></div>\n\n> **SvGrid Base, part of the Suite edition.** The `fieldType` / `fieldProps`\n> column properties and the `rowAdder`, `rowColor`, `columnAdder`,\n> `fieldMenu`, `expandRows` and `primaryField` props are part of the free\n> `@svgrid/grid` types; what draws them is SvGrid Base\n> (`@svgrid/enterprise/base`, or `@svgrid/enterprise/fields` for the field\n> types alone). Without it a `fieldType` column draws as an ordinary column and\n> the props do nothing. Without a Suite key the grid shows the Enterprise\n> watermark and everything still runs. New here? [Build a project\n> tracker](./base/start.md) first.\n\n## Turn it on\n\n`enableFields()` registers the built-in types for every grid on the page. It is\na separate module: `installEnterprise()` does not load it, so an app that never\ncalls `enableFields()` does not ship it.\n\n```ts\nimport { enableFields } from '@svgrid/enterprise/fields'\n\nenableFields()\n```\n\n## A table with views\n\n`SvBase` is a grid with a view bar over it. Every prop it does not name\ngoes to the grid; `views` are the saved views and `activeView` the one shown.\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, type FieldView } from '@svgrid/enterprise/fields'\n\n let views = $state<FieldView[]>([\n { id: 'all', name: 'All tasks', type: 'grid' },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n { id: 'due', name: 'Due dates', type: 'calendar', dateField: 'due' },\n { id: 'cards', name: 'Gallery', type: 'gallery', coverField: 'files' },\n { id: 'form', name: 'Request a task', type: 'form' },\n ])\n</script>\n\n<SvBase {data} {columns} bind:views primaryField=\"task\" editable\n showRowNumbers expandRows containerHeight={600} />\n```\n\nA grid, Kanban, calendar, Gantt or gallery view is the grid itself in another\nmode (`board`, `scheduler`, `gantt`, `gallery`), so the filter and the sort\ncarry over; a form view is drawn beside the grid, which stays mounted under\nit. In a board, calendar or gallery the bar's search narrows the records; the\ntext is not saved with the view. The Gantt type is\noffered once the app has enabled the Gantt view; its task table holds the\nprimary field, the two dates and the working days.\n\n`SvBaseViewBar` is the bar on its own, for a page that lays out its own\ngrid:\n\n```svelte\n<SvBaseViewBar {api} bind:views bind:activeView />\n<SvGrid {data} {columns} onApiReady={(a) => (api = a)} />\n```\n\n## The view bar\n\nFrom the left: the view switcher, then Hide fields, Filter, Group, Sort,\nColor and Row height, and at the right the record count and search (the\ngrid's find bar, Ctrl+F). A button with something set says so (\"2 hidden\nfields\", \"Filtered by Status\", \"Sorted by 1 field\") and is tinted. Each\nsetting goes through the grid's own state, so `api.getState()` holds it.\n\n- **Hide fields**: a switch per field, a search, hide all / show all, and\n drag to reorder. The primary field is always shown.\n- **Filter**: conditions on fields (below), joined by \"and\" or \"or\", with\n condition groups one level deep. Each change filters at once.\n- **Group**: up to three fields, each with a direction. Group headers show\n the value as its cell draws it (see [Grouped records](#grouped-records)).\n- **Sort**: fields in order, each with a direction labeled for its type:\n \"1 → 9\" for a number or a date, \"A → Z\" for text, \"☐ → ☑\" for a checkbox.\n- **Color**: none, a single select's option colors, or conditions in order\n with a color each (the first match colors the row, where the `rowColor`\n prop's `target` says; a condition still missing its value colors nothing).\n A view with no color setting shows the `rowColor` prop's colors.\n- **Row height**: short, medium, tall and extra tall (`rowHeights` on\n `SvBase` or `SvBaseViewBar` sets the list).\n\n## Filter conditions\n\nA condition is a field, an operator that fits the field's type and a value in\nthe control the field calls for. A condition without a value yet filters\nnothing. The filter is the grid's advanced filter with its own expression\nkind, `fieldFilter`, so `api.setAdvancedFilter` sets it and a saved view\nkeeps it.\n\n| Field type | Operators |\n|---|---|\n| Text, long text, URL, email, phone, barcode, formula, lookup | contains, does not contain, is, is not, is empty, is not empty |\n| Number, currency, percent, rating, duration, autonumber, count, rollup | =, ≠, <, >, ≤, ≥, is empty, is not empty |\n| Single select, user | is, is not, is any of, is none of, is empty, is not empty |\n| Multiple select, multiple users | has any of, has all of, is exactly, has none of, is empty, is not empty |\n| Date, created time, last modified time | is, is before, is after, is on or before, is on or after, is within, is empty, is not empty |\n| Checkbox | is checked / unchecked |\n| Attachment | file name contains, is empty, is not empty |\n| Link to another table | contains, does not contain, is, is not (by the records' names), is empty, is not empty |\n\nA date compares days: \"today\", \"tomorrow\", \"one week ago\", \"one month from\nnow\" or an exact date, and \"is within\" takes the past or next week, month or\nyear, or a number of days. A bare `'2026-10-14'` is that day where the user\nis.\n\n```ts\napi.setAdvancedFilter({\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'status', kind: 'select', op: 'isAnyOf', value: ['Todo', 'Blocked'] },\n { column: 'due', kind: 'date', op: 'isWithin', value: { span: 'nextWeek' } },\n ],\n})\n```\n\n## Saved views\n\nA view is a name, a type and the settings it had when it was last left:\n\n| Key | What it holds |\n|---|---|\n| `id`, `name`, `type` | `'grid'`, `'kanban'`, `'calendar'`, `'gantt'`, `'gallery'`, `'chart'` or `'form'` |\n| `state` | the grid's state: sorts, groups, the filter, hidden fields, order, widths, pinned columns |\n| `rowHeight`, `color` | the row height and how rows are colored |\n| `stackBy` | Kanban: the single select or user field the cards stack by |\n| `dateField`, `endField` | calendar and Gantt: the dates a record starts and ends on |\n| `progressField`, `dependencyField`, `zoom` | Gantt: a percent field the bars fill with, a link field to the same table naming what each record depends on, and the zoom it was left at |\n| `coverField` | gallery: the attachment field whose first image is the cover |\n| `chart` | chart: `kind` (`'bar'`, `'barH'`, `'line'`, `'pie'`, `'donut'`), `x` the field to group by, `y` a number field (else a count), `aggregation` (`'sum'` or `'avg'`) |\n| `formFields`, `formTitle`, `formDescription` | form: the fields it asks for and its heading |\n\nThe view switcher creates a view of any type (a Kanban asks what to stack by,\na calendar which date field), renames, duplicates and deletes. A new view\nstarts plain: no filter, sorts or groups, every field shown. Changes to the\nshown view are kept a moment after they are made, and `onViewsChange` reports\nthe list whenever it changes, so the app can store it. A Kanban card moved to\nanother lane, or a calendar record moved to another day, writes the field\nthrough the grid's edit path (undo, validation, `onCellValueChange`); a date\nfield without a time shows as all-day events. A Kanban card draws its fields as their cells do (pills,\navatars, file thumbnails), and \"+ Add a card\" in a lane adds a record already\nin that lane, named by the primary field. Double-click a card (or F2) to open its record. On\nthe calendar, picking a day adds a record on it and opens it with its name\nready to type.\n\nA Kanban stacked by a field draws an \"Uncategorized\" lane only while a record\nhas no value in that field. A calendar view whose `color` is a single select\n(`{ mode: 'field', field: 'stage' }`) colors each event as the record's\noption, with the options above the calendar as a legend that hides and shows\ntheir events.\n\n## Gallery, chart and form views\n\nA gallery draws each record as a card: the cover image, the primary field as\nthe title, and the fields the grid shows, each drawn as its cell draws it. The\ncards follow the filter, the sort and the hidden fields; a click opens the\nrecord. It is the grid's [gallery view](./rows/gallery.md) (`gallery`), set up\nfrom the view: the cover field, the primary field as the title, the shown\nfields as the card's fields.\n\nA chart groups the records the view shows (its filter applies) by one field\nand counts them, or adds up or averages a number field, as a bar, horizontal\nbar, line, pie or donut chart. A single select keeps its options' order and\ncolors, a person and a linked record show by name, a date groups by month, and\nthe values read as the summed field writes them (\"$480,000\"). \"Customize\nchart\" in the view bar changes the kind, the field and the value; the view\nkeeps them as `chart`:\n\n```ts\n{ id: 'pipeline', name: 'Pipeline value by stage', type: 'chart', chart: { kind: 'bar', x: 'stage', y: 'value' } }\n{ id: 'funnel', name: 'Candidates by stage', type: 'chart', chart: { kind: 'donut', x: 'stage' } }\n```\n\nA form asks for the fields a person can fill in (computed fields are left\nout), each with the editor its cell uses, and adds a row the way \"+ Add row\"\ndoes: field defaults, the next autonumber, then what was typed, and\n`onRowAdd`. `SvBaseForm` takes `fields`, `required`, `title`,\n`description` and `onSubmit`; a field's `description` shows under it.\n\n## The primary field\n\n`primaryField` names the field that is the record's name. It is always the\nfirst column and pinned, it cannot be hidden or deleted (the column menu does\nnot offer it, the pin splitter stops at it), and it titles the expanded\nrecord, a gallery card and a calendar event.\n\n```svelte\n<SvGrid {data} {columns} primaryField=\"task\" />\n```\n\n## Declare columns by type\n\n```ts\nimport type { GridColumns } from '@svgrid/grid'\n\ntype Task = { task: string; status: string; tags: string[]; due: string; score: number; budget: number; spec: string }\n\nconst columns: GridColumns<Task> = [\n { field: 'task', header: 'Task', fieldType: 'text' },\n {\n field: 'status',\n header: 'Status',\n fieldType: 'singleSelect',\n fieldProps: { options: [{ value: 'Todo', color: '#64748b' }, { value: 'Done', color: '#16a34a' }] },\n },\n { field: 'tags', header: 'Tags', fieldType: 'multiSelect', fieldProps: { options: [{ value: 'Design' }, { value: 'Docs' }] } },\n { field: 'due', header: 'Due', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'score', header: 'Score', fieldType: 'rating' },\n { field: 'budget', header: 'Budget', fieldType: 'number', fieldProps: { format: 'currency', symbol: '€', symbolPosition: 'after', precision: 0 } },\n { field: 'spec', header: 'Spec', fieldType: 'url' },\n]\n```\n\nA property the column sets itself wins over its type:\n`{ fieldType: 'number', align: 'left' }` stays left-aligned.\n\n| Type | `fieldProps` |\n| --- | --- |\n| `text` | `default` |\n| `longText` | `richText` (**bold**, *italic*, `code`, [links](https://svgrid.com), \"- \" lists; drawn as elements, never as HTML) |\n| `attachment` | `accept`, `maxFiles`, `maxSize`, `upload` |\n| `checkbox` | `icon` (`check`, `x`, `star`, `heart`, `thumbsUp`, `flag`, `dot`), `color`, `default` |\n| `singleSelect`, `multiSelect` | `options` (`{ value, label?, color? }[]`, 40 colors in the editor, sort A to Z), `default` |\n| `user` | `multiple`, `default`; the people come from `setFieldUsers` |\n| `date` | `dateFormat` (`local`, `friendly`, `us`, `european`, `iso`), `time`, `timeFormat` (`12hour`, `24hour`), `gmt` (one time zone for everyone), `showTimeZone`, `defaultToday` |\n| `phone`, `email`, `url` | none |\n| `barcode` | none |\n| `button` | `label`, `color`, `url` (`{Field name}` filled from the row), or `onClick` set in code |\n| `number` | `format` (`integer`, `decimal`, `currency`, `percent`), `precision` 0 to 8, `step` (the editor's spinner, default 1), `separators` (`local`, `comma-period`, `period-comma`, `space-comma`, `space-period`), `showThousands`, `abbreviation` (`none`, `thousand`, `million`, `billion`; not for percent), `allowNegative`, `default`; currency: `symbol`, `symbolPosition` (`before`, `after`); percent: `showBar`, `points` (values 0 to 100 instead of fractions) |\n| `duration` | `durationFormat` (`h:mm`, `h:mm:ss`, `h:mm:ss.S`, `h:mm:ss.SS`, `h:mm:ss.SSS`); values are seconds, typed as `1:30` or `1h 30m` |\n| `rating` | `max` 1 to 10, `icon` (`star`, `heart`, `thumbsUp`, `flag`, `dot`), `color` |\n| `formula` | `formula`, `result` (`auto`, `number`, `currency`, `percent`, `date`) and that format's options |\n| `createdTime`, `lastModifiedTime` | the date options; last modified also `watch` (`all`, `specific`) and `watchFields` |\n| `createdBy`, `lastModifiedBy` | last modified by: `watch`, `watchFields`; the user comes from `setCurrentUser` |\n| `autoNumber` | none |\n| `link` | `table` (from `registerLinkedTable`), `multiple` |\n| `lookup` | `linkField`, `field` |\n| `rollup` | `linkField`, `field`, `aggregation` (`SUM`, `AVERAGE`, `MIN`, `MAX`, `COUNT`, `COUNTA`, `COUNTALL`, `ARRAYJOIN`, `ARRAYUNIQUE`, `CONCATENATE`, `AND`, `OR`), `precision` |\n| `count` | `linkField` |\n\nA number field has one editor for every format. The box shows the plain\nnumber with the field's decimal character, the currency symbol (before or\nafter) or the percent sign right beside it, and a spinner at the cell's\nedge: its arrows, or Up and Down, add or take away `step` (Shift: ten\ntimes). It reads what people type the way the field writes it: its own\nseparators, a pasted symbol or percent sign, `2.5k`, `3M`, `(120)` for -120.\nEnter commits and moves a row down, Tab a column across. On commit the\nvalue is rounded to the field's precision; text that is not a number, or a\nnegative where the field allows none, keeps the box open and says why under\nthe cell. Pasting `$1,200.50` into the cell is read the same way. Columns\nwith the older `currency` and `percent` field types keep working and open in\nthe field editor as a number in that format.\n\nLong text opens a panel over the cell with room for paragraphs: Enter\nstarts a new line, Ctrl+Enter (Cmd+Enter), Tab or a click outside saves,\nEscape leaves the cell as it was. With rich text on, the panel names the\nmarkup the cell draws.\n\nA duration uses the same editor in its own format: `2:00` in the box,\n`1:30` or `1h 30m` typed, a minute a step (a second when the format shows\nseconds). A date opens with the date written as its cells write it\n(`October 24, 2026` for friendly), and a date without time is stored as the\ncalendar date (`'2026-10-24'`), never moved across a day by a time zone.\n\nA select cell opens a panel over itself: the chosen options as pills (each\nwith a remove button), a search box and the options. Typing filters them; a\nvalue that is not an option yet is offered as \"Add option\", which adds it to\nthe field (with a color, through `onColumnChange`) and picks it. A multiple\nselect stays open to pick more; Backspace in the empty search box removes the\nlast choice. A user field opens the same panel with the people from\n`setFieldUsers`, each with the avatar and name its cells show.\n\nA `default` (or a type's own new-row value: today, the next autonumber, the\ncreated time, the current user) fills the rows the row adder adds. Computed\nand automatic fields are read-only; autonumber and created time give every\nexisting row a value when the field is created.\n\nURL, email and phone cells become links only for the schemes they mean\n(`http(s):`, `mailto:`, `tel:`). A value such as `javascript:alert(1)` stays\ntext.\n\n## Attachments\n\nAn attachment cell holds an array of files:\n\n```ts\nimport type { Attachment } from '@svgrid/enterprise/fields'\n\nconst files: Attachment[] = [\n { id: 'a1', url: 'https://cdn.example.com/plan.png', name: 'plan.png', type: 'image/png', size: 48213 },\n { id: 'a2', url: 'https://cdn.example.com/spec.pdf', name: 'spec.pdf', type: 'application/pdf' },\n]\n```\n\nImages show as thumbnails, other files as chips, as many as the column width\nholds and then \"+N\". Enter or a double click opens the dialog: add files with\nthe picker, by dropping them, by pasting them or by URL; remove, reorder (drag,\nor Alt+Left / Alt+Right) and preview (images and PDFs inline). Files dropped on\nthe cell itself are added without the dialog. Export writes the file names. A\ncopy in `<SvBase>` writes their URLs, and pasting text adds one attachment per\nhttp(s) URL in it, so a copied cell pastes as the same files. In a base, people\nand links copy as names too, and a pasted name finds its person or record.\n\nUploading is yours to decide. Set one uploader for the app, or one per column\nin `fieldProps.upload`; it gets the file, the row and an abort signal, reports\nprogress, and returns the attachment. A failed upload stays in the dialog with\nRetry.\n\n```ts\nimport { setAttachmentUploader } from '@svgrid/enterprise/fields'\n\nsetAttachmentUploader(async (file, { signal, onProgress }) => {\n const res = await fetch(`/api/upload?name=${encodeURIComponent(file.name)}`, { method: 'PUT', body: file, signal })\n if (!res.ok) throw new Error(`Upload failed (${res.status})`)\n onProgress(1)\n const { url } = (await res.json()) as { url: string }\n return { id: url, url, name: file.name, type: file.type, size: file.size }\n})\n```\n\nWith no uploader, added files stay in the page as `blob:` URLs and are gone\non reload. Thumbnails use `http(s):`, `blob:` and raster `data:image` URLs\nonly.\n\n## People, linked tables and formulas\n\nUser fields choose from the people you list; created by and last modified by\nwrite whoever you say is signed in. Link fields point at rows of a table you\nregister; lookup, rollup and count read through a link field.\n\n```ts\nimport { registerLinkedTable, setCurrentUser, setFieldUsers } from '@svgrid/enterprise/fields'\n\nsetFieldUsers([\n { id: 'u1', name: 'Ana Ruiz' },\n { id: 'u2', name: 'Ben Okafor', avatarUrl: 'https://cdn.example.com/ben.png' },\n])\nsetCurrentUser({ id: 'u1', name: 'Ana Ruiz' })\n\nregisterLinkedTable({\n id: 'milestones',\n name: 'Milestones',\n primaryField: 'name',\n rows: () => [{ id: 'm1', name: 'Beta', date: '2026-10-31' }],\n // A field's type, when it has one, is how a lookup shows it.\n fields: [{ field: 'name', header: 'Name' }, { field: 'date', header: 'Date', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } }],\n})\n\nconst columns = [\n { field: 'milestone', header: 'Milestone', fieldType: 'link', fieldProps: { table: 'milestones', multiple: false } },\n { field: 'milestoneDate', header: 'Milestone date', fieldType: 'lookup', fieldProps: { linkField: 'milestone', field: 'date' } },\n { field: 'total', header: 'Total', fieldType: 'formula', fieldProps: { formula: '{Qty} * {Unit price}', result: 'currency', precision: 2 } },\n]\n```\n\nA link cell shows one chip per linked record. A click on a chip opens that\nrecord (its fields, read-only: the table is the app's), and resting the\npointer on one previews it. A table with a `create` function lets the link\npicker add a record: a search that names no record offers \"+ Create\" for it,\npicked at once.\n\n```ts\nlet milestones = [{ id: 'm1', name: 'Beta', date: '2026-10-31' }]\nregisterLinkedTable({\n id: 'milestones',\n name: 'Milestones',\n primaryField: 'name',\n rows: () => milestones,\n create: (name) => {\n const row = { id: `m${milestones.length + 1}`, name, date: '' }\n milestones = [...milestones, row]\n return row\n },\n})\n```\n\nA formula refers to fields by name in braces and supports `+ - * /`, `&` to\njoin text, comparisons, and functions such as `IF`, `SWITCH`, `AND`, `OR`,\n`CONCATENATE`, `LEFT`, `ROUND`, `SUM`, `DATEADD` and `DATETIME_DIFF`\n(the editor lists them all). It is parsed into functions once, never\nevaluated as code; a formula that does not compile shows `#ERROR` in its\ncells and its message in the field editor.\n\n## Tables and links\n\n`<SvBase tables>` holds several tables, one tab each. A table is its records,\nits fields and its views; `id` is what link fields name.\n\n```ts\nimport { SvBase, type BaseTable } from '@svgrid/enterprise/base'\n\nlet tables: BaseTable[] = [\n {\n id: 'deals', name: 'Deals', primaryField: 'deal', data: deals,\n columns: [\n { field: 'deal', header: 'Deal', fieldType: 'text' },\n { field: 'account', header: 'Account', fieldType: 'link', fieldProps: { table: 'accounts', multiple: false, inverse: 'deals' } },\n ],\n views: [{ id: 'all', name: 'All deals', type: 'grid' }],\n },\n {\n id: 'accounts', name: 'Accounts', primaryField: 'name', data: accounts,\n columns: [\n { field: 'name', header: 'Name', fieldType: 'text' },\n { field: 'deals', header: 'Deals', fieldType: 'link', fieldProps: { table: 'deals', inverse: 'account' } },\n { field: 'pipeline', header: 'Pipeline', fieldType: 'rollup', fieldProps: { linkField: 'deals', field: 'value', aggregation: 'SUM' } },\n ],\n },\n]\n```\n\n```svelte\n<SvBase bind:tables editable columnAdder fieldMenu onTablesChange={save} />\n```\n\nThe tabs take the theme's colors: the tables sit on its muted surface and the\nshown one is marked with its accent. They switch tables; double-click one, or use its menu, to rename it. The\nmenu also duplicates and deletes the table (deleting asks first and lists the\nlink fields that go with it), and \"Add table\" starts a new one with a Name,\nNotes and Status field. A record of a base has an `id`, and the row adder\ngives a new one its own.\n\nEvery table of the base is a table a link field can point at. A link field\nfrom one table to another gets a field in the other table that links back\n(`fieldProps.inverse` on each names the other), and the two stay in step:\n\n- Linking a deal to an account lists the deal on the account, and the other\n way round. Deleting records takes them out of the links on the other side.\n- Pointing the field at another table moves the field back to that table and\n clears the old links. Turning the field into another type, or deleting it,\n takes the field back with it; the delete asks first and names the lookups,\n rollups and counts that read it, which go with it.\n- Deleting a table deletes the link fields that point at it, and the\n lookups, rollups and counts that read those links.\n\nA rollup of amounts shows as the amounts do (\"$482,000\"). A linked record\nopened from a chip has \"Open in {table}\", which switches to that tab with\nthe record expanded. `onTablesChange` hands over every table after each\nchange to records, fields, views or tables, ready to store.\n\nTo keep the records in a database instead, give each table a `source`: the\nbase loads from it and writes every change back, a link to one record as a\nforeign key and a link to many through a junction table. See\n[Keep a base in a database](./base/data.md).\n\n## Automations\n\nA table's `automations` do things on their own when a record is created,\nchanges, starts matching a condition, is sent with a form or has its button\npressed, or at a scheduled time: update the record, create a record in any\ntable and link it back, show a notice, color the record while it matches, or\nrun an action your app adds. \"Automations\" in the view bar edits them and\nlists every run. See [Automations](./base/automations.md).\n\n## Add a row\n\n`rowAdder` draws \"+ Add row\" under the last row. A click appends a row, scrolls\nto it and starts editing its first editable cell, then fires `onRowAdd` with\nthe row so you can store it.\n\n```ts\nimport type { RowAdderConfig } from '@svgrid/grid'\n\nconst rowAdder: RowAdderConfig<{ status: string }> = {\n label: 'Add task',\n defaults: () => ({ status: 'Todo' }),\n}\n```\n\nWith the grid's `rowDragManaged`, rows drag into a new order by their row\nnumber, but only while nothing sorts or groups them: in a sorted table the\norder is the sort's, so the fields module turns dragging off until the sort is\ncleared.\n\n## Expand a row\n\n`expandRows` (with `showRowNumbers`) makes the row number the row's handle:\non hover it turns into a checkbox that selects the row and an expand button.\nExpand opens the row as a record: every field with its name and type icon,\nits value drawn as the cell draws it, and the same editor the cell uses one\nclick away. A value changed there is written the way a cell edit is, so undo,\nvalidation, `onCellValueChange` and last-modified fields behave the same.\nThe arrows step through the rows in the grid's order. Space on a selected\ncell (not a checkbox) opens its row too.\n\nFields the grid hides are listed under the others, folded, and read-only. Beside\nthe fields is the record's activity: the changes made to it in this session\n(who changed which field to what) and its comments. Comments live in memory\nunless the app keeps them:\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers expandRows editable />\n```\n\n```ts\nimport { setRecordComments } from '@svgrid/enterprise/fields'\n\nsetRecordComments({\n list: (rowId) => comments.filter((c) => c.rowId === rowId),\n add: (rowId, comment) => saveComment(comment),\n})\n```\n\n## Drag to pin columns\n\nThe grid's [`pinSplitter`](./columns/column-pinning.md#drag-to-pin) works over\nfield columns too: drag the divider at the edge of the pinned columns to pin\nmore or fewer. With a `primaryField` it stops at the primary field, which\nstays pinned.\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers pinSplitter primaryField=\"task\" />\n```\n\n## Taller rows\n\nRow height is the grid's `rowHeight`; a view can offer it as short, medium,\ntall and extra tall (34, 56, 88, 128 in the demo above). From 48px the field\ncells use the height: content starts at the top, text wraps to as many lines\nas fit (2 to 6), select pills wrap, long text keeps its line breaks and\nattachment thumbnails grow with the row.\n\n## Summaries at the bottom\n\nWith the grid's `summary` prop on, each field's cell in the footer row picks\nits own summary: a click offers what fits the field (sum, average, median,\nmin, max, range for numbers; checked for a checkbox; earliest, latest and the\nspan for dates; empty, filled, unique and their percentages for every field).\nThe result is written as the field writes its values (`Sum $17,700`,\n`Average 42%`). The choice is kept in `fieldProps.summary` and reported\nthrough `onColumnChange`, so it can be set in the column too:\n\n```ts\n{ field: 'budget', header: 'Budget', fieldType: 'number', fieldProps: { format: 'currency', summary: 'sum' } }\n```\n\n## Grouped records\n\nGrouped by a field (the view bar's Group, the column menu, or `groupBy`), each\ngroup's header shows the field's name over its value, drawn as the cell draws\nit (a select's pill, a person's avatar), the number of records, the summaries\nthe fields picked for that group (\"Budget $4,300\"), and \"+\" to add a record\nthat is already in the group: it gets the group's value, and its parent\ngroups' values, before editing starts.\n\nA single select sorts and groups in the order of its options (\"Q4 2026\"\nbefore \"Q1 2027\" before \"Later\"), not alphabetically. With a filter on, the\ngroup's count and summaries, the record count in the view bar and the footer\ntotals leave out the records the filter hides, whether the group is open or\nclosed.\n\n## Act on selected rows\n\nTick rows with the row header's checkbox (`expandRows`) or the selection\ncolumn, and the grid's [selection bar](./rows/selection-bar.md) acts on all of\nthem: `'editFields'` sets fields on every selected row with each field's own\ncontrol, `'deleteRows'` deletes them after an inline confirm.\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers expandRows\n selectionBar={['selectAll', 'editFields', 'deleteRows']}\n onRowsDelete={(e) => (data = e.data)} />\n```\n\n## Color rows by status\n\nWith `fieldMenu`, a single select's column menu has \"Color rows by this\nfield\" (and \"Stop coloring rows\" on the one in use): the rows take that\nfield's option colors at once, and `onRowColorChange` reports the choice so\nthe app can keep it as `rowColor`.\n\n`rowColor` gives each row a color on its row header: a 3px stripe on the\nleading edge, with the row number left as it is. Color by a select field and\neach row takes its option's color; or give rules, first match wins.\n`target: 'bar'` puts the stripe on the first cell (for grids without row\nnumbers), `target: 'row'` tints the whole row. The row header also gets the status as its title, so the color is\nnever the only signal. Only rendered rows are colored, so it costs nothing at\na million rows.\n\n```ts\nimport type { RowColorConfig } from '@svgrid/grid'\n\ntype Task = { status: string; budget: number }\n\nconst byStatus: RowColorConfig<Task> = { field: 'status' }\nconst byRule: RowColorConfig<Task> = {\n target: 'row',\n rules: [{ when: (row) => row.budget > 2500, color: '#f59e0b', label: 'Over budget' }],\n}\n```\n\n## Create and edit fields\n\n`columnAdder` draws a \"+\" after the last column. It opens the field editor: a\nname, a type (`{ types: [...] }` limits the list) and that type's properties.\nA field left unnamed is named after its type (`Number`, then `Number 2`).\nEvery field column shows its type's icon before the header label.\n`fieldMenu` adds Edit field, Insert left, Insert right, Duplicate field, Hide\nfield and Delete field to every column menu; with a view bar over the grid,\nalso \"Filter by this field\" and \"Group by this field\", which add the condition\nor group and open the bar's panel. The menu's sort items are labeled for the\nfield (\"Sort 1 → 9\", \"Sort A → Z\"). A field's description shows as an info\nmark after its name, read on hover.\n\nChanging a field's type converts its values where they can be (a number typed\nas text stays a number, a comma list becomes multiple-select values, URLs in\ntext become attachments); before applying, the editor says how many cells\nwould be cleared. A select made from other values starts with those values as\nits options.\n\nThe grid keeps no schema. Every change fires an event with the whole column\nlist after the change, as you declared it, and the converted rows when values\nchanged. Store them and the grid stays in step:\n\n```ts\ntype Row = Record<string, unknown>\nlet columns: Record<string, unknown>[] = []\nlet rows: Row[] = []\n\nfunction onFieldChange(e: { columns: Record<string, unknown>[]; data?: Row[] }) {\n columns = e.columns\n if (e.data) rows = e.data\n}\n// <SvGrid {columns} data={rows} columnAdder fieldMenu\n// onColumnAdd={onFieldChange} onColumnChange={onFieldChange} onColumnRemove={onFieldChange} />\n```\n\n## Your own field type\n\n`registerFieldType` adds a type, or replaces a built-in one with the same id.\n`fill` sets up the column; `properties` is what the field editor shows for it;\n`cell` (optional) is a Svelte component that draws the cell and receives\n`{ value, props, row, column }`.\n\n```ts\nimport { registerFieldType } from '@svgrid/enterprise/fields'\n\nregisterFieldType({\n id: 'sku',\n label: 'SKU',\n defaults: { prefix: 'SKU-' },\n properties: [{ key: 'prefix', label: 'Prefix', kind: 'text' }],\n fill: (def, props) => ({\n ...def,\n editorType: def.editorType ?? 'text',\n formatter: def.formatter ?? ((ctx: { value: unknown }) => `${String(props.prefix)}${String(ctx.value ?? '')}`),\n }),\n})\n```\n\n## See also\n\n- [Cell data types](./cells/cell-data-types.md)\n- [Cell components](./cells/cell-components.md)\n- [Conditional formatting](./cells/conditional-formatting.md)\n- [Column menu](./columns/column-menu.md)\n"
5732
+ "markdown": "# Field types\n\nA column can say what it is - a rating, a URL, a single select with colored\noptions, a list of files - with `fieldType`, and set that type's properties\nwith `fieldProps`. The type fills in the editor, the format and the\nalignment, and draws the cell when the type needs a cell of its own (stars,\nlinks, file thumbnails). The same module adds a \"+\" after the last column to\ncreate fields, a \"+ Add row\" line under the last row, status colors on the\nrow header, field actions in the column menu, and a view bar with saved grid,\nKanban, calendar, gallery and form views.\n\n<div data-docs-demo=\"504-project-tracker\" data-height=\"620\"></div>\n\n> **SvGrid Base, part of the Suite edition.** The `fieldType` / `fieldProps`\n> column properties and the `rowAdder`, `rowColor`, `columnAdder`,\n> `fieldMenu`, `expandRows` and `primaryField` props are part of the free\n> `@svgrid/grid` types; what draws them is SvGrid Base\n> (`@svgrid/enterprise/base`, or `@svgrid/enterprise/fields` for the field\n> types alone). Without it a `fieldType` column draws as an ordinary column and\n> the props do nothing. Without a Suite key the grid shows the Enterprise\n> watermark and everything still runs. New here? [Build a project\n> tracker](./base/start.md) first.\n\n## Turn it on\n\n`enableFields()` registers the built-in types for every grid on the page. It is\na separate module: `installEnterprise()` does not load it, so an app that never\ncalls `enableFields()` does not ship it.\n\n```ts\nimport { enableFields } from '@svgrid/enterprise/fields'\n\nenableFields()\n```\n\n## A table with views\n\n`SvBase` is a grid with a view bar over it. Every prop it does not name\ngoes to the grid; `views` are the saved views and `activeView` the one shown.\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, type FieldView } from '@svgrid/enterprise/fields'\n\n let views = $state<FieldView[]>([\n { id: 'all', name: 'All tasks', type: 'grid' },\n { id: 'board', name: 'By status', type: 'kanban', stackBy: 'status' },\n { id: 'due', name: 'Due dates', type: 'calendar', dateField: 'due' },\n { id: 'cards', name: 'Gallery', type: 'gallery', coverField: 'files' },\n { id: 'form', name: 'Request a task', type: 'form' },\n ])\n</script>\n\n<SvBase {data} {columns} bind:views primaryField=\"task\" editable\n showRowNumbers expandRows containerHeight={600} />\n```\n\nA grid, Kanban, calendar, Gantt or gallery view is the grid itself in another\nmode (`board`, `scheduler`, `gantt`, `gallery`), so the filter and the sort\ncarry over; a form view is drawn beside the grid, which stays mounted under\nit. In a board, calendar or gallery the bar's search narrows the records; the\ntext is not saved with the view. The Gantt type is\noffered once the app has enabled the Gantt view; its task table holds the\nprimary field, the two dates and the working days.\n\n`SvBaseViewBar` is the bar on its own, for a page that lays out its own\ngrid:\n\n```svelte\n<SvBaseViewBar {api} bind:views bind:activeView />\n<SvGrid {data} {columns} onApiReady={(a) => (api = a)} />\n```\n\n## The view bar\n\nFrom the left: the view switcher, then Hide fields, Filter, Group, Sort,\nColor and Row height, and at the right the record count and search (the\ngrid's find bar, Ctrl+F). A button with something set says so (\"2 hidden\nfields\", \"Filtered by Status\", \"Sorted by 1 field\") and is tinted. Each\nsetting goes through the grid's own state, so `api.getState()` holds it.\n\n- **Hide fields**: a switch per field, a search, hide all / show all, and\n drag to reorder. The primary field is always shown.\n- **Filter**: conditions on fields (below), joined by \"and\" or \"or\", with\n condition groups one level deep. Each change filters at once.\n- **Group**: up to three fields, each with a direction. Group headers show\n the value as its cell draws it (see [Grouped records](#grouped-records)).\n- **Sort**: fields in order, each with a direction labeled for its type:\n \"1 → 9\" for a number or a date, \"A → Z\" for text, \"☐ → ☑\" for a checkbox.\n- **Color**: none, a single select's option colors, or conditions in order\n with a color each (the first match colors the row, where the `rowColor`\n prop's `target` says; a condition still missing its value colors nothing).\n A view with no color setting shows the `rowColor` prop's colors.\n- **Row height**: short, medium, tall and extra tall (`rowHeights` on\n `SvBase` or `SvBaseViewBar` sets the list).\n\n## Filter conditions\n\nA condition is a field, an operator that fits the field's type and a value in\nthe control the field calls for. A condition without a value yet filters\nnothing. The filter is the grid's advanced filter with its own expression\nkind, `fieldFilter`, so `api.setAdvancedFilter` sets it and a saved view\nkeeps it.\n\n| Field type | Operators |\n|---|---|\n| Text, long text, URL, email, phone, barcode, color, formula, lookup | contains, does not contain, is, is not, is empty, is not empty |\n| Checklist | is complete, is not complete, % done ≥, % done <, has an item containing, is empty, is not empty |\n| Time of day | is, is before, is after, is at or before, is at or after, is empty, is not empty |\n| Number, currency, percent, rating, duration, autonumber, count, rollup | =, ≠, <, >, ≤, ≥, is empty, is not empty |\n| Single select, user | is, is not, is any of, is none of, is empty, is not empty |\n| Multiple select, multiple users | has any of, has all of, is exactly, has none of, is empty, is not empty |\n| Date, created time, last modified time | is, is before, is after, is on or before, is on or after, is within, is empty, is not empty |\n| Checkbox | is checked / unchecked |\n| Attachment | file name contains, is empty, is not empty |\n| Link to another table | contains, does not contain, is, is not (by the records' names), is empty, is not empty |\n\nA date compares days: \"today\", \"tomorrow\", \"one week ago\", \"one month from\nnow\" or an exact date, and \"is within\" takes the past or next week, month or\nyear, or a number of days. A bare `'2026-10-14'` is that day where the user\nis.\n\n```ts\napi.setAdvancedFilter({\n kind: 'fieldFilter',\n conjunction: 'and',\n conditions: [\n { column: 'status', kind: 'select', op: 'isAnyOf', value: ['Todo', 'Blocked'] },\n { column: 'due', kind: 'date', op: 'isWithin', value: { span: 'nextWeek' } },\n ],\n})\n```\n\n## Saved views\n\nA view is a name, a type and the settings it had when it was last left:\n\n| Key | What it holds |\n|---|---|\n| `id`, `name`, `type` | `'grid'`, `'kanban'`, `'calendar'`, `'gantt'`, `'gallery'`, `'chart'` or `'form'` |\n| `state` | the grid's state: sorts, groups, the filter, hidden fields, order, widths, pinned columns |\n| `rowHeight`, `color` | the row height and how rows are colored |\n| `stackBy` | Kanban: the single select or user field the cards stack by |\n| `dateField`, `endField` | calendar and Gantt: the dates a record starts and ends on |\n| `progressField`, `dependencyField`, `zoom` | Gantt: a percent field the bars fill with, a link field to the same table naming what each record depends on, and the zoom it was left at |\n| `coverField` | gallery: the attachment field whose first image is the cover |\n| `chart` | chart: `kind` (`'bar'`, `'barH'`, `'line'`, `'pie'`, `'donut'`), `x` the field to group by, `y` a number field (else a count), `aggregation` (`'sum'` or `'avg'`) |\n| `formFields`, `formTitle`, `formDescription` | form: the fields it asks for and its heading |\n\nThe view switcher creates a view of any type (a Kanban asks what to stack by,\na calendar which date field), renames, duplicates and deletes. A new view\nstarts plain: no filter, sorts or groups, every field shown. Changes to the\nshown view are kept a moment after they are made, and `onViewsChange` reports\nthe list whenever it changes, so the app can store it. A Kanban card moved to\nanother lane, or a calendar record moved to another day, writes the field\nthrough the grid's edit path (undo, validation, `onCellValueChange`); a date\nfield without a time shows as all-day events. A Kanban card draws its fields as their cells do (pills,\navatars, file thumbnails), and \"+ Add a card\" in a lane adds a record already\nin that lane, named by the primary field. Double-click a card (or F2) to open its record. On\nthe calendar, picking a day adds a record on it and opens it with its name\nready to type.\n\nA Kanban stacked by a field draws an \"Uncategorized\" lane only while a record\nhas no value in that field. A calendar view whose `color` is a single select\n(`{ mode: 'field', field: 'stage' }`) colors each event as the record's\noption, with the options above the calendar as a legend that hides and shows\ntheir events.\n\n## Gallery, chart and form views\n\nA gallery draws each record as a card: the cover image, the primary field as\nthe title, and the fields the grid shows, each drawn as its cell draws it. The\ncards follow the filter, the sort and the hidden fields; a click opens the\nrecord. It is the grid's [gallery view](./rows/gallery.md) (`gallery`), set up\nfrom the view: the cover field, the primary field as the title, the shown\nfields as the card's fields.\n\nA chart groups the records the view shows (its filter applies) by one field\nand counts them, or adds up or averages a number field, as a bar, horizontal\nbar, line, pie or donut chart. A single select keeps its options' order and\ncolors, a person and a linked record show by name, a date groups by month, and\nthe values read as the summed field writes them (\"$480,000\"). \"Customize\nchart\" in the view bar changes the kind, the field and the value; the view\nkeeps them as `chart`:\n\n```ts\n{ id: 'pipeline', name: 'Pipeline value by stage', type: 'chart', chart: { kind: 'bar', x: 'stage', y: 'value' } }\n{ id: 'funnel', name: 'Candidates by stage', type: 'chart', chart: { kind: 'donut', x: 'stage' } }\n```\n\nA form asks for the fields a person can fill in (computed fields are left\nout), each with the editor its cell uses, and adds a row the way \"+ Add row\"\ndoes: field defaults, the next autonumber, then what was typed, and\n`onRowAdd`. `SvBaseForm` takes `fields`, `required`, `title`,\n`description` and `onSubmit`; a field's `description` shows under it.\n\n## The primary field\n\n`primaryField` names the field that is the record's name. It is always the\nfirst column and pinned, it cannot be hidden or deleted (the column menu does\nnot offer it, the pin splitter stops at it), and it titles the expanded\nrecord, a gallery card and a calendar event.\n\n```svelte\n<SvGrid {data} {columns} primaryField=\"task\" />\n```\n\n## Declare columns by type\n\n```ts\nimport type { GridColumns } from '@svgrid/grid'\n\ntype Task = { task: string; status: string; tags: string[]; due: string; score: number; budget: number; spec: string }\n\nconst columns: GridColumns<Task> = [\n { field: 'task', header: 'Task', fieldType: 'text' },\n {\n field: 'status',\n header: 'Status',\n fieldType: 'singleSelect',\n fieldProps: { options: [{ value: 'Todo', color: '#64748b' }, { value: 'Done', color: '#16a34a' }] },\n },\n { field: 'tags', header: 'Tags', fieldType: 'multiSelect', fieldProps: { options: [{ value: 'Design' }, { value: 'Docs' }] } },\n { field: 'due', header: 'Due', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } },\n { field: 'score', header: 'Score', fieldType: 'rating' },\n { field: 'budget', header: 'Budget', fieldType: 'number', fieldProps: { format: 'currency', symbol: '€', symbolPosition: 'after', precision: 0 } },\n { field: 'spec', header: 'Spec', fieldType: 'url' },\n]\n```\n\nA property the column sets itself wins over its type:\n`{ fieldType: 'number', align: 'left' }` stays left-aligned.\n\n| Type | `fieldProps` |\n| --- | --- |\n| `text` | `default` |\n| `longText` | `richText` (**bold**, *italic*, `code`, [links](https://svgrid.com), \"- \" lists; drawn as elements, never as HTML) |\n| `attachment` | `accept`, `maxFiles`, `maxSize`, `upload` |\n| `checkbox` | `icon` (`check`, `x`, `star`, `heart`, `thumbsUp`, `flag`, `dot`), `color`, `default` |\n| `singleSelect`, `multiSelect` | `options` (`{ value, label?, color? }[]`, 40 colors in the editor, sort A to Z), `default` |\n| `user` | `multiple`, `default`; the people come from `setFieldUsers` |\n| `date` | `dateFormat` (`local`, `friendly`, `us`, `european`, `iso`), `time`, `timeFormat` (`12hour`, `24hour`), `gmt` (one time zone for everyone), `showTimeZone`, `defaultToday` |\n| `phone`, `email`, `url` | none |\n| `barcode` | none |\n| `checklist` | none; values are `{ id, text, done }[]` |\n| `color` | `default`; values are `'#rrggbb'` |\n| `button` | `label`, `color`, `url` (`{Field name}` filled from the row), or `onClick` set in code |\n| `number` | `format` (`integer`, `decimal`, `currency`, `percent`), `precision` 0 to 8, `step` (the editor's spinner, default 1), `separators` (`local`, `comma-period`, `period-comma`, `space-comma`, `space-period`), `showThousands`, `abbreviation` (`none`, `thousand`, `million`, `billion`; not for percent), `allowNegative`, `default`; currency: `symbol`, `symbolPosition` (`before`, `after`); percent: `showBar`, `points` (values 0 to 100 instead of fractions) |\n| `duration` | `durationFormat` (`h:mm`, `h:mm:ss`, `h:mm:ss.S`, `h:mm:ss.SS`, `h:mm:ss.SSS`); values are seconds, typed as `1:30` or `1h 30m` |\n| `timeOfDay` | `timeFormat` (`12hour`, `24hour`), `showSeconds`, `default`; values are `'HH:MM'` (24 hour), `'HH:MM:SS'` with seconds |\n| `rating` | `max` 1 to 10, `icon` (`star`, `heart`, `thumbsUp`, `flag`, `dot`), `color` |\n| `formula` | `formula`, `result` (`auto`, `number`, `currency`, `percent`, `date`) and that format's options |\n| `createdTime`, `lastModifiedTime` | the date options; last modified also `watch` (`all`, `specific`) and `watchFields` |\n| `createdBy`, `lastModifiedBy` | last modified by: `watch`, `watchFields`; the user comes from `setCurrentUser` |\n| `autoNumber` | none |\n| `link` | `table` (from `registerLinkedTable`), `multiple` |\n| `lookup` | `linkField`, `field` |\n| `rollup` | `linkField`, `field`, `aggregation` (`SUM`, `AVERAGE`, `MIN`, `MAX`, `COUNT`, `COUNTA`, `COUNTALL`, `ARRAYJOIN`, `ARRAYUNIQUE`, `CONCATENATE`, `AND`, `OR`), `precision` |\n| `count` | `linkField` |\n\nA number field has one editor for every format. The box shows the plain\nnumber with the field's decimal character, the currency symbol (before or\nafter) or the percent sign right beside it, and a spinner at the cell's\nedge: its arrows, or Up and Down, add or take away `step` (Shift: ten\ntimes). It reads what people type the way the field writes it: its own\nseparators, a pasted symbol or percent sign, `2.5k`, `3M`, `(120)` for -120.\nEnter commits and moves a row down, Tab a column across. On commit the\nvalue is rounded to the field's precision; text that is not a number, or a\nnegative where the field allows none, keeps the box open and says why under\nthe cell. Pasting `$1,200.50` into the cell is read the same way. Columns\nwith the older `currency` and `percent` field types keep working and open in\nthe field editor as a number in that format.\n\nLong text opens a panel over the cell with room for paragraphs: Enter\nstarts a new line, Ctrl+Enter (Cmd+Enter), Tab or a click outside saves,\nEscape leaves the cell as it was. With rich text on, the panel names the\nmarkup the cell draws.\n\nA duration uses the same editor in its own format: `2:00` in the box,\n`1:30` or `1h 30m` typed, a minute a step (a second when the format shows\nseconds). A date opens with the date written as its cells write it\n(`October 24, 2026` for friendly), and a date without time is stored as the\ncalendar date (`'2026-10-24'`), never moved across a day by a time zone.\n\nA select cell opens a panel over itself: the chosen options as pills (each\nwith a remove button), a search box and the options. Typing filters them; a\nvalue that is not an option yet is offered as \"Add option\", which adds it to\nthe field (with a color, through `onColumnChange`) and picks it. A multiple\nselect stays open to pick more; Backspace in the empty search box removes the\nlast choice. A user field opens the same panel with the people from\n`setFieldUsers`, each with the avatar and name its cells show.\n\nA `default` (or a type's own new-row value: today, the next autonumber, the\ncreated time, the current user) fills the rows the row adder adds. Computed\nand automatic fields are read-only; autonumber and created time give every\nexisting row a value when the field is created.\n\nURL, email and phone cells become links only for the schemes they mean\n(`http(s):`, `mailto:`, `tel:`). A value such as `javascript:alert(1)` stays\ntext.\n\n## Checklists, colors and times of day\n\n<div data-docs-demo=\"715-base-checklist-color-time\" data-height=\"620\"></div>\n\n```ts\nconst columns = [\n { field: 'session', header: 'Session', fieldType: 'text' },\n { field: 'prep', header: 'Prep', fieldType: 'checklist' },\n { field: 'track', header: 'Track', fieldType: 'color' },\n { field: 'starts', header: 'Starts', fieldType: 'timeOfDay', fieldProps: { timeFormat: '12hour' } },\n]\n\nconst row = {\n session: 'Opening keynote',\n prep: [\n { id: 's1', text: 'Slides final', done: true },\n { id: 's2', text: 'Mic check', done: false },\n ],\n track: '#2d7ff9',\n starts: '09:00',\n}\n```\n\nA **checklist** holds to-do items in order, each `{ id, text, done }`. The\ncell shows `1/2` and a bar, green once every item is done. A click on them\n(or Enter, a double-click, a typed key, which starts a new item) opens a\npanel over the cell; a click beside them only selects the cell. In the panel, tick\nan item, rename it in place, drag it by its handle or move it with Alt+Up\nand Alt+Down, delete it, and add one in the box at the bottom (Enter adds\nand stays there). Ctrl+Enter, Tab, Done or a click outside saves; Escape\nleaves the cell as it was. It sorts by the share done, and groups into Not\nstarted, In progress and Done, with empty checklists last. Those groups have\nno \"+\", and Insert record above or below leaves the new record's checklist\nempty: a copy would duplicate someone's to-dos. A column of your own groups\nby what its value amounts to with `groupValue: (value) => key`.\n\nAs text a checklist is one item per line, `[x] Done item` or `[ ] Open item`.\nThat is what a type change to long text, an export and a lookup write, and\na paste, a CSV import or a type change from text read: a line with no mark\nis an open item, and `- [x]` (a Markdown task list) works too. A copy\n(Ctrl+C) puts the items on one line, `[x] Slides final [ ] Mic check`,\nbecause a paste splits rows at line breaks; the field reads several marks\non one line as several items.\n\nA **color** is stored lower case as `'#rrggbb'`. The cell shows a swatch and\nthe code. The editor offers the 40 option colors (Arrow keys walk them) and\na box for a code. A paste or the box reads `#rgb`, `#rrggbb`, `2d7ff9`\n(without `#` when the code has a digit), `rgb(45, 127, 249)` and these CSS\nnames: black, white, gray, grey, silver, red, maroon, orange, yellow, olive,\nlime, green, teal, cyan, aqua, blue, navy, purple, magenta, fuchsia, pink,\nbrown, gold, indigo, violet. Anything else (another name, `hsl()`, a color\nwith alpha) is refused: a paste keeps the old value and the editor says so.\nColors sort around the color wheel from red, grays last, and filter as text.\n\nA **time of day** has no date. It is stored as `'HH:MM'` on a 24-hour clock\n(`'HH:MM:SS'` when the field shows seconds) rather than seconds since\nmidnight: it reads the same in JSON, a CSV and a SQL `time` column, sorts in\ntime order as text, and cannot be mistaken for a `duration`, which is\nseconds. `timeFormat` only changes what the cell shows (`2:05 PM` or\n`14:05`). Typed or pasted, it reads `14:05`, `9:30 am`, `9.30 p.m.`, `2pm`,\n`0930`, `noon` and `midnight`; without `showSeconds` the seconds are\ndropped. In the editor Up and Down move by 15 minutes (Shift: an hour). A\nfilter compares to the minute (\"is 9:30\" holds 9:30:15) unless its value\nnames seconds.\n\nA CSV import gives a column of times (`9:00 am`, `22:30`) a time of day\nfield, a column of `#` codes a color field, and a column whose every value\nstarts with `[x]` or `[ ]` a checklist. Changing a duration to a time of day\nreads its seconds as the time since midnight; a date with a time gives its\nlocal time. In SQL (`baseToSql`) a checklist is `jsonb` and a time of day\n`time`.\n\n## Attachments\n\nAn attachment cell holds an array of files:\n\n```ts\nimport type { Attachment } from '@svgrid/enterprise/fields'\n\nconst files: Attachment[] = [\n { id: 'a1', url: 'https://cdn.example.com/plan.png', name: 'plan.png', type: 'image/png', size: 48213 },\n { id: 'a2', url: 'https://cdn.example.com/spec.pdf', name: 'spec.pdf', type: 'application/pdf' },\n]\n```\n\nImages show as thumbnails, other files as chips, as many as the column width\nholds and then \"+N\". Enter or a double click opens the dialog: add files with\nthe picker, by dropping them, by pasting them or by URL; remove, reorder (drag,\nor Alt+Left / Alt+Right) and preview (images and PDFs inline). Files dropped on\nthe cell itself are added without the dialog. Export writes the file names. A\ncopy in `<SvBase>` writes their URLs, and pasting text adds one attachment per\nhttp(s) URL in it, so a copied cell pastes as the same files. In a base, people\nand links copy as names too, and a pasted name finds its person or record.\n\nUploading is yours to decide. Set one uploader for the app, or one per column\nin `fieldProps.upload`; it gets the file, the row and an abort signal, reports\nprogress, and returns the attachment. A failed upload stays in the dialog with\nRetry.\n\n```ts\nimport { setAttachmentUploader } from '@svgrid/enterprise/fields'\n\nsetAttachmentUploader(async (file, { signal, onProgress }) => {\n const res = await fetch(`/api/upload?name=${encodeURIComponent(file.name)}`, { method: 'PUT', body: file, signal })\n if (!res.ok) throw new Error(`Upload failed (${res.status})`)\n onProgress(1)\n const { url } = (await res.json()) as { url: string }\n return { id: url, url, name: file.name, type: file.type, size: file.size }\n})\n```\n\nWith no uploader, added files stay in the page as `blob:` URLs and are gone\non reload. Thumbnails use `http(s):`, `blob:` and raster `data:image` URLs\nonly.\n\n## People, linked tables and formulas\n\nUser fields choose from the people you list; created by and last modified by\nwrite whoever you say is signed in. Link fields point at rows of a table you\nregister; lookup, rollup and count read through a link field.\n\n```ts\nimport { registerLinkedTable, setCurrentUser, setFieldUsers } from '@svgrid/enterprise/fields'\n\nsetFieldUsers([\n { id: 'u1', name: 'Ana Ruiz' },\n { id: 'u2', name: 'Ben Okafor', avatarUrl: 'https://cdn.example.com/ben.png' },\n])\nsetCurrentUser({ id: 'u1', name: 'Ana Ruiz' })\n\nregisterLinkedTable({\n id: 'milestones',\n name: 'Milestones',\n primaryField: 'name',\n rows: () => [{ id: 'm1', name: 'Beta', date: '2026-10-31' }],\n // A field's type, when it has one, is how a lookup shows it.\n fields: [{ field: 'name', header: 'Name' }, { field: 'date', header: 'Date', fieldType: 'date', fieldProps: { dateFormat: 'friendly' } }],\n})\n\nconst columns = [\n { field: 'milestone', header: 'Milestone', fieldType: 'link', fieldProps: { table: 'milestones', multiple: false } },\n { field: 'milestoneDate', header: 'Milestone date', fieldType: 'lookup', fieldProps: { linkField: 'milestone', field: 'date' } },\n { field: 'total', header: 'Total', fieldType: 'formula', fieldProps: { formula: '{Qty} * {Unit price}', result: 'currency', precision: 2 } },\n]\n```\n\nA link cell shows one chip per linked record. A click on a chip opens that\nrecord (its fields, read-only: the table is the app's), and resting the\npointer on one previews it. A table with a `create` function lets the link\npicker add a record: a search that names no record offers \"+ Create\" for it,\npicked at once.\n\n```ts\nlet milestones = [{ id: 'm1', name: 'Beta', date: '2026-10-31' }]\nregisterLinkedTable({\n id: 'milestones',\n name: 'Milestones',\n primaryField: 'name',\n rows: () => milestones,\n create: (name) => {\n const row = { id: `m${milestones.length + 1}`, name, date: '' }\n milestones = [...milestones, row]\n return row\n },\n})\n```\n\nA formula refers to fields by name in braces and supports `+ - * /`, `&` to\njoin text, comparisons, and functions such as `IF`, `SWITCH`, `AND`, `OR`,\n`CONCATENATE`, `LEFT`, `ROUND`, `SUM`, `DATEADD` and `DATETIME_DIFF`\n(the editor lists them all). It is parsed into functions once, never\nevaluated as code; a formula that does not compile shows `#ERROR` in its\ncells and its message in the field editor.\n\n## Tables and links\n\n`<SvBase tables>` holds several tables, one tab each. A table is its records,\nits fields and its views; `id` is what link fields name.\n\n```ts\nimport { SvBase, type BaseTable } from '@svgrid/enterprise/base'\n\nlet tables: BaseTable[] = [\n {\n id: 'deals', name: 'Deals', primaryField: 'deal', data: deals,\n columns: [\n { field: 'deal', header: 'Deal', fieldType: 'text' },\n { field: 'account', header: 'Account', fieldType: 'link', fieldProps: { table: 'accounts', multiple: false, inverse: 'deals' } },\n ],\n views: [{ id: 'all', name: 'All deals', type: 'grid' }],\n },\n {\n id: 'accounts', name: 'Accounts', primaryField: 'name', data: accounts,\n columns: [\n { field: 'name', header: 'Name', fieldType: 'text' },\n { field: 'deals', header: 'Deals', fieldType: 'link', fieldProps: { table: 'deals', inverse: 'account' } },\n { field: 'pipeline', header: 'Pipeline', fieldType: 'rollup', fieldProps: { linkField: 'deals', field: 'value', aggregation: 'SUM' } },\n ],\n },\n]\n```\n\n```svelte\n<SvBase bind:tables editable columnAdder fieldMenu onTablesChange={save} />\n```\n\nThe tabs take the theme's colors: the tables sit on its muted surface and the\nshown one is marked with its accent. They switch tables; double-click one, or use its menu, to rename it. The\nmenu also duplicates and deletes the table (deleting asks first and lists the\nlink fields that go with it), and \"Add table\" starts a new one with a Name,\nNotes and Status field. A record of a base has an `id`, and the row adder\ngives a new one its own.\n\nEvery table of the base is a table a link field can point at. A link field\nfrom one table to another gets a field in the other table that links back\n(`fieldProps.inverse` on each names the other), and the two stay in step:\n\n- Linking a deal to an account lists the deal on the account, and the other\n way round. Deleting records takes them out of the links on the other side.\n- Pointing the field at another table moves the field back to that table and\n clears the old links. Turning the field into another type, or deleting it,\n takes the field back with it; the delete asks first and names the lookups,\n rollups and counts that read it, which go with it.\n- Deleting a table deletes the link fields that point at it, and the\n lookups, rollups and counts that read those links.\n\nA rollup of amounts shows as the amounts do (\"$482,000\"). A linked record\nopened from a chip has \"Open in {table}\", which switches to that tab with\nthe record expanded. `onTablesChange` hands over every table after each\nchange to records, fields, views or tables, ready to store.\n\nTo keep the records in a database instead, give each table a `source`: the\nbase loads from it and writes every change back, a link to one record as a\nforeign key and a link to many through a junction table. See\n[Keep a base in a database](./base/data.md).\n\n## Automations\n\nA table's `automations` do things on their own when a record is created,\nchanges, starts matching a condition, is sent with a form or has its button\npressed, or at a scheduled time: update the record, create a record in any\ntable and link it back, show a notice, color the record while it matches, or\nrun an action your app adds. \"Automations\" in the view bar edits them and\nlists every run. See [Automations](./base/automations.md).\n\n## Add a row\n\n`rowAdder` draws \"+ Add row\" under the last row. A click appends a row, scrolls\nto it and starts editing its first editable cell, then fires `onRowAdd` with\nthe row so you can store it.\n\n```ts\nimport type { RowAdderConfig } from '@svgrid/grid'\n\nconst rowAdder: RowAdderConfig<{ status: string }> = {\n label: 'Add task',\n defaults: () => ({ status: 'Todo' }),\n}\n```\n\nWith the grid's `rowDragManaged`, rows drag into a new order by their row\nnumber, but only while nothing sorts or groups them: in a sorted table the\norder is the sort's, so the fields module turns dragging off until the sort is\ncleared.\n\n## Expand a row\n\n`expandRows` (with `showRowNumbers`) makes the row number the row's handle:\non hover it turns into a checkbox that selects the row and an expand button.\nExpand opens the row as a record: every field with its name and type icon,\nits value drawn as the cell draws it, and the same editor the cell uses one\nclick away. A value changed there is written the way a cell edit is, so undo,\nvalidation, `onCellValueChange` and last-modified fields behave the same.\nThe arrows step through the rows in the grid's order. Space on a selected\ncell (not a checkbox) opens its row too.\n\nFields the grid hides are listed under the others, folded, and read-only. Beside\nthe fields is the record's activity: the changes made to it in this session\n(who changed which field to what) and its comments. Comments live in memory\nunless the app keeps them:\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers expandRows editable />\n```\n\n```ts\nimport { setRecordComments } from '@svgrid/enterprise/fields'\n\nsetRecordComments({\n list: (rowId) => comments.filter((c) => c.rowId === rowId),\n add: (rowId, comment) => saveComment(comment),\n})\n```\n\n## Drag to pin columns\n\nThe grid's [`pinSplitter`](./columns/column-pinning.md#drag-to-pin) works over\nfield columns too: drag the divider at the edge of the pinned columns to pin\nmore or fewer. With a `primaryField` it stops at the primary field, which\nstays pinned.\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers pinSplitter primaryField=\"task\" />\n```\n\n## Taller rows\n\nRow height is the grid's `rowHeight`; a view can offer it as short, medium,\ntall and extra tall (34, 56, 88, 128 in the demo above). From 48px the field\ncells use the height: content starts at the top, text wraps to as many lines\nas fit (2 to 6), select pills wrap, long text keeps its line breaks and\nattachment thumbnails grow with the row.\n\n## Summaries at the bottom\n\nWith the grid's `summary` prop on, each field's cell in the footer row picks\nits own summary: a click offers what fits the field (sum, average, median,\nmin, max, range for numbers; checked for a checkbox; earliest, latest and the\nspan for dates; empty, filled, unique and their percentages for every field).\nThe result is written as the field writes its values (`Sum $17,700`,\n`Average 42%`). The choice is kept in `fieldProps.summary` and reported\nthrough `onColumnChange`, so it can be set in the column too:\n\n```ts\n{ field: 'budget', header: 'Budget', fieldType: 'number', fieldProps: { format: 'currency', summary: 'sum' } }\n```\n\n## Grouped records\n\nGrouped by a field (the view bar's Group, the column menu, or `groupBy`), each\ngroup's header shows the field's name over its value, drawn as the cell draws\nit (a select's pill, a person's avatar), the number of records, the summaries\nthe fields picked for that group (\"Budget $4,300\"), and \"+\" to add a record\nthat is already in the group: it gets the group's value, and its parent\ngroups' values, before editing starts.\n\nA single select sorts and groups in the order of its options (\"Q4 2026\"\nbefore \"Q1 2027\" before \"Later\"), not alphabetically. With a filter on, the\ngroup's count and summaries, the record count in the view bar and the footer\ntotals leave out the records the filter hides, whether the group is open or\nclosed.\n\n## Act on selected rows\n\nTick rows with the row header's checkbox (`expandRows`) or the selection\ncolumn, and the grid's [selection bar](./rows/selection-bar.md) acts on all of\nthem: `'editFields'` sets fields on every selected row with each field's own\ncontrol, `'deleteRows'` deletes them after an inline confirm.\n\n```svelte\n<SvGrid {data} {columns} showRowNumbers expandRows\n selectionBar={['selectAll', 'editFields', 'deleteRows']}\n onRowsDelete={(e) => (data = e.data)} />\n```\n\n## Color rows by status\n\nWith `fieldMenu`, a single select's column menu has \"Color rows by this\nfield\" (and \"Stop coloring rows\" on the one in use): the rows take that\nfield's option colors at once, and `onRowColorChange` reports the choice so\nthe app can keep it as `rowColor`.\n\n`rowColor` gives each row a color on its row header: a 3px stripe on the\nleading edge, with the row number left as it is. Color by a select field and\neach row takes its option's color; or give rules, first match wins.\n`target: 'bar'` puts the stripe on the first cell (for grids without row\nnumbers), `target: 'row'` tints the whole row. The row header also gets the status as its title, so the color is\nnever the only signal. Only rendered rows are colored, so it costs nothing at\na million rows.\n\n```ts\nimport type { RowColorConfig } from '@svgrid/grid'\n\ntype Task = { status: string; budget: number }\n\nconst byStatus: RowColorConfig<Task> = { field: 'status' }\nconst byRule: RowColorConfig<Task> = {\n target: 'row',\n rules: [{ when: (row) => row.budget > 2500, color: '#f59e0b', label: 'Over budget' }],\n}\n```\n\n## Create and edit fields\n\n`columnAdder` draws a \"+\" after the last column. It opens the field editor: a\nname, a type (`{ types: [...] }` limits the list) and that type's properties.\nA field left unnamed is named after its type (`Number`, then `Number 2`).\nEvery field column shows its type's icon before the header label.\n`fieldMenu` adds Edit field, Insert left, Insert right, Duplicate field, Hide\nfield and Delete field to every column menu; with a view bar over the grid,\nalso \"Filter by this field\" and \"Group by this field\", which add the condition\nor group and open the bar's panel. The menu's sort items are labeled for the\nfield (\"Sort 1 → 9\", \"Sort A → Z\"). A field's description shows as an info\nmark after its name, read on hover.\n\nChanging a field's type converts its values where they can be (a number typed\nas text stays a number, a comma list becomes multiple-select values, URLs in\ntext become attachments); before applying, the editor says how many cells\nwould be cleared. A select made from other values starts with those values as\nits options.\n\nThe grid keeps no schema. Every change fires an event with the whole column\nlist after the change, as you declared it, and the converted rows when values\nchanged. Store them and the grid stays in step:\n\n```ts\ntype Row = Record<string, unknown>\nlet columns: Record<string, unknown>[] = []\nlet rows: Row[] = []\n\nfunction onFieldChange(e: { columns: Record<string, unknown>[]; data?: Row[] }) {\n columns = e.columns\n if (e.data) rows = e.data\n}\n// <SvGrid {columns} data={rows} columnAdder fieldMenu\n// onColumnAdd={onFieldChange} onColumnChange={onFieldChange} onColumnRemove={onFieldChange} />\n```\n\n## Your own field type\n\n`registerFieldType` adds a type, or replaces a built-in one with the same id.\n`fill` sets up the column; `properties` is what the field editor shows for it;\n`cell` (optional) is a Svelte component that draws the cell and receives\n`{ value, props, row, column }`.\n\n```ts\nimport { registerFieldType } from '@svgrid/enterprise/fields'\n\nregisterFieldType({\n id: 'sku',\n label: 'SKU',\n defaults: { prefix: 'SKU-' },\n properties: [{ key: 'prefix', label: 'Prefix', kind: 'text' }],\n fill: (def, props) => ({\n ...def,\n editorType: def.editorType ?? 'text',\n formatter: def.formatter ?? ((ctx: { value: unknown }) => `${String(props.prefix)}${String(ctx.value ?? '')}`),\n }),\n})\n```\n\n## See also\n\n- [Cell data types](./cells/cell-data-types.md)\n- [Cell components](./cells/cell-components.md)\n- [Conditional formatting](./cells/conditional-formatting.md)\n- [Column menu](./columns/column-menu.md)\n"
5590
5733
  },
5591
5734
  {
5592
5735
  "slug": "help/figma",
@@ -5880,14 +6023,14 @@ export const docs = [
5880
6023
  "path": "docs/help/migrating-from-ag-grid.md",
5881
6024
  "title": "Migrating from AG Grid to SvGrid",
5882
6025
  "section": "Help",
5883
- "markdown": "\n# Migrating from AG Grid to SvGrid\n\nIf you tried AG Grid on a Svelte 5 project - via `ag-grid-svelte`, the\nold `ag-grid-community/svelte`, or a hand-rolled wrapper - you probably\nhit the same friction everyone hits: the bridge between AG Grid's\nReact/Angular-first API and Svelte 5 runes is brittle, the bundle is\nheavy, and the Enterprise pricing only makes sense at scale.\n\n<!-- facts:start ag-grid -->\n> **Facts, checked 12 Sep 2026.** `ag-grid-community` 36.1.0, MIT, last published 5 Aug 2026, 12,400,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `ag-grid-community` 36.1.0 317.5 KB JS, no separate stylesheet (measured 12 Sep 2026). AG Grid pricing, as its site states it: AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer (https://www.ag-grid.com/license-pricing/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/).\n<!-- facts:end -->\n\nThis page is a 30-minute migration recipe from AG Grid to SvGrid. It\ncovers what maps 1:1, what's different by design, and what you'll lose.\nWe tell you when **not** to switch at the bottom.\n\n## TL;DR\n\n| | AG Grid Community | AG Grid Enterprise | SvGrid Community | @svgrid/enterprise |\n| --- | --- | --- | --- | --- |\n| **Licence** | MIT | Commercial, per developer (the price is in the facts box above) | **MIT** | $599/dev/yr (grid) or $999/dev/yr (grid + spreadsheet + Studio) |\n| **Svelte 5 native** | No (community-built integration) | No (community-built integration) | Yes | Yes |\n| **Bundle (gzipped)** | measured, in the facts box above | not measured (licence) | measured, in the facts box above | lazy-loaded subpaths |\n| **Sorting / filtering** | Yes | Yes | Yes | (in Community) |\n| **Row grouping + aggregation** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Master/detail, tree, range select** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Set filter / Excel-style filter menu** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Server-side data, flat (infinite row model)** | Yes | Yes | Yes (free) | (in Community) |\n| **Server-side row model (grouping, tree, pivot, transactions, selection)** | No (Enterprise) | Yes | No | Yes |\n| **Integrated charts** | No (Enterprise) | Yes, AG Charts | Yes (free) | (in Community) |\n| **CSV export** | Yes (API) | Yes | Yes, with TSV and JSON | (in Community) |\n| **Excel export** | No | Yes | No | Yes |\n| **PDF / styled-HTML export, print** | No | No | No | Yes |\n| **Pivot tables** | No | Yes | No | Yes |\n| **MCP server for AI assistants** | Yes, `ag-mcp` | Yes | Yes, `@svgrid/mcp` | (in Community) |\n| **In-grid AI helpers** | No | No | Yes (bring your own model) | (in Community) |\n\n**SvGrid Community gives you most of what AG Grid sells as Enterprise for\nfree**, and `@svgrid/enterprise` adds Excel, PDF and print output, import,\npivot tables and the server-side row model per developer per year. Compare what each paid tier adds\nbefore comparing prices; both are in the facts box. The trade-offs are\nSvelte-only and a much smaller ecosystem. Every AG Grid cell above follows\nag-grid.com's own pages; the dated list is on the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page.\n\n## Mental model - what changes\n\nAG Grid is one big object you configure declaratively. SvGrid is a\n**headless engine** (`createSvGrid`) with an optional **render\ncomponent** (`<SvGrid>`) on top - the same split TanStack Table made\npopular. You can use either layer; most projects use the render\ncomponent.\n\nEvery example below runs against this setup:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature, type ColumnDef } from '@svgrid/grid'\n\n type Row = { id: number; make: string; model: string; price: number }\n\n const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n\n let rows = $state<Row[]>([\n { id: 1, make: 'Toyota', model: 'Celica', price: 35000 },\n { id: 2, make: 'Ford', model: 'Mondeo', price: 32000 },\n { id: 3, make: 'Porsche', model: 'Boxster', price: 72000 },\n ])\n const data = rows\n\n const columns: ColumnDef<typeof features, Row>[] = [\n { field: 'make', header: 'Make' },\n { field: 'model', header: 'Model' },\n { field: 'price', header: 'Price', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte\n<!-- AG Grid (via a Svelte wrapper) -->\n<AgGridSvelte\n gridOptions={{\n rowData: rows,\n columnDefs: columns,\n onGridReady: (params) => (gridApi = params.api),\n }}\n/>\n\n<!-- SvGrid -->\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(api) => (gridApi = api)}\n/>\n```\n\nThree things to note:\n\n1. **No giant `gridOptions` blob.** Each capability is a top-level prop.\n2. **Features are opt-in.** You pass a `features` object built with\n `tableFeatures({...})` - only the features you list ship JS.\n3. **`onApiReady`** gives you a typed `SvGridApi` that is roughly the\n AG Grid `gridApi` equivalent (see the API-mapping table below).\n\n## Column definitions - direct translation\n\nThe shapes are similar enough that you can usually translate by hand\nwithout thinking too hard.\n\n```ts\n// AG Grid\nconst columnDefs: ColDef[] = [\n { field: 'name', headerName: 'Name', sortable: true, filter: true, width: 200 },\n { field: 'price', headerName: 'Price', type: 'numericColumn',\n valueFormatter: ({ value }) => `$${value.toFixed(2)}` },\n { field: 'date', headerName: 'Date',\n valueGetter: ({ data }) => new Date(data.date).toISOString().slice(0, 10) },\n { field: 'status', headerName: 'Status',\n cellRenderer: StatusCellRenderer,\n cellRendererParams: { onChange: handleStatusChange } },\n]\n```\n\n```ts\n// SvGrid\nimport { renderComponent, type ColumnDef } from '@svgrid/grid'\nimport StatusCell from './StatusCell.svelte'\n\nconst columns: ColumnDef<typeof features, Row>[] = [\n { field: 'name', header: 'Name', width: 200 }, // sortable + filterable by default\n { field: 'price', header: 'Price',\n format: { type: 'currency', currency: 'USD' } },\n { field: 'date', header: 'Date',\n format: { type: 'date', pattern: 'y-m-d' } },\n { field: 'status', header: 'Status',\n cell: renderComponent(StatusCell, (ctx) => ({\n value: ctx.getValue(),\n onChange: handleStatusChange,\n })),\n },\n]\n```\n\n### Property mapping\n\n| AG Grid | SvGrid | Notes |\n| --- | --- | --- |\n| `field` | `field` | Same. |\n| `headerName` | `header` | Accepts a string or a snippet/component. |\n| `width` | `width` | Same. |\n| `minWidth` / `maxWidth` | `minWidth` / `maxWidth` | Same. |\n| `sortable: true` | (default) | Sorting is on when `rowSortingFeature` is registered. |\n| `filter: true` | (default) | Filtering is on when `columnFilteringFeature` is registered. |\n| `valueFormatter` | `format: { ... }` | Built-in types: `number`, `currency`, `percent`, `date`. For custom, use `cell`. |\n| `valueGetter` | `fieldFn` | Returns the value for sorting/filtering. |\n| `cellRenderer` + `cellRendererParams` | `cell: renderComponent(C, ctx => props)` | One call, type-checked. |\n| `cellEditor: 'agTextCellEditor'` | `editorType: 'text'` | Built-in: `text`, `number`, `checkbox`, `date`. |\n| `editable: true` | `enableInlineEditing` prop on `<SvGrid>` | Per-grid, not per-column. (Per-column control on the roadmap.) |\n| `pinned: 'left'` / `'right'` | Right-click column menu → Pin | Set programmatically via the api. |\n| `rowGroup: true` | Via `setGroupBy([colId])` | See Grouping below. |\n| `aggFunc: 'sum'` | `aggregate: 'sum'` | Built-in: `sum`, `avg`, `min`, `max`, `count`. |\n\n## Feature registration - the one new thing\n\nAG Grid auto-enables most features; you turn them off. SvGrid is the\nopposite - features are opt-in. The result is a smaller bundle.\n\n```ts\nimport {\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n columnGroupingFeature,\n rowExpandingFeature,\n rowPaginationFeature,\n rowSelectionFeature,\n} from '@svgrid/grid'\n\nconst features = tableFeatures({\n rowSortingFeature,\n columnFilteringFeature,\n rowSelectionFeature,\n // omit any you don't need - their code won't ship\n})\n```\n\nPass `features` to `<SvGrid>` once. From then on the grid behaves like\nAG Grid's `enableSorting`, `enableFilter`, `rowSelection`, etc. are all\non for the registered features.\n\n## API mapping (`gridApi` → `SvGridApi`)\n\nYou get the SvGrid API from `onApiReady` (equivalent to AG Grid's\n`onGridReady`).\n\n| AG Grid `gridApi.X()` | SvGrid `api.X()` |\n| --- | --- |\n| `setRowData(rows)` | (declarative - just update `data` prop) |\n| `addRow(row)` / `applyTransaction({ add: [row] })` | `api.addRow(row)` / `api.addRows(rows)` |\n| `applyTransaction({ remove: [row] })` | `api.removeRow(rowIndex)` |\n| `getValue(colId, rowNode)` | `api.getCellValue(rowIndex, columnId)` |\n| `setValue(...)` | `api.setCellValue(rowIndex, columnId, value)` |\n| `setColumnVisible(colId, visible)` | `api.setColumnVisible(columnId, visible)` |\n| `getSortModel()` / `setSortModel()` | `api.setSort(columnId, 'asc'\\|'desc'\\|null)` |\n| `setFilterModel({...})` | `api.setFilter(columnId, { operator, value })` |\n| `getDisplayedRowAtIndex(i)` / `forEachNodeAfterFilterAndSort(...)` | `api.getDisplayedRows()` |\n| `getModel()` (raw rows) | `api.getData()` |\n\n## Common patterns\n\n### Sorting + filtering + pagination (the 80% case)\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n } from '@svgrid/grid'\n\n const features = tableFeatures({\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n })\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showPagination\n showColumnFilters\n/>\n```\n\nAG Grid equivalent: `gridOptions: { defaultColDef: { sortable: true, filter: true }, pagination: true }`.\n\n### Cell editing with persistence\n\n```svelte\n<script lang=\"ts\">\n function onCellValueChange(e: { rowIndex: number; columnId: string; value: unknown }) {\n // Persist however you like (fetch to backend, optimistic local update, etc.)\n console.log('cell changed', e)\n }\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n enableInlineEditing\n onCellValueChange={onCellValueChange}\n/>\n```\n\nAG Grid equivalent: `onCellValueChanged: ({ data, colDef, newValue, oldValue }) => ...`.\nSvGrid's event payload is column-id + row-index based rather than node-based; the row data is yours\nto mutate (or not) on the `rows` array you passed in.\n\n### Grouping + aggregation\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid,\n tableFeatures,\n columnGroupingFeature,\n rowSortingFeature,\n rowExpandingFeature,\n } from '@svgrid/grid'\n\n const features = tableFeatures({\n rowSortingFeature,\n columnGroupingFeature,\n rowExpandingFeature,\n })\n\n const columns = [\n { field: 'department', header: 'Department' },\n { field: 'team', header: 'Team' },\n { field: 'salary', header: 'Salary', aggregate: 'sum',\n format: { type: 'currency', currency: 'USD' } },\n ]\n\n function setGroup(api) {\n api.setGroupBy(['department', 'team'])\n }\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showGroupingControls\n onApiReady={setGroup}\n/>\n```\n\nAG Grid Enterprise's `rowGroupPanelShow: 'always'` + `aggFunc: 'sum'` translates 1:1.\n\n### Master / detail\n\nAG Grid Enterprise feature; **free in SvGrid Community**. See\n[demo 08](https://svgrid.com/demos/08-tree-and-master-detail/) for the exact pattern.\n\n### Server-side data\n\nAG Grid's Infinite Row Model (Community) and Server-Side Row Model\n(Enterprise) both take an `IServerSideDatasource` with a `getRows(params)`\nthat answers through `params.success({ rowData, rowCount })`. SvGrid has one\n`ServerDataSource` whose `getRows(request)` returns `{ rows, rowCount }`,\nand two controllers over it: `createServerDataSource` (free: paging or\ninfinite block scroll, sort, filter, CRUD) and `createServerRowModel`\n(Enterprise: lazy grouping, tree, pivot, transactions, selection). Both\nmount through one prop, `<SvGrid rowModel={ctl} />`.\n\nAn existing datasource written for AG Grid keeps working behind one call:\n\n```ts\nimport { adaptCallbackDatasource, createServerRowModel } from '@svgrid/enterprise'\n\nconst ctl = createServerRowModel(adaptCallbackDatasource(myServerSideDatasource), {\n groupBy: ['country'],\n aggregations: [{ col: 'amount', fn: 'sum' }],\n})\n```\n\n`adaptCallbackDatasource` maps the request both ways (`rowGroupCols` ->\n`groupBy`, `valueCols` -> `aggregations`, `pivotCols` -> `pivotBy`, the\nsort and filter models, `context`, `parentNode`) and turns `success` /\n`fail` into a resolved or rejected promise.\n\nMore often the datasource is a thin `fetch` and the real investment is the\nendpoint behind it - a Java or Node service that parses AG Grid's\n`IServerSideGetRowsRequest` JSON. That endpoint stays as it is: post\n`toCallbackRequest(request)` and read the answer back.\n\n```ts\nimport { toCallbackRequest } from '@svgrid/enterprise'\n\nconst source = {\n async getRows(request) {\n const res = await fetch('/api/sales', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(toCallbackRequest(request)),\n })\n const { rowData, rowCount, pivotResultFields } = await res.json()\n return { rows: rowData, rowCount: rowCount ?? -1, pivotResultFields }\n },\n}\n```\n\n`fromCallbackRequest` is the other direction, for a SvelteKit endpoint that\nhas to keep serving an AG Grid client during the switch. A saved selection\nor a bulk endpoint written against `getServerSideSelectionState()` keeps\nits shape the same way: `toCallbackSelectionState(ctl.getSelectionState())`\nproduces `{ selectAll, toggledNodes }` (or the `nodeId` /\n`selectAllChildren` / `toggledNodes` tree), `ctl.setSelectionState` takes\nthat shape as it is when your group node ids are the group keys, and\n`fromCallbackSelectionState(state, { groupKey, isGroup })` maps them when\na `getRowId` gave group rows ids of their own. Option by option:\n\n| AG Grid | SvGrid |\n| --- | --- |\n| `rowModelType: 'infinite'` + `datasource` | `createServerDataSource(source, { mode: 'infinite' })` + `rowModel={ctl}` |\n| `rowModelType: 'serverSide'` + `serverSideDatasource` | `createServerRowModel(source, options)` + `rowModel={ctl}` |\n| `getRows(params)` + `params.success({ rowData, rowCount })` / `params.fail()` | `getRows(request)` returning `{ rows, rowCount }` / throwing |\n| `cacheBlockSize`, `maxBlocksInCache`, `maxConcurrentDatasourceRequests`, `blockLoadDebounceMillis` | `blockSize`, `maxBlocksInCache`, `maxConcurrentRequests`, `blockLoadDebounceMs` |\n| `infiniteInitialRowCount` / `serverSideInitialRowCount` | `initialRowCount` |\n| `rowCount: -1` (unknown) | `rowCount: -1` |\n| `refreshInfiniteCache()` / `purgeInfiniteCache()` | `ctl.refresh()` / `ctl.purge()` |\n| `request.rowGroupCols`, `groupKeys`, `valueCols`, `pivotCols`, `pivotMode` | `request.groupBy`, `groupKeys`, `aggregations`, `pivotBy`, `pivotMode` |\n| `getChildCount(data)` | `childCount: (row) => row.childCount` |\n| `isServerSideGroupOpenByDefault` | `isGroupOpenByDefault(route, row)` |\n| `getServerSideGroupLevelParams` | `levelParams(level, route)` |\n| `isServerSideGroup` / `getServerSideGroupKey` (tree) | `treeData: true` + `hasChildren` / `getRowId` |\n| `grandTotalRow` / `groupTotalRow` | `grandTotalRow` / `groupFooters` |\n| `refreshServerSide({ route, purge })` / `retryServerSideLoads()` | `ctl.refresh({ route, purge })` / `ctl.retryLoads()` |\n| `applyServerSideTransaction` / `applyServerSideTransactionAsync` / `flushServerSideAsyncTransactions` | `ctl.applyTransaction` / `applyTransactionAsync` / `flushAsyncTransactions` |\n| `applyServerSideRowData` | `ctl.applyRowData` |\n| `serverSideSortAllLevels`, `serverSideEnableClientSideSort`, `serverSideOnlyRefreshFilteredGroups` | `sortAllLevels`, `clientSideSort`, `onlyRefreshFilteredGroups` |\n| `getServerSideSelectionState` / `setServerSideSelectionState` | `ctl.getSelectionState()` / `setSelectionState()` (the `toggledNodes` shape is accepted; `toCallbackSelectionState` / `fromCallbackSelectionState` convert) |\n| `ServerSideTransactionResult.status`: `Applied`, `StoreNotFound`, `StoreLoading`, `StoreWaitingToLoad`, `StoreLoadingFailed`, `Cancelled` | `ServerTransactionResult.status`: the same six, lower camel case (`applied`, `storeNotFound`, ...) - a `switch` on the old spelling falls through silently |\n| `groupSelects: 'descendants'` | `selection: { groupSelects: 'descendants' }` |\n| `pivotResultFields` in `success`, `setPivotResultColumns`, `processPivotResultColDef` | `pivotResultFields` / `pivotResultColumns` in the result, `pivotResultColumn(field, def)` |\n| `pagination` + `paginateChildRows` | `pagination: { pageSize, paginateChildRows }` |\n| `getCacheBlockState()` / `getServerSideGroupLevelState()` | `ctl.getCacheState()` / `ctl.levelStates()` |\n| `serverSideDatasource.destroy()` | `source.destroy()` |\n\nTwo differences worth knowing before you start: SvGrid sends the global\nsearch box to the server as `filterModel.global` (AG Grid's quick filter is\nclient-side only and unsupported under its infinite and server-side models),\nand SvGrid has no viewport row model. See\n[Server grouping](./server/server-grouping.md) and\n[demo 467](https://svgrid.com/demos/467-server-row-model-1m/).\n\n### Excel / PDF export\n\nAG Grid: `gridApi.exportDataAsExcel({...})` (Enterprise-only).\nSvGrid: install `@svgrid/enterprise`, call `api.exportData({ format: 'xlsx', ... })`. See [Data export and printing](./export.md).\n\n```ts\nimport { installEnterprise, setLicenseKey } from '@svgrid/enterprise'\nsetLicenseKey('YOUR-LICENSE-KEY') // your Enterprise key\n\n// inside onApiReady:\nconst pro = installEnterprise(api)\nawait pro.exportData({ format: 'xlsx', filename: 'orders' })\n```\n\n## Gotchas - things that don't translate directly\n\n### 1. Per-column `editable: true`\nEditing is switched on at the grid level (`enableInlineEditing`) and\nnarrowed per column with `editable: boolean | (ctx) => boolean` on the\ncolumn definition, so AG Grid's per-column flag and its callback form both\nmap directly. What does not map is AG Grid's `editable` on a column\ngroup: set it on each child column.\n\n### 2. Column drag-to-reorder\nHeader drag is `enableColumnReorder` on `<SvGrid>`; `setColumnOrder`\non the API does the same from code. See\n[column moving](./columns/column-moving.md) for the events.\n\n### 3. AG Grid `valueGetter` chains\nAG Grid's `valueGetter` can read other column values via the API. In\nSvGrid, `fieldFn` only receives the row; if you need cross-column\ncomputed values, do it in the cell renderer with `ctx.row.original` or\ncompute the derived value upstream and store it in the row.\n\n### 4. `cellClass` / `rowClass` callbacks\nOn the roadmap. For now, render a wrapper element in your `cell` snippet\nwith the conditional class.\n\n### 5. The Status Bar / Side Bar / Tool Panels\nAG Grid's chrome (status bar with row count, side bar with filters and\ncolumns panels) doesn't exist in SvGrid - build it as plain Svelte\nmarkup around the grid. Most teams build their own anyway because\nAG Grid's defaults rarely match a polished design system.\n\n### 6. Set filter (the Excel-style funnel popup)\nSvGrid ships an Excel-style filter menu (free in Community). API surface\nis similar but not identical - see [Set filter](./filtering/set-filter.md).\n\n## When NOT to migrate\n\nBe honest. Stay on AG Grid if you:\n\n- **Use multiple frameworks** - AG Grid has React, Angular, Vue, Solid, Qwik, vanilla adapters. SvGrid is Svelte-only.\n- **Need a push-based viewport row model** - SvGrid's server-side row model covers grouping, tree, pivot, transactions and select-all across unloaded rows, and its real-time page merges deltas into loaded rows, but the server cannot push the visible window over a socket the way the viewport model does.\n- **Need custom tool panels** - SvGrid's tool panel is a fixed Columns + Filters pair. (Custom filter components are covered: a column's `customFilter` renders your own control in the filter menu, the floating filter row and the Filters tab.)\n- **Are mid-project and shipping in <2 weeks** - the migration is a few hours per grid, but only do it when you have buffer.\n- **Have a Svelte 4 codebase you can't upgrade** - SvGrid requires Svelte 5 runes. (Consider [htmlelements.com](https://www.htmlelements.com) for vanilla / multi-framework.)\n\nIf none of those apply: switching drops a per-developer Enterprise licence\nfor features that are in SvGrid's MIT core, cuts the bundle by the\ndifference in the facts box above, and gives you a Svelte-native API that\nplays well with runes.\n\n## Step-by-step migration\n\nA typical migration of a single grid takes 1-3 hours:\n\n1. **Install** - `pnpm add @svgrid/grid` (and `@svgrid/enterprise` if you need export).\n2. **Translate columnDefs** - use the mapping table above. Most columns are 1:1.\n3. **Wrap features** - figure out which AG Grid features you actually use; register only those in `tableFeatures({...})`.\n4. **Swap the component** - `<AgGridSvelte gridOptions={...}>` → `<SvGrid data={rows} columns={columns} features={features}>`.\n5. **Move event handlers** - AG Grid `onCellValueChanged` → SvGrid `onCellValueChange` (signature differs slightly, see above).\n6. **Move API calls** - AG Grid `gridApi.X()` → SvGrid `api.X()` per the API table.\n7. **Test interactions** - sort, filter, edit, select. Most \"just works.\"\n8. **Remove `ag-grid-*` packages** - `pnpm remove ag-grid-community ag-grid-svelte` etc. Inspect your bundle to confirm the drop; the facts box above has both measured sizes.\n\n## Need help migrating?\n\nEnterprise customers get **migration help included** with the support plan\n(architecture review, port one grid for you as a reference). Email\n`support@jqwidgets.com` after purchase, or `sales@jqwidgets.com` for\npre-sales questions.\n\n## Frequently asked questions\n\n### Is SvGrid a drop-in replacement for AG Grid in Svelte?\n\nNot a literal drop-in - there is no `ag-grid-svelte` shim to swap. But the\nconcepts map closely: column definitions, row models, sorting, filtering,\ngrouping, and an imperative API all have direct SvGrid equivalents, so most\nteams port a grid in 30 minutes to a day. It is a configuration translation,\nnot a rewrite.\n\n### What is the SvGrid equivalent of AG Grid Enterprise?\n\n`@svgrid/enterprise`. It adds Excel/PDF/styled-HTML export (CSV, TSV and JSON export are already free in the grid), a printable view, pivot\ntables and data import. The in-grid AI helpers are free in `@svgrid/grid`.\nIt is licensed per developer ($599 for the grid, $999 with the spreadsheet\nand Studio, both covering unlimited apps), and the\nCommunity package is MIT-licensed and free for commercial use.\n\n### Does SvGrid use Svelte 5 runes, or is it a wrapper?\n\nIt is Svelte-5-native. State is `$state` / `$derived` / `$effect` and cells\nrender through Svelte snippets - there is no React or Angular core underneath\nand no framework bridge to keep in sync.\n\n### Will my AG Grid bundle size shrink?\n\nAlmost always. The facts box at the top of this page has both packages\nmeasured the same way on the same date: the full SvGrid render component\nwith its stylesheet against `createGrid` with every AG Grid Community\nmodule registered. You add `@svgrid/enterprise` features only where you\nimport them, and the headless core on its own is a small fraction of the\nrender component.\n\n## More examples\n\n### AG Grid ↔ sv-grid side-by-side\n\nTwo real grids over the same dataset: the installed AG Grid Community on the left, sv-grid on the right. Same global filter drives both. Source code panels for either side.\n\n<div data-docs-demo=\"139-migration-from-ag-grid\" data-height=\"460\"></div>\n\n## See also\n\n- [Getting started](../getting-started.md) - full SvGrid walkthrough\n- [Why headless?](../why-headless.md) - the headless / render-component split\n- [Data export and printing](./export.md) - the `@svgrid/enterprise` feature pack\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](./comparison.md) - the\n measured benchmark and the feature matrix\n- [SvGrid vs AG Grid comparison page](https://svgrid.com/compare/ag-grid/) -\n every claim with its source and date\n"
6026
+ "markdown": "\n# Migrating from AG Grid to SvGrid\n\nIf you tried AG Grid on a Svelte 5 project - via `ag-grid-svelte`, the\nold `ag-grid-community/svelte`, or a hand-rolled wrapper - you probably\nhit the same friction everyone hits: the bridge between AG Grid's\nReact/Angular-first API and Svelte 5 runes is brittle, the bundle is\nheavy, and the Enterprise pricing only makes sense at scale.\n\n<!-- facts:start ag-grid -->\n> **Facts, checked 12 Sep 2026.** `ag-grid-community` 36.1.0, MIT, last published 5 Aug 2026, 12,400,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `ag-grid-community` 36.1.0 317.5 KB JS, no separate stylesheet (measured 12 Sep 2026). AG Grid pricing, as its site states it: AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer (https://www.ag-grid.com/license-pricing/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/).\n<!-- facts:end -->\n\nThis page is a 30-minute migration recipe from AG Grid to SvGrid. It\ncovers what maps 1:1, what's different by design, and what you'll lose.\nWe tell you when **not** to switch at the bottom.\n\n## TL;DR\n\n| | AG Grid Community | AG Grid Enterprise | SvGrid Community | @svgrid/enterprise |\n| --- | --- | --- | --- | --- |\n| **Licence** | MIT | Commercial, per developer (the price is in the facts box above) | **MIT** | $599/dev/yr (grid) or $999/dev/yr (grid + spreadsheet + Studio) |\n| **Svelte 5 native** | No (community-built integration) | No (community-built integration) | Yes | Yes |\n| **Bundle (gzipped)** | measured, in the facts box above | not measured (licence) | measured, in the facts box above | lazy-loaded subpaths |\n| **Sorting / filtering** | Yes | Yes | Yes | (in Community) |\n| **Row grouping + aggregation** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Master/detail, tree, range select** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Set filter / Excel-style filter menu** | No (Enterprise) | Yes | Yes (free) | (in Community) |\n| **Server-side data, flat (infinite row model)** | Yes | Yes | Yes (free) | (in Community) |\n| **Server-side row model (grouping, tree, pivot, transactions, selection)** | No (Enterprise) | Yes | No | Yes |\n| **Integrated charts** | No (Enterprise) | Yes, AG Charts | Yes (free) | (in Community) |\n| **CSV export** | Yes (API) | Yes | Yes, with TSV and JSON | (in Community) |\n| **Excel export** | No | Yes | No | Yes |\n| **PDF / styled-HTML export, print** | No | No | No | Yes |\n| **Pivot tables** | No | Yes | No | Yes |\n| **MCP server for AI assistants** | Yes, `ag-mcp` | Yes | Yes, `@svgrid/mcp` | (in Community) |\n| **In-grid AI helpers** | No | No | Yes (bring your own model) | (in Community) |\n\n**SvGrid Community gives you most of what AG Grid sells as Enterprise for\nfree**, and `@svgrid/enterprise` adds Excel, PDF and print output, import,\npivot tables and the server-side row model per developer per year. Compare what each paid tier adds\nbefore comparing prices; both are in the facts box. The trade-offs are\nSvelte-only and a much smaller ecosystem. Every AG Grid cell above follows\nag-grid.com's own pages; the dated list is on the\n[SvGrid vs AG Grid](https://svgrid.com/compare/ag-grid/) page.\n\n## Mental model - what changes\n\nAG Grid is one big object you configure declaratively. SvGrid is a\n**headless engine** (`createSvGrid`) with an optional **render\ncomponent** (`<SvGrid>`) on top - the same split TanStack Table made\npopular. You can use either layer; most projects use the render\ncomponent.\n\nEvery example below runs against this setup:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature, type ColumnDef } from '@svgrid/grid'\n\n type Row = { id: number; make: string; model: string; price: number }\n\n const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n\n let rows = $state<Row[]>([\n { id: 1, make: 'Toyota', model: 'Celica', price: 35000 },\n { id: 2, make: 'Ford', model: 'Mondeo', price: 32000 },\n { id: 3, make: 'Porsche', model: 'Boxster', price: 72000 },\n ])\n const data = rows\n\n const columns: ColumnDef<typeof features, Row>[] = [\n { field: 'make', header: 'Make' },\n { field: 'model', header: 'Model' },\n { field: 'price', header: 'Price', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```svelte\n<!-- AG Grid (via a Svelte wrapper) -->\n<AgGridSvelte\n gridOptions={{\n rowData: rows,\n columnDefs: columns,\n onGridReady: (params) => (gridApi = params.api),\n }}\n/>\n\n<!-- SvGrid -->\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n onApiReady={(api) => (gridApi = api)}\n/>\n```\n\nThree things to note:\n\n1. **No giant `gridOptions` blob.** Each capability is a top-level prop.\n2. **Features are opt-in.** You pass a `features` object built with\n `tableFeatures({...})` - only the features you list ship JS.\n3. **`onApiReady`** gives you a typed `SvGridApi` that is roughly the\n AG Grid `gridApi` equivalent (see the API-mapping table below).\n\n## Column definitions - direct translation\n\nThe shapes are similar enough that you can usually translate by hand\nwithout thinking too hard.\n\n```ts\n// AG Grid\nconst columnDefs: ColDef[] = [\n { field: 'name', headerName: 'Name', sortable: true, filter: true, width: 200 },\n { field: 'price', headerName: 'Price', type: 'numericColumn',\n valueFormatter: ({ value }) => `$${value.toFixed(2)}` },\n { field: 'date', headerName: 'Date',\n valueGetter: ({ data }) => new Date(data.date).toISOString().slice(0, 10) },\n { field: 'status', headerName: 'Status',\n cellRenderer: StatusCellRenderer,\n cellRendererParams: { onChange: handleStatusChange } },\n]\n```\n\n```ts\n// SvGrid\nimport { renderComponent, type ColumnDef } from '@svgrid/grid'\nimport StatusCell from './StatusCell.svelte'\n\nconst columns: ColumnDef<typeof features, Row>[] = [\n { field: 'name', header: 'Name', width: 200 }, // sortable + filterable by default\n { field: 'price', header: 'Price',\n format: { type: 'currency', currency: 'USD' } },\n { field: 'date', header: 'Date',\n format: { type: 'date', pattern: 'y-m-d' } },\n { field: 'status', header: 'Status',\n cell: renderComponent(StatusCell, (ctx) => ({\n value: ctx.getValue(),\n onChange: handleStatusChange,\n })),\n },\n]\n```\n\n### Property mapping\n\n| AG Grid | SvGrid | Notes |\n| --- | --- | --- |\n| `field` | `field` | Same. |\n| `headerName` | `header` | Accepts a string or a snippet/component. |\n| `width` | `width` | Same. |\n| `minWidth` / `maxWidth` | `minWidth` / `maxWidth` | Same. |\n| `sortable: true` | (default) | Sorting is on when `rowSortingFeature` is registered. |\n| `filter: true` | (default) | Filtering is on when `columnFilteringFeature` is registered. |\n| `valueFormatter` | `format: { ... }` | Built-in types: `number`, `currency`, `percent`, `date`. For custom, use `cell`. |\n| `valueGetter` | `fieldFn` | Returns the value for sorting/filtering. |\n| `cellRenderer` + `cellRendererParams` | `cell: renderComponent(C, ctx => props)` | One call, type-checked. |\n| `cellEditor: 'agTextCellEditor'` | `editorType: 'text'` | Built-in: `text`, `number`, `checkbox`, `date`. |\n| `editable: true` | `enableInlineEditing` prop on `<SvGrid>` | Per-grid, not per-column. (Per-column control on the roadmap.) |\n| `pinned: 'left'` / `'right'` | Right-click column menu → Pin | Set programmatically via the api. |\n| `rowGroup: true` | Via `setGroupBy([colId])` | See Grouping below. |\n| `aggFunc: 'sum'` | `aggregate: 'sum'` | Built-in: `sum`, `avg`, `min`, `max`, `count`. |\n\n## Feature registration - the one new thing\n\nAG Grid auto-enables most features; you turn them off. SvGrid is the\nopposite - features are opt-in. The result is a smaller bundle.\n\n```ts\nimport {\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n columnGroupingFeature,\n rowExpandingFeature,\n rowPaginationFeature,\n rowSelectionFeature,\n} from '@svgrid/grid'\n\nconst features = tableFeatures({\n rowSortingFeature,\n columnFilteringFeature,\n rowSelectionFeature,\n // omit any you don't need - their code won't ship\n})\n```\n\nPass `features` to `<SvGrid>` once. From then on the grid behaves like\nAG Grid's `enableSorting`, `enableFilter`, `rowSelection`, etc. are all\non for the registered features.\n\n## API mapping (`gridApi` → `SvGridApi`)\n\nYou get the SvGrid API from `onApiReady` (equivalent to AG Grid's\n`onGridReady`).\n\n| AG Grid `gridApi.X()` | SvGrid `api.X()` |\n| --- | --- |\n| `setRowData(rows)` | (declarative - just update `data` prop) |\n| `addRow(row)` / `applyTransaction({ add: [row] })` | `api.addRow(row)` / `api.addRows(rows)` |\n| `applyTransaction({ remove: [row] })` | `api.removeRow(rowIndex)` |\n| `getValue(colId, rowNode)` | `api.getCellValue(rowIndex, columnId)` |\n| `setValue(...)` | `api.setCellValue(rowIndex, columnId, value)` |\n| `setColumnVisible(colId, visible)` | `api.setColumnVisible(columnId, visible)` |\n| `getSortModel()` / `setSortModel()` | `api.setSort(columnId, 'asc'\\|'desc'\\|null)` |\n| `setFilterModel({...})` | `api.setFilter(columnId, { operator, value })` |\n| `getDisplayedRowAtIndex(i)` / `forEachNodeAfterFilterAndSort(...)` | `api.getDisplayedRows()` |\n| `getModel()` (raw rows) | `api.getData()` |\n\n## Common patterns\n\n### Sorting + filtering + pagination (the 80% case)\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid,\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n } from '@svgrid/grid'\n\n const features = tableFeatures({\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n })\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showPagination\n showColumnFilters\n/>\n```\n\nAG Grid equivalent: `gridOptions: { defaultColDef: { sortable: true, filter: true }, pagination: true }`.\n\n### Cell editing with persistence\n\n```svelte\n<script lang=\"ts\">\n function onCellValueChange(e: { rowIndex: number; columnId: string; value: unknown }) {\n // Persist however you like (fetch to backend, optimistic local update, etc.)\n console.log('cell changed', e)\n }\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n enableInlineEditing\n onCellValueChange={onCellValueChange}\n/>\n```\n\nAG Grid equivalent: `onCellValueChanged: ({ data, colDef, newValue, oldValue }) => ...`.\nSvGrid's event payload is column-id + row-index based rather than node-based; the row data is yours\nto mutate (or not) on the `rows` array you passed in.\n\n### Grouping + aggregation\n\n```svelte\n<script lang=\"ts\">\n import {\n SvGrid,\n tableFeatures,\n columnGroupingFeature,\n rowSortingFeature,\n rowExpandingFeature,\n } from '@svgrid/grid'\n\n const features = tableFeatures({\n rowSortingFeature,\n columnGroupingFeature,\n rowExpandingFeature,\n })\n\n const columns = [\n { field: 'department', header: 'Department' },\n { field: 'team', header: 'Team' },\n { field: 'salary', header: 'Salary', aggregate: 'sum',\n format: { type: 'currency', currency: 'USD' } },\n ]\n\n function setGroup(api) {\n api.setGroupBy(['department', 'team'])\n }\n</script>\n\n<SvGrid\n data={rows}\n columns={columns}\n features={features}\n showGroupingControls\n onApiReady={setGroup}\n/>\n```\n\nAG Grid Enterprise's `rowGroupPanelShow: 'always'` + `aggFunc: 'sum'` translates 1:1.\n\n### Master / detail\n\nAG Grid Enterprise feature; **free in SvGrid Community**. See\n[demo 08](https://svgrid.com/demos/08-tree-and-master-detail/) for the exact pattern.\n\n### Server-side data\n\nAG Grid's Infinite Row Model (Community) and Server-Side Row Model\n(Enterprise) both take an `IServerSideDatasource` with a `getRows(params)`\nthat answers through `params.success({ rowData, rowCount })`. SvGrid has one\n`ServerDataSource` whose `getRows(request)` returns `{ rows, rowCount }`,\nand two controllers over it: `createServerDataSource` (free: paging or\ninfinite block scroll, sort, filter, CRUD) and `createServerRowModel`\n(Enterprise: lazy grouping, tree, pivot, transactions, selection). Both\nmount through one prop, `<SvGrid rowModel={ctl} />`.\n\nAn existing datasource written for AG Grid keeps working behind one call:\n\n```ts\nimport { adaptCallbackDatasource, createServerRowModel } from '@svgrid/enterprise'\n\nconst ctl = createServerRowModel(adaptCallbackDatasource(myServerSideDatasource), {\n groupBy: ['country'],\n aggregations: [{ col: 'amount', fn: 'sum' }],\n})\n```\n\n`adaptCallbackDatasource` maps the request both ways (`rowGroupCols` ->\n`groupBy`, `valueCols` -> `aggregations`, `pivotCols` -> `pivotBy`, the\nsort and filter models, `context`, `parentNode`) and turns `success` /\n`fail` into a resolved or rejected promise.\n\nMore often the datasource is a thin `fetch` and the real investment is the\nendpoint behind it - a Java or Node service that parses AG Grid's\n`IServerSideGetRowsRequest` JSON. That endpoint stays as it is: post\n`toCallbackRequest(request)` and read the answer back.\n\n```ts\nimport { toCallbackRequest } from '@svgrid/enterprise'\n\nconst source = {\n async getRows(request) {\n const res = await fetch('/api/sales', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(toCallbackRequest(request)),\n })\n const { rowData, rowCount, pivotResultFields } = await res.json()\n return { rows: rowData, rowCount: rowCount ?? -1, pivotResultFields }\n },\n}\n```\n\n`fromCallbackRequest` is the other direction, for a SvelteKit endpoint that\nhas to keep serving an AG Grid client during the switch. A saved selection\nor a bulk endpoint written against `getServerSideSelectionState()` keeps\nits shape the same way: `toCallbackSelectionState(ctl.getSelectionState())`\nproduces `{ selectAll, toggledNodes }` (or the `nodeId` /\n`selectAllChildren` / `toggledNodes` tree), `ctl.setSelectionState` takes\nthat shape as it is when your group node ids are the group keys, and\n`fromCallbackSelectionState(state, { groupKey, isGroup })` maps them when\na `getRowId` gave group rows ids of their own. Option by option:\n\n| AG Grid | SvGrid |\n| --- | --- |\n| `rowModelType: 'infinite'` + `datasource` | `createServerDataSource(source, { mode: 'infinite' })` + `rowModel={ctl}` |\n| `rowModelType: 'serverSide'` + `serverSideDatasource` | `createServerRowModel(source, options)` + `rowModel={ctl}` |\n| `getRows(params)` + `params.success({ rowData, rowCount })` / `params.fail()` | `getRows(request)` returning `{ rows, rowCount }` / throwing |\n| `cacheBlockSize`, `maxBlocksInCache`, `maxConcurrentDatasourceRequests`, `blockLoadDebounceMillis` | `blockSize`, `maxBlocksInCache`, `maxConcurrentRequests`, `blockLoadDebounceMs` |\n| `infiniteInitialRowCount` / `serverSideInitialRowCount` | `initialRowCount` |\n| `rowCount: -1` (unknown) | `rowCount: -1` |\n| `refreshInfiniteCache()` / `purgeInfiniteCache()` | `ctl.refresh()` / `ctl.purge()` |\n| `request.rowGroupCols`, `groupKeys`, `valueCols`, `pivotCols`, `pivotMode` | `request.groupBy`, `groupKeys`, `aggregations`, `pivotBy`, `pivotMode` |\n| `getChildCount(data)` | `childCount: (row) => row.childCount` |\n| `isServerSideGroupOpenByDefault` | `isGroupOpenByDefault(route, row)` |\n| `getServerSideGroupLevelParams` | `levelParams(level, route)` |\n| `isServerSideGroup` / `getServerSideGroupKey` (tree) | `treeData: true` + `hasChildren` / `getRowId` |\n| `grandTotalRow` / `groupTotalRow` | `grandTotalRow` / `groupFooters` |\n| `refreshServerSide({ route, purge })` / `retryServerSideLoads()` | `ctl.refresh({ route, purge })` / `ctl.retryLoads()` |\n| `applyServerSideTransaction` / `applyServerSideTransactionAsync` / `flushServerSideAsyncTransactions` | `ctl.applyTransaction` / `applyTransactionAsync` / `flushAsyncTransactions` |\n| `applyServerSideRowData` | `ctl.applyRowData` |\n| `serverSideSortAllLevels`, `serverSideEnableClientSideSort`, `serverSideOnlyRefreshFilteredGroups` | `sortAllLevels`, `clientSideSort`, `onlyRefreshFilteredGroups` |\n| `getServerSideSelectionState` / `setServerSideSelectionState` | `ctl.getSelectionState()` / `setSelectionState()` (the `toggledNodes` shape is accepted; `toCallbackSelectionState` / `fromCallbackSelectionState` convert) |\n| `ServerSideTransactionResult.status`: `Applied`, `StoreNotFound`, `StoreLoading`, `StoreWaitingToLoad`, `StoreLoadingFailed`, `Cancelled` | `ServerTransactionResult.status`: the same six, lower camel case (`applied`, `storeNotFound`, ...) - a `switch` on the old spelling falls through silently |\n| `groupSelects: 'descendants'` | `selection: { groupSelects: 'descendants' }` |\n| `pivotResultFields` in `success`, `setPivotResultColumns`, `processPivotResultColDef` | `pivotResultFields` / `pivotResultColumns` in the result, `pivotResultColumn(field, def)` |\n| `pagination` + `paginateChildRows` | `pagination: { pageSize, paginateChildRows }` |\n| `getCacheBlockState()` / `getServerSideGroupLevelState()` | `ctl.getCacheState()` / `ctl.levelStates()` |\n| `serverSideDatasource.destroy()` | `source.destroy()` |\n\nTwo differences worth knowing before you start: SvGrid sends the global\nsearch box to the server as `filterModel.global` (AG Grid's quick filter is\nclient-side only and unsupported under its infinite and server-side models),\nand SvGrid has no viewport row model. See\n[Server grouping](./server/server-grouping.md) and\n[demo 467](https://svgrid.com/demos/467-server-row-model-1m/).\n\n### Excel / PDF export\n\nAG Grid: `gridApi.exportDataAsExcel({...})` (Enterprise-only).\nSvGrid: install `@svgrid/enterprise`, call `api.exportData({ format: 'xlsx', ... })`. See [Data export and printing](./export.md).\n\n```ts\nimport { installEnterprise, setLicenseKey } from '@svgrid/enterprise'\nsetLicenseKey('YOUR-LICENSE-KEY') // your Enterprise key\n\n// inside onApiReady:\nconst pro = installEnterprise(api)\nawait pro.exportData({ format: 'xlsx', filename: 'orders' })\n```\n\n## Gotchas - things that don't translate directly\n\n### 1. Per-column `editable: true`\nEditing is switched on at the grid level (`enableInlineEditing`) and\nnarrowed per column with `editable: boolean | (ctx) => boolean` on the\ncolumn definition, so AG Grid's per-column flag and its callback form both\nmap directly. What does not map is AG Grid's `editable` on a column\ngroup: set it on each child column.\n\n### 2. Column drag-to-reorder\nHeader drag is `enableColumnReorder` on `<SvGrid>`; `setColumnOrder`\non the API does the same from code. See\n[column moving](./columns/column-moving.md) for the events.\n\n### 3. AG Grid `valueGetter` chains\nAG Grid's `valueGetter` can read other column values via the API. In\nSvGrid, `fieldFn` only receives the row; if you need cross-column\ncomputed values, do it in the cell renderer with `ctx.row.original` or\ncompute the derived value upstream and store it in the row.\n\n### 4. `cellClass` / `rowClass` callbacks\nOn the roadmap. For now, render a wrapper element in your `cell` snippet\nwith the conditional class.\n\n### 5. The Status Bar / Side Bar / Tool Panels\nAG Grid's chrome (status bar with row count, side bar with filters and\ncolumns panels) doesn't exist in SvGrid - build it as plain Svelte\nmarkup around the grid. Most teams build their own anyway because\nAG Grid's defaults rarely match a polished design system.\n\n### 6. Set filter (the Excel-style funnel popup)\nSvGrid ships an Excel-style filter menu (free in Community). API surface\nis similar but not identical - see [Set filter](./filtering/set-filter.md).\n\n## When NOT to migrate\n\nBe honest. Stay on AG Grid if you:\n\n- **Use multiple frameworks** - AG Grid has React, Angular, Vue, Solid, Qwik, vanilla adapters. SvGrid is Svelte-only.\n- **Need a push-based viewport row model** - SvGrid's server-side row model covers grouping, tree, pivot, transactions and select-all across unloaded rows, and its real-time page merges deltas into loaded rows, but the server cannot push the visible window over a socket the way the viewport model does.\n- **Need custom tool panels** - SvGrid's tool panel is a fixed Columns + Filters pair. (Custom filter components are covered: a column's `customFilter` renders your own control in the filter menu, the floating filter row and the Filters tab.)\n- **Are mid-project and shipping in <2 weeks** - the migration is a few hours per grid, but only do it when you have buffer.\n- **Have a Svelte 4 codebase you can't upgrade** - SvGrid requires Svelte 5 runes. (Consider [htmlelements.com](https://www.htmlelements.com) for vanilla / multi-framework.)\n\nIf none of those apply: switching drops a per-developer Enterprise licence\nfor features that are in SvGrid's MIT core, cuts the bundle by the\ndifference in the facts box above, and gives you a Svelte-native API that\nplays well with runes.\n\n## Step-by-step migration\n\nA typical migration of a single grid takes 1-3 hours:\n\n1. **Install** - `pnpm add @svgrid/grid` (and `@svgrid/enterprise` if you need export).\n2. **Translate columnDefs** - use the mapping table above. Most columns are 1:1.\n3. **Wrap features** - figure out which AG Grid features you actually use; register only those in `tableFeatures({...})`.\n4. **Swap the component** - `<AgGridSvelte gridOptions={...}>` → `<SvGrid data={rows} columns={columns} features={features}>`.\n5. **Move event handlers** - AG Grid `onCellValueChanged` → SvGrid `onCellValueChange` (signature differs slightly, see above).\n6. **Move API calls** - AG Grid `gridApi.X()` → SvGrid `api.X()` per the API table.\n7. **Test interactions** - sort, filter, edit, select. Most \"just works.\"\n8. **Remove `ag-grid-*` packages** - `pnpm remove ag-grid-community ag-grid-svelte` etc. Inspect your bundle to confirm the drop; the facts box above has both measured sizes.\n\n## Need help migrating?\n\nEnterprise customers get **migration help included** with the support plan\n(architecture review, port one grid for you as a reference). Email\n`support@jqwidgets.com` after purchase, or `sales@jqwidgets.com` for\npre-sales questions.\n\n## Frequently asked questions\n\n### Is SvGrid a drop-in replacement for AG Grid in Svelte?\n\nNot a literal drop-in - there is no `ag-grid-svelte` shim to swap. But the\nconcepts map closely: column definitions, row models, sorting, filtering,\ngrouping, and an imperative API all have direct SvGrid equivalents, so most\nteams port a grid in 30 minutes to a day. It is a configuration translation,\nnot a rewrite.\n\n### What is the SvGrid equivalent of AG Grid Enterprise?\n\n`@svgrid/enterprise`. It adds Excel/PDF/styled-HTML export (CSV, TSV and JSON export are already free in the grid), a printable view, pivot\ntables and data import. The in-grid AI helpers are free in `@svgrid/grid`.\nIt is licensed per developer ($599 for the grid, $999 with the spreadsheet\nand Studio, both covering unlimited apps), and the\nCommunity package is MIT-licensed and free for commercial use.\n\n### Does SvGrid use Svelte 5 runes, or is it a wrapper?\n\nIt is Svelte-5-native. State is `$state` / `$derived` / `$effect` and cells\nrender through Svelte snippets - there is no React or Angular core underneath\nand no framework bridge to keep in sync.\n\n### Will my AG Grid bundle size shrink?\n\nAlmost always. The facts box at the top of this page has both packages\nmeasured the same way on the same date: the full SvGrid render component\nwith its stylesheet against `createGrid` with every AG Grid Community\nmodule registered. You add `@svgrid/enterprise` features only where you\nimport them, and the headless core on its own is a small fraction of the\nrender component.\n\n## More examples\n\n### AG Grid ↔ sv-grid side-by-side\n\nTwo real grids over the same dataset: the installed AG Grid Community on the left, sv-grid on the right. Same global filter drives both. Source code panels for either side.\n\n<div data-docs-demo=\"139-migration-from-ag-grid\" data-height=\"460\"></div>\n\n## See also\n\n- [Getting started](../getting-started.md) - full SvGrid walkthrough\n- [Why headless?](../why-headless.md) - the headless / render-component split\n- [Data export and printing](./export.md) - the `@svgrid/enterprise` feature pack\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](./comparison.md) - the\n measured benchmark and the feature matrix\n- [SvGrid vs AG Grid comparison page](https://svgrid.com/compare/ag-grid/) -\n every claim with its source and date\n"
5884
6027
  },
5885
6028
  {
5886
6029
  "slug": "help/migrating-from-airtable",
5887
6030
  "path": "docs/help/migrating-from-airtable.md",
5888
6031
  "title": "Migrating from Airtable",
5889
6032
  "section": "Help",
5890
- "markdown": "# Migrating from Airtable\n\nAirtable is a cloud service: the base, its views and its records live on\nAirtable, and the most you can put in your own app is a read-only iframe.\n[SvGrid Base](./base/start.md) is the same kind of table database shipped\nas a Svelte 5 component. The records move into your own database, `<SvBase>`\nrenders the views inside your app, and every edit goes back to your tables.\n\n> Estimated effort: **half a day** for a typical base, plus the time to\n> rebuild its automations.\n\n<!-- facts:start airtable -->\n> **Facts, checked 14 Oct 2026.** `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the 30 days to 10 Sep 2026. Airtable pricing, as its site states it: Airtable Free has no cost. airtable.com/pricing lists Team at $20 per seat per month billed annually ($24 monthly) and Business at $45 per seat per month billed annually ($54 monthly); Enterprise Scale pricing is custom. Read-only collaborators are not charged on Team or Business (https://airtable.com/pricing, read 14 Oct 2026). SvGrid: SvGrid Base ships in Enterprise Suite of @svgrid/enterprise, $999 per developer per year, unlimited apps and end users; the grid it runs on is MIT. Side by side, with sources: [SvGrid vs Airtable](https://svgrid.com/compare/airtable/).\n<!-- facts:end -->\n\n## What maps to what\n\n| Airtable | SvGrid Base |\n| --- | --- |\n| A base | A `<SvBase tables>` with one tab per table |\n| A table | A table in your database, opened as a `BaseTable` |\n| A linked record field | A foreign key (link to one) or a junction table (link to many) |\n| A view | A `FieldView`: `grid`, `kanban`, `calendar`, `gallery`, `chart` or `form` |\n| An automation | An automation in the view bar, or `createAutomationServer` on your server |\n| Collaborators and permissions | Your app's login, and `authorize` on the endpoint |\n| Comments | `setRecordComments`, stored where your app stores them |\n| An interface | Your own Svelte page around the base |\n\nField types carry over almost one to one:\n\n| Airtable field | `fieldType` |\n| --- | --- |\n| Single line text | `text` |\n| Long text | `longText` (with `richText` for bold, italic, links and lists) |\n| Attachment | `attachment` |\n| Checkbox | `checkbox` |\n| Single select, multiple select | `singleSelect`, `multiSelect` |\n| User | `user` |\n| Date | `date` |\n| Phone number, email, URL | `phone`, `email`, `url` |\n| Number, currency, percent | `number` with `format: 'integer'`, `'currency'` or `'percent'` |\n| Duration | `duration` |\n| Rating | `rating` |\n| Formula | `formula` |\n| Lookup, rollup, count | `lookup`, `rollup`, `count` |\n| Created time, last modified time | `createdTime`, `lastModifiedTime` |\n| Created by, last modified by | `createdBy`, `lastModifiedBy` |\n| Autonumber | `autoNumber` |\n| Barcode, button | `barcode`, `button` |\n| Linked record | `link` |\n\nFormulas use the same shape: fields by name in braces, `&` to join text,\nand functions such as `IF`, `SWITCH`, `ROUND`, `DATEADD` and\n`DATETIME_DIFF`. Paste each formula into the field editor; one that uses a\nfunction the base does not have shows `#ERROR` and names it, and you\nrewrite that part.\n\n## 1. Export each table\n\nIn Airtable, open a grid view that shows every field and every record (no\nfilter, no hidden fields) and choose **Download CSV**. Do this for each\ntable. A linked record column comes out as text naming the linked records\nrather than as record ids; open one file to see the exact form before the\nnext step turns those names back into links.\n\nAttachment columns come out as URLs that Airtable expires after a few\nhours. Download the files straight away and put them in your own storage,\nor skip the column and move the files later.\n\n## 2. Load the tables into your database\n\nCreate a table per Airtable table, with a key the database makes, and load\nthe CSV with a text column for each link. Postgres:\n\n```sql\ncreate table projects (\n id uuid primary key default gen_random_uuid(),\n name text not null,\n status text,\n due date\n);\n\ncreate table tasks (\n id uuid primary key default gen_random_uuid(),\n task text not null,\n status text,\n budget numeric,\n project_name text, -- the CSV's \"Project\" column\n project_id uuid references projects(id)\n);\n\n\\copy projects (name, status, due) from 'Projects-Grid view.csv' csv header\n\\copy tasks (task, status, budget, project_name) from 'Tasks-Grid view.csv' csv header\n```\n\nThen match the names to keys and drop the text column:\n\n```sql\nupdate tasks t set project_id = p.id\nfrom projects p where p.name = t.project_name;\n\nalter table tasks drop column project_name;\n```\n\nA link to many records becomes a table that pairs the two. Load the CSV's\nlist of names into a text column first (`tag_names` below; adjust the\nseparator to what the file holds), then:\n\n```sql\ncreate table task_tags (\n task_id uuid references tasks(id) on delete cascade,\n tag_id uuid references tags(id) on delete cascade,\n primary key (task_id, tag_id)\n);\n\ninsert into task_tags (task_id, tag_id)\nselect t.id, g.id\nfrom tasks t\ncross join lateral unnest(string_to_array(t.tag_names, ', ')) as n(name)\njoin tags g on g.name = n.name;\n```\n\nNames must be unique for the match to be right. If two Airtable records\nshared a primary value, give them distinct names before you export, or\nmatch on another column.\n\n## 3. Open the database as a base\n\nOne endpoint on your server reads the tables and serves them; the page\nopens them. A foreign key becomes a link with a field in the other table\nthat links back, a pairing table a link to many records, and a text column\nthat repeats a few values a single select with a color per value\n([what it reads](./base/quick-start.md#what-it-reads-from-your-database)).\n\n```ts\n// src/routes/api/base/+server.ts\nimport { createBaseEndpoint } from '@svgrid/enterprise/base'\n\n// Your database driver: run parameterized SQL, return the rows.\ndeclare function query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>\n\nexport const { GET, POST } = createBaseEndpoint({ execute: query })\n```\n\n```svelte\n<!-- src/routes/base/+page.svelte (with `export const ssr = false` in +page.ts) -->\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseFromEndpoint, enableBase } from '@svgrid/enterprise/base'\n\n enableBase()\n const tables = baseFromEndpoint('/api/base')\n</script>\n\n{#await tables then tables}\n <SvBase {tables} editable sortable columnAdder fieldMenu />\n{/await}\n<SvToaster />\n```\n\n[Build a base on Postgres](./base/postgres.md) is the same thing end to\nend, and [From a database to an app](./base/quick-start.md) covers MySQL,\nSQLite and Supabase.\n\n## 4. Set the field types and views\n\nThe base guesses the types from the columns. Fix the ones it cannot know\n(a percent, a rating, a user, a formula) and recreate the views you used:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n { id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } },\n { id: 'board', name: 'Board', type: 'kanban', stackBy: 'status' },\n { id: 'due', name: 'Due dates', type: 'calendar', dateField: 'due' },\n { id: 'request', name: 'Request a task', type: 'form' },\n]\n```\n\nWhat you change in the app (field types, views, colors) comes back through\n`onTablesChange`; store it and start from it next time. The records stay in\nyour database either way.\n\n## 5. Rebuild the automations\n\nOpen **Automations** in the view bar. The triggers you know are there: a\nrecord is created, a record changes, a record matches a condition, a form\nis sent, a button is pressed, a scheduled time. The actions update the\nrecord, create a record in any table, show a notice, color the record,\ncall a webhook or send an email. An Airtable script that calls an API\nbecomes a webhook action, or an action you register in code with\n`registerAutomationAction`.\n\nAutomations that must run whoever made the change, or that hold secrets,\nrun on your server with `createAutomationServer`; see\n[Automations on the server](./base/automations.md#on-the-server).\n\n## 6. Users, permissions and comments\n\nYour app's login replaces Airtable collaborators. List the people for user\nfields with `setFieldUsers`, say who is signed in with `setCurrentUser`\n(created by and last modified by read it), and decide who may read or write\nwhat in the endpoint's `authorize`, or with row level security on Supabase.\nComments go through `setRecordComments` to wherever you keep them.\n\n## What you give up\n\n- The hosted service: someone adds `<SvBase>` to a Svelte app and runs the\n database it reads.\n- Interfaces, Omni and the AI credits. The pages around the base are your\n own Svelte pages.\n- Native mobile apps, and the list and inbox views.\n- The permissions screen, sharing links and the long revision history.\n Access rules live in your server or database; the record shows the\n changes made in the session, and the endpoint's `audit` hook can log\n every write.\n\nSvGrid Base is part of the Suite edition of `@svgrid/enterprise` ($999 per\ndeveloper). It runs without a key during an evaluation, with a watermark.\n\n## See also\n\n- [SvGrid vs Airtable](https://svgrid.com/compare/airtable/): the side-by-side comparison with sources.\n- [Build a project tracker](./base/start.md): SvGrid Base step by step.\n- [Ready-to-use bases](./base/templates.md): a CRM, a content calendar, a roadmap and more.\n- [Field types](./fields.md): every type and its properties.\n"
6033
+ "markdown": "# Migrating from Airtable\n\nAirtable is a cloud service: the base, its views and its records live on\nAirtable, and the most you can put in your own app is a read-only iframe.\n[SvGrid Base](./base/start.md) is the same kind of table database shipped\nas a Svelte 5 component. The records move into your own database, `<SvBase>`\nrenders the views inside your app, and every edit goes back to your tables.\n\n> Estimated effort: **half a day** for a typical base, plus the time to\n> rebuild its automations.\n\n<!-- facts:start airtable -->\n> **Facts, checked 14 Oct 2026.** `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the 30 days to 10 Sep 2026. Airtable pricing, as its site states it: Airtable Free has no cost. airtable.com/pricing lists Team at $20 per seat per month billed annually ($24 monthly) and Business at $45 per seat per month billed annually ($54 monthly); Enterprise Scale pricing is custom. Read-only collaborators are not charged on Team or Business (https://airtable.com/pricing, read 14 Oct 2026). SvGrid: SvGrid Base ships in Enterprise Suite of @svgrid/enterprise, $999 per developer per year, unlimited apps and end users; the grid it runs on is MIT. Side by side, with sources: [SvGrid vs Airtable](https://svgrid.com/compare/airtable/).\n<!-- facts:end -->\n\n## What maps to what\n\n| Airtable | SvGrid Base |\n| --- | --- |\n| A base | A `<SvBase tables>` with one tab per table |\n| A table | A table in your database, opened as a `BaseTable` |\n| A linked record field | A foreign key (link to one) or a junction table (link to many) |\n| A view | A `FieldView`: `grid`, `kanban`, `calendar`, `gallery`, `chart` or `form` |\n| An automation | An automation in the view bar, or `createAutomationServer` on your server |\n| Collaborators and permissions | Your app's login, and `authorize` on the endpoint |\n| Comments | `setRecordComments`, stored where your app stores them |\n| An interface | Your own Svelte page around the base |\n\nField types carry over almost one to one:\n\n| Airtable field | `fieldType` |\n| --- | --- |\n| Single line text | `text` |\n| Long text | `longText` (with `richText` for bold, italic, links and lists) |\n| Attachment | `attachment` |\n| Checkbox | `checkbox` |\n| Single select, multiple select | `singleSelect`, `multiSelect` |\n| User | `user` |\n| Date | `date` |\n| Phone number, email, URL | `phone`, `email`, `url` |\n| Number, currency, percent | `number` with `format: 'integer'`, `'currency'` or `'percent'` |\n| Duration | `duration` |\n| Rating | `rating` |\n| Formula | `formula` |\n| Lookup, rollup, count | `lookup`, `rollup`, `count` |\n| Created time, last modified time | `createdTime`, `lastModifiedTime` |\n| Created by, last modified by | `createdBy`, `lastModifiedBy` |\n| Autonumber | `autoNumber` |\n| Barcode, button | `barcode`, `button` |\n| Linked record | `link` |\n| AI text | `ai` (the prompt carries over; your app supplies the model) |\n\nFormulas use the same shape: fields by name in braces, `&` to join text,\nand the same functions; [Formula functions](#formula-functions) lists each\none. Paste each formula into the field editor, or let `baseFromAirtable`\ncarry them over; one that uses a function the base does not have shows\n`#ERROR` and names it, and you rewrite that part.\n\n## Open an Airtable base from its API\n\n`baseFromAirtable` turns what Airtable's Web API returns into the tables\n`<SvBase>` takes. Give it the schema (`GET /v0/meta/bases/{baseId}/tables`)\nand, if you want the records too, each table's records (`GET\n/v0/{baseId}/{tableId}`), keyed by table id or name. A personal access\ntoken with `schema.bases:read` and `data.records:read` reads both.\n\n```ts\n// scripts/airtable-to-base.ts: run once with Node 18 or later\nimport { writeFileSync } from 'node:fs'\nimport { baseFromAirtable, type AirtableRecord, type AirtableRecords } from '@svgrid/enterprise/base'\n\nconst BASE = 'appXXXXXXXXXXXXXX'\nconst headers = { Authorization: `Bearer ${process.env.AIRTABLE_TOKEN}` }\nconst get = async (path: string) => (await fetch(`https://api.airtable.com/v0/${path}`, { headers })).json()\n\nconst schema = await get(`meta/bases/${BASE}/tables`)\nconst records: AirtableRecords = {}\nfor (const table of schema.tables) {\n const all: AirtableRecord[] = []\n let offset = ''\n do {\n const page = await get(`${BASE}/${table.id}?pageSize=100${offset ? `&offset=${offset}` : ''}`)\n all.push(...page.records)\n offset = page.offset ?? ''\n } while (offset)\n records[table.id] = all\n}\n\nconst { tables, users, report } = baseFromAirtable(schema, records)\nfor (const r of report) console.log(`${r.table} / ${r.name}: ${r.message}`)\nwriteFileSync('src/lib/airtable-base.json', JSON.stringify({ tables, users }, null, 2))\n```\n\n```svelte\n<script lang=\"ts\">\n import { SvBase, enableBase, setFieldUsers, type BaseTable } from '@svgrid/enterprise/base'\n import base from '$lib/airtable-base.json'\n\n enableBase()\n setFieldUsers(base.users)\n let tables = $state.raw(base.tables as BaseTable[])\n</script>\n\n<SvBase bind:tables editable sortable columnAdder fieldMenu />\n```\n\nWhat it does:\n\n- Every field type in the table above becomes its Base type, with its\n options: select choices keep their colors, numbers their precision and\n currency symbol, dates their format, ratings their icon and maximum.\n- Each field gets a row key made from its name (`Due date` is `due_date`).\n Table, record and view ids stay Airtable's, so a link field's record ids\n still point at the right records, and each link names the field that\n links back in the other table.\n- A formula's `{fldXXX}` references become `{Field name}`, and its result\n type sets how the cell shows a number, an amount, a percent or a date.\n `CREATED_TIME()`, `LAST_MODIFIED_TIME()` and `LAST_MODIFIED_TIME({Field})`\n read a Created time or Last modified time field. The import uses the\n table's own when it has a fitting one and adds one when it has not (a\n Last modified time field that watches the named fields, for the last\n form), and the report lists what it added. An added Created time field\n holds each record's `createdTime`; an added Last modified time field is\n empty until the next edit, since the API does not return those times.\n- Collaborators become user ids (the Airtable `usrXXX` id, or what your\n `userId` option returns), and `users` lists them for `setFieldUsers`.\n Attachments keep their URL, name, type, size and thumbnail.\n- An AI text field becomes an [AI field](./base/ai-agents.md#ai-fields) with\n the same prompt, its field ids written as `{Field name}`. The generated\n values come over as stored text; new ones come from the provider your app\n registers with `setAIProvider`.\n- Grid, Kanban, calendar, gallery and form views carry over, and a\n timeline becomes a Gantt view.\n\n`report` lists what did not carry over as it was, one entry per field or\nview, with a `kind`:\n\n| `kind` | Means |\n| --- | --- |\n| `field` | A field type Base does not have (a sync source). It arrives as a text field with each value as text. |\n| `formula` | A formula calls a function Base does not have, or does not compile. Its cells show `#ERROR` until you rewrite that part. |\n| `view` | A view type Base does not have (a list, an interface page), or a Kanban or calendar the table has no field for. It is left out. |\n| `link` | A link to a table you left out with the `tables` option. |\n| `setting` | Something the schema does not say, which the import chose: the field a board stacks by, the dates a calendar uses, a rollup's aggregation, what a button opens, and that an AI field generates new values with the AI provider your app sets. |\n\nThe schema has no rollup aggregation: a rollup with a number result is a\n`SUM` and the rest an `ARRAYJOIN` until you change it in the field editor.\nThe tables live in the page until you store them; `baseToSql(tables)`\nwrites the SQL that creates them, with their records, in Postgres, and\n[step 3](#3-open-the-database-as-a-base) opens that database as a base.\n\n<div data-docs-demo=\"707-base-airtable-import\" data-height=\"680\"></div>\n\n## Formula functions\n\nEvery function in Airtable's formula field reference, and what a Base\nformula does with it. The table is checked against `FORMULA_FUNCTIONS`\nby a test, so it says what the formula language in this release does.\n\nTry any of them in a formula field below; the second tab is this table.\n\n<div data-docs-demo=\"708-base-formula-compat\" data-height=\"640\"></div>\n\n**Text**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `CONCATENATE` | Supported | |\n| `LEFT` | Supported | |\n| `RIGHT` | Supported | |\n| `MID` | Supported | The count may be left out for the rest of the text. |\n| `LEN` | Supported | |\n| `FIND` | Supported | Case matters; 0 when the text is not there. |\n| `SEARCH` | Supported | Case matters; empty when the text is not there. |\n| `SUBSTITUTE` | Supported | |\n| `REPLACE` | Supported | |\n| `TRIM` | Supported | |\n| `UPPER` | Supported | |\n| `LOWER` | Supported | |\n| `REPT` | Supported with a difference | At most 1,000 repeats. |\n| `T` | Supported | |\n| `ENCODE_URL_COMPONENT` | Supported | |\n| `REGEX_MATCH` | Supported with a difference | JavaScript regular expressions, not RE2. A leading (?i) works; other inline flags do not. |\n| `REGEX_EXTRACT` | Supported with a difference | JavaScript regular expressions, not RE2. Empty when nothing matches. |\n| `REGEX_REPLACE` | Supported with a difference | JavaScript regular expressions, not RE2. Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does. |\n\n**Logical**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `IF` | Supported | |\n| `SWITCH` | Supported with a difference | Compares as text, so 1 matches \"1\". |\n| `AND` | Supported | |\n| `OR` | Supported | |\n| `NOT` | Supported | |\n| `XOR` | Supported | |\n| `TRUE` | Supported | With or without the parentheses. |\n| `FALSE` | Supported | With or without the parentheses. |\n| `BLANK` | Supported | |\n| `ERROR` | Supported | The cell shows #ERROR. |\n| `ISERROR` | Supported with a difference | Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false. |\n\n**Numeric**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `ABS` | Supported | |\n| `AVERAGE` | Supported | |\n| `CEILING` | Supported | |\n| `COUNT` | Supported | |\n| `COUNTA` | Supported | |\n| `COUNTALL` | Supported | |\n| `EVEN` | Supported | |\n| `EXP` | Supported | |\n| `FLOOR` | Supported | |\n| `INT` | Supported | |\n| `LOG` | Supported | Base 10 unless a base is given. |\n| `MAX` | Supported | |\n| `MIN` | Supported | |\n| `MOD` | Supported | |\n| `ODD` | Supported | |\n| `POWER` | Supported | |\n| `ROUND` | Supported | Halves round toward positive: ROUND(-2.5) is -2. |\n| `ROUNDDOWN` | Supported | Toward zero. |\n| `ROUNDUP` | Supported | Away from zero. |\n| `SQRT` | Supported | |\n| `SUM` | Supported | |\n| `VALUE` | Supported | Skips characters that are not part of a number: VALUE(\"1,200.50 USD\") is 1200.5. |\n\n**Date**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `DATEADD` | Supported with a difference | The units Airtable names, except that \"M\" is minutes here: write \"months\". |\n| `DATESTR` | Supported | |\n| `DATETIME_DIFF` | Supported with a difference | Units as in DATEADD: \"M\" is minutes, write \"months\". |\n| `DATETIME_FORMAT` | Supported with a difference | moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read. |\n| `DATETIME_PARSE` | Supported with a difference | Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time. |\n| `DAY` | Supported | |\n| `HOUR` | Supported | |\n| `IS_AFTER` | Supported | |\n| `IS_BEFORE` | Supported | |\n| `IS_SAME` | Supported | |\n| `MINUTE` | Supported | |\n| `MONTH` | Supported | |\n| `NOW` | Supported | |\n| `SECOND` | Supported | |\n| `SET_LOCALE` | Supported with a difference | Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English. |\n| `SET_TIMEZONE` | Supported with a difference | Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty. |\n| `TIMESTR` | Supported | |\n| `TONOW` | Supported with a difference | Calendar days from the date to today, signed. |\n| `FROMNOW` | Supported with a difference | Calendar days from today to the date, signed. |\n| `TODAY` | Supported | |\n| `WEEKDAY` | Supported | 0 for Sunday; \"Monday\" as the second argument makes Monday 0. |\n| `WEEKNUM` | Supported | Weeks start on Sunday, or on Monday with \"Monday\". |\n| `WORKDAY` | Supported | Holidays as text (\"2026-12-25, 2026-12-26\") or a list of dates. |\n| `WORKDAY_DIFF` | Supported | Both days count. Holidays as in WORKDAY. |\n| `YEAR` | Supported | |\n\n**Array**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `ARRAYCOMPACT` | Supported | |\n| `ARRAYFLATTEN` | Supported | |\n| `ARRAYJOIN` | Supported | |\n| `ARRAYUNIQUE` | Supported | |\n| `ARRAYSLICE` | Supported | |\n\n**Record**\n\n| Function | SvGrid Base | Notes |\n| --- | --- | --- |\n| `RECORD_ID` | Supported | The record's id; after baseFromAirtable, the Airtable record id. |\n| `CREATED_TIME` | Not supported | A Base record keeps that time in a Created time field. baseFromAirtable rewrites CREATED_TIME() to read the table's, and adds one when the table has none. |\n| `LAST_MODIFIED_TIME` | Not supported | A Base record keeps that time in a Last modified time field. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read one that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none. |\n\n## 1. Export each table\n\nIn Airtable, open a grid view that shows every field and every record (no\nfilter, no hidden fields) and choose **Download CSV**. Do this for each\ntable. A linked record column comes out as text naming the linked records\nrather than as record ids; open one file to see the exact form before the\nnext step turns those names back into links.\n\nAttachment columns come out as URLs that Airtable expires after a few\nhours. Download the files straight away and put them in your own storage,\nor skip the column and move the files later.\n\n## 2. Load the tables into your database\n\nCreate a table per Airtable table, with a key the database makes, and load\nthe CSV with a text column for each link. Postgres:\n\n```sql\ncreate table projects (\n id uuid primary key default gen_random_uuid(),\n name text not null,\n status text,\n due date\n);\n\ncreate table tasks (\n id uuid primary key default gen_random_uuid(),\n task text not null,\n status text,\n budget numeric,\n project_name text, -- the CSV's \"Project\" column\n project_id uuid references projects(id)\n);\n\n\\copy projects (name, status, due) from 'Projects-Grid view.csv' csv header\n\\copy tasks (task, status, budget, project_name) from 'Tasks-Grid view.csv' csv header\n```\n\nThen match the names to keys and drop the text column:\n\n```sql\nupdate tasks t set project_id = p.id\nfrom projects p where p.name = t.project_name;\n\nalter table tasks drop column project_name;\n```\n\nA link to many records becomes a table that pairs the two. Load the CSV's\nlist of names into a text column first (`tag_names` below; adjust the\nseparator to what the file holds), then:\n\n```sql\ncreate table task_tags (\n task_id uuid references tasks(id) on delete cascade,\n tag_id uuid references tags(id) on delete cascade,\n primary key (task_id, tag_id)\n);\n\ninsert into task_tags (task_id, tag_id)\nselect t.id, g.id\nfrom tasks t\ncross join lateral unnest(string_to_array(t.tag_names, ', ')) as n(name)\njoin tags g on g.name = n.name;\n```\n\nNames must be unique for the match to be right. If two Airtable records\nshared a primary value, give them distinct names before you export, or\nmatch on another column.\n\n## 3. Open the database as a base\n\nOne endpoint on your server reads the tables and serves them; the page\nopens them. A foreign key becomes a link with a field in the other table\nthat links back, a pairing table a link to many records, and a text column\nthat repeats a few values a single select with a color per value\n([what it reads](./base/quick-start.md#what-it-reads-from-your-database)).\n\n```ts\n// src/routes/api/base/+server.ts\nimport { createBaseEndpoint } from '@svgrid/enterprise/base'\n\n// Your database driver: run parameterized SQL, return the rows.\ndeclare function query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>\n\nexport const { GET, POST } = createBaseEndpoint({ execute: query })\n```\n\n```svelte\n<!-- src/routes/base/+page.svelte (with `export const ssr = false` in +page.ts) -->\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, baseFromEndpoint, enableBase } from '@svgrid/enterprise/base'\n\n enableBase()\n const tables = baseFromEndpoint('/api/base')\n</script>\n\n{#await tables then tables}\n <SvBase {tables} editable sortable columnAdder fieldMenu />\n{/await}\n<SvToaster />\n```\n\n[Build a base on Postgres](./base/postgres.md) is the same thing end to\nend, and [From a database to an app](./base/quick-start.md) covers MySQL,\nSQLite and Supabase.\n\n## 4. Set the field types and views\n\nThe base guesses the types from the columns. Fix the ones it cannot know\n(a percent, a rating, a user, a formula) and recreate the views you used:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst views: FieldView[] = [\n { id: 'all', name: 'All tasks', type: 'grid', color: { mode: 'field', field: 'status' } },\n { id: 'board', name: 'Board', type: 'kanban', stackBy: 'status' },\n { id: 'due', name: 'Due dates', type: 'calendar', dateField: 'due' },\n { id: 'request', name: 'Request a task', type: 'form' },\n]\n```\n\nWhat you change in the app (field types, views, colors) comes back through\n`onTablesChange`; store it and start from it next time. The records stay in\nyour database either way.\n\n## 5. Rebuild the automations\n\nOpen **Automations** in the view bar. The triggers you know are there: a\nrecord is created, a record changes, a record matches a condition, a form\nis sent, a button is pressed, a scheduled time. The actions update the\nrecord, create a record in any table, show a notice, color the record,\ncall a webhook or send an email. An Airtable script that calls an API\nbecomes a webhook action, or an action you register in code with\n`registerAutomationAction`.\n\nAutomations that must run whoever made the change, or that hold secrets,\nrun on your server with `createAutomationServer`; see\n[Automations on the server](./base/automations.md#on-the-server).\n\n## 6. Users, permissions and comments\n\nYour app's login replaces Airtable collaborators. List the people for user\nfields with `setFieldUsers`, say who is signed in with `setCurrentUser`\n(created by and last modified by read it), and decide who may read or write\nwhat in the endpoint's `authorize`, or with row level security on Supabase.\nComments go through `setRecordComments` to wherever you keep them.\n\n## What you give up\n\n- The hosted service: someone adds `<SvBase>` to a Svelte app and runs the\n database it reads.\n- Interfaces, Omni and the AI credits. The pages around the base are your\n own Svelte pages.\n- Native mobile apps, and the list and inbox views.\n- The permissions screen, sharing links and the long revision history.\n Access rules live in your server or database; the record shows the\n changes made in the session, and the endpoint's `audit` hook can log\n every write.\n\nSvGrid Base is part of the Suite edition of `@svgrid/enterprise` ($999 per\ndeveloper). It runs without a key during an evaluation, with a watermark.\n\n## See also\n\n- [SvGrid vs Airtable](https://svgrid.com/compare/airtable/): the side-by-side comparison with sources.\n- [Build a project tracker](./base/start.md): SvGrid Base step by step.\n- [Ready-to-use bases](./base/templates.md): a CRM, a content calendar, a roadmap and more.\n- [Field types](./fields.md): every type and its properties.\n"
5891
6034
  },
5892
6035
  {
5893
6036
  "slug": "help/migrating-from-baserow",
@@ -5901,49 +6044,49 @@ export const docs = [
5901
6044
  "path": "docs/help/migrating-from-devextreme.md",
5902
6045
  "title": "Migrating from DevExtreme DataGrid (DevExpress)",
5903
6046
  "section": "Help",
5904
- "markdown": "# Migrating from DevExtreme DataGrid (DevExpress)\n\nDevExtreme DataGrid is a deep, commercial multi-framework grid from\nDevExpress (jQuery, React, Vue, Angular). Moving to SvGrid trades the\ncommercial suite for a Svelte-5-native grid with an MIT core and a far\nlower-cost paid tier.\n\n> Estimated effort: **3-6 hours** per grid.\n>\n> DevExtreme's option names vary by framework flavour; map your version's\n> columns and events onto the SvGrid equivalents below.\n\n<!-- facts:start devextreme-datagrid -->\n> **Facts, checked 12 Sep 2026.** `devextreme` 26.1.4, Commercial (see licence file), last published 7 Aug 2026, 1,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). DevExtreme DataGrid pricing, as its site states it: js.devexpress.com lists DevExtreme Complete at $899.99 per developer for a 12-month subscription with updates and support, renewing at $449.99; no free or non-commercial tier is shown (https://js.devexpress.com/Buy/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs DevExtreme DataGrid (DevExpress)](https://svgrid.com/compare/devextreme-datagrid/).\n<!-- facts:end -->\n\n## Concept map\n\n| DevExtreme DataGrid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ dataField, caption }]` | `columns: [{ field, header }]` |\n| `cellTemplate` | `cell: (c) => renderSnippet(...)` |\n| `editing: { mode, allowUpdating }` | `enableInlineEditing` + `editorType` |\n| `sorting` / `filterRow` / `headerFilter` | `rowSortingFeature` / `columnFilteringFeature` |\n| `grouping` + `summary` | `columnGroupingFeature` + aggregates |\n| `masterDetail` | `rowExpandingFeature` / master-detail rows |\n| `dataSource` (store / remote) | `data` array or `externalSort/Filter` |\n| `paging` + `pager` | `showPagination` |\n| `export` | `@svgrid/enterprise` export pack |\n| `stateStoring` | persist column state yourself (saved views) |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- $('#grid').dxDataGrid({\n- dataSource: rows,\n- paging: { pageSize: 25 },\n- sorting: { mode: 'multiple' }, filterRow: { visible: true },\n- editing: { mode: 'cell', allowUpdating: true },\n- columns: [\n- { dataField: 'name', caption: 'Name' },\n- { dataField: 'amount', caption: 'Amount', format: 'currency' },\n- ],\n- })\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a multi-framework commercial library.\n- **MIT community core** plus an optional Enterprise pack for export / import /\n pivot / AI.\n- **Much lower-cost paid tier.**\n\n## What to weigh\n\n- DevExtreme has a **larger built-in feature surface** (state storing,\n broad export, a full suite). If you depend on those, factor them in -\n `stateStoring` in particular becomes a saved-views pattern you wire up.\n\n## Frequently asked questions\n\n### How do DevExtreme columns map to SvGrid?\n\n`dataField` becomes `field`, `caption` becomes `header`, and `cellTemplate`\nbecomes a `renderSnippet` cell. Sorting / filtering / grouping move from grid\noptions to registered features.\n\n### Is SvGrid cheaper than DevExtreme?\n\nFor a Svelte stack, yes - the core is MIT and the paid tier is far below\ncommercial-suite pricing. You give up DevExtreme's multi-framework reach and\nsome built-in features like `stateStoring`.\n\n### Does SvGrid export like DevExtreme?\n\nYes, via the `@svgrid/enterprise` pack: Excel, PDF, CSV, TSV, and HTML export plus a\nprintable view.\n\n## What you end up with\n\nGrouping with totals plus the filter row, the DevExtreme default layout.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} summary groupable sortable filterMode=\"row\" />\n```\n\n## See also\n\n- [SvGrid vs DevExtreme DataGrid](https://svgrid.com/compare/devextreme-datagrid/) - the side-by-side comparison\n- [Saved views](./saved-views.md) - the state-persistence pattern\n- [Data export and printing - Enterprise](./export.md) - the Enterprise export pack\n"
6047
+ "markdown": "# Migrating from DevExtreme DataGrid (DevExpress)\n\nDevExtreme DataGrid is a deep, commercial multi-framework grid from\nDevExpress (jQuery, React, Vue, Angular). Moving to SvGrid trades the\ncommercial suite for a Svelte-5-native grid with an MIT core and a far\nlower-cost paid tier.\n\n> Estimated effort: **3-6 hours** per grid.\n>\n> DevExtreme's option names vary by framework flavour; map your version's\n> columns and events onto the SvGrid equivalents below.\n\n<!-- facts:start devextreme-datagrid -->\n> **Facts, checked 12 Sep 2026.** `devextreme` 26.1.4, Commercial (see licence file), last published 7 Aug 2026, 1,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). DevExtreme DataGrid pricing, as its site states it: js.devexpress.com lists DevExtreme Complete at $899.99 per developer for a 12-month subscription with updates and support, renewing at $449.99; no free or non-commercial tier is shown (https://js.devexpress.com/Buy/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs DevExtreme DataGrid (DevExpress)](https://svgrid.com/compare/devextreme-datagrid/).\n<!-- facts:end -->\n\n## Concept map\n\n| DevExtreme DataGrid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ dataField, caption }]` | `columns: [{ field, header }]` |\n| `cellTemplate` | `cell: (c) => renderSnippet(...)` |\n| `editing: { mode, allowUpdating }` | `enableInlineEditing` + `editorType` |\n| `sorting` / `filterRow` / `headerFilter` | `rowSortingFeature` / `columnFilteringFeature` |\n| `grouping` + `summary` | `columnGroupingFeature` + aggregates |\n| `masterDetail` | `rowExpandingFeature` / master-detail rows |\n| `dataSource` (store / remote) | `data` array or `externalSort/Filter` |\n| `paging` + `pager` | `showPagination` |\n| `export` | `@svgrid/enterprise` export pack |\n| `stateStoring` | persist column state yourself (saved views) |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- $('#grid').dxDataGrid({\n- dataSource: rows,\n- paging: { pageSize: 25 },\n- sorting: { mode: 'multiple' }, filterRow: { visible: true },\n- editing: { mode: 'cell', allowUpdating: true },\n- columns: [\n- { dataField: 'name', caption: 'Name' },\n- { dataField: 'amount', caption: 'Amount', format: 'currency' },\n- ],\n- })\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a multi-framework commercial library.\n- **MIT community core** plus an optional Enterprise pack for export / import /\n pivot / AI.\n- **Much lower-cost paid tier.**\n\n## What to weigh\n\n- DevExtreme has a **larger built-in feature surface** (state storing,\n broad export, a full suite). If you depend on those, factor them in -\n `stateStoring` in particular becomes a saved-views pattern you wire up.\n\n## Frequently asked questions\n\n### How do DevExtreme columns map to SvGrid?\n\n`dataField` becomes `field`, `caption` becomes `header`, and `cellTemplate`\nbecomes a `renderSnippet` cell. Sorting / filtering / grouping move from grid\noptions to registered features.\n\n### Is SvGrid cheaper than DevExtreme?\n\nFor a Svelte stack, yes - the core is MIT and the paid tier is far below\ncommercial-suite pricing. You give up DevExtreme's multi-framework reach and\nsome built-in features like `stateStoring`.\n\n### Does SvGrid export like DevExtreme?\n\nYes, via the `@svgrid/enterprise` pack: Excel, PDF, CSV, TSV, and HTML export plus a\nprintable view.\n\n## What you end up with\n\nGrouping with totals plus the filter row, the DevExtreme default layout.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} summary groupable sortable filterMode=\"row\" />\n```\n\n## See also\n\n- [SvGrid vs DevExtreme DataGrid](https://svgrid.com/compare/devextreme-datagrid/) - the side-by-side comparison\n- [Saved views](./saved-views.md) - the state-persistence pattern\n- [Data export and printing - Enterprise](./export.md) - the Enterprise export pack\n"
5905
6048
  },
5906
6049
  {
5907
6050
  "slug": "help/migrating-from-glide",
5908
6051
  "path": "docs/help/migrating-from-glide.md",
5909
6052
  "title": "Migrating from Glide Data Grid",
5910
6053
  "section": "Help",
5911
- "markdown": "# Migrating from Glide Data Grid\n\nGlide Data Grid is the canvas-rendered, ultra-high-performance choice\nfor very wide datasets (100k+ rows, 100+ columns). Sv-grid renders to\nDOM with virtualization, which trades peak FPS for\naccessibility + standards-compliant HTML.\n\n> Estimated effort: **3-6 hours** per grid. Glide's getCellContent /\n> onCellEdited cell-data model is the opposite of sv-grid's\n> data-array model; the mental flip takes the most time.\n\n<!-- facts:start glide-data-grid -->\n> **Facts, checked 12 Sep 2026.** `@glideapps/glide-data-grid` 6.0.3, MIT, last published 3 Feb 2024, 1,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `@glideapps/glide-data-grid` 6.0.3 71.1 KB JS + 0.2 KB CSS, lodash + marked + react + react-dom + react-responsive-carousel external (measured 12 Sep 2026). Glide Data Grid pricing, as its site states it: Glide Data Grid is MIT and, in its own words, fully free and open source; no licence is sold for the grid (https://grid.glideapps.com/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/).\n<!-- facts:end -->\n\n## Mental-model flip\n\nGlide gives you a **canvas + a `getCellContent` callback**: the grid\nasks you for each visible cell on demand. Sv-grid wants the\n**whole data array up front** (`<SvGrid data={rows}>`); the engine\nslices for virtualization.\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- function getCellContent([col, row]) {\n- const r = rows[row]\n- if (col === 0) return { kind: 'text', data: r.name, displayData: r.name, allowOverlay: true }\n- if (col === 1) return { kind: 'number', data: r.amount, displayData: fmt(r.amount), allowOverlay: true }\n- }\n- <DataEditor columns={[...]} getCellContent={getCellContent} rows={rows.length} />\n\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name', editorType: 'text' },\n+ { field: 'amount', header: 'Amount', editorType: 'number',\n+ format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nThis change is **good** for 99% of apps: it's less code, less risk\nof typos in cell coordinates, full TypeScript type checking on the\nrow shape. For the 1% of apps with rows that don't fit in memory,\nsee \"Out-of-memory data\" below.\n\n## Cell editing\n\n```diff\n- function onCellEdited([col, row], newValue) {\n- rows[row] = { ...rows[row], [colToField(col)]: newValue.data }\n- }\n- <DataEditor onCellEdited={onCellEdited} />\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ onCellValueChange={(e) => {\n+ rows[e.rowIndex] = { ...rows[e.rowIndex], [e.columnId]: e.newValue }\n+ }}\n+ />\n```\n\nYou can also rely on sv-grid's built-in write-back if `data` is a\nSvelte 5 `$state` array - mutations propagate automatically.\n\n## Sorting + filtering\n\nGlide doesn't ship sort / filter UI; you wrap your own. Sv-grid\nships them:\n\n```diff\n- // Build your own sort buttons in the toolbar; sort rows yourself.\n\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ <SvGrid data={rows} columns={columns} features={features} filterMode=\"menu\" />\n```\n\n## Frozen columns / row markers\n\n| Glide | sv-grid |\n| -------------------------------------- | --------------------------------------------- |\n| `freezeColumns={1}` | `api.setColumnPinning({ left: ['firstColId'] })` |\n| `rowMarkers=\"number\"` | `showRowNumbers={true}` prop |\n| `rowMarkers=\"checkbox\"` | `selectionMode=\"row\"` prop |\n\n## Custom drawing → custom snippets\n\nGlide's `drawCustomCell` lets you render anything via canvas. The\nsv-grid equivalent is a Svelte snippet (DOM):\n\n```diff\n- drawCustomCell(args) {\n- const ctx = args.ctx\n- ctx.fillStyle = args.cell.data.color\n- ctx.fillRect(args.rect.x, args.rect.y, args.rect.width, args.rect.height)\n- return true\n- }\n\n+ {\n+ field: 'color',\n+ cell: (ctx) => renderSnippet(ColorChip, { color: ctx.row.original.color }),\n+ }\n```\n\n```svelte\n{#snippet ColorChip(props)}\n <span style=\"display: inline-block; width: 18px; height: 18px; background: {props.color};\"></span>\n{/snippet}\n```\n\n## Out-of-memory data\n\nFor \"10M rows, fetched on scroll\" workloads (the only case Glide\ngenuinely beats sv-grid on), use sv-grid's\n[server-side / infinite-scroll pattern](./server-side-data.md):\n\n```svelte\n<SvGrid\n data={loadedSlice}\n columns={columns} features={features}\n externalSort={true}\n externalFilter={true}\n onSortingChange={async (s) => { loadedSlice = await fetchPage({ sort: s, offset: 0, limit: 200 }) }}\n/>\n```\n\nYou'll cap practical perf at ~100k rendered rows; for true 10M+\ndatasets Glide's canvas approach has a perf edge sv-grid won't\nmatch. Most apps don't need 10M rows on screen at once - they need\nfast server-side filtering, which both libraries support equally.\n\n## Theming\n\nGlide: huge `theme` prop object. Sv-grid: CSS custom properties (`--sg-*`).\n\n```diff\n- <DataEditor theme={{\n- accentColor: '#4F5DFF',\n- accentLight: 'rgba(62, 116, 253, 0.2)',\n- bgCell: '#1c1c20',\n- /* …40 more properties… */\n- }} />\n\n+ <div style=\"--sg-accent: #4F5DFF; --sg-bg: #1c1c20;\">\n+ <SvGrid {data} {columns} features={features} />\n+ </div>\n```\n\nSee [design tokens](./tokens.md) for the full list (≤ 30 tokens\ncovers everything; Glide's theme has ~40).\n\n## What you get for free vs Glide\n\n- **Accessibility.** Glide's canvas is invisible to screen readers\n unless you build an off-screen ARIA buffer. Sv-grid is WAI-ARIA\n 1.2 grid pattern out of the box; demo 17 covers axe-core CI.\n- **Standard HTML.** SEO crawlers, browser Find-in-Page, browser\n zoom, OS-level text scaling - all work because the grid emits\n actual `<table><tr><td>`.\n- **Familiar editing.** Browser-native `<input>` / `<select>` for\n cells, with autofill / clipboard / autocorrect intact.\n- **Built-in sort / filter / pagination UI.**\n\n## What you give up\n\n- **Peak FPS on >200k visible rows.** Canvas wins here. For most\n apps the gap is invisible; if you've actually measured it on real\n hardware and need the FPS, Glide remains the right call.\n- **Per-pixel cell drawing.** DOM cells are sub-pixel-uniform but\n not arbitrarily drawn.\n\n## Frequently asked questions\n\n### Should I move from Glide Data Grid to SvGrid?\n\nMove if you need accessibility, standards-compliant HTML, SEO-friendly markup,\nor DOM-based custom cells. Stay on Glide only if you have measured a need for\npeak canvas FPS on 200k+ simultaneously visible rows. For most apps the\nperformance gap is invisible, and SvGrid virtualizes comfortably to 100k+ rows.\n\n### How long does a Glide migration take?\n\nAbout 3-6 hours per grid. The biggest shift is conceptual: Glide's\n`getCellContent` / `onCellEdited` cell-data model is the inverse of SvGrid's\nplain data-array model, so the mental flip takes the most time, not the code.\n\n### Does SvGrid render to canvas or DOM?\n\nDOM, with row and column virtualization. That is what gives you WAI-ARIA roles,\nkeyboard navigation, screen-reader support, and selectable/indexable text -\nthings a canvas grid like Glide cannot offer.\n\n## What you end up with\n\nInline editing over a virtualized body, without a canvas to draw into.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection sortable />\n```\n\n## See also\n\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/) - the side-by-side comparison\n- [Performance benchmarks](./benchmarks.md) - measured numbers\n- [Server-side data](./server-side-data.md) - the >100k-row pattern\n- [Accessibility](./accessibility.md) - the standards compliance Glide doesn't ship\n"
6054
+ "markdown": "# Migrating from Glide Data Grid\n\nGlide Data Grid is the canvas-rendered, ultra-high-performance choice\nfor very wide datasets (100k+ rows, 100+ columns). Sv-grid renders to\nDOM with virtualization, which trades peak FPS for\naccessibility + standards-compliant HTML.\n\n> Estimated effort: **3-6 hours** per grid. Glide's getCellContent /\n> onCellEdited cell-data model is the opposite of sv-grid's\n> data-array model; the mental flip takes the most time.\n\n<!-- facts:start glide-data-grid -->\n> **Facts, checked 12 Sep 2026.** `@glideapps/glide-data-grid` 6.0.3, MIT, last published 3 Feb 2024, 1,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `@glideapps/glide-data-grid` 6.0.3 71.1 KB JS + 0.2 KB CSS, lodash + marked + react + react-dom + react-responsive-carousel external (measured 12 Sep 2026). Glide Data Grid pricing, as its site states it: Glide Data Grid is MIT and, in its own words, fully free and open source; no licence is sold for the grid (https://grid.glideapps.com/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/).\n<!-- facts:end -->\n\n## Mental-model flip\n\nGlide gives you a **canvas + a `getCellContent` callback**: the grid\nasks you for each visible cell on demand. Sv-grid wants the\n**whole data array up front** (`<SvGrid data={rows}>`); the engine\nslices for virtualization.\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- function getCellContent([col, row]) {\n- const r = rows[row]\n- if (col === 0) return { kind: 'text', data: r.name, displayData: r.name, allowOverlay: true }\n- if (col === 1) return { kind: 'number', data: r.amount, displayData: fmt(r.amount), allowOverlay: true }\n- }\n- <DataEditor columns={[...]} getCellContent={getCellContent} rows={rows.length} />\n\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name', editorType: 'text' },\n+ { field: 'amount', header: 'Amount', editorType: 'number',\n+ format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nThis change is **good** for 99% of apps: it's less code, less risk\nof typos in cell coordinates, full TypeScript type checking on the\nrow shape. For the 1% of apps with rows that don't fit in memory,\nsee \"Out-of-memory data\" below.\n\n## Cell editing\n\n```diff\n- function onCellEdited([col, row], newValue) {\n- rows[row] = { ...rows[row], [colToField(col)]: newValue.data }\n- }\n- <DataEditor onCellEdited={onCellEdited} />\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ onCellValueChange={(e) => {\n+ rows[e.rowIndex] = { ...rows[e.rowIndex], [e.columnId]: e.newValue }\n+ }}\n+ />\n```\n\nYou can also rely on sv-grid's built-in write-back if `data` is a\nSvelte 5 `$state` array - mutations propagate automatically.\n\n## Sorting + filtering\n\nGlide doesn't ship sort / filter UI; you wrap your own. Sv-grid\nships them:\n\n```diff\n- // Build your own sort buttons in the toolbar; sort rows yourself.\n\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ <SvGrid data={rows} columns={columns} features={features} filterMode=\"menu\" />\n```\n\n## Frozen columns / row markers\n\n| Glide | sv-grid |\n| -------------------------------------- | --------------------------------------------- |\n| `freezeColumns={1}` | `api.setColumnPinning({ left: ['firstColId'] })` |\n| `rowMarkers=\"number\"` | `showRowNumbers={true}` prop |\n| `rowMarkers=\"checkbox\"` | `selectionMode=\"row\"` prop |\n\n## Custom drawing → custom snippets\n\nGlide's `drawCustomCell` lets you render anything via canvas. The\nsv-grid equivalent is a Svelte snippet (DOM):\n\n```diff\n- drawCustomCell(args) {\n- const ctx = args.ctx\n- ctx.fillStyle = args.cell.data.color\n- ctx.fillRect(args.rect.x, args.rect.y, args.rect.width, args.rect.height)\n- return true\n- }\n\n+ {\n+ field: 'color',\n+ cell: (ctx) => renderSnippet(ColorChip, { color: ctx.row.original.color }),\n+ }\n```\n\n```svelte\n{#snippet ColorChip(props)}\n <span style=\"display: inline-block; width: 18px; height: 18px; background: {props.color};\"></span>\n{/snippet}\n```\n\n## Out-of-memory data\n\nFor \"10M rows, fetched on scroll\" workloads (the only case Glide\ngenuinely beats sv-grid on), use sv-grid's\n[server-side / infinite-scroll pattern](./server-side-data.md):\n\n```svelte\n<SvGrid\n data={loadedSlice}\n columns={columns} features={features}\n externalSort={true}\n externalFilter={true}\n onSortingChange={async (s) => { loadedSlice = await fetchPage({ sort: s, offset: 0, limit: 200 }) }}\n/>\n```\n\nYou'll cap practical perf at ~100k rendered rows; for true 10M+\ndatasets Glide's canvas approach has a perf edge sv-grid won't\nmatch. Most apps don't need 10M rows on screen at once - they need\nfast server-side filtering, which both libraries support equally.\n\n## Theming\n\nGlide: huge `theme` prop object. Sv-grid: CSS custom properties (`--sg-*`).\n\n```diff\n- <DataEditor theme={{\n- accentColor: '#4F5DFF',\n- accentLight: 'rgba(62, 116, 253, 0.2)',\n- bgCell: '#1c1c20',\n- /* …40 more properties… */\n- }} />\n\n+ <div style=\"--sg-accent: #4F5DFF; --sg-bg: #1c1c20;\">\n+ <SvGrid {data} {columns} features={features} />\n+ </div>\n```\n\nSee [design tokens](./tokens.md) for the full list (≤ 30 tokens\ncovers everything; Glide's theme has ~40).\n\n## What you get for free vs Glide\n\n- **Accessibility.** Glide's canvas is invisible to screen readers\n unless you build an off-screen ARIA buffer. Sv-grid is WAI-ARIA\n 1.2 grid pattern out of the box; demo 17 covers axe-core CI.\n- **Standard HTML.** SEO crawlers, browser Find-in-Page, browser\n zoom, OS-level text scaling - all work because the grid emits\n actual `<table><tr><td>`.\n- **Familiar editing.** Browser-native `<input>` / `<select>` for\n cells, with autofill / clipboard / autocorrect intact.\n- **Built-in sort / filter / pagination UI.**\n\n## What you give up\n\n- **Peak FPS on >200k visible rows.** Canvas wins here. For most\n apps the gap is invisible; if you've actually measured it on real\n hardware and need the FPS, Glide remains the right call.\n- **Per-pixel cell drawing.** DOM cells are sub-pixel-uniform but\n not arbitrarily drawn.\n\n## Frequently asked questions\n\n### Should I move from Glide Data Grid to SvGrid?\n\nMove if you need accessibility, standards-compliant HTML, SEO-friendly markup,\nor DOM-based custom cells. Stay on Glide only if you have measured a need for\npeak canvas FPS on 200k+ simultaneously visible rows. For most apps the\nperformance gap is invisible, and SvGrid virtualizes comfortably to 100k+ rows.\n\n### How long does a Glide migration take?\n\nAbout 3-6 hours per grid. The biggest shift is conceptual: Glide's\n`getCellContent` / `onCellEdited` cell-data model is the inverse of SvGrid's\nplain data-array model, so the mental flip takes the most time, not the code.\n\n### Does SvGrid render to canvas or DOM?\n\nDOM, with row and column virtualization. That is what gives you WAI-ARIA roles,\nkeyboard navigation, screen-reader support, and selectable/indexable text -\nthings a canvas grid like Glide cannot offer.\n\n## What you end up with\n\nInline editing over a virtualized body, without a canvas to draw into.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection sortable />\n```\n\n## See also\n\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/) - the side-by-side comparison\n- [Performance benchmarks](./benchmarks.md) - measured numbers\n- [Server-side data](./server-side-data.md) - the >100k-row pattern\n- [Accessibility](./accessibility.md) - the standards compliance Glide doesn't ship\n"
5912
6055
  },
5913
6056
  {
5914
6057
  "slug": "help/migrating-from-gridjs",
5915
6058
  "path": "docs/help/migrating-from-gridjs.md",
5916
6059
  "title": "Migrating from Grid.js",
5917
6060
  "section": "Help",
5918
- "markdown": "# Migrating from Grid.js\n\nGrid.js is a small vanilla-JS table for search, sort, and pagination\nthat you render into a DOM element. SvGrid does the same in a\nSvelte-5-native component and keeps going - virtualization, Excel-style\nfilters, editing, grouping - when you outgrow the basics.\n\n> Estimated effort: **30 min - 1 hour** per table.\n\n<!-- facts:start gridjs -->\n> **Facts, checked 12 Sep 2026.** `gridjs` 6.2.0, MIT, last published 3 Mar 2024, 161,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `gridjs` 6.2.0 17.8 KB JS + 2.4 KB CSS (measured 12 Sep 2026). Grid.js pricing, as its site states it: Grid.js is MIT, free and open source; no licence is sold (https://gridjs.io/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Grid.js | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `new Grid({ ... }).render(el)` | `<SvGrid ... />` |\n| `columns: ['Name', 'Amount']` | `columns: [{ field, header }]` |\n| `columns: [{ name, formatter }]` | `{ header, cell: (c) => renderSnippet(...) }` |\n| `sort: true` | `rowSortingFeature` |\n| `search: true` | `api.setState({ globalFilter: query })` / filter feature |\n| `pagination: { limit: 25 }` | `showPagination` (+ page size) |\n| `server: { url, then }` | `externalSort` / `externalFilter` + refetch |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { Grid } from 'gridjs'\n- import 'gridjs/dist/theme/mermaid.css'\n-\n- new Grid({\n- data: rows,\n- columns: ['Name', 'Amount'],\n- sort: true, search: true,\n- pagination: { limit: 25 },\n- }).render(document.getElementById('grid'))\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What you gain\n\n- **Virtualization** for large datasets (Grid.js renders the page).\n- **Excel-style filter menu**, **inline editing**, **grouping**, and\n **tree / master-detail** when you need them.\n- **Reactive data** - no `.render(el)` re-instantiation.\n- A **headless engine** and an **imperative API** plus `@svgrid/mcp`.\n\n## Frequently asked questions\n\n### When should I move from Grid.js to SvGrid?\n\nWhen you need more than search / sort / paginate - virtualization for big\ndatasets, inline editing, Excel-style filters, grouping, or tree data. For a\nsmall table, Grid.js stays lighter.\n\n### Is SvGrid MIT-licensed like Grid.js?\n\nYes. `@svgrid/grid` is MIT. Only the optional `@svgrid/enterprise` add-on is paid.\n\n### Does SvGrid support server-side data like Grid.js?\n\nYes. Set `externalSort` / `externalFilter` and refetch on the\n`onSortingChange` / `onFiltersChange` events.\n\n## What you end up with\n\nSearch, sort and pagination - the whole Grid.js surface, plus editing.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} editable />\n```\n\n## See also\n\n- [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/) - the side-by-side comparison\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n- [Server-side data](./server-side-data.md) - the external-data pattern\n"
6061
+ "markdown": "# Migrating from Grid.js\n\nGrid.js is a small vanilla-JS table for search, sort, and pagination\nthat you render into a DOM element. SvGrid does the same in a\nSvelte-5-native component and keeps going - virtualization, Excel-style\nfilters, editing, grouping - when you outgrow the basics.\n\n> Estimated effort: **30 min - 1 hour** per table.\n\n<!-- facts:start gridjs -->\n> **Facts, checked 12 Sep 2026.** `gridjs` 6.2.0, MIT, last published 3 Mar 2024, 161,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `gridjs` 6.2.0 17.8 KB JS + 2.4 KB CSS (measured 12 Sep 2026). Grid.js pricing, as its site states it: Grid.js is MIT, free and open source; no licence is sold (https://gridjs.io/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Grid.js | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `new Grid({ ... }).render(el)` | `<SvGrid ... />` |\n| `columns: ['Name', 'Amount']` | `columns: [{ field, header }]` |\n| `columns: [{ name, formatter }]` | `{ header, cell: (c) => renderSnippet(...) }` |\n| `sort: true` | `rowSortingFeature` |\n| `search: true` | `api.setState({ globalFilter: query })` / filter feature |\n| `pagination: { limit: 25 }` | `showPagination` (+ page size) |\n| `server: { url, then }` | `externalSort` / `externalFilter` + refetch |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { Grid } from 'gridjs'\n- import 'gridjs/dist/theme/mermaid.css'\n-\n- new Grid({\n- data: rows,\n- columns: ['Name', 'Amount'],\n- sort: true, search: true,\n- pagination: { limit: 25 },\n- }).render(document.getElementById('grid'))\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What you gain\n\n- **Virtualization** for large datasets (Grid.js renders the page).\n- **Excel-style filter menu**, **inline editing**, **grouping**, and\n **tree / master-detail** when you need them.\n- **Reactive data** - no `.render(el)` re-instantiation.\n- A **headless engine** and an **imperative API** plus `@svgrid/mcp`.\n\n## Frequently asked questions\n\n### When should I move from Grid.js to SvGrid?\n\nWhen you need more than search / sort / paginate - virtualization for big\ndatasets, inline editing, Excel-style filters, grouping, or tree data. For a\nsmall table, Grid.js stays lighter.\n\n### Is SvGrid MIT-licensed like Grid.js?\n\nYes. `@svgrid/grid` is MIT. Only the optional `@svgrid/enterprise` add-on is paid.\n\n### Does SvGrid support server-side data like Grid.js?\n\nYes. Set `externalSort` / `externalFilter` and refetch on the\n`onSortingChange` / `onFiltersChange` events.\n\n## What you end up with\n\nSearch, sort and pagination - the whole Grid.js surface, plus editing.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} editable />\n```\n\n## See also\n\n- [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/) - the side-by-side comparison\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n- [Server-side data](./server-side-data.md) - the external-data pattern\n"
5919
6062
  },
5920
6063
  {
5921
6064
  "slug": "help/migrating-from-handsontable",
5922
6065
  "path": "docs/help/migrating-from-handsontable.md",
5923
6066
  "title": "Migrating from Handsontable",
5924
6067
  "section": "Help",
5925
- "markdown": "# Migrating from Handsontable\n\nHandsontable's mental model is \"spreadsheet-in-a-page\": every cell\neditable, formulas, copy/paste with the OS clipboard, frozen rows\nand columns. Sv-grid covers ~90% of the same surface; the port is\nmostly a configuration translation, except for HyperFormula (see\nthe Formulas section below).\n\n> Estimated effort: **2-4 hours** per grid for typical spreadsheet\n> workflows. **Add 1-2 days** if you depend heavily on\n> HyperFormula features sv-grid doesn't ship.\n\n<!-- facts:start handsontable -->\n> **Facts, checked 12 Sep 2026.** `handsontable` 18.1.0, Commercial (see licence file), last published 1 Sep 2026, 1,190,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). Handsontable pricing, as its site states it: Handsontable's Hobby licence is free for personal, exploratory projects and cannot be used in commercial settings; handsontable.com lists Standard from $999 per developer and Priority from $1,299 per developer, with Enterprise on custom terms (https://handsontable.com/pricing, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/).\n<!-- facts:end -->\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import Handsontable from 'handsontable'\n- import 'handsontable/dist/handsontable.full.min.css'\n\n+ import {\n+ SvGrid, tableFeatures,\n+ rowSortingFeature, columnFilteringFeature, rowSelectionFeature,\n+ + } from '@svgrid/grid'\n```\n\n## Schema → columns\n\nHandsontable accepts a 2D array OR an array of objects. Sv-grid\nexpects the array-of-objects form:\n\n```diff\n- const hot = new Handsontable(container, {\n- data: [\n- ['Tesla', 2017, 'black', false],\n- ['Nissan', 2018, 'blue', true ],\n- ],\n- colHeaders: ['Make', 'Year', 'Color', 'In stock'],\n- columns: [\n- {},\n- { type: 'numeric' },\n- {},\n- { type: 'checkbox' },\n- ],\n- })\n\n+ type Car = { make: string; year: number; color: string; inStock: boolean }\n+ const rows: Car[] = [\n+ { make: 'Tesla', year: 2017, color: 'black', inStock: false },\n+ { make: 'Nissan', year: 2018, color: 'blue', inStock: true },\n+ ]\n+ const columns: ColumnDef<typeof features, Car>[] = [\n+ { field: 'make', header: 'Make' },\n+ { field: 'year', header: 'Year', editorType: 'number' },\n+ { field: 'color', header: 'Color' },\n+ { field: 'inStock', header: 'In stock', editorType: 'checkbox' },\n+ ]\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nIf your existing data is a 2D array, transform once at boot:\n\n```ts\nconst headerRow = raw[0]\nconst rows = raw.slice(1).map((cells) =>\n Object.fromEntries(cells.map((v, i) => [headerRow[i], v])),\n)\n```\n\n## Editor types\n\n| Handsontable | sv-grid |\n| ---------------------------------------------- | ------------------------------------------------ |\n| `type: 'text'` | `editorType: 'text'` |\n| `type: 'numeric'` | `editorType: 'number'` |\n| `type: 'date'` | `editorType: 'date'` |\n| `type: 'checkbox'` | `editorType: 'checkbox'` |\n| `type: 'dropdown', source: [...]` | `editorType: 'list', editorOptions: [...]` |\n| `type: 'autocomplete'` | `editorType: 'list'` (combobox UI ships) |\n| `type: 'time'` | `editorType: 'time'` |\n| `type: 'password'` | Use `editorType: 'text'` + a custom snippet |\n\n## Selection + clipboard\n\n| Handsontable | sv-grid |\n| --------------------------------------- | ------------------------------------------------------- |\n| `selectCells([[0,0,2,5]])` | `api.selectCells(ranges)`, with `selectionMode='cell'` |\n| `getSelected()` | `api.getSelected()`: the same `[[startRow, startCol, endRow, endCol], ...]`, normalised to top-left / bottom-right and `[]` rather than `undefined` when nothing is selected |\n| `getSelectedLast()` | `api.getSelectedLast()`: `[startRow, startCol, endRow, endCol]` with the orientation kept (a range dragged upwards has `startRow > endRow`), or `undefined` |\n| `getSelectedRange()` / `getSelectedRangeLast()` | `api.getSelectedRange()` / `api.getSelectedRangeLast()`: `{ from, to, highlight }` per rectangle, the same three fields as `CellRange`; plain data rather than a class, so use `Math.min` / `Math.max` for the corners |\n| `copyPaste: true` (default) | Ships built-in; `enableCellSelection={true}`. The spreadsheet shell also exchanges formats, number formats and formulas with Excel and Google Sheets through the HTML clipboard |\n| `fillHandle: true` | Ships built-in (drag-to-fill on selected range) |\n| `moveCells: true` | `moveCells` - drag the range border to move it, Ctrl / Cmd to copy. On by default; see [move or copy a range](./editing/move-cells.md) |\n\n## Frozen rows / columns\n\n| Handsontable | sv-grid |\n| ---------------------------------- | ------------------------------------------------------ |\n| `fixedColumnsStart: 2` | `api.setColumnPinning({ left: ['firstColId', 'secondColId'] })` |\n| `fixedRowsTop: 1` | `pinnedTopRows` (and `pinnedBottomRows`) |\n| `manualColumnFreeze: true` | Ships via the column-header right-click menu |\n| `mergeCells: [{ row, col, rowspan, colspan }]` | `mergedCells={[{ rowIndex, colIndex, rowSpan, colSpan }]}` on `<SvGrid>`; the spreadsheet shell adds Merge & Center, Merge Across, Merge Cells and Unmerge on the ribbon and the cell menu |\n\nFreeze panes on a plain `<SvGrid>`: two pinned columns and the sticky\nletter and number headers, with formulas underneath.\n\n<div data-docs-demo=\"208-freeze-panes\" data-height=\"520\"></div>\n\n## Hooks → callbacks\n\n| Handsontable hook | sv-grid |\n| -------------------------------------- | ------------------------------------------------------- |\n| `afterChange((changes, src) => {})` | `onCellValueChange((e) => {...})` |\n| `afterSelection(...)` | `onActiveCellChange((cell) => {...})` |\n| `afterFilter(...)` | `onFiltersChange((f) => {...})` |\n| `afterColumnSort(...)` | `onSortingChange((s) => {...})` |\n| `beforeChange((changes) => false)` | Throw / return `false` from your inline validator; see [validation](./editing/validation.md) |\n| `afterCreateRow / afterRemoveRow` | Wrap `api.addRow / removeRow` in your own emitter; on the spreadsheet shell, `onChange` reports a `structure` reason with the edit |\n| `afterMergeCells / afterUnmergeCells` | On the spreadsheet shell, `onChange` reports `merges`; `api.getMergedCells()` reads the grid's list |\n| `afterSetCellMeta` (comments, validation) | `onChange` reports `comments`, `validation`, `conditional-formats` and `protection` on the shell |\n| `afterFilter` (the Filters plugin) | `onChange` reports `filter` on the shell; `getState().sheets[name].autoFilter` is the state |\n\nOn the spreadsheet shell (`<SvSheet>` in `@svgrid/enterprise`) one callback\ncovers the lot: `onChange(reasons)` fires once per tick with every kind of\nchange since the last call (`cells`, `formats`, `sizes`, `hidden`,\n`freeze`, `sheets`, `comments`, `protection`, `validation`,\n`conditional-formats`, `merges`, `filter`, `structure` with the insert or\ndelete, `restore`), which is where Handsontable's `afterChange` autosave\ngoes. `getState()` gives the document to save and `setState()` puts it back.\n\n## Cell meta → the sheet document\n\nHandsontable keeps comments, validators, read-only flags and merges as cell\nmeta on the instance. On the spreadsheet shell they are parts of the\ndocument, per sheet, saved with it and moved by inserts and deletes:\n\n| Handsontable | sv-grid spreadsheet shell |\n| --------------------------------------------------- | --------------------------------------------------------------- |\n| `comments: true`, `cell: [{ row, col, comment }]` | Review > New Comment, Shift+F2, the cell menu; `getState().sheets[name].comments` |\n| `validator: 'numeric'`, `allowInvalid: false` | Data > Data Validation (Whole number, Decimal, List, Date, Text length, Custom), Stop or Warning; `validation` in the state |\n| `readOnly: true` on a cell | Format Cells > Protection unlocks the cells that may change, Review > Protect Sheet locks the rest; `locked: false` in the format entry, `protected` per sheet |\n| `mergeCells` | Merge & Center on the ribbon and the cell menu; `merges` in the state |\n| `filters: true` + `dropdownMenu` | Ctrl+Shift+L or Data > Filter: Excel's AutoFilter arrows and menus; `autoFilter` in the state |\n| conditional formatting (a custom renderer) | Home > Styles > Conditional Formatting: Highlight Cells, Top/Bottom, Data Bars, Color Scales, Icon Sets, Manage Rules; `conditionalFormats` in the state |\n| `autofill` rules | The fill handle's own series: numbers, dates by day or by the set gap, `Item 1`, weekdays and months |\n\nOn a plain `<SvGrid>` the free grid has the primitives instead: `notes`\nand `editableComments` for comments, `editable` and `valueParser` on a\ncolumn for read-only cells and validation, `mergedCells` for merges, the\nfilter row and its Excel-style menu for filtering, and value-driven\n`conditionalFormats` by column.\n\n## Formulas (HyperFormula)\n\nSv-grid ships a focused subset under\n[`spreadsheet-formulas`](./spreadsheet-formulas.md) (SUM, IF, COUNTIF\n+ cell refs + ranges + cycle detection). It does NOT ship the full\nHyperFormula library.\n\nIf you need HyperFormula's full surface (~400 functions, complex\ndate math, R1C1 refs), the integration pattern is:\n\n```ts\nimport { HyperFormula } from 'hyperformula'\n\nconst hf = HyperFormula.buildFromArray(rowsAsMatrix, { licenseKey: 'gpl-v3' })\n\n// On every cell edit, push to HF + read back the computed value:\nfunction onCellValueChange(e) {\n hf.setCellContents({ sheet: 0, row: e.rowIndex, col: columnIndex }, e.newValue)\n // ...read computed cells you depend on + push back via api.setCellValue\n}\n```\n\nThis is the only piece where the swap isn't 1:1. Most teams find\nsv-grid's shipped subset covers 80% of real-world formula usage; if\nyours is in the 20%, HyperFormula plugs in with the pattern above.\n\n## Licence\n\nHandsontable's grid needs a commercial licence for commercial use; its free\nHobby licence is for personal, exploratory projects, as its pricing page\nstates (the wording and the date are in the facts box at the top of this\npage). Sv-grid's `@svgrid/grid` is MIT with no licence key, and the\n[Enterprise tier](../enterprise/licensing.md) needs no key to evaluate:\nit works without one and displays a watermark and a console\nmessage until you add one, so there is no cutoff to plan around.\n\n## What you get for free vs Handsontable\n\n- **No commercial licence for the grid.** @svgrid/grid is MIT.\n- **Modern Svelte 5 ergonomics.** `$state` arrays beat\n `loadData(...)`.\n- **Grid features a spreadsheet does not have.** Row grouping with\n aggregation, master/detail, server-side data (grouping, tree, pivot and transactions on the server are Enterprise) and integrated\n charts in the same package.\n- **CSP-clean.** Handsontable's HyperFormula path needs CSP `eval`\n exceptions in some configurations.\n\n## What you give up\n\n- **Full HyperFormula surface as a supported feature.** Sv-grid ships a\n subset and lets you wire HyperFormula yourself; see above.\n- **Nested headers.** Handsontable's `nestedHeaders` have no\n counterpart beyond column groups.\n- **Threaded comments and a validation Input Message.** Comments on the\n shell are Excel's notes, one text per cell; validation shows its message\n on a refusal, not on arrival.\n- **Excel export without a paid pack.** Handsontable's export plugin writes\n XLSX through its asynchronous method; on sv-grid, CSV, TSV and JSON export\n are free and Excel, PDF and print output are in `@svgrid/enterprise`.\n\n## Frequently asked questions\n\n### Can SvGrid replace Handsontable's spreadsheet features?\n\nIt covers roughly 90% of the surface - inline editing on every cell, copy/paste\nas TSV, range selection, column groups, and a built-in formula engine. Budget\n2-4 hours per grid for typical spreadsheet workflows, plus 1-2 days if you lean\nheavily on the full HyperFormula function set.\n\n### Does SvGrid support formulas like Handsontable?\n\nYes, a built-in formula engine with cell references, ranges, and common\nfunctions (see the spreadsheet-formulas guide and demo 27). It is a practical\nsubset rather than the complete HyperFormula library, so verify your specific\nfunctions before porting.\n\n### Is SvGrid licensed like Handsontable?\n\nNo. The `@svgrid/grid` core is MIT and free for commercial use - no per-seat\nlicence key - whereas Handsontable's free licence excludes commercial use and\nits commercial plans are per developer; the facts box has the statement as\nread from handsontable.com. The optional `@svgrid/enterprise` pack (Excel and\nPDF export, print, pivot, import) is priced per developer.\n\n### Does SvGrid have a blank spreadsheet like Handsontable?\n\nYes, on the plain grid: column-letter headers, a row gutter, a name box\nand formula bar, gridlines, range selection and a fill handle, with\nHyperFormula underneath when you want its function library.\n\n<div data-docs-demo=\"207-blank-sheet\" data-height=\"560\"></div>\n\n## What you end up with\n\nSpreadsheet behaviour: inline edit, drag a cell range, copy it out as TSV.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection statusBar />\n```\n\n## See also\n\n- [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/) - the side-by-side comparison, with a source and date for every claim\n- [Spreadsheet formulas](./spreadsheet-formulas.md) - sv-grid's\n built-in formula engine, and the rest of the spreadsheet demos\n- [Demo 27 (Spreadsheet + Ribbon)](https://svgrid.com/demos/27-spreadsheet-ribbon/) - live\n- [Migrating from AG Grid](./migrating-from-ag-grid.md)\n"
6068
+ "markdown": "# Migrating from Handsontable\n\nHandsontable's mental model is \"spreadsheet-in-a-page\": every cell\neditable, formulas, copy/paste with the OS clipboard, frozen rows\nand columns. Sv-grid covers ~90% of the same surface; the port is\nmostly a configuration translation, except for HyperFormula (see\nthe Formulas section below).\n\n> Estimated effort: **2-4 hours** per grid for typical spreadsheet\n> workflows. **Add 1-2 days** if you depend heavily on\n> HyperFormula features sv-grid doesn't ship.\n\n<!-- facts:start handsontable -->\n> **Facts, checked 12 Sep 2026.** `handsontable` 18.1.0, Commercial (see licence file), last published 1 Sep 2026, 1,190,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). Handsontable pricing, as its site states it: Handsontable's Hobby licence is free for personal, exploratory projects and cannot be used in commercial settings; handsontable.com lists Standard from $999 per developer and Priority from $1,299 per developer, with Enterprise on custom terms (https://handsontable.com/pricing, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/).\n<!-- facts:end -->\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import Handsontable from 'handsontable'\n- import 'handsontable/dist/handsontable.full.min.css'\n\n+ import {\n+ SvGrid, tableFeatures,\n+ rowSortingFeature, columnFilteringFeature, rowSelectionFeature,\n+ + } from '@svgrid/grid'\n```\n\n## Schema → columns\n\nHandsontable accepts a 2D array OR an array of objects. Sv-grid\nexpects the array-of-objects form:\n\n```diff\n- const hot = new Handsontable(container, {\n- data: [\n- ['Tesla', 2017, 'black', false],\n- ['Nissan', 2018, 'blue', true ],\n- ],\n- colHeaders: ['Make', 'Year', 'Color', 'In stock'],\n- columns: [\n- {},\n- { type: 'numeric' },\n- {},\n- { type: 'checkbox' },\n- ],\n- })\n\n+ type Car = { make: string; year: number; color: string; inStock: boolean }\n+ const rows: Car[] = [\n+ { make: 'Tesla', year: 2017, color: 'black', inStock: false },\n+ { make: 'Nissan', year: 2018, color: 'blue', inStock: true },\n+ ]\n+ const columns: ColumnDef<typeof features, Car>[] = [\n+ { field: 'make', header: 'Make' },\n+ { field: 'year', header: 'Year', editorType: 'number' },\n+ { field: 'color', header: 'Color' },\n+ { field: 'inStock', header: 'In stock', editorType: 'checkbox' },\n+ ]\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nIf your existing data is a 2D array, transform once at boot:\n\n```ts\nconst headerRow = raw[0]\nconst rows = raw.slice(1).map((cells) =>\n Object.fromEntries(cells.map((v, i) => [headerRow[i], v])),\n)\n```\n\n## Editor types\n\n| Handsontable | sv-grid |\n| ---------------------------------------------- | ------------------------------------------------ |\n| `type: 'text'` | `editorType: 'text'` |\n| `type: 'numeric'` | `editorType: 'number'` |\n| `type: 'date'` | `editorType: 'date'` |\n| `type: 'checkbox'` | `editorType: 'checkbox'` |\n| `type: 'dropdown', source: [...]` | `editorType: 'list', editorOptions: [...]` |\n| `type: 'autocomplete'` | `editorType: 'list'` (combobox UI ships) |\n| `type: 'time'` | `editorType: 'time'` |\n| `type: 'password'` | Use `editorType: 'text'` + a custom snippet |\n\n## Selection + clipboard\n\n| Handsontable | sv-grid |\n| --------------------------------------- | ------------------------------------------------------- |\n| `selectCells([[0,0,2,5]])` | `api.selectCells(ranges)`, with `selectionMode='cell'` |\n| `getSelected()` | `api.getSelected()`: the same `[[startRow, startCol, endRow, endCol], ...]`, normalised to top-left / bottom-right and `[]` rather than `undefined` when nothing is selected |\n| `getSelectedLast()` | `api.getSelectedLast()`: `[startRow, startCol, endRow, endCol]` with the orientation kept (a range dragged upwards has `startRow > endRow`), or `undefined` |\n| `getSelectedRange()` / `getSelectedRangeLast()` | `api.getSelectedRange()` / `api.getSelectedRangeLast()`: `{ from, to, highlight }` per rectangle, the same three fields as `CellRange`; plain data rather than a class, so use `Math.min` / `Math.max` for the corners |\n| `copyPaste: true` (default) | Ships built-in; `enableCellSelection={true}`. The spreadsheet shell also exchanges formats, number formats and formulas with Excel and Google Sheets through the HTML clipboard |\n| `fillHandle: true` | Ships built-in (drag-to-fill on selected range) |\n| `moveCells: true` | `moveCells` - drag the range border to move it, Ctrl / Cmd to copy. On by default; see [move or copy a range](./editing/move-cells.md) |\n\n## Frozen rows / columns\n\n| Handsontable | sv-grid |\n| ---------------------------------- | ------------------------------------------------------ |\n| `fixedColumnsStart: 2` | `api.setColumnPinning({ left: ['firstColId', 'secondColId'] })` |\n| `fixedRowsTop: 1` | `pinnedTopRows` (and `pinnedBottomRows`) |\n| `manualColumnFreeze: true` | Ships via the column-header right-click menu |\n| `mergeCells: [{ row, col, rowspan, colspan }]` | `mergedCells={[{ rowIndex, colIndex, rowSpan, colSpan }]}` on `<SvGrid>`; the spreadsheet shell adds Merge & Center, Merge Across, Merge Cells and Unmerge on the ribbon and the cell menu |\n\nFreeze panes on a plain `<SvGrid>`: two pinned columns and the sticky\nletter and number headers, with formulas underneath.\n\n<div data-docs-demo=\"208-freeze-panes\" data-height=\"520\"></div>\n\n## Hooks → callbacks\n\n| Handsontable hook | sv-grid |\n| -------------------------------------- | ------------------------------------------------------- |\n| `afterChange((changes, src) => {})` | `onCellValueChange((e) => {...})` |\n| `afterSelection(...)` | `onActiveCellChange((cell) => {...})` |\n| `afterFilter(...)` | `onFiltersChange((f) => {...})` |\n| `afterColumnSort(...)` | `onSortingChange((s) => {...})` |\n| `beforeChange((changes) => false)` | Throw / return `false` from your inline validator; see [validation](./editing/validation.md) |\n| `afterCreateRow / afterRemoveRow` | Wrap `api.addRow / removeRow` in your own emitter; on the spreadsheet shell, `onChange` reports a `structure` reason with the edit |\n| `afterMergeCells / afterUnmergeCells` | On the spreadsheet shell, `onChange` reports `merges`; `api.getMergedCells()` reads the grid's list |\n| `afterSetCellMeta` (comments, validation) | `onChange` reports `comments`, `validation`, `conditional-formats` and `protection` on the shell |\n| `afterFilter` (the Filters plugin) | `onChange` reports `filter` on the shell; `getState().sheets[name].autoFilter` is the state |\n\nOn the spreadsheet shell (`<SvSheet>` in `@svgrid/enterprise`) one callback\ncovers the lot: `onChange(reasons)` fires once per tick with every kind of\nchange since the last call (`cells`, `formats`, `sizes`, `hidden`,\n`freeze`, `sheets`, `comments`, `protection`, `validation`,\n`conditional-formats`, `merges`, `filter`, `structure` with the insert or\ndelete, `restore`), which is where Handsontable's `afterChange` autosave\ngoes. `getState()` gives the document to save and `setState()` puts it back.\n\n## Cell meta → the sheet document\n\nHandsontable keeps comments, validators, read-only flags and merges as cell\nmeta on the instance. On the spreadsheet shell they are parts of the\ndocument, per sheet, saved with it and moved by inserts and deletes:\n\n| Handsontable | sv-grid spreadsheet shell |\n| --------------------------------------------------- | --------------------------------------------------------------- |\n| `comments: true`, `cell: [{ row, col, comment }]` | Review > New Comment, Shift+F2, the cell menu; `getState().sheets[name].comments` |\n| `validator: 'numeric'`, `allowInvalid: false` | Data > Data Validation (Whole number, Decimal, List, Date, Text length, Custom), Stop or Warning; `validation` in the state |\n| `readOnly: true` on a cell | Format Cells > Protection unlocks the cells that may change, Review > Protect Sheet locks the rest; `locked: false` in the format entry, `protected` per sheet |\n| `mergeCells` | Merge & Center on the ribbon and the cell menu; `merges` in the state |\n| `filters: true` + `dropdownMenu` | Ctrl+Shift+L or Data > Filter: Excel's AutoFilter arrows and menus; `autoFilter` in the state |\n| conditional formatting (a custom renderer) | Home > Styles > Conditional Formatting: Highlight Cells, Top/Bottom, Data Bars, Color Scales, Icon Sets, Manage Rules; `conditionalFormats` in the state |\n| `autofill` rules | The fill handle's own series: numbers, dates by day or by the set gap, `Item 1`, weekdays and months |\n\nOn a plain `<SvGrid>` the free grid has the primitives instead: `notes`\nand `editableComments` for comments, `editable` and `valueParser` on a\ncolumn for read-only cells and validation, `mergedCells` for merges, the\nfilter row and its Excel-style menu for filtering, and value-driven\n`conditionalFormats` by column.\n\n## Formulas (HyperFormula)\n\nSv-grid ships a focused subset under\n[`spreadsheet-formulas`](./spreadsheet-formulas.md) (SUM, IF, COUNTIF\n+ cell refs + ranges + cycle detection). It does NOT ship the full\nHyperFormula library.\n\nIf you need HyperFormula's full surface (~400 functions, complex\ndate math, R1C1 refs), the integration pattern is:\n\n```ts\nimport { HyperFormula } from 'hyperformula'\n\nconst hf = HyperFormula.buildFromArray(rowsAsMatrix, { licenseKey: 'gpl-v3' })\n\n// On every cell edit, push to HF + read back the computed value:\nfunction onCellValueChange(e) {\n hf.setCellContents({ sheet: 0, row: e.rowIndex, col: columnIndex }, e.newValue)\n // ...read computed cells you depend on + push back via api.setCellValue\n}\n```\n\nThis is the only piece where the swap isn't 1:1. Most teams find\nsv-grid's shipped subset covers 80% of real-world formula usage; if\nyours is in the 20%, HyperFormula plugs in with the pattern above.\n\n## Licence\n\nHandsontable's grid needs a commercial licence for commercial use; its free\nHobby licence is for personal, exploratory projects, as its pricing page\nstates (the wording and the date are in the facts box at the top of this\npage). Sv-grid's `@svgrid/grid` is MIT with no licence key, and the\n[Enterprise tier](../enterprise/licensing.md) needs no key to evaluate:\nit works without one and displays a watermark and a console\nmessage until you add one, so there is no cutoff to plan around.\n\n## What you get for free vs Handsontable\n\n- **No commercial licence for the grid.** @svgrid/grid is MIT.\n- **Modern Svelte 5 ergonomics.** `$state` arrays beat\n `loadData(...)`.\n- **Grid features a spreadsheet does not have.** Row grouping with\n aggregation, master/detail, server-side data (grouping, tree, pivot and transactions on the server are Enterprise) and integrated\n charts in the same package.\n- **CSP-clean.** Handsontable's HyperFormula path needs CSP `eval`\n exceptions in some configurations.\n\n## What you give up\n\n- **Full HyperFormula surface as a supported feature.** Sv-grid ships a\n subset and lets you wire HyperFormula yourself; see above.\n- **Nested headers.** Handsontable's `nestedHeaders` have no\n counterpart beyond column groups.\n- **Threaded comments and a validation Input Message.** Comments on the\n shell are Excel's notes, one text per cell; validation shows its message\n on a refusal, not on arrival.\n- **Excel export without a paid pack.** Handsontable's export plugin writes\n XLSX through its asynchronous method; on sv-grid, CSV, TSV and JSON export\n are free and Excel, PDF and print output are in `@svgrid/enterprise`.\n\n## Frequently asked questions\n\n### Can SvGrid replace Handsontable's spreadsheet features?\n\nIt covers roughly 90% of the surface - inline editing on every cell, copy/paste\nas TSV, range selection, column groups, and a built-in formula engine. Budget\n2-4 hours per grid for typical spreadsheet workflows, plus 1-2 days if you lean\nheavily on the full HyperFormula function set.\n\n### Does SvGrid support formulas like Handsontable?\n\nYes, a built-in formula engine with cell references, ranges, and common\nfunctions (see the spreadsheet-formulas guide and demo 27). It is a practical\nsubset rather than the complete HyperFormula library, so verify your specific\nfunctions before porting.\n\n### Is SvGrid licensed like Handsontable?\n\nNo. The `@svgrid/grid` core is MIT and free for commercial use - no per-seat\nlicence key - whereas Handsontable's free licence excludes commercial use and\nits commercial plans are per developer; the facts box has the statement as\nread from handsontable.com. The optional `@svgrid/enterprise` pack (Excel and\nPDF export, print, pivot, import) is priced per developer.\n\n### Does SvGrid have a blank spreadsheet like Handsontable?\n\nYes, on the plain grid: column-letter headers, a row gutter, a name box\nand formula bar, gridlines, range selection and a fill handle, with\nHyperFormula underneath when you want its function library.\n\n<div data-docs-demo=\"207-blank-sheet\" data-height=\"560\"></div>\n\n## What you end up with\n\nSpreadsheet behaviour: inline edit, drag a cell range, copy it out as TSV.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection statusBar />\n```\n\n## See also\n\n- [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/) - the side-by-side comparison, with a source and date for every claim\n- [Spreadsheet formulas](./spreadsheet-formulas.md) - sv-grid's\n built-in formula engine, and the rest of the spreadsheet demos\n- [Demo 27 (Spreadsheet + Ribbon)](https://svgrid.com/demos/27-spreadsheet-ribbon/) - live\n- [Migrating from AG Grid](./migrating-from-ag-grid.md)\n"
5926
6069
  },
5927
6070
  {
5928
6071
  "slug": "help/migrating-from-jqxgrid",
5929
6072
  "path": "docs/help/migrating-from-jqxgrid.md",
5930
6073
  "title": "Migrating from jqxGrid (jQWidgets)",
5931
6074
  "section": "Help",
5932
- "markdown": "# Migrating from jqxGrid (jQWidgets)\n\njqxGrid and SvGrid come from the **same team**. jqxGrid is the mature,\nmulti-framework grid (jQuery core with Angular, React, and Vue\nintegrations); SvGrid is the Svelte-5-native member of the family. If\nyour team is consolidating on Svelte 5, this guide maps a jqxGrid setup\nonto SvGrid - and the concepts will feel familiar because the\nengineering lineage is shared.\n\n> Estimated effort: **2-4 hours** per grid. Most of the work is moving\n> from the imperative jQuery source / API to reactive `$state`.\n\n<!-- facts:start jqxgrid -->\n> **Facts, checked 12 Sep 2026.** `jqwidgets-scripts` 26.0.0, https://www.jqwidgets.com/license/, last published 9 Jul 2026, 41,900 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). jqxGrid pricing, as its site states it: jqwidgets.com lists the Developer License at $499 (on sale at $399) per developer, perpetual and royalty-free with one year of updates and support, and the Team License at $1,499 for five or more developers; the free Community License excludes the Grid (https://www.jqwidgets.com/license/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs jqxGrid (jQWidgets)](https://svgrid.com/compare/jqxgrid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| jqxGrid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `$('#grid').jqxGrid({ ... })` | `<SvGrid ... />` |\n| `source` / `jqxDataAdapter` | `data` array (or `externalSort/Filter`) |\n| `{ text: 'Name', datafield: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `cellsrenderer` | `cell: (c) => renderSnippet(...)` |\n| `columntype` / cell editor | `editorType` |\n| `cellsformat: 'c2'` | `format: { type: 'currency', currency: 'USD' }` |\n| `sortable` / `filterable` | `rowSortingFeature` / `columnFilteringFeature` |\n| `groupable` + `groups` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `pageable` | `showPagination` |\n| `jqxGrid('updatebounddata')` | reassign the `$state` data array |\n| `editable` + `cellendedit` event | `enableInlineEditing` + `onCellValueChange` |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- const source = { localdata: rows, datatype: 'array' }\n- const adapter = new $.jqx.dataAdapter(source)\n- $('#grid').jqxGrid({\n- source: adapter, sortable: true, filterable: true, pageable: true, editable: true,\n- columns: [\n- { text: 'Name', datafield: 'name' },\n- { text: 'Amount', datafield: 'amount', cellsformat: 'c2' },\n- ],\n- })\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination enableInlineEditing />\n```\n\n## What changes\n\n- **jQuery source / dataAdapter → reactive `$state`.** No\n `updatebounddata()`; reassign the array.\n- **`cellsrenderer` → snippet cells** via `renderSnippet`.\n- **jQWidgets theme → `--sg-*` tokens** (or your Tailwind theme).\n\n## A note on family\n\nMoving to SvGrid keeps you with the same team's Svelte-5 grid rather\nthan switching vendors. The Enterprise tier and support come from the same people behind jqxGrid.\nIf your app is still on jQuery / Angular / React / Vue, jqxGrid remains\nthe right tool; reach for SvGrid when the codebase is Svelte 5.\n\n## Frequently asked questions\n\n### Is SvGrid made by the same team as jqxGrid?\n\nYes. SvGrid is built by jQWidgets - the same team behind jqxGrid - specifically\nfor Svelte 5, rebuilt around runes and snippets with an MIT community core.\n\n### How do jqxGrid columns map to SvGrid?\n\n`text` becomes `header`, `datafield` becomes `field`, `cellsrenderer` becomes a\n`renderSnippet` cell, and `cellsformat` maps onto the `format` config. Sorting /\nfiltering / grouping move to registered features.\n\n### Should I migrate my jQuery jqxGrid app to SvGrid?\n\nOnly if you are moving that app to Svelte 5. If it stays on jQuery / Angular /\nReact / Vue, jqxGrid is the better fit. SvGrid is the native choice once the\nstack is Svelte.\n\n## What you end up with\n\nEditing plus range selection and a totals row - the jqxGrid working set.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection summary sortable />\n```\n\n## See also\n\n- [SvGrid vs jqxGrid](https://svgrid.com/compare/jqxgrid/) - the side-by-side comparison\n- [About SvGrid](https://svgrid.com/about/) - built by jQWidgets\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
6075
+ "markdown": "# Migrating from jqxGrid (jQWidgets)\n\njqxGrid and SvGrid come from the **same team**. jqxGrid is the mature,\nmulti-framework grid (jQuery core with Angular, React, and Vue\nintegrations); SvGrid is the Svelte-5-native member of the family. If\nyour team is consolidating on Svelte 5, this guide maps a jqxGrid setup\nonto SvGrid - and the concepts will feel familiar because the\nengineering lineage is shared.\n\n> Estimated effort: **2-4 hours** per grid. Most of the work is moving\n> from the imperative jQuery source / API to reactive `$state`.\n\n<!-- facts:start jqxgrid -->\n> **Facts, checked 12 Sep 2026.** `jqwidgets-scripts` 26.0.0, https://www.jqwidgets.com/license/, last published 9 Jul 2026, 41,900 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). jqxGrid pricing, as its site states it: jqwidgets.com lists the Developer License at $499 (on sale at $399) per developer, perpetual and royalty-free with one year of updates and support, and the Team License at $1,499 for five or more developers; the free Community License excludes the Grid (https://www.jqwidgets.com/license/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs jqxGrid (jQWidgets)](https://svgrid.com/compare/jqxgrid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| jqxGrid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `$('#grid').jqxGrid({ ... })` | `<SvGrid ... />` |\n| `source` / `jqxDataAdapter` | `data` array (or `externalSort/Filter`) |\n| `{ text: 'Name', datafield: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `cellsrenderer` | `cell: (c) => renderSnippet(...)` |\n| `columntype` / cell editor | `editorType` |\n| `cellsformat: 'c2'` | `format: { type: 'currency', currency: 'USD' }` |\n| `sortable` / `filterable` | `rowSortingFeature` / `columnFilteringFeature` |\n| `groupable` + `groups` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `pageable` | `showPagination` |\n| `jqxGrid('updatebounddata')` | reassign the `$state` data array |\n| `editable` + `cellendedit` event | `enableInlineEditing` + `onCellValueChange` |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- const source = { localdata: rows, datatype: 'array' }\n- const adapter = new $.jqx.dataAdapter(source)\n- $('#grid').jqxGrid({\n- source: adapter, sortable: true, filterable: true, pageable: true, editable: true,\n- columns: [\n- { text: 'Name', datafield: 'name' },\n- { text: 'Amount', datafield: 'amount', cellsformat: 'c2' },\n- ],\n- })\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination enableInlineEditing />\n```\n\n## What changes\n\n- **jQuery source / dataAdapter → reactive `$state`.** No\n `updatebounddata()`; reassign the array.\n- **`cellsrenderer` → snippet cells** via `renderSnippet`.\n- **jQWidgets theme → `--sg-*` tokens** (or your Tailwind theme).\n\n## A note on family\n\nMoving to SvGrid keeps you with the same team's Svelte-5 grid rather\nthan switching vendors. The Enterprise tier and support come from the same people behind jqxGrid.\nIf your app is still on jQuery / Angular / React / Vue, jqxGrid remains\nthe right tool; reach for SvGrid when the codebase is Svelte 5.\n\n## Frequently asked questions\n\n### Is SvGrid made by the same team as jqxGrid?\n\nYes. SvGrid is built by jQWidgets - the same team behind jqxGrid - specifically\nfor Svelte 5, rebuilt around runes and snippets with an MIT community core.\n\n### How do jqxGrid columns map to SvGrid?\n\n`text` becomes `header`, `datafield` becomes `field`, `cellsrenderer` becomes a\n`renderSnippet` cell, and `cellsformat` maps onto the `format` config. Sorting /\nfiltering / grouping move to registered features.\n\n### Should I migrate my jQuery jqxGrid app to SvGrid?\n\nOnly if you are moving that app to Svelte 5. If it stays on jQuery / Angular /\nReact / Vue, jqxGrid is the better fit. SvGrid is the native choice once the\nstack is Svelte.\n\n## What you end up with\n\nEditing plus range selection and a totals row - the jqxGrid working set.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection summary sortable />\n```\n\n## See also\n\n- [SvGrid vs jqxGrid](https://svgrid.com/compare/jqxgrid/) - the side-by-side comparison\n- [About SvGrid](https://svgrid.com/about/) - built by jQWidgets\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
5933
6076
  },
5934
6077
  {
5935
6078
  "slug": "help/migrating-from-kendo-grid",
5936
6079
  "path": "docs/help/migrating-from-kendo-grid.md",
5937
6080
  "title": "Migrating from Kendo UI Grid (Telerik)",
5938
6081
  "section": "Help",
5939
- "markdown": "# Migrating from Kendo UI Grid (Telerik)\n\nKendo UI Grid is the polished, commercial enterprise grid from Telerik /\nProgress, available for jQuery, React, Vue, and Angular. Moving to SvGrid\ntrades the multi-framework commercial suite for a Svelte-5-native grid\nwith an MIT core - and a much cheaper paid tier.\n\n> Estimated effort: **3-6 hours** per grid - column / event translation\n> plus re-theming.\n>\n> Kendo's exact API differs across its jQuery / React / Vue / Angular\n> flavours; map your version's column and event names onto the SvGrid\n> equivalents below.\n\n<!-- facts:start kendo-ui-grid -->\n> **Facts, checked 12 Sep 2026.** `@progress/kendo-react-grid` 16.1.0, Commercial (see licence file), last published 8 Sep 2026, 385,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). Kendo UI Grid pricing, as its site states it: telerik.com lists the Kendo UI bundle at $799, $849 or $1,299 per developer per year depending on the support tier, and KendoReact alone from $649 per developer per year; no free tier for the grid (https://www.telerik.com/purchase.aspx, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Kendo UI Grid (Telerik)](https://svgrid.com/compare/kendo-ui-grid/).\n<!-- facts:end -->\n\n## Concept map\n\n| Kendo UI Grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ field, title }]` | `columns: [{ field, header }]` |\n| `template` / cell render | `cell: (c) => renderSnippet(...)` |\n| `editable` + editor | `enableInlineEditing` + `editorType` |\n| `sortable` / `filterable` | `rowSortingFeature` / `columnFilteringFeature` |\n| `group` / aggregates | `columnGroupingFeature` + `api.setGroupBy()` |\n| `dataSource` (local / remote) | `data` array or `externalSort/Filter` |\n| `pageable` | `showPagination` |\n| Kendo themes (Default / Bootstrap) | `--sg-*` tokens / Tailwind |\n| Grid events (`change`, `dataBound`) | `onCellValueChange`, `onApiReady`, ... |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- $('#grid').kendoGrid({\n- dataSource: { data: rows, pageSize: 25 },\n- sortable: true, filterable: true, pageable: true, editable: true,\n- columns: [\n- { field: 'name', title: 'Name' },\n- { field: 'amount', title: 'Amount', format: '{0:c}' },\n- ],\n- })\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a jQuery / multi-framework suite.\n- **MIT community core** - no per-developer license for the grid itself.\n- **Paid support at a fraction of enterprise-suite pricing.**\n- **No design-system lock-in** - theme via `--sg-*` tokens.\n\n## What to weigh\n\n- Kendo bundles a **huge component suite** (charts, scheduler, editor)\n and decades of vendor support. If you need the whole suite across\n several frameworks, that has real value.\n\n## Frequently asked questions\n\n### Is SvGrid a cheaper alternative to Kendo UI Grid?\n\nFor a Svelte stack, yes: the `@svgrid/grid` core is MIT (free, including\ncommercial use), and the paid `@svgrid/enterprise` tier is a fraction of enterprise\ncomponent-suite pricing.\n\n### How long does a Kendo Grid migration take?\n\nAbout 3-6 hours per grid. It is a column / event rename pass plus re-theming;\nthe columns and editing concepts map closely.\n\n### Does SvGrid match Kendo's feature set?\n\nFor the grid itself it covers the common enterprise surface - sorting,\nExcel-style filters, grouping, virtualization, editing, master/detail, tree.\nKendo's value beyond that is the wider suite and multi-framework parity.\n\n## What you end up with\n\nSorting, filtering, grouping and editing, with the column menu Kendo users expect.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} groupable sortable filterable editable />\n```\n\n## See also\n\n- [SvGrid vs Kendo UI Grid](https://svgrid.com/compare/kendo-ui-grid/) - the side-by-side comparison\n- [Pricing](https://svgrid.com/pricing/) - the SvGrid Enterprise tiers\n- [Architecture](./architecture.md) - engine + render-component split\n"
6082
+ "markdown": "# Migrating from Kendo UI Grid (Telerik)\n\nKendo UI Grid is the polished, commercial enterprise grid from Telerik /\nProgress, available for jQuery, React, Vue, and Angular. Moving to SvGrid\ntrades the multi-framework commercial suite for a Svelte-5-native grid\nwith an MIT core - and a much cheaper paid tier.\n\n> Estimated effort: **3-6 hours** per grid - column / event translation\n> plus re-theming.\n>\n> Kendo's exact API differs across its jQuery / React / Vue / Angular\n> flavours; map your version's column and event names onto the SvGrid\n> equivalents below.\n\n<!-- facts:start kendo-ui-grid -->\n> **Facts, checked 12 Sep 2026.** `@progress/kendo-react-grid` 16.1.0, Commercial (see licence file), last published 8 Sep 2026, 385,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). Kendo UI Grid pricing, as its site states it: telerik.com lists the Kendo UI bundle at $799, $849 or $1,299 per developer per year depending on the support tier, and KendoReact alone from $649 per developer per year; no free tier for the grid (https://www.telerik.com/purchase.aspx, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Kendo UI Grid (Telerik)](https://svgrid.com/compare/kendo-ui-grid/).\n<!-- facts:end -->\n\n## Concept map\n\n| Kendo UI Grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ field, title }]` | `columns: [{ field, header }]` |\n| `template` / cell render | `cell: (c) => renderSnippet(...)` |\n| `editable` + editor | `enableInlineEditing` + `editorType` |\n| `sortable` / `filterable` | `rowSortingFeature` / `columnFilteringFeature` |\n| `group` / aggregates | `columnGroupingFeature` + `api.setGroupBy()` |\n| `dataSource` (local / remote) | `data` array or `externalSort/Filter` |\n| `pageable` | `showPagination` |\n| Kendo themes (Default / Bootstrap) | `--sg-*` tokens / Tailwind |\n| Grid events (`change`, `dataBound`) | `onCellValueChange`, `onApiReady`, ... |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- $('#grid').kendoGrid({\n- dataSource: { data: rows, pageSize: 25 },\n- sortable: true, filterable: true, pageable: true, editable: true,\n- columns: [\n- { field: 'name', title: 'Name' },\n- { field: 'amount', title: 'Amount', format: '{0:c}' },\n- ],\n- })\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a jQuery / multi-framework suite.\n- **MIT community core** - no per-developer license for the grid itself.\n- **Paid support at a fraction of enterprise-suite pricing.**\n- **No design-system lock-in** - theme via `--sg-*` tokens.\n\n## What to weigh\n\n- Kendo bundles a **huge component suite** (charts, scheduler, editor)\n and decades of vendor support. If you need the whole suite across\n several frameworks, that has real value.\n\n## Frequently asked questions\n\n### Is SvGrid a cheaper alternative to Kendo UI Grid?\n\nFor a Svelte stack, yes: the `@svgrid/grid` core is MIT (free, including\ncommercial use), and the paid `@svgrid/enterprise` tier is a fraction of enterprise\ncomponent-suite pricing.\n\n### How long does a Kendo Grid migration take?\n\nAbout 3-6 hours per grid. It is a column / event rename pass plus re-theming;\nthe columns and editing concepts map closely.\n\n### Does SvGrid match Kendo's feature set?\n\nFor the grid itself it covers the common enterprise surface - sorting,\nExcel-style filters, grouping, virtualization, editing, master/detail, tree.\nKendo's value beyond that is the wider suite and multi-framework parity.\n\n## What you end up with\n\nSorting, filtering, grouping and editing, with the column menu Kendo users expect.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} groupable sortable filterable editable />\n```\n\n## See also\n\n- [SvGrid vs Kendo UI Grid](https://svgrid.com/compare/kendo-ui-grid/) - the side-by-side comparison\n- [Pricing](https://svgrid.com/pricing/) - the SvGrid Enterprise tiers\n- [Architecture](./architecture.md) - engine + render-component split\n"
5940
6083
  },
5941
6084
  {
5942
6085
  "slug": "help/migrating-from-mui-x",
5943
6086
  "path": "docs/help/migrating-from-mui-x.md",
5944
6087
  "title": "Migrating from MUI X DataGrid",
5945
6088
  "section": "Help",
5946
- "markdown": "# Migrating from MUI X DataGrid\n\nMUI X DataGrid is the most common starting point for teams already\non Material UI. Its MIT Community edition plus paid Pro and Premium\ntiers is a split similar to sv-grid's, except that column pinning,\nmaster/detail, tree data, row grouping, aggregation and cell selection\nare paid in MUI X and free here. The port is mostly mechanical.\n\n> Estimated effort: **1-3 hours** per grid, depending on how heavily\n> you've leant on `apiRef.current.*` calls.\n\n<!-- facts:start mui-x-datagrid -->\n> **Facts, checked 12 Sep 2026.** `@mui/x-data-grid` 9.13.0, MIT, last published 4 Sep 2026, 11,800,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `@mui/x-data-grid` 9.13.0 155.0 KB JS, no separate stylesheet, @emotion/react + @emotion/styled + @mui/material + @mui/system + react + react-dom external (measured 12 Sep 2026). MUI X DataGrid pricing, as its site states it: MUI X Community is free under MIT. mui.com lists Pro at $299 per year per developer, Premium at $599 per year per developer and Enterprise at $1,399 per year per developer, with perpetual and annual licence models (https://mui.com/pricing/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/).\n<!-- facts:end -->\n\n## Package map\n\n| MUI X | sv-grid |\n| ------------------------------------ | ---------------------------------------- |\n| `@mui/x-data-grid` | `@svgrid/grid` |\n| `@mui/x-data-grid-pro` | `@svgrid/enterprise` (export, import, pivot, AI) |\n| `@mui/x-data-grid-premium` | All of `@svgrid/enterprise` ships in one tier |\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid'\n\n+ import { SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef } from '@svgrid/grid'\n```\n\n## Column defs\n\n```diff\n- const columns: GridColDef[] = [\n- { field: 'id', headerName: 'ID', width: 90 },\n- { field: 'lastName', headerName: 'Last', width: 150, editable: true },\n- { field: 'age', headerName: 'Age', type: 'number', width: 110, editable: true },\n- ]\n\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'id', header: 'ID', width: 90 },\n+ { field: 'lastName', header: 'Last', width: 150 },\n+ { field: 'age', header: 'Age', width: 110, editorType: 'number' },\n+ ]\n```\n\n- `headerName` → `header`\n- `type: 'number'` → `editorType: 'number'`\n- `editable: true` → omit (every column is editable by default; set\n `editable: false` to OPT OUT)\n\n## Mounting\n\n```diff\n- <DataGrid rows={rows} columns={columns} pageSize={25} checkboxSelection />\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ showPagination={true} pageSize={25}\n+ selectionMode=\"row\" />\n```\n\n`tableFeatures({ rowSortingFeature, columnFilteringFeature,\nrowSelectionFeature })` registers what you'd implicitly get from\nMUI X.\n\n## `apiRef` translation\n\n| MUI X (`apiRef.current.*`) | sv-grid (`api.*`) |\n| -------------------------------------------- | ------------------------------------------ |\n| `setRows(rows)` | mutate the `$state` array you bound to `data` |\n| `updateRows([{id, ...patch}])` | `api.setCellValue(rowIndex, field, value)` |\n| `setSortModel([{field, sort}])` | `api.setSort(field, sort)` |\n| `setFilterModel({items: [...]})` | `api.setFilter(field, {operator, value})` |\n| `setPage(0)` / `setPageSize(50)` | Use the built-in pager; for headless control register `pageSize` prop |\n| `selectRow(id)` | Toggle the row checkbox via the wrapper's UI; programmatic select is `api.selectRows([id])` (`api.toggleRowSelected(id)` to flip one) |\n| `getSelectedRows()` | `api.getSelectedRows()` (ids via `api.getSelectedRowIds()`) |\n| `exportDataAsExcel()` | `api.exportData({ format: 'xlsx' })` (Enterprise) |\n| `setColumnVisibilityModel({field: false})` | `api.setColumnVisible('field', false)` |\n\n## Custom cells\n\n```diff\n- {\n- field: 'status',\n- renderCell: ({ row }) => <Chip label={row.status} color={row.status === 'active' ? 'success' : 'default'} />,\n- }\n\n+ {\n+ field: 'status',\n+ cell: (ctx) => renderSnippet(StatusChip, { status: ctx.row.original.status }),\n+ }\n```\n\n## Selection\n\n```diff\n- <DataGrid checkboxSelection\n- onRowSelectionModelChange={(ids) => setSelected(ids)} />\n\n+ <SvGrid\n+ {data} {columns} features={features}\n+ selectionMode=\"row\"\n+ onRowSelectionChange={(selection, rows) => setSelected(rows)} />\n```\n\n`selectionMode` values: `'row'` (the MUI X equivalent), `'cell'`\n(spreadsheet-style range), `'both'`, `'none'`.\n\n## Inline editing\n\nMUI X had `processRowUpdate(newRow, oldRow)` returning the new row.\nSv-grid's equivalent is `onCellValueChange`:\n\n```diff\n- <DataGrid processRowUpdate={async (newRow) => {\n- await api.savePatch(newRow)\n- return newRow\n- }} />\n\n+ <SvGrid\n+ onCellValueChange={async (e) => {\n+ await api.savePatch({ id: e.row.id, [e.columnId]: e.newValue })\n+ }}\n+ />\n```\n\nFor full-row editing (one Save button per row), see\n[Full-row editing](./editing/full-row.md).\n\n## Server-side data\n\nMUI X's `pagination + serverSideMode + filterMode='server'` maps to\nsv-grid's `externalSort + externalFilter`, or to `createServerDataSource` (free:\npaging or infinite scroll, sort, filter) when the server pages, and to the\nEnterprise `createServerRowModel` when it also groups; the demo below runs\nthe free controller against a fake API with sort, filter and infinite scroll:\n\n<div data-docs-demo=\"148-server-row-model\" data-height=\"520\"></div>\n\nMUI X's server-side row grouping and aggregation (Premium) map to the\nEnterprise row model, which loads each group level on expand and pages,\nedits and selects across rows the grid never fetched:\n\n<div data-docs-demo=\"467-server-row-model-1m\" data-height=\"600\"></div>\n\n```svelte\n<SvGrid\n data={rows} columns={columns} features={features}\n externalSort={true}\n externalFilter={true}\n onSortingChange={async (s) => { rows = await fetchPage({ sort: s }) }}\n onFiltersChange={async (f) => { rows = await fetchPage({ filters: f.columns }) }}\n/>\n```\n\n## Slots / customisation\n\nMUI X exposes a `slots` object. Sv-grid doesn't - instead, every\nvisual piece is a CSS custom property (`--sg-*`); see\n[design tokens](./tokens.md). Override at any DOM level:\n\n```css\n.grid-host { --sg-accent: #db2777; --sg-radius: 10px; }\n```\n\nRow height is the exception: it is the `rowHeight` prop rather than a\ntoken, because the virtualizer needs it as a number.\n\nFor full theme presets (Ant, MUI, Fluent, Base Web, shadcn) see\n[demo 74](https://svgrid.com/demos/74-theme-integrations/).\n\n## What you get for free vs MUI X\n\n- **No Emotion / no Material theme dependency.** The facts box at the\n top of the page has both packages measured the same way; the MUI X\n figure excludes React, Material UI, Emotion and the MUI system, which\n it needs and sv-grid does not.\n- **Pro and Premium features in the MIT core.** Column pinning, master/detail,\n tree data, row grouping, aggregation and cell selection carry Pro or\n Premium badges on mui.com; they are free here. Excel export and pivot\n are paid on both sides.\n- **In-grid AI helpers against your own model.** MUI X's AI assistant is a\n Premium feature that routes prompts through MUI's hosted service unless\n you build your own; sv-grid's natural-language filter, smart fill and\n summarise helpers are free and run against a provider you register.\n- **CSP-clean.** No `eval`.\n\n## What you give up\n\n- **The Material Design look out of the box.** Sv-grid ships\n unstyled-by-token; the [MUI preset in demo 74](https://svgrid.com/demos/74-theme-integrations/)\n is one drop-in.\n- **MUI form-field integration.** Bind directly to your own MUI\n inputs in custom cell components if you want them.\n- **The rest of MUI X in one design system.** Date pickers, charts and\n the tree view share MUI X's theme; sv-grid ships its own date and time\n editors and charts, themed through the same `--sg-*` tokens.\n- **A hosted AI assistant with starter credits.** Premium licence holders\n get MUI's service; sv-grid's helpers need a model provider you host or\n pay for yourself.\n\n## Frequently asked questions\n\n### How hard is it to migrate from MUI X DataGrid to SvGrid?\n\nMostly mechanical - typically 1-3 hours per grid, depending on how heavily you\nrelied on `apiRef.current.*`. The Community/Enterprise split mirrors MUI X's, so the\nlicensing mental model carries over directly.\n\n### Can SvGrid keep the Material Design look?\n\nYes. SvGrid ships unstyled-by-token and re-themes through `--sg-*` CSS\nvariables; the MUI preset in demo 74 is a drop-in starting point. You can also\nbind your own MUI inputs inside custom cell components.\n\n### Is SvGrid cheaper than MUI X Pro/Premium?\n\nSvGrid's Community tier is MIT and free for commercial use, and `@svgrid/enterprise`\nis priced per developer ($599 for the grid, $999 with the spreadsheet and\nStudio, both covering unlimited apps). MUI X Pro and\nPremium are also per developer per year; the prices mui.com listed on the\ndate we read it are in the facts box at the top of this page. The difference\nis what the free tier holds: most of what MUI X sells in Pro and Premium is\nin SvGrid's MIT core, so compare feature needs before prices on the\n[pricing page](https://svgrid.com/pricing/).\n\n## What you end up with\n\nSorting, filtering, pagination and inline editing - the MUI X DataGrid feature set.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/) - the side-by-side comparison, with a source and date for every claim\n- [Server-side data](./server-side-data.md) - the row model the demo above uses\n- [AI assistant](./ai.md) - the free in-grid helpers\n- [Migrating from AG Grid](./migrating-from-ag-grid.md)\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md)\n- [Design tokens](./tokens.md)\n"
6089
+ "markdown": "# Migrating from MUI X DataGrid\n\nMUI X DataGrid is the most common starting point for teams already\non Material UI. Its MIT Community edition plus paid Pro and Premium\ntiers is a split similar to sv-grid's, except that column pinning,\nmaster/detail, tree data, row grouping, aggregation and cell selection\nare paid in MUI X and free here. The port is mostly mechanical.\n\n> Estimated effort: **1-3 hours** per grid, depending on how heavily\n> you've leant on `apiRef.current.*` calls.\n\n<!-- facts:start mui-x-datagrid -->\n> **Facts, checked 12 Sep 2026.** `@mui/x-data-grid` 9.13.0, MIT, last published 4 Sep 2026, 11,800,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `@mui/x-data-grid` 9.13.0 155.0 KB JS, no separate stylesheet, @emotion/react + @emotion/styled + @mui/material + @mui/system + react + react-dom external (measured 12 Sep 2026). MUI X DataGrid pricing, as its site states it: MUI X Community is free under MIT. mui.com lists Pro at $299 per year per developer, Premium at $599 per year per developer and Enterprise at $1,399 per year per developer, with perpetual and annual licence models (https://mui.com/pricing/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/).\n<!-- facts:end -->\n\n## Package map\n\n| MUI X | sv-grid |\n| ------------------------------------ | ---------------------------------------- |\n| `@mui/x-data-grid` | `@svgrid/grid` |\n| `@mui/x-data-grid-pro` | `@svgrid/enterprise` (export, import, pivot, AI) |\n| `@mui/x-data-grid-premium` | All of `@svgrid/enterprise` ships in one tier |\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { DataGrid, GridColDef, GridRowsProp } from '@mui/x-data-grid'\n\n+ import { SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef } from '@svgrid/grid'\n```\n\n## Column defs\n\n```diff\n- const columns: GridColDef[] = [\n- { field: 'id', headerName: 'ID', width: 90 },\n- { field: 'lastName', headerName: 'Last', width: 150, editable: true },\n- { field: 'age', headerName: 'Age', type: 'number', width: 110, editable: true },\n- ]\n\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'id', header: 'ID', width: 90 },\n+ { field: 'lastName', header: 'Last', width: 150 },\n+ { field: 'age', header: 'Age', width: 110, editorType: 'number' },\n+ ]\n```\n\n- `headerName` → `header`\n- `type: 'number'` → `editorType: 'number'`\n- `editable: true` → omit (every column is editable by default; set\n `editable: false` to OPT OUT)\n\n## Mounting\n\n```diff\n- <DataGrid rows={rows} columns={columns} pageSize={25} checkboxSelection />\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ showPagination={true} pageSize={25}\n+ selectionMode=\"row\" />\n```\n\n`tableFeatures({ rowSortingFeature, columnFilteringFeature,\nrowSelectionFeature })` registers what you'd implicitly get from\nMUI X.\n\n## `apiRef` translation\n\n| MUI X (`apiRef.current.*`) | sv-grid (`api.*`) |\n| -------------------------------------------- | ------------------------------------------ |\n| `setRows(rows)` | mutate the `$state` array you bound to `data` |\n| `updateRows([{id, ...patch}])` | `api.setCellValue(rowIndex, field, value)` |\n| `setSortModel([{field, sort}])` | `api.setSort(field, sort)` |\n| `setFilterModel({items: [...]})` | `api.setFilter(field, {operator, value})` |\n| `setPage(0)` / `setPageSize(50)` | Use the built-in pager; for headless control register `pageSize` prop |\n| `selectRow(id)` | Toggle the row checkbox via the wrapper's UI; programmatic select is `api.selectRows([id])` (`api.toggleRowSelected(id)` to flip one) |\n| `getSelectedRows()` | `api.getSelectedRows()` (ids via `api.getSelectedRowIds()`) |\n| `exportDataAsExcel()` | `api.exportData({ format: 'xlsx' })` (Enterprise) |\n| `setColumnVisibilityModel({field: false})` | `api.setColumnVisible('field', false)` |\n\n## Custom cells\n\n```diff\n- {\n- field: 'status',\n- renderCell: ({ row }) => <Chip label={row.status} color={row.status === 'active' ? 'success' : 'default'} />,\n- }\n\n+ {\n+ field: 'status',\n+ cell: (ctx) => renderSnippet(StatusChip, { status: ctx.row.original.status }),\n+ }\n```\n\n## Selection\n\n```diff\n- <DataGrid checkboxSelection\n- onRowSelectionModelChange={(ids) => setSelected(ids)} />\n\n+ <SvGrid\n+ {data} {columns} features={features}\n+ selectionMode=\"row\"\n+ onRowSelectionChange={(selection, rows) => setSelected(rows)} />\n```\n\n`selectionMode` values: `'row'` (the MUI X equivalent), `'cell'`\n(spreadsheet-style range), `'both'`, `'none'`.\n\n## Inline editing\n\nMUI X had `processRowUpdate(newRow, oldRow)` returning the new row.\nSv-grid's equivalent is `onCellValueChange`:\n\n```diff\n- <DataGrid processRowUpdate={async (newRow) => {\n- await api.savePatch(newRow)\n- return newRow\n- }} />\n\n+ <SvGrid\n+ onCellValueChange={async (e) => {\n+ await api.savePatch({ id: e.row.id, [e.columnId]: e.newValue })\n+ }}\n+ />\n```\n\nFor full-row editing (one Save button per row), see\n[Full-row editing](./editing/full-row.md).\n\n## Server-side data\n\nMUI X's `pagination + serverSideMode + filterMode='server'` maps to\nsv-grid's `externalSort + externalFilter`, or to `createServerDataSource` (free:\npaging or infinite scroll, sort, filter) when the server pages, and to the\nEnterprise `createServerRowModel` when it also groups; the demo below runs\nthe free controller against a fake API with sort, filter and infinite scroll:\n\n<div data-docs-demo=\"148-server-row-model\" data-height=\"520\"></div>\n\nMUI X's server-side row grouping and aggregation (Premium) map to the\nEnterprise row model, which loads each group level on expand and pages,\nedits and selects across rows the grid never fetched:\n\n<div data-docs-demo=\"467-server-row-model-1m\" data-height=\"600\"></div>\n\n```svelte\n<SvGrid\n data={rows} columns={columns} features={features}\n externalSort={true}\n externalFilter={true}\n onSortingChange={async (s) => { rows = await fetchPage({ sort: s }) }}\n onFiltersChange={async (f) => { rows = await fetchPage({ filters: f.columns }) }}\n/>\n```\n\n## Slots / customisation\n\nMUI X exposes a `slots` object. Sv-grid doesn't - instead, every\nvisual piece is a CSS custom property (`--sg-*`); see\n[design tokens](./tokens.md). Override at any DOM level:\n\n```css\n.grid-host { --sg-accent: #db2777; --sg-radius: 10px; }\n```\n\nRow height is the exception: it is the `rowHeight` prop rather than a\ntoken, because the virtualizer needs it as a number.\n\nFor full theme presets (Ant, MUI, Fluent, Base Web, shadcn) see\n[demo 74](https://svgrid.com/demos/74-theme-integrations/).\n\n## What you get for free vs MUI X\n\n- **No Emotion / no Material theme dependency.** The facts box at the\n top of the page has both packages measured the same way; the MUI X\n figure excludes React, Material UI, Emotion and the MUI system, which\n it needs and sv-grid does not.\n- **Pro and Premium features in the MIT core.** Column pinning, master/detail,\n tree data, row grouping, aggregation and cell selection carry Pro or\n Premium badges on mui.com; they are free here. Excel export and pivot\n are paid on both sides.\n- **In-grid AI helpers against your own model.** MUI X's AI assistant is a\n Premium feature that routes prompts through MUI's hosted service unless\n you build your own; sv-grid's natural-language filter, smart fill and\n summarise helpers are free and run against a provider you register.\n- **CSP-clean.** No `eval`.\n\n## What you give up\n\n- **The Material Design look out of the box.** Sv-grid ships\n unstyled-by-token; the [MUI preset in demo 74](https://svgrid.com/demos/74-theme-integrations/)\n is one drop-in.\n- **MUI form-field integration.** Bind directly to your own MUI\n inputs in custom cell components if you want them.\n- **The rest of MUI X in one design system.** Date pickers, charts and\n the tree view share MUI X's theme; sv-grid ships its own date and time\n editors and charts, themed through the same `--sg-*` tokens.\n- **A hosted AI assistant with starter credits.** Premium licence holders\n get MUI's service; sv-grid's helpers need a model provider you host or\n pay for yourself.\n\n## Frequently asked questions\n\n### How hard is it to migrate from MUI X DataGrid to SvGrid?\n\nMostly mechanical - typically 1-3 hours per grid, depending on how heavily you\nrelied on `apiRef.current.*`. The Community/Enterprise split mirrors MUI X's, so the\nlicensing mental model carries over directly.\n\n### Can SvGrid keep the Material Design look?\n\nYes. SvGrid ships unstyled-by-token and re-themes through `--sg-*` CSS\nvariables; the MUI preset in demo 74 is a drop-in starting point. You can also\nbind your own MUI inputs inside custom cell components.\n\n### Is SvGrid cheaper than MUI X Pro/Premium?\n\nSvGrid's Community tier is MIT and free for commercial use, and `@svgrid/enterprise`\nis priced per developer ($599 for the grid, $999 with the spreadsheet and\nStudio, both covering unlimited apps). MUI X Pro and\nPremium are also per developer per year; the prices mui.com listed on the\ndate we read it are in the facts box at the top of this page. The difference\nis what the free tier holds: most of what MUI X sells in Pro and Premium is\nin SvGrid's MIT core, so compare feature needs before prices on the\n[pricing page](https://svgrid.com/pricing/).\n\n## What you end up with\n\nSorting, filtering, pagination and inline editing - the MUI X DataGrid feature set.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/) - the side-by-side comparison, with a source and date for every claim\n- [Server-side data](./server-side-data.md) - the row model the demo above uses\n- [AI assistant](./ai.md) - the free in-grid helpers\n- [Migrating from AG Grid](./migrating-from-ag-grid.md)\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md)\n- [Design tokens](./tokens.md)\n"
5947
6090
  },
5948
6091
  {
5949
6092
  "slug": "help/migrating-from-nocodb",
@@ -5957,77 +6100,77 @@ export const docs = [
5957
6100
  "path": "docs/help/migrating-from-primevue-datatable.md",
5958
6101
  "title": "Migrating from PrimeVue / PrimeNG / PrimeReact DataTable",
5959
6102
  "section": "Help",
5960
- "markdown": "\n# Migrating from PrimeVue / PrimeNG / PrimeReact DataTable\n\nThe Prime DataTable is the grid in the Prime UI suites for Vue, Angular,\nand React. Its columns are declared as `<Column>` children with `field`\n/ `header` props - a shape that maps cleanly onto SvGrid's `ColumnDef`\narray. The port is mostly translating columns and events into a Svelte 5\ncomponent. Since PrimeVue 5 the package ships under the PrimeUI licence\nrather than MIT: free for individuals and small organisations under the\nlimits in its licence file, per developer with a licence key otherwise.\nThe facts box below quotes the terms as read on the date shown.\n\n> Estimated effort: **2-4 hours** per grid.\n\n<!-- facts:start primevue-datatable -->\n> **Facts, checked 12 Sep 2026.** `primevue` 5.0.1, Commercial (see licence file), last published 13 Aug 2026, 3,010,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). PrimeVue / PrimeNG / PrimeReact DataTable pricing, as its site states it: primeui.dev lists the Commercial Suite at a launch price of $599 per developer (standard $799) as a perpetual licence with one year of updates, renewable at $399 per developer per year; the Community License is free for individuals, non-profits and organisations under $1M revenue, fewer than five developers, fewer than ten employees and under $3M in venture funding (https://primeui.dev/pricing, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs PrimeVue / PrimeNG / PrimeReact DataTable](https://svgrid.com/compare/primevue-datatable/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Prime DataTable | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<DataTable :value=\"rows\">` | `<SvGrid data={rows}>` |\n| `<Column field=\"name\" header=\"Name\" />` | `{ field: 'name', header: 'Name' }` |\n| `sortable` | `rowSortingFeature` |\n| `:filters` / filter display | `columnFilteringFeature` |\n| `<template #body>` cell slot | `cell: (c) => renderSnippet(...)` |\n| `editMode` + cell editor template | `editorType` (+ custom `cellEditor`) |\n| `:expandedRows` / row expansion | `rowExpandingFeature` |\n| `lazy` + `@page` / `@sort` / `@filter` | `externalSort` / `externalFilter` + events |\n| `paginator` + `:rows` | `showPagination` (+ page size) |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <DataTable :value=\"rows\" paginator :rows=\"25\" sortMode=\"multiple\">\n- <Column field=\"name\" header=\"Name\" sortable />\n- <Column field=\"amount\" header=\"Amount\" sortable>\n- <template #body=\"{ data }\">{{ fmt(data.amount) }}</template>\n- </Column>\n- </DataTable>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What changes\n\n- **`<Column>` children → a `ColumnDef[]` array.**\n- **`#body` slots → `cell` snippets** via `renderSnippet`.\n- **Prime theming → `--sg-*` tokens / Tailwind** - no Prime theme\n dependency.\n- **`lazy` → `externalSort` / `externalFilter`** with refetch on events.\n\n## Frequently asked questions\n\n### How do Prime `<Column>` definitions map to SvGrid?\n\nEach `<Column field header />` becomes a `{ field, header }` object in SvGrid's\n`columns` array, and `#body` templates become `renderSnippet` cells. Sorting and\nfiltering move from per-column props to the `rowSortingFeature` /\n`columnFilteringFeature` registration.\n\n### Is SvGrid open-source like the Prime grid core?\n\n`@svgrid/grid` is MIT with no licence key or eligibility conditions. The\nPrime cores were MIT through PrimeVue 4; from PrimeVue 5 the npm package\ncarries the PrimeUI licence, whose free Community License depends on your\nrevenue, developer count, headcount and funding, and whose Commercial\nLicense is per developer with a key. The other difference is framework:\nSvGrid is Svelte 5, not Vue / Angular / React.\n\n### Do I lose Prime theming?\n\nYou re-create the look with `--sg-*` tokens (optionally driven by your Tailwind\ntheme), so the grid matches your design system without a Prime theme dependency.\n\n## What you end up with\n\nSorting, filtering, pagination and row selection in one pass.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [SvGrid vs Prime DataTable](https://svgrid.com/compare/primevue-datatable/) - the side-by-side comparison\n- [Tailwind integration](./tailwind.md) - match your design system\n- [Cell components](./cells/cell-components.md) - snippet cells + editors\n"
6103
+ "markdown": "\n# Migrating from PrimeVue / PrimeNG / PrimeReact DataTable\n\nThe Prime DataTable is the grid in the Prime UI suites for Vue, Angular,\nand React. Its columns are declared as `<Column>` children with `field`\n/ `header` props - a shape that maps cleanly onto SvGrid's `ColumnDef`\narray. The port is mostly translating columns and events into a Svelte 5\ncomponent. Since PrimeVue 5 the package ships under the PrimeUI licence\nrather than MIT: free for individuals and small organisations under the\nlimits in its licence file, per developer with a licence key otherwise.\nThe facts box below quotes the terms as read on the date shown.\n\n> Estimated effort: **2-4 hours** per grid.\n\n<!-- facts:start primevue-datatable -->\n> **Facts, checked 12 Sep 2026.** `primevue` 5.0.1, Commercial (see licence file), last published 13 Aug 2026, 3,010,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). PrimeVue / PrimeNG / PrimeReact DataTable pricing, as its site states it: primeui.dev lists the Commercial Suite at a launch price of $599 per developer (standard $799) as a perpetual licence with one year of updates, renewable at $399 per developer per year; the Community License is free for individuals, non-profits and organisations under $1M revenue, fewer than five developers, fewer than ten employees and under $3M in venture funding (https://primeui.dev/pricing, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs PrimeVue / PrimeNG / PrimeReact DataTable](https://svgrid.com/compare/primevue-datatable/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Prime DataTable | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<DataTable :value=\"rows\">` | `<SvGrid data={rows}>` |\n| `<Column field=\"name\" header=\"Name\" />` | `{ field: 'name', header: 'Name' }` |\n| `sortable` | `rowSortingFeature` |\n| `:filters` / filter display | `columnFilteringFeature` |\n| `<template #body>` cell slot | `cell: (c) => renderSnippet(...)` |\n| `editMode` + cell editor template | `editorType` (+ custom `cellEditor`) |\n| `:expandedRows` / row expansion | `rowExpandingFeature` |\n| `lazy` + `@page` / `@sort` / `@filter` | `externalSort` / `externalFilter` + events |\n| `paginator` + `:rows` | `showPagination` (+ page size) |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <DataTable :value=\"rows\" paginator :rows=\"25\" sortMode=\"multiple\">\n- <Column field=\"name\" header=\"Name\" sortable />\n- <Column field=\"amount\" header=\"Amount\" sortable>\n- <template #body=\"{ data }\">{{ fmt(data.amount) }}</template>\n- </Column>\n- </DataTable>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What changes\n\n- **`<Column>` children → a `ColumnDef[]` array.**\n- **`#body` slots → `cell` snippets** via `renderSnippet`.\n- **Prime theming → `--sg-*` tokens / Tailwind** - no Prime theme\n dependency.\n- **`lazy` → `externalSort` / `externalFilter`** with refetch on events.\n\n## Frequently asked questions\n\n### How do Prime `<Column>` definitions map to SvGrid?\n\nEach `<Column field header />` becomes a `{ field, header }` object in SvGrid's\n`columns` array, and `#body` templates become `renderSnippet` cells. Sorting and\nfiltering move from per-column props to the `rowSortingFeature` /\n`columnFilteringFeature` registration.\n\n### Is SvGrid open-source like the Prime grid core?\n\n`@svgrid/grid` is MIT with no licence key or eligibility conditions. The\nPrime cores were MIT through PrimeVue 4; from PrimeVue 5 the npm package\ncarries the PrimeUI licence, whose free Community License depends on your\nrevenue, developer count, headcount and funding, and whose Commercial\nLicense is per developer with a key. The other difference is framework:\nSvGrid is Svelte 5, not Vue / Angular / React.\n\n### Do I lose Prime theming?\n\nYou re-create the look with `--sg-*` tokens (optionally driven by your Tailwind\ntheme), so the grid matches your design system without a Prime theme dependency.\n\n## What you end up with\n\nSorting, filtering, pagination and row selection in one pass.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [SvGrid vs Prime DataTable](https://svgrid.com/compare/primevue-datatable/) - the side-by-side comparison\n- [Tailwind integration](./tailwind.md) - match your design system\n- [Cell components](./cells/cell-components.md) - snippet cells + editors\n"
5961
6104
  },
5962
6105
  {
5963
6106
  "slug": "help/migrating-from-react-data-grid",
5964
6107
  "path": "docs/help/migrating-from-react-data-grid.md",
5965
6108
  "title": "Migrating from React Data Grid (adazzle)",
5966
6109
  "section": "Help",
5967
- "markdown": "# Migrating from React Data Grid (adazzle)\n\n`react-data-grid` is a fast, Excel-like React grid with a clean column\nAPI. SvGrid mirrors its shape - virtualized DOM, typed columns, inline\nediting, custom cells - on Svelte 5 runes instead of React, so the port\nis mostly a column rename pass.\n\n> Estimated effort: **2-4 hours** per grid, more if you lean on custom\n> editors.\n\n<!-- facts:start react-data-grid -->\n> **Facts, checked 12 Sep 2026.** `react-data-grid` 7.0.0-beta.61, MIT, last published 14 Jul 2026, 2,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `react-data-grid` 7.0.0-beta.61 15.7 KB JS + 2.1 KB CSS, react + react-dom external (measured 12 Sep 2026). React Data Grid pricing, as its site states it: react-data-grid is MIT on npm and free; no licence is sold (https://github.com/adazzle/react-data-grid, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| react-data-grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<DataGrid columns rows />` | `<SvGrid columns data />` |\n| `{ key: 'name', name: 'Name' }` | `{ field: 'name', header: 'Name' }` |\n| `renderCell: (p) => <Badge .../>` | `cell: (c) => renderSnippet(Badge, {...})` |\n| `renderEditCell` / `editor` | `editorType` (+ custom `cellEditor`) |\n| `rowKeyGetter={(r) => r.id}` | `getRowId={(r) => r.id}` |\n| `onRowsChange={setRows}` | `onCellValueChange` (+ your state) |\n| `sortColumns` / `onSortColumnsChange` | `rowSortingFeature` + `onSortingChange` |\n| `<DataGrid className=...>` theming | `--sg-*` tokens / Tailwind |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import DataGrid, { textEditor } from 'react-data-grid'\n- const columns = [\n- { key: 'name', name: 'Name' },\n- { key: 'amount', name: 'Amount', renderEditCell: textEditor },\n- ]\n- <DataGrid columns={columns} rows={rows} rowKeyGetter={(r) => r.id} onRowsChange={setRows} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', editorType: 'text' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features}\n+ getRowId={(r) => r.id} enableInlineEditing\n+ onCellValueChange={(e) => save(e)} />\n```\n\n## What changes\n\n- **React → Svelte 5.** `renderCell` / `renderEditCell` become\n `renderSnippet` snippets and `editorType`.\n- **`onRowsChange` → `onCellValueChange`.** SvGrid writes to its own\n working copy; subscribe to commits and persist where you like.\n- **Filtering UI is built in.** react-data-grid leaves the filter row to\n you; SvGrid ships the Excel-style menu.\n\n## Frequently asked questions\n\n### How do react-data-grid columns map to SvGrid?\n\n`key` becomes `field`, `name` becomes `header`, `renderCell` becomes a\n`renderSnippet` cell, and editors map to `editorType` (or a custom `cellEditor`\nsnippet). `rowKeyGetter` becomes `getRowId`.\n\n### Is SvGrid free like react-data-grid?\n\nYes - `@svgrid/grid` is MIT-licensed, like react-data-grid. SvGrid adds an\noptional paid Enterprise pack for export, import, pivot, and AI.\n\n### Does SvGrid have built-in filtering?\n\nYes. react-data-grid asks you to build the filter UI; SvGrid ships an\nExcel-style column filter menu and a global filter out of the box.\n\n## What you end up with\n\nInline editing with cell-range selection, which is the reason most people picked it.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection sortable />\n```\n\n## See also\n\n- [SvGrid vs React Data Grid](https://svgrid.com/compare/react-data-grid/) - the side-by-side comparison\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - sibling React-to-Svelte guide\n- [Cell components](./cells/cell-components.md) - custom cells + editors\n"
6110
+ "markdown": "# Migrating from React Data Grid (adazzle)\n\n`react-data-grid` is a fast, Excel-like React grid with a clean column\nAPI. SvGrid mirrors its shape - virtualized DOM, typed columns, inline\nediting, custom cells - on Svelte 5 runes instead of React, so the port\nis mostly a column rename pass.\n\n> Estimated effort: **2-4 hours** per grid, more if you lean on custom\n> editors.\n\n<!-- facts:start react-data-grid -->\n> **Facts, checked 12 Sep 2026.** `react-data-grid` 7.0.0-beta.61, MIT, last published 14 Jul 2026, 2,180,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `react-data-grid` 7.0.0-beta.61 15.7 KB JS + 2.1 KB CSS, react + react-dom external (measured 12 Sep 2026). React Data Grid pricing, as its site states it: react-data-grid is MIT on npm and free; no licence is sold (https://github.com/adazzle/react-data-grid, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| react-data-grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<DataGrid columns rows />` | `<SvGrid columns data />` |\n| `{ key: 'name', name: 'Name' }` | `{ field: 'name', header: 'Name' }` |\n| `renderCell: (p) => <Badge .../>` | `cell: (c) => renderSnippet(Badge, {...})` |\n| `renderEditCell` / `editor` | `editorType` (+ custom `cellEditor`) |\n| `rowKeyGetter={(r) => r.id}` | `getRowId={(r) => r.id}` |\n| `onRowsChange={setRows}` | `onCellValueChange` (+ your state) |\n| `sortColumns` / `onSortColumnsChange` | `rowSortingFeature` + `onSortingChange` |\n| `<DataGrid className=...>` theming | `--sg-*` tokens / Tailwind |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import DataGrid, { textEditor } from 'react-data-grid'\n- const columns = [\n- { key: 'name', name: 'Name' },\n- { key: 'amount', name: 'Amount', renderEditCell: textEditor },\n- ]\n- <DataGrid columns={columns} rows={rows} rowKeyGetter={(r) => r.id} onRowsChange={setRows} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', editorType: 'text' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features}\n+ getRowId={(r) => r.id} enableInlineEditing\n+ onCellValueChange={(e) => save(e)} />\n```\n\n## What changes\n\n- **React → Svelte 5.** `renderCell` / `renderEditCell` become\n `renderSnippet` snippets and `editorType`.\n- **`onRowsChange` → `onCellValueChange`.** SvGrid writes to its own\n working copy; subscribe to commits and persist where you like.\n- **Filtering UI is built in.** react-data-grid leaves the filter row to\n you; SvGrid ships the Excel-style menu.\n\n## Frequently asked questions\n\n### How do react-data-grid columns map to SvGrid?\n\n`key` becomes `field`, `name` becomes `header`, `renderCell` becomes a\n`renderSnippet` cell, and editors map to `editorType` (or a custom `cellEditor`\nsnippet). `rowKeyGetter` becomes `getRowId`.\n\n### Is SvGrid free like react-data-grid?\n\nYes - `@svgrid/grid` is MIT-licensed, like react-data-grid. SvGrid adds an\noptional paid Enterprise pack for export, import, pivot, and AI.\n\n### Does SvGrid have built-in filtering?\n\nYes. react-data-grid asks you to build the filter UI; SvGrid ships an\nExcel-style column filter menu and a global filter out of the box.\n\n## What you end up with\n\nInline editing with cell-range selection, which is the reason most people picked it.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} editable enableCellSelection sortable />\n```\n\n## See also\n\n- [SvGrid vs React Data Grid](https://svgrid.com/compare/react-data-grid/) - the side-by-side comparison\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - sibling React-to-Svelte guide\n- [Cell components](./cells/cell-components.md) - custom cells + editors\n"
5968
6111
  },
5969
6112
  {
5970
6113
  "slug": "help/migrating-from-shadcn-data-table",
5971
6114
  "path": "docs/help/migrating-from-shadcn-data-table.md",
5972
6115
  "title": "Migrating from the shadcn-svelte data table",
5973
6116
  "section": "Help",
5974
- "markdown": "# Migrating from the shadcn-svelte data table\n\nThe shadcn-svelte **Data Table** is not the same thing as its `<Table>`\ncomponent. `<Table>` is presentation only. The data table is a recipe\nbuilt on TanStack Table v9 that you copy into your own repo: it already\ndoes sorting, filtering, pagination, row selection, and column\nvisibility. If that is what you have, this is your page. If you have the\nplain styled `<Table>` and hand-wrote the sorting yourself, read\n[Migrating from a UI-kit table](./migrating-from-ui-kit-tables.md)\ninstead.\n\n> Estimated effort: **20-40 min** per table. Your column definitions and\n> your feature registration carry over almost unchanged. Most of the work\n> is deleting files.\n\n<!-- facts:start tanstack-table,svelte-ui-kit-tables -->\n> **Facts, checked 12 Sep 2026.** `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). Flowbite / Skeleton / shadcn-svelte tables pricing, as its site states it: Flowbite Svelte, Skeleton and shadcn-svelte are MIT component libraries; their table components are free and no grid licence is sold (https://github.com/themesberg/flowbite-svelte, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/), [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/).\n<!-- facts:end -->\n\n## Why this port is small\n\nSvGrid speaks the same vocabulary TanStack Table v9 introduced. These are\nreal exports from `@svgrid/grid`, not lookalikes:\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```ts\nimport {\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n rowSelectionFeature,\n rowExpandingFeature,\n columnGroupingFeature,\n} from '@svgrid/grid'\n```\n\nSo `data-table-features.ts` moves over as-is, and `columns.ts` keeps its\nshape. What does not move is the rendering scaffolding, because SvGrid\nships a renderer and there is nothing to translate it into.\n\n## What happens to each file\n\nThe shadcn recipe generates seven files. Five of them stop existing.\n\n| Their file | Becomes |\n| --- | --- |\n| `data-table-features.ts` | Kept. Same `tableFeatures({...})` call. |\n| `columns.ts` | Kept, minus the `header` render helpers. `{ accessorKey: 'email' }` becomes `{ field: 'email' }`. |\n| `data-table.svelte` | Deleted. It is `<table>` markup over `getHeaderGroups()` / `getRowModel()`, which `<SvGrid>` does. |\n| `data-table-checkbox.svelte` | Deleted. `showRowSelection` renders the column and the select-all header. |\n| `data-table-email-button.svelte` | Deleted. `sortable` makes every header a sort toggle. |\n| `data-table-actions.svelte` | Kept if you want it, as a cell snippet. |\n| `+page.svelte` | Kept. It now renders one component instead of wiring state. |\n\n## Let the codemod do the mechanical part\n\n```bash\nnpx @svgrid/migrate src/routes/payments # preview\nnpx @svgrid/migrate src/routes/payments --write # apply\n```\n\nIt previews by default and only writes with `--write`. Point it at the whole\nroute directory rather than a single file: the shadcn layout keeps `features`\nin its own module, and the codemod follows that import to work out which\nprops the component needs.\n\nIt renames the column keys, re-points the imports, strips the features SvGrid\ndoes not have, and deletes the markup along with the `$state` / `onXChange`\npairs. Custom `cell` and `header` render functions are kept and reported, never\nguessed at. Run your type-checker afterwards - the markup is regenerated rather\nthan edited.\n\n## Before and after\n\n```diff\n- <script lang=\"ts\">\n- import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table'\n- import { columns } from './columns'\n- import { features } from './data-table-features'\n-\n- let sorting = $state([])\n- let filters = $state([])\n- let selection = $state({})\n- let pagination = $state({ pageIndex: 0, pageSize: 10 })\n-\n- const table = createSvelteTable({\n- get data() { return data },\n- columns, features,\n- state: { get sorting() { return sorting }, /* ...and three more... */ },\n- onSortingChange: (u) => (sorting = typeof u === 'function' ? u(sorting) : u),\n- // ...one of these per piece of state...\n- })\n- </script>\n-\n- <Table.Root>\n- <Table.Header>\n- {#each table.getHeaderGroups() as headerGroup}\n- <!-- ...twenty more lines of markup... -->\n- {/each}\n- </Table.Header>\n- <Table.Body>\n- {#each table.getRowModel().rows as row}\n- <!-- ...and twenty more... -->\n- {/each}\n- </Table.Body>\n- </Table.Root>\n\n+ <script lang=\"ts\">\n+ import { SvGrid } from '@svgrid/grid'\n+ import '@svgrid/grid/themes/shadcn.css'\n+ import { columns } from './columns'\n+ import { features } from './data-table-features'\n+ </script>\n+\n+ <SvGrid\n+ {data} {columns} {features}\n+ sortable filterable showGlobalFilter showRowSelection\n+ pageable showPagination pageSize={10}\n+ fitColumns\n+ />\n```\n\nThe four `$state` declarations and their four `onXChange` updaters go\naway with the markup. Sorting, filtering, paging, and selection state\nlive in the grid.\n\nColumn visibility moves too: mark a column `visible: false` to start it\nhidden, and users toggle it from the header column menu. You no longer\nmaintain a dropdown for it.\n\n## One command\n\nUse the CLI you already have:\n\n```sh\nnpx shadcn-svelte@latest add https://svgrid.com/r/data-table.json\n```\n\nThat writes a ready-to-edit `data-table.svelte` into\n`$lib/components/ui/data-table/`, beside your other components, and\ninstalls `@svgrid/grid`. It is a normal registry item, so `components.json`\naliases and your existing setup are respected.\n\nIf you are not in a shadcn project, the same component ships through\nSvGrid's own scaffolder:\n\n```sh\nnpx @svgrid/ui add data-table\n```\n\nBoth routes write the identical file. It is yours to edit, exactly like a\nshadcn recipe. The difference is where the engine lives.\n\n## The upgrade path is the real difference\n\nBoth approaches put a file you own in your repo. Only one puts the\n*engine* in a package.\n\nWhen TanStack Table went from v8 to v9, `useReactTable` became `useTable`,\nthe `get*RowModel()` options became a features object, and `flexRender`\nbecame a component. Every copied data-table had to be hand-fixed, because\nthere is no `npm update` for code you pasted. With SvGrid the file you own\nstays a thin call site, and the behaviour behind it updates with a version\nbump.\n\nThe cost scales with how much you pasted. A seven-file starter is an\nafternoon. The richer community grids paste a whole subsystem - row\nrendering, virtualization, context menus, paste dialogs, hooks, config -\nand every one of those files is now yours to carry through the next\nupstream change.\n\n## Keep your design system\n\nYou do not have to leave shadcn's look, and you do not have to leave its\nmarkup either.\n\n- **Tokens.** `import '@svgrid/grid/themes/shadcn.css'` is a one-line\n match for the default palette in light and dark. To follow a customized\n theme, map your `--background` / `--border` / `--primary` onto the\n `--sg-*` properties - see the [shadcn integration\n guide](./shadcn.md).\n- **Your own markup.** If you want to keep shadcn's `Table.Root` /\n `Table.Row` elements exactly as they are, use the headless core from\n `@svgrid/grid/core` and swap only the engine. See\n [Why headless?](../why-headless.md).\n\n## What you gain\n\nThe official recipe stops where its docs stop: sorting, filtering,\npagination, row selection, column visibility. Community registry items go\nfurther, at the cost of pasting a whole multi-file subsystem into your\nrepo. In SvGrid each of these is a prop:\n\n- **Virtualization** (`virtualization`) - the official recipe has none, so\n a large table is a rewrite rather than a prop.\n- **Inline editing** (`editable`) and cell-range selection\n (`enableCellSelection`).\n- **Grouping with aggregation** (`groupable`) and tree data (`treeData`).\n- **Export** to CSV, and to Excel / PDF on the paid tier.\n- **WAI-ARIA grid semantics and keyboard navigation**, instead of a plain\n `<table>` you keep accessible yourself.\n\n## What you give up\n\n- **A file you can read top to bottom.** The recipe's behaviour is\n visible in your repo; SvGrid's is behind a prop. That is the trade the\n whole page is about.\n- **Pixel-level control of the markup**, unless you go headless.\n- **Weight.** For a short static list that never sorts, the copied\n recipe is smaller.\n\n## Frequently asked questions\n\n### Does SvGrid replace shadcn-svelte?\n\nNo. It replaces one recipe in it. Your buttons, dialogs, and inputs stay\nexactly as they are, and the grid reads the same theme variables they do.\n\n### Can I keep my existing columns.ts?\n\nMostly. Rename `accessorKey` to `field`, drop the `header` render\nhelpers that only existed to draw a sort button, and the rest carries\nover. Custom cells become snippets via `renderSnippet`.\n\n### Do I have to give up owning the code?\n\nYou still own the call site - `npx @svgrid/ui add data-table` writes a\nfile into your project that you edit freely. What you stop owning is the\nrow-model plumbing, which is the part that broke on the v8 to v9 upgrade.\n\n### Is this worth it for a 50-row table?\n\nProbably not, unless you want editing, grouping, or export later. The\ncase gets strong when the table grows past what fits on a page, or when\nthe next feature request is one you would otherwise hand-build.\n\n## What you end up with\n\nSorting, filtering, pagination and selection - the shadcn data-table demo, as props.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [shadcn-svelte integration](./shadcn.md) - matching the theme\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - the\n underlying API map\n- [Migrating from a UI-kit table](./migrating-from-ui-kit-tables.md) - for\n the plain styled `<Table>`\n- [Why headless?](../why-headless.md) - keeping your own markup\n"
6117
+ "markdown": "# Migrating from the shadcn-svelte data table\n\nThe shadcn-svelte **Data Table** is not the same thing as its `<Table>`\ncomponent. `<Table>` is presentation only. The data table is a recipe\nbuilt on TanStack Table v9 that you copy into your own repo: it already\ndoes sorting, filtering, pagination, row selection, and column\nvisibility. If that is what you have, this is your page. If you have the\nplain styled `<Table>` and hand-wrote the sorting yourself, read\n[Migrating from a UI-kit table](./migrating-from-ui-kit-tables.md)\ninstead.\n\n> Estimated effort: **20-40 min** per table. Your column definitions and\n> your feature registration carry over almost unchanged. Most of the work\n> is deleting files.\n\n<!-- facts:start tanstack-table,svelte-ui-kit-tables -->\n> **Facts, checked 12 Sep 2026.** `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). Flowbite / Skeleton / shadcn-svelte tables pricing, as its site states it: Flowbite Svelte, Skeleton and shadcn-svelte are MIT component libraries; their table components are free and no grid licence is sold (https://github.com/themesberg/flowbite-svelte, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/), [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/).\n<!-- facts:end -->\n\n## Why this port is small\n\nSvGrid speaks the same vocabulary TanStack Table v9 introduced. These are\nreal exports from `@svgrid/grid`, not lookalikes:\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```ts\nimport {\n tableFeatures,\n rowSortingFeature,\n columnFilteringFeature,\n rowPaginationFeature,\n rowSelectionFeature,\n rowExpandingFeature,\n columnGroupingFeature,\n} from '@svgrid/grid'\n```\n\nSo `data-table-features.ts` moves over as-is, and `columns.ts` keeps its\nshape. What does not move is the rendering scaffolding, because SvGrid\nships a renderer and there is nothing to translate it into.\n\n## What happens to each file\n\nThe shadcn recipe generates seven files. Five of them stop existing.\n\n| Their file | Becomes |\n| --- | --- |\n| `data-table-features.ts` | Kept. Same `tableFeatures({...})` call. |\n| `columns.ts` | Kept, minus the `header` render helpers. `{ accessorKey: 'email' }` becomes `{ field: 'email' }`. |\n| `data-table.svelte` | Deleted. It is `<table>` markup over `getHeaderGroups()` / `getRowModel()`, which `<SvGrid>` does. |\n| `data-table-checkbox.svelte` | Deleted. `showRowSelection` renders the column and the select-all header. |\n| `data-table-email-button.svelte` | Deleted. `sortable` makes every header a sort toggle. |\n| `data-table-actions.svelte` | Kept if you want it, as a cell snippet. |\n| `+page.svelte` | Kept. It now renders one component instead of wiring state. |\n\n## Let the codemod do the mechanical part\n\n```bash\nnpx @svgrid/migrate src/routes/payments # preview\nnpx @svgrid/migrate src/routes/payments --write # apply\n```\n\nIt previews by default and only writes with `--write`. Point it at the whole\nroute directory rather than a single file: the shadcn layout keeps `features`\nin its own module, and the codemod follows that import to work out which\nprops the component needs.\n\nIt renames the column keys, re-points the imports, strips the features SvGrid\ndoes not have, and deletes the markup along with the `$state` / `onXChange`\npairs. Custom `cell` and `header` render functions are kept and reported, never\nguessed at. Run your type-checker afterwards - the markup is regenerated rather\nthan edited.\n\n## Before and after\n\n```diff\n- <script lang=\"ts\">\n- import { createSvelteTable, FlexRender } from '$lib/components/ui/data-table'\n- import { columns } from './columns'\n- import { features } from './data-table-features'\n-\n- let sorting = $state([])\n- let filters = $state([])\n- let selection = $state({})\n- let pagination = $state({ pageIndex: 0, pageSize: 10 })\n-\n- const table = createSvelteTable({\n- get data() { return data },\n- columns, features,\n- state: { get sorting() { return sorting }, /* ...and three more... */ },\n- onSortingChange: (u) => (sorting = typeof u === 'function' ? u(sorting) : u),\n- // ...one of these per piece of state...\n- })\n- </script>\n-\n- <Table.Root>\n- <Table.Header>\n- {#each table.getHeaderGroups() as headerGroup}\n- <!-- ...twenty more lines of markup... -->\n- {/each}\n- </Table.Header>\n- <Table.Body>\n- {#each table.getRowModel().rows as row}\n- <!-- ...and twenty more... -->\n- {/each}\n- </Table.Body>\n- </Table.Root>\n\n+ <script lang=\"ts\">\n+ import { SvGrid } from '@svgrid/grid'\n+ import '@svgrid/grid/themes/shadcn.css'\n+ import { columns } from './columns'\n+ import { features } from './data-table-features'\n+ </script>\n+\n+ <SvGrid\n+ {data} {columns} {features}\n+ sortable filterable showGlobalFilter showRowSelection\n+ pageable showPagination pageSize={10}\n+ fitColumns\n+ />\n```\n\nThe four `$state` declarations and their four `onXChange` updaters go\naway with the markup. Sorting, filtering, paging, and selection state\nlive in the grid.\n\nColumn visibility moves too: mark a column `visible: false` to start it\nhidden, and users toggle it from the header column menu. You no longer\nmaintain a dropdown for it.\n\n## One command\n\nUse the CLI you already have:\n\n```sh\nnpx shadcn-svelte@latest add https://svgrid.com/r/data-table.json\n```\n\nThat writes a ready-to-edit `data-table.svelte` into\n`$lib/components/ui/data-table/`, beside your other components, and\ninstalls `@svgrid/grid`. It is a normal registry item, so `components.json`\naliases and your existing setup are respected.\n\nIf you are not in a shadcn project, the same component ships through\nSvGrid's own scaffolder:\n\n```sh\nnpx @svgrid/ui add data-table\n```\n\nBoth routes write the identical file. It is yours to edit, exactly like a\nshadcn recipe. The difference is where the engine lives.\n\n## The upgrade path is the real difference\n\nBoth approaches put a file you own in your repo. Only one puts the\n*engine* in a package.\n\nWhen TanStack Table went from v8 to v9, `useReactTable` became `useTable`,\nthe `get*RowModel()` options became a features object, and `flexRender`\nbecame a component. Every copied data-table had to be hand-fixed, because\nthere is no `npm update` for code you pasted. With SvGrid the file you own\nstays a thin call site, and the behaviour behind it updates with a version\nbump.\n\nThe cost scales with how much you pasted. A seven-file starter is an\nafternoon. The richer community grids paste a whole subsystem - row\nrendering, virtualization, context menus, paste dialogs, hooks, config -\nand every one of those files is now yours to carry through the next\nupstream change.\n\n## Keep your design system\n\nYou do not have to leave shadcn's look, and you do not have to leave its\nmarkup either.\n\n- **Tokens.** `import '@svgrid/grid/themes/shadcn.css'` is a one-line\n match for the default palette in light and dark. To follow a customized\n theme, map your `--background` / `--border` / `--primary` onto the\n `--sg-*` properties - see the [shadcn integration\n guide](./shadcn.md).\n- **Your own markup.** If you want to keep shadcn's `Table.Root` /\n `Table.Row` elements exactly as they are, use the headless core from\n `@svgrid/grid/core` and swap only the engine. See\n [Why headless?](../why-headless.md).\n\n## What you gain\n\nThe official recipe stops where its docs stop: sorting, filtering,\npagination, row selection, column visibility. Community registry items go\nfurther, at the cost of pasting a whole multi-file subsystem into your\nrepo. In SvGrid each of these is a prop:\n\n- **Virtualization** (`virtualization`) - the official recipe has none, so\n a large table is a rewrite rather than a prop.\n- **Inline editing** (`editable`) and cell-range selection\n (`enableCellSelection`).\n- **Grouping with aggregation** (`groupable`) and tree data (`treeData`).\n- **Export** to CSV, and to Excel / PDF on the paid tier.\n- **WAI-ARIA grid semantics and keyboard navigation**, instead of a plain\n `<table>` you keep accessible yourself.\n\n## What you give up\n\n- **A file you can read top to bottom.** The recipe's behaviour is\n visible in your repo; SvGrid's is behind a prop. That is the trade the\n whole page is about.\n- **Pixel-level control of the markup**, unless you go headless.\n- **Weight.** For a short static list that never sorts, the copied\n recipe is smaller.\n\n## Frequently asked questions\n\n### Does SvGrid replace shadcn-svelte?\n\nNo. It replaces one recipe in it. Your buttons, dialogs, and inputs stay\nexactly as they are, and the grid reads the same theme variables they do.\n\n### Can I keep my existing columns.ts?\n\nMostly. Rename `accessorKey` to `field`, drop the `header` render\nhelpers that only existed to draw a sort button, and the rest carries\nover. Custom cells become snippets via `renderSnippet`.\n\n### Do I have to give up owning the code?\n\nYou still own the call site - `npx @svgrid/ui add data-table` writes a\nfile into your project that you edit freely. What you stop owning is the\nrow-model plumbing, which is the part that broke on the v8 to v9 upgrade.\n\n### Is this worth it for a 50-row table?\n\nProbably not, unless you want editing, grouping, or export later. The\ncase gets strong when the table grows past what fits on a page, or when\nthe next feature request is one you would otherwise hand-build.\n\n## What you end up with\n\nSorting, filtering, pagination and selection - the shadcn data-table demo, as props.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [shadcn-svelte integration](./shadcn.md) - matching the theme\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - the\n underlying API map\n- [Migrating from a UI-kit table](./migrating-from-ui-kit-tables.md) - for\n the plain styled `<Table>`\n- [Why headless?](../why-headless.md) - keeping your own markup\n"
5975
6118
  },
5976
6119
  {
5977
6120
  "slug": "help/migrating-from-smart-grid",
5978
6121
  "path": "docs/help/migrating-from-smart-grid.md",
5979
6122
  "title": "Migrating from Smart.Grid (Smart Web Components)",
5980
6123
  "section": "Help",
5981
- "markdown": "\n# Migrating from Smart.Grid (Smart Web Components)\n\nSmart.Grid (htmlelements.com) and SvGrid come from the **same team**.\nSmart.Grid is a framework-agnostic custom element - it even works inside\nSvelte today - while SvGrid is the reactive, Svelte-5-native option. If\nyou are standardising a Svelte app on idiomatic components, this guide\nmaps a Smart.Grid setup onto SvGrid.\n\n> Estimated effort: **2-4 hours** per grid. The main shift is from a\n> custom element bound through properties / attributes to a reactive\n> Svelte component.\n\n<!-- facts:start smart-grid -->\n> **Facts, checked 12 Sep 2026.** `smart-webcomponents` 27.0.1, ISC, last published 13 Aug 2026, 6,620 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). Smart.Grid pricing, as its site states it: htmlelements.com lists the Developer License at $499 (on sale at $399) per developer, perpetual, or $39 per month, and the Team License at $1,499 per five developers; the free Community License covers the core components but not the Grid (https://www.htmlelements.com/license/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Smart.Grid (Smart Web Components)](https://svgrid.com/compare/smart-grid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Smart.Grid (web component) | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<smart-grid>` element | `<SvGrid ... />` |\n| `grid.dataSource = new Smart.DataAdapter`| `data` array (or `externalSort/Filter`) |\n| `{ label: 'Name', dataField: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `template` / cell template | `cell: (c) => renderSnippet(...)` |\n| `editing` + editor | `enableInlineEditing` + `editorType` |\n| `sorting` / `filtering` | `rowSortingFeature` / `columnFilteringFeature` |\n| `grouping` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `paging` + `pager` | `showPagination` |\n| element events (`change`, ...) | `onCellValueChange`, `onApiReady` |\n| `theme` attribute | `--sg-*` tokens / Tailwind |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <smart-grid id=\"grid\" sorting filtering paging></smart-grid>\n- <script>\n- const grid = document.querySelector('#grid')\n- grid.dataSource = new Smart.DataAdapter({ dataSource: rows, dataFields: [...] })\n- grid.columns = [\n- { label: 'Name', dataField: 'name' },\n- { label: 'Amount', dataField: 'amount' },\n- ]\n- </script>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What changes\n\n- **Custom element + DataAdapter → reactive `$state`.** Data binding is a\n prop, not an assigned `dataSource`.\n- **Element templates → Svelte snippets** via `renderSnippet`.\n- **`theme` attribute → `--sg-*` tokens.**\n\n## A note on family\n\nSmart.Grid is a genuinely good framework-agnostic grid from the same\nteam, and it runs in Svelte as a web component. The reason to pick SvGrid\nis *idiomatic* Svelte: runes, snippets, and an MIT core. If you need one\ngrid across Angular, React, Vue, Svelte, and vanilla, Smart.Grid is the\nright call.\n\n## Frequently asked questions\n\n### Is SvGrid from the same team as Smart.Grid?\n\nYes. Smart Web Components (htmlelements.com) and SvGrid are built by the same\nteam. SvGrid is the Svelte-5-native option with an MIT community core.\n\n### Can I keep using Smart.Grid in Svelte instead?\n\nYes - Smart.Grid is a web component and works inside Svelte. Choose SvGrid when\nyou want an idiomatic Svelte component (runes + snippets) rather than a custom\nelement bound through properties.\n\n### How do Smart.Grid columns map to SvGrid?\n\n`label` becomes `header`, `dataField` becomes `field`, and element templates\nbecome `renderSnippet` cells. Sorting / filtering / grouping move to registered\nfeatures.\n\n## More examples\n\n### Smart.Chart integration\n\nMounts a <smart-chart> web component (htmlelements.com) and pipes the grid's displayed rows into its dataSource. Re-aggregates on every filter / sort.\n\n<div data-docs-demo=\"77-smart-chart\" data-height=\"460\"></div>\n\n## What you end up with\n\nSorting, filtering and editing with a footer summary.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable summary />\n```\n\n## The ported grid, running\n\nSorting, filtering, editing and a totals row - the working set a Smart grid\nusually carries, as props.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n city: string\n age: number\n salary: number\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', city: 'Portland', age: 54, salary: 155000 },\n ]\n\n let rows = $state<Person[]>(seed.map((p) => ({ ...p })))\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180, editorType: 'text' },\n { field: 'city', header: 'City', width: 150, editorType: 'text' },\n { field: 'salary', header: 'Salary', width: 150, editorType: 'number', summary: 'sum',\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid data={rows} {columns} sortable filterable editable summary />\n```\n\n## See also\n\n- [SvGrid vs Smart.Grid](https://svgrid.com/compare/smart-grid/) - the side-by-side comparison\n- [About SvGrid](https://svgrid.com/about/) - built by jQWidgets / htmlelements.com\n- [Cell components](./cells/cell-components.md) - snippet-based custom cells\n"
6124
+ "markdown": "\n# Migrating from Smart.Grid (Smart Web Components)\n\nSmart.Grid (htmlelements.com) and SvGrid come from the **same team**.\nSmart.Grid is a framework-agnostic custom element - it even works inside\nSvelte today - while SvGrid is the reactive, Svelte-5-native option. If\nyou are standardising a Svelte app on idiomatic components, this guide\nmaps a Smart.Grid setup onto SvGrid.\n\n> Estimated effort: **2-4 hours** per grid. The main shift is from a\n> custom element bound through properties / attributes to a reactive\n> Svelte component.\n\n<!-- facts:start smart-grid -->\n> **Facts, checked 12 Sep 2026.** `smart-webcomponents` 27.0.1, ISC, last published 13 Aug 2026, 6,620 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). Smart.Grid pricing, as its site states it: htmlelements.com lists the Developer License at $499 (on sale at $399) per developer, perpetual, or $39 per month, and the Team License at $1,499 per five developers; the free Community License covers the core components but not the Grid (https://www.htmlelements.com/license/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Smart.Grid (Smart Web Components)](https://svgrid.com/compare/smart-grid/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Smart.Grid (web component) | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `<smart-grid>` element | `<SvGrid ... />` |\n| `grid.dataSource = new Smart.DataAdapter`| `data` array (or `externalSort/Filter`) |\n| `{ label: 'Name', dataField: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `template` / cell template | `cell: (c) => renderSnippet(...)` |\n| `editing` + editor | `enableInlineEditing` + `editorType` |\n| `sorting` / `filtering` | `rowSortingFeature` / `columnFilteringFeature` |\n| `grouping` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `paging` + `pager` | `showPagination` |\n| element events (`change`, ...) | `onCellValueChange`, `onApiReady` |\n| `theme` attribute | `--sg-*` tokens / Tailwind |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <smart-grid id=\"grid\" sorting filtering paging></smart-grid>\n- <script>\n- const grid = document.querySelector('#grid')\n- grid.dataSource = new Smart.DataAdapter({ dataSource: rows, dataFields: [...] })\n- grid.columns = [\n- { label: 'Name', dataField: 'name' },\n- { label: 'Amount', dataField: 'amount' },\n- ]\n- </script>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## What changes\n\n- **Custom element + DataAdapter → reactive `$state`.** Data binding is a\n prop, not an assigned `dataSource`.\n- **Element templates → Svelte snippets** via `renderSnippet`.\n- **`theme` attribute → `--sg-*` tokens.**\n\n## A note on family\n\nSmart.Grid is a genuinely good framework-agnostic grid from the same\nteam, and it runs in Svelte as a web component. The reason to pick SvGrid\nis *idiomatic* Svelte: runes, snippets, and an MIT core. If you need one\ngrid across Angular, React, Vue, Svelte, and vanilla, Smart.Grid is the\nright call.\n\n## Frequently asked questions\n\n### Is SvGrid from the same team as Smart.Grid?\n\nYes. Smart Web Components (htmlelements.com) and SvGrid are built by the same\nteam. SvGrid is the Svelte-5-native option with an MIT community core.\n\n### Can I keep using Smart.Grid in Svelte instead?\n\nYes - Smart.Grid is a web component and works inside Svelte. Choose SvGrid when\nyou want an idiomatic Svelte component (runes + snippets) rather than a custom\nelement bound through properties.\n\n### How do Smart.Grid columns map to SvGrid?\n\n`label` becomes `header`, `dataField` becomes `field`, and element templates\nbecome `renderSnippet` cells. Sorting / filtering / grouping move to registered\nfeatures.\n\n## More examples\n\n### Smart.Chart integration\n\nMounts a <smart-chart> web component (htmlelements.com) and pipes the grid's displayed rows into its dataSource. Re-aggregates on every filter / sort.\n\n<div data-docs-demo=\"77-smart-chart\" data-height=\"460\"></div>\n\n## What you end up with\n\nSorting, filtering and editing with a footer summary.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable summary />\n```\n\n## The ported grid, running\n\nSorting, filtering, editing and a totals row - the working set a Smart grid\nusually carries, as props.\n\n```svelte {runnable}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n city: string\n age: number\n salary: number\n }\n\n const seed: Person[] = [\n { id: 1, name: 'Ada Lovelace', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', city: 'Portland', age: 54, salary: 155000 },\n ]\n\n let rows = $state<Person[]>(seed.map((p) => ({ ...p })))\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 180, editorType: 'text' },\n { field: 'city', header: 'City', width: 150, editorType: 'text' },\n { field: 'salary', header: 'Salary', width: 150, editorType: 'number', summary: 'sum',\n format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n\n<SvGrid data={rows} {columns} sortable filterable editable summary />\n```\n\n## See also\n\n- [SvGrid vs Smart.Grid](https://svgrid.com/compare/smart-grid/) - the side-by-side comparison\n- [About SvGrid](https://svgrid.com/about/) - built by jQWidgets / htmlelements.com\n- [Cell components](./cells/cell-components.md) - snippet-based custom cells\n"
5982
6125
  },
5983
6126
  {
5984
6127
  "slug": "help/migrating-from-svar-svelte-datagrid",
5985
6128
  "path": "docs/help/migrating-from-svar-svelte-datagrid.md",
5986
6129
  "title": "Migrating from SVAR Svelte DataGrid",
5987
6130
  "section": "Help",
5988
- "markdown": "# Migrating from SVAR Svelte DataGrid\n\nSVAR Svelte DataGrid (`wx-svelte-grid`) is, like SvGrid, an actual\nSvelte-native grid rather than a wrapper, and both are MIT-licensed and\nfree for commercial use. Because both are component-first with\narray-of-object column definitions, a port is mostly a configuration\ntranslation. The reasons people switch are **capability** (SvGrid adds\nrow grouping with aggregation, master-detail, Excel-style cell-range\nselection, integrated charts, and pivot) and **architecture** (SvGrid\nalso exposes a headless engine and an MCP server).\n\n> Estimated effort: **2-4 hours** per grid - a prop and event rename\n> pass, plus re-theming.\n>\n> SVAR's exact prop and event names evolve across releases; check the\n> current SVAR docs and map them onto the SvGrid equivalents below.\n\n<!-- facts:start svar-svelte-datagrid -->\n> **Facts, checked 12 Sep 2026.** `wx-svelte-grid` 2.7.0, MIT, last published 3 Jun 2026, 62,800 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `wx-svelte-grid` 2.7.0 51.5 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). SVAR Svelte DataGrid pricing, as its site states it: The DataGrid is MIT and free for commercial use with no paid tier; svar.dev sells PRO editions of its Gantt, Calendar and Kanban components and offers paid consulting and custom development, with no price list for the grid (https://svar.dev/svelte/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/).\n<!-- facts:end -->\n\n## Concept map\n\n| SVAR DataGrid (wx-svelte-grid) | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `<Grid {data} {columns} />` | `<SvGrid data={...} columns={...} />` |\n| `columns: [{ id, header, width, ... }]` | `columns: [{ field, header, width, ... }]` |\n| `sizes={{ rowHeight, columnWidth }}` | `rowHeight` prop, `width` per column |\n| `autoRowHeight` | `autoRowHeight` |\n| Per-column `editor` / `template` | `editorType` + `cell` snippet |\n| `sort: true` on a column, `sortMarks` | `rowSortingFeature`; `initialSorting` |\n| Header filters, the Filter component | `columnFilteringFeature`; Excel-style menu and filter row built in |\n| `tree` prop + `data` with children | `treeData={{ parentField }}` or `rowExpandingFeature` with sub rows |\n| `select` / `multiselect` | `selectionMode=\"row\"` (+ checkbox column) |\n| `split={{ left: n }}` (pinned columns) | `initialColumnPinning` or `pinned: 'left' \\| 'right'` per column |\n| `reorder` (row drag) | `rowDragManaged` |\n| `undo` prop, undo/redo hotkeys | `history` prop; `api.undo()` / `api.redo()` |\n| Context menu component | `contextMenu` prop with items |\n| `init={(api) => ...}` | `onApiReady={(api) => ...}` |\n| `api.exec('sort-rows', { key, order })` | `api.setSort(field, 'asc' \\| 'desc')` |\n| `api.exec('filter-rows', { filter })` | `api.setFilter(field, { operator, value })` |\n| `api.on('...')` event bus | `onXxx` callback props |\n| Export to CSV, print API | `api.exportCsv()` (free); print in `@svgrid/enterprise` |\n| `RestDataProvider` | server-side row model / `externalSort` + `externalFilter` |\n| Theme / skin components (Willow, Material)| `--sg-*` CSS custom properties / Tailwind |\n\n## Before / after (shape, not exact prop names)\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { Grid } from 'wx-svelte-grid'\n- const columns = [\n- { id: 'name', header: 'Name', width: 200 },\n- { id: 'amount', header: 'Amount', width: 120, editor: 'text' },\n- ]\n- </script>\n-\n- <Grid {data} {columns} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name', width: 200 },\n+ { field: 'amount', header: 'Amount', width: 120, editorType: 'text' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={data} columns={columns} features={features} enableInlineEditing />\n```\n\n## Licensing note\n\nBoth grids are MIT and free for commercial use, so licensing is not the\ndeciding factor. The difference is monetization: SVAR keeps the whole\ngrid free (including CSV export and print) and sells PRO editions of its\nGantt, Calendar and Kanban instead, whereas SvGrid's `@svgrid/grid` core is\nMIT and the optional `@svgrid/enterprise` pack (XLSX/PDF export, print,\npivot, import, support) is the paid piece. CSV, TSV and JSON export and the\nin-grid AI helpers are free on SvGrid too. If all you need is CSV export and\nprint, SVAR gives both free; if you need pivot, Excel or PDF output, or a\nsupport SLA, that is Enterprise on SvGrid.\n\n## What you get with SvGrid\n\n- **Row grouping with aggregation**, **master-detail**, **pinned rows**,\n and left/right column freezing - beyond SVAR's documented surface.\n- A **headless engine** (`createSvGrid` + row models) in addition to the\n component, if you want to compose your own layer.\n- **Excel-style filter menu**, **cell-range selection + TSV copy**, a\n **fill handle**, **integrated charts**, and a documented **imperative API**.\n- **In-grid AI helpers** (natural-language filter, smart fill, summarise),\n free against a model you register, and **@svgrid/mcp** so AI assistants\n answer accurately about your grid and can check the code they write.\n\nThe two features most SVAR teams port for:\n\n<div data-docs-demo=\"07-grouping-aggregation\" data-height=\"520\"></div>\n\n<div data-docs-demo=\"181-master-detail-grid\" data-height=\"520\"></div>\n\n## What you give up\n\n- **Free printing.** SVAR's print API is in the MIT grid; SvGrid's print\n view is in `@svgrid/enterprise`.\n- **The React and Vue versions** of the same grid. SvGrid is Svelte-only.\n- **A smaller bundle.** The facts box at the top of the page has both\n packages measured the same way; the difference is the grouping,\n master/detail, range editing, charts and server-side data (flat paging and infinite scroll free; grouping, tree, pivot and transactions on the server are Enterprise) SvGrid\n carries, and features you never import load as separate chunks.\n- **The SVAR suite around the grid.** Gantt, Calendar, Kanban and File\n Manager share SVAR's core; SvGrid's Kanban and scheduler are views of the\n grid in `@svgrid/enterprise`.\n\n## What to check on the SVAR side\n\n- The **wider SVAR suite** (Gantt, Calendar, Kanban) - if you use several\n SVAR components together, staying on SVAR may be simpler.\n- Any **SVAR-specific column features** you rely on; map each to a SvGrid\n `cell` snippet, `editorType`, or feature before porting.\n- **Filter functions.** SVAR filters with a predicate you write; SvGrid's\n filter takes an operator and a value per column, and `externalFilter`\n hands you the rows when you want to keep a custom predicate.\n\n## Frequently asked questions\n\n### Why move from SVAR Svelte DataGrid to SvGrid?\n\nCapability and architecture, not licensing (both are MIT). SvGrid adds row\ngrouping with aggregation, master-detail, Excel-style cell-range selection,\nintegrated charts, and pivot, and it ships a headless engine plus an MCP server\nalongside the component. Both are Svelte-native, so the core grid\nbehaviour is comparable; SvGrid covers more ground.\n\n### Is the migration a rewrite?\n\nNo. Both are component-first with array-of-object columns, so it is mostly a\nprop / event rename pass (`id` → `field`, edit events → `onCellValueChange`)\nplus re-theming through `--sg-*` tokens.\n\n### Are SvGrid and SVAR both free and MIT?\n\nYes. `@svgrid/grid` and the SVAR DataGrid are both MIT and free for\ncommercial, closed-source use. SVAR keeps the whole grid free and sells PRO\neditions of its Gantt, Calendar and Kanban; on SvGrid, only the optional\n`@svgrid/enterprise` add-on (Excel and PDF export, print, pivot, import,\nsupport) is paid. The dated statement from svar.dev is in the facts box at\nthe top of this page.\n\n### How does SVAR's tree data map to SvGrid?\n\nSVAR takes hierarchical data with the `tree` prop. SvGrid takes either a\nflat array with a parent field (`treeData={{ parentField: 'parentId' }}`)\nor nested rows through `rowExpandingFeature`, and the same grid also does\nmaster/detail, which SVAR's docs do not list. The example below runs the\nflat shape:\n\n## What you end up with\n\nGrouping with aggregation and a totals row, the main capability step up.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} summary groupable sortable filterable />\n```\n\nAnd the tree shape, from the same rows with a parent link, which is what SVAR's `tree` prop becomes:\n\n```svelte {runnable}\n<SvGrid data={rows.map((r, i) => ({ ...r, parentId: i === 0 ? null : rows[0].id }))} {columns} treeData={{ parentField: 'parentId' }} sortable />\n```\n\n## See also\n\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/) - the side-by-side comparison, with a source and date for every claim and the measured benchmark\n- [Grouping and aggregation](./grouping-aggregation.md) - the first demo above\n- [Master/detail](./rows/master-detail.md) - the second demo above\n- [Architecture](./architecture.md) - the engine + render-component split\n- [Cell components](./cells/cell-components.md) - custom cells and editors\n"
6131
+ "markdown": "# Migrating from SVAR Svelte DataGrid\n\nSVAR Svelte DataGrid (`wx-svelte-grid`) is, like SvGrid, an actual\nSvelte-native grid rather than a wrapper, and both are MIT-licensed and\nfree for commercial use. Because both are component-first with\narray-of-object column definitions, a port is mostly a configuration\ntranslation. The reasons people switch are **capability** (SvGrid adds\nrow grouping with aggregation, master-detail, Excel-style cell-range\nselection, integrated charts, and pivot) and **architecture** (SvGrid\nalso exposes a headless engine and an MCP server).\n\n> Estimated effort: **2-4 hours** per grid - a prop and event rename\n> pass, plus re-theming.\n>\n> SVAR's exact prop and event names evolve across releases; check the\n> current SVAR docs and map them onto the SvGrid equivalents below.\n\n<!-- facts:start svar-svelte-datagrid -->\n> **Facts, checked 12 Sep 2026.** `wx-svelte-grid` 2.7.0, MIT, last published 3 Jun 2026, 62,800 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `wx-svelte-grid` 2.7.0 51.5 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). SVAR Svelte DataGrid pricing, as its site states it: The DataGrid is MIT and free for commercial use with no paid tier; svar.dev sells PRO editions of its Gantt, Calendar and Kanban components and offers paid consulting and custom development, with no price list for the grid (https://svar.dev/svelte/, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/).\n<!-- facts:end -->\n\n## Concept map\n\n| SVAR DataGrid (wx-svelte-grid) | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `<Grid {data} {columns} />` | `<SvGrid data={...} columns={...} />` |\n| `columns: [{ id, header, width, ... }]` | `columns: [{ field, header, width, ... }]` |\n| `sizes={{ rowHeight, columnWidth }}` | `rowHeight` prop, `width` per column |\n| `autoRowHeight` | `autoRowHeight` |\n| Per-column `editor` / `template` | `editorType` + `cell` snippet |\n| `sort: true` on a column, `sortMarks` | `rowSortingFeature`; `initialSorting` |\n| Header filters, the Filter component | `columnFilteringFeature`; Excel-style menu and filter row built in |\n| `tree` prop + `data` with children | `treeData={{ parentField }}` or `rowExpandingFeature` with sub rows |\n| `select` / `multiselect` | `selectionMode=\"row\"` (+ checkbox column) |\n| `split={{ left: n }}` (pinned columns) | `initialColumnPinning` or `pinned: 'left' \\| 'right'` per column |\n| `reorder` (row drag) | `rowDragManaged` |\n| `undo` prop, undo/redo hotkeys | `history` prop; `api.undo()` / `api.redo()` |\n| Context menu component | `contextMenu` prop with items |\n| `init={(api) => ...}` | `onApiReady={(api) => ...}` |\n| `api.exec('sort-rows', { key, order })` | `api.setSort(field, 'asc' \\| 'desc')` |\n| `api.exec('filter-rows', { filter })` | `api.setFilter(field, { operator, value })` |\n| `api.on('...')` event bus | `onXxx` callback props |\n| Export to CSV, print API | `api.exportCsv()` (free); print in `@svgrid/enterprise` |\n| `RestDataProvider` | server-side row model / `externalSort` + `externalFilter` |\n| Theme / skin components (Willow, Material)| `--sg-*` CSS custom properties / Tailwind |\n\n## Before / after (shape, not exact prop names)\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { Grid } from 'wx-svelte-grid'\n- const columns = [\n- { id: 'name', header: 'Name', width: 200 },\n- { id: 'amount', header: 'Amount', width: 120, editor: 'text' },\n- ]\n- </script>\n-\n- <Grid {data} {columns} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name', width: 200 },\n+ { field: 'amount', header: 'Amount', width: 120, editorType: 'text' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={data} columns={columns} features={features} enableInlineEditing />\n```\n\n## Licensing note\n\nBoth grids are MIT and free for commercial use, so licensing is not the\ndeciding factor. The difference is monetization: SVAR keeps the whole\ngrid free (including CSV export and print) and sells PRO editions of its\nGantt, Calendar and Kanban instead, whereas SvGrid's `@svgrid/grid` core is\nMIT and the optional `@svgrid/enterprise` pack (XLSX/PDF export, print,\npivot, import, support) is the paid piece. CSV, TSV and JSON export and the\nin-grid AI helpers are free on SvGrid too. If all you need is CSV export and\nprint, SVAR gives both free; if you need pivot, Excel or PDF output, or a\nsupport SLA, that is Enterprise on SvGrid.\n\n## What you get with SvGrid\n\n- **Row grouping with aggregation**, **master-detail**, **pinned rows**,\n and left/right column freezing - beyond SVAR's documented surface.\n- A **headless engine** (`createSvGrid` + row models) in addition to the\n component, if you want to compose your own layer.\n- **Excel-style filter menu**, **cell-range selection + TSV copy**, a\n **fill handle**, **integrated charts**, and a documented **imperative API**.\n- **In-grid AI helpers** (natural-language filter, smart fill, summarise),\n free against a model you register, and **@svgrid/mcp** so AI assistants\n answer accurately about your grid and can check the code they write.\n\nThe two features most SVAR teams port for:\n\n<div data-docs-demo=\"07-grouping-aggregation\" data-height=\"520\"></div>\n\n<div data-docs-demo=\"181-master-detail-grid\" data-height=\"520\"></div>\n\n## What you give up\n\n- **Free printing.** SVAR's print API is in the MIT grid; SvGrid's print\n view is in `@svgrid/enterprise`.\n- **The React and Vue versions** of the same grid. SvGrid is Svelte-only.\n- **A smaller bundle.** The facts box at the top of the page has both\n packages measured the same way; the difference is the grouping,\n master/detail, range editing, charts and server-side data (flat paging and infinite scroll free; grouping, tree, pivot and transactions on the server are Enterprise) SvGrid\n carries, and features you never import load as separate chunks.\n- **The SVAR suite around the grid.** Gantt, Calendar, Kanban and File\n Manager share SVAR's core; SvGrid's Kanban and scheduler are views of the\n grid in `@svgrid/enterprise`.\n\n## What to check on the SVAR side\n\n- The **wider SVAR suite** (Gantt, Calendar, Kanban) - if you use several\n SVAR components together, staying on SVAR may be simpler.\n- Any **SVAR-specific column features** you rely on; map each to a SvGrid\n `cell` snippet, `editorType`, or feature before porting.\n- **Filter functions.** SVAR filters with a predicate you write; SvGrid's\n filter takes an operator and a value per column, and `externalFilter`\n hands you the rows when you want to keep a custom predicate.\n\n## Frequently asked questions\n\n### Why move from SVAR Svelte DataGrid to SvGrid?\n\nCapability and architecture, not licensing (both are MIT). SvGrid adds row\ngrouping with aggregation, master-detail, Excel-style cell-range selection,\nintegrated charts, and pivot, and it ships a headless engine plus an MCP server\nalongside the component. Both are Svelte-native, so the core grid\nbehaviour is comparable; SvGrid covers more ground.\n\n### Is the migration a rewrite?\n\nNo. Both are component-first with array-of-object columns, so it is mostly a\nprop / event rename pass (`id` → `field`, edit events → `onCellValueChange`)\nplus re-theming through `--sg-*` tokens.\n\n### Are SvGrid and SVAR both free and MIT?\n\nYes. `@svgrid/grid` and the SVAR DataGrid are both MIT and free for\ncommercial, closed-source use. SVAR keeps the whole grid free and sells PRO\neditions of its Gantt, Calendar and Kanban; on SvGrid, only the optional\n`@svgrid/enterprise` add-on (Excel and PDF export, print, pivot, import,\nsupport) is paid. The dated statement from svar.dev is in the facts box at\nthe top of this page.\n\n### How does SVAR's tree data map to SvGrid?\n\nSVAR takes hierarchical data with the `tree` prop. SvGrid takes either a\nflat array with a parent field (`treeData={{ parentField: 'parentId' }}`)\nor nested rows through `rowExpandingFeature`, and the same grid also does\nmaster/detail, which SVAR's docs do not list. The example below runs the\nflat shape:\n\n## What you end up with\n\nGrouping with aggregation and a totals row, the main capability step up.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} summary groupable sortable filterable />\n```\n\nAnd the tree shape, from the same rows with a parent link, which is what SVAR's `tree` prop becomes:\n\n```svelte {runnable}\n<SvGrid data={rows.map((r, i) => ({ ...r, parentId: i === 0 ? null : rows[0].id }))} {columns} treeData={{ parentField: 'parentId' }} sortable />\n```\n\n## See also\n\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/) - the side-by-side comparison, with a source and date for every claim and the measured benchmark\n- [Grouping and aggregation](./grouping-aggregation.md) - the first demo above\n- [Master/detail](./rows/master-detail.md) - the second demo above\n- [Architecture](./architecture.md) - the engine + render-component split\n- [Cell components](./cells/cell-components.md) - custom cells and editors\n"
5989
6132
  },
5990
6133
  {
5991
6134
  "slug": "help/migrating-from-svelte-headless-table",
5992
6135
  "path": "docs/help/migrating-from-svelte-headless-table.md",
5993
6136
  "title": "Migrating from svelte-headless-table",
5994
6137
  "section": "Help",
5995
- "markdown": "\n# Migrating from svelte-headless-table\n\nsvelte-headless-table popularised the headless-table pattern in the\nSvelte ecosystem. It is built on Svelte 4 stores and plugins\n(`addSortBy`, `addColumnFilters`, `addPagination`, ...), and it leaves\nthe markup to you. SvGrid keeps the same headless idea but runs on\nSvelte 5 runes and ships a render component, so the port mostly\n*removes* the table you used to hand-author.\n\n> Estimated effort: **1-3 hours** per grid. Most of the time is deleting\n> the `<table>` markup and `Subscribe` blocks you no longer need.\n\n<!-- facts:start svelte-headless-table pkg:@humanspeak/svelte-headless-table -->\n> **Facts, checked 12 Sep 2026.** `svelte-headless-table` 0.18.3, MIT, last published 28 Oct 2024, 90,100 npm downloads in the 30 days to 10 Sep 2026. `@humanspeak/svelte-headless-table` 6.2.0, MIT, last published 27 Aug 2026, 8,640 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `svelte-headless-table` 0.18.3 5.7 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). svelte-headless-table pricing, as its site states it: svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port (https://github.com/bryanmylee/svelte-headless-table, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/).\n<!-- facts:end -->\n\n## Know your options first\n\nThe original package's last release and its Svelte 4 peer range are in the\nfacts box above, and its README states there are no current plans for a\nSvelte 5 port, so a Svelte 5 upgrade forces a decision. There are three\nhonest answers and you should know all of them:\n\n1. **`@humanspeak/svelte-headless-table`** - a maintained fork on Svelte 5 with\n the same API; its version, publish date and downloads are in the facts box\n too. Changing one package name is the cheapest path by a wide margin. If\n your table works and you only need Svelte 5, do that.\n2. **TanStack Table v9** - its Svelte adapter declares a Svelte 5 peer range.\n Still headless-only, so you keep writing and maintaining the markup.\n3. **SvGrid** - this page. A different trade: you delete the markup and take a\n renderer instead.\n\nPick SvGrid when the markup is the part you are tired of. Note that the blocker\nis not the syntax and not really the install either: `svelte-headless-table@0.18.3`\ndeclares `svelte@^4`, which npm 11 overrides with a warning (older npm needed\n`--legacy-peer-deps`), and the untouched component then type-checks clean in\nlegacy mode. Slots and `let:` still work in Svelte 5 - they are deprecated in\nfavour of snippets, not removed - so the `Subscribe` blocks below keep\nrendering. The trouble starts when that component moves to runes: the library\ntakes a store, your data is a rune, and the bridge between them is yours to\nwrite and maintain. We ran the whole upgrade and captured every line of it in\n[Upgrading a Svelte 4 table to Svelte 5](./svelte-5-upgrade-data-tables.md).\n\n## Run the codemod\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```bash\nnpx @svgrid/migrate # preview the result\nnpx @svgrid/migrate src --write # apply it\n```\n\nIt translates column definitions and plugin config, deletes the\n`Subscribe`/`Render` scaffolding, and reports anything it cannot map rather than\ndropping it silently. It previews by default. See\n[`@svgrid/migrate`](https://www.npmjs.com/package/@svgrid/migrate) for the full\nmapping and its limits.\n\n## Vocabulary cheat sheet\n\n| svelte-headless-table | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `createTable(data, plugins)` | `createSvGrid({...})` or `<SvGrid>` |\n| `table.createColumns((t) => [...])` | `columns: ColumnDef[]` |\n| `t.column({ accessor: 'x', header })` | `{ field: 'x', header }` |\n| `t.column({ accessor: (r) => ... })` | `{ id, fieldFn: (r) => ... }` |\n| `t.group({ header, columns })` | `{ header, columns: [...] }` (column group) |\n| `addSortBy()` | `rowSortingFeature` |\n| `addColumnFilters()` / `addTableFilter()` | `columnFilteringFeature` |\n| `addPagination()` | Built in; toggle `showPagination` |\n| `addExpandedRows()` / `addSubRows()` | `rowExpandingFeature` |\n| `addGroupBy()` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `addSelectedRows()` | `rowSelectionFeature` |\n| `addDataExport()` | `@svgrid/enterprise` export pack |\n| `createViewModel(columns)` + `Subscribe` | `<SvGrid>` (no view model to wire) |\n| `pluginStates.sort.sortKeys` | `api.setSort(id, dir)` / `onSortingChange` |\n\n### The shortcut form\n\nThat table maps plugins onto the headless *features*, which is what you want if\nyou keep driving the engine yourself. If you are moving to the `<SvGrid>`\ncomponent, every capability also has a boolean prop, and that is what the\ncodemod emits:\n\n| Plugin | `<SvGrid>` prop |\n| --- | --- |\n| `addSortBy()` | `sortable` |\n| `addTableFilter()` | `filterable showGlobalFilter` |\n| `addColumnFilters()` | `filterable showColumnFilters` |\n| `addPagination({ initialPageSize: 25 })` | `pageable pageSize={25}` |\n| `addSelectedRows()` | `showRowSelection` |\n| `addGroupBy()` | `groupable` |\n| `addSubRows()` | `treeData` |\n| `addColumnOrder()` | `enableColumnReorder` |\n| `addResizedColumns()` | nothing - resizing is built in |\n| `addHiddenColumns()` | `visible: false` on the column |\n| `addExpandedRows()` | `treeData`, or `isDetailRow` + `renderDetailRow` |\n| `addGridLayout()` | nothing - SvGrid owns its layout |\n\nEvery capability is off by default and turned on by its prop; there is no\nplugin registration step.\n\n## Before / after\n\n```diff\n- <script>\n- import { createTable } from 'svelte-headless-table'\n- import { addSortBy, addColumnFilters, addPagination } from 'svelte-headless-table/plugins'\n- import { readable } from 'svelte/store'\n-\n- const table = createTable(readable(data), {\n- sort: addSortBy(), filter: addColumnFilters(), page: addPagination(),\n- })\n- const columns = table.createColumns((t) => [\n- t.column({ accessor: 'name', header: 'Name' }),\n- t.column({ accessor: 'amount', header: 'Amount' }),\n- ])\n- const { headerRows, rows, tableAttrs, tableBodyAttrs } = table.createViewModel(columns)\n- </script>\n-\n- <table {...$tableAttrs}>\n- <thead> ...Subscribe over headerRows... </thead>\n- <tbody {...$tableBodyAttrs}> ...Subscribe over rows... </tbody>\n- </table>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\nType the column array against your row type. `GridColumns<(typeof data)[number]>`\nis the shortest form; a bare `GridColumns` widens the row to\n`Record<string, unknown>` and stops checking `field` against your real keys.\n\n## What you get for free\n\n- **The renderer.** No `createViewModel`, no `Subscribe`, no hand-built\n `<table>`. SvGrid ships virtualization, sticky headers, column\n resize, keyboard nav, and ARIA.\n- **Excel-style filter menu** and **cell-range selection + TSV copy**,\n which are BYO in svelte-headless-table.\n- **Inline editing** with typed editors and validation hooks.\n- **In-grid AI helpers** - natural-language filter, smart fill, summarise -\n free in `@svgrid/grid` against a model you register.\n- **Enterprise features** - Excel and PDF export, print, import and pivot -\n in one paid add-on; CSV, TSV and JSON export are free.\n\nIf you would rather keep driving your own `<table>`, the headless demo\nbelow does exactly that on `createSvGrid`, plugins replaced by features:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\n## What changes\n\n- **Stores → runes.** Reactive data is `$state` / a plain array, not a\n Svelte store you pass to `createTable`. If your rows came from a `derived`\n store, read it with `$` at the call site or move it to `$derived`.\n- **Plugins → features.** Register `rowSortingFeature` etc. in\n `tableFeatures({...})` instead of `addSortBy()` in the plugin bag.\n- **View model → component.** You stop owning the markup; style through\n `--sg-*` tokens (and Tailwind) instead of `tableAttrs`.\n\n## What does not come across\n\n- **Custom `cell` renderers.** `createRender(MyComponent, props)` has no direct\n equivalent; SvGrid uses a `cell` snippet. The codemod preserves yours as a\n `// TODO port:` comment.\n- **Your own plugins.** There is no plugin system to port them into.\n- **`tableAttrs` / `attrs()` spreading.** The component owns its attributes.\n\n## When not to migrate\n\n- You need control of the exact DOM. Use the fork, or SvGrid's\n [headless core](../why-headless.md) at `@svgrid/grid/core`.\n- Your table is a handful of rows with no interaction. A plain `{#each}` is\n less code than either library.\n- You depend on custom plugins. That is a rewrite, not a migration.\n- You only need Svelte 5 support. Use the fork.\n\n## Frequently asked questions\n\n### How hard is it to move from svelte-headless-table to SvGrid?\n\nUsually 1-3 hours per grid, and `npx @svgrid/migrate` does the mechanical part.\nThe plugin-to-feature mapping is almost one-to-one; most of the work is deleting\nthe `createViewModel` + `Subscribe` + `<table>` markup, because SvGrid renders\nthat for you.\n\n### Does SvGrid use Svelte 5 runes instead of stores?\n\nYes. svelte-headless-table is built on Svelte 4 stores; SvGrid is Svelte-5\nnative (`$state` / `$derived` / `$effect`) with snippets for custom cells.\n\n### Is SvGrid still headless like svelte-headless-table?\n\nYes - `createSvGrid` plus the row-model factories is a headless engine you can\ndrive with your own markup, importable on its own from `@svgrid/grid/core`. The\ndifference is that SvGrid *also* ships a batteries-included `<SvGrid>` component\nso you usually do not have to.\n\n### Is svelte-headless-table still maintained?\n\nThe original's last publish date and Svelte 4 peer range are in the facts box\nat the top of the page, read from npm on the date shown, and its README says\nthere are no current plans for a Svelte 5 port. A community fork,\n`@humanspeak/svelte-headless-table`, is maintained and runs on Svelte 5 with\nthe same API; the facts box has its release line too. The fork is the\nlowest-effort option if you are happy with the library and only need Svelte 5.\n\n## What you end up with\n\nSorting, filtering and selection, on a library that still ships for Svelte 5.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable selectable />\n```\n\n## See also\n\n- [Upgrading a Svelte 4 table to Svelte 5](./svelte-5-upgrade-data-tables.md) - the whole upgrade run and captured, step by step\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/) - the side-by-side comparison, with a source and date for every claim\n- [Headless: build a table](./headless/build-a-table.md) - the demo above, step by step\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - sibling headless guide\n- [Why headless?](../why-headless.md) - the design rationale\n- [Architecture](./architecture.md) - the engine + render-component split\n"
6138
+ "markdown": "\n# Migrating from svelte-headless-table\n\nsvelte-headless-table popularised the headless-table pattern in the\nSvelte ecosystem. It is built on Svelte 4 stores and plugins\n(`addSortBy`, `addColumnFilters`, `addPagination`, ...), and it leaves\nthe markup to you. SvGrid keeps the same headless idea but runs on\nSvelte 5 runes and ships a render component, so the port mostly\n*removes* the table you used to hand-author.\n\n> Estimated effort: **1-3 hours** per grid. Most of the time is deleting\n> the `<table>` markup and `Subscribe` blocks you no longer need.\n\n<!-- facts:start svelte-headless-table pkg:@humanspeak/svelte-headless-table -->\n> **Facts, checked 12 Sep 2026.** `svelte-headless-table` 0.18.3, MIT, last published 28 Oct 2024, 90,100 npm downloads in the 30 days to 10 Sep 2026. `@humanspeak/svelte-headless-table` 6.2.0, MIT, last published 27 Aug 2026, 8,640 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `svelte-headless-table` 0.18.3 5.7 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). svelte-headless-table pricing, as its site states it: svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port (https://github.com/bryanmylee/svelte-headless-table, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/).\n<!-- facts:end -->\n\n## Know your options first\n\nThe original package's last release and its Svelte 4 peer range are in the\nfacts box above, and its README states there are no current plans for a\nSvelte 5 port, so a Svelte 5 upgrade forces a decision. There are three\nhonest answers and you should know all of them:\n\n1. **`@humanspeak/svelte-headless-table`** - a maintained fork on Svelte 5 with\n the same API; its version, publish date and downloads are in the facts box\n too. Changing one package name is the cheapest path by a wide margin. If\n your table works and you only need Svelte 5, do that.\n2. **TanStack Table v9** - its Svelte adapter declares a Svelte 5 peer range.\n Still headless-only, so you keep writing and maintaining the markup.\n3. **SvGrid** - this page. A different trade: you delete the markup and take a\n renderer instead.\n\nPick SvGrid when the markup is the part you are tired of. Note that the blocker\nis not the syntax and not really the install either: `svelte-headless-table@0.18.3`\ndeclares `svelte@^4`, which npm 11 overrides with a warning (older npm needed\n`--legacy-peer-deps`), and the untouched component then type-checks clean in\nlegacy mode. Slots and `let:` still work in Svelte 5 - they are deprecated in\nfavour of snippets, not removed - so the `Subscribe` blocks below keep\nrendering. The trouble starts when that component moves to runes: the library\ntakes a store, your data is a rune, and the bridge between them is yours to\nwrite and maintain. We ran the whole upgrade and captured every line of it in\n[Upgrading a Svelte 4 table to Svelte 5](./svelte-5-upgrade-data-tables.md).\n\n## Run the codemod\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```bash\nnpx @svgrid/migrate # preview the result\nnpx @svgrid/migrate src --write # apply it\n```\n\nIt translates column definitions and plugin config, deletes the\n`Subscribe`/`Render` scaffolding, and reports anything it cannot map rather than\ndropping it silently. It previews by default. See\n[`@svgrid/migrate`](https://www.npmjs.com/package/@svgrid/migrate) for the full\nmapping and its limits.\n\n## Vocabulary cheat sheet\n\n| svelte-headless-table | sv-grid |\n| ----------------------------------------- | ----------------------------------------- |\n| `createTable(data, plugins)` | `createSvGrid({...})` or `<SvGrid>` |\n| `table.createColumns((t) => [...])` | `columns: ColumnDef[]` |\n| `t.column({ accessor: 'x', header })` | `{ field: 'x', header }` |\n| `t.column({ accessor: (r) => ... })` | `{ id, fieldFn: (r) => ... }` |\n| `t.group({ header, columns })` | `{ header, columns: [...] }` (column group) |\n| `addSortBy()` | `rowSortingFeature` |\n| `addColumnFilters()` / `addTableFilter()` | `columnFilteringFeature` |\n| `addPagination()` | Built in; toggle `showPagination` |\n| `addExpandedRows()` / `addSubRows()` | `rowExpandingFeature` |\n| `addGroupBy()` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `addSelectedRows()` | `rowSelectionFeature` |\n| `addDataExport()` | `@svgrid/enterprise` export pack |\n| `createViewModel(columns)` + `Subscribe` | `<SvGrid>` (no view model to wire) |\n| `pluginStates.sort.sortKeys` | `api.setSort(id, dir)` / `onSortingChange` |\n\n### The shortcut form\n\nThat table maps plugins onto the headless *features*, which is what you want if\nyou keep driving the engine yourself. If you are moving to the `<SvGrid>`\ncomponent, every capability also has a boolean prop, and that is what the\ncodemod emits:\n\n| Plugin | `<SvGrid>` prop |\n| --- | --- |\n| `addSortBy()` | `sortable` |\n| `addTableFilter()` | `filterable showGlobalFilter` |\n| `addColumnFilters()` | `filterable showColumnFilters` |\n| `addPagination({ initialPageSize: 25 })` | `pageable pageSize={25}` |\n| `addSelectedRows()` | `showRowSelection` |\n| `addGroupBy()` | `groupable` |\n| `addSubRows()` | `treeData` |\n| `addColumnOrder()` | `enableColumnReorder` |\n| `addResizedColumns()` | nothing - resizing is built in |\n| `addHiddenColumns()` | `visible: false` on the column |\n| `addExpandedRows()` | `treeData`, or `isDetailRow` + `renderDetailRow` |\n| `addGridLayout()` | nothing - SvGrid owns its layout |\n\nEvery capability is off by default and turned on by its prop; there is no\nplugin registration step.\n\n## Before / after\n\n```diff\n- <script>\n- import { createTable } from 'svelte-headless-table'\n- import { addSortBy, addColumnFilters, addPagination } from 'svelte-headless-table/plugins'\n- import { readable } from 'svelte/store'\n-\n- const table = createTable(readable(data), {\n- sort: addSortBy(), filter: addColumnFilters(), page: addPagination(),\n- })\n- const columns = table.createColumns((t) => [\n- t.column({ accessor: 'name', header: 'Name' }),\n- t.column({ accessor: 'amount', header: 'Amount' }),\n- ])\n- const { headerRows, rows, tableAttrs, tableBodyAttrs } = table.createViewModel(columns)\n- </script>\n-\n- <table {...$tableAttrs}>\n- <thead> ...Subscribe over headerRows... </thead>\n- <tbody {...$tableBodyAttrs}> ...Subscribe over rows... </tbody>\n- </table>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\nType the column array against your row type. `GridColumns<(typeof data)[number]>`\nis the shortest form; a bare `GridColumns` widens the row to\n`Record<string, unknown>` and stops checking `field` against your real keys.\n\n## What you get for free\n\n- **The renderer.** No `createViewModel`, no `Subscribe`, no hand-built\n `<table>`. SvGrid ships virtualization, sticky headers, column\n resize, keyboard nav, and ARIA.\n- **Excel-style filter menu** and **cell-range selection + TSV copy**,\n which are BYO in svelte-headless-table.\n- **Inline editing** with typed editors and validation hooks.\n- **In-grid AI helpers** - natural-language filter, smart fill, summarise -\n free in `@svgrid/grid` against a model you register.\n- **Enterprise features** - Excel and PDF export, print, import and pivot -\n in one paid add-on; CSV, TSV and JSON export are free.\n\nIf you would rather keep driving your own `<table>`, the headless demo\nbelow does exactly that on `createSvGrid`, plugins replaced by features:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\n## What changes\n\n- **Stores → runes.** Reactive data is `$state` / a plain array, not a\n Svelte store you pass to `createTable`. If your rows came from a `derived`\n store, read it with `$` at the call site or move it to `$derived`.\n- **Plugins → features.** Register `rowSortingFeature` etc. in\n `tableFeatures({...})` instead of `addSortBy()` in the plugin bag.\n- **View model → component.** You stop owning the markup; style through\n `--sg-*` tokens (and Tailwind) instead of `tableAttrs`.\n\n## What does not come across\n\n- **Custom `cell` renderers.** `createRender(MyComponent, props)` has no direct\n equivalent; SvGrid uses a `cell` snippet. The codemod preserves yours as a\n `// TODO port:` comment.\n- **Your own plugins.** There is no plugin system to port them into.\n- **`tableAttrs` / `attrs()` spreading.** The component owns its attributes.\n\n## When not to migrate\n\n- You need control of the exact DOM. Use the fork, or SvGrid's\n [headless core](../why-headless.md) at `@svgrid/grid/core`.\n- Your table is a handful of rows with no interaction. A plain `{#each}` is\n less code than either library.\n- You depend on custom plugins. That is a rewrite, not a migration.\n- You only need Svelte 5 support. Use the fork.\n\n## Frequently asked questions\n\n### How hard is it to move from svelte-headless-table to SvGrid?\n\nUsually 1-3 hours per grid, and `npx @svgrid/migrate` does the mechanical part.\nThe plugin-to-feature mapping is almost one-to-one; most of the work is deleting\nthe `createViewModel` + `Subscribe` + `<table>` markup, because SvGrid renders\nthat for you.\n\n### Does SvGrid use Svelte 5 runes instead of stores?\n\nYes. svelte-headless-table is built on Svelte 4 stores; SvGrid is Svelte-5\nnative (`$state` / `$derived` / `$effect`) with snippets for custom cells.\n\n### Is SvGrid still headless like svelte-headless-table?\n\nYes - `createSvGrid` plus the row-model factories is a headless engine you can\ndrive with your own markup, importable on its own from `@svgrid/grid/core`. The\ndifference is that SvGrid *also* ships a batteries-included `<SvGrid>` component\nso you usually do not have to.\n\n### Is svelte-headless-table still maintained?\n\nThe original's last publish date and Svelte 4 peer range are in the facts box\nat the top of the page, read from npm on the date shown, and its README says\nthere are no current plans for a Svelte 5 port. A community fork,\n`@humanspeak/svelte-headless-table`, is maintained and runs on Svelte 5 with\nthe same API; the facts box has its release line too. The fork is the\nlowest-effort option if you are happy with the library and only need Svelte 5.\n\n## What you end up with\n\nSorting, filtering and selection, on a library that still ships for Svelte 5.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable selectable />\n```\n\n## See also\n\n- [Upgrading a Svelte 4 table to Svelte 5](./svelte-5-upgrade-data-tables.md) - the whole upgrade run and captured, step by step\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/) - the side-by-side comparison, with a source and date for every claim\n- [Headless: build a table](./headless/build-a-table.md) - the demo above, step by step\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - sibling headless guide\n- [Why headless?](../why-headless.md) - the design rationale\n- [Architecture](./architecture.md) - the engine + render-component split\n"
5996
6139
  },
5997
6140
  {
5998
6141
  "slug": "help/migrating-from-syncfusion",
5999
6142
  "path": "docs/help/migrating-from-syncfusion.md",
6000
6143
  "title": "Migrating from Syncfusion Grid",
6001
6144
  "section": "Help",
6002
- "markdown": "# Migrating from Syncfusion Grid\n\nSyncfusion Grid is a comprehensive commercial grid across JavaScript,\nReact, Vue, Angular, and Blazor, with a free community license for\nqualifying small teams. Moving to SvGrid trades the multi-framework suite\nfor a Svelte-5-native grid with an unconditional MIT core.\n\n> Estimated effort: **3-6 hours** per grid.\n>\n> Syncfusion's option names vary across its framework flavours; map your\n> version's columns and events onto the SvGrid equivalents below.\n\n<!-- facts:start syncfusion-grid -->\n> **Facts, checked 12 Sep 2026.** `@syncfusion/ej2-grids` 34.2.7, Commercial (see licence file), last published 8 Sep 2026, 711,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). Syncfusion Grid pricing, as its site states it: syncfusion.com lists the Grid SDK at $959 per developer per year and the UI Component Suite at $1,199 per developer per year, minimum five developers; a free Community License applies to companies and individuals with under $1M annual revenue, up to five developers and no more than ten employees (https://www.syncfusion.com/sales/products, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Syncfusion Grid](https://svgrid.com/compare/syncfusion-grid/).\n<!-- facts:end -->\n\n## Concept map\n\n| Syncfusion Grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ field, headerText }]` | `columns: [{ field, header }]` |\n| `template` / cell template | `cell: (c) => renderSnippet(...)` |\n| `editSettings` + `editType` | `enableInlineEditing` + `editorType` |\n| `allowSorting` / `allowFiltering` | `rowSortingFeature` / `columnFilteringFeature` |\n| `allowGrouping` + `aggregates` | `columnGroupingFeature` + aggregates |\n| `detailTemplate` | `rowExpandingFeature` / master-detail rows |\n| `dataSource` (local / `DataManager`) | `data` array or `externalSort/Filter` |\n| `allowPaging` + `pageSettings` | `showPagination` |\n| `toolbar` export | `@svgrid/enterprise` export pack |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <ejs-grid [dataSource]=\"rows\" [allowSorting]=\"true\" [allowFiltering]=\"true\"\n- [allowPaging]=\"true\" [editSettings]=\"{ allowEditing: true }\">\n- <e-columns>\n- <e-column field=\"name\" headerText=\"Name\"></e-column>\n- <e-column field=\"amount\" headerText=\"Amount\" format=\"C2\"></e-column>\n- </e-columns>\n- </ejs-grid>\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a multi-framework commercial suite.\n- **Unconditional MIT core** - no revenue / headcount threshold like the\n Syncfusion community license.\n- **Optional Enterprise pack** for export / import / pivot / AI.\n\n## What to weigh\n\n- Syncfusion ships **one of the largest feature sets and suites**\n available, plus Blazor support. If you need that breadth or Blazor,\n weigh it against the Svelte-native fit.\n\n## Frequently asked questions\n\n### Is SvGrid free, unlike the Syncfusion commercial license?\n\n`@svgrid/grid` is MIT - free for everyone, with no revenue or team-size\nconditions. Syncfusion's community license is free only for qualifying small\nteams; otherwise it is commercial.\n\n### How do Syncfusion columns map to SvGrid?\n\n`field` stays `field`, `headerText` becomes `header`, and `template` becomes a\n`renderSnippet` cell. Sorting / filtering / grouping move to registered\nfeatures.\n\n### Does SvGrid support Blazor?\n\nNo - SvGrid is Svelte 5 only. If you need Blazor, that is a genuine reason to\nstay on Syncfusion. For a Svelte stack, SvGrid is the native fit.\n\n## What you end up with\n\nSort, filter, group and inline edit - the four things a Syncfusion grid is usually doing.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} groupable sortable filterable editable />\n```\n\n## See also\n\n- [SvGrid vs Syncfusion Grid](https://svgrid.com/compare/syncfusion-grid/) - the side-by-side comparison\n- [Data export and printing - Enterprise](./export.md) - the Enterprise export pack\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
6145
+ "markdown": "# Migrating from Syncfusion Grid\n\nSyncfusion Grid is a comprehensive commercial grid across JavaScript,\nReact, Vue, Angular, and Blazor, with a free community license for\nqualifying small teams. Moving to SvGrid trades the multi-framework suite\nfor a Svelte-5-native grid with an unconditional MIT core.\n\n> Estimated effort: **3-6 hours** per grid.\n>\n> Syncfusion's option names vary across its framework flavours; map your\n> version's columns and events onto the SvGrid equivalents below.\n\n<!-- facts:start syncfusion-grid -->\n> **Facts, checked 12 Sep 2026.** `@syncfusion/ej2-grids` 34.2.7, Commercial (see licence file), last published 8 Sep 2026, 711,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). Syncfusion Grid pricing, as its site states it: syncfusion.com lists the Grid SDK at $959 per developer per year and the UI Component Suite at $1,199 per developer per year, minimum five developers; a free Community License applies to companies and individuals with under $1M annual revenue, up to five developers and no more than ten employees (https://www.syncfusion.com/sales/products, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Syncfusion Grid](https://svgrid.com/compare/syncfusion-grid/).\n<!-- facts:end -->\n\n## Concept map\n\n| Syncfusion Grid | sv-grid |\n| ---------------------------------------- | ----------------------------------------- |\n| `columns: [{ field, headerText }]` | `columns: [{ field, header }]` |\n| `template` / cell template | `cell: (c) => renderSnippet(...)` |\n| `editSettings` + `editType` | `enableInlineEditing` + `editorType` |\n| `allowSorting` / `allowFiltering` | `rowSortingFeature` / `columnFilteringFeature` |\n| `allowGrouping` + `aggregates` | `columnGroupingFeature` + aggregates |\n| `detailTemplate` | `rowExpandingFeature` / master-detail rows |\n| `dataSource` (local / `DataManager`) | `data` array or `externalSort/Filter` |\n| `allowPaging` + `pageSettings` | `showPagination` |\n| `toolbar` export | `@svgrid/enterprise` export pack |\n\n## Shape of the change\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <ejs-grid [dataSource]=\"rows\" [allowSorting]=\"true\" [allowFiltering]=\"true\"\n- [allowPaging]=\"true\" [editSettings]=\"{ allowEditing: true }\">\n- <e-columns>\n- <e-column field=\"name\" headerText=\"Name\"></e-column>\n- <e-column field=\"amount\" headerText=\"Amount\" format=\"C2\"></e-column>\n- </e-columns>\n- </ejs-grid>\n\n+ <SvGrid\n+ data={rows}\n+ columns={[\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]}\n+ features={tableFeatures({ rowSortingFeature, columnFilteringFeature })}\n+ showPagination enableInlineEditing />\n```\n\n## Why teams switch\n\n- **Svelte 5 native** instead of a multi-framework commercial suite.\n- **Unconditional MIT core** - no revenue / headcount threshold like the\n Syncfusion community license.\n- **Optional Enterprise pack** for export / import / pivot / AI.\n\n## What to weigh\n\n- Syncfusion ships **one of the largest feature sets and suites**\n available, plus Blazor support. If you need that breadth or Blazor,\n weigh it against the Svelte-native fit.\n\n## Frequently asked questions\n\n### Is SvGrid free, unlike the Syncfusion commercial license?\n\n`@svgrid/grid` is MIT - free for everyone, with no revenue or team-size\nconditions. Syncfusion's community license is free only for qualifying small\nteams; otherwise it is commercial.\n\n### How do Syncfusion columns map to SvGrid?\n\n`field` stays `field`, `headerText` becomes `header`, and `template` becomes a\n`renderSnippet` cell. Sorting / filtering / grouping move to registered\nfeatures.\n\n### Does SvGrid support Blazor?\n\nNo - SvGrid is Svelte 5 only. If you need Blazor, that is a genuine reason to\nstay on Syncfusion. For a Svelte stack, SvGrid is the native fit.\n\n## What you end up with\n\nSort, filter, group and inline edit - the four things a Syncfusion grid is usually doing.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} groupBy={['department']} groupable sortable filterable editable />\n```\n\n## See also\n\n- [SvGrid vs Syncfusion Grid](https://svgrid.com/compare/syncfusion-grid/) - the side-by-side comparison\n- [Data export and printing - Enterprise](./export.md) - the Enterprise export pack\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
6003
6146
  },
6004
6147
  {
6005
6148
  "slug": "help/migrating-from-tabulator",
6006
6149
  "path": "docs/help/migrating-from-tabulator.md",
6007
6150
  "title": "Migrating from Tabulator",
6008
6151
  "section": "Help",
6009
- "markdown": "# Migrating from Tabulator\n\nTabulator is a feature-rich vanilla-JS table you instantiate against a\nDOM element and drive imperatively (`table.setData(...)`,\n`table.on('cellEdited', ...)`). SvGrid covers a similar feature surface\nbut as a Svelte 5 component: data is a reactive `$state` array, custom\ncells are snippets, and there is no manual mount / teardown.\n\n> Estimated effort: **2-4 hours** per grid - column translation plus\n> swapping imperative `setData` for reactive state.\n\n<!-- facts:start tabulator -->\n> **Facts, checked 12 Sep 2026.** `tabulator-tables` 6.5.2, MIT, last published 23 Jun 2026, 672,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `tabulator-tables` 6.5.2 106.9 KB JS + 3.8 KB CSS (measured 12 Sep 2026). Tabulator pricing, as its site states it: Tabulator is MIT and free; no licence or support plan is sold (https://github.com/olifolkerd/tabulator, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Tabulator | sv-grid |\n| -------------------------------------- | ----------------------------------------- |\n| `new Tabulator(el, { data, columns })` | `<SvGrid data={...} columns={...} />` |\n| `{ title: 'Name', field: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `formatter: fn` / `formatter: 'money'` | `cell: (c) => renderSnippet(...)` or `format` |\n| `editor: 'input' / 'number' / ...` | `editorType: 'text' / 'number' / ...` |\n| `headerFilter: true` | `columnFilteringFeature` |\n| `dataTree: true` | `rowExpandingFeature` + tree row shape |\n| `table.setData(rows)` | reassign the `$state` data array |\n| `table.on('cellEdited', ...)` | `onCellValueChange` |\n| `table.setSort(field, dir)` | `api.setSort(field, dir)` |\n| `layout: 'fitColumns'` | `fitColumns` prop |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { TabulatorFull as Tabulator } from 'tabulator-tables'\n-\n- const table = new Tabulator('#grid', {\n- data: rows,\n- layout: 'fitColumns',\n- columns: [\n- { title: 'Name', field: 'name' },\n- { title: 'Amount', field: 'amount', formatter: 'money', editor: 'number' },\n- ],\n- })\n- table.on('cellEdited', (cell) => save(cell.getData()))\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' }, editorType: 'number' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} fitColumns enableInlineEditing\n+ onCellValueChange={(e) => save(e)} />\n```\n\n## What changes\n\n- **Imperative → reactive.** No `setData()` - reassign the `$state`\n array and the grid updates.\n- **String formatters → snippets.** Custom cells are Svelte snippets /\n components, not HTML-string formatters.\n- **Mount / teardown disappears.** No `new Tabulator(el)` and no manual\n destroy on unmount.\n\n## Frequently asked questions\n\n### Is migrating from Tabulator to SvGrid hard?\n\nIt is a configuration translation plus one mindset shift: you stop calling\n`setData()` and instead let a reactive `$state` array drive the grid. Budget\n2-4 hours per grid.\n\n### Is SvGrid free like Tabulator?\n\nYes. `@svgrid/grid` is MIT-licensed like Tabulator. The optional\n`@svgrid/enterprise` pack (export, import, pivot, AI) is the only paid piece.\n\n### Can I keep Tabulator's custom formatters?\n\nYou re-create them as Svelte snippets via `renderSnippet`. Any Svelte\ncomponent or markup works, not just an HTML string.\n\n## What you end up with\n\nSort, filter and edit, with pagination underneath.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/) - the side-by-side comparison\n- [Cell components](./cells/cell-components.md) - snippet-based custom cells\n- [Architecture](./architecture.md) - engine + render-component split\n"
6152
+ "markdown": "# Migrating from Tabulator\n\nTabulator is a feature-rich vanilla-JS table you instantiate against a\nDOM element and drive imperatively (`table.setData(...)`,\n`table.on('cellEdited', ...)`). SvGrid covers a similar feature surface\nbut as a Svelte 5 component: data is a reactive `$state` array, custom\ncells are snippets, and there is no manual mount / teardown.\n\n> Estimated effort: **2-4 hours** per grid - column translation plus\n> swapping imperative `setData` for reactive state.\n\n<!-- facts:start tabulator -->\n> **Facts, checked 12 Sep 2026.** `tabulator-tables` 6.5.2, MIT, last published 23 Jun 2026, 672,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `tabulator-tables` 6.5.2 106.9 KB JS + 3.8 KB CSS (measured 12 Sep 2026). Tabulator pricing, as its site states it: Tabulator is MIT and free; no licence or support plan is sold (https://github.com/olifolkerd/tabulator, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| Tabulator | sv-grid |\n| -------------------------------------- | ----------------------------------------- |\n| `new Tabulator(el, { data, columns })` | `<SvGrid data={...} columns={...} />` |\n| `{ title: 'Name', field: 'name' }` | `{ header: 'Name', field: 'name' }` |\n| `formatter: fn` / `formatter: 'money'` | `cell: (c) => renderSnippet(...)` or `format` |\n| `editor: 'input' / 'number' / ...` | `editorType: 'text' / 'number' / ...` |\n| `headerFilter: true` | `columnFilteringFeature` |\n| `dataTree: true` | `rowExpandingFeature` + tree row shape |\n| `table.setData(rows)` | reassign the `$state` data array |\n| `table.on('cellEdited', ...)` | `onCellValueChange` |\n| `table.setSort(field, dir)` | `api.setSort(field, dir)` |\n| `layout: 'fitColumns'` | `fitColumns` prop |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import { TabulatorFull as Tabulator } from 'tabulator-tables'\n-\n- const table = new Tabulator('#grid', {\n- data: rows,\n- layout: 'fitColumns',\n- columns: [\n- { title: 'Name', field: 'name' },\n- { title: 'Amount', field: 'amount', formatter: 'money', editor: 'number' },\n- ],\n- })\n- table.on('cellEdited', (cell) => save(cell.getData()))\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' }, editorType: 'number' },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} fitColumns enableInlineEditing\n+ onCellValueChange={(e) => save(e)} />\n```\n\n## What changes\n\n- **Imperative → reactive.** No `setData()` - reassign the `$state`\n array and the grid updates.\n- **String formatters → snippets.** Custom cells are Svelte snippets /\n components, not HTML-string formatters.\n- **Mount / teardown disappears.** No `new Tabulator(el)` and no manual\n destroy on unmount.\n\n## Frequently asked questions\n\n### Is migrating from Tabulator to SvGrid hard?\n\nIt is a configuration translation plus one mindset shift: you stop calling\n`setData()` and instead let a reactive `$state` array drive the grid. Budget\n2-4 hours per grid.\n\n### Is SvGrid free like Tabulator?\n\nYes. `@svgrid/grid` is MIT-licensed like Tabulator. The optional\n`@svgrid/enterprise` pack (export, import, pivot, AI) is the only paid piece.\n\n### Can I keep Tabulator's custom formatters?\n\nYou re-create them as Svelte snippets via `renderSnippet`. Any Svelte\ncomponent or markup works, not just an HTML string.\n\n## What you end up with\n\nSort, filter and edit, with pagination underneath.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable editable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/) - the side-by-side comparison\n- [Cell components](./cells/cell-components.md) - snippet-based custom cells\n- [Architecture](./architecture.md) - engine + render-component split\n"
6010
6153
  },
6011
6154
  {
6012
6155
  "slug": "help/migrating-from-tanstack-table",
6013
6156
  "path": "docs/help/migrating-from-tanstack-table.md",
6014
6157
  "title": "Migrating from TanStack Table",
6015
6158
  "section": "Help",
6016
- "markdown": "# Migrating from TanStack Table\n\nTanStack Table (formerly React Table) is the closest conceptual\nsibling to sv-grid - both are \"headless data grid\" libraries with\nexplicit row-model pipelines, and the v9 Svelte adapter,\n`@tanstack/svelte-table`, targets Svelte 5 with the same runes-first\nshape. If you already think in `createTable()` + a features object,\nthis is a half-day port; the vocabulary below covers the v8 names too.\n\n> Estimated effort: **30 min** per grid for read-only views, **2-4\n> hours** for editing-heavy grids.\n\n<!-- facts:start tanstack-table -->\n> **Facts, checked 12 Sep 2026.** `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/).\n<!-- facts:end -->\n\n> **On v9?** SvGrid exports the same feature vocabulary, so most of this\n> page is automated. Run `npx @svgrid/migrate src` to preview the port, and\n> see [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md)\n> if that is where your table came from.\n\n## Vocabulary cheat sheet\n\n| TanStack Table | sv-grid |\n| ------------------------------- | ---------------------------------------- |\n| `useReactTable({...})` | `createSvGrid({...})` or `<SvGrid>` |\n| `getCoreRowModel()` | `createCoreRowModel()` |\n| `getSortedRowModel()` | Auto-registered by `rowSortingFeature` |\n| `getFilteredRowModel()` | Auto-registered by `columnFilteringFeature` |\n| `getPaginationRowModel()` | Built in; toggle with `showPagination` |\n| `getGroupedRowModel()` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `getExpandedRowModel()` | `rowExpandingFeature` |\n| `flexRender(col.cell, ctx)` | `renderSnippet(MyCell, props)` OR string field |\n| `columnHelper.accessor('field')` | `{ field: 'field' }` directly |\n| `table.getRowModel().rows` | `api.getDisplayedRows()` |\n| `table.setColumnFilters(...)` | `api.setFilter(id, {...})` per column |\n| `meta` (column / table) | n/a - use column `cellClass` / `cell` instead |\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import {\n- useReactTable, getCoreRowModel, getSortedRowModel, getFilteredRowModel,\n- flexRender, createColumnHelper,\n- } from '@tanstack/react-table'\n\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ renderSnippet,\n+ } from '@svgrid/grid'\n```\n\n## Column definitions\n\n```diff\n- const columnHelper = createColumnHelper<Order>()\n- const columns = [\n- columnHelper.accessor('orderId', { header: 'Order ID' }),\n- columnHelper.accessor('amount', { header: 'Amount', cell: ({ getValue }) => fmt(getValue<number>()) }),\n- ]\n\n+ const columns: ColumnDef<typeof features, Order>[] = [\n+ { field: 'orderId', header: 'Order ID' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n```\n\nThe `fieldFn` form is the same:\n\n```diff\n- columnHelper.accessor((row) => row.profile.name, { id: 'name', header: 'Name' })\n\n+ { id: 'name', fieldFn: (row) => row.profile.name, header: 'Name' }\n```\n\n## Mounting\n\n```diff\n- const table = useReactTable({\n- data, columns,\n- getCoreRowModel: getCoreRowModel(),\n- getSortedRowModel: getSortedRowModel(),\n- getFilteredRowModel: getFilteredRowModel(),\n- })\n- return (\n- <table>\n- <thead>{table.getHeaderGroups().map(/* ... */)}</thead>\n- <tbody>{table.getRowModel().rows.map(/* ... */)}</tbody>\n- </table>\n- )\n\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nSv-grid bundles the render + virtualization. No `<table>` you have\nto author yourself.\n\n## Imperative state\n\n| TanStack Table | sv-grid |\n| ------------------------------------------- | ---------------------------------------- |\n| `table.setColumnFilters([{id, value}])` | `api.setFilter(id, { operator: 'contains', value })` |\n| `table.getColumn('id')?.setFilterValue(v)` | `api.setFilter(id, { operator: 'contains', value: v })` |\n| `table.setSorting([{id, desc}])` | `api.setSort(id, desc ? 'desc' : 'asc')` |\n| `table.setRowSelection(state)` | n/a - use `api.clearRowSelection()` + UI events |\n| `table.toggleAllRowsExpanded()` | `api.expandAllGroups()` |\n| `table.getColumn('x').toggleVisibility()` | `api.setColumnVisible('x', false)` |\n| `table.options.meta?.foo` | Pass through component props / `$state` |\n\n## Custom cells\n\n```diff\n- {\n- header: 'Status',\n- cell: ({ row }) => <Badge tone={row.original.status} />,\n- }\n\n+ {\n+ field: 'status', header: 'Status',\n+ cell: (ctx) => renderSnippet(StatusCell, { tone: ctx.row.original.status }),\n+ }\n```\n\n`renderSnippet` accepts any Svelte 5 snippet; `renderComponent`\naccepts a regular component if you prefer SFCs.\n\n## Server-side data\n\n```diff\n- const [pagination, setPagination] = useState({pageIndex: 0, pageSize: 25})\n- const [sorting, setSorting] = useState([])\n- const table = useReactTable({\n- data, columns, manualPagination: true, manualSorting: true,\n- state: { pagination, sorting },\n- onPaginationChange: setPagination,\n- onSortingChange: setSorting,\n- })\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ externalSort={true}\n+ externalFilter={true}\n+ onSortingChange={(clauses) => refetch({ sort: clauses })}\n+ onFiltersChange={(f) => refetch({ filters: f.columns })}\n+ />\n```\n\nOr hand the fetching to a controller and pass it as one prop:\n`createServerDataSource(source, { mode: 'infinite' })` owns the blocks,\nthe sort and filter round trips and the placeholder rows, and the\nmanual-flag wiring above disappears. TanStack Table has no server row\nmodel; per-group fetching is yours to write, where the Enterprise\n`createServerRowModel` does it over the same contract.\n\n<div data-docs-demo=\"148-server-row-model\" data-height=\"480\"></div>\n\n## What you get for free vs TanStack Table\n\n- **Renderer**. TanStack is headless-only; you draw the `<table>`.\n Sv-grid ships an opinionated, fast renderer with virtualization,\n scroll, sticky headers, column resize, keyboard nav, ARIA.\n- **Inline editing**. `editorType: 'text' | 'number' | 'date' |\n 'list' | ...` - built-in editors with parsing + validation hooks.\n- **CSP-clean**. No `eval`. The shipped tests confirm.\n- **In-grid AI helpers**. Natural-language filter, smart fill, summarise\n and classify, free in `@svgrid/grid` against a model you register.\n- **Enterprise features**. Excel and PDF export, print, import and pivot\n in one paid add-on; CSV, TSV and JSON export are free.\n\nThe headless demo below is the shape a TanStack app has today - a plain\n`<table>` driven by the engine - running on `createSvGrid`:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\n## What you give up\n\n- **One engine across frameworks.** TanStack has adapters for React,\n Vue, Solid, Qwik, Lit and Svelte; sv-grid is Svelte 5-native and has\n no React wrapper.\n- **The smallest engine-only bundle.** The facts box at the top of the\n page has both packages measured the same way; the difference is the\n renderer, virtualizer, filter UI and editors you would otherwise write.\n- **TanStack Virtual and the shadcn-svelte data table recipe.** Sv-grid\n virtualizes on its own and has its own\n [shadcn-svelte guide](./migrating-from-shadcn-data-table.md).\n- **`meta` for arbitrary side-channel state.** Pass props directly.\n- **`@tanstack/match-sorter-utils` integration**. The grid's filter\n has a `contains` operator; if you need fuzzy match, plug your\n matcher in via the column's `cell` snippet or use\n `externalFilter={true}` and run the matcher yourself.\n\n## Frequently asked questions\n\n### How long does it take to migrate from TanStack Table to SvGrid?\n\nAbout 30 minutes per read-only grid and 2-4 hours for editing-heavy grids.\nBoth libraries use explicit row-model pipelines, so `createTable()` +\n`getCoreRowModel()` maps almost directly onto `createSvGrid()` +\n`createCoreRowModel()`.\n\n### Why switch from TanStack Table to SvGrid on Svelte 5?\n\nTanStack Table is headless-only and multi-framework, so you build the entire\nDOM, virtualization, filter UI, and editing layer yourself. SvGrid keeps the\nheadless core but ships a batteries-included `<SvGrid>` render component -\nvirtualization, Excel-style filters, cell selection, and inline editing work\nin one prop pass.\n\n### Is SvGrid free like TanStack Table?\n\nYes - `@svgrid/grid` is MIT-licensed, like TanStack Table. SvGrid\nadditionally offers an optional paid `@svgrid/enterprise` pack for Excel and\nPDF export, print, pivot and import, which TanStack Table does not provide at\nall; TanStack sells Enterprise Support as consulting instead, as the facts box\nabove notes.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The v9 line of `@tanstack/svelte-table` declares a Svelte 5 peer range\nand reads rune data through getters; the version in the facts box above is\nthe one read from npm. If you are on the v8 adapter with Svelte 4 stores,\nthe port to sv-grid is the same work as the port to v9, minus the markup.\n\n## What you end up with\n\nThe same model you had, with the rendering already written.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [SvGrid vs TanStack Table](https://svgrid.com/compare/tanstack-table/) -\n the side-by-side comparison, with a source and date for every claim\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](./comparison.md) -\n the measured benchmark, TanStack column included\n- [Architecture](./architecture.md) - the headless engine + render\n component split\n- [Migrating from AG Grid](./migrating-from-ag-grid.md) - sibling guide\n- [Why headless?](../why-headless.md) - the design rationale\n"
6159
+ "markdown": "# Migrating from TanStack Table\n\nTanStack Table (formerly React Table) is the closest conceptual\nsibling to sv-grid - both are \"headless data grid\" libraries with\nexplicit row-model pipelines, and the v9 Svelte adapter,\n`@tanstack/svelte-table`, targets Svelte 5 with the same runes-first\nshape. If you already think in `createTable()` + a features object,\nthis is a half-day port; the vocabulary below covers the v8 names too.\n\n> Estimated effort: **30 min** per grid for read-only views, **2-4\n> hours** for editing-heavy grids.\n\n<!-- facts:start tanstack-table -->\n> **Facts, checked 12 Sep 2026.** `@tanstack/svelte-table` 9.2.4, MIT, last published 28 Aug 2026, 231,000 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `@tanstack/svelte-table` 9.2.4 36.3 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). TanStack Table pricing, as its site states it: TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table (https://tanstack.com/table/latest, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/).\n<!-- facts:end -->\n\n> **On v9?** SvGrid exports the same feature vocabulary, so most of this\n> page is automated. Run `npx @svgrid/migrate src` to preview the port, and\n> see [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md)\n> if that is where your table came from.\n\n## Vocabulary cheat sheet\n\n| TanStack Table | sv-grid |\n| ------------------------------- | ---------------------------------------- |\n| `useReactTable({...})` | `createSvGrid({...})` or `<SvGrid>` |\n| `getCoreRowModel()` | `createCoreRowModel()` |\n| `getSortedRowModel()` | Auto-registered by `rowSortingFeature` |\n| `getFilteredRowModel()` | Auto-registered by `columnFilteringFeature` |\n| `getPaginationRowModel()` | Built in; toggle with `showPagination` |\n| `getGroupedRowModel()` | `columnGroupingFeature` + `api.setGroupBy()` |\n| `getExpandedRowModel()` | `rowExpandingFeature` |\n| `flexRender(col.cell, ctx)` | `renderSnippet(MyCell, props)` OR string field |\n| `columnHelper.accessor('field')` | `{ field: 'field' }` directly |\n| `table.getRowModel().rows` | `api.getDisplayedRows()` |\n| `table.setColumnFilters(...)` | `api.setFilter(id, {...})` per column |\n| `meta` (column / table) | n/a - use column `cellClass` / `cell` instead |\n\n## Imports\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- import {\n- useReactTable, getCoreRowModel, getSortedRowModel, getFilteredRowModel,\n- flexRender, createColumnHelper,\n- } from '@tanstack/react-table'\n\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ renderSnippet,\n+ } from '@svgrid/grid'\n```\n\n## Column definitions\n\n```diff\n- const columnHelper = createColumnHelper<Order>()\n- const columns = [\n- columnHelper.accessor('orderId', { header: 'Order ID' }),\n- columnHelper.accessor('amount', { header: 'Amount', cell: ({ getValue }) => fmt(getValue<number>()) }),\n- ]\n\n+ const columns: ColumnDef<typeof features, Order>[] = [\n+ { field: 'orderId', header: 'Order ID' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n```\n\nThe `fieldFn` form is the same:\n\n```diff\n- columnHelper.accessor((row) => row.profile.name, { id: 'name', header: 'Name' })\n\n+ { id: 'name', fieldFn: (row) => row.profile.name, header: 'Name' }\n```\n\n## Mounting\n\n```diff\n- const table = useReactTable({\n- data, columns,\n- getCoreRowModel: getCoreRowModel(),\n- getSortedRowModel: getSortedRowModel(),\n- getFilteredRowModel: getFilteredRowModel(),\n- })\n- return (\n- <table>\n- <thead>{table.getHeaderGroups().map(/* ... */)}</thead>\n- <tbody>{table.getRowModel().rows.map(/* ... */)}</tbody>\n- </table>\n- )\n\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+\n+ <SvGrid data={rows} columns={columns} features={features} />\n```\n\nSv-grid bundles the render + virtualization. No `<table>` you have\nto author yourself.\n\n## Imperative state\n\n| TanStack Table | sv-grid |\n| ------------------------------------------- | ---------------------------------------- |\n| `table.setColumnFilters([{id, value}])` | `api.setFilter(id, { operator: 'contains', value })` |\n| `table.getColumn('id')?.setFilterValue(v)` | `api.setFilter(id, { operator: 'contains', value: v })` |\n| `table.setSorting([{id, desc}])` | `api.setSort(id, desc ? 'desc' : 'asc')` |\n| `table.setRowSelection(state)` | n/a - use `api.clearRowSelection()` + UI events |\n| `table.toggleAllRowsExpanded()` | `api.expandAllGroups()` |\n| `table.getColumn('x').toggleVisibility()` | `api.setColumnVisible('x', false)` |\n| `table.options.meta?.foo` | Pass through component props / `$state` |\n\n## Custom cells\n\n```diff\n- {\n- header: 'Status',\n- cell: ({ row }) => <Badge tone={row.original.status} />,\n- }\n\n+ {\n+ field: 'status', header: 'Status',\n+ cell: (ctx) => renderSnippet(StatusCell, { tone: ctx.row.original.status }),\n+ }\n```\n\n`renderSnippet` accepts any Svelte 5 snippet; `renderComponent`\naccepts a regular component if you prefer SFCs.\n\n## Server-side data\n\n```diff\n- const [pagination, setPagination] = useState({pageIndex: 0, pageSize: 25})\n- const [sorting, setSorting] = useState([])\n- const table = useReactTable({\n- data, columns, manualPagination: true, manualSorting: true,\n- state: { pagination, sorting },\n- onPaginationChange: setPagination,\n- onSortingChange: setSorting,\n- })\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ externalSort={true}\n+ externalFilter={true}\n+ onSortingChange={(clauses) => refetch({ sort: clauses })}\n+ onFiltersChange={(f) => refetch({ filters: f.columns })}\n+ />\n```\n\nOr hand the fetching to a controller and pass it as one prop:\n`createServerDataSource(source, { mode: 'infinite' })` owns the blocks,\nthe sort and filter round trips and the placeholder rows, and the\nmanual-flag wiring above disappears. TanStack Table has no server row\nmodel; per-group fetching is yours to write, where the Enterprise\n`createServerRowModel` does it over the same contract.\n\n<div data-docs-demo=\"148-server-row-model\" data-height=\"480\"></div>\n\n## What you get for free vs TanStack Table\n\n- **Renderer**. TanStack is headless-only; you draw the `<table>`.\n Sv-grid ships an opinionated, fast renderer with virtualization,\n scroll, sticky headers, column resize, keyboard nav, ARIA.\n- **Inline editing**. `editorType: 'text' | 'number' | 'date' |\n 'list' | ...` - built-in editors with parsing + validation hooks.\n- **CSP-clean**. No `eval`. The shipped tests confirm.\n- **In-grid AI helpers**. Natural-language filter, smart fill, summarise\n and classify, free in `@svgrid/grid` against a model you register.\n- **Enterprise features**. Excel and PDF export, print, import and pivot\n in one paid add-on; CSV, TSV and JSON export are free.\n\nThe headless demo below is the shape a TanStack app has today - a plain\n`<table>` driven by the engine - running on `createSvGrid`:\n\n<div data-docs-demo=\"186-headless-table\" data-height=\"520\"></div>\n\n## What you give up\n\n- **One engine across frameworks.** TanStack has adapters for React,\n Vue, Solid, Qwik, Lit and Svelte; sv-grid is Svelte 5-native and has\n no React wrapper.\n- **The smallest engine-only bundle.** The facts box at the top of the\n page has both packages measured the same way; the difference is the\n renderer, virtualizer, filter UI and editors you would otherwise write.\n- **TanStack Virtual and the shadcn-svelte data table recipe.** Sv-grid\n virtualizes on its own and has its own\n [shadcn-svelte guide](./migrating-from-shadcn-data-table.md).\n- **`meta` for arbitrary side-channel state.** Pass props directly.\n- **`@tanstack/match-sorter-utils` integration**. The grid's filter\n has a `contains` operator; if you need fuzzy match, plug your\n matcher in via the column's `cell` snippet or use\n `externalFilter={true}` and run the matcher yourself.\n\n## Frequently asked questions\n\n### How long does it take to migrate from TanStack Table to SvGrid?\n\nAbout 30 minutes per read-only grid and 2-4 hours for editing-heavy grids.\nBoth libraries use explicit row-model pipelines, so `createTable()` +\n`getCoreRowModel()` maps almost directly onto `createSvGrid()` +\n`createCoreRowModel()`.\n\n### Why switch from TanStack Table to SvGrid on Svelte 5?\n\nTanStack Table is headless-only and multi-framework, so you build the entire\nDOM, virtualization, filter UI, and editing layer yourself. SvGrid keeps the\nheadless core but ships a batteries-included `<SvGrid>` render component -\nvirtualization, Excel-style filters, cell selection, and inline editing work\nin one prop pass.\n\n### Is SvGrid free like TanStack Table?\n\nYes - `@svgrid/grid` is MIT-licensed, like TanStack Table. SvGrid\nadditionally offers an optional paid `@svgrid/enterprise` pack for Excel and\nPDF export, print, pivot and import, which TanStack Table does not provide at\nall; TanStack sells Enterprise Support as consulting instead, as the facts box\nabove notes.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The v9 line of `@tanstack/svelte-table` declares a Svelte 5 peer range\nand reads rune data through getters; the version in the facts box above is\nthe one read from npm. If you are on the v8 adapter with Svelte 4 stores,\nthe port to sv-grid is the same work as the port to v9, minus the markup.\n\n## What you end up with\n\nThe same model you had, with the rendering already written.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} selectable />\n```\n\n## See also\n\n- [SvGrid vs TanStack Table](https://svgrid.com/compare/tanstack-table/) -\n the side-by-side comparison, with a source and date for every claim\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](./comparison.md) -\n the measured benchmark, TanStack column included\n- [Architecture](./architecture.md) - the headless engine + render\n component split\n- [Migrating from AG Grid](./migrating-from-ag-grid.md) - sibling guide\n- [Why headless?](../why-headless.md) - the design rationale\n"
6017
6160
  },
6018
6161
  {
6019
6162
  "slug": "help/migrating-from-ui-kit-tables",
6020
6163
  "path": "docs/help/migrating-from-ui-kit-tables.md",
6021
6164
  "title": "Migrating from a UI-kit table (Flowbite / Skeleton / shadcn-svelte)",
6022
6165
  "section": "Help",
6023
- "markdown": "\n# Migrating from a UI-kit table (Flowbite / Skeleton / shadcn-svelte)\n\nFlowbite-Svelte, Skeleton, and shadcn-svelte all ship a styled `<Table>`\ncomponent. They are presentation components: they render the rows you\npass and match your design tokens, but sorting, filtering,\nvirtualization, and editing are yours to write by hand. Moving to SvGrid\nreplaces that hand-rolled logic with built-in features - while still\nletting you match the design system.\n\n> **Not the shadcn-svelte data table.** That one is a separate recipe\n> built on TanStack Table v9, and it already does sorting, filtering,\n> pagination, and row selection. If that is what you have, read\n> [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md)\n> instead - the port is different, and smaller.\n\n<!-- facts:start svelte-ui-kit-tables -->\n> **Facts, checked 12 Sep 2026.** `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the 30 days to 10 Sep 2026. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026). Flowbite / Skeleton / shadcn-svelte tables pricing, as its site states it: Flowbite Svelte, Skeleton and shadcn-svelte are MIT component libraries; their table components are free and no grid licence is sold (https://github.com/themesberg/flowbite-svelte, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/).\n<!-- facts:end -->\n\n> Estimated effort: **30 min - 1 hour** per table. You are mostly\n> deleting `{#each}` markup and the sort / filter state you wrote\n> yourself.\n\n## When this guide applies\n\nYou have a table that started simple and has grown:\n\n- You added a click-to-sort handler and a sort-state variable.\n- You added a search box and an array `.filter(...)`.\n- The list got long and now you want virtualization or pagination.\n- You started editing cells inline and it got messy.\n\nThat is the moment a styled `<Table>` stops paying for itself.\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { Table, TableHead, TableHeadCell, TableBody, TableBodyRow, TableBodyCell } from 'flowbite-svelte'\n- let sortKey = 'name', asc = true\n- $: sorted = [...rows].sort((a, b) => (a[sortKey] > b[sortKey] ? 1 : -1) * (asc ? 1 : -1))\n- </script>\n-\n- <Table>\n- <TableHead>\n- <TableHeadCell on:click={() => (sortKey = 'name')}>Name</TableHeadCell>\n- <TableHeadCell on:click={() => (sortKey = 'amount')}>Amount</TableHeadCell>\n- </TableHead>\n- <TableBody>\n- {#each sorted as row}\n- <TableBodyRow>\n- <TableBodyCell>{row.name}</TableBodyCell>\n- <TableBodyCell>{row.amount}</TableBodyCell>\n- </TableBodyRow>\n- {/each}\n- </TableBody>\n- </Table>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\nThe sort handler, the `sorted` derivation, and the `{#each}` all go\naway. Sorting is a click on the header; filtering is the column menu.\n\n## Keep your design system\n\nSvGrid is unstyled-by-token, so it can match Flowbite / Skeleton /\nshadcn:\n\n- Re-theme through the `--sg-*` CSS custom properties (borders, header\n background, zebra rows, hover, selection, density).\n- Or drive those tokens from your Tailwind theme - see the\n [Tailwind integration](./tailwind.md) guide.\n\n## What you get for free\n\n- **Sorting, filtering, and pagination** without writing handlers.\n- **Row + column virtualization** so thousands of rows stay smooth.\n- **Inline editing**, **cell-range selection + copy**, grouping, tree,\n and master/detail when you need them.\n- **Accessibility** - WAI-ARIA grid roles and keyboard navigation built\n in, instead of a plain `<table>`.\n\n## What you give up\n\n- The **tiny footprint** of a styled `<table>` for a truly static list.\n- A **pixel-perfect**, zero-config match with the rest of the kit - you\n re-create the look with tokens instead (a one-time setup).\n\n## Frequently asked questions\n\n### When should I replace a Flowbite / Skeleton / shadcn table with a data grid?\n\nWhen the table needs sorting, filtering, virtualization, inline editing, or\nlarge datasets. These styled `<Table>` components are presentation only;\nonce you are hand-writing table behaviour, a data grid like SvGrid removes\nthat code. (shadcn-svelte also ships a separate TanStack-based data table -\nsee [that migration guide](./migrating-from-shadcn-data-table.md).)\n\n### Can SvGrid match my existing UI-kit styling?\n\nYes. SvGrid themes through `--sg-*` CSS variables, which you can wire to your\nTailwind / design-system tokens so it matches Flowbite, Skeleton, or\nshadcn-svelte.\n\n### Is it overkill for a small static table?\n\nFor a small, static table that never sorts or filters, a styled `<table>` is\nlighter and fine. Switch when the behaviour - not just the styling - becomes the\nwork.\n\n## What you end up with\n\nEverything the presentational table could not do: sort, filter, page, edit.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} editable />\n```\n\n## See also\n\n- [SvGrid vs UI-kit tables](https://svgrid.com/compare/svelte-ui-kit-tables/) - the side-by-side comparison\n- [Tailwind integration](./tailwind.md) - match your design system\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
6166
+ "markdown": "\n# Migrating from a UI-kit table (Flowbite / Skeleton / shadcn-svelte)\n\nFlowbite-Svelte, Skeleton, and shadcn-svelte all ship a styled `<Table>`\ncomponent. They are presentation components: they render the rows you\npass and match your design tokens, but sorting, filtering,\nvirtualization, and editing are yours to write by hand. Moving to SvGrid\nreplaces that hand-rolled logic with built-in features - while still\nletting you match the design system.\n\n> **Not the shadcn-svelte data table.** That one is a separate recipe\n> built on TanStack Table v9, and it already does sorting, filtering,\n> pagination, and row selection. If that is what you have, read\n> [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md)\n> instead - the port is different, and smaller.\n\n<!-- facts:start svelte-ui-kit-tables -->\n> **Facts, checked 12 Sep 2026.** `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the 30 days to 10 Sep 2026. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026). Flowbite / Skeleton / shadcn-svelte tables pricing, as its site states it: Flowbite Svelte, Skeleton and shadcn-svelte are MIT component libraries; their table components are free and no grid licence is sold (https://github.com/themesberg/flowbite-svelte, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/).\n<!-- facts:end -->\n\n> Estimated effort: **30 min - 1 hour** per table. You are mostly\n> deleting `{#each}` markup and the sort / filter state you wrote\n> yourself.\n\n## When this guide applies\n\nYou have a table that started simple and has grown:\n\n- You added a click-to-sort handler and a sort-state variable.\n- You added a search box and an array `.filter(...)`.\n- The list got long and now you want virtualization or pagination.\n- You started editing cells inline and it got messy.\n\nThat is the moment a styled `<Table>` stops paying for itself.\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { Table, TableHead, TableHeadCell, TableBody, TableBodyRow, TableBodyCell } from 'flowbite-svelte'\n- let sortKey = 'name', asc = true\n- $: sorted = [...rows].sort((a, b) => (a[sortKey] > b[sortKey] ? 1 : -1) * (asc ? 1 : -1))\n- </script>\n-\n- <Table>\n- <TableHead>\n- <TableHeadCell on:click={() => (sortKey = 'name')}>Name</TableHeadCell>\n- <TableHeadCell on:click={() => (sortKey = 'amount')}>Amount</TableHeadCell>\n- </TableHead>\n- <TableBody>\n- {#each sorted as row}\n- <TableBodyRow>\n- <TableBodyCell>{row.name}</TableBodyCell>\n- <TableBodyCell>{row.amount}</TableBodyCell>\n- </TableBodyRow>\n- {/each}\n- </TableBody>\n- </Table>\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\nThe sort handler, the `sorted` derivation, and the `{#each}` all go\naway. Sorting is a click on the header; filtering is the column menu.\n\n## Keep your design system\n\nSvGrid is unstyled-by-token, so it can match Flowbite / Skeleton /\nshadcn:\n\n- Re-theme through the `--sg-*` CSS custom properties (borders, header\n background, zebra rows, hover, selection, density).\n- Or drive those tokens from your Tailwind theme - see the\n [Tailwind integration](./tailwind.md) guide.\n\n## What you get for free\n\n- **Sorting, filtering, and pagination** without writing handlers.\n- **Row + column virtualization** so thousands of rows stay smooth.\n- **Inline editing**, **cell-range selection + copy**, grouping, tree,\n and master/detail when you need them.\n- **Accessibility** - WAI-ARIA grid roles and keyboard navigation built\n in, instead of a plain `<table>`.\n\n## What you give up\n\n- The **tiny footprint** of a styled `<table>` for a truly static list.\n- A **pixel-perfect**, zero-config match with the rest of the kit - you\n re-create the look with tokens instead (a one-time setup).\n\n## Frequently asked questions\n\n### When should I replace a Flowbite / Skeleton / shadcn table with a data grid?\n\nWhen the table needs sorting, filtering, virtualization, inline editing, or\nlarge datasets. These styled `<Table>` components are presentation only;\nonce you are hand-writing table behaviour, a data grid like SvGrid removes\nthat code. (shadcn-svelte also ships a separate TanStack-based data table -\nsee [that migration guide](./migrating-from-shadcn-data-table.md).)\n\n### Can SvGrid match my existing UI-kit styling?\n\nYes. SvGrid themes through `--sg-*` CSS variables, which you can wire to your\nTailwind / design-system tokens so it matches Flowbite, Skeleton, or\nshadcn-svelte.\n\n### Is it overkill for a small static table?\n\nFor a small, static table that never sorts or filters, a styled `<table>` is\nlighter and fine. Switch when the behaviour - not just the styling - becomes the\nwork.\n\n## What you end up with\n\nEverything the presentational table could not do: sort, filter, page, edit.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} editable />\n```\n\n## See also\n\n- [SvGrid vs UI-kit tables](https://svgrid.com/compare/svelte-ui-kit-tables/) - the side-by-side comparison\n- [Tailwind integration](./tailwind.md) - match your design system\n- [Getting started](../getting-started.md) - a working grid in ~15 lines\n"
6024
6167
  },
6025
6168
  {
6026
6169
  "slug": "help/migrating-from-vincjo-datatables",
6027
6170
  "path": "docs/help/migrating-from-vincjo-datatables.md",
6028
6171
  "title": "Migrating from @vincjo/datatables",
6029
6172
  "section": "Help",
6030
- "markdown": "# Migrating from @vincjo/datatables\n\n`@vincjo/datatables` is a small, ergonomic Svelte datatable helper: you\nwrap your data in a handler and it gives you reactive sorting,\nfiltering, and pagination while you keep your own table markup. SvGrid\ncovers the same job and then keeps going - virtualization, an\nExcel-style filter menu, inline editing, and a render component - so the\nport is mostly about deciding how much markup you want to keep.\n\n> Estimated effort: **30 min - 2 hours** per table. A simple list is a\n> 30-minute swap; a feature-heavy one trends toward two hours.\n\n<!-- facts:start vincjo-datatables -->\n> **Facts, checked 12 Sep 2026.** `@vincjo/datatables` 2.8.1, MIT, last published 4 Jun 2026, 72,800 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `@vincjo/datatables` 2.8.1 10.2 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). @vincjo/datatables pricing, as its site states it: @vincjo/datatables is MIT on npm and free; no licence is sold (https://github.com/vincjo/datatables, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| @vincjo/datatables | sv-grid |\n| ------------------------------------------ | ----------------------------------------- |\n| `new TableHandler(data, { rowsPerPage })` | `createSvGrid({...})` or `<SvGrid>` |\n| `<ThSort {table} field=\"name\">` | `rowSortingFeature` (header sort built in) |\n| `<ThFilter {table} field=\"name\">` | `columnFilteringFeature` |\n| `table.global.set(query)` (search) | `api.setState({ globalFilter: query })` |\n| `<Pagination {table} />` / `<RowCount>` | Built in; toggle `showPagination` |\n| `table.rows` (current page rows) | `api.getDisplayedRows()` |\n| Server mode (`table.load(...)`) | `externalSort` / `externalFilter` + refetch |\n| Your own `<table>` + `{#each table.rows}` | `<SvGrid>` render component |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { TableHandler, ThSort, ThFilter, Pagination } from '@vincjo/datatables'\n- const table = new TableHandler(rows, { rowsPerPage: 25 })\n- </script>\n-\n- <table>\n- <thead><tr>\n- <ThSort {table} field=\"name\">Name</ThSort>\n- <ThSort {table} field=\"amount\">Amount</ThSort>\n- </tr></thead>\n- <tbody>\n- {#each table.rows as row}\n- <tr><td>{row.name}</td><td>{row.amount}</td></tr>\n- {/each}\n- </tbody>\n- </table>\n- <Pagination {table} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## Server-side data\n\n```diff\n- // @vincjo/datatables: drive a server with the handler's load hook\n- const table = new TableHandler(rows, { rowsPerPage: 25 })\n- table.load((state) => fetchRows(state)) // sort/filter/page sent to your API\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ externalSort={true} externalFilter={true}\n+ onSortingChange={(clauses) => refetch({ sort: clauses })}\n+ onFiltersChange={(f) => refetch({ filters: f.columns })}\n+ />\n```\n\n## What you get for free\n\n- **A render component** with virtualization - you stop authoring the\n `<table>` and the `{#each}`.\n- **Excel-style filter menu**, **cell-range selection + copy**, and\n **inline editing** with typed editors.\n- **Grouping, tree data, and master/detail** when the table grows up.\n- **Enterprise features** - export, import, pivot, AI.\n\n## What you give up\n\n- **The tiny footprint.** If all you ever need is sort / filter /\n paginate over a small list, `@vincjo/datatables` stays smaller.\n- **Total markup control.** SvGrid renders the table; you theme it with\n `--sg-*` tokens and Tailwind rather than writing every `<td>`.\n\n## Frequently asked questions\n\n### Should I move from @vincjo/datatables to SvGrid?\n\nMove when a hand-rolled table stops being enough - when you need virtualization\nfor large datasets, an Excel-style filter menu, inline editing, grouping, or\ntree data. For a small sort/filter/paginate list, `@vincjo/datatables` is a fine,\nlighter choice.\n\n### Is SvGrid also MIT-licensed like @vincjo/datatables?\n\nYes. `@svgrid/grid` is MIT, like `@vincjo/datatables`. SvGrid adds an\noptional paid `@svgrid/enterprise` pack (export, import, pivot, AI).\n\n### Can I keep my own table markup after switching?\n\nYes. SvGrid has a headless core (`createSvGrid` + row-model factories) you can\ndrive with your own markup, the same way `@vincjo/datatables` lets you. Most\nteams use the `<SvGrid>` component instead because it removes the boilerplate.\n\n## What you end up with\n\nSorting, filtering and pagination without the hand-written table around it.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/) - the side-by-side comparison\n- [Migrating from svelte-headless-table](./migrating-from-svelte-headless-table.md) - sibling Svelte guide\n- [Why headless?](../why-headless.md) - keep your own markup if you want to\n"
6173
+ "markdown": "# Migrating from @vincjo/datatables\n\n`@vincjo/datatables` is a small, ergonomic Svelte datatable helper: you\nwrap your data in a handler and it gives you reactive sorting,\nfiltering, and pagination while you keep your own table markup. SvGrid\ncovers the same job and then keeps going - virtualization, an\nExcel-style filter menu, inline editing, and a render component - so the\nport is mostly about deciding how much markup you want to keep.\n\n> Estimated effort: **30 min - 2 hours** per table. A simple list is a\n> 30-minute swap; a feature-heavy one trends toward two hours.\n\n<!-- facts:start vincjo-datatables -->\n> **Facts, checked 12 Sep 2026.** `@vincjo/datatables` 2.8.1, MIT, last published 4 Jun 2026, 72,800 npm downloads in the 30 days to 10 Sep 2026. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `@vincjo/datatables` 2.8.1 10.2 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). @vincjo/datatables pricing, as its site states it: @vincjo/datatables is MIT on npm and free; no licence is sold (https://github.com/vincjo/datatables, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/).\n<!-- facts:end -->\n\n## Vocabulary cheat sheet\n\n| @vincjo/datatables | sv-grid |\n| ------------------------------------------ | ----------------------------------------- |\n| `new TableHandler(data, { rowsPerPage })` | `createSvGrid({...})` or `<SvGrid>` |\n| `<ThSort {table} field=\"name\">` | `rowSortingFeature` (header sort built in) |\n| `<ThFilter {table} field=\"name\">` | `columnFilteringFeature` |\n| `table.global.set(query)` (search) | `api.setState({ globalFilter: query })` |\n| `<Pagination {table} />` / `<RowCount>` | Built in; toggle `showPagination` |\n| `table.rows` (current page rows) | `api.getDisplayedRows()` |\n| Server mode (`table.load(...)`) | `externalSort` / `externalFilter` + refetch |\n| Your own `<table>` + `{#each table.rows}` | `<SvGrid>` render component |\n\n## Before / after\n\nThe example at the end of this page runs against these rows:\n\n```svelte {preamble}\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n\n type Person = {\n id: number\n name: string\n department: string\n city: string\n age: number\n salary: number\n }\n\n const people: Person[] = [\n { id: 1, name: 'Ada Lovelace', department: 'Engineering', city: 'London', age: 36, salary: 142000 },\n { id: 2, name: 'Grace Hopper', department: 'Engineering', city: 'New York', age: 45, salary: 168000 },\n { id: 3, name: 'Linus Torvalds', department: 'Platform', city: 'Portland', age: 54, salary: 155000 },\n { id: 4, name: 'Radia Perlman', department: 'Networking', city: 'Seattle', age: 49, salary: 161000 },\n { id: 5, name: 'Barbara Liskov', department: 'Platform', city: 'Boston', age: 52, salary: 172000 },\n ]\n\n let rows = $state<Person[]>(people)\n\n const columns: GridColumns<Person> = [\n { field: 'name', header: 'Name', width: 200, editorType: 'text' },\n { field: 'department', header: 'Department', width: 150, editorType: 'text' },\n { field: 'city', header: 'City', width: 140, editorType: 'text' },\n { field: 'age', header: 'Age', width: 90, editorType: 'number' },\n { field: 'salary', header: 'Salary', width: 130, editorType: 'number', format: { type: 'currency', currency: 'USD' } },\n ]\n</script>\n```\n\n```diff\n- <script>\n- import { TableHandler, ThSort, ThFilter, Pagination } from '@vincjo/datatables'\n- const table = new TableHandler(rows, { rowsPerPage: 25 })\n- </script>\n-\n- <table>\n- <thead><tr>\n- <ThSort {table} field=\"name\">Name</ThSort>\n- <ThSort {table} field=\"amount\">Amount</ThSort>\n- </tr></thead>\n- <tbody>\n- {#each table.rows as row}\n- <tr><td>{row.name}</td><td>{row.amount}</td></tr>\n- {/each}\n- </tbody>\n- </table>\n- <Pagination {table} />\n\n+ <script lang=\"ts\">\n+ import {\n+ SvGrid, tableFeatures, rowSortingFeature, columnFilteringFeature,\n+ type ColumnDef,\n+ } from '@svgrid/grid'\n+\n+ const features = tableFeatures({ rowSortingFeature, columnFilteringFeature })\n+ const columns: ColumnDef<typeof features, Row>[] = [\n+ { field: 'name', header: 'Name' },\n+ { field: 'amount', header: 'Amount', format: { type: 'currency', currency: 'USD' } },\n+ ]\n+ </script>\n+\n+ <SvGrid data={rows} columns={columns} features={features} showPagination />\n```\n\n## Server-side data\n\n```diff\n- // @vincjo/datatables: drive a server with the handler's load hook\n- const table = new TableHandler(rows, { rowsPerPage: 25 })\n- table.load((state) => fetchRows(state)) // sort/filter/page sent to your API\n\n+ <SvGrid\n+ data={rows} columns={columns} features={features}\n+ externalSort={true} externalFilter={true}\n+ onSortingChange={(clauses) => refetch({ sort: clauses })}\n+ onFiltersChange={(f) => refetch({ filters: f.columns })}\n+ />\n```\n\n## What you get for free\n\n- **A render component** with virtualization - you stop authoring the\n `<table>` and the `{#each}`.\n- **Excel-style filter menu**, **cell-range selection + copy**, and\n **inline editing** with typed editors.\n- **Grouping, tree data, and master/detail** when the table grows up.\n- **Enterprise features** - export, import, pivot, AI.\n\n## What you give up\n\n- **The tiny footprint.** If all you ever need is sort / filter /\n paginate over a small list, `@vincjo/datatables` stays smaller.\n- **Total markup control.** SvGrid renders the table; you theme it with\n `--sg-*` tokens and Tailwind rather than writing every `<td>`.\n\n## Frequently asked questions\n\n### Should I move from @vincjo/datatables to SvGrid?\n\nMove when a hand-rolled table stops being enough - when you need virtualization\nfor large datasets, an Excel-style filter menu, inline editing, grouping, or\ntree data. For a small sort/filter/paginate list, `@vincjo/datatables` is a fine,\nlighter choice.\n\n### Is SvGrid also MIT-licensed like @vincjo/datatables?\n\nYes. `@svgrid/grid` is MIT, like `@vincjo/datatables`. SvGrid adds an\noptional paid `@svgrid/enterprise` pack (export, import, pivot, AI).\n\n### Can I keep my own table markup after switching?\n\nYes. SvGrid has a headless core (`createSvGrid` + row-model factories) you can\ndrive with your own markup, the same way `@vincjo/datatables` lets you. Most\nteams use the `<SvGrid>` component instead because it removes the boilerplate.\n\n## What you end up with\n\nSorting, filtering and pagination without the hand-written table around it.\n\n```svelte {runnable}\n<SvGrid data={rows} {columns} sortable filterable pageable pageSize={3} />\n```\n\n## See also\n\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/) - the side-by-side comparison\n- [Migrating from svelte-headless-table](./migrating-from-svelte-headless-table.md) - sibling Svelte guide\n- [Why headless?](../why-headless.md) - keep your own markup if you want to\n"
6031
6174
  },
6032
6175
  {
6033
6176
  "slug": "help/missing-features",
@@ -6447,7 +6590,7 @@ export const docs = [
6447
6590
  "path": "docs/help/svelte-5-upgrade-data-tables.md",
6448
6591
  "title": "Upgrading a Svelte 4 table to Svelte 5: what breaks, what does not, and the three ways out",
6449
6592
  "section": "Help",
6450
- "markdown": "\n# Upgrading a Svelte 4 table to Svelte 5: what breaks, what does not, and the three ways out\n\nIf your Svelte 4 app has a table built on `svelte-headless-table`, the Svelte 5\nupgrade forces a decision about it, and most of what is written about that\ndecision is guesswork. This page is not. We put the table from the library's\nown documentation into a Svelte 4 project, upgraded it to Svelte 5 one step at a\ntime, and captured every line the tools printed. The script and the captures\nare in the repo at\n[tools/migration-lab](https://github.com/sv-grid/sv-grid/tree/main/tools/migration-lab);\nevery code block below is a quote from those files, checked by a test, and the\nfirst line of each capture records the versions it was made with.\n\n<!-- facts:start svelte-headless-table pkg:@humanspeak/svelte-headless-table -->\n> **Facts, checked 12 Sep 2026.** `svelte-headless-table` 0.18.3, MIT, last published 28 Oct 2024, 90,100 npm downloads in the 30 days to 10 Sep 2026. `@humanspeak/svelte-headless-table` 6.2.0, MIT, last published 27 Aug 2026, 8,640 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.30 100.0 KB JS + 11.3 KB CSS (measured 30 Oct 2026); `svelte-headless-table` 0.18.3 5.7 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). svelte-headless-table pricing, as its site states it: svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port (https://github.com/bryanmylee/svelte-headless-table, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/).\n<!-- facts:end -->\n\nThe short version: the install warns and goes through, the untouched component\nkeeps compiling, and the trouble starts the day you write your first rune in\nthat component. The three exits are a maintained fork, TanStack Table v9, and\nSvGrid, and they trade different things.\n\n## The component we upgraded\n\nA `PeopleTable` written the way svelte-headless-table's docs teach it: a\n`writable` over a prop, a `$:` to keep it in sync, three plugins, the view model\nread through `<Subscribe>` and `<Render>`, a pager on `pluginStates.page`, and a\n`select` event dispatched from the row.\n\n<!-- captured: fixture/svelte4/PeopleTable.svelte -->\n```svelte\n<script lang=\"ts\">\n // The table as svelte-headless-table's own docs show it: a store for the\n // data, plugins for behaviour, and a view model read through <Subscribe>\n // and <Render>. Svelte 4 throughout: `export let`, `$:`, a dispatcher,\n // `on:click`, and `let:` slot props.\n import { createEventDispatcher } from 'svelte'\n import { writable } from 'svelte/store'\n import { createTable, Subscribe, Render } from 'svelte-headless-table'\n import { addSortBy, addColumnFilters, addPagination } from 'svelte-headless-table/plugins'\n import type { Person } from './people'\n\n export let people: Person[] = []\n export let pageSize = 5\n\n const dispatch = createEventDispatcher<{ select: Person }>()\n\n const data = writable<Person[]>(people)\n $: data.set(people)\n\n const table = createTable(data, {\n sort: addSortBy(),\n filter: addColumnFilters(),\n page: addPagination({ initialPageSize: pageSize }),\n })\n```\n\nThe full file is 83 lines; the 40 that follow are the `<table>`, three levels\nof `<Subscribe let:...>` and a `<p>` with the pager. On the pinned Svelte 4\ntoolchain it checks clean:\n\n<!-- captured: 01-svelte4-baseline.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\n## Step 1: the install warns and goes through\n\n`svelte-headless-table` declares `peerDependencies: { svelte: \"^4.0.0\" }`, and\nthat range is not going to change: the facts box above has the last release\ndate, and the project's README says there are no plans for a Svelte 5 port.\nSo what does `npm install svelte@5` do against it? On npm 11, this:\n\n<!-- captured: 02-npm-install-svelte5.txt -->\n```text\n$ npm install svelte@5.57.1\n\nadded 10 packages, removed 10 packages, and changed 2 packages in <time>\nnpm warn ERESOLVE overriding peer dependency\nnpm warn While resolving: svgrid-migration-lab@undefined\nnpm warn Found: svelte@4.2.20\nnpm warn node_modules/svelte\nnpm warn peer svelte@\"^4.0.0 || ^5.0.0-next.0\" from svelte-check@4.7.6\nnpm warn node_modules/svelte-check\nnpm warn dev svelte-check@\"4.7.6\" from the root project\nnpm warn 5 more (svelte-headless-table, svelte-keyed, svelte-render, ...)\nnpm warn\nnpm warn Could not resolve dependency:\nnpm warn peer svelte@\"^4.0.0\" from svelte-headless-table@0.18.3\nnpm warn node_modules/svelte-headless-table\nnpm warn dev svelte-headless-table@\"0.18.3\" from the root project\nnpm warn ERESOLVE overriding peer dependency\nnpm warn ERESOLVE overriding peer dependency\nnpm warn ERESOLVE overriding peer dependency\n\n(exit 0)\n```\n\nExit 0. npm 11 overrides the conflict and tells you so; older npm releases\nstopped with an `ERESOLVE` error until you added `--legacy-peer-deps`, and\npnpm prints an unmet-peer warning of its own. Either way, the peer range is a\nstatement, not a lock: the library's author is telling you it was never run\nagainst the Svelte you now have. Nothing enforces it.\n\n## Step 2: the untouched component still compiles\n\nSvelte 5 compiles Svelte 4 components in legacy mode, so `export let`, `$:`,\n`createEventDispatcher`, `on:click` and `let:` slot props all keep working\nuntil you opt a file into runes. With Svelte 5 installed and the component\nexactly as it was:\n\n<!-- captured: 03-svelte5-legacy-component.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\nThis is the part the scare stories leave out. If your only goal is to be on\nSvelte 5, you can install it, keep the table exactly as it is, and ship. The\nlibrary's own components (`<Subscribe>`, `<Render>`) compile in legacy mode\ntoo.\n\n## Step 3: the first rune\n\nWhat you cannot do is make that component a runes component and keep the\ntable as it is. Port `PeopleTable` by the rules in the\n[official migration guide](https://svelte.dev/docs/svelte/v5-migration-guide):\n`export let` becomes `$props()`, `$:` becomes `$derived` and `$effect`, the\ndispatcher becomes a callback prop, `on:click` becomes `onclick`. Leave the\nsvelte-headless-table wiring alone, because the guide has nothing to say about\nit. The checker now says:\n\n<!-- captured: 04-svelte5-runes-component.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\n<lab>\\src\\PeopleTable.svelte:19:35\nWarn: This reference only captures the initial value of `people`. Did you mean to reference it inside a closure instead?\nhttps://svelte.dev/e/state_referenced_locally (svelte)\n\n<lab>\\src\\PeopleTable.svelte:27:44\nWarn: This reference only captures the initial value of `pageSize`. Did you mean to reference it inside a closure instead?\nhttps://svelte.dev/e/state_referenced_locally (svelte)\n\n====================================\nsvelte-check found 0 errors and 2 warnings in 1 file\n```\n\nTwo warnings, no errors, and both are the same fact: the library takes a store,\nyour data is now a rune, and the `writable(people)` you built to bridge them\ncaptured the first value of `people` and nothing after. The fix is an\n`$effect` that writes the prop into the store on every change, which is what\nthe ported fixture does, and it works. It is also a bridge you now own, in\nevery component that has a table, between a reactivity model the library was\nbuilt for and the one your app is written in.\n\nThat is the actual shape of the problem. Not a red build: a component that\ncompiles, with a store-and-slot-props library bolted to a runes app by code you\nmaintain, on a package that will not move. The pieces it leans on are the ones\nSvelte 5 has deprecated: `let:` slot props and `<slot>` in favour of snippets,\nand `<svelte:component>`, which is what `<Render>` uses underneath\n(`svelte-render` 2.0.1, `PropsRenderer.svelte`, peer `svelte ^4.0.0`). They\nkeep working in legacy mode today; deprecated syntax is what the next major\nremoves, and this library will not be updated when it does.\n\n## The three ways out\n\nYou have three honest options, and you should know all of them before picking.\n\n1. **`@humanspeak/svelte-headless-table`**, a maintained fork on Svelte 5 with\n the same API. Its version, publish date and downloads are in the facts box.\n Switching is one package rename; you keep every line of markup and every\n `<Subscribe>`, and you keep the store bridge from step 3. If your table\n works and Svelte 5 is all you need, this is the cheapest exit by a wide\n margin.\n2. **TanStack Table v9.** Its Svelte adapter declares a Svelte 5 peer range and\n its state shape is runes-first, so the bridge goes away. It is still\n headless: you write and maintain the `<table>`, the virtualizer, the filter\n UI and the editors yourself. The\n [TanStack migration guide](./migrating-from-tanstack-table.md) covers the\n vocabulary.\n3. **SvGrid.** A different trade: you delete the markup and take a renderer.\n The column definitions and the plugin list carry over; the `<table>`, the\n `<Subscribe>` blocks, the pager and the store bridge do not exist any more,\n because `<SvGrid>` renders all of that. The rest of this page is what that\n looks like on the fixture above.\n\nPick 1 if the markup is fine and the library being dead does not bother you.\nPick 2 if you want the markup and a maintained engine. Pick 3 if the markup is\nthe part you are tired of.\n\n## Step 4: the codemod\n\n`npx @svgrid/migrate` ports a svelte-headless-table component to SvGrid. It\npreviews by default and only writes with `--write`, and it says what it could\nnot map instead of dropping it. On the Svelte 4 original:\n\n<!-- captured: 05-codemod.txt -->\n```text\n warning A custom `cell` renderer was found. SvGrid renders cells with a snippet, not `createRender`, so this one needs porting by hand - it is preserved as a comment.\n warning The template still reads `pageIndex`, `pageCount`, `shown` from the view model, which is gone. <SvGrid> renders its own pager and row count (`pageable`, `showPagination`), so remove that markup, or read the grid through `onApiReady` if you need the numbers.\n warning The table markup dispatched `select` from a row; that handler went with the `<tr>`. Wire it to `onRowClick={({ row }) => ...}` (or `onCellClick`) on <SvGrid>, and turn the `createEventDispatcher` into a callback prop if the component is moving to runes.\n note Column resizing, keyboard navigation and ARIA grid semantics are built into <SvGrid>; the markup that provided them is intentionally gone.\n\n1 file(s) would change, with 3 warning(s).\nRe-run with --write to apply.\n```\n\nThree warnings, each naming a thing it left for you. Write it, swap the\npackages, and check:\n\n<!-- captured: 06-after-codemod.txt -->\n```text\n$ npm install @svgrid/grid@3.0.4 --legacy-peer-deps\n\nadded 1 package in <time>\n\n(exit 0)\n\n$ npm uninstall svelte-headless-table --legacy-peer-deps\n\nremoved 4 packages in <time>\n\n(exit 0)\n\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\n<lab>\\src\\PeopleTable.svelte:31:23\nError: `$pageIndex` is an illegal variable name. To reference a global variable called `$pageIndex`, use `globalThis.$pageIndex`\nhttps://svelte.dev/e/global_reference_invalid (svelte)\n```\n\n<!-- captured: 06-after-codemod.txt -->\n```text\nsvelte-check found 9 errors and 0 warnings in 1 file\n```\n\nAll nine are the pager `<p>` the second warning named, reading `shown`,\n`$pageIndex` and `$pageCount` from a view model that no longer exists. The\ncodemod does not delete markup outside the `<table>`, because it cannot know\nwhat else is in there; it tells you what will not compile. Delete the `<p>`\n(the grid draws its own pager), turn the `select` event into a callback prop\non `onRowClick` as the third warning says, and:\n\n<!-- captured: 07-hand-edits.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\n## What you end up with\n\nThe component after the codemod and the two hand edits:\n\n<!-- captured: PeopleTable.after.svelte -->\n```svelte\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n import type { Person } from './people'\n export let people: Person[] = []\n export let pageSize = 5\n export let onselect: (person: Person) => void = () => {}\n\n const columns: GridColumns<(typeof people)[number]> = [\n {\n header: 'Name',\n field: 'name',\n },\n {\n header: 'Department',\n field: 'department',\n },\n {\n header: 'City',\n field: 'city',\n },\n {\n header: 'Salary',\n field: 'salary',\n // TODO port: cell: ({ value }) => value.toLocaleString('en-US', { style: 'currency', currency: 'USD\n },\n ]\n</script>\n\n<SvGrid data={people} {columns} sortable filterable showColumnFilters pageable pageSize={pageSize}\n onRowClick={({ row }) => onselect(row)} />\n```\n\n83 lines became 31. The `TODO port:` comment is the one thing left to do by\nhand: the currency cell becomes `format: { type: 'currency', currency: 'USD' }`\non the column, and the comment goes. There is no store, no `$:`, no\n`<Subscribe>`, no `let:`, and nothing in the file that Svelte 5 has deprecated,\nso the same component moves to runes whenever you like with the official\nmigration script and nothing else to port.\n\n## What to read next\n\n- [Migrating from svelte-headless-table](./migrating-from-svelte-headless-table.md) -\n the plugin-by-plugin mapping and what the codemod will not do\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/) -\n the side-by-side, with a source and date for every claim\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - exit 2 in detail\n- [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md) -\n the same codemod on the TanStack-based recipe\n- [Why headless?](../why-headless.md) - if you want to keep your own markup\n on a maintained Svelte 5 engine, `@svgrid/grid/core` is that too\n\n## Frequently asked questions\n\n### Does svelte-headless-table work with Svelte 5?\n\nIn legacy mode, yes: the install prints a peer-dependency warning and the\nuntouched component type-checks clean, as the captures above show. What does\nnot work is moving a component that uses it to runes without maintaining a\nstore bridge yourself, and the library is not going to be updated for the\ndeprecations that bridge leans on.\n\n### Is the peer dependency conflict an error?\n\nOn npm 11 it is a warning and the install exits 0; on older npm it was an\n`ERESOLVE` error until you passed `--legacy-peer-deps`; pnpm warns. It never\nstops the code from running. It tells you the library was not built against\nthe Svelte you have.\n\n### Should I just use the maintained fork?\n\nIf your table works and all you need is Svelte 5, yes, and this page says so.\nThe fork keeps the same API, so you keep the same markup and the same store\nbridge. Move to SvGrid when the markup and the bridge are what you want gone.\n\n### How much of the port does the codemod do?\n\nThe column definitions, the plugin list and the `<table>` replacement, and it\nnames what it leaves: custom cell renderers, markup outside the table that read\nthe view model, and events the rows dispatched. On the fixture that was two\nhand edits and one `format` option.\n\n### Can I rerun this myself?\n\n`node tools/migration-lab/run.mjs` in the repo. It installs the pinned Svelte 4\ntoolchain into its own folder, upgrades it, runs the codemod from the checkout,\nand rewrites the captured files; the header of each one records the versions.\nBump the pins to try a newer Svelte.\n"
6593
+ "markdown": "\n# Upgrading a Svelte 4 table to Svelte 5: what breaks, what does not, and the three ways out\n\nIf your Svelte 4 app has a table built on `svelte-headless-table`, the Svelte 5\nupgrade forces a decision about it, and most of what is written about that\ndecision is guesswork. This page is not. We put the table from the library's\nown documentation into a Svelte 4 project, upgraded it to Svelte 5 one step at a\ntime, and captured every line the tools printed. The script and the captures\nare in the repo at\n[tools/migration-lab](https://github.com/sv-grid/sv-grid/tree/main/tools/migration-lab);\nevery code block below is a quote from those files, checked by a test, and the\nfirst line of each capture records the versions it was made with.\n\n<!-- facts:start svelte-headless-table pkg:@humanspeak/svelte-headless-table -->\n> **Facts, checked 12 Sep 2026.** `svelte-headless-table` 0.18.3, MIT, last published 28 Oct 2024, 90,100 npm downloads in the 30 days to 10 Sep 2026. `@humanspeak/svelte-headless-table` 6.2.0, MIT, last published 27 Aug 2026, 8,640 npm downloads in the same window. `@svgrid/grid` 3.0.3, MIT, last published 11 Sep 2026, 16,900 npm downloads in the same window. Bundle, minified and gzipped, each package built alone with Svelte external: SvGrid 3.0.31 99.8 KB JS + 11.3 KB CSS (measured 1 Nov 2026); `svelte-headless-table` 0.18.3 5.7 KB JS, no separate stylesheet, svelte external (measured 12 Sep 2026). svelte-headless-table pricing, as its site states it: svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port (https://github.com/bryanmylee/svelte-headless-table, read 12 Sep 2026). SvGrid: MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise. Side by side, with sources: [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/).\n<!-- facts:end -->\n\nThe short version: the install warns and goes through, the untouched component\nkeeps compiling, and the trouble starts the day you write your first rune in\nthat component. The three exits are a maintained fork, TanStack Table v9, and\nSvGrid, and they trade different things.\n\n## The component we upgraded\n\nA `PeopleTable` written the way svelte-headless-table's docs teach it: a\n`writable` over a prop, a `$:` to keep it in sync, three plugins, the view model\nread through `<Subscribe>` and `<Render>`, a pager on `pluginStates.page`, and a\n`select` event dispatched from the row.\n\n<!-- captured: fixture/svelte4/PeopleTable.svelte -->\n```svelte\n<script lang=\"ts\">\n // The table as svelte-headless-table's own docs show it: a store for the\n // data, plugins for behaviour, and a view model read through <Subscribe>\n // and <Render>. Svelte 4 throughout: `export let`, `$:`, a dispatcher,\n // `on:click`, and `let:` slot props.\n import { createEventDispatcher } from 'svelte'\n import { writable } from 'svelte/store'\n import { createTable, Subscribe, Render } from 'svelte-headless-table'\n import { addSortBy, addColumnFilters, addPagination } from 'svelte-headless-table/plugins'\n import type { Person } from './people'\n\n export let people: Person[] = []\n export let pageSize = 5\n\n const dispatch = createEventDispatcher<{ select: Person }>()\n\n const data = writable<Person[]>(people)\n $: data.set(people)\n\n const table = createTable(data, {\n sort: addSortBy(),\n filter: addColumnFilters(),\n page: addPagination({ initialPageSize: pageSize }),\n })\n```\n\nThe full file is 83 lines; the 40 that follow are the `<table>`, three levels\nof `<Subscribe let:...>` and a `<p>` with the pager. On the pinned Svelte 4\ntoolchain it checks clean:\n\n<!-- captured: 01-svelte4-baseline.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\n## Step 1: the install warns and goes through\n\n`svelte-headless-table` declares `peerDependencies: { svelte: \"^4.0.0\" }`, and\nthat range is not going to change: the facts box above has the last release\ndate, and the project's README says there are no plans for a Svelte 5 port.\nSo what does `npm install svelte@5` do against it? On npm 11, this:\n\n<!-- captured: 02-npm-install-svelte5.txt -->\n```text\n$ npm install svelte@5.57.1\n\nadded 10 packages, removed 10 packages, and changed 2 packages in <time>\nnpm warn ERESOLVE overriding peer dependency\nnpm warn While resolving: svgrid-migration-lab@undefined\nnpm warn Found: svelte@4.2.20\nnpm warn node_modules/svelte\nnpm warn peer svelte@\"^4.0.0 || ^5.0.0-next.0\" from svelte-check@4.7.6\nnpm warn node_modules/svelte-check\nnpm warn dev svelte-check@\"4.7.6\" from the root project\nnpm warn 5 more (svelte-headless-table, svelte-keyed, svelte-render, ...)\nnpm warn\nnpm warn Could not resolve dependency:\nnpm warn peer svelte@\"^4.0.0\" from svelte-headless-table@0.18.3\nnpm warn node_modules/svelte-headless-table\nnpm warn dev svelte-headless-table@\"0.18.3\" from the root project\nnpm warn ERESOLVE overriding peer dependency\nnpm warn ERESOLVE overriding peer dependency\nnpm warn ERESOLVE overriding peer dependency\n\n(exit 0)\n```\n\nExit 0. npm 11 overrides the conflict and tells you so; older npm releases\nstopped with an `ERESOLVE` error until you added `--legacy-peer-deps`, and\npnpm prints an unmet-peer warning of its own. Either way, the peer range is a\nstatement, not a lock: the library's author is telling you it was never run\nagainst the Svelte you now have. Nothing enforces it.\n\n## Step 2: the untouched component still compiles\n\nSvelte 5 compiles Svelte 4 components in legacy mode, so `export let`, `$:`,\n`createEventDispatcher`, `on:click` and `let:` slot props all keep working\nuntil you opt a file into runes. With Svelte 5 installed and the component\nexactly as it was:\n\n<!-- captured: 03-svelte5-legacy-component.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\nThis is the part the scare stories leave out. If your only goal is to be on\nSvelte 5, you can install it, keep the table exactly as it is, and ship. The\nlibrary's own components (`<Subscribe>`, `<Render>`) compile in legacy mode\ntoo.\n\n## Step 3: the first rune\n\nWhat you cannot do is make that component a runes component and keep the\ntable as it is. Port `PeopleTable` by the rules in the\n[official migration guide](https://svelte.dev/docs/svelte/v5-migration-guide):\n`export let` becomes `$props()`, `$:` becomes `$derived` and `$effect`, the\ndispatcher becomes a callback prop, `on:click` becomes `onclick`. Leave the\nsvelte-headless-table wiring alone, because the guide has nothing to say about\nit. The checker now says:\n\n<!-- captured: 04-svelte5-runes-component.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\n<lab>\\src\\PeopleTable.svelte:19:35\nWarn: This reference only captures the initial value of `people`. Did you mean to reference it inside a closure instead?\nhttps://svelte.dev/e/state_referenced_locally (svelte)\n\n<lab>\\src\\PeopleTable.svelte:27:44\nWarn: This reference only captures the initial value of `pageSize`. Did you mean to reference it inside a closure instead?\nhttps://svelte.dev/e/state_referenced_locally (svelte)\n\n====================================\nsvelte-check found 0 errors and 2 warnings in 1 file\n```\n\nTwo warnings, no errors, and both are the same fact: the library takes a store,\nyour data is now a rune, and the `writable(people)` you built to bridge them\ncaptured the first value of `people` and nothing after. The fix is an\n`$effect` that writes the prop into the store on every change, which is what\nthe ported fixture does, and it works. It is also a bridge you now own, in\nevery component that has a table, between a reactivity model the library was\nbuilt for and the one your app is written in.\n\nThat is the actual shape of the problem. Not a red build: a component that\ncompiles, with a store-and-slot-props library bolted to a runes app by code you\nmaintain, on a package that will not move. The pieces it leans on are the ones\nSvelte 5 has deprecated: `let:` slot props and `<slot>` in favour of snippets,\nand `<svelte:component>`, which is what `<Render>` uses underneath\n(`svelte-render` 2.0.1, `PropsRenderer.svelte`, peer `svelte ^4.0.0`). They\nkeep working in legacy mode today; deprecated syntax is what the next major\nremoves, and this library will not be updated when it does.\n\n## The three ways out\n\nYou have three honest options, and you should know all of them before picking.\n\n1. **`@humanspeak/svelte-headless-table`**, a maintained fork on Svelte 5 with\n the same API. Its version, publish date and downloads are in the facts box.\n Switching is one package rename; you keep every line of markup and every\n `<Subscribe>`, and you keep the store bridge from step 3. If your table\n works and Svelte 5 is all you need, this is the cheapest exit by a wide\n margin.\n2. **TanStack Table v9.** Its Svelte adapter declares a Svelte 5 peer range and\n its state shape is runes-first, so the bridge goes away. It is still\n headless: you write and maintain the `<table>`, the virtualizer, the filter\n UI and the editors yourself. The\n [TanStack migration guide](./migrating-from-tanstack-table.md) covers the\n vocabulary.\n3. **SvGrid.** A different trade: you delete the markup and take a renderer.\n The column definitions and the plugin list carry over; the `<table>`, the\n `<Subscribe>` blocks, the pager and the store bridge do not exist any more,\n because `<SvGrid>` renders all of that. The rest of this page is what that\n looks like on the fixture above.\n\nPick 1 if the markup is fine and the library being dead does not bother you.\nPick 2 if you want the markup and a maintained engine. Pick 3 if the markup is\nthe part you are tired of.\n\n## Step 4: the codemod\n\n`npx @svgrid/migrate` ports a svelte-headless-table component to SvGrid. It\npreviews by default and only writes with `--write`, and it says what it could\nnot map instead of dropping it. On the Svelte 4 original:\n\n<!-- captured: 05-codemod.txt -->\n```text\n warning A custom `cell` renderer was found. SvGrid renders cells with a snippet, not `createRender`, so this one needs porting by hand - it is preserved as a comment.\n warning The template still reads `pageIndex`, `pageCount`, `shown` from the view model, which is gone. <SvGrid> renders its own pager and row count (`pageable`, `showPagination`), so remove that markup, or read the grid through `onApiReady` if you need the numbers.\n warning The table markup dispatched `select` from a row; that handler went with the `<tr>`. Wire it to `onRowClick={({ row }) => ...}` (or `onCellClick`) on <SvGrid>, and turn the `createEventDispatcher` into a callback prop if the component is moving to runes.\n note Column resizing, keyboard navigation and ARIA grid semantics are built into <SvGrid>; the markup that provided them is intentionally gone.\n\n1 file(s) would change, with 3 warning(s).\nRe-run with --write to apply.\n```\n\nThree warnings, each naming a thing it left for you. Write it, swap the\npackages, and check:\n\n<!-- captured: 06-after-codemod.txt -->\n```text\n$ npm install @svgrid/grid@3.0.4 --legacy-peer-deps\n\nadded 1 package in <time>\n\n(exit 0)\n\n$ npm uninstall svelte-headless-table --legacy-peer-deps\n\nremoved 4 packages in <time>\n\n(exit 0)\n\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\n<lab>\\src\\PeopleTable.svelte:31:23\nError: `$pageIndex` is an illegal variable name. To reference a global variable called `$pageIndex`, use `globalThis.$pageIndex`\nhttps://svelte.dev/e/global_reference_invalid (svelte)\n```\n\n<!-- captured: 06-after-codemod.txt -->\n```text\nsvelte-check found 9 errors and 0 warnings in 1 file\n```\n\nAll nine are the pager `<p>` the second warning named, reading `shown`,\n`$pageIndex` and `$pageCount` from a view model that no longer exists. The\ncodemod does not delete markup outside the `<table>`, because it cannot know\nwhat else is in there; it tells you what will not compile. Delete the `<p>`\n(the grid draws its own pager), turn the `select` event into a callback prop\non `onRowClick` as the third warning says, and:\n\n<!-- captured: 07-hand-edits.txt -->\n```text\n$ npx svelte-check --tsconfig ./tsconfig.json --output human --threshold warning\nsvelte-check found 0 errors and 0 warnings\n```\n\n## What you end up with\n\nThe component after the codemod and the two hand edits:\n\n<!-- captured: PeopleTable.after.svelte -->\n```svelte\n<script lang=\"ts\">\n import { SvGrid, type GridColumns } from '@svgrid/grid'\n import type { Person } from './people'\n export let people: Person[] = []\n export let pageSize = 5\n export let onselect: (person: Person) => void = () => {}\n\n const columns: GridColumns<(typeof people)[number]> = [\n {\n header: 'Name',\n field: 'name',\n },\n {\n header: 'Department',\n field: 'department',\n },\n {\n header: 'City',\n field: 'city',\n },\n {\n header: 'Salary',\n field: 'salary',\n // TODO port: cell: ({ value }) => value.toLocaleString('en-US', { style: 'currency', currency: 'USD\n },\n ]\n</script>\n\n<SvGrid data={people} {columns} sortable filterable showColumnFilters pageable pageSize={pageSize}\n onRowClick={({ row }) => onselect(row)} />\n```\n\n83 lines became 31. The `TODO port:` comment is the one thing left to do by\nhand: the currency cell becomes `format: { type: 'currency', currency: 'USD' }`\non the column, and the comment goes. There is no store, no `$:`, no\n`<Subscribe>`, no `let:`, and nothing in the file that Svelte 5 has deprecated,\nso the same component moves to runes whenever you like with the official\nmigration script and nothing else to port.\n\n## What to read next\n\n- [Migrating from svelte-headless-table](./migrating-from-svelte-headless-table.md) -\n the plugin-by-plugin mapping and what the codemod will not do\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/) -\n the side-by-side, with a source and date for every claim\n- [Migrating from TanStack Table](./migrating-from-tanstack-table.md) - exit 2 in detail\n- [Migrating from the shadcn-svelte data table](./migrating-from-shadcn-data-table.md) -\n the same codemod on the TanStack-based recipe\n- [Why headless?](../why-headless.md) - if you want to keep your own markup\n on a maintained Svelte 5 engine, `@svgrid/grid/core` is that too\n\n## Frequently asked questions\n\n### Does svelte-headless-table work with Svelte 5?\n\nIn legacy mode, yes: the install prints a peer-dependency warning and the\nuntouched component type-checks clean, as the captures above show. What does\nnot work is moving a component that uses it to runes without maintaining a\nstore bridge yourself, and the library is not going to be updated for the\ndeprecations that bridge leans on.\n\n### Is the peer dependency conflict an error?\n\nOn npm 11 it is a warning and the install exits 0; on older npm it was an\n`ERESOLVE` error until you passed `--legacy-peer-deps`; pnpm warns. It never\nstops the code from running. It tells you the library was not built against\nthe Svelte you have.\n\n### Should I just use the maintained fork?\n\nIf your table works and all you need is Svelte 5, yes, and this page says so.\nThe fork keeps the same API, so you keep the same markup and the same store\nbridge. Move to SvGrid when the markup and the bridge are what you want gone.\n\n### How much of the port does the codemod do?\n\nThe column definitions, the plugin list and the `<table>` replacement, and it\nnames what it leaves: custom cell renderers, markup outside the table that read\nthe view model, and events the rows dispatched. On the fixture that was two\nhand edits and one `format` option.\n\n### Can I rerun this myself?\n\n`node tools/migration-lab/run.mjs` in the repo. It installs the pinned Svelte 4\ntoolchain into its own folder, upgrades it, runs the codemod from the checkout,\nand rewrites the captured files; the header of each one records the versions.\nBump the pins to try a newer Svelte.\n"
6451
6594
  },
6452
6595
  {
6453
6596
  "slug": "help/tailwind",
@@ -7441,7 +7584,7 @@ export const docs = [
7441
7584
  "path": "docs/help/web-components/enterprise.md",
7442
7585
  "title": "Enterprise features from the element",
7443
7586
  "section": "help/web-components",
7444
- "markdown": "# Enterprise features from the element\n\n`@svgrid/grid-wc` is MIT and complete on its own. The paid pack -\n[@svgrid/enterprise](https://svgrid.com/pricing/) - is a separate install, and\nmost of it works from a React, Vue or Angular host with no Svelte in your build.\n\nWhere the line falls is a packaging consequence, not a policy: four of the\nenterprise entry points are plain JavaScript, and the main entry pulls Svelte\ncomponents with it.\n\n## The spreadsheet as an element\n\nThe whole spreadsheet shell, ribbon and formula engine included, is its own\nelement: [`<sv-sheet>`](sv-sheet.md), from `@svgrid/enterprise/wc`, with\nReact and Vue wrappers beside it. It needs no `<sv-grid>` and no Svelte in\nthe host.\n\n## The api handle\n\nEverything here needs the grid's imperative api. The element parks it on itself\nonce the grid has mounted, and fires `apiready` at the same moment:\n\n```js\nconst grid = document.querySelector('sv-grid')\ngrid.addEventListener('apiready', () => {\n // grid.api is now the SvGridApi\n})\n```\n\nIn React the wrapper surfaces both:\n\n```tsx {nocheck}\nimport { useRef, useState } from 'react'\nimport { SvGrid, type SvGridHandle } from '@svgrid/grid-wc/react'\n\nconst ref = useRef<SvGridHandle>(null)\nconst [ready, setReady] = useState(false)\n\n<SvGrid ref={ref} data={rows} columns={columns} onApiReady={() => setReady(true)} />\n// ref.current.api - the same object `apiready` carries\n```\n\n## Works with no Svelte in your build\n\nThese four entry points are plain JavaScript. Import them from any bundler,\nincluding Angular's, and pass them the element's api.\n\n### Excel, PDF, HTML, CSV and TSV export\n\n```js\nimport { exportGrid } from '@svgrid/enterprise/export'\n\nawait exportGrid(grid.api, { format: 'xlsx', filename: 'orders' })\n```\n\n`format` takes `xlsx`, `pdf`, `html`, `csv` or `tsv`. Pass `download: false` to\nget the file back instead of saving it - useful for uploading or attaching it:\n\n```js\nconst { blob, filename, mime } = await exportGrid(grid.api, {\n format: 'pdf',\n download: false,\n})\n```\n\nCSV and TSV are already free in `@svgrid/grid`; `xlsx` and `pdf` are the paid\nformats.\n\n### Import\n\n```js\nimport { importData } from '@svgrid/enterprise/import'\n\nconst { rows, errors, total } = await importData(grid.api, {\n file, // a File, Blob, or inline CSV / TSV / JSON text\n format: 'auto', // sniffs xlsx vs text\n})\n```\n\n### Print\n\n```js\nimport { printGrid } from '@svgrid/enterprise/print'\n\nawait printGrid(grid.api, { title: 'Q3 orders', orientation: 'landscape' })\n```\n\n### Pivot model\n\n`createPivotModel` is a pure function - rows in, model out - so it needs no api\nat all, though the element's rows are the obvious input:\n\n```js\nimport { createPivotModel } from '@svgrid/enterprise/pivot'\n\nconst model = createPivotModel(grid.api.getData(), {\n rows: ['region'],\n cols: ['status'],\n values: [{ field: 'total', agg: 'sum' }],\n})\n```\n\nFeed `model.rows` and `model.columns` into a second, read-only `<sv-grid>`.\n\n## The license key\n\n```js\nimport { setLicenseKey } from '@svgrid/enterprise/license'\n\nsetLicenseKey('YOUR-LICENSE-KEY')\n```\n\nCall it once, before the first export. With **no** key nothing breaks: the paid\nfeatures still run, the grid shows a small watermark, and the console carries a\none-time notice.\n\nA key that is not your license key (a typo, a placeholder) behaves like no key:\nthe features run with the watermark, and the console warns once that the key is\nnot valid. Nothing throws.\n\n## Needs a Svelte-aware bundler\n\nThe main entry - `@svgrid/enterprise` - imports the pack's Svelte components, so\na host that cannot compile `.svelte` files cannot import it. With Vite plus\n[`@sveltejs/vite-plugin-svelte`](https://github.com/sveltejs/vite-plugin-svelte)\nit works, and three more things become available:\n\n```js\nimport { installEnterprise, enableBoardView, enableSchedulerView } from '@svgrid/enterprise'\n\ninstallEnterprise(grid.api) // adds api.exportData / importData / print / pivot / ai\nenableBoardView() // makes the element's `board` prop render a Kanban board\nenableSchedulerView() // makes its `scheduler` prop render a calendar\n```\n\n`installEnterprise` is a convenience: it hangs the same export, import, print\nand pivot functions off the api object rather than you importing them. The board\nand scheduler views are the part you cannot get any other way, because they are\nSvelte components rendered inside the element.\n\nAngular CLI builds have no Svelte compiler, so for Angular the four entry points\nabove are the whole of what is reachable.\n\n## Summary\n\n| Feature | Any bundler | Needs a Svelte-aware build |\n| --- | --- | --- |\n| xlsx / pdf / html / csv / tsv export | ✓ | |\n| Import (xlsx / csv / tsv / json) | ✓ | |\n| Print | ✓ | |\n| Pivot model | ✓ | |\n| License key | ✓ | |\n| `installEnterprise(api)` | | ✓ |\n| Kanban board view | | ✓ |\n| Scheduler / calendar view | | ✓ |\n\nSee also [limitations](./limitations.md) for what the element itself cannot do,\nregardless of licensing.\n"
7587
+ "markdown": "# Enterprise features from the element\n\n`@svgrid/grid-wc` is MIT and complete on its own. The paid pack -\n[@svgrid/enterprise](https://svgrid.com/pricing/) - is a separate install, and\nmost of it works from a React, Vue or Angular host with no Svelte in your build.\n\nWhere the line falls is a packaging consequence, not a policy: four of the\nenterprise entry points are plain JavaScript, and the main entry pulls Svelte\ncomponents with it.\n\n## The spreadsheet as an element\n\nThe whole spreadsheet shell, ribbon and formula engine included, is its own\nelement: [`<sv-sheet>`](sv-sheet.md), from `@svgrid/enterprise/wc`, with\nReact and Vue wrappers beside it. It needs no `<sv-grid>` and no Svelte in\nthe host.\n\nSvGrid Base is one too: [`<sv-base>`](sv-base.md), from\n`@svgrid/enterprise/wc/base`, takes the tables as a property and reports every\nchange as a `tableschange` event.\n\n## The api handle\n\nEverything here needs the grid's imperative api. The element parks it on itself\nonce the grid has mounted, and fires `apiready` at the same moment:\n\n```js\nconst grid = document.querySelector('sv-grid')\ngrid.addEventListener('apiready', () => {\n // grid.api is now the SvGridApi\n})\n```\n\nIn React the wrapper surfaces both:\n\n```tsx {nocheck}\nimport { useRef, useState } from 'react'\nimport { SvGrid, type SvGridHandle } from '@svgrid/grid-wc/react'\n\nconst ref = useRef<SvGridHandle>(null)\nconst [ready, setReady] = useState(false)\n\n<SvGrid ref={ref} data={rows} columns={columns} onApiReady={() => setReady(true)} />\n// ref.current.api - the same object `apiready` carries\n```\n\n## Works with no Svelte in your build\n\nThese four entry points are plain JavaScript. Import them from any bundler,\nincluding Angular's, and pass them the element's api.\n\n### Excel, PDF, HTML, CSV and TSV export\n\n```js\nimport { exportGrid } from '@svgrid/enterprise/export'\n\nawait exportGrid(grid.api, { format: 'xlsx', filename: 'orders' })\n```\n\n`format` takes `xlsx`, `pdf`, `html`, `csv` or `tsv`. Pass `download: false` to\nget the file back instead of saving it - useful for uploading or attaching it:\n\n```js\nconst { blob, filename, mime } = await exportGrid(grid.api, {\n format: 'pdf',\n download: false,\n})\n```\n\nCSV and TSV are already free in `@svgrid/grid`; `xlsx` and `pdf` are the paid\nformats.\n\n### Import\n\n```js\nimport { importData } from '@svgrid/enterprise/import'\n\nconst { rows, errors, total } = await importData(grid.api, {\n file, // a File, Blob, or inline CSV / TSV / JSON text\n format: 'auto', // sniffs xlsx vs text\n})\n```\n\n### Print\n\n```js\nimport { printGrid } from '@svgrid/enterprise/print'\n\nawait printGrid(grid.api, { title: 'Q3 orders', orientation: 'landscape' })\n```\n\n### Pivot model\n\n`createPivotModel` is a pure function - rows in, model out - so it needs no api\nat all, though the element's rows are the obvious input:\n\n```js\nimport { createPivotModel } from '@svgrid/enterprise/pivot'\n\nconst model = createPivotModel(grid.api.getData(), {\n rows: ['region'],\n cols: ['status'],\n values: [{ field: 'total', agg: 'sum' }],\n})\n```\n\nFeed `model.rows` and `model.columns` into a second, read-only `<sv-grid>`.\n\n## The license key\n\n```js\nimport { setLicenseKey } from '@svgrid/enterprise/license'\n\nsetLicenseKey('YOUR-LICENSE-KEY')\n```\n\nCall it once, before the first export. With **no** key nothing breaks: the paid\nfeatures still run, the grid shows a small watermark, and the console carries a\none-time notice.\n\nA key that is not your license key (a typo, a placeholder) behaves like no key:\nthe features run with the watermark, and the console warns once that the key is\nnot valid. Nothing throws.\n\n## Needs a Svelte-aware bundler\n\nThe main entry - `@svgrid/enterprise` - imports the pack's Svelte components, so\na host that cannot compile `.svelte` files cannot import it. With Vite plus\n[`@sveltejs/vite-plugin-svelte`](https://github.com/sveltejs/vite-plugin-svelte)\nit works, and three more things become available:\n\n```js\nimport { installEnterprise, enableBoardView, enableSchedulerView } from '@svgrid/enterprise'\n\ninstallEnterprise(grid.api) // adds api.exportData / importData / print / pivot / ai\nenableBoardView() // makes the element's `board` prop render a Kanban board\nenableSchedulerView() // makes its `scheduler` prop render a calendar\n```\n\n`installEnterprise` is a convenience: it hangs the same export, import, print\nand pivot functions off the api object rather than you importing them. The board\nand scheduler views are the part you cannot get any other way, because they are\nSvelte components rendered inside the element.\n\nAngular CLI builds have no Svelte compiler, so for Angular the four entry points\nabove are the whole of what is reachable.\n\n## Summary\n\n| Feature | Any bundler | Needs a Svelte-aware build |\n| --- | --- | --- |\n| xlsx / pdf / html / csv / tsv export | ✓ | |\n| Import (xlsx / csv / tsv / json) | ✓ | |\n| Print | ✓ | |\n| Pivot model | ✓ | |\n| License key | ✓ | |\n| `installEnterprise(api)` | | ✓ |\n| Kanban board view | | ✓ |\n| Scheduler / calendar view | | ✓ |\n\nSee also [limitations](./limitations.md) for what the element itself cannot do,\nregardless of licensing.\n"
7445
7588
  },
7446
7589
  {
7447
7590
  "slug": "help/web-components/frameworks",
@@ -7478,6 +7621,13 @@ export const docs = [
7478
7621
  "section": "help/web-components",
7479
7622
  "markdown": "# Shadow DOM: `<sv-grid-shadow>`\n\nTwo elements ship, and which one you want is a styling decision:\n\n| Element | Renders in | Page CSS | Use when |\n| --- | --- | --- | --- |\n| `<sv-grid>` | the light DOM | applies normally | Almost always - a data grid usually wants to inherit your app's theme. |\n| `<sv-grid-shadow>` | an open shadow root | **cannot reach the grid** | You are embedding in a page whose CSS you do not control, or shipping into someone else's site. |\n\nThey are two elements rather than one with a `shadow` attribute because Svelte's\n`customElement.shadow` is resolved when the component is COMPILED. No runtime\nflag can switch it, so no attribute can either.\n\n```html\n<script type=\"module\" src=\"https://unpkg.com/@svgrid/grid-wc/dist/shadow/sv-grid-shadow-element.js\"></script>\n\n<sv-grid-shadow id=\"grid\" sortable filterable style=\"display:block;height:420px\"></sv-grid-shadow>\n<script type=\"module\">\n const grid = document.getElementById('grid')\n grid.columns = [{ field: 'name', header: 'Name' }, { field: 'city', header: 'City' }]\n grid.data = [{ name: 'Ada', city: 'London' }, { name: 'Linus', city: 'Helsinki' }]\n</script>\n```\n\nEverything else is identical: the same 124 properties, the same 84 attributes,\nthe same 35 events. Events are dispatched `composed: true`, so\n`addEventListener` on the host works exactly as it does on `<sv-grid>`.\n\n\n## What the shadow root does and does not isolate\n\nTheming with `--sg-*` tokens, which reach into the shadow root by inheritance.\n\n<div data-docs-demo=\"10-custom-cells-and-themes\" data-height=\"500\"></div>\n\nThe root is **open**, never closed. A closed root leaves `el.shadowRoot` null,\nwhich would stop you styling, querying, or testing your own grid - so it is not\noffered.\n\nIsolation is one-directional, and worth being precise about:\n\n- **Page CSS cannot reach the grid.** A page rule like\n `table td { background: fuchsia }` hits `<sv-grid>` and stops at\n `<sv-grid-shadow>`'s boundary. That is the point of the element.\n- **The grid's CSS is still in your page.** About twenty overlay surfaces - the\n cell dropdown, the date picker, tooltips, toasts, modals - portal to\n `document.body` deliberately, so they escape every ancestor `overflow` and\n clip. Those land outside the shadow root, so the bundle injects its stylesheet\n into `document.head` as well as adopting it into the root. Every rule is\n scoped to an `.sv-grid-*` class, so it does not style your page, but it is\n present in it.\n- **Styles arrive with the code that needs them.** The entry carries the\n grid's own sheet; a lazy chunk (the chart, the date pickers, the menus)\n carries the styles of the components inside it and adds them to the page\n and to every open root when it loads. A page that never charts never\n downloads the chart's styles.\n\n## Theming\n\n`--sg-*` tokens work in both elements, unchanged:\n\n```css\nsv-grid, sv-grid-shadow {\n --sg-bg: #fff;\n --sg-header-bg: #f8fafc;\n}\n```\n\nA theme stylesheet works too, including its dark variant, even though its\nselectors are `:root` and `:root[data-theme='dark']` and neither can MATCH\ninside a shadow tree. Custom properties are *inherited* properties, and\ninheritance crosses a shadow boundary - so the values land on the host and are\ninherited by everything in the root. Verified in a browser rather than reasoned\nabout: it was assumed to be broken for a while, and it is not.\n\n\n## Constraints\n\nSelection, clipboard and the menus that portal out of the root - all identical inside a shadow tree.\n\n<div data-docs-demo=\"04-selection-copy-paste\" data-height=\"460\"></div>\n\n- **The root is resolved on mount.** Moving a live `<sv-grid-shadow>` into a\n different document needs a fresh element, not a reparent.\n- **Do not give the host a `transform`, `filter`, or `contain`.** Any of those\n makes it a containing block for fixed positioning, and the grid's menus -\n which are `position: fixed` - would anchor to the host instead of the\n viewport.\n- **Closed roots are unsupported**, for the reason above.\n\n\n## See also\n\n- [Quick start](./quick-start.md)\n- [`<sv-grid>` reference](./sv-grid.md)\n- [Limitations](./limitations.md)\n"
7480
7623
  },
7624
+ {
7625
+ "slug": "help/web-components/sv-base",
7626
+ "path": "docs/help/web-components/sv-base.md",
7627
+ "title": "<sv-base>: SvGrid Base as a custom element",
7628
+ "section": "help/web-components",
7629
+ "markdown": "\n# `<sv-base>`: SvGrid Base as a custom element\n\n[SvGrid Base](../base/start.md), tables with typed fields, linked records,\nviews, forms and automations, as one custom element for a page or a host with\nno Svelte in its build: React, Vue, Angular, or a plain `<script>` tag. It is\npart of `@svgrid/enterprise` (Suite edition): without a key it runs and shows\nthe pack's watermark and notice, as every entry does.\n\nThe element wraps `<SvBase>` and calls `enableBase()` itself.\n\n## Loading it\n\n```html\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@svgrid/enterprise/dist/wc/sv-base-element.js\"></script>\n\n<sv-base id=\"base\" height=\"480\" editable sortable show-row-numbers column-adder field-menu></sv-base>\n<script type=\"module\">\n const base = document.getElementById('base')\n base.users = [{ id: 'u1', name: 'Ana Ruiz' }, { id: 'u2', name: 'Ben Okafor' }]\n base.currentUser = base.users[0]\n base.tables = [\n {\n id: 'tasks', name: 'Tasks', primaryField: 'title',\n columns: [\n { field: 'title', header: 'Task', fieldType: 'text' },\n { field: 'owner', header: 'Owner', fieldType: 'user' },\n { field: 'due', header: 'Due', fieldType: 'date' },\n ],\n data: [{ id: 't1', title: 'Draft the launch post', owner: 'u1', due: '2026-11-04' }],\n },\n ]\n base.addEventListener('tableschange', (e) => save(e.detail)) // the whole list, after every change\n</script>\n```\n\nFrom npm, `import '@svgrid/enterprise/wc/base'` registers the element. The\ntables take the same shape as `<SvBase tables>`: see\n[the field types](../fields.md) and [linked records](../base/linked-records.md).\n\nRegistering is guarded: a page that loads the file twice (the CDN copy beside\nan npm build, or one file under two URLs) keeps the first definition instead\nof throwing on the second.\n\n## The license key\n\n```html\n<sv-base license-key=\"YOUR-LICENSE-KEY\"></sv-base>\n```\n\nThe file carries its own copy of the pack, so `setLicenseKey()` imported from\n`@svgrid/enterprise/license` sets the key of a different copy and the element\nkeeps its watermark. Pass the key to the element instead. The attribute is read\nbefore the first render, so the watermark never shows; a key assigned later as\na property (`base.licenseKey = key`) takes the watermark and the notice down.\n\n## Attributes vs properties\n\nThe [same rule as the grid element](sv-grid.md#attributes-vs-properties):\nprimitives are attributes, arrays and objects are properties.\n\n| Attribute | Property | Type |\n| --- | --- | --- |\n| `height` | `height` | pixels (`480`) or a CSS length (`100%`). Default 560. |\n| `container-height` | `containerHeight` | the same as `height`, under `<SvBase>`'s name |\n| `active-table` | `activeTable` | the id of the table shown first |\n| `active-view` | `activeView` | the id of the view shown first (one table) |\n| `primary-field` | `primaryField` | the field that names a record (one table) |\n| `editable` | `editable` | `boolean` |\n| `sortable` | `sortable` | `boolean` |\n| `show-row-numbers` | `showRowNumbers` | `boolean` |\n| `column-adder` | `columnAdder` | `boolean`: the \"+\" that adds a field |\n| `field-menu` | `fieldMenu` | `boolean`: the header menu that edits, hides and deletes a field |\n| `expand-rows` | `expandRows` | `boolean`: the button on each row that opens the record |\n| `row-height` | `rowHeight` | `number` |\n| `license-key` | `licenseKey` | `string` |\n\n| Property only | Type |\n| --- | --- |\n| `tables` | `BaseTable[]`: several tables, shown as tabs |\n| `data`, `columns`, `views` | one table, without tabs |\n| `viewTypes` | the view types the view bar offers |\n| `users` | the people user fields choose from (`setFieldUsers`) |\n| `currentUser` | who is signed in: what \"created by\" and \"last modified by\" write (`setCurrentUser`) |\n| `options` | any other `<SvBase>` or `<SvGrid>` prop, passed through as is |\n\nA boolean attribute is on when present, whatever its value: `editable=\"false\"`\nis editable. Remove the attribute, or set the property to `false`.\n\n`users` and `currentUser` are one list for the page, as they are in a Svelte\napp: two elements that set different lists share the last one set.\n\n## Events\n\n| Event | `detail` |\n| --- | --- |\n| `tableschange` | the whole `tables` list, after an edit, a record added or deleted, a field, a view, an automation or a table changed |\n| `viewschange` | the views of the one table (without `tables`; with it, a view change is a `tableschange`) |\n| `remotechange` | changes made in the database by someone else, for tables with a realtime `source` |\n| `ready` | `{ api }`, when the shown table's grid mounts. It fires again when another tab is opened. |\n\n`ready` parks the api on the element (`base.api`) and `tableschange` parks the\nlist (`base.tables`), so code that runs later reads them without having caught\nthe event.\n\n**Assigning `tables` loads it.** The element is upgraded the moment its file\nloads, which on a plain page is before the script that sets its properties, so\nthe first `base.tables = [...]` arrives after an empty mount and is shown in its\nplace. A later assignment of a new list replaces what is on screen, edits\nincluded, which is what reloading from a server wants. Handing back the list\n`tableschange` gave you, or `base.tables` itself, is not a reload.\n\nWith `data` and `columns` instead of `tables`, the grid writes edits into the\nrow objects of `data` and no `tableschange` fires; use `tables` with one table\nwhen the app needs to hear about every edit.\n\n## React and Vue\n\nBoth wrappers register the element on import and hand every prop over as a DOM\nproperty, so `tables` arrives as the array it is, also in React 18, which\nwould otherwise write it to an attribute as a string. Events become `onX`\ncallbacks in React and `@x` listeners in Vue.\n\n```tsx\nimport { useRef } from 'react'\nimport { SvBase, type SvBaseHandle } from '@svgrid/enterprise/wc/base/react'\n\nexport function Projects({ tables, save }) {\n const base = useRef<SvBaseHandle>(null)\n return (\n <SvBase ref={base} tables={tables} editable height={560}\n onTableschange={(next) => save(next)} />\n )\n}\n```\n\n```vue\n<script setup>\nimport { SvBase } from '@svgrid/enterprise/wc/base/vue'\ndefineProps(['tables'])\nconst emit = defineEmits(['save'])\n</script>\n\n<template>\n <SvBase :tables=\"tables\" editable :height=\"560\" @tableschange=\"(next) => emit('save', next)\" />\n</template>\n```\n\nThe ref's `element` is the `<sv-base>` itself, and `element.api` is the shown\ngrid's api.\n\n## Styling\n\n`<sv-base>` renders in the light DOM, like `<sv-grid>` and `<sv-sheet>`, so the\n`--sg-*` theme tokens set on the page or on the element reach it, and its dialogs, menus and toasts portal to `document.body`. The element\ndraws the toaster that automation notices and save errors show in; with several\n`<sv-base>` elements on a page, only the first one draws it.\n\n## What it does not carry\n\nSvelte snippets cannot cross the custom-element boundary, so `<SvBase>` props\nthat take one (a custom cell, a custom header) are not reachable. Custom field\ntypes registered with `registerFieldType` are registered in the element's own\ncopy of the pack, which the page cannot import, so only the built-in field\ntypes are available.\n\n## See also\n\n- [Demo 714](https://svgrid.com/demos/714-base-web-component/), the element\n driven from plain DOM code with an event log.\n- [SvGrid Base](../base/start.md), the component behind the element.\n- [`<sv-sheet>`](sv-sheet.md), the spreadsheet as an element.\n"
7630
+ },
7481
7631
  {
7482
7632
  "slug": "help/web-components/sv-chart",
7483
7633
  "path": "docs/help/web-components/sv-chart.md",
@@ -7497,7 +7647,7 @@ export const docs = [
7497
7647
  "path": "docs/help/web-components/sv-sheet.md",
7498
7648
  "title": "<sv-sheet>: the spreadsheet as a custom element",
7499
7649
  "section": "Spreadsheet",
7500
- "markdown": "\n# `<sv-sheet>`: the spreadsheet as a custom element\n\nThe spreadsheet shell of `@svgrid/enterprise`, ribbon and formula engine\nincluded, as one custom element for a page or a host with no Svelte in its\nbuild: React, Vue, Angular, or a plain `<script>` tag. It is part of the\npaid pack, with its 30-day evaluation period: without a key it runs and\ndisplays the pack's watermark and console message, as every entry does.\n\n**The reference below is generated** from `<SvSheet>`'s own `Props` type by\n`packages/enterprise/scripts/generate-sheet-surface.mjs`, the same way the\n[`<sv-grid>`](sv-grid.md) and [`<sv-chart>`](sv-chart.md) references are,\nand the package's tests fail if it drifts.\n\n## Loading it\n\n```html\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@svgrid/enterprise/dist/wc/sv-sheet-element.js\"></script>\n\n<sv-sheet id=\"sheet\" height=\"480\" rows=\"30\" columns=\"10\"></sv-sheet>\n<script type=\"module\">\n const sheet = document.getElementById('sheet')\n sheet.data = [{ name: 'Budget', cells: [['Item', 'Amount'], ['Rent', '1200'], ['Total', '=SUM(B2:B2)']] }]\n sheet.addEventListener('ready', () => console.log(sheet.getState()))\n sheet.addEventListener('change', (e) => console.log(e.detail)) // the reasons, once per tick\n sheet.addEventListener('action', (e) => {\n if (e.detail.action === 'file-save-xlsx') { e.preventDefault(); upload(sheet.toXlsx()) }\n })\n</script>\n```\n\nFrom npm, `import '@svgrid/enterprise/wc'` registers the element. The React\nand Vue wrappers are `@svgrid/enterprise/wc/react` and\n`@svgrid/enterprise/wc/vue`; Angular uses the element directly with\n`CUSTOM_ELEMENTS_SCHEMA`, the way the [Angular page](angular.md) shows for\n`<sv-grid>` before its wrapper existed.\n\nSave As and Open need `jszip`, an optional peer the element loads on demand.\nA page that uses them names it in an import map:\n\n```html\n<script type=\"importmap\">{ \"imports\": { \"jszip\": \"https://cdn.jsdelivr.net/npm/jszip@3/+esm\" } }</script>\n```\n\n## Attributes vs properties\n\nThe [same rule as the grid element](sv-grid.md#attributes-vs-properties):\nprimitives are attributes, arrays, objects and functions are properties.\n`data`, `workbook`, `document`, `formats`, `columnWidths`, `extras` and\n`localization` are properties; `height` takes a number or `\"100%\"`, so it\nkeeps a string attribute.\n\nA document built with `createSheetDocument` from `@svgrid/enterprise` is\nassigned as `sheet.document`; `ready` hands the api and the document back\nand parks both on the element (`sheet.api`, `sheet.document`), so a listener\nbound after the mount still reaches them.\n\n**Content assigned after the element is on the page is taken up.** A custom\nelement is upgraded the moment its definition loads, which on a plain page\nis before the script that sets its properties runs, so `sheet.data = [...]`\nin the quick start above arrives after the shell has already mounted on an\nempty sheet. The element remounts on it. That happens only while nothing has\nbeen done to the sheet: once a cell has been written, a later `data`,\n`workbook` or `document` is ignored rather than throwing the work away,\nwhich is what a React render passing a fresh array does on every parent\nupdate. To load content over a sheet that has been edited, call\n`setState(state)` or `newWorkbook()`.\n\n## Events and methods\n\nEvery callback of the component is an event with the callback's argument\nas `detail`. `action` is the one whose answer matters: a listener that calls\n`event.preventDefault()` has taken the action over, and the shell's own\ndialog stays closed, which is what returning `true` from `onAction` does.\n\nThe component's methods are on the element: `getState()`, `setState(state)`,\n`refresh()`, `act(action)`, `open(file)`, `toXlsx()`, `toCsv()`,\n`newWorkbook()`, `print()` and `printHtml()`.\n\n```js\nsheet.act('sort-asc')\nconst state = sheet.getState()\nlocalStorage.setItem('budget', JSON.stringify(state))\n```\n\n## React and Vue\n\n```tsx {nocheck}\nimport { useRef } from 'react'\nimport { SvSheet, type SvSheetHandle } from '@svgrid/enterprise/wc/react'\n\nconst ref = useRef<SvSheetHandle>(null)\n\n<SvSheet ref={ref} data={sheets} height={480}\n onAction={(detail, e) => { if (detail.action === 'file-print') { e.preventDefault(); printMyWay() } }}\n onChange={(reasons) => save(ref.current?.element?.getState())} />\n```\n\n```vue {nocheck}\n<script setup>\nimport { SvSheet } from '@svgrid/enterprise/wc/vue'\n</script>\n\n<SvSheet :data=\"sheets\" :height=\"480\" @change=\"save\" @ready=\"({ api }) => (grid = api)\" />\n```\n\nThe React wrapper assigns object props as properties (React 18 and earlier\nstringify them onto attributes) and binds the handlers once; the Vue wrapper\nforwards every prop with the `.prop` modifier. Both expose the element, with\nits methods, through the ref.\n\n<!-- BEGIN generated reference - packages/enterprise/scripts/generate-sheet-surface.mjs -->\n\n### Attributes (11)\n\nPrimitives, so they work in plain HTML as well as through a property.\n\n| Attribute | Property | Type |\n| --- | --- | --- |\n| `rows` | `rows` | `number` |\n| `columns` | `columns` | `number` |\n| `height` | `height` | `number \\| '100%'` |\n| `column-width` | `columnWidth` | `number` |\n| `row-height` | `rowHeight` | `number` |\n| `look` | `look` | `'excel' \\| 'theme'` |\n| `comment-author` | `commentAuthor` | `string` |\n| `show-ribbon` | `showRibbon` | `boolean` |\n| `show-formula-bar` | `showFormulaBar` | `boolean` |\n| `show-tabs` | `showTabs` | `boolean` |\n| `show-status-bar` | `showStatusBar` | `boolean` |\n\n### Properties only (9)\n\nArrays, objects and functions. An HTML attribute is a string, so these can\nonly be assigned in script: `el.document = doc`.\n\n| Property | Type |\n| --- | --- |\n| `document` | `SheetDocument` |\n| `workbook` | `Workbook` |\n| `data` | `ReadonlyArray<SheetData>` |\n| `gridSheets` | `Record<string, GridSheetSpec>` |\n| `columnWidths` | `Readonly<Record<string, number>>` |\n| `formats` | `Readonly<Record<string, CellFormatEntry>>` |\n| `extras` | `ReadonlyArray<'insert-table' \\| 'insert-chart'>` |\n| `localization` | `SheetLocalization` |\n| `presence` | `ReadonlyArray<SheetPresence>` |\n\n### Events (5)\n\n`detail` is the callback's argument, or an object keyed by the parameter names\nwhen it takes more than one. `action` is cancelable: `event.preventDefault()`\ntakes the action over, as returning `true` from `onAction` does.\n\n| Event | From | `detail` |\n| --- | --- | --- |\n| `action` | `onAction` | `{ action, cmd }` |\n| `cellaction` | `onCellAction` | `event` |\n| `ready` | `onReady` | `{ api, document }` |\n| `change` | `onChange` | `reasons` |\n| `presence` | `onPresence` | `me` |\n\n### Methods (12)\n\nThe component's own, on the element once `ready` has fired.\n\n| Method | What it does |\n| --- | --- |\n| `getState(): SheetState` | The document as plain JSON. |\n| `setState(state: SheetState): void` | Put a saved document back. |\n| `refresh(): void` | Repaint after a write the shell could not see. |\n| `act(action: RibbonActionId): void` | Run a ribbon action as if its button had been clicked. |\n| `open(file: Blob & { name?: string }): Promise<void>` | Replace the document with an .xlsx, .ods or .csv file. |\n| `toXlsx(): Promise<Blob>` | The document as an .xlsx Blob. |\n| `toOds(): Promise<Blob>` | The document as an .ods Blob, which LibreOffice Calc opens. |\n| `toXls(): Blob` | The document as an .xls Blob, which Excel 97-2003 opens. |\n| `toCsv(): string` | The active sheet as CSV. |\n| `newWorkbook(): void` | Start over with one empty sheet. |\n| `print(): void` | The active sheet in the print dialog. |\n| `printHtml(): string` | The page File > Print would open. |\n\n<!-- END generated reference -->\n\n## What it does not carry\n\nSvelte snippets cannot cross the custom-element boundary, and `<SvSheet>`\nhas none in its props, so nothing is left out. What the element cannot do\nis what the component cannot: see [the shell page](../cells/spreadsheet-shell.md#what-it-does-not-do).\n\n## See also\n\n- [The spreadsheet shell](../cells/spreadsheet-shell.md), the component\n behind the element: its ribbon, dialogs, document and files.\n- [Enterprise features from the element](enterprise.md), for the export,\n import, print and pivot entries that work beside `<sv-grid>`.\n"
7650
+ "markdown": "\n# `<sv-sheet>`: the spreadsheet as a custom element\n\nThe spreadsheet shell of `@svgrid/enterprise`, ribbon and formula engine\nincluded, as one custom element for a page or a host with no Svelte in its\nbuild: React, Vue, Angular, or a plain `<script>` tag. It is part of the\npaid pack, with its 30-day evaluation period: without a key it runs and\ndisplays the pack's watermark and console message, as every entry does.\n\n**The reference below is generated** from `<SvSheet>`'s own `Props` type by\n`packages/enterprise/scripts/generate-sheet-surface.mjs`, the same way the\n[`<sv-grid>`](sv-grid.md) and [`<sv-chart>`](sv-chart.md) references are,\nand the package's tests fail if it drifts.\n\n## Loading it\n\n```html\n<script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@svgrid/enterprise/dist/wc/sv-sheet-element.js\"></script>\n\n<sv-sheet id=\"sheet\" height=\"480\" rows=\"30\" columns=\"10\"></sv-sheet>\n<script type=\"module\">\n const sheet = document.getElementById('sheet')\n sheet.data = [{ name: 'Budget', cells: [['Item', 'Amount'], ['Rent', '1200'], ['Total', '=SUM(B2:B2)']] }]\n sheet.addEventListener('ready', () => console.log(sheet.getState()))\n sheet.addEventListener('change', (e) => console.log(e.detail)) // the reasons, once per tick\n sheet.addEventListener('action', (e) => {\n if (e.detail.action === 'file-save-xlsx') { e.preventDefault(); upload(sheet.toXlsx()) }\n })\n</script>\n```\n\nFrom npm, `import '@svgrid/enterprise/wc'` registers the element. The React\nand Vue wrappers are `@svgrid/enterprise/wc/react` and\n`@svgrid/enterprise/wc/vue`; Angular uses the element directly with\n`CUSTOM_ELEMENTS_SCHEMA`, the way the [Angular page](angular.md) shows for\n`<sv-grid>` before its wrapper existed.\n\nSave As and Open need `jszip`, an optional peer the element loads on demand.\nA page that uses them names it in an import map:\n\n```html\n<script type=\"importmap\">{ \"imports\": { \"jszip\": \"https://cdn.jsdelivr.net/npm/jszip@3/+esm\" } }</script>\n```\n\n## The license key\n\n```html\n<sv-sheet license-key=\"YOUR-LICENSE-KEY\"></sv-sheet>\n```\n\nThe file carries its own copy of the pack, so `setLicenseKey()` imported from\n`@svgrid/enterprise/license` sets the key of a different copy and the element\nkeeps its watermark. Pass the key to the element instead. The attribute is read\nbefore the first render, so the watermark never shows; a key assigned later as\na property (`sheet.licenseKey = key`) takes the watermark and the notice down.\n`licenseKey` is the one element prop `<SvSheet>` itself does not have.\n\n## Attributes vs properties\n\nThe [same rule as the grid element](sv-grid.md#attributes-vs-properties):\nprimitives are attributes, arrays, objects and functions are properties.\n`data`, `workbook`, `document`, `formats`, `columnWidths`, `extras` and\n`localization` are properties; `height` takes a number or `\"100%\"`, so it\nkeeps a string attribute.\n\nA document built with `createSheetDocument` from `@svgrid/enterprise` is\nassigned as `sheet.document`; `ready` hands the api and the document back\nand parks both on the element (`sheet.api`, `sheet.document`), so a listener\nbound after the mount still reaches them.\n\n**Content assigned after the element is on the page is taken up.** A custom\nelement is upgraded the moment its definition loads, which on a plain page\nis before the script that sets its properties runs, so `sheet.data = [...]`\nin the quick start above arrives after the shell has already mounted on an\nempty sheet. The element remounts on it. That happens only while nothing has\nbeen done to the sheet: once a cell has been written, a later `data`,\n`workbook` or `document` is ignored rather than throwing the work away,\nwhich is what a React render passing a fresh array does on every parent\nupdate. To load content over a sheet that has been edited, call\n`setState(state)` or `newWorkbook()`.\n\n## Events and methods\n\nEvery callback of the component is an event with the callback's argument\nas `detail`. `action` is the one whose answer matters: a listener that calls\n`event.preventDefault()` has taken the action over, and the shell's own\ndialog stays closed, which is what returning `true` from `onAction` does.\n\nThe component's methods are on the element: `getState()`, `setState(state)`,\n`refresh()`, `act(action)`, `open(file)`, `toXlsx()`, `toCsv()`,\n`newWorkbook()`, `print()` and `printHtml()`.\n\n```js\nsheet.act('sort-asc')\nconst state = sheet.getState()\nlocalStorage.setItem('budget', JSON.stringify(state))\n```\n\n## React and Vue\n\n```tsx {nocheck}\nimport { useRef } from 'react'\nimport { SvSheet, type SvSheetHandle } from '@svgrid/enterprise/wc/react'\n\nconst ref = useRef<SvSheetHandle>(null)\n\n<SvSheet ref={ref} data={sheets} height={480}\n onAction={(detail, e) => { if (detail.action === 'file-print') { e.preventDefault(); printMyWay() } }}\n onChange={(reasons) => save(ref.current?.element?.getState())} />\n```\n\n```vue {nocheck}\n<script setup>\nimport { SvSheet } from '@svgrid/enterprise/wc/vue'\n</script>\n\n<SvSheet :data=\"sheets\" :height=\"480\" @change=\"save\" @ready=\"({ api }) => (grid = api)\" />\n```\n\nThe React wrapper assigns object props as properties (React 18 and earlier\nstringify them onto attributes) and binds the handlers once; the Vue wrapper\nforwards every prop with the `.prop` modifier. Both expose the element, with\nits methods, through the ref.\n\n<!-- BEGIN generated reference - packages/enterprise/scripts/generate-sheet-surface.mjs -->\n\n### Attributes (12)\n\nPrimitives, so they work in plain HTML as well as through a property.\n\n| Attribute | Property | Type |\n| --- | --- | --- |\n| `rows` | `rows` | `number` |\n| `columns` | `columns` | `number` |\n| `height` | `height` | `number \\| '100%'` |\n| `column-width` | `columnWidth` | `number` |\n| `row-height` | `rowHeight` | `number` |\n| `look` | `look` | `'excel' \\| 'theme'` |\n| `comment-author` | `commentAuthor` | `string` |\n| `show-ribbon` | `showRibbon` | `boolean` |\n| `show-formula-bar` | `showFormulaBar` | `boolean` |\n| `show-tabs` | `showTabs` | `boolean` |\n| `show-status-bar` | `showStatusBar` | `boolean` |\n| `license-key` | `licenseKey` | `string` |\n\n### Properties only (9)\n\nArrays, objects and functions. An HTML attribute is a string, so these can\nonly be assigned in script: `el.document = doc`.\n\n| Property | Type |\n| --- | --- |\n| `document` | `SheetDocument` |\n| `workbook` | `Workbook` |\n| `data` | `ReadonlyArray<SheetData>` |\n| `gridSheets` | `Record<string, GridSheetSpec>` |\n| `columnWidths` | `Readonly<Record<string, number>>` |\n| `formats` | `Readonly<Record<string, CellFormatEntry>>` |\n| `extras` | `ReadonlyArray<'insert-table' \\| 'insert-chart'>` |\n| `localization` | `SheetLocalization` |\n| `presence` | `ReadonlyArray<SheetPresence>` |\n\n### Events (5)\n\n`detail` is the callback's argument, or an object keyed by the parameter names\nwhen it takes more than one. `action` is cancelable: `event.preventDefault()`\ntakes the action over, as returning `true` from `onAction` does.\n\n| Event | From | `detail` |\n| --- | --- | --- |\n| `action` | `onAction` | `{ action, cmd }` |\n| `cellaction` | `onCellAction` | `event` |\n| `ready` | `onReady` | `{ api, document }` |\n| `change` | `onChange` | `reasons` |\n| `presence` | `onPresence` | `me` |\n\n### Methods (12)\n\nThe component's own, on the element once `ready` has fired.\n\n| Method | What it does |\n| --- | --- |\n| `getState(): SheetState` | The document as plain JSON. |\n| `setState(state: SheetState): void` | Put a saved document back. |\n| `refresh(): void` | Repaint after a write the shell could not see. |\n| `act(action: RibbonActionId): void` | Run a ribbon action as if its button had been clicked. |\n| `open(file: Blob & { name?: string }): Promise<void>` | Replace the document with an .xlsx, .ods or .csv file. |\n| `toXlsx(): Promise<Blob>` | The document as an .xlsx Blob. |\n| `toOds(): Promise<Blob>` | The document as an .ods Blob, which LibreOffice Calc opens. |\n| `toXls(): Blob` | The document as an .xls Blob, which Excel 97-2003 opens. |\n| `toCsv(): string` | The active sheet as CSV. |\n| `newWorkbook(): void` | Start over with one empty sheet. |\n| `print(): void` | The active sheet in the print dialog. |\n| `printHtml(): string` | The page File > Print would open. |\n\n<!-- END generated reference -->\n\n## What it does not carry\n\nSvelte snippets cannot cross the custom-element boundary, and `<SvSheet>`\nhas none in its props, so nothing is left out. What the element cannot do\nis what the component cannot: see [the shell page](../cells/spreadsheet-shell.md#what-it-does-not-do).\n\n## See also\n\n- [The spreadsheet shell](../cells/spreadsheet-shell.md), the component\n behind the element: its ribbon, dialogs, document and files.\n- [Enterprise features from the element](enterprise.md), for the export,\n import, print and pivot entries that work beside `<sv-grid>`.\n"
7501
7651
  },
7502
7652
  {
7503
7653
  "slug": "help/web-components/typescript",
@@ -8414,7 +8564,7 @@ export const docs = [
8414
8564
  "path": "docs/_data/comparisons/ag-grid.json",
8415
8565
  "title": "SvGrid vs AG Grid (community + enterprise)",
8416
8566
  "section": "Comparisons",
8417
- "markdown": "# SvGrid vs AG Grid (community + enterprise)\n\nCanonical URL: https://svgrid.com/compare/ag-grid/\nFacts verified: 2026-09-12\nCompetitor package: ag-grid-community\nCompetitor site: https://www.ag-grid.com/\n\nAG Grid is the most widely used JavaScript data grid, sold for React, Angular, Vue and plain JavaScript, with Svelte covered only by community-built integrations.\n\n## Verdict\n\nAG Grid has the longer track record and the wider Enterprise catalogue; SvGrid is Svelte-5-native, smaller on a Svelte page, and puts most of what AG Grid sells as Enterprise into its MIT core. Pick AG Grid for parity with React and Angular teams; pick SvGrid for a Svelte-first stack.\n\nMigration guide: moving from AG Grid (community + enterprise) to SvGrid: https://svgrid.com/docs/help/migrating-from-ag-grid/\n\n## At a glance\n\n| Fact | SvGrid | AG Grid (community + enterprise) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 36.1.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 5 Aug 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript, React, Angular, Vue) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 12,400,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 317.5 KB JS, no separate stylesheet | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript, React, Angular, Vue | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; ag-grid-community 36.1.0 entry `createGrid + AllCommunityModule + themeQuartz` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nAG Grid is the heavyweight of the category: a Community edition under MIT and an Enterprise edition sold per developer that adds the set filter, range selection, master/detail, tree data, row grouping, pivoting, integrated charts, Excel export and the server-side row model. Its own pages mark each of those as Enterprise, and the sources at the bottom of this page link to them.\n\nFor Svelte there is no official package. ag-grid.com names React, Angular, Vue and JavaScript and points Svelte users to community-built integrations, so in practice you call the JavaScript API from onMount and manage the DOM yourself. SvGrid is the inverse: a Svelte 5 component with runes and snippets, and a headless core underneath it.\n\n## Looking for an AG Grid alternative for Svelte?\n\nThe usual reason to look is that AG Grid on Svelte means the JavaScript API inside onMount plus a wrapper you do not control. SvGrid gives you a component that speaks runes natively and an MIT core with no row cap and no licence key. What you give up is breadth: AG Grid has more Enterprise modules, more integrations and a far larger body of examples, and if you need one grid across three frameworks it is still the right answer.\n\n## What they have in common\n\n- A full grid with sorting, filtering, grouping, virtualization, editing and selection.\n- Documentation with a runnable example per feature.\n- TypeScript-first APIs with an imperative grid API for code outside the component.\n- An MIT core plus a paid tier with support.\n- An official MCP server so AI assistants read the real docs instead of guessing.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native: runes for state, snippets for cells, no wrapper layer and no DOM imperatives.\n- A smaller bundle on a Svelte page; the At a glance table above carries both measured numbers and the method.\n- Set-style Excel filters, cell-range selection with clipboard, master/detail, tree data, row grouping with aggregation, integrated charts, the column tool panel and the context menu are in the MIT core. AG Grid lists each of these under Enterprise. Flat server-side data (paging, infinite block scroll) is free in both; the server-side row model with lazy grouping, tree, pivot, transactions and selection across unloaded rows is a paid module in both.\n- In-grid AI helpers (natural-language filter, smart fill, summarise, classify, anomalies) ship free in @svgrid/grid with your own model provider.\n- @svgrid/mcp validates props and imports against the real API surface and scaffolds a project, on top of docs and examples.\n- @svgrid/enterprise costs $599 per developer per year for the enterprise grid, unlimited applications; AG Grid Enterprise's per-developer price is in the pricing line above.\n\n## Where AG Grid (community + enterprise) is stronger\n\n- A longer production record across very large enterprise deployments, and the largest body of third-party examples and answers of any grid.\n- The viewport row model, where the server pushes the visible window over a socket; SvGrid has no equivalent.\n- AG Charts, a separately licensed charting product with far more chart types than SvGridChart.\n- One grid API across React, Angular and Vue teams.\n- Enterprise support through Zendesk with one year of updates on the licence.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | AG Grid (community + enterprise) |\n| --- | --- | --- |\n| Svelte 5 native | Yes - runes and snippets | No - JavaScript build; Svelte is pointed to community-built integrations |\n| Sorting and filtering | Yes | Yes |\n| Excel-style set filter | Yes - MIT core | Paid tier - the Set Filter page is marked Enterprise |\n| Row and column virtualization | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Cell-range selection and clipboard | Yes - MIT core, with a fill handle | Paid tier - Range Selection and Clipboard are Enterprise |\n| Master/detail | Yes - MIT core | Paid tier - Enterprise |\n| Tree data | Yes - MIT core | Paid tier - the Tree Data page is marked Enterprise |\n| Row grouping with aggregation | Yes - MIT core | Paid tier - Enterprise |\n| Pivot tables | Paid tier - @svgrid/enterprise | Paid tier - Enterprise |\n| Integrated charts | Yes - SvGridChart in the MIT core | Paid tier - Enterprise, through AG Charts |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - MIT core: createServerDataSource, page or infinite block scroll | Yes - Infinite Row Model, Community |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise: createServerRowModel | Paid tier - Server-Side Row Model, Enterprise |\n| Global search over server-side data | Yes - filterModel.global goes to the server | No - the Quick Filter is not supported by the Infinite or Server-Side row models |\n| Viewport row model (server pushes the visible window) | No - not built; real-time deltas merge into loaded rows instead | Paid tier - Viewport Row Model, Enterprise |\n| CSV export | Yes - MIT core | Yes - Community, through the API |\n| Excel export | Paid tier - @svgrid/enterprise | Paid tier - Enterprise |\n| Column tool panel | Yes - MIT core | Paid tier - Tool Panels are Enterprise |\n| Context menu | Yes - MIT core | Paid tier - Enterprise |\n| MCP server for AI assistants | Yes - @svgrid/mcp, MIT: docs, examples, code check, scaffold, preview | Yes - ag-mcp, MIT: docs search, version detection, upgrade prompts |\n| In-grid AI helpers (natural-language filter, smart fill) | Yes - MIT core, bring your own model | No - not in the feature list |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | Yes - Enterprise licence, Zendesk |\n| Core licence | Yes - MIT | Yes - MIT (Community) |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, ag-grid-community 36.1.0. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | AG Grid (community + enterprise) |\n| --- | --- | --- |\n| Mount | 30.7 ms | 67 ms |\n| Sort, text column | 77.4 ms | 213.9 ms |\n| Sort, numeric column | 32.8 ms | 216.7 ms |\n| Filter, one column (indicative only) | 34.5 ms | 148.8 ms |\n| Scroll, p95 frame | 34.3 ms | 34.5 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 259.2 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 36 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid shaped by Svelte idioms rather than a wrapper around a JavaScript build.\n- You want the set filter, master/detail, tree data, range selection, grouping and flat server-side infinite scroll without an Enterprise licence.\n- You want a paid support tier priced per developer per year at $599.\n- You want an assistant that can check the code it writes against the real API, not only read the docs.\n\n## When to choose AG Grid (community + enterprise)\n\n- You depend on a specific AG Grid Enterprise module, the viewport row model or server-side pivoting.\n- You run the same grid across React, Angular and Vue teams and want one library.\n- Your procurement already covers AG Grid Enterprise, or you need AG Charts.\n- You want the largest possible pool of existing examples, answers and contractors.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- AG Charts as a separately licensed charting product with far more chart types than SvGridChart.\n- The viewport row model; SvGrid's server-side row model covers sort, filter, grouping, tree, pivot, transactions and select-all across unloaded rows, but the server cannot push the visible window.\n- One grid API across React, Angular and Vue teams.\n- The largest body of third-party examples, Stack Overflow answers and contractors of any grid.\n\nMigration guide: moving from AG Grid (community + enterprise) to SvGrid: https://svgrid.com/docs/help/migrating-from-ag-grid/\n\n## Live example\n\nMigration From Ag Grid: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/139-migration-from-ag-grid/\n\n## The bottom line\n\nAG Grid is the safer pick for a multi-framework organisation, or when you need its deepest Enterprise modules, AG Charts or the viewport row model. For a Svelte-first team, SvGrid covers the Enterprise surface most teams actually buy AG Grid for, in the MIT core: master/detail, tree data, range selection, grouping, flat server-side infinite scroll and integrated charts, with pivot tables, the server-side row model and Excel, PDF and print output in the @svgrid/enterprise pack. The bundle and benchmark numbers on this page are measured on the dates shown, so read them rather than either vendor's adjectives.\n\n## Frequently asked questions\n\n### Does AG Grid support Svelte?\n\nNot with an official package. ag-grid.com names React, Angular, Vue and JavaScript, and points Svelte, Solid and Python users to community-built integrations. In practice you create the grid from the JavaScript API inside onMount and keep its state in sync with your Svelte state by hand.\n\n### Which AG Grid Enterprise features does SvGrid include in its MIT core?\n\nThe set-style Excel filter, cell-range selection with clipboard, master/detail, tree data, row grouping with aggregation, integrated charts, the column tool panel and the context menu. AG Grid's own pages list each of these under Enterprise. Pivot tables, the server-side row model (grouping, tree, pivot, transactions, selection) and Excel, PDF and print output are in @svgrid/enterprise, as they are in AG Grid Enterprise; flat server-side infinite scroll is free in both.\n\n### What does SvGrid not have that AG Grid Enterprise has?\n\nThe viewport row model, AG Charts as a full charting product, and the breadth of niche Enterprise modules that come from a decade of enterprise customers. SvGrid's server-side row model handles sort, filter, grouping, tree, pivot, transactions and selection across unloaded rows; if your requirement is the viewport model, AG Grid Enterprise is the better fit.\n\n### Does AG Grid have an MCP server too?\n\nYes. ag-mcp (MIT) gives an assistant AG Grid's docs, examples and version-specific upgrade prompts. @svgrid/mcp covers the same ground for SvGrid and adds a code checker that validates props and imports against the real API surface, a scaffold tool and a preview. Neither is an in-grid feature; SvGrid's natural-language filter, smart fill and summarise helpers are, and they ship free in @svgrid/grid with your own model provider.\n\n### How much does AG Grid Enterprise cost compared with SvGrid?\n\nAG Grid Enterprise is sold per developer with one year of updates; the price as ag-grid.com listed it on the date we read it is in the pricing line at the top of this page. SvGrid's core is MIT and @svgrid/enterprise is $599 per developer per year for the enterprise grid or $999 with the spreadsheet and Studio, both for unlimited applications. Compare what each paid tier adds before comparing prices: most of what AG Grid sells as Enterprise is in SvGrid's free core.\n\n### How long does a migration from AG Grid to SvGrid take?\n\nThe migration guide budgets one to three hours per grid. Column definitions map almost one to one, the imperative API has equivalents on SvGridApi, and most of the time goes into moving cell renderers to snippets. The guide also lists what does not map, so you can decide before you start.\n\n### Is SvGrid a good AG Grid alternative for Svelte?\n\nThe usual reason to look is that AG Grid on Svelte means the JavaScript API inside onMount plus a wrapper you do not control. SvGrid gives you a component that speaks runes natively and an MIT core with no row cap and no licence key. What you give up is breadth: AG Grid has more Enterprise modules, more integrations and a far larger body of examples, and if you need one grid across three frameworks it is still the right answer.\n\n## Related comparisons and docs\n\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Performance benchmarks](https://svgrid.com/docs/help/benchmarks/)\n- [Server-side data](https://svgrid.com/docs/help/server-side-data/)\n- [MCP server](https://svgrid.com/docs/help/mcp-server/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- ag-pricing: Enterprise is per developer at $999 USD with one year of updates and Zendesk support; the Enterprise Bundle is $1,498 USD; Community is free under MIT (checked 12 Sep 2026) https://www.ag-grid.com/license-pricing/\n- ag-community-vs-enterprise: Lists Range Selection, Clipboard, Master/Detail, Row Grouping, Pivot Tables and Aggregations, Integrated Charts, Excel export, Server-Side Row Model, Tool Panels and Context Menu under Enterprise Features; no AI feature in either list (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/community-vs-enterprise/\n- ag-set-filter: The Set Filter page is marked enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/filter-set/\n- ag-tree-data: The Tree Data page is marked enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/tree-data/\n- ag-csv-export: CSV export is available in Community through the API; the context-menu export and Excel export are Enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/csv-export/\n- ag-mcp: Official MCP server installed with npx ag-mcp: search_docs, detect_version, set_version and list_versions tools, quick-start and upgrade-grid prompts, docs and examples as resources; described as help for integrating and maintaining grid code, not an in-grid feature. The ag-mcp package on npm is MIT (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/mcp-server/\n- ag-home: Names React, Angular, Vue and JavaScript; says Svelte, Solid and Python users can use community-built integrations; the 36.1.0 release notes list an AI Coding Skill (checked 12 Sep 2026) https://www.ag-grid.com/\n- ag-row-models: The row-models feature table lists the Infinite Row Model as Community and the Server-Side and Viewport row models as Enterprise; the Quick Filter row is marked unsupported for the Infinite, Server-Side and Viewport models (checked 15 Sep 2026) https://www.ag-grid.com/javascript-data-grid/row-models/\n"
8567
+ "markdown": "# SvGrid vs AG Grid (community + enterprise)\n\nCanonical URL: https://svgrid.com/compare/ag-grid/\nFacts verified: 2026-09-12\nCompetitor package: ag-grid-community\nCompetitor site: https://www.ag-grid.com/\n\nAG Grid is the most widely used JavaScript data grid, sold for React, Angular, Vue and plain JavaScript, with Svelte covered only by community-built integrations.\n\n## Verdict\n\nAG Grid has the longer track record and the wider Enterprise catalogue; SvGrid is Svelte-5-native, smaller on a Svelte page, and puts most of what AG Grid sells as Enterprise into its MIT core. Pick AG Grid for parity with React and Angular teams; pick SvGrid for a Svelte-first stack.\n\nMigration guide: moving from AG Grid (community + enterprise) to SvGrid: https://svgrid.com/docs/help/migrating-from-ag-grid/\n\n## At a glance\n\n| Fact | SvGrid | AG Grid (community + enterprise) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 36.1.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 5 Aug 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript, React, Angular, Vue) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 12,400,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 317.5 KB JS, no separate stylesheet | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript, React, Angular, Vue | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | AG Grid Community is free under MIT. AG Grid Enterprise is listed at $999 USD per developer with one year of updates and Zendesk support; the Enterprise Bundle with AG Charts Enterprise is $1,498 USD per developer | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; ag-grid-community 36.1.0 entry `createGrid + AllCommunityModule + themeQuartz` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nAG Grid is the heavyweight of the category: a Community edition under MIT and an Enterprise edition sold per developer that adds the set filter, range selection, master/detail, tree data, row grouping, pivoting, integrated charts, Excel export and the server-side row model. Its own pages mark each of those as Enterprise, and the sources at the bottom of this page link to them.\n\nFor Svelte there is no official package. ag-grid.com names React, Angular, Vue and JavaScript and points Svelte users to community-built integrations, so in practice you call the JavaScript API from onMount and manage the DOM yourself. SvGrid is the inverse: a Svelte 5 component with runes and snippets, and a headless core underneath it.\n\n## Looking for an AG Grid alternative for Svelte?\n\nThe usual reason to look is that AG Grid on Svelte means the JavaScript API inside onMount plus a wrapper you do not control. SvGrid gives you a component that speaks runes natively and an MIT core with no row cap and no licence key. What you give up is breadth: AG Grid has more Enterprise modules, more integrations and a far larger body of examples, and if you need one grid across three frameworks it is still the right answer.\n\n## What they have in common\n\n- A full grid with sorting, filtering, grouping, virtualization, editing and selection.\n- Documentation with a runnable example per feature.\n- TypeScript-first APIs with an imperative grid API for code outside the component.\n- An MIT core plus a paid tier with support.\n- An official MCP server so AI assistants read the real docs instead of guessing.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native: runes for state, snippets for cells, no wrapper layer and no DOM imperatives.\n- A smaller bundle on a Svelte page; the At a glance table above carries both measured numbers and the method.\n- Set-style Excel filters, cell-range selection with clipboard, master/detail, tree data, row grouping with aggregation, integrated charts, the column tool panel and the context menu are in the MIT core. AG Grid lists each of these under Enterprise. Flat server-side data (paging, infinite block scroll) is free in both; the server-side row model with lazy grouping, tree, pivot, transactions and selection across unloaded rows is a paid module in both.\n- In-grid AI helpers (natural-language filter, smart fill, summarise, classify, anomalies) ship free in @svgrid/grid with your own model provider.\n- @svgrid/mcp validates props and imports against the real API surface and scaffolds a project, on top of docs and examples.\n- @svgrid/enterprise costs $599 per developer per year for the enterprise grid, unlimited applications; AG Grid Enterprise's per-developer price is in the pricing line above.\n\n## Where AG Grid (community + enterprise) is stronger\n\n- A longer production record across very large enterprise deployments, and the largest body of third-party examples and answers of any grid.\n- The viewport row model, where the server pushes the visible window over a socket; SvGrid has no equivalent.\n- AG Charts, a separately licensed charting product with far more chart types than SvGridChart.\n- One grid API across React, Angular and Vue teams.\n- Enterprise support through Zendesk with one year of updates on the licence.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | AG Grid (community + enterprise) |\n| --- | --- | --- |\n| Svelte 5 native | Yes - runes and snippets | No - JavaScript build; Svelte is pointed to community-built integrations |\n| Sorting and filtering | Yes | Yes |\n| Excel-style set filter | Yes - MIT core | Paid tier - the Set Filter page is marked Enterprise |\n| Row and column virtualization | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Cell-range selection and clipboard | Yes - MIT core, with a fill handle | Paid tier - Range Selection and Clipboard are Enterprise |\n| Master/detail | Yes - MIT core | Paid tier - Enterprise |\n| Tree data | Yes - MIT core | Paid tier - the Tree Data page is marked Enterprise |\n| Row grouping with aggregation | Yes - MIT core | Paid tier - Enterprise |\n| Pivot tables | Paid tier - @svgrid/enterprise | Paid tier - Enterprise |\n| Integrated charts | Yes - SvGridChart in the MIT core | Paid tier - Enterprise, through AG Charts |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - MIT core: createServerDataSource, page or infinite block scroll | Yes - Infinite Row Model, Community |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise: createServerRowModel | Paid tier - Server-Side Row Model, Enterprise |\n| Global search over server-side data | Yes - filterModel.global goes to the server | No - the Quick Filter is not supported by the Infinite or Server-Side row models |\n| Viewport row model (server pushes the visible window) | No - not built; real-time deltas merge into loaded rows instead | Paid tier - Viewport Row Model, Enterprise |\n| CSV export | Yes - MIT core | Yes - Community, through the API |\n| Excel export | Paid tier - @svgrid/enterprise | Paid tier - Enterprise |\n| Column tool panel | Yes - MIT core | Paid tier - Tool Panels are Enterprise |\n| Context menu | Yes - MIT core | Paid tier - Enterprise |\n| MCP server for AI assistants | Yes - @svgrid/mcp, MIT: docs, examples, code check, scaffold, preview | Yes - ag-mcp, MIT: docs search, version detection, upgrade prompts |\n| In-grid AI helpers (natural-language filter, smart fill) | Yes - MIT core, bring your own model | No - not in the feature list |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | Yes - Enterprise licence, Zendesk |\n| Core licence | Yes - MIT | Yes - MIT (Community) |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, ag-grid-community 36.1.0. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | AG Grid (community + enterprise) |\n| --- | --- | --- |\n| Mount | 30.7 ms | 67 ms |\n| Sort, text column | 77.4 ms | 213.9 ms |\n| Sort, numeric column | 32.8 ms | 216.7 ms |\n| Filter, one column (indicative only) | 34.5 ms | 148.8 ms |\n| Scroll, p95 frame | 34.3 ms | 34.5 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 259.2 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 36 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid shaped by Svelte idioms rather than a wrapper around a JavaScript build.\n- You want the set filter, master/detail, tree data, range selection, grouping and flat server-side infinite scroll without an Enterprise licence.\n- You want a paid support tier priced per developer per year at $599.\n- You want an assistant that can check the code it writes against the real API, not only read the docs.\n\n## When to choose AG Grid (community + enterprise)\n\n- You depend on a specific AG Grid Enterprise module, the viewport row model or server-side pivoting.\n- You run the same grid across React, Angular and Vue teams and want one library.\n- Your procurement already covers AG Grid Enterprise, or you need AG Charts.\n- You want the largest possible pool of existing examples, answers and contractors.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- AG Charts as a separately licensed charting product with far more chart types than SvGridChart.\n- The viewport row model; SvGrid's server-side row model covers sort, filter, grouping, tree, pivot, transactions and select-all across unloaded rows, but the server cannot push the visible window.\n- One grid API across React, Angular and Vue teams.\n- The largest body of third-party examples, Stack Overflow answers and contractors of any grid.\n\nMigration guide: moving from AG Grid (community + enterprise) to SvGrid: https://svgrid.com/docs/help/migrating-from-ag-grid/\n\n## Live example\n\nMigration From Ag Grid: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/139-migration-from-ag-grid/\n\n## The bottom line\n\nAG Grid is the safer pick for a multi-framework organisation, or when you need its deepest Enterprise modules, AG Charts or the viewport row model. For a Svelte-first team, SvGrid covers the Enterprise surface most teams actually buy AG Grid for, in the MIT core: master/detail, tree data, range selection, grouping, flat server-side infinite scroll and integrated charts, with pivot tables, the server-side row model and Excel, PDF and print output in the @svgrid/enterprise pack. The bundle and benchmark numbers on this page are measured on the dates shown, so read them rather than either vendor's adjectives.\n\n## Frequently asked questions\n\n### Does AG Grid support Svelte?\n\nNot with an official package. ag-grid.com names React, Angular, Vue and JavaScript, and points Svelte, Solid and Python users to community-built integrations. In practice you create the grid from the JavaScript API inside onMount and keep its state in sync with your Svelte state by hand.\n\n### Which AG Grid Enterprise features does SvGrid include in its MIT core?\n\nThe set-style Excel filter, cell-range selection with clipboard, master/detail, tree data, row grouping with aggregation, integrated charts, the column tool panel and the context menu. AG Grid's own pages list each of these under Enterprise. Pivot tables, the server-side row model (grouping, tree, pivot, transactions, selection) and Excel, PDF and print output are in @svgrid/enterprise, as they are in AG Grid Enterprise; flat server-side infinite scroll is free in both.\n\n### What does SvGrid not have that AG Grid Enterprise has?\n\nThe viewport row model, AG Charts as a full charting product, and the breadth of niche Enterprise modules that come from a decade of enterprise customers. SvGrid's server-side row model handles sort, filter, grouping, tree, pivot, transactions and selection across unloaded rows; if your requirement is the viewport model, AG Grid Enterprise is the better fit.\n\n### Does AG Grid have an MCP server too?\n\nYes. ag-mcp (MIT) gives an assistant AG Grid's docs, examples and version-specific upgrade prompts. @svgrid/mcp covers the same ground for SvGrid and adds a code checker that validates props and imports against the real API surface, a scaffold tool and a preview. Neither is an in-grid feature; SvGrid's natural-language filter, smart fill and summarise helpers are, and they ship free in @svgrid/grid with your own model provider.\n\n### How much does AG Grid Enterprise cost compared with SvGrid?\n\nAG Grid Enterprise is sold per developer with one year of updates; the price as ag-grid.com listed it on the date we read it is in the pricing line at the top of this page. SvGrid's core is MIT and @svgrid/enterprise is $599 per developer per year for the enterprise grid or $999 with the spreadsheet and Studio, both for unlimited applications. Compare what each paid tier adds before comparing prices: most of what AG Grid sells as Enterprise is in SvGrid's free core.\n\n### How long does a migration from AG Grid to SvGrid take?\n\nThe migration guide budgets one to three hours per grid. Column definitions map almost one to one, the imperative API has equivalents on SvGridApi, and most of the time goes into moving cell renderers to snippets. The guide also lists what does not map, so you can decide before you start.\n\n### Is SvGrid a good AG Grid alternative for Svelte?\n\nThe usual reason to look is that AG Grid on Svelte means the JavaScript API inside onMount plus a wrapper you do not control. SvGrid gives you a component that speaks runes natively and an MIT core with no row cap and no licence key. What you give up is breadth: AG Grid has more Enterprise modules, more integrations and a far larger body of examples, and if you need one grid across three frameworks it is still the right answer.\n\n## Related comparisons and docs\n\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs Handsontable](https://svgrid.com/compare/handsontable/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Performance benchmarks](https://svgrid.com/docs/help/benchmarks/)\n- [Server-side data](https://svgrid.com/docs/help/server-side-data/)\n- [MCP server](https://svgrid.com/docs/help/mcp-server/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- ag-pricing: Enterprise is per developer at $999 USD with one year of updates and Zendesk support; the Enterprise Bundle is $1,498 USD; Community is free under MIT (checked 12 Sep 2026) https://www.ag-grid.com/license-pricing/\n- ag-community-vs-enterprise: Lists Range Selection, Clipboard, Master/Detail, Row Grouping, Pivot Tables and Aggregations, Integrated Charts, Excel export, Server-Side Row Model, Tool Panels and Context Menu under Enterprise Features; no AI feature in either list (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/community-vs-enterprise/\n- ag-set-filter: The Set Filter page is marked enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/filter-set/\n- ag-tree-data: The Tree Data page is marked enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/tree-data/\n- ag-csv-export: CSV export is available in Community through the API; the context-menu export and Excel export are Enterprise (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/csv-export/\n- ag-mcp: Official MCP server installed with npx ag-mcp: search_docs, detect_version, set_version and list_versions tools, quick-start and upgrade-grid prompts, docs and examples as resources; described as help for integrating and maintaining grid code, not an in-grid feature. The ag-mcp package on npm is MIT (checked 12 Sep 2026) https://www.ag-grid.com/javascript-data-grid/mcp-server/\n- ag-home: Names React, Angular, Vue and JavaScript; says Svelte, Solid and Python users can use community-built integrations; the 36.1.0 release notes list an AI Coding Skill (checked 12 Sep 2026) https://www.ag-grid.com/\n- ag-row-models: The row-models feature table lists the Infinite Row Model as Community and the Server-Side and Viewport row models as Enterprise; the Quick Filter row is marked unsupported for the Infinite, Server-Side and Viewport models (checked 15 Sep 2026) https://www.ag-grid.com/javascript-data-grid/row-models/\n"
8418
8568
  },
8419
8569
  {
8420
8570
  "slug": "compare/airtable",
@@ -8442,14 +8592,14 @@ export const docs = [
8442
8592
  "path": "docs/_data/comparisons/glide-data-grid.json",
8443
8593
  "title": "SvGrid vs Glide Data Grid",
8444
8594
  "section": "Comparisons",
8445
- "markdown": "# SvGrid vs Glide Data Grid\n\nCanonical URL: https://svgrid.com/compare/glide-data-grid/\nFacts verified: 2026-09-12\nCompetitor package: @glideapps/glide-data-grid\nCompetitor site: https://grid.glideapps.com/\n\nGlide Data Grid is a canvas-rendered React data grid built for extreme scroll performance on very large datasets.\n\n## Verdict\n\nGlide wins on raw canvas FPS for hundreds of thousands of visible cells. SvGrid renders accessible, selectable DOM with virtualization and is Svelte-5-native - the right call for most apps.\n\nMigration guide: moving from Glide Data Grid to SvGrid: https://svgrid.com/docs/help/migrating-from-glide/\n\n## At a glance\n\n| Fact | SvGrid | Glide Data Grid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.0.3 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Feb 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 1,180,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 71.1 KB JS + 0.2 KB CSS, lodash + marked + react + react-dom + react-responsive-carousel external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Glide Data Grid is MIT and, in its own words, fully free and open source; no licence is sold for the grid | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; @glideapps/glide-data-grid 6.0.3 entry `DataEditor component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nGlide Data Grid renders to a <canvas> instead of DOM, which gives it exceptional performance on very wide, very tall datasets at the cost of standard HTML semantics. It is React-only and MIT-licensed.\n\nSvGrid renders virtualized DOM: real table semantics, WAI-ARIA roles, keyboard navigation, and selectable / indexable text. For the vast majority of apps the performance gap is invisible, and you keep accessibility and SEO-friendly markup.\n\n## Looking for a Glide Data Grid alternative for Svelte?\n\nGlide renders to canvas, which is why it is fast and also why text selection, accessibility and custom cells work differently there. SvGrid renders real DOM with virtualization, so a screen reader and browser find behave normally and a cell can be any Svelte snippet. If your bar is a million-row canvas scroll inside React, Glide is still the specialist.\n\n## What they have in common\n\n- MIT-licensed.\n- Virtualized rendering for large datasets.\n- Cell editing and custom cell content.\n- TypeScript-first.\n\n## Where SvGrid is stronger\n\n- Renders real DOM - WAI-ARIA, keyboard nav, screen-reader support, selectable text.\n- Svelte 5 native rather than React-only.\n- Excel-style filter menu, headless engine, and the imperative API out of the box.\n- @svgrid/mcp MCP server for AI assistants.\n\n## Where Glide Data Grid is stronger\n\n- Peak canvas rendering performance on hundreds of thousands of visible cells.\n- Per-pixel custom cell drawing.\n- Proven inside Glide's own product at scale.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Glide Data Grid |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - React only |\n| Rendering | Yes - Accessible DOM | Partial - canvas |\n| WAI-ARIA + keyboard | Yes | Partial - Limited (canvas) |\n| Selectable / indexable text | Yes | No - Canvas pixels |\n| Peak FPS on 200k+ visible cells | Partial - Good | Yes - Best |\n| Virtualization | Yes | Yes |\n| Excel-style filters | Yes | No - BYO |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need accessibility, keyboard support, or selectable text.\n- You are on Svelte 5 and want a native grid.\n- You want filters, editing, and an imperative API without building them.\n\n## When to choose Glide Data Grid\n\n- You have measured a need for peak canvas FPS on 200k+ simultaneously visible cells.\n- You require per-pixel custom cell drawing.\n- Your app is React and accessibility is not a requirement.\n\n## Migration effort\n\nEstimated effort: 3-6 hours per grid.\n\nWhat you give up:\n\n- Canvas rendering throughput on very wide, very dense sheets.\n- The React ecosystem around it, including Glide Data Editor.\n\nMigration guide: moving from Glide Data Grid to SvGrid: https://svgrid.com/docs/help/migrating-from-glide/\n\n## Live example\n\nHeadless Virtual: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/187-headless-virtual/\n\n## The bottom line\n\nGlide is the right tool when you have measured a need for canvas-level FPS on hundreds of thousands of visible cells. For everyone else - and especially when accessibility, selectable text, or Svelte matter - the virtualized DOM in SvGrid is the better default.\n\n## Frequently asked questions\n\n### SvGrid vs Glide Data Grid - which should I use?\n\nUse SvGrid unless you have a measured need for canvas rendering at extreme scale. SvGrid renders accessible DOM and is Svelte-native; Glide is React-only and canvas-based.\n\n### Is Glide faster than SvGrid?\n\nAt hundreds of thousands of simultaneously visible cells, canvas rendering gives Glide higher peak FPS. For typical datasets the difference is invisible, and SvGrid virtualizes comfortably to 100k+ rows.\n\n### Does SvGrid handle accessibility better than Glide?\n\nYes. SvGrid renders real DOM with WAI-ARIA roles, keyboard navigation, and selectable text; a canvas grid like Glide cannot offer those natively.\n\n### Is SvGrid a good Glide Data Grid alternative for Svelte?\n\nGlide renders to canvas, which is why it is fast and also why text selection, accessibility and custom cells work differently there. SvGrid renders real DOM with virtualization, so a screen reader and browser find behave normally and a cell can be any Svelte snippet. If your bar is a million-row canvas scroll inside React, Glide is still the specialist.\n\n## Related comparisons and docs\n\n- [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/)\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n- [Accessibility](https://svgrid.com/docs/help/accessibility/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- glide-site: MIT, fully free and open source; a React data grid that scales to millions of rows with lazy cell rendering and native scrolling (checked 12 Sep 2026) https://grid.glideapps.com/\n- glide-readme: README explains why the grid renders on an HTML canvas; supports React 16 and later (checked 12 Sep 2026) https://github.com/glideapps/glide-data-grid\n"
8595
+ "markdown": "# SvGrid vs Glide Data Grid\n\nCanonical URL: https://svgrid.com/compare/glide-data-grid/\nFacts verified: 2026-09-12\nCompetitor package: @glideapps/glide-data-grid\nCompetitor site: https://grid.glideapps.com/\n\nGlide Data Grid is a canvas-rendered React data grid built for extreme scroll performance on very large datasets.\n\n## Verdict\n\nGlide wins on raw canvas FPS for hundreds of thousands of visible cells. SvGrid renders accessible, selectable DOM with virtualization and is Svelte-5-native - the right call for most apps.\n\nMigration guide: moving from Glide Data Grid to SvGrid: https://svgrid.com/docs/help/migrating-from-glide/\n\n## At a glance\n\n| Fact | SvGrid | Glide Data Grid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.0.3 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Feb 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 1,180,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 71.1 KB JS + 0.2 KB CSS, lodash + marked + react + react-dom + react-responsive-carousel external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Glide Data Grid is MIT and, in its own words, fully free and open source; no licence is sold for the grid | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; @glideapps/glide-data-grid 6.0.3 entry `DataEditor component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nGlide Data Grid renders to a <canvas> instead of DOM, which gives it exceptional performance on very wide, very tall datasets at the cost of standard HTML semantics. It is React-only and MIT-licensed.\n\nSvGrid renders virtualized DOM: real table semantics, WAI-ARIA roles, keyboard navigation, and selectable / indexable text. For the vast majority of apps the performance gap is invisible, and you keep accessibility and SEO-friendly markup.\n\n## Looking for a Glide Data Grid alternative for Svelte?\n\nGlide renders to canvas, which is why it is fast and also why text selection, accessibility and custom cells work differently there. SvGrid renders real DOM with virtualization, so a screen reader and browser find behave normally and a cell can be any Svelte snippet. If your bar is a million-row canvas scroll inside React, Glide is still the specialist.\n\n## What they have in common\n\n- MIT-licensed.\n- Virtualized rendering for large datasets.\n- Cell editing and custom cell content.\n- TypeScript-first.\n\n## Where SvGrid is stronger\n\n- Renders real DOM - WAI-ARIA, keyboard nav, screen-reader support, selectable text.\n- Svelte 5 native rather than React-only.\n- Excel-style filter menu, headless engine, and the imperative API out of the box.\n- @svgrid/mcp MCP server for AI assistants.\n\n## Where Glide Data Grid is stronger\n\n- Peak canvas rendering performance on hundreds of thousands of visible cells.\n- Per-pixel custom cell drawing.\n- Proven inside Glide's own product at scale.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Glide Data Grid |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - React only |\n| Rendering | Yes - Accessible DOM | Partial - canvas |\n| WAI-ARIA + keyboard | Yes | Partial - Limited (canvas) |\n| Selectable / indexable text | Yes | No - Canvas pixels |\n| Peak FPS on 200k+ visible cells | Partial - Good | Yes - Best |\n| Virtualization | Yes | Yes |\n| Excel-style filters | Yes | No - BYO |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need accessibility, keyboard support, or selectable text.\n- You are on Svelte 5 and want a native grid.\n- You want filters, editing, and an imperative API without building them.\n\n## When to choose Glide Data Grid\n\n- You have measured a need for peak canvas FPS on 200k+ simultaneously visible cells.\n- You require per-pixel custom cell drawing.\n- Your app is React and accessibility is not a requirement.\n\n## Migration effort\n\nEstimated effort: 3-6 hours per grid.\n\nWhat you give up:\n\n- Canvas rendering throughput on very wide, very dense sheets.\n- The React ecosystem around it, including Glide Data Editor.\n\nMigration guide: moving from Glide Data Grid to SvGrid: https://svgrid.com/docs/help/migrating-from-glide/\n\n## Live example\n\nHeadless Virtual: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/187-headless-virtual/\n\n## The bottom line\n\nGlide is the right tool when you have measured a need for canvas-level FPS on hundreds of thousands of visible cells. For everyone else - and especially when accessibility, selectable text, or Svelte matter - the virtualized DOM in SvGrid is the better default.\n\n## Frequently asked questions\n\n### SvGrid vs Glide Data Grid - which should I use?\n\nUse SvGrid unless you have a measured need for canvas rendering at extreme scale. SvGrid renders accessible DOM and is Svelte-native; Glide is React-only and canvas-based.\n\n### Is Glide faster than SvGrid?\n\nAt hundreds of thousands of simultaneously visible cells, canvas rendering gives Glide higher peak FPS. For typical datasets the difference is invisible, and SvGrid virtualizes comfortably to 100k+ rows.\n\n### Does SvGrid handle accessibility better than Glide?\n\nYes. SvGrid renders real DOM with WAI-ARIA roles, keyboard navigation, and selectable text; a canvas grid like Glide cannot offer those natively.\n\n### Is SvGrid a good Glide Data Grid alternative for Svelte?\n\nGlide renders to canvas, which is why it is fast and also why text selection, accessibility and custom cells work differently there. SvGrid renders real DOM with virtualization, so a screen reader and browser find behave normally and a cell can be any Svelte snippet. If your bar is a million-row canvas scroll inside React, Glide is still the specialist.\n\n## Related comparisons and docs\n\n- [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/)\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n- [Accessibility](https://svgrid.com/docs/help/accessibility/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- glide-site: MIT, fully free and open source; a React data grid that scales to millions of rows with lazy cell rendering and native scrolling (checked 12 Sep 2026) https://grid.glideapps.com/\n- glide-readme: README explains why the grid renders on an HTML canvas; supports React 16 and later (checked 12 Sep 2026) https://github.com/glideapps/glide-data-grid\n"
8446
8596
  },
8447
8597
  {
8448
8598
  "slug": "compare/gridjs",
8449
8599
  "path": "docs/_data/comparisons/gridjs.json",
8450
8600
  "title": "SvGrid vs Grid.js",
8451
8601
  "section": "Comparisons",
8452
- "markdown": "# SvGrid vs Grid.js\n\nCanonical URL: https://svgrid.com/compare/gridjs/\nFacts verified: 2026-09-12\nCompetitor package: gridjs\nCompetitor site: https://gridjs.io/\n\nGrid.js is a small, elegant, framework-agnostic table library focused on the essentials, MIT-licensed.\n\n## Verdict\n\nGrid.js is a lovely lightweight pick for search / sort / paginate. SvGrid is the fuller, Svelte-native grid when you need virtualization, editing, grouping, or large datasets.\n\nMigration guide: moving from Grid.js to SvGrid: https://svgrid.com/docs/help/migrating-from-gridjs/\n\n## At a glance\n\n| Fact | SvGrid | Grid.js | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.2.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Mar 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 161,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 17.8 KB JS + 2.4 KB CSS | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Grid.js is MIT, free and open source; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; gridjs 6.2.0 entry `Grid` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nGrid.js keeps a deliberately small surface: search, sort, pagination, and basic server-side data, rendered through a tiny vanilla-JS core with framework wrappers. It is MIT-licensed and easy to learn.\n\nSvGrid trades that minimalism for depth: a Svelte-5-native render component with virtualization, an Excel-style filter menu, inline editing, grouping, tree data, and an imperative API.\n\n## Looking for a Grid.js alternative for Svelte?\n\nGrid.js is deliberately small and covers the essentials well. People outgrow it at the same points every time: virtualization for large datasets, inline editing, row grouping and server-side data. SvGrid has those, and keeps a headless core so a simple table does not have to carry the weight of the full component.\n\n## What they have in common\n\n- MIT-licensed.\n- Search, sort, and pagination out of the box.\n- Server-side data support.\n- Small, approachable API.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native instead of a vanilla core + wrapper.\n- Row + column virtualization for large datasets.\n- Excel-style filters, inline editing, grouping, tree, master/detail.\n- Headless engine + imperative API + @svgrid/mcp.\n\n## Where Grid.js is stronger\n\n- Tiny footprint if all you need is search / sort / paginate.\n- Framework-agnostic core.\n- Very fast to learn for a simple table.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Grid.js |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - vanilla JavaScript with React, Angular and Vue wrappers |\n| Search / sort / paginate | Yes | Yes |\n| Excel-style filters | Yes | No |\n| Inline editing | Yes | No |\n| Virtualization | Yes | No |\n| Grouping / tree / master-detail | Yes | No |\n| Footprint for a simple table | Partial - Larger | Yes - Tiny |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need virtualization, editing, grouping, or tree data.\n- You are on Svelte 5 and want a native component.\n- You expect the table to grow beyond search / sort / paginate.\n\n## When to choose Grid.js\n\n- You only need search / sort / paginate over a modest dataset.\n- You want the smallest possible footprint.\n- You want a framework-agnostic drop-in.\n\n## Migration effort\n\nEstimated effort: 30 minutes to 1 hour per table.\n\nWhat you give up:\n\n- A very small library for a simple table on any page.\n- Wrappers for React, Angular and Vue.\n\nMigration guide: moving from Grid.js to SvGrid: https://svgrid.com/docs/help/migrating-from-gridjs/\n\n## Live example\n\nExcel Filters: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/03-excel-filters/\n\n## The bottom line\n\nGrid.js is a lovely minimalist table for search, sort, and paginate. When you outgrow that - virtualization, editing, grouping, tree - SvGrid is the Svelte-native grid that already covers it.\n\n## Frequently asked questions\n\n### SvGrid vs Grid.js - which should I choose?\n\nGrid.js for a small table that only needs search, sort, and paginate; SvGrid when you need virtualization, editing, Excel-style filters, or grouping.\n\n### Is SvGrid heavier than Grid.js?\n\nYes, because it does much more. For a trivial table Grid.js is lighter; for a real data grid SvGrid pays for itself.\n\n### Does SvGrid support server-side data like Grid.js?\n\nYes - externalSort and externalFilter, plus the onSortingChange and onFiltersChange events.\n\n### Is SvGrid a good Grid.js alternative for Svelte?\n\nGrid.js is deliberately small and covers the essentials well. People outgrow it at the same points every time: virtualization for large datasets, inline editing, row grouping and server-side data. SvGrid has those, and keeps a headless core so a simple table does not have to carry the weight of the full component.\n\n## Related comparisons and docs\n\n- [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Getting started with SvGrid](https://svgrid.com/docs/getting-started/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- gridjs-site: Free and open source under MIT; works with React, Angular, Vue and vanilla JavaScript; an extensible data pipeline (checked 12 Sep 2026) https://gridjs.io/\n"
8602
+ "markdown": "# SvGrid vs Grid.js\n\nCanonical URL: https://svgrid.com/compare/gridjs/\nFacts verified: 2026-09-12\nCompetitor package: gridjs\nCompetitor site: https://gridjs.io/\n\nGrid.js is a small, elegant, framework-agnostic table library focused on the essentials, MIT-licensed.\n\n## Verdict\n\nGrid.js is a lovely lightweight pick for search / sort / paginate. SvGrid is the fuller, Svelte-native grid when you need virtualization, editing, grouping, or large datasets.\n\nMigration guide: moving from Grid.js to SvGrid: https://svgrid.com/docs/help/migrating-from-gridjs/\n\n## At a glance\n\n| Fact | SvGrid | Grid.js | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.2.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Mar 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 161,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 17.8 KB JS + 2.4 KB CSS | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Grid.js is MIT, free and open source; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; gridjs 6.2.0 entry `Grid` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nGrid.js keeps a deliberately small surface: search, sort, pagination, and basic server-side data, rendered through a tiny vanilla-JS core with framework wrappers. It is MIT-licensed and easy to learn.\n\nSvGrid trades that minimalism for depth: a Svelte-5-native render component with virtualization, an Excel-style filter menu, inline editing, grouping, tree data, and an imperative API.\n\n## Looking for a Grid.js alternative for Svelte?\n\nGrid.js is deliberately small and covers the essentials well. People outgrow it at the same points every time: virtualization for large datasets, inline editing, row grouping and server-side data. SvGrid has those, and keeps a headless core so a simple table does not have to carry the weight of the full component.\n\n## What they have in common\n\n- MIT-licensed.\n- Search, sort, and pagination out of the box.\n- Server-side data support.\n- Small, approachable API.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native instead of a vanilla core + wrapper.\n- Row + column virtualization for large datasets.\n- Excel-style filters, inline editing, grouping, tree, master/detail.\n- Headless engine + imperative API + @svgrid/mcp.\n\n## Where Grid.js is stronger\n\n- Tiny footprint if all you need is search / sort / paginate.\n- Framework-agnostic core.\n- Very fast to learn for a simple table.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Grid.js |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - vanilla JavaScript with React, Angular and Vue wrappers |\n| Search / sort / paginate | Yes | Yes |\n| Excel-style filters | Yes | No |\n| Inline editing | Yes | No |\n| Virtualization | Yes | No |\n| Grouping / tree / master-detail | Yes | No |\n| Footprint for a simple table | Partial - Larger | Yes - Tiny |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need virtualization, editing, grouping, or tree data.\n- You are on Svelte 5 and want a native component.\n- You expect the table to grow beyond search / sort / paginate.\n\n## When to choose Grid.js\n\n- You only need search / sort / paginate over a modest dataset.\n- You want the smallest possible footprint.\n- You want a framework-agnostic drop-in.\n\n## Migration effort\n\nEstimated effort: 30 minutes to 1 hour per table.\n\nWhat you give up:\n\n- A very small library for a simple table on any page.\n- Wrappers for React, Angular and Vue.\n\nMigration guide: moving from Grid.js to SvGrid: https://svgrid.com/docs/help/migrating-from-gridjs/\n\n## Live example\n\nExcel Filters: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/03-excel-filters/\n\n## The bottom line\n\nGrid.js is a lovely minimalist table for search, sort, and paginate. When you outgrow that - virtualization, editing, grouping, tree - SvGrid is the Svelte-native grid that already covers it.\n\n## Frequently asked questions\n\n### SvGrid vs Grid.js - which should I choose?\n\nGrid.js for a small table that only needs search, sort, and paginate; SvGrid when you need virtualization, editing, Excel-style filters, or grouping.\n\n### Is SvGrid heavier than Grid.js?\n\nYes, because it does much more. For a trivial table Grid.js is lighter; for a real data grid SvGrid pays for itself.\n\n### Does SvGrid support server-side data like Grid.js?\n\nYes - externalSort and externalFilter, plus the onSortingChange and onFiltersChange events.\n\n### Is SvGrid a good Grid.js alternative for Svelte?\n\nGrid.js is deliberately small and covers the essentials well. People outgrow it at the same points every time: virtualization for large datasets, inline editing, row grouping and server-side data. SvGrid has those, and keeps a headless core so a simple table does not have to carry the weight of the full component.\n\n## Related comparisons and docs\n\n- [SvGrid vs Tabulator](https://svgrid.com/compare/tabulator/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Getting started with SvGrid](https://svgrid.com/docs/getting-started/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- gridjs-site: Free and open source under MIT; works with React, Angular, Vue and vanilla JavaScript; an extensible data pipeline (checked 12 Sep 2026) https://gridjs.io/\n"
8453
8603
  },
8454
8604
  {
8455
8605
  "slug": "compare/handsontable",
@@ -8477,7 +8627,7 @@ export const docs = [
8477
8627
  "path": "docs/_data/comparisons/mui-x-datagrid.json",
8478
8628
  "title": "SvGrid vs MUI X DataGrid",
8479
8629
  "section": "Comparisons",
8480
- "markdown": "# SvGrid vs MUI X DataGrid\n\nCanonical URL: https://svgrid.com/compare/mui-x-datagrid/\nFacts verified: 2026-09-12\nCompetitor package: @mui/x-data-grid\nCompetitor site: https://mui.com/x/react-data-grid/\n\nMUI X DataGrid is the data grid of the Material UI ecosystem on React, split into a free Community tier and paid Pro and Premium tiers.\n\n## Verdict\n\nMUI X is the obvious pick if you are already on Material UI and React. SvGrid is Svelte-5-native, ships more in its MIT core (pinning, master/detail, tree data, grouping and cell selection are not Pro or Premium features), and carries no Material Design opinion.\n\nMigration guide: moving from MUI X DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-mui-x/\n\n## At a glance\n\n| Fact | SvGrid | MUI X DataGrid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 9.13.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 4 Sep 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 11,800,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 155.0 KB JS, no separate stylesheet, @emotion/react + @emotion/styled + @mui/material + @mui/system + react + react-dom external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | MUI X Community is free under MIT. mui.com lists Pro at $299 per year per developer, Premium at $599 per year per developer and Enterprise at $1,399 per year per developer, with perpetual and annual licence models | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; @mui/x-data-grid 9.13.0 entry `DataGrid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nMUI X DataGrid is what most React teams on Material UI reach for. The Community edition is MIT and covers sorting, filtering, pagination, CSV export and row virtualization. Column pinning, column virtualization, row reordering, tree data and master/detail are Pro; row grouping, aggregation, cell selection, Excel export, pivoting and the AI assistant are Premium. Both paid tiers are sold per developer per year, and the sources below link to the pages that mark each feature.\n\nSvGrid is the inverse trade: one Svelte-5-native grid whose MIT core already includes pinning, master/detail, tree data, grouping with aggregation, cell-range selection with a fill handle, integrated charts and in-grid AI helpers you point at your own model, plus an optional @svgrid/enterprise pack for Excel, PDF and print output, import and pivot tables.\n\n## Looking for a MUI X DataGrid alternative for Svelte?\n\nMUI X DataGrid is React-only, so this is less an alternative than a port. The concepts carry over almost one to one: column definitions, a free tier and a paid tier, server-side rows, an imperative API. What does not carry over is Material Design: SvGrid is themed through CSS custom properties, so you bring your own look, and Emotion and Material UI stay out of the bundle.\n\n## What they have in common\n\n- A Community / paid split with an MIT free tier.\n- Sorting, filtering, pagination, virtualization and inline editing.\n- Server-side data through a row model the app feeds.\n- TypeScript-first with an imperative API for code outside the component.\n- An official MCP server so AI assistants read the real docs.\n- An in-grid AI assistant driven by natural language.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native: runes and snippets, not a React component behind a wrapper.\n- Column pinning, master/detail, tree data, row grouping with aggregation and cell-range selection are in the MIT core; MUI X sells them as Pro or Premium.\n- The in-grid AI helpers (natural-language filter, smart fill, summarise, classify) are free in @svgrid/grid and run against a provider you register; MUI X's AI assistant is Premium and routes prompts through MUI's hosted service unless you build your own.\n- No Material Design opinion: theme through --sg-* tokens, with no Emotion or Material UI in the bundle. The At a glance table has the measured sizes.\n- Integrated charts in the MIT core, without a separate charts package.\n\n## Where MUI X DataGrid is stronger\n\n- First-class fit if the app is already built on Material UI and React: theming, date pickers and charts share one design system.\n- Pro and Premium features are vendor-supported with priority support and guaranteed response times on the Enterprise plan.\n- A very large React community and years of production use.\n- The Premium AI assistant comes with a hosted prompt service and starter credits, so there is nothing to run yourself.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | MUI X DataGrid |\n| --- | --- | --- |\n| Svelte 5 native | Yes - runes and snippets | No - React only |\n| Sorting, filtering, pagination | Yes | Yes - Community |\n| Row virtualization | Yes | Yes - Community |\n| Column virtualization | Yes | Paid tier - Pro |\n| Column pinning | Yes - MIT core, left and right | Paid tier - Pro |\n| Row reordering by drag | Yes - MIT core | Paid tier - Pro |\n| Master/detail | Yes - MIT core | Paid tier - Pro |\n| Tree data | Yes - MIT core | Paid tier - Pro |\n| Row grouping with aggregation | Yes - MIT core | Paid tier - Premium |\n| Cell-range selection and clipboard | Yes - MIT core, with a fill handle | Paid tier - Premium |\n| CSV export | Yes - MIT core | Yes - Community |\n| Excel export | Paid tier - @svgrid/enterprise | Paid tier - Premium |\n| Pivot tables | Paid tier - @svgrid/enterprise | Paid tier - Premium |\n| Integrated charts | Yes - SvGridChart in the MIT core | Partial - MUI X Charts is a separate package |\n| In-grid AI assistant | Yes - MIT core, bring your own model | Paid tier - Premium, through MUI's hosted service or your own proxy |\n| MCP server for AI assistants | Yes - @svgrid/mcp, MIT: docs, examples, code check, scaffold, preview | Yes - @mui/mcp, free: docs and examples |\n| Inline editing | Yes | Yes - Community |\n| Design-system independence | Yes - --sg-* tokens, no UI framework dependency | Partial - Material UI, Emotion and the MUI system are peer dependencies |\n| Core licence | Yes - MIT | Yes - MIT (Community) |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid shaped by runes, not a React component.\n- You want pinning, master/detail, tree data, grouping and cell selection without buying Pro or Premium.\n- You do not want Material Design, Emotion or the MUI system in your bundle.\n- You want the in-grid AI helpers to talk to a model you choose and host.\n\n## When to choose MUI X DataGrid\n\n- Your app is already built on Material UI and React.\n- You need Premium grouping, aggregation, pivoting or Excel export as vendor-supported features with a support contract.\n- You want one grid that matches React teammates across the MUI X suite, including date pickers and charts.\n- You want a hosted AI assistant with nothing to run yourself.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- Material Design out of the box; SvGrid ships neutral tokens and you theme it.\n- The rest of MUI X in the same design system: date pickers, charts and the tree view.\n- A hosted AI assistant with starter credits; SvGrid's helpers need a model provider you register.\n- React-specific patterns such as slots and hooks; SvGrid uses snippets and props.\n\nMigration guide: moving from MUI X DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-mui-x/\n\n## Live example\n\nTree And Master Detail: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/08-tree-and-master-detail/\n\n## The bottom line\n\nIf your app already lives in Material UI and React, MUI X is the path of least resistance, and its Premium tier now includes a hosted AI assistant. On Svelte 5, SvGrid is the better fit: it puts pinning, master/detail, tree data, grouping and cell selection in the MIT core that MUI X reserves for Pro and Premium, keeps Material UI and Emotion out of the bundle, and runs its AI helpers against a model you choose.\n\n## Frequently asked questions\n\n### SvGrid vs MUI X DataGrid: which one for Svelte?\n\nSvGrid, if your stack is Svelte. MUI X is React-only and depends on Material UI, Emotion and the MUI system as peer dependencies; SvGrid is Svelte-5-native with no design-system dependency.\n\n### Which MUI X Pro and Premium features are free in SvGrid?\n\nColumn pinning, column virtualization, row reordering, master/detail and tree data (Pro in MUI X), and row grouping, aggregation and cell-range selection (Premium in MUI X) ship in the MIT core of SvGrid. Excel export and pivoting are paid on both sides: Premium in MUI X, @svgrid/enterprise in SvGrid.\n\n### Does MUI X have an AI assistant like SvGrid?\n\nYes, in Premium. mui.com describes a natural-language assistant (sort by name, show amounts larger than a value) that sends prompts through a proxy to MUI's hosted service with an API key, with starter credits included and the option to build your own processing service. SvGrid's natural-language filter, smart fill, summarise and classify helpers are free in @svgrid/grid and only run against a model provider you register, so nothing leaves your infrastructure unless you route it there.\n\n### Does MUI ship an MCP server?\n\nYes. @mui/mcp gives an AI client the official docs and code examples for Material UI and MUI X, including the Data Grid. @svgrid/mcp does the same for SvGrid and adds a code checker that validates props and imports against the real API surface, a scaffold tool and a preview.\n\n### Is SvGrid cheaper than MUI X Pro or Premium?\n\nThe prices mui.com listed on the date we read them are in the pricing line at the top of this page, per developer per year for Pro and Premium. SvGrid's core is MIT and @svgrid/enterprise is $599 per developer per year for the enterprise grid or $999 with the spreadsheet and Studio, both for unlimited applications. The difference is what the free tier holds: most features MUI X sells in Pro and Premium are in SvGrid's MIT core, so many teams never need the paid pack.\n\n### How long does a MUI X to SvGrid migration take?\n\nThe migration guide budgets one to three hours per grid. Column definitions and the row model map directly; the time goes into replacing React slots and renderCell functions with Svelte snippets and re-theming away from Material Design.\n\n### Is SvGrid a good MUI X DataGrid alternative for Svelte?\n\nMUI X DataGrid is React-only, so this is less an alternative than a port. The concepts carry over almost one to one: column definitions, a free tier and a paid tier, server-side rows, an imperative API. What does not carry over is Material Design: SvGrid is themed through CSS custom properties, so you bring your own look, and Emotion and Material UI stay out of the bundle.\n\n## Related comparisons and docs\n\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/)\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [AI assistant](https://svgrid.com/docs/help/ai/)\n- [Column pinning](https://svgrid.com/docs/help/columns/column-pinning/)\n- [Master / detail (nested grids)](https://svgrid.com/docs/help/rows/master-detail/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- mui-overview: Feature list with plan badges: CSV export, cell editing and row virtualization in Community; column pinning, column reordering, row reordering, tree data and column virtualization Pro; row grouping, aggregation, Excel export and pivoting Premium; React package with Material UI peer dependencies (checked 12 Sep 2026) https://mui.com/x/react-data-grid/\n- mui-master-detail: Master-detail row panels carry the Pro plan badge (checked 12 Sep 2026) https://mui.com/x/react-data-grid/master-detail/\n- mui-cell-selection: Cell selection carries the Premium plan badge: with the Data Grid Premium, you can apply the cellSelection prop (checked 12 Sep 2026) https://mui.com/x/react-data-grid/cell-selection/\n- mui-ai-assistant: AI Assistant is Premium: natural-language prompts such as sort by name or show amounts larger than 1000, sent through a server-side proxy to MUI's hosted service with an API key from MUI Console; Premium licence holders get starter credits; a self-built prompt service is optional (checked 12 Sep 2026) https://mui.com/x/react-data-grid/ai-assistant/\n- mui-mcp: Official MCP server (@mui/mcp) that quotes the official docs and code examples for MUI X components including the Data Grid; installed with npx, no payment (checked 12 Sep 2026) https://mui.com/x/introduction/mcp/\n- mui-pricing: Community free forever under MIT; Pro $299 per year per dev; Premium $599 per year per dev; Enterprise $1,399 per year per dev; perpetual and annual models both allow perpetual production use (checked 12 Sep 2026) https://mui.com/pricing/\n"
8630
+ "markdown": "# SvGrid vs MUI X DataGrid\n\nCanonical URL: https://svgrid.com/compare/mui-x-datagrid/\nFacts verified: 2026-09-12\nCompetitor package: @mui/x-data-grid\nCompetitor site: https://mui.com/x/react-data-grid/\n\nMUI X DataGrid is the data grid of the Material UI ecosystem on React, split into a free Community tier and paid Pro and Premium tiers.\n\n## Verdict\n\nMUI X is the obvious pick if you are already on Material UI and React. SvGrid is Svelte-5-native, ships more in its MIT core (pinning, master/detail, tree data, grouping and cell selection are not Pro or Premium features), and carries no Material Design opinion.\n\nMigration guide: moving from MUI X DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-mui-x/\n\n## At a glance\n\n| Fact | SvGrid | MUI X DataGrid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 9.13.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 4 Sep 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 11,800,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 155.0 KB JS, no separate stylesheet, @emotion/react + @emotion/styled + @mui/material + @mui/system + react + react-dom external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | MUI X Community is free under MIT. mui.com lists Pro at $299 per year per developer, Premium at $599 per year per developer and Enterprise at $1,399 per year per developer, with perpetual and annual licence models | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; @mui/x-data-grid 9.13.0 entry `DataGrid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nMUI X DataGrid is what most React teams on Material UI reach for. The Community edition is MIT and covers sorting, filtering, pagination, CSV export and row virtualization. Column pinning, column virtualization, row reordering, tree data and master/detail are Pro; row grouping, aggregation, cell selection, Excel export, pivoting and the AI assistant are Premium. Both paid tiers are sold per developer per year, and the sources below link to the pages that mark each feature.\n\nSvGrid is the inverse trade: one Svelte-5-native grid whose MIT core already includes pinning, master/detail, tree data, grouping with aggregation, cell-range selection with a fill handle, integrated charts and in-grid AI helpers you point at your own model, plus an optional @svgrid/enterprise pack for Excel, PDF and print output, import and pivot tables.\n\n## Looking for a MUI X DataGrid alternative for Svelte?\n\nMUI X DataGrid is React-only, so this is less an alternative than a port. The concepts carry over almost one to one: column definitions, a free tier and a paid tier, server-side rows, an imperative API. What does not carry over is Material Design: SvGrid is themed through CSS custom properties, so you bring your own look, and Emotion and Material UI stay out of the bundle.\n\n## What they have in common\n\n- A Community / paid split with an MIT free tier.\n- Sorting, filtering, pagination, virtualization and inline editing.\n- Server-side data through a row model the app feeds.\n- TypeScript-first with an imperative API for code outside the component.\n- An official MCP server so AI assistants read the real docs.\n- An in-grid AI assistant driven by natural language.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native: runes and snippets, not a React component behind a wrapper.\n- Column pinning, master/detail, tree data, row grouping with aggregation and cell-range selection are in the MIT core; MUI X sells them as Pro or Premium.\n- The in-grid AI helpers (natural-language filter, smart fill, summarise, classify) are free in @svgrid/grid and run against a provider you register; MUI X's AI assistant is Premium and routes prompts through MUI's hosted service unless you build your own.\n- No Material Design opinion: theme through --sg-* tokens, with no Emotion or Material UI in the bundle. The At a glance table has the measured sizes.\n- Integrated charts in the MIT core, without a separate charts package.\n\n## Where MUI X DataGrid is stronger\n\n- First-class fit if the app is already built on Material UI and React: theming, date pickers and charts share one design system.\n- Pro and Premium features are vendor-supported with priority support and guaranteed response times on the Enterprise plan.\n- A very large React community and years of production use.\n- The Premium AI assistant comes with a hosted prompt service and starter credits, so there is nothing to run yourself.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | MUI X DataGrid |\n| --- | --- | --- |\n| Svelte 5 native | Yes - runes and snippets | No - React only |\n| Sorting, filtering, pagination | Yes | Yes - Community |\n| Row virtualization | Yes | Yes - Community |\n| Column virtualization | Yes | Paid tier - Pro |\n| Column pinning | Yes - MIT core, left and right | Paid tier - Pro |\n| Row reordering by drag | Yes - MIT core | Paid tier - Pro |\n| Master/detail | Yes - MIT core | Paid tier - Pro |\n| Tree data | Yes - MIT core | Paid tier - Pro |\n| Row grouping with aggregation | Yes - MIT core | Paid tier - Premium |\n| Cell-range selection and clipboard | Yes - MIT core, with a fill handle | Paid tier - Premium |\n| CSV export | Yes - MIT core | Yes - Community |\n| Excel export | Paid tier - @svgrid/enterprise | Paid tier - Premium |\n| Pivot tables | Paid tier - @svgrid/enterprise | Paid tier - Premium |\n| Integrated charts | Yes - SvGridChart in the MIT core | Partial - MUI X Charts is a separate package |\n| In-grid AI assistant | Yes - MIT core, bring your own model | Paid tier - Premium, through MUI's hosted service or your own proxy |\n| MCP server for AI assistants | Yes - @svgrid/mcp, MIT: docs, examples, code check, scaffold, preview | Yes - @mui/mcp, free: docs and examples |\n| Inline editing | Yes | Yes - Community |\n| Design-system independence | Yes - --sg-* tokens, no UI framework dependency | Partial - Material UI, Emotion and the MUI system are peer dependencies |\n| Core licence | Yes - MIT | Yes - MIT (Community) |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid shaped by runes, not a React component.\n- You want pinning, master/detail, tree data, grouping and cell selection without buying Pro or Premium.\n- You do not want Material Design, Emotion or the MUI system in your bundle.\n- You want the in-grid AI helpers to talk to a model you choose and host.\n\n## When to choose MUI X DataGrid\n\n- Your app is already built on Material UI and React.\n- You need Premium grouping, aggregation, pivoting or Excel export as vendor-supported features with a support contract.\n- You want one grid that matches React teammates across the MUI X suite, including date pickers and charts.\n- You want a hosted AI assistant with nothing to run yourself.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- Material Design out of the box; SvGrid ships neutral tokens and you theme it.\n- The rest of MUI X in the same design system: date pickers, charts and the tree view.\n- A hosted AI assistant with starter credits; SvGrid's helpers need a model provider you register.\n- React-specific patterns such as slots and hooks; SvGrid uses snippets and props.\n\nMigration guide: moving from MUI X DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-mui-x/\n\n## Live example\n\nTree And Master Detail: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/08-tree-and-master-detail/\n\n## The bottom line\n\nIf your app already lives in Material UI and React, MUI X is the path of least resistance, and its Premium tier now includes a hosted AI assistant. On Svelte 5, SvGrid is the better fit: it puts pinning, master/detail, tree data, grouping and cell selection in the MIT core that MUI X reserves for Pro and Premium, keeps Material UI and Emotion out of the bundle, and runs its AI helpers against a model you choose.\n\n## Frequently asked questions\n\n### SvGrid vs MUI X DataGrid: which one for Svelte?\n\nSvGrid, if your stack is Svelte. MUI X is React-only and depends on Material UI, Emotion and the MUI system as peer dependencies; SvGrid is Svelte-5-native with no design-system dependency.\n\n### Which MUI X Pro and Premium features are free in SvGrid?\n\nColumn pinning, column virtualization, row reordering, master/detail and tree data (Pro in MUI X), and row grouping, aggregation and cell-range selection (Premium in MUI X) ship in the MIT core of SvGrid. Excel export and pivoting are paid on both sides: Premium in MUI X, @svgrid/enterprise in SvGrid.\n\n### Does MUI X have an AI assistant like SvGrid?\n\nYes, in Premium. mui.com describes a natural-language assistant (sort by name, show amounts larger than a value) that sends prompts through a proxy to MUI's hosted service with an API key, with starter credits included and the option to build your own processing service. SvGrid's natural-language filter, smart fill, summarise and classify helpers are free in @svgrid/grid and only run against a model provider you register, so nothing leaves your infrastructure unless you route it there.\n\n### Does MUI ship an MCP server?\n\nYes. @mui/mcp gives an AI client the official docs and code examples for Material UI and MUI X, including the Data Grid. @svgrid/mcp does the same for SvGrid and adds a code checker that validates props and imports against the real API surface, a scaffold tool and a preview.\n\n### Is SvGrid cheaper than MUI X Pro or Premium?\n\nThe prices mui.com listed on the date we read them are in the pricing line at the top of this page, per developer per year for Pro and Premium. SvGrid's core is MIT and @svgrid/enterprise is $599 per developer per year for the enterprise grid or $999 with the spreadsheet and Studio, both for unlimited applications. The difference is what the free tier holds: most features MUI X sells in Pro and Premium are in SvGrid's MIT core, so many teams never need the paid pack.\n\n### How long does a MUI X to SvGrid migration take?\n\nThe migration guide budgets one to three hours per grid. Column definitions and the row model map directly; the time goes into replacing React slots and renderCell functions with Svelte snippets and re-theming away from Material Design.\n\n### Is SvGrid a good MUI X DataGrid alternative for Svelte?\n\nMUI X DataGrid is React-only, so this is less an alternative than a port. The concepts carry over almost one to one: column definitions, a free tier and a paid tier, server-side rows, an imperative API. What does not carry over is Material Design: SvGrid is themed through CSS custom properties, so you bring your own look, and Emotion and Material UI stay out of the bundle.\n\n## Related comparisons and docs\n\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [SvGrid vs React Data Grid (adazzle)](https://svgrid.com/compare/react-data-grid/)\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [AI assistant](https://svgrid.com/docs/help/ai/)\n- [Column pinning](https://svgrid.com/docs/help/columns/column-pinning/)\n- [Master / detail (nested grids)](https://svgrid.com/docs/help/rows/master-detail/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- mui-overview: Feature list with plan badges: CSV export, cell editing and row virtualization in Community; column pinning, column reordering, row reordering, tree data and column virtualization Pro; row grouping, aggregation, Excel export and pivoting Premium; React package with Material UI peer dependencies (checked 12 Sep 2026) https://mui.com/x/react-data-grid/\n- mui-master-detail: Master-detail row panels carry the Pro plan badge (checked 12 Sep 2026) https://mui.com/x/react-data-grid/master-detail/\n- mui-cell-selection: Cell selection carries the Premium plan badge: with the Data Grid Premium, you can apply the cellSelection prop (checked 12 Sep 2026) https://mui.com/x/react-data-grid/cell-selection/\n- mui-ai-assistant: AI Assistant is Premium: natural-language prompts such as sort by name or show amounts larger than 1000, sent through a server-side proxy to MUI's hosted service with an API key from MUI Console; Premium licence holders get starter credits; a self-built prompt service is optional (checked 12 Sep 2026) https://mui.com/x/react-data-grid/ai-assistant/\n- mui-mcp: Official MCP server (@mui/mcp) that quotes the official docs and code examples for MUI X components including the Data Grid; installed with npx, no payment (checked 12 Sep 2026) https://mui.com/x/introduction/mcp/\n- mui-pricing: Community free forever under MIT; Pro $299 per year per dev; Premium $599 per year per dev; Enterprise $1,399 per year per dev; perpetual and annual models both allow perpetual production use (checked 12 Sep 2026) https://mui.com/pricing/\n"
8481
8631
  },
8482
8632
  {
8483
8633
  "slug": "compare/nocodb",
@@ -8498,7 +8648,7 @@ export const docs = [
8498
8648
  "path": "docs/_data/comparisons/react-data-grid.json",
8499
8649
  "title": "SvGrid vs React Data Grid (adazzle)",
8500
8650
  "section": "Comparisons",
8501
- "markdown": "# SvGrid vs React Data Grid (adazzle)\n\nCanonical URL: https://svgrid.com/compare/react-data-grid/\nFacts verified: 2026-09-12\nCompetitor package: react-data-grid\nCompetitor site: https://github.com/adazzle/react-data-grid\n\nreact-data-grid is a fast, Excel-like data grid for React, MIT-licensed.\n\n## Verdict\n\nreact-data-grid is a strong, lightweight React grid with great editing. SvGrid is the Svelte-5-native equivalent, with a similar feature set and no React dependency.\n\nMigration guide: moving from React Data Grid (adazzle) to SvGrid: https://svgrid.com/docs/help/migrating-from-react-data-grid/\n\n## At a glance\n\n| Fact | SvGrid | React Data Grid (adazzle) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 7.0.0-beta.61 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 14 Jul 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 2,180,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 15.7 KB JS + 2.1 KB CSS, react + react-dom external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | react-data-grid is MIT on npm and free; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; react-data-grid 7.0.0-beta.61 entry `DataGrid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nreact-data-grid (the adazzle project) is a focused, performant React grid known for spreadsheet-style editing, virtualization, and a clean column API. It is MIT-licensed and React-only.\n\nSvGrid offers the same shape - virtualized DOM, typed columns, inline editing, custom cells - built on Svelte 5 runes and snippets rather than React components.\n\n## Looking for a React Data Grid alternative for Svelte?\n\nreact-data-grid is React-only, so this is a port rather than a swap, and the shapes line up well: both are Excel-like, both MIT, both driven by column definitions. Cell renderers become Svelte snippets and hooks become runes. If you are staying on React, there is no reason to move.\n\n## What they have in common\n\n- MIT-licensed.\n- Virtualized rows and columns.\n- Spreadsheet-style inline editing.\n- Typed column definitions.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native - runes and snippets, not React.\n- Built-in Excel-style filter menu and the imperative API.\n- Grouping, tree data, and master/detail in the core.\n- @svgrid/mcp MCP server + optional Enterprise pack.\n\n## Where React Data Grid (adazzle) is stronger\n\n- First-class fit for a React codebase.\n- Mature, focused, and battle-tested in React apps.\n- Large React community.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | React Data Grid (adazzle) |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - React only |\n| Virtualization | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Excel-style filter menu | Yes | Partial - BYO filter UI |\n| Grouping / tree | Yes | Yes - row grouping and a TreeDataGrid |\n| Master/detail | Yes | Partial - bring your own detail row |\n| Headless engine | Yes | No |\n| AI / MCP integration | Yes | No |\n| Fill handle and copy/paste | Yes | Yes - cell copy, paste and value dragging |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 rather than React.\n- You want filters, grouping, and master/detail without building them.\n- You want a headless engine option and an MCP server.\n\n## When to choose React Data Grid (adazzle)\n\n- Your app is React and you want a focused, proven grid.\n- You want the React community and ecosystem around it.\n- You only need the feature set react-data-grid already covers.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- A very small React grid with the spreadsheet basics built in.\n- React 19 features such as the use hook in cell renderers.\n\nMigration guide: moving from React Data Grid (adazzle) to SvGrid: https://svgrid.com/docs/help/migrating-from-react-data-grid/\n\n## Live example\n\nFill Handle: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/95-fill-handle/\n\n## The bottom line\n\nreact-data-grid is a strong, focused choice in React. On Svelte 5, SvGrid is the equivalent - similar editing and virtualization - plus a built-in filter menu, grouping, and a headless core, with no React dependency.\n\n## Frequently asked questions\n\n### SvGrid vs react-data-grid - which for Svelte?\n\nSvGrid - it is Svelte-5-native, while react-data-grid is React-only. They share a similar editing and virtualization model.\n\n### Does SvGrid have built-in filtering unlike react-data-grid?\n\nYes - SvGrid ships an Excel-style filter menu and a global filter; react-data-grid leaves the filter UI to you.\n\n### Is SvGrid free like react-data-grid?\n\nYes, the core is MIT. SvGrid adds an optional Enterprise pack for export, import, pivot, and AI.\n\n### Is SvGrid a good React Data Grid alternative for Svelte?\n\nreact-data-grid is React-only, so this is a port rather than a swap, and the shapes line up well: both are Excel-like, both MIT, both driven by column definitions. Cell renderers become Svelte snippets and hooks become runes. If you are staying on React, there is no reason to move.\n\n## Related comparisons and docs\n\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/)\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Cell text selection](https://svgrid.com/docs/help/cells/cell-text-selection/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- rdg-readme: React 19.2+; virtualization of rows and columns, multi-column sorting, cell editing, row grouping and a TreeDataGrid, frozen columns, cell copy and paste, cell value dragging; light and dark mode through color-scheme (checked 12 Sep 2026) https://github.com/adazzle/react-data-grid\n- rdg-npm: The latest tag is a 7.0 beta line; licence MIT (checked 12 Sep 2026) https://www.npmjs.com/package/react-data-grid\n"
8651
+ "markdown": "# SvGrid vs React Data Grid (adazzle)\n\nCanonical URL: https://svgrid.com/compare/react-data-grid/\nFacts verified: 2026-09-12\nCompetitor package: react-data-grid\nCompetitor site: https://github.com/adazzle/react-data-grid\n\nreact-data-grid is a fast, Excel-like data grid for React, MIT-licensed.\n\n## Verdict\n\nreact-data-grid is a strong, lightweight React grid with great editing. SvGrid is the Svelte-5-native equivalent, with a similar feature set and no React dependency.\n\nMigration guide: moving from React Data Grid (adazzle) to SvGrid: https://svgrid.com/docs/help/migrating-from-react-data-grid/\n\n## At a glance\n\n| Fact | SvGrid | React Data Grid (adazzle) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 7.0.0-beta.61 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 14 Jul 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (React) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 2,180,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 15.7 KB JS + 2.1 KB CSS, react + react-dom external | 12 Sep 2026 |\n| Frameworks | Svelte 5 | React | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | react-data-grid is MIT on npm and free; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; react-data-grid 7.0.0-beta.61 entry `DataGrid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nreact-data-grid (the adazzle project) is a focused, performant React grid known for spreadsheet-style editing, virtualization, and a clean column API. It is MIT-licensed and React-only.\n\nSvGrid offers the same shape - virtualized DOM, typed columns, inline editing, custom cells - built on Svelte 5 runes and snippets rather than React components.\n\n## Looking for a React Data Grid alternative for Svelte?\n\nreact-data-grid is React-only, so this is a port rather than a swap, and the shapes line up well: both are Excel-like, both MIT, both driven by column definitions. Cell renderers become Svelte snippets and hooks become runes. If you are staying on React, there is no reason to move.\n\n## What they have in common\n\n- MIT-licensed.\n- Virtualized rows and columns.\n- Spreadsheet-style inline editing.\n- Typed column definitions.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native - runes and snippets, not React.\n- Built-in Excel-style filter menu and the imperative API.\n- Grouping, tree data, and master/detail in the core.\n- @svgrid/mcp MCP server + optional Enterprise pack.\n\n## Where React Data Grid (adazzle) is stronger\n\n- First-class fit for a React codebase.\n- Mature, focused, and battle-tested in React apps.\n- Large React community.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | React Data Grid (adazzle) |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - React only |\n| Virtualization | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Excel-style filter menu | Yes | Partial - BYO filter UI |\n| Grouping / tree | Yes | Yes - row grouping and a TreeDataGrid |\n| Master/detail | Yes | Partial - bring your own detail row |\n| Headless engine | Yes | No |\n| AI / MCP integration | Yes | No |\n| Fill handle and copy/paste | Yes | Yes - cell copy, paste and value dragging |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 rather than React.\n- You want filters, grouping, and master/detail without building them.\n- You want a headless engine option and an MCP server.\n\n## When to choose React Data Grid (adazzle)\n\n- Your app is React and you want a focused, proven grid.\n- You want the React community and ecosystem around it.\n- You only need the feature set react-data-grid already covers.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- A very small React grid with the spreadsheet basics built in.\n- React 19 features such as the use hook in cell renderers.\n\nMigration guide: moving from React Data Grid (adazzle) to SvGrid: https://svgrid.com/docs/help/migrating-from-react-data-grid/\n\n## Live example\n\nFill Handle: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/95-fill-handle/\n\n## The bottom line\n\nreact-data-grid is a strong, focused choice in React. On Svelte 5, SvGrid is the equivalent - similar editing and virtualization - plus a built-in filter menu, grouping, and a headless core, with no React dependency.\n\n## Frequently asked questions\n\n### SvGrid vs react-data-grid - which for Svelte?\n\nSvGrid - it is Svelte-5-native, while react-data-grid is React-only. They share a similar editing and virtualization model.\n\n### Does SvGrid have built-in filtering unlike react-data-grid?\n\nYes - SvGrid ships an Excel-style filter menu and a global filter; react-data-grid leaves the filter UI to you.\n\n### Is SvGrid free like react-data-grid?\n\nYes, the core is MIT. SvGrid adds an optional Enterprise pack for export, import, pivot, and AI.\n\n### Is SvGrid a good React Data Grid alternative for Svelte?\n\nreact-data-grid is React-only, so this is a port rather than a swap, and the shapes line up well: both are Excel-like, both MIT, both driven by column definitions. Cell renderers become Svelte snippets and hooks become runes. If you are staying on React, there is no reason to move.\n\n## Related comparisons and docs\n\n- [SvGrid vs Glide Data Grid](https://svgrid.com/compare/glide-data-grid/)\n- [SvGrid vs MUI X DataGrid](https://svgrid.com/compare/mui-x-datagrid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Cell text selection](https://svgrid.com/docs/help/cells/cell-text-selection/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- rdg-readme: React 19.2+; virtualization of rows and columns, multi-column sorting, cell editing, row grouping and a TreeDataGrid, frozen columns, cell copy and paste, cell value dragging; light and dark mode through color-scheme (checked 12 Sep 2026) https://github.com/adazzle/react-data-grid\n- rdg-npm: The latest tag is a 7.0 beta line; licence MIT (checked 12 Sep 2026) https://www.npmjs.com/package/react-data-grid\n"
8502
8652
  },
8503
8653
  {
8504
8654
  "slug": "compare/smart-grid",
@@ -8512,14 +8662,14 @@ export const docs = [
8512
8662
  "path": "docs/_data/comparisons/svar-svelte-datagrid.json",
8513
8663
  "title": "SvGrid vs SVAR Svelte DataGrid",
8514
8664
  "section": "Comparisons",
8515
- "markdown": "# SvGrid vs SVAR Svelte DataGrid\n\nCanonical URL: https://svgrid.com/compare/svar-svelte-datagrid/\nFacts verified: 2026-09-12\nCompetitor package: wx-svelte-grid\nCompetitor site: https://svar.dev/svelte/datagrid/\n\nSVAR Svelte DataGrid (wx-svelte-grid) is a Svelte-native, MIT-licensed data grid from XB Software, the team behind Webix, with React and Vue versions of the same grid.\n\n## Verdict\n\nSVAR is the closest genuinely Svelte-native rival: both grids are MIT and both target Svelte 5. SvGrid has the wider capability surface (grouping with aggregation, master/detail, Excel-style range editing with a fill handle, integrated charts, a headless core, in-grid AI helpers and an MCP server); SVAR is the smaller grid with print in the free package, React and Vue versions, and the Webix team behind it.\n\nMigration guide: moving from SVAR Svelte DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-svar-svelte-datagrid/\n\n## At a glance\n\n| Fact | SvGrid | SVAR Svelte DataGrid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 2.7.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Svelte package, no peer range declared | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 62,800 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 51.5 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 30 Oct 2026 |\n| Frameworks | Svelte 5 | Svelte, React, Vue | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | The DataGrid is MIT and free for commercial use with no paid tier; svar.dev sells PRO editions of its Gantt, Calendar and Kanban components and offers paid consulting and custom development, with no price list for the grid | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; wx-svelte-grid 2.7.0 entry `Grid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nSVAR DataGrid (npm: wx-svelte-grid) is part of the SVAR suite from XB Software, the makers of Webix, and is one of the few grids built for Svelte rather than wrapped from another framework. Its docs list in-cell editing, header and advanced filtering, single and multi-column sorting, tree data, virtual scrolling for rows and columns, columns pinned to the left, column and row spans in the header and footer, auto-sized rows, undo and redo, a context menu, row reordering, CSV export, a print API and a REST data provider, all under MIT.\n\nSvGrid overlaps on the Svelte-native angle and reaches further: row grouping with aggregation, master/detail, Excel-style cell-range selection with clipboard and a fill handle, pinned rows and left and right column pinning, integrated charts, a server-side row model, a headless engine, in-grid AI helpers and the @svgrid/mcp server, all in the MIT package. Excel, PDF and print output, import, pivot tables and the Kanban and Scheduler views of the grid live in the paid @svgrid/enterprise pack, whereas SVAR keeps its grid entirely free and sells PRO editions of its Gantt, Calendar and Kanban instead.\n\n## Looking for a SVAR Svelte DataGrid alternative for Svelte?\n\nThe closest comparison on this list, since both are Svelte-native and both are MIT, so licensing does not decide it. The differences are depth and direction: SvGrid ships a larger feature surface, a UI component suite, in-grid AI helpers and an MCP server, while SVAR spans Svelte, React and Vue and keeps a smaller core. The At a glance table above has both measured bundle sizes; if a compact MIT grid with sorting, filtering, editing, tree data and CSV export is all you need, SVAR is a perfectly good answer.\n\n## What they have in common\n\n- Purpose-built for Svelte 5, not a cross-framework wrapper.\n- MIT-licensed and free for commercial use.\n- Sorting, filtering, in-cell editing, virtualization on rows and columns, tree data.\n- Auto-sized row heights, undo and redo, a context menu and drag-and-drop row reordering.\n- Themeable through CSS variables with light and dark themes, localization, WAI-ARIA markup and keyboard navigation.\n\n## Where SvGrid is stronger\n\n- Row grouping with aggregation and a drag-and-drop group panel; SVAR's docs list neither.\n- Master/detail and expandable detail rows; SVAR offers tree data only.\n- Excel-style cell-range selection with clipboard copy and paste and a fill handle; SVAR selects rows.\n- Pinned top and bottom rows, and columns pinned left and right; SVAR pins columns to the left only.\n- Integrated charts with no dependency, plus a chart wizard.\n- A server-side row model with cursor pagination, GraphQL, websocket and optimistic updates, beyond a REST data provider.\n- A headless engine (createSvGrid) you can compose, in addition to the render component.\n- In-grid AI helpers free in @svgrid/grid, and @svgrid/mcp with llms.txt so assistants answer and write code accurately.\n- A paid pack with Excel, PDF and styled-HTML export, print, pivot tables, Excel and CSV import and support. CSV, TSV and JSON export are free in the grid.\n\n## Where SVAR Svelte DataGrid is stronger\n\n- The whole grid is free, print API included; SvGrid puts print and Excel and PDF export in the paid pack. Both export CSV for free.\n- The same grid for React and Vue as well as Svelte; SvGrid is Svelte-only by design.\n- A smaller bundle: the At a glance table has both measured numbers.\n- XB Software and Webix behind it, a team that has built data grids for a long time.\n- Part of the wider SVAR suite, with paid consulting and custom development on offer.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | SVAR Svelte DataGrid |\n| --- | --- | --- |\n| Svelte 5 native | Yes | Yes - Svelte 5 compatible |\n| Licence | Yes - MIT core, paid enterprise pack | Yes - MIT, the grid is entirely free |\n| Headless engine | Yes - createSvGrid | No - component only |\n| Excel-style filter menu | Yes - built in | Yes - header filters plus the SVAR Filter component |\n| Cell-range selection and clipboard | Yes - built in | No - single and multiple row selection |\n| Fill handle | Yes | No - not in the feature list |\n| Row grouping with aggregation | Yes - with a group panel | No - not in the feature list |\n| Master/detail rows | Yes | No - tree data only |\n| Tree data | Yes | Yes |\n| Pinned columns | Yes - left and right | Partial - to the left |\n| Pinned rows (top and bottom) | Yes | No - not in the feature list |\n| Header and footer column spans | Yes | Yes |\n| Auto-sized row height | Yes - autoRowHeight | Yes |\n| Virtualization (rows and columns) | Yes | Yes |\n| Undo and redo, context menu, row drag | Yes | Yes |\n| Integrated charts | Yes - no dependency, plus a chart wizard | No - not in the feature list |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - createServerDataSource: page or infinite block scroll, cursor, GraphQL, websocket | Partial - RestDataProvider and dynamic loading while scrolling |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - not in the feature list |\n| CSV export | Yes - free, with TSV and JSON | Yes - free |\n| Excel and PDF export | Paid tier - @svgrid/enterprise | No - CSV only in the feature list |\n| Print | Paid tier - @svgrid/enterprise | Yes - print API, free |\n| Pivot tables | Paid tier - @svgrid/enterprise | No - not in the SVAR Svelte product list |\n| React and Vue versions | No - Svelte only | Yes |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not mentioned in the docs |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | Partial - paid consulting and custom development; no support plan for the grid listed |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, wx-svelte-grid 2.7.0. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | SVAR Svelte DataGrid |\n| --- | --- | --- |\n| Mount | 30.7 ms | 11.4 ms |\n| Sort, text column | 77.4 ms | 135.4 ms |\n| Sort, numeric column | 32.8 ms | 141.7 ms |\n| Filter, one column (indicative only) | 34.5 ms | 26.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.6 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 152.2 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 19 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\n## When to choose SvGrid\n\n- You need grouping with aggregation, master/detail, Excel-style range editing or pivot tables, which SVAR's docs do not list.\n- You want a headless engine plus a render component, not a component-only API.\n- You want integrated charts and a full server-side row model in one library.\n- You want in-grid AI helpers, an MCP server that checks generated code, and a paid support tier.\n\n## When to choose SVAR Svelte DataGrid\n\n- You want a fully free grid with print included and no paid tier at all.\n- You ship to React and Vue as well as Svelte and want one grid across them.\n- A smaller bundle matters more than grouping with aggregation, master/detail, range editing and the other features SvGrid adds.\n- You are already adopting the wider SVAR suite: Gantt, Calendar, Kanban, File Manager.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- Free printing: SVAR's print API is in the MIT grid, SvGrid's print view is in @svgrid/enterprise.\n- The React and Vue versions of the same grid.\n- A smaller bundle, by the measurements in the At a glance table.\n- The SVAR suite around the grid: Gantt, Calendar, Kanban and File Manager share its core.\n\nMigration guide: moving from SVAR Svelte DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-svar-svelte-datagrid/\n\n## Live example\n\nGrouping Aggregation: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/07-grouping-aggregation/\n\n## The bottom line\n\nBoth grids are Svelte-5-native and MIT, so this is not a licensing call. On capability SvGrid is the more complete grid: grouping, master/detail, range editing with a fill handle, charts, a server-side row model, a headless core, AI helpers and an MCP server. SVAR is the smaller, fully free, multi-framework option from the Webix team, and it prints for free where SvGrid charges for print and Excel and PDF export. Choose SvGrid when you need the deeper feature set or support; choose SVAR when a compact free grid covers your needs or you also ship React and Vue.\n\n## Frequently asked questions\n\n### SvGrid vs SVAR Svelte DataGrid: what is the difference?\n\nBoth are MIT-licensed, Svelte-5-native grids. SvGrid is the broader product: row grouping with aggregation, master/detail, Excel-style range selection with a fill handle, integrated charts, a server-side row model, a headless core, in-grid AI helpers and an MCP server. SVAR is a smaller, fully free grid with React and Vue versions from XB Software, with CSV export and a print API included.\n\n### Are SvGrid and SVAR both free?\n\nBoth are free under MIT, including commercial use. SVAR keeps the whole grid free, CSV export and print included, and sells PRO editions of its Gantt, Calendar and Kanban. SvGrid's grid is free too, including CSV, TSV and JSON export, charts and the AI helpers; Excel, PDF and print output, import, pivot tables, the Kanban and Scheduler views and support are in @svgrid/enterprise at $599 per developer per year.\n\n### Are both built for Svelte 5?\n\nYes. SvGrid is written in Svelte 5 runes, and svar.dev states the DataGrid is Svelte 5 compatible. Neither is a cross-framework wrapper, although SVAR also ships React and Vue versions of its grid.\n\n### Which grid is smaller?\n\nSVAR, by the measurements in the At a glance table: both packages were built alone with Vite, minified and gzipped with Svelte external, on the dates shown. SvGrid's extra size buys grouping, master/detail, range editing, charts and the server-side row model; features you never import, such as the date editors, menus and charts, load as separate chunks.\n\n### Does SVAR have row grouping, master/detail or cell-range selection?\n\nNot according to its docs overview on the date we read it, which lists tree data, single and multiple row selection, header and advanced filters, sorting, in-cell editing, columns pinned to the left, CSV export and a print API. SvGrid has all three in the MIT core, and the demos on this page show them.\n\n### How long does a SVAR to SvGrid migration take?\n\nThe migration guide budgets two to four hours per grid: a prop and event rename pass, since both use array-of-object column definitions, plus re-theming through --sg-* tokens.\n\n### Is SvGrid a good SVAR Svelte DataGrid alternative for Svelte?\n\nThe closest comparison on this list, since both are Svelte-native and both are MIT, so licensing does not decide it. The differences are depth and direction: SvGrid ships a larger feature surface, a UI component suite, in-grid AI helpers and an MCP server, while SVAR spans Svelte, React and Vue and keeps a smaller core. The At a glance table above has both measured bundle sizes; if a compact MIT grid with sorting, filtering, editing, tree data and CSV export is all you need, SVAR is a perfectly good answer.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Grouping & aggregation](https://svgrid.com/docs/help/grouping-aggregation/)\n- [Master / detail (nested grids)](https://svgrid.com/docs/help/rows/master-detail/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- svar-datagrid: Licensed under MIT; Svelte 5 compatible; React and Vue versions available; lists multi-column sorting, header filters, in-cell editing, tree data, virtual scrolling, columns pinned to the left, context menu, row drag-and-drop, checkbox selection, pagination, hotkeys, WAI-ARIA, print, undo/redo (checked 12 Sep 2026) https://svar.dev/svelte/datagrid/\n- svar-overview: Feature list: in-cell editing, header and advanced filtering, sorting, single and multiple row selection, row reordering, context menu, undo/redo, tree data, pagination, colspans and rowspans in header and footer, collapsible column groups, pinned columns to the left, auto-sizing of rows and columns, localization, themes, export to CSV, print API, RestDataProvider, virtual scrolling for rows and columns, WAI-ARIA, keyboard navigation; no Excel export, row grouping, aggregation, master/detail, charts, AI or MCP (checked 12 Sep 2026) https://docs.svar.dev/svelte/grid/overview/\n- svar-svelte: DataGrid, Filter, Editor, File Manager and Core are MIT; Gantt, Calendar and Kanban have MIT cores with paid PRO editions; no pivot component in the list; no price list on the page (checked 12 Sep 2026) https://svar.dev/svelte/\n- svar-gantt: Offers paid consulting and custom development services; PRO edition pricing is on a separate page (checked 12 Sep 2026) https://svar.dev/svelte/gantt/\n"
8665
+ "markdown": "# SvGrid vs SVAR Svelte DataGrid\n\nCanonical URL: https://svgrid.com/compare/svar-svelte-datagrid/\nFacts verified: 2026-09-12\nCompetitor package: wx-svelte-grid\nCompetitor site: https://svar.dev/svelte/datagrid/\n\nSVAR Svelte DataGrid (wx-svelte-grid) is a Svelte-native, MIT-licensed data grid from XB Software, the team behind Webix, with React and Vue versions of the same grid.\n\n## Verdict\n\nSVAR is the closest genuinely Svelte-native rival: both grids are MIT and both target Svelte 5. SvGrid has the wider capability surface (grouping with aggregation, master/detail, Excel-style range editing with a fill handle, integrated charts, a headless core, in-grid AI helpers and an MCP server); SVAR is the smaller grid with print in the free package, React and Vue versions, and the Webix team behind it.\n\nMigration guide: moving from SVAR Svelte DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-svar-svelte-datagrid/\n\n## At a glance\n\n| Fact | SvGrid | SVAR Svelte DataGrid | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 2.7.0 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 3 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Svelte package, no peer range declared | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 62,800 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 51.5 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 1 Nov 2026 |\n| Frameworks | Svelte 5 | Svelte, React, Vue | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | The DataGrid is MIT and free for commercial use with no paid tier; svar.dev sells PRO editions of its Gantt, Calendar and Kanban components and offers paid consulting and custom development, with no price list for the grid | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; wx-svelte-grid 2.7.0 entry `Grid component` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nSVAR DataGrid (npm: wx-svelte-grid) is part of the SVAR suite from XB Software, the makers of Webix, and is one of the few grids built for Svelte rather than wrapped from another framework. Its docs list in-cell editing, header and advanced filtering, single and multi-column sorting, tree data, virtual scrolling for rows and columns, columns pinned to the left, column and row spans in the header and footer, auto-sized rows, undo and redo, a context menu, row reordering, CSV export, a print API and a REST data provider, all under MIT.\n\nSvGrid overlaps on the Svelte-native angle and reaches further: row grouping with aggregation, master/detail, Excel-style cell-range selection with clipboard and a fill handle, pinned rows and left and right column pinning, integrated charts, a server-side row model, a headless engine, in-grid AI helpers and the @svgrid/mcp server, all in the MIT package. Excel, PDF and print output, import, pivot tables and the Kanban and Scheduler views of the grid live in the paid @svgrid/enterprise pack, whereas SVAR keeps its grid entirely free and sells PRO editions of its Gantt, Calendar and Kanban instead.\n\n## Looking for a SVAR Svelte DataGrid alternative for Svelte?\n\nThe closest comparison on this list, since both are Svelte-native and both are MIT, so licensing does not decide it. The differences are depth and direction: SvGrid ships a larger feature surface, a UI component suite, in-grid AI helpers and an MCP server, while SVAR spans Svelte, React and Vue and keeps a smaller core. The At a glance table above has both measured bundle sizes; if a compact MIT grid with sorting, filtering, editing, tree data and CSV export is all you need, SVAR is a perfectly good answer.\n\n## What they have in common\n\n- Purpose-built for Svelte 5, not a cross-framework wrapper.\n- MIT-licensed and free for commercial use.\n- Sorting, filtering, in-cell editing, virtualization on rows and columns, tree data.\n- Auto-sized row heights, undo and redo, a context menu and drag-and-drop row reordering.\n- Themeable through CSS variables with light and dark themes, localization, WAI-ARIA markup and keyboard navigation.\n\n## Where SvGrid is stronger\n\n- Row grouping with aggregation and a drag-and-drop group panel; SVAR's docs list neither.\n- Master/detail and expandable detail rows; SVAR offers tree data only.\n- Excel-style cell-range selection with clipboard copy and paste and a fill handle; SVAR selects rows.\n- Pinned top and bottom rows, and columns pinned left and right; SVAR pins columns to the left only.\n- Integrated charts with no dependency, plus a chart wizard.\n- A server-side row model with cursor pagination, GraphQL, websocket and optimistic updates, beyond a REST data provider.\n- A headless engine (createSvGrid) you can compose, in addition to the render component.\n- In-grid AI helpers free in @svgrid/grid, and @svgrid/mcp with llms.txt so assistants answer and write code accurately.\n- A paid pack with Excel, PDF and styled-HTML export, print, pivot tables, Excel and CSV import and support. CSV, TSV and JSON export are free in the grid.\n\n## Where SVAR Svelte DataGrid is stronger\n\n- The whole grid is free, print API included; SvGrid puts print and Excel and PDF export in the paid pack. Both export CSV for free.\n- The same grid for React and Vue as well as Svelte; SvGrid is Svelte-only by design.\n- A smaller bundle: the At a glance table has both measured numbers.\n- XB Software and Webix behind it, a team that has built data grids for a long time.\n- Part of the wider SVAR suite, with paid consulting and custom development on offer.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | SVAR Svelte DataGrid |\n| --- | --- | --- |\n| Svelte 5 native | Yes | Yes - Svelte 5 compatible |\n| Licence | Yes - MIT core, paid enterprise pack | Yes - MIT, the grid is entirely free |\n| Headless engine | Yes - createSvGrid | No - component only |\n| Excel-style filter menu | Yes - built in | Yes - header filters plus the SVAR Filter component |\n| Cell-range selection and clipboard | Yes - built in | No - single and multiple row selection |\n| Fill handle | Yes | No - not in the feature list |\n| Row grouping with aggregation | Yes - with a group panel | No - not in the feature list |\n| Master/detail rows | Yes | No - tree data only |\n| Tree data | Yes | Yes |\n| Pinned columns | Yes - left and right | Partial - to the left |\n| Pinned rows (top and bottom) | Yes | No - not in the feature list |\n| Header and footer column spans | Yes | Yes |\n| Auto-sized row height | Yes - autoRowHeight | Yes |\n| Virtualization (rows and columns) | Yes | Yes |\n| Undo and redo, context menu, row drag | Yes | Yes |\n| Integrated charts | Yes - no dependency, plus a chart wizard | No - not in the feature list |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - createServerDataSource: page or infinite block scroll, cursor, GraphQL, websocket | Partial - RestDataProvider and dynamic loading while scrolling |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - not in the feature list |\n| CSV export | Yes - free, with TSV and JSON | Yes - free |\n| Excel and PDF export | Paid tier - @svgrid/enterprise | No - CSV only in the feature list |\n| Print | Paid tier - @svgrid/enterprise | Yes - print API, free |\n| Pivot tables | Paid tier - @svgrid/enterprise | No - not in the SVAR Svelte product list |\n| React and Vue versions | No - Svelte only | Yes |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not mentioned in the docs |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | Partial - paid consulting and custom development; no support plan for the grid listed |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, wx-svelte-grid 2.7.0. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | SVAR Svelte DataGrid |\n| --- | --- | --- |\n| Mount | 30.7 ms | 11.4 ms |\n| Sort, text column | 77.4 ms | 135.4 ms |\n| Sort, numeric column | 32.8 ms | 141.7 ms |\n| Filter, one column (indicative only) | 34.5 ms | 26.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.6 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 152.2 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 19 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\n## When to choose SvGrid\n\n- You need grouping with aggregation, master/detail, Excel-style range editing or pivot tables, which SVAR's docs do not list.\n- You want a headless engine plus a render component, not a component-only API.\n- You want integrated charts and a full server-side row model in one library.\n- You want in-grid AI helpers, an MCP server that checks generated code, and a paid support tier.\n\n## When to choose SVAR Svelte DataGrid\n\n- You want a fully free grid with print included and no paid tier at all.\n- You ship to React and Vue as well as Svelte and want one grid across them.\n- A smaller bundle matters more than grouping with aggregation, master/detail, range editing and the other features SvGrid adds.\n- You are already adopting the wider SVAR suite: Gantt, Calendar, Kanban, File Manager.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- Free printing: SVAR's print API is in the MIT grid, SvGrid's print view is in @svgrid/enterprise.\n- The React and Vue versions of the same grid.\n- A smaller bundle, by the measurements in the At a glance table.\n- The SVAR suite around the grid: Gantt, Calendar, Kanban and File Manager share its core.\n\nMigration guide: moving from SVAR Svelte DataGrid to SvGrid: https://svgrid.com/docs/help/migrating-from-svar-svelte-datagrid/\n\n## Live example\n\nGrouping Aggregation: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/07-grouping-aggregation/\n\n## The bottom line\n\nBoth grids are Svelte-5-native and MIT, so this is not a licensing call. On capability SvGrid is the more complete grid: grouping, master/detail, range editing with a fill handle, charts, a server-side row model, a headless core, AI helpers and an MCP server. SVAR is the smaller, fully free, multi-framework option from the Webix team, and it prints for free where SvGrid charges for print and Excel and PDF export. Choose SvGrid when you need the deeper feature set or support; choose SVAR when a compact free grid covers your needs or you also ship React and Vue.\n\n## Frequently asked questions\n\n### SvGrid vs SVAR Svelte DataGrid: what is the difference?\n\nBoth are MIT-licensed, Svelte-5-native grids. SvGrid is the broader product: row grouping with aggregation, master/detail, Excel-style range selection with a fill handle, integrated charts, a server-side row model, a headless core, in-grid AI helpers and an MCP server. SVAR is a smaller, fully free grid with React and Vue versions from XB Software, with CSV export and a print API included.\n\n### Are SvGrid and SVAR both free?\n\nBoth are free under MIT, including commercial use. SVAR keeps the whole grid free, CSV export and print included, and sells PRO editions of its Gantt, Calendar and Kanban. SvGrid's grid is free too, including CSV, TSV and JSON export, charts and the AI helpers; Excel, PDF and print output, import, pivot tables, the Kanban and Scheduler views and support are in @svgrid/enterprise at $599 per developer per year.\n\n### Are both built for Svelte 5?\n\nYes. SvGrid is written in Svelte 5 runes, and svar.dev states the DataGrid is Svelte 5 compatible. Neither is a cross-framework wrapper, although SVAR also ships React and Vue versions of its grid.\n\n### Which grid is smaller?\n\nSVAR, by the measurements in the At a glance table: both packages were built alone with Vite, minified and gzipped with Svelte external, on the dates shown. SvGrid's extra size buys grouping, master/detail, range editing, charts and the server-side row model; features you never import, such as the date editors, menus and charts, load as separate chunks.\n\n### Does SVAR have row grouping, master/detail or cell-range selection?\n\nNot according to its docs overview on the date we read it, which lists tree data, single and multiple row selection, header and advanced filters, sorting, in-cell editing, columns pinned to the left, CSV export and a print API. SvGrid has all three in the MIT core, and the demos on this page show them.\n\n### How long does a SVAR to SvGrid migration take?\n\nThe migration guide budgets two to four hours per grid: a prop and event rename pass, since both use array-of-object column definitions, plus re-theming through --sg-* tokens.\n\n### Is SvGrid a good SVAR Svelte DataGrid alternative for Svelte?\n\nThe closest comparison on this list, since both are Svelte-native and both are MIT, so licensing does not decide it. The differences are depth and direction: SvGrid ships a larger feature surface, a UI component suite, in-grid AI helpers and an MCP server, while SVAR spans Svelte, React and Vue and keeps a smaller core. The At a glance table above has both measured bundle sizes; if a compact MIT grid with sorting, filtering, editing, tree data and CSV export is all you need, SVAR is a perfectly good answer.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Grouping & aggregation](https://svgrid.com/docs/help/grouping-aggregation/)\n- [Master / detail (nested grids)](https://svgrid.com/docs/help/rows/master-detail/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- svar-datagrid: Licensed under MIT; Svelte 5 compatible; React and Vue versions available; lists multi-column sorting, header filters, in-cell editing, tree data, virtual scrolling, columns pinned to the left, context menu, row drag-and-drop, checkbox selection, pagination, hotkeys, WAI-ARIA, print, undo/redo (checked 12 Sep 2026) https://svar.dev/svelte/datagrid/\n- svar-overview: Feature list: in-cell editing, header and advanced filtering, sorting, single and multiple row selection, row reordering, context menu, undo/redo, tree data, pagination, colspans and rowspans in header and footer, collapsible column groups, pinned columns to the left, auto-sizing of rows and columns, localization, themes, export to CSV, print API, RestDataProvider, virtual scrolling for rows and columns, WAI-ARIA, keyboard navigation; no Excel export, row grouping, aggregation, master/detail, charts, AI or MCP (checked 12 Sep 2026) https://docs.svar.dev/svelte/grid/overview/\n- svar-svelte: DataGrid, Filter, Editor, File Manager and Core are MIT; Gantt, Calendar and Kanban have MIT cores with paid PRO editions; no pivot component in the list; no price list on the page (checked 12 Sep 2026) https://svar.dev/svelte/\n- svar-gantt: Offers paid consulting and custom development services; PRO edition pricing is on a separate page (checked 12 Sep 2026) https://svar.dev/svelte/gantt/\n"
8516
8666
  },
8517
8667
  {
8518
8668
  "slug": "compare/svelte-headless-table",
8519
8669
  "path": "docs/_data/comparisons/svelte-headless-table.json",
8520
8670
  "title": "SvGrid vs svelte-headless-table",
8521
8671
  "section": "Comparisons",
8522
- "markdown": "# SvGrid vs svelte-headless-table\n\nCanonical URL: https://svgrid.com/compare/svelte-headless-table/\nFacts verified: 2026-09-12\nCompetitor package: svelte-headless-table\nCompetitor site: https://svelte-headless-table.bryanmylee.com/\n\nsvelte-headless-table is the Svelte-native headless table library by Bryan Lee, one of the earliest Svelte-specific table options, now deprecated on Svelte 4.\n\n## Verdict\n\nsvelte-headless-table popularised headless tables in Svelte and still works on Svelte 4. Its author states there are no plans for a Svelte 5 port, so a Svelte 5 upgrade forces the question. SvGrid keeps the headless approach on Svelte 5 runes, adds virtualization and a rendered grid, and the @humanspeak fork is the option if you want to stay headless with the same API.\n\nMigration guide: moving from svelte-headless-table to SvGrid: https://svgrid.com/docs/help/migrating-from-svelte-headless-table/\n\n## At a glance\n\n| Fact | SvGrid | svelte-headless-table | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 0.18.3 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 28 Oct 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Svelte 4 range (peer svelte ^4.0.0) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 90,100 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 5.7 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 30 Oct 2026 |\n| Frameworks | Svelte 5 | Svelte | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; svelte-headless-table 0.18.3 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nsvelte-headless-table exposes a createTable function with composable plugins for sorting, filtering, column ordering and hiding, pagination, row selection, expansion, grouping with aggregation and column resizing, and leaves the markup to you. The npm package's peer range is Svelte 4, and the repository README states there are no current plans for a Svelte 5 port. A community fork, @humanspeak/svelte-headless-table, carries the same API on Svelte 5 runes; the At a glance table shows the original's registry facts, and the migration guide has the fork's.\n\nSvGrid takes the same headless approach but is written in Svelte 5 runes, adds a production render component, and covers virtualization, Excel-style filters, cell-range selection with a fill handle, inline editing, master/detail, a server-side row model and integrated charts natively.\n\n## Looking for a svelte-headless-table alternative for Svelte?\n\nThis is the clearest migration case on the list: the original package's peer range is Svelte 4, its last release was in 2024 and the README says there are no plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. SvGrid keeps the headless approach you already chose and adds runes, virtualization and a render component if you want one. If you would rather keep the plugin API, the maintained community fork @humanspeak/svelte-headless-table targets Svelte 5, and its facts are in the guide.\n\n## What they have in common\n\n- Svelte-specific, not a port from another framework.\n- Headless-first composition: plugins in svelte-headless-table, a features object in SvGrid.\n- Sorting, filtering, pagination, row selection, expansion and grouping with aggregation in the engine.\n- MIT-licensed with a strong TypeScript story.\n\n## Where SvGrid is stronger\n\n- Built on Svelte 5 runes and released continuously; the original package is Svelte 4 only and its author has stopped.\n- A bundled <SvGrid /> component, so nobody assembles headers, body and virtualization by hand.\n- Virtualization on rows and columns built in; svelte-headless-table leaves it to a virtual-list library.\n- Excel-style filter menu, cell-range selection with a fill handle, inline editing, master/detail, a server-side row model and charts in the MIT package.\n- In-grid AI helpers free in @svgrid/grid and @svgrid/mcp for assistants, plus a paid support tier.\n\n## Where svelte-headless-table is stronger\n\n- A smaller bundle if all you want is the engine; the At a glance table has both measured sizes.\n- A plugin API many Svelte 4 codebases already know, and a documentation site that still reads well.\n- The @humanspeak fork keeps that API on Svelte 5 without a rewrite.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | svelte-headless-table |\n| --- | --- | --- |\n| Svelte 5 runes | Yes - native | No - Svelte 4 stores; no Svelte 5 port planned by the author |\n| Maintained release line | Yes | Partial - original deprecated; the @humanspeak fork is maintained on Svelte 5 |\n| Render component | Yes - <SvGrid /> | No - bring your own markup |\n| Headless engine | Yes - createSvGrid and a features object | Yes - createTable and plugins |\n| Sorting and column filtering | Yes | Yes - engine only |\n| Excel-style filter menu | Yes - built in | No - bring your own UI |\n| Cell-range selection and clipboard | Yes - built in, with a fill handle | No - row selection only |\n| Inline editing | Yes - built in | No - not a plugin |\n| Virtualization | Yes - rows and columns, built in | Partial - pair with a virtual-list library |\n| Pagination | Yes | Yes |\n| Row grouping with aggregation | Yes - engine and rendered group rows | Yes - engine only |\n| Row expansion and tree | Yes | Yes - expansion plugin |\n| Column ordering, hiding, resizing | Yes | Yes |\n| Master/detail | Yes | No - not a plugin |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes | No - not a plugin |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - not a plugin |\n| Integrated charts | Yes - SvGridChart | No - not part of a headless engine |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not in the docs |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | No - none offered |\n\n## When to choose SvGrid\n\n- You are moving to Svelte 5 and want a maintained grid that keeps the headless approach.\n- You want virtualization, an Excel-style filter menu, editing and cell selection without building them.\n- You want a rendered component for the common case and a headless core for the rest.\n- You want a support tier behind the library.\n\n## When to choose svelte-headless-table\n\n- You are staying on Svelte 4 for now and the plugin set already covers you.\n- You want the smallest possible engine and will keep writing the markup yourself.\n- You want the same plugin API on Svelte 5 and are happy to move to the @humanspeak fork.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- The plugin API and its documentation site, if your team knows it well.\n- The smallest engine-only bundle; the At a glance table has both measured sizes.\n- Nothing in maintenance terms on the original package, which is where most migrations start.\n\nMigration guide: moving from svelte-headless-table to SvGrid: https://svgrid.com/docs/help/migrating-from-svelte-headless-table/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nFor a Svelte 4 codebase that is not moving, svelte-headless-table still works. For a Svelte 5 codebase, the original package is not an option and its author says so; the choice is between the @humanspeak fork, which keeps the plugin API, and SvGrid, which keeps the headless approach and adds virtualization, filters, editing, selection and a rendered grid in the same MIT package.\n\n## Frequently asked questions\n\n### Does svelte-headless-table work with Svelte 5?\n\nThe original package's peer range is Svelte 4 and its README states there are no current plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. The community fork @humanspeak/svelte-headless-table targets Svelte 5 with runes; SvGrid is written in Svelte 5 from the first line.\n\n### Can I keep a headless table with SvGrid?\n\nYes. createSvGrid plus the row-model factories is a headless engine; you can drive your own markup as before and adopt the SvGrid component only where you want it. The headless demos on this page show a plain table and a virtualized one.\n\n### Is SvGrid heavier than svelte-headless-table?\n\nYes, by the measurements in the At a glance table, because it ships a rendered grid, a virtualizer, filter menus and editors that a headless engine leaves to you. If you only need the engine and will write the rest, the difference is what you would otherwise write.\n\n### How long does a migration take?\n\nThe migration guide budgets one to three hours per grid; most of the time goes into deleting the markup and plugins the rendered grid replaces. Column definitions and the plugin concepts (sort, filter, page, select, expand, group) map one to one onto SvGrid's features.\n\n### Should I move to the @humanspeak fork instead?\n\nIf you want the same plugin API on Svelte 5 and are happy to keep writing the markup, yes, and its registry facts are in the migration guide. If the upgrade is also a chance to stop maintaining a table layer, SvGrid gives you the rendered grid and keeps the headless core for the cases that need it.\n\n### Is SvGrid a good svelte-headless-table alternative for Svelte?\n\nThis is the clearest migration case on the list: the original package's peer range is Svelte 4, its last release was in 2024 and the README says there are no plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. SvGrid keeps the headless approach you already chose and adds runes, virtualization and a render component if you want one. If you would rather keep the plugin API, the maintained community fork @humanspeak/svelte-headless-table targets Svelte 5, and its facts are in the guide.\n\n## Related comparisons and docs\n\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n- [Grouping & aggregation](https://svgrid.com/docs/help/grouping-aggregation/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- sht-github: README: there are no current plans to work on a Svelte 5 port of this project nor is there a maintenance schedule for Svelte 3/4; the project is flagged as deprecated and users are encouraged to seek alternatives or fork (checked 12 Sep 2026) https://github.com/bryanmylee/svelte-headless-table\n- sht-docs: Advertised plugins: multi-sorting, column filtering, global filtering, column reordering, hiding columns, pagination, row grouping and aggregation, row expansion, row selection, column resizing; headless, you write the markup (checked 12 Sep 2026) https://svelte-headless-table.bryanmylee.com/\n- sht-fork: MIT; part of the Humanspeak family of runes-native Svelte 5 packages; the npm package declares a Svelte 5 peer range (checked 12 Sep 2026) https://github.com/humanspeak/svelte-headless-table\n"
8672
+ "markdown": "# SvGrid vs svelte-headless-table\n\nCanonical URL: https://svgrid.com/compare/svelte-headless-table/\nFacts verified: 2026-09-12\nCompetitor package: svelte-headless-table\nCompetitor site: https://svelte-headless-table.bryanmylee.com/\n\nsvelte-headless-table is the Svelte-native headless table library by Bryan Lee, one of the earliest Svelte-specific table options, now deprecated on Svelte 4.\n\n## Verdict\n\nsvelte-headless-table popularised headless tables in Svelte and still works on Svelte 4. Its author states there are no plans for a Svelte 5 port, so a Svelte 5 upgrade forces the question. SvGrid keeps the headless approach on Svelte 5 runes, adds virtualization and a rendered grid, and the @humanspeak fork is the option if you want to stay headless with the same API.\n\nMigration guide: moving from svelte-headless-table to SvGrid: https://svgrid.com/docs/help/migrating-from-svelte-headless-table/\n\n## At a glance\n\n| Fact | SvGrid | svelte-headless-table | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 0.18.3 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 28 Oct 2024 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Svelte 4 range (peer svelte ^4.0.0) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 90,100 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 5.7 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 1 Nov 2026 |\n| Frameworks | Svelte 5 | Svelte | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | svelte-headless-table is MIT and free; no paid licence or support is offered, and the author states there are no plans for a Svelte 5 port | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; svelte-headless-table 0.18.3 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nsvelte-headless-table exposes a createTable function with composable plugins for sorting, filtering, column ordering and hiding, pagination, row selection, expansion, grouping with aggregation and column resizing, and leaves the markup to you. The npm package's peer range is Svelte 4, and the repository README states there are no current plans for a Svelte 5 port. A community fork, @humanspeak/svelte-headless-table, carries the same API on Svelte 5 runes; the At a glance table shows the original's registry facts, and the migration guide has the fork's.\n\nSvGrid takes the same headless approach but is written in Svelte 5 runes, adds a production render component, and covers virtualization, Excel-style filters, cell-range selection with a fill handle, inline editing, master/detail, a server-side row model and integrated charts natively.\n\n## Looking for a svelte-headless-table alternative for Svelte?\n\nThis is the clearest migration case on the list: the original package's peer range is Svelte 4, its last release was in 2024 and the README says there are no plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. SvGrid keeps the headless approach you already chose and adds runes, virtualization and a render component if you want one. If you would rather keep the plugin API, the maintained community fork @humanspeak/svelte-headless-table targets Svelte 5, and its facts are in the guide.\n\n## What they have in common\n\n- Svelte-specific, not a port from another framework.\n- Headless-first composition: plugins in svelte-headless-table, a features object in SvGrid.\n- Sorting, filtering, pagination, row selection, expansion and grouping with aggregation in the engine.\n- MIT-licensed with a strong TypeScript story.\n\n## Where SvGrid is stronger\n\n- Built on Svelte 5 runes and released continuously; the original package is Svelte 4 only and its author has stopped.\n- A bundled <SvGrid /> component, so nobody assembles headers, body and virtualization by hand.\n- Virtualization on rows and columns built in; svelte-headless-table leaves it to a virtual-list library.\n- Excel-style filter menu, cell-range selection with a fill handle, inline editing, master/detail, a server-side row model and charts in the MIT package.\n- In-grid AI helpers free in @svgrid/grid and @svgrid/mcp for assistants, plus a paid support tier.\n\n## Where svelte-headless-table is stronger\n\n- A smaller bundle if all you want is the engine; the At a glance table has both measured sizes.\n- A plugin API many Svelte 4 codebases already know, and a documentation site that still reads well.\n- The @humanspeak fork keeps that API on Svelte 5 without a rewrite.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | svelte-headless-table |\n| --- | --- | --- |\n| Svelte 5 runes | Yes - native | No - Svelte 4 stores; no Svelte 5 port planned by the author |\n| Maintained release line | Yes | Partial - original deprecated; the @humanspeak fork is maintained on Svelte 5 |\n| Render component | Yes - <SvGrid /> | No - bring your own markup |\n| Headless engine | Yes - createSvGrid and a features object | Yes - createTable and plugins |\n| Sorting and column filtering | Yes | Yes - engine only |\n| Excel-style filter menu | Yes - built in | No - bring your own UI |\n| Cell-range selection and clipboard | Yes - built in, with a fill handle | No - row selection only |\n| Inline editing | Yes - built in | No - not a plugin |\n| Virtualization | Yes - rows and columns, built in | Partial - pair with a virtual-list library |\n| Pagination | Yes | Yes |\n| Row grouping with aggregation | Yes - engine and rendered group rows | Yes - engine only |\n| Row expansion and tree | Yes | Yes - expansion plugin |\n| Column ordering, hiding, resizing | Yes | Yes |\n| Master/detail | Yes | No - not a plugin |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes | No - not a plugin |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - not a plugin |\n| Integrated charts | Yes - SvGridChart | No - not part of a headless engine |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not in the docs |\n| Paid support | Yes - with @svgrid/enterprise, per developer per year | No - none offered |\n\n## When to choose SvGrid\n\n- You are moving to Svelte 5 and want a maintained grid that keeps the headless approach.\n- You want virtualization, an Excel-style filter menu, editing and cell selection without building them.\n- You want a rendered component for the common case and a headless core for the rest.\n- You want a support tier behind the library.\n\n## When to choose svelte-headless-table\n\n- You are staying on Svelte 4 for now and the plugin set already covers you.\n- You want the smallest possible engine and will keep writing the markup yourself.\n- You want the same plugin API on Svelte 5 and are happy to move to the @humanspeak fork.\n\n## Migration effort\n\nEstimated effort: 1-3 hours per grid.\n\nWhat you give up:\n\n- The plugin API and its documentation site, if your team knows it well.\n- The smallest engine-only bundle; the At a glance table has both measured sizes.\n- Nothing in maintenance terms on the original package, which is where most migrations start.\n\nMigration guide: moving from svelte-headless-table to SvGrid: https://svgrid.com/docs/help/migrating-from-svelte-headless-table/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nFor a Svelte 4 codebase that is not moving, svelte-headless-table still works. For a Svelte 5 codebase, the original package is not an option and its author says so; the choice is between the @humanspeak fork, which keeps the plugin API, and SvGrid, which keeps the headless approach and adds virtualization, filters, editing, selection and a rendered grid in the same MIT package.\n\n## Frequently asked questions\n\n### Does svelte-headless-table work with Svelte 5?\n\nThe original package's peer range is Svelte 4 and its README states there are no current plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. The community fork @humanspeak/svelte-headless-table targets Svelte 5 with runes; SvGrid is written in Svelte 5 from the first line.\n\n### Can I keep a headless table with SvGrid?\n\nYes. createSvGrid plus the row-model factories is a headless engine; you can drive your own markup as before and adopt the SvGrid component only where you want it. The headless demos on this page show a plain table and a virtualized one.\n\n### Is SvGrid heavier than svelte-headless-table?\n\nYes, by the measurements in the At a glance table, because it ships a rendered grid, a virtualizer, filter menus and editors that a headless engine leaves to you. If you only need the engine and will write the rest, the difference is what you would otherwise write.\n\n### How long does a migration take?\n\nThe migration guide budgets one to three hours per grid; most of the time goes into deleting the markup and plugins the rendered grid replaces. Column definitions and the plugin concepts (sort, filter, page, select, expand, group) map one to one onto SvGrid's features.\n\n### Should I move to the @humanspeak fork instead?\n\nIf you want the same plugin API on Svelte 5 and are happy to keep writing the markup, yes, and its registry facts are in the migration guide. If the upgrade is also a chance to stop maintaining a table layer, SvGrid gives you the rendered grid and keeps the headless core for the cases that need it.\n\n### Is SvGrid a good svelte-headless-table alternative for Svelte?\n\nThis is the clearest migration case on the list: the original package's peer range is Svelte 4, its last release was in 2024 and the README says there are no plans for a Svelte 5 port nor a maintenance schedule for Svelte 3 and 4. SvGrid keeps the headless approach you already chose and adds runes, virtualization and a render component if you want one. If you would rather keep the plugin API, the maintained community fork @humanspeak/svelte-headless-table targets Svelte 5, and its facts are in the guide.\n\n## Related comparisons and docs\n\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/)\n- [SvGrid vs @vincjo/datatables](https://svgrid.com/compare/vincjo-datatables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n- [Grouping & aggregation](https://svgrid.com/docs/help/grouping-aggregation/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- sht-github: README: there are no current plans to work on a Svelte 5 port of this project nor is there a maintenance schedule for Svelte 3/4; the project is flagged as deprecated and users are encouraged to seek alternatives or fork (checked 12 Sep 2026) https://github.com/bryanmylee/svelte-headless-table\n- sht-docs: Advertised plugins: multi-sorting, column filtering, global filtering, column reordering, hiding columns, pagination, row grouping and aggregation, row expansion, row selection, column resizing; headless, you write the markup (checked 12 Sep 2026) https://svelte-headless-table.bryanmylee.com/\n- sht-fork: MIT; part of the Humanspeak family of runes-native Svelte 5 packages; the npm package declares a Svelte 5 peer range (checked 12 Sep 2026) https://github.com/humanspeak/svelte-headless-table\n"
8523
8673
  },
8524
8674
  {
8525
8675
  "slug": "compare/svelte-ui-kit-tables",
@@ -8540,21 +8690,21 @@ export const docs = [
8540
8690
  "path": "docs/_data/comparisons/tabulator.json",
8541
8691
  "title": "SvGrid vs Tabulator",
8542
8692
  "section": "Comparisons",
8543
- "markdown": "# SvGrid vs Tabulator\n\nCanonical URL: https://svgrid.com/compare/tabulator/\nFacts verified: 2026-09-12\nCompetitor package: tabulator-tables\nCompetitor site: https://tabulator.info/\n\nTabulator is a feature-rich, framework-agnostic vanilla-JS interactive table library, MIT-licensed.\n\n## Verdict\n\nTabulator is enormously capable and free, but it is vanilla JS you wire into Svelte imperatively. SvGrid delivers a similar feature surface as a Svelte-5-native component with reactive data binding.\n\nMigration guide: moving from Tabulator to SvGrid: https://svgrid.com/docs/help/migrating-from-tabulator/\n\n## At a glance\n\n| Fact | SvGrid | Tabulator | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.5.2 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 23 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 672,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 106.9 KB JS + 3.8 KB CSS | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Tabulator is MIT and free; no licence or support plan is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; tabulator-tables 6.5.2 entry `TabulatorFull` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nTabulator packs a huge feature set - sorting, filtering, grouping, editing, tree data, formatters, and more - into a framework-agnostic vanilla-JS library. You instantiate it against a DOM element and drive it through its imperative API.\n\nSvGrid covers the same ground but as a Svelte 5 component: data is a reactive `$state` array, cells are snippets, and the imperative API is there when you want it - no manual mount/teardown or DOM bridging.\n\n## Looking for a Tabulator alternative for Svelte?\n\nTabulator is mature, MIT and framework-agnostic, and the reason people move is usually reactivity: it owns its own DOM, so Svelte state and table state have to be kept in sync by hand. SvGrid is driven by your runes directly. Tabulator still wins on breadth of built-in features and on being usable from plain HTML with no build step.\n\n## What they have in common\n\n- Broad feature set: sort, filter, group, edit, tree, format.\n- MIT-licensed / free for commercial use.\n- Virtualized rendering for large datasets.\n- Rich, mature documentation.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native - reactive data binding, no imperative mount/teardown.\n- Custom cells are Svelte snippets, not HTML-string formatters.\n- Headless engine available in addition to the component.\n- @svgrid/mcp MCP server for AI assistants.\n\n## Where Tabulator is stronger\n\n- Framework-agnostic - the same library across vanilla, React, Vue, Angular.\n- Very large built-in formatter / editor catalogue.\n- Long track record and a big community.\n- No build step required to drop into a plain HTML page.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Tabulator |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - vanilla JavaScript |\n| Reactive data binding | Yes - $state | Partial - Imperative setData() |\n| Custom cells | Yes - Snippets / components | Partial - HTML-string formatters |\n| Sort / filter / group | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Tree data | Yes | Yes |\n| Virtualization | Yes | Yes |\n| Headless engine | Yes | No |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want reactive data, not imperative setData calls.\n- You want Svelte snippets for custom cells instead of HTML strings.\n- You want a headless engine option and an MCP server.\n\n## When to choose Tabulator\n\n- You need one table library across vanilla JS, React, Vue, and Angular.\n- You want a no-build-step drop-in for a plain HTML page.\n- You rely on a specific Tabulator formatter / module.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- One library for plain JavaScript pages as well as React, Angular and Vue.\n- Built-in download to CSV, XLSX and PDF without a paid pack; SvGrid has CSV free and Excel and PDF in @svgrid/enterprise.\n\nMigration guide: moving from Tabulator to SvGrid: https://svgrid.com/docs/help/migrating-from-tabulator/\n\n## Live example\n\nExcel Filters: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/03-excel-filters/\n\n## The bottom line\n\nTabulator is a free, feature-packed table that runs anywhere. If your app is Svelte 5, SvGrid gives you a comparable feature set with reactive data binding and snippet cells instead of imperative setData and HTML-string formatters.\n\n## Frequently asked questions\n\n### SvGrid vs Tabulator for Svelte - which is better?\n\nFor Svelte 5, SvGrid: reactive $state data and Svelte snippet cells, with no imperative mount or teardown. Tabulator wins if you need one library across vanilla JS, React, Vue, and Angular.\n\n### Is SvGrid free like Tabulator?\n\nYes - the core is MIT, like Tabulator. Only the optional @svgrid/enterprise pack is paid.\n\n### Can I reuse Tabulator formatters in SvGrid?\n\nYou re-create them as Svelte snippets via renderSnippet, which is more flexible than HTML-string formatters.\n\n### Is SvGrid a good Tabulator alternative for Svelte?\n\nTabulator is mature, MIT and framework-agnostic, and the reason people move is usually reactivity: it owns its own DOM, so Svelte state and table state have to be kept in sync by hand. SvGrid is driven by your runes directly. Tabulator still wins on breadth of built-in features and on being usable from plain HTML with no build step.\n\n## Related comparisons and docs\n\n- [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/)\n- [SvGrid vs Smart.Grid (Smart Web Components)](https://svgrid.com/compare/smart-grid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Cell components](https://svgrid.com/docs/help/cells/cell-components/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- tabulator-readme: MIT; a vanilla JavaScript library that builds interactive tables from HTML tables, arrays or JSON, with support for React, Angular and Vue; installed as tabulator-tables (checked 12 Sep 2026) https://github.com/olifolkerd/tabulator\n"
8693
+ "markdown": "# SvGrid vs Tabulator\n\nCanonical URL: https://svgrid.com/compare/tabulator/\nFacts verified: 2026-09-12\nCompetitor package: tabulator-tables\nCompetitor site: https://tabulator.info/\n\nTabulator is a feature-rich, framework-agnostic vanilla-JS interactive table library, MIT-licensed.\n\n## Verdict\n\nTabulator is enormously capable and free, but it is vanilla JS you wire into Svelte imperatively. SvGrid delivers a similar feature surface as a Svelte-5-native component with reactive data binding.\n\nMigration guide: moving from Tabulator to SvGrid: https://svgrid.com/docs/help/migrating-from-tabulator/\n\n## At a glance\n\n| Fact | SvGrid | Tabulator | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 6.5.2 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 23 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | No Svelte package (JavaScript) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 672,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 106.9 KB JS + 3.8 KB CSS | 12 Sep 2026 |\n| Frameworks | Svelte 5 | JavaScript | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | Tabulator is MIT and free; no licence or support plan is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; tabulator-tables 6.5.2 entry `TabulatorFull` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nTabulator packs a huge feature set - sorting, filtering, grouping, editing, tree data, formatters, and more - into a framework-agnostic vanilla-JS library. You instantiate it against a DOM element and drive it through its imperative API.\n\nSvGrid covers the same ground but as a Svelte 5 component: data is a reactive `$state` array, cells are snippets, and the imperative API is there when you want it - no manual mount/teardown or DOM bridging.\n\n## Looking for a Tabulator alternative for Svelte?\n\nTabulator is mature, MIT and framework-agnostic, and the reason people move is usually reactivity: it owns its own DOM, so Svelte state and table state have to be kept in sync by hand. SvGrid is driven by your runes directly. Tabulator still wins on breadth of built-in features and on being usable from plain HTML with no build step.\n\n## What they have in common\n\n- Broad feature set: sort, filter, group, edit, tree, format.\n- MIT-licensed / free for commercial use.\n- Virtualized rendering for large datasets.\n- Rich, mature documentation.\n\n## Where SvGrid is stronger\n\n- Svelte 5 native - reactive data binding, no imperative mount/teardown.\n- Custom cells are Svelte snippets, not HTML-string formatters.\n- Headless engine available in addition to the component.\n- @svgrid/mcp MCP server for AI assistants.\n\n## Where Tabulator is stronger\n\n- Framework-agnostic - the same library across vanilla, React, Vue, Angular.\n- Very large built-in formatter / editor catalogue.\n- Long track record and a big community.\n- No build step required to drop into a plain HTML page.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | Tabulator |\n| --- | --- | --- |\n| Svelte 5 native | Yes | No - vanilla JavaScript |\n| Reactive data binding | Yes - $state | Partial - Imperative setData() |\n| Custom cells | Yes - Snippets / components | Partial - HTML-string formatters |\n| Sort / filter / group | Yes | Yes |\n| Inline editing | Yes | Yes |\n| Tree data | Yes | Yes |\n| Virtualization | Yes | Yes |\n| Headless engine | Yes | No |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want reactive data, not imperative setData calls.\n- You want Svelte snippets for custom cells instead of HTML strings.\n- You want a headless engine option and an MCP server.\n\n## When to choose Tabulator\n\n- You need one table library across vanilla JS, React, Vue, and Angular.\n- You want a no-build-step drop-in for a plain HTML page.\n- You rely on a specific Tabulator formatter / module.\n\n## Migration effort\n\nEstimated effort: 2-4 hours per grid.\n\nWhat you give up:\n\n- One library for plain JavaScript pages as well as React, Angular and Vue.\n- Built-in download to CSV, XLSX and PDF without a paid pack; SvGrid has CSV free and Excel and PDF in @svgrid/enterprise.\n\nMigration guide: moving from Tabulator to SvGrid: https://svgrid.com/docs/help/migrating-from-tabulator/\n\n## Live example\n\nExcel Filters: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/03-excel-filters/\n\n## The bottom line\n\nTabulator is a free, feature-packed table that runs anywhere. If your app is Svelte 5, SvGrid gives you a comparable feature set with reactive data binding and snippet cells instead of imperative setData and HTML-string formatters.\n\n## Frequently asked questions\n\n### SvGrid vs Tabulator for Svelte - which is better?\n\nFor Svelte 5, SvGrid: reactive $state data and Svelte snippet cells, with no imperative mount or teardown. Tabulator wins if you need one library across vanilla JS, React, Vue, and Angular.\n\n### Is SvGrid free like Tabulator?\n\nYes - the core is MIT, like Tabulator. Only the optional @svgrid/enterprise pack is paid.\n\n### Can I reuse Tabulator formatters in SvGrid?\n\nYou re-create them as Svelte snippets via renderSnippet, which is more flexible than HTML-string formatters.\n\n### Is SvGrid a good Tabulator alternative for Svelte?\n\nTabulator is mature, MIT and framework-agnostic, and the reason people move is usually reactivity: it owns its own DOM, so Svelte state and table state have to be kept in sync by hand. SvGrid is driven by your runes directly. Tabulator still wins on breadth of built-in features and on being usable from plain HTML with no build step.\n\n## Related comparisons and docs\n\n- [SvGrid vs Grid.js](https://svgrid.com/compare/gridjs/)\n- [SvGrid vs Smart.Grid (Smart Web Components)](https://svgrid.com/compare/smart-grid/)\n- [SvGrid vs AG Grid (community + enterprise)](https://svgrid.com/compare/ag-grid/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Cell components](https://svgrid.com/docs/help/cells/cell-components/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- tabulator-readme: MIT; a vanilla JavaScript library that builds interactive tables from HTML tables, arrays or JSON, with support for React, Angular and Vue; installed as tabulator-tables (checked 12 Sep 2026) https://github.com/olifolkerd/tabulator\n"
8544
8694
  },
8545
8695
  {
8546
8696
  "slug": "compare/tanstack-table",
8547
8697
  "path": "docs/_data/comparisons/tanstack-table.json",
8548
8698
  "title": "SvGrid vs TanStack Table (Svelte)",
8549
8699
  "section": "Comparisons",
8550
- "markdown": "# SvGrid vs TanStack Table (Svelte)\n\nCanonical URL: https://svgrid.com/compare/tanstack-table/\nFacts verified: 2026-09-12\nCompetitor package: @tanstack/svelte-table\nCompetitor site: https://tanstack.com/table/latest\n\nTanStack Table is the headless table engine with adapters for React, Vue, Svelte, Solid, Qwik and Lit; you bring the markup.\n\n## Verdict\n\nThe closest peer to SvGrid's headless core. SvGrid ships a rendered component on top of the same kind of engine, in Svelte 5 runes; TanStack stays framework-agnostic and asks you to build and maintain the DOM, the virtualizer, the filter menus and the editors yourself.\n\nMigration guide: moving from TanStack Table (Svelte) to SvGrid: https://svgrid.com/docs/help/migrating-from-tanstack-table/\n\n## At a glance\n\n| Fact | SvGrid | TanStack Table (Svelte) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 9.2.4 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 28 Aug 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Yes (peer svelte ^5.0.0) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 231,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 36.3 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 30 Oct 2026 |\n| Frameworks | Svelte 5 | Svelte, React, Vue, Solid, Qwik, Lit | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; @tanstack/svelte-table 9.2.4 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nTanStack Table is the canonical headless table library: it provides the data pipeline (filter, sort, group, expand, paginate, select) and leaves the markup to you. The v9 line ships a Svelte adapter, @tanstack/svelte-table, whose peer dependency range is Svelte 5, with createTable and getters for reactive data instead of the stores the v8 adapter used.\n\nSvGrid covers the same headless surface (createSvGrid, row models, a features object) and adds a full render component with virtualization, Excel-style filters, inline editing, cell-range selection with a fill handle, grouping with aggregation, master/detail, a server-side row model and integrated charts, all in the MIT package.\n\n## Looking for a TanStack Table alternative for Svelte?\n\nPeople arrive here wanting less glue code, and that is the trade: you keep a headless engine with row models and composable features, and you stop hand-building the DOM, the virtualizer, the filter menus and the editors. If you need one table engine across React and Svelte, stay where you are; that portability is exactly what SvGrid gives up.\n\n## What they have in common\n\n- Headless-first architecture with row-model factories and a features object.\n- Composable features: sorting, filtering, grouping, pagination, expansion, selection.\n- TypeScript-first, MIT-licensed, with paid support available from the maintainers.\n- A createTable / createSvGrid entry point that takes columns, data and features.\n- Svelte 5 in both: runes in SvGrid, a Svelte 5 peer range in the TanStack adapter.\n\n## Where SvGrid is stronger\n\n- Ships <SvGrid />: a production render component with virtualization, Excel-style filters, cell-range selection, inline editing, grouping, master/detail and pagination. With TanStack Table you build all of this.\n- The headless core is written in Svelte 5 runes; the TanStack adapter wraps a framework-agnostic core.\n- An imperative API (SvGridApi) for adding rows, setting filters and mutating columns from outside the component.\n- A gallery of runnable examples that covers every feature, and per-feature docs pages with embedded demos.\n- In-grid AI helpers free in @svgrid/grid, and @svgrid/mcp so assistants fetch real example sources and can check the code they write.\n- A paid pack with Excel, PDF and print output, import, pivot tables and support.\n\n## Where TanStack Table (Svelte) is stronger\n\n- A far larger community; the At a glance table has the download counts side by side.\n- Multi-framework parity: if your shop has React, Vue and Svelte apps, the API stays consistent.\n- A smaller bundle when all you want is the engine; the At a glance table has both measured sizes.\n- Framework-specific documentation for each adapter and years of production use in large companies.\n- Enterprise Support as private consulting, and sponsor perks such as priority issue requests.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | TanStack Table (Svelte) |\n| --- | --- | --- |\n| Headless engine | Yes - createSvGrid | Yes - createTable |\n| Render component (drop-in) | Yes - <SvGrid /> | No - bring your own markup |\n| Svelte 5 | Yes - runes throughout | Yes - the adapter's peer range is Svelte 5 |\n| Row virtualization | Yes - built in | Partial - pair with @tanstack/svelte-virtual |\n| Column virtualization | Yes - built in | Partial - pair with @tanstack/svelte-virtual |\n| Excel-style filter menu | Yes - built in | No - filtering logic only; the UI is yours |\n| Inline editing | Yes - enableInlineEditing | No - bring your own |\n| Cell-range selection and clipboard | Yes - enableCellSelection, fill handle | No - bring your own |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - createServerDataSource: page or infinite block scroll | Yes - manual sorting, filtering and pagination flags |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - the engine has no server row model; the app fetches per group |\n| Master/detail and tree | Yes | Yes - expansion and subRows |\n| Grouping with aggregation | Yes - engine and rendered group rows | Yes - engine only |\n| Integrated charts | Yes - SvGridChart | No - not part of a headless engine |\n| WAI-ARIA helpers | Yes - exported, and applied by <SvGrid /> | Partial - your markup, your ARIA |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not in the docs |\n| Multi-framework support | No - Svelte only | Yes - React, Vue, Svelte, Solid, Qwik, Lit |\n| Paid support tier | Yes - with @svgrid/enterprise, per developer per year | Yes - Enterprise Support (private consulting) and sponsor perks such as priority issues |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, @tanstack/svelte-table 9.2.4. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | TanStack Table (Svelte) |\n| --- | --- | --- |\n| Mount | 30.7 ms | 170.2 ms |\n| Sort, text column | 77.4 ms | 360.9 ms |\n| Sort, numeric column | 32.8 ms | 178.2 ms |\n| Filter, one column (indicative only) | 34.5 ms | 51.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.3 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 563.4 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 27 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\nTanStack Table renders nothing, so its adapter draws the row model through a minimal fixed-height windowed table with no virtualizer library, filter UI or editors; the numbers are the engine plus that DOM.\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid that uses runes idiomatically, headless or rendered.\n- You want a drop-in <SvGrid /> with virtualization, filters, editing and selection working in one prop pass.\n- You want AI tools to give accurate answers about your grid through MCP, and to have their code checked.\n- You want paid support available without switching libraries later.\n\n## When to choose TanStack Table (Svelte)\n\n- You ship to multiple frameworks (React, Vue, Svelte) and want one API across them.\n- You explicitly want a headless library and intend to build your own render layer.\n- You want the smallest possible engine and the largest possible community.\n- A shadcn-svelte data table built on TanStack already does what you need.\n\n## Migration effort\n\nEstimated effort: About 30 minutes per read-only grid, 2-4 hours for editing-heavy grids.\n\nWhat you give up:\n\n- One table engine across React, Vue, Svelte, Solid, Qwik and Lit.\n- The smallest engine-only bundle; the At a glance table has both measured sizes.\n- The TanStack ecosystem around the table: Virtual, Query and the shadcn-svelte data table recipe.\n\nMigration guide: moving from TanStack Table (Svelte) to SvGrid: https://svgrid.com/docs/help/migrating-from-tanstack-table/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nIf you build across React, Vue and Svelte and want one headless API, TanStack Table is the safer bet. If you are committed to Svelte 5 and want virtualization, Excel-style filters, editing and selection out of the box, SvGrid gets you there with far less code, and you keep a headless core when you need it.\n\n## Frequently asked questions\n\n### Is SvGrid better than TanStack Table for Svelte?\n\nFor a Svelte 5 app, SvGrid is usually the faster path: it ships a virtualized render component with built-in filters, editing and accessibility, so there is no DOM layer to write. The TanStack Svelte adapter is Svelte 5 in its v9 line, but it is headless by design; you still build and maintain the table, virtualization and editing UI. TanStack wins if you need one API across several frameworks, or if owning that markup is the point.\n\n### Can I keep a headless setup like TanStack Table?\n\nYes. createSvGrid plus the row-model factories is a headless engine; you can drive your own markup exactly as with TanStack and adopt the SvGrid component only where you want it. The headless docs and the headless demos on this page show both.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The @tanstack/svelte-table package on npm declares a Svelte 5 peer range in its v9 line and its examples pass data through getters rather than stores. The At a glance table shows the version and the peer range as read from the registry.\n\n### How long is a TanStack Table to SvGrid migration?\n\nAbout thirty minutes for a read-only grid and two to four hours for editing-heavy ones. The row-model concepts map almost one to one; the migration guide walks through createTable to createSvGrid, the features object and the rendering options.\n\n### Which is smaller, TanStack Table or SvGrid?\n\nThe TanStack adapter, as an engine with no rendering. The At a glance table has both packages measured the same way on the same date. Add what you would write on top of TanStack (a virtualizer, filter UI, editors) before comparing, since that is what the extra size in SvGrid is.\n\n### Is SvGrid a good TanStack Table alternative for Svelte?\n\nPeople arrive here wanting less glue code, and that is the trade: you keep a headless engine with row models and composable features, and you stop hand-building the DOM, the virtualizer, the filter menus and the editors. If you need one table engine across React and Svelte, stay where you are; that portability is exactly what SvGrid gives up.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n- [Server-side data (load on demand)](https://svgrid.com/docs/help/headless/server-side/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- tanstack-svelte: The Svelte adapter is headless: build your own markup from the table instance's state and APIs; createTable takes features, columns and data through a getter; adapters exist for React, Vue, Solid, Qwik, Lit and Svelte (checked 12 Sep 2026) https://tanstack.com/table/latest/docs/framework/svelte/overview\n- tanstack-npm: The latest version's peerDependencies declare svelte ^5.0.0; licence MIT (checked 12 Sep 2026) https://www.npmjs.com/package/@tanstack/svelte-table\n- tanstack-home: Sponsor-supported with gold, silver and bronze sponsors; sponsors get private discord channels, priority issue requests and direct support; an Enterprise Support tier offers private consulting and expert support; no licence for the table is sold (checked 12 Sep 2026) https://tanstack.com/table/latest\n"
8700
+ "markdown": "# SvGrid vs TanStack Table (Svelte)\n\nCanonical URL: https://svgrid.com/compare/tanstack-table/\nFacts verified: 2026-09-12\nCompetitor package: @tanstack/svelte-table\nCompetitor site: https://tanstack.com/table/latest\n\nTanStack Table is the headless table engine with adapters for React, Vue, Svelte, Solid, Qwik and Lit; you bring the markup.\n\n## Verdict\n\nThe closest peer to SvGrid's headless core. SvGrid ships a rendered component on top of the same kind of engine, in Svelte 5 runes; TanStack stays framework-agnostic and asks you to build and maintain the DOM, the virtualizer, the filter menus and the editors yourself.\n\nMigration guide: moving from TanStack Table (Svelte) to SvGrid: https://svgrid.com/docs/help/migrating-from-tanstack-table/\n\n## At a glance\n\n| Fact | SvGrid | TanStack Table (Svelte) | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 9.2.4 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 28 Aug 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Yes (peer svelte ^5.0.0) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 231,000 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 36.3 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 1 Nov 2026 |\n| Frameworks | Svelte 5 | Svelte, React, Vue, Solid, Qwik, Lit | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | TanStack Table is MIT and free; tanstack.com is sponsor-supported and offers Enterprise Support as private consulting and expert support, with no licence sold for the table | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; @tanstack/svelte-table 9.2.4 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\nTanStack Table is the canonical headless table library: it provides the data pipeline (filter, sort, group, expand, paginate, select) and leaves the markup to you. The v9 line ships a Svelte adapter, @tanstack/svelte-table, whose peer dependency range is Svelte 5, with createTable and getters for reactive data instead of the stores the v8 adapter used.\n\nSvGrid covers the same headless surface (createSvGrid, row models, a features object) and adds a full render component with virtualization, Excel-style filters, inline editing, cell-range selection with a fill handle, grouping with aggregation, master/detail, a server-side row model and integrated charts, all in the MIT package.\n\n## Looking for a TanStack Table alternative for Svelte?\n\nPeople arrive here wanting less glue code, and that is the trade: you keep a headless engine with row models and composable features, and you stop hand-building the DOM, the virtualizer, the filter menus and the editors. If you need one table engine across React and Svelte, stay where you are; that portability is exactly what SvGrid gives up.\n\n## What they have in common\n\n- Headless-first architecture with row-model factories and a features object.\n- Composable features: sorting, filtering, grouping, pagination, expansion, selection.\n- TypeScript-first, MIT-licensed, with paid support available from the maintainers.\n- A createTable / createSvGrid entry point that takes columns, data and features.\n- Svelte 5 in both: runes in SvGrid, a Svelte 5 peer range in the TanStack adapter.\n\n## Where SvGrid is stronger\n\n- Ships <SvGrid />: a production render component with virtualization, Excel-style filters, cell-range selection, inline editing, grouping, master/detail and pagination. With TanStack Table you build all of this.\n- The headless core is written in Svelte 5 runes; the TanStack adapter wraps a framework-agnostic core.\n- An imperative API (SvGridApi) for adding rows, setting filters and mutating columns from outside the component.\n- A gallery of runnable examples that covers every feature, and per-feature docs pages with embedded demos.\n- In-grid AI helpers free in @svgrid/grid, and @svgrid/mcp so assistants fetch real example sources and can check the code they write.\n- A paid pack with Excel, PDF and print output, import, pivot tables and support.\n\n## Where TanStack Table (Svelte) is stronger\n\n- A far larger community; the At a glance table has the download counts side by side.\n- Multi-framework parity: if your shop has React, Vue and Svelte apps, the API stays consistent.\n- A smaller bundle when all you want is the engine; the At a glance table has both measured sizes.\n- Framework-specific documentation for each adapter and years of production use in large companies.\n- Enterprise Support as private consulting, and sponsor perks such as priority issue requests.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | TanStack Table (Svelte) |\n| --- | --- | --- |\n| Headless engine | Yes - createSvGrid | Yes - createTable |\n| Render component (drop-in) | Yes - <SvGrid /> | No - bring your own markup |\n| Svelte 5 | Yes - runes throughout | Yes - the adapter's peer range is Svelte 5 |\n| Row virtualization | Yes - built in | Partial - pair with @tanstack/svelte-virtual |\n| Column virtualization | Yes - built in | Partial - pair with @tanstack/svelte-virtual |\n| Excel-style filter menu | Yes - built in | No - filtering logic only; the UI is yours |\n| Inline editing | Yes - enableInlineEditing | No - bring your own |\n| Cell-range selection and clipboard | Yes - enableCellSelection, fill handle | No - bring your own |\n| Server-side data, flat (sort, filter, paging, infinite scroll) | Yes - createServerDataSource: page or infinite block scroll | Yes - manual sorting, filtering and pagination flags |\n| Server-side row model (lazy grouping, tree, pivot, transactions, select-all across unloaded rows) | Paid tier - @svgrid/enterprise | No - the engine has no server row model; the app fetches per group |\n| Master/detail and tree | Yes | Yes - expansion and subRows |\n| Grouping with aggregation | Yes - engine and rendered group rows | Yes - engine only |\n| Integrated charts | Yes - SvGridChart | No - not part of a headless engine |\n| WAI-ARIA helpers | Yes - exported, and applied by <SvGrid /> | Partial - your markup, your ARIA |\n| In-grid AI helpers and MCP server | Yes - helpers free in @svgrid/grid; @svgrid/mcp, MIT | No - not in the docs |\n| Multi-framework support | No - Svelte only | Yes - React, Vue, Svelte, Solid, Qwik, Lit |\n| Paid support tier | Yes - with @svgrid/enterprise, per developer per year | Yes - Enterprise Support (private consulting) and sponsor perks such as priority issues |\n\n## Measured performance\n\nMeasured 28 Oct 2026 with the harness in the repository (pnpm bench:compare): 100,000 rows, fastest of 3 samples per operation, each grid in a fresh page, Chromium through Playwright, headless, on win32 10.0.26200 x64, Intel(R) Core(TM) Ultra 7 255U; a developer workstation, not a dedicated bench rig. Versions: @svgrid/grid 3.0.25, @tanstack/svelte-table 9.2.4. Lower is better. Tick: 1,000 of the rows replaced per tick with a new amount, the grid sorted by amount, on the update path each grid provides, timed until the changed cells paint; 180 ticks after 10 to warm up.\n\n| Operation | SvGrid | TanStack Table (Svelte) |\n| --- | --- | --- |\n| Mount | 30.7 ms | 170.2 ms |\n| Sort, text column | 77.4 ms | 360.9 ms |\n| Sort, numeric column | 32.8 ms | 178.2 ms |\n| Filter, one column (indicative only) | 34.5 ms | 51.1 ms |\n| Scroll, p95 frame | 34.3 ms | 34.3 ms |\n| Live tick, 1,000 rows replaced, sorted by that column, p95 | 48.6 ms | 563.4 ms |\n| Ticks over one 60 Hz frame, of 180 | 115 | 180 |\n| Rows kept in the DOM (virtualization on) | 36 | 27 |\n\nThe filter row is not like for like: each grid is driven through its own single-column filter API, and the amount of work differs. The comparison guide explains the method, what is left out and why.\n\nTanStack Table renders nothing, so its adapter draws the row model through a minimal fixed-height windowed table with no virtualizer library, filter UI or editors; the numbers are the engine plus that DOM.\n\n## When to choose SvGrid\n\n- You are on Svelte 5 and want a grid that uses runes idiomatically, headless or rendered.\n- You want a drop-in <SvGrid /> with virtualization, filters, editing and selection working in one prop pass.\n- You want AI tools to give accurate answers about your grid through MCP, and to have their code checked.\n- You want paid support available without switching libraries later.\n\n## When to choose TanStack Table (Svelte)\n\n- You ship to multiple frameworks (React, Vue, Svelte) and want one API across them.\n- You explicitly want a headless library and intend to build your own render layer.\n- You want the smallest possible engine and the largest possible community.\n- A shadcn-svelte data table built on TanStack already does what you need.\n\n## Migration effort\n\nEstimated effort: About 30 minutes per read-only grid, 2-4 hours for editing-heavy grids.\n\nWhat you give up:\n\n- One table engine across React, Vue, Svelte, Solid, Qwik and Lit.\n- The smallest engine-only bundle; the At a glance table has both measured sizes.\n- The TanStack ecosystem around the table: Virtual, Query and the shadcn-svelte data table recipe.\n\nMigration guide: moving from TanStack Table (Svelte) to SvGrid: https://svgrid.com/docs/help/migrating-from-tanstack-table/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nIf you build across React, Vue and Svelte and want one headless API, TanStack Table is the safer bet. If you are committed to Svelte 5 and want virtualization, Excel-style filters, editing and selection out of the box, SvGrid gets you there with far less code, and you keep a headless core when you need it.\n\n## Frequently asked questions\n\n### Is SvGrid better than TanStack Table for Svelte?\n\nFor a Svelte 5 app, SvGrid is usually the faster path: it ships a virtualized render component with built-in filters, editing and accessibility, so there is no DOM layer to write. The TanStack Svelte adapter is Svelte 5 in its v9 line, but it is headless by design; you still build and maintain the table, virtualization and editing UI. TanStack wins if you need one API across several frameworks, or if owning that markup is the point.\n\n### Can I keep a headless setup like TanStack Table?\n\nYes. createSvGrid plus the row-model factories is a headless engine; you can drive your own markup exactly as with TanStack and adopt the SvGrid component only where you want it. The headless docs and the headless demos on this page show both.\n\n### Does the TanStack Svelte adapter support Svelte 5?\n\nYes. The @tanstack/svelte-table package on npm declares a Svelte 5 peer range in its v9 line and its examples pass data through getters rather than stores. The At a glance table shows the version and the peer range as read from the registry.\n\n### How long is a TanStack Table to SvGrid migration?\n\nAbout thirty minutes for a read-only grid and two to four hours for editing-heavy ones. The row-model concepts map almost one to one; the migration guide walks through createTable to createSvGrid, the features object and the rendering options.\n\n### Which is smaller, TanStack Table or SvGrid?\n\nThe TanStack adapter, as an engine with no rendering. The At a glance table has both packages measured the same way on the same date. Add what you would write on top of TanStack (a virtualizer, filter UI, editors) before comparing, since that is what the extra size in SvGrid is.\n\n### Is SvGrid a good TanStack Table alternative for Svelte?\n\nPeople arrive here wanting less glue code, and that is the trade: you keep a headless engine with row models and composable features, and you stop hand-building the DOM, the virtualizer, the filter menus and the editors. If you need one table engine across React and Svelte, stay where you are; that portability is exactly what SvGrid gives up.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs SVAR Svelte DataGrid](https://svgrid.com/compare/svar-svelte-datagrid/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n- [Server-side data (load on demand)](https://svgrid.com/docs/help/headless/server-side/)\n- [Headless virtualization](https://svgrid.com/docs/help/headless/virtualization/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- tanstack-svelte: The Svelte adapter is headless: build your own markup from the table instance's state and APIs; createTable takes features, columns and data through a getter; adapters exist for React, Vue, Solid, Qwik, Lit and Svelte (checked 12 Sep 2026) https://tanstack.com/table/latest/docs/framework/svelte/overview\n- tanstack-npm: The latest version's peerDependencies declare svelte ^5.0.0; licence MIT (checked 12 Sep 2026) https://www.npmjs.com/package/@tanstack/svelte-table\n- tanstack-home: Sponsor-supported with gold, silver and bronze sponsors; sponsors get private discord channels, priority issue requests and direct support; an Enterprise Support tier offers private consulting and expert support; no licence for the table is sold (checked 12 Sep 2026) https://tanstack.com/table/latest\n"
8551
8701
  },
8552
8702
  {
8553
8703
  "slug": "compare/vincjo-datatables",
8554
8704
  "path": "docs/_data/comparisons/vincjo-datatables.json",
8555
8705
  "title": "SvGrid vs @vincjo/datatables",
8556
8706
  "section": "Comparisons",
8557
- "markdown": "# SvGrid vs @vincjo/datatables\n\nCanonical URL: https://svgrid.com/compare/vincjo-datatables/\nFacts verified: 2026-09-12\nCompetitor package: @vincjo/datatables\nCompetitor site: https://github.com/vincjo/datatables\n\n@vincjo/datatables is a lightweight, headless Svelte datatable helper for sorting, filtering, and paginating your own markup.\n\n## Verdict\n\n@vincjo/datatables is a great minimal pick when you want to keep your own table markup and just need sort / filter / paginate. SvGrid is the fuller grid - virtualization, Excel filters, editing, a render component - for heavier apps.\n\nMigration guide: moving from @vincjo/datatables to SvGrid: https://svgrid.com/docs/help/migrating-from-vincjo-datatables/\n\n## At a glance\n\n| Fact | SvGrid | @vincjo/datatables | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 2.8.1 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 4 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Yes (peer svelte ^5.56.1) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 72,800 | 12 Sep 2026 |\n| Bundle, minified + gzip | 100.0 KB JS + 11.3 KB CSS | 10.2 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 30 Oct 2026 |\n| Frameworks | Svelte 5 | Svelte | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | @vincjo/datatables is MIT on npm and free; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.30 measured 30 Oct 2026 with packages/grid/scripts/measure-size.mjs; @vincjo/datatables 2.8.1 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\n@vincjo/datatables gives you a small, ergonomic handler that wraps your data with reactive sorting, filtering, and pagination while you keep full control of the markup. It is MIT-licensed and popular for its simplicity.\n\nSvGrid scales further up the curve: it keeps a headless engine but also ships a virtualized render component, an Excel-style filter menu, inline editing, cell selection, and an imperative API - for when a hand-rolled table stops being enough.\n\n## Looking for a @vincjo/datatables alternative for Svelte?\n\nIt is a helper for your own markup rather than a grid, which is exactly right until you need virtualization, inline editing or column pinning and start building them yourself. Moving to SvGrid keeps the headless option and adds those. If your table is a few hundred rows of your own HTML, staying put is the smaller dependency.\n\n## What they have in common\n\n- Svelte-native, not a port.\n- Headless-friendly: you can drive your own markup.\n- MIT-licensed.\n- Client- and server-side data modes.\n\n## Where SvGrid is stronger\n\n- Built-in virtualized render component - no need to author the table.\n- Excel-style filter menu, inline editing, and cell-range selection.\n- Row + column virtualization for large datasets.\n- Imperative SvGridApi + @svgrid/mcp MCP server.\n- Optional Enterprise pack for export, import, pivot, and AI.\n\n## Where @vincjo/datatables is stronger\n\n- Much smaller surface and bundle if all you need is sort / filter / paginate.\n- You keep 100% control of the table markup with zero render opinions.\n- Faster to learn for a simple table.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | @vincjo/datatables |\n| --- | --- | --- |\n| Svelte native | Yes | Yes - Svelte 5 peer range |\n| Render component | Yes - <SvGrid /> | No - headless, you render the markup |\n| Virtualization | Yes | No |\n| Excel-style filters | Yes | Partial - Basic filtering |\n| Inline editing | Yes | No - BYO |\n| Cell selection + copy | Yes | No - BYO |\n| Grouping / tree / master-detail | Yes | No |\n| Footprint for a simple table | Partial - Larger | Yes - Tiny |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need virtualization, editing, or Excel-style filtering.\n- You want a render component instead of hand-authoring the table.\n- You expect the grid to grow into grouping, tree, or master/detail.\n\n## When to choose @vincjo/datatables\n\n- You only need sort / filter / paginate over a small dataset.\n- You want to keep full control of your own table markup.\n- You want the smallest possible bundle for a simple table.\n\n## Migration effort\n\nEstimated effort: 30 minutes to 2 hours per table.\n\nWhat you give up:\n\n- A tiny dependency-free helper when a sortable, filterable list is all you need.\n- Full control of the markup without opting into a headless mode.\n\nMigration guide: moving from @vincjo/datatables to SvGrid: https://svgrid.com/docs/help/migrating-from-vincjo-datatables/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nFor a small sort/filter/paginate list you keep full control over, @vincjo/datatables is delightfully light. The moment you need virtualization, Excel-style filters, editing, or grouping, SvGrid is the grid that already has them.\n\n## Frequently asked questions\n\n### SvGrid vs @vincjo/datatables - which to pick?\n\nPick @vincjo/datatables for a small, markup-controlled table; pick SvGrid when you need virtualization, editing, filters, or grouping. Both are MIT and Svelte-native.\n\n### Is @vincjo/datatables lighter than SvGrid?\n\nYes, for a simple table it is smaller. SvGrid carries more because it ships a virtualized render component and a full feature set.\n\n### Can SvGrid be headless like @vincjo/datatables?\n\nYes - its headless core lets you keep your own markup, the same way @vincjo/datatables does.\n\n### Is SvGrid a good @vincjo/datatables alternative for Svelte?\n\nIt is a helper for your own markup rather than a grid, which is exactly right until you need virtualization, inline editing or column pinning and start building them yourself. Moving to SvGrid keeps the headless option and adds those. If your table is a few hundred rows of your own HTML, staying put is the smaller dependency.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- vincjo-docs: A headless, SSR-friendly toolkit with no dependency: sort, filter, search and pagination in client-side and server-side modes; you render the markup (checked 12 Sep 2026) https://vincjo.fr/datatables/\n- vincjo-npm: MIT; the latest version declares a Svelte 5 peer range (checked 12 Sep 2026) https://www.npmjs.com/package/@vincjo/datatables\n"
8707
+ "markdown": "# SvGrid vs @vincjo/datatables\n\nCanonical URL: https://svgrid.com/compare/vincjo-datatables/\nFacts verified: 2026-09-12\nCompetitor package: @vincjo/datatables\nCompetitor site: https://github.com/vincjo/datatables\n\n@vincjo/datatables is a lightweight, headless Svelte datatable helper for sorting, filtering, and paginating your own markup.\n\n## Verdict\n\n@vincjo/datatables is a great minimal pick when you want to keep your own table markup and just need sort / filter / paginate. SvGrid is the fuller grid - virtualization, Excel filters, editing, a render component - for heavier apps.\n\nMigration guide: moving from @vincjo/datatables to SvGrid: https://svgrid.com/docs/help/migrating-from-vincjo-datatables/\n\n## At a glance\n\n| Fact | SvGrid | @vincjo/datatables | Checked |\n| --- | --- | --- | --- |\n| Latest version | 3.0.3 | 2.8.1 | 12 Sep 2026 |\n| Licence field on npm | MIT | MIT | 12 Sep 2026 |\n| Last published | 11 Sep 2026 | 4 Jun 2026 | 12 Sep 2026 |\n| Svelte 5 support | Native (Svelte 5 runes) | Yes (peer svelte ^5.56.1) | 12 Sep 2026 |\n| npm downloads, 30 days to 10 Sep 2026 | 16,900 | 72,800 | 12 Sep 2026 |\n| Bundle, minified + gzip | 99.8 KB JS + 11.3 KB CSS | 10.2 KB JS, no separate stylesheet, svelte external | 12 Sep 2026 |\n| Engine alone, minified + gzip | 3.2 KB JS, no separate stylesheet (`createSvGrid` from `@svgrid/grid/core`) | the row above; the package is the engine | 1 Nov 2026 |\n| Frameworks | Svelte 5 | Svelte | 12 Sep 2026 |\n| Pricing | MIT core; @svgrid/enterprise from $299 per developer per year (Indie, under $1M revenue), $599 for Enterprise | @vincjo/datatables is MIT on npm and free; no licence is sold | 12 Sep 2026 |\n\nBundle sizes: each package built alone with Vite in library mode, minified, gzip level 9, Svelte kept external where a package uses it (it is a peer dependency). SvGrid 3.0.31 measured 1 Nov 2026 with packages/grid/scripts/measure-size.mjs; @vincjo/datatables 2.8.1 entry `whole package` measured 12 Sep 2026 with packages/grid/scripts/measure-competitor-bundles.mjs.\n\n## Overview\n\n@vincjo/datatables gives you a small, ergonomic handler that wraps your data with reactive sorting, filtering, and pagination while you keep full control of the markup. It is MIT-licensed and popular for its simplicity.\n\nSvGrid scales further up the curve: it keeps a headless engine but also ships a virtualized render component, an Excel-style filter menu, inline editing, cell selection, and an imperative API - for when a hand-rolled table stops being enough.\n\n## Looking for a @vincjo/datatables alternative for Svelte?\n\nIt is a helper for your own markup rather than a grid, which is exactly right until you need virtualization, inline editing or column pinning and start building them yourself. Moving to SvGrid keeps the headless option and adds those. If your table is a few hundred rows of your own HTML, staying put is the smaller dependency.\n\n## What they have in common\n\n- Svelte-native, not a port.\n- Headless-friendly: you can drive your own markup.\n- MIT-licensed.\n- Client- and server-side data modes.\n\n## Where SvGrid is stronger\n\n- Built-in virtualized render component - no need to author the table.\n- Excel-style filter menu, inline editing, and cell-range selection.\n- Row + column virtualization for large datasets.\n- Imperative SvGridApi + @svgrid/mcp MCP server.\n- Optional Enterprise pack for export, import, pivot, and AI.\n\n## Where @vincjo/datatables is stronger\n\n- Much smaller surface and bundle if all you need is sort / filter / paginate.\n- You keep 100% control of the table markup with zero render opinions.\n- Faster to learn for a simple table.\n\n## Feature by feature\n\nYes: shipped in the package. Partial: needs extra work or a companion package. Paid tier: only in a paid edition. No: not available. n/a: does not apply.\n\n| Feature | SvGrid | @vincjo/datatables |\n| --- | --- | --- |\n| Svelte native | Yes | Yes - Svelte 5 peer range |\n| Render component | Yes - <SvGrid /> | No - headless, you render the markup |\n| Virtualization | Yes | No |\n| Excel-style filters | Yes | Partial - Basic filtering |\n| Inline editing | Yes | No - BYO |\n| Cell selection + copy | Yes | No - BYO |\n| Grouping / tree / master-detail | Yes | No |\n| Footprint for a simple table | Partial - Larger | Yes - Tiny |\n| AI / MCP integration | Yes | No |\n\n## When to choose SvGrid\n\n- You need virtualization, editing, or Excel-style filtering.\n- You want a render component instead of hand-authoring the table.\n- You expect the grid to grow into grouping, tree, or master/detail.\n\n## When to choose @vincjo/datatables\n\n- You only need sort / filter / paginate over a small dataset.\n- You want to keep full control of your own table markup.\n- You want the smallest possible bundle for a simple table.\n\n## Migration effort\n\nEstimated effort: 30 minutes to 2 hours per table.\n\nWhat you give up:\n\n- A tiny dependency-free helper when a sortable, filterable list is all you need.\n- Full control of the markup without opting into a headless mode.\n\nMigration guide: moving from @vincjo/datatables to SvGrid: https://svgrid.com/docs/help/migrating-from-vincjo-datatables/\n\n## Live example\n\nHeadless Table: open it in the gallery for the source and the full-size version. https://svgrid.com/demos/186-headless-table/\n\n## The bottom line\n\nFor a small sort/filter/paginate list you keep full control over, @vincjo/datatables is delightfully light. The moment you need virtualization, Excel-style filters, editing, or grouping, SvGrid is the grid that already has them.\n\n## Frequently asked questions\n\n### SvGrid vs @vincjo/datatables - which to pick?\n\nPick @vincjo/datatables for a small, markup-controlled table; pick SvGrid when you need virtualization, editing, filters, or grouping. Both are MIT and Svelte-native.\n\n### Is @vincjo/datatables lighter than SvGrid?\n\nYes, for a simple table it is smaller. SvGrid carries more because it ships a virtualized render component and a full feature set.\n\n### Can SvGrid be headless like @vincjo/datatables?\n\nYes - its headless core lets you keep your own markup, the same way @vincjo/datatables does.\n\n### Is SvGrid a good @vincjo/datatables alternative for Svelte?\n\nIt is a helper for your own markup rather than a grid, which is exactly right until you need virtualization, inline editing or column pinning and start building them yourself. Moving to SvGrid keeps the headless option and adds those. If your table is a few hundred rows of your own HTML, staying put is the smaller dependency.\n\n## Related comparisons and docs\n\n- [SvGrid vs svelte-headless-table](https://svgrid.com/compare/svelte-headless-table/)\n- [SvGrid vs TanStack Table (Svelte)](https://svgrid.com/compare/tanstack-table/)\n- [SvGrid vs Flowbite / Skeleton / shadcn-svelte tables](https://svgrid.com/compare/svelte-ui-kit-tables/)\n- [Comparison: SvGrid vs AG Grid vs TanStack Table](https://svgrid.com/docs/help/comparison/)\n- [Build a table from scratch](https://svgrid.com/docs/help/headless/build-a-table/)\n\n## Sources and last verified\n\nEvery claim on this page was last checked on 12 Sep 2026. Versions, licences and download counts come from the npm registry; feature and pricing statements from the pages listed below.\n\n- vincjo-docs: A headless, SSR-friendly toolkit with no dependency: sort, filter, search and pagination in client-side and server-side modes; you render the markup (checked 12 Sep 2026) https://vincjo.fr/datatables/\n- vincjo-npm: MIT; the latest version declares a Svelte 5 peer range (checked 12 Sep 2026) https://www.npmjs.com/package/@vincjo/datatables\n"
8558
8708
  }
8559
8709
  ];
8560
8710
  export const apiReference = {
@@ -8631,8 +8781,8 @@ export const apiReference = {
8631
8781
  ]
8632
8782
  };
8633
8783
  export const apiSurface = {
8634
- "gridVersion": "3.0.31",
8635
- "enterpriseVersion": "3.1.34",
8784
+ "gridVersion": "3.0.32",
8785
+ "enterpriseVersion": "3.1.35",
8636
8786
  "grid": {
8637
8787
  "values": [
8638
8788
  "ALL_FILTER_OPERATORS",
@@ -10995,6 +11145,9 @@ export const apiSurface = {
10995
11145
  "@svgrid/enterprise/sheet",
10996
11146
  "@svgrid/enterprise/studio",
10997
11147
  "@svgrid/enterprise/wc",
11148
+ "@svgrid/enterprise/wc/base",
11149
+ "@svgrid/enterprise/wc/base/react",
11150
+ "@svgrid/enterprise/wc/base/vue",
10998
11151
  "@svgrid/enterprise/wc/react",
10999
11152
  "@svgrid/enterprise/wc/vue",
11000
11153
  "@svgrid/enterprise/worker"
@@ -11848,6 +12001,11 @@ export const apiSurface = {
11848
12001
  "optional": true,
11849
12002
  "type": "Record<string, unknown>"
11850
12003
  },
12004
+ {
12005
+ "name": "description",
12006
+ "optional": true,
12007
+ "type": "string"
12008
+ },
11851
12009
  {
11852
12010
  "name": "columns",
11853
12011
  "optional": true,
@@ -11983,6 +12141,16 @@ export const apiSurface = {
11983
12141
  "optional": true,
11984
12142
  "type": "(a: unknown, b: unknown, desc: boolean) => number"
11985
12143
  },
12144
+ {
12145
+ "name": "groupOrder",
12146
+ "optional": true,
12147
+ "type": "(a: unknown, b: unknown) => number"
12148
+ },
12149
+ {
12150
+ "name": "groupValue",
12151
+ "optional": true,
12152
+ "type": "(value: unknown) => unknown"
12153
+ },
11986
12154
  {
11987
12155
  "name": "aggregate",
11988
12156
  "optional": true,