@svgrid/mcp 3.0.47 → 3.0.48
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 +5 -5
- package/dist/preview.d.ts +1 -1
- package/dist/preview.js +1 -1
- package/package.json +2 -2
- package/server.json +2 -2
package/dist/data.js
CHANGED
|
@@ -5178,14 +5178,14 @@ export const docs = [
|
|
|
5178
5178
|
"path": "docs/help/base/automations.md",
|
|
5179
5179
|
"title": "Automations",
|
|
5180
5180
|
"section": "SvGrid Base",
|
|
5181
|
-
"markdown": "# Automations\n\nAn automation does something on its own when something happens to a\nrecord: a task set to Done ticks its Done box, a new request goes to Todo, a\nblocked task tells its owner, a button starts the work. Each table of a base\nhas its own, under \"Automations\" in the view bar.\n\n<div data-docs-demo=\"504-project-tracker\" data-height=\"680\"></div>\n\nIn the demo, set a task's Status to Done, press Start in the Kick off\ncolumn, or send the Request a task form, then open \"5 automations\" and look\nat Runs.\n\n\n\n## Add one\n\nOpen \"Automations\" in the view bar and press \"+ New automation\". The dialog\nhas three parts:\n\n- **When**: what sets it off.\n- **Only for records where**: a condition written with the view bar's\n filter, so it compares a select's option, a person, a linked record's name\n or \"within the past week\" the way the filter does. Leave it empty for\n every record.\n- **Do**: the actions, in order.\n\n\n\nEvery change is kept as you make it. \"Run now\" tries the automation on the\nrecord you pick, as if its trigger had happened.\n\n## When\n\n| Trigger | Runs |\n|---|---|\n| A record is created | When a record is added: \"+ Add row\", a form, a board lane, a calendar day, another automation. A record brought back by Restore or an undo of a delete is not created, and no rule runs for it |\n| A record changes | When a record is edited; pick fields to run only when one of them changes. A link made from the other table counts: adding a guest to an event from Guests changes the event's Guests field |\n| A record matches a condition | When a record starts to match the condition. It does not run again while the record keeps matching |\n| A form is sent | When a form view sends a record; pick the form, or any form of the table |\n| A button is pressed | When a Button field is pressed on a record |\n| At a scheduled time | Every day at 9, every Monday, every hour, or a cron expression: once for each record that matches the condition then, or once with no record |\n| A webhook is received | On the server: a request to the automation's own address, with no record. The body's values are `{webhook.name}` in the steps ([below](#a-webhook-starts-it)) |\n\nA paste or a fill that changes several cells of one record is one change to\nit. An undo or a redo is no change: it runs no automation.\n\n## Do\n\n| Action | What it does |\n|---|---|\n| Update the record | Sets fields of the record that set it off |\n| Create a record | Adds a record to any table of the base; \"Link it back\" fills a link field of the new record with the record that set it off |\n| Show a notice | A toast; `{Field name}` is that field of the record |\n| Color the record while it matches | Colors the whole row, or some fields, for as long as the record matches the condition |\n| Call a webhook | POSTs the record (or a body you write) to a URL: a team chat, your API. Secrets as `{secret:NAME}`, read on the server only |\n| Send an email | To, subject and text with field names; sent by the [server](#on-the-server) |\n| Send a Slack, Teams or Google Chat message | A message to a channel through the address its chat app gave; only that app's own addresses ([below](#chat-messages)) |\n| Send a text message (SMS or Viber) | A text to phone numbers, or a phone field, by SMS or by Viber; sent by the [server](#on-the-server) through your provider ([below](#text-messages)) |\n| Find records and, for each, do | Steps run on every record of a table that matches a condition ([below](#if-and-find-records)) |\n| If a condition holds, do | Then steps when the record matches, Otherwise steps when it does not |\n| Ask AI | A prompt with field names; the answer goes into a field, and is `{ai}` in the next steps ([below](#ask-ai)) |\n| Run a script | JavaScript in a sandbox in the browser, as Airtable's automation scripts ([below](#run-a-script)) |\n| Your own actions | Anything the app adds with `registerAutomationAction` |\n\nA webhook's URL, headers and body name fields in braces, and secrets as\n`{secret:NAME}`; leave the body empty to send the record as JSON. A secret is\nnamed only by the automation: what a record holds is data, so `{secret:NAME}`\ntyped into a field goes out as that text.\n\nFrom the server a webhook does not call private or local addresses (`localhost`,\n`10.x`, `192.168.x`, `169.254.169.254`, a name that resolves to one, an IPv6 form\nthat wraps one) and does not follow redirects. On Node it connects to the\naddresses it checked, so a name cannot answer one way for the check and another\nfor the call; a name that does not resolve is not sent. A `fetch` of your own\npassed to `createAutomationServer` gets the check but not that pin, and neither\ndoes a runtime with no sockets of its own. For a webhook on your own network, set\n`allowInternalWebhooks: true` on `createAutomationServer`.\n\n\n\n\nValues are written as the field shows them:\n\n| Field | Write |\n|---|---|\n| Single or multiple select | The option's name: `Done`, `Bug, Risk` |\n| Person | The person's name: `Ana Ruiz` |\n| Checkbox | `true` or `false` |\n| Number | `42`; in a percent field, `100%` |\n| Date | `2026-11-01`, `today`, `today+7`, `today-1`, `now` |\n| Link | A record's name, several with commas, or `{record}` for the record that set it off |\n| Any text | Text with fields in braces: `{Task} follow-up` |\n| Any field | Nothing, to clear it |\n\n## If and Find records\n\n\"If a condition holds\" runs its Then steps when the record matches the\ncondition, and its Otherwise steps when it does not. With no record (a\nschedule, a webhook) only an \"If\" with no condition runs Then.\n\n\"Find records and, for each, do\" reads the records of a table that match a\ncondition, at most the number you set (100, up to 1,000), and runs its steps\non each: in them `{Field}` is the found record's field, `{trigger.Field}` the\nfield of the record that set the automation off, and `{found}` how many were\nfound. \"Update the record\" there updates the found record.\n\n```ts\n{ type: 'repeat', table: 'tasks', condition: statusIs('Todo'), limit: 50, actions: [\n { type: 'updateRecord', values: { note: 'Waiting on {trigger.Task}' } },\n] }\n{ type: 'if', condition: statusIs('Done'), then: [{ type: 'notify', message: 'Shipped' }], else: [] }\n```\n\nA step can be inside an \"If\" or a \"Find records\", and one of those inside\nanother, but no deeper. A script or a color is a step of the automation\nitself only.\n\n## Chat messages\n\nPaste the address the chat app gives for its channel:\n\n| App | Where the address comes from | What is sent |\n|---|---|---|\n| Slack | Apps, Incoming Webhooks, Add to a channel (`https://hooks.slack.com/...`) | `{ \"text\": ... }` |\n| Microsoft Teams | The channel's Workflows, \"Post to a channel when a webhook request is received\" (`*.logic.azure.com`, `*.powerplatform.com`) | An Adaptive Card with the text |\n| Google Chat | The space's Apps and integrations, Webhooks (`https://chat.googleapis.com/...`) | `{ \"text\": ... }` |\n\nThe text names fields in braces. A message goes only to its app's own https\naddresses, so a chat step cannot be pointed at any other server; an address\nmay name a secret (`{secret:SLACK_HOOK}`) on the server.\n\n## Text messages\n\n\"Send a text message\" sends a text to the numbers in **To**: written with their\ncountry code (`+359 88 123 4567`), or a phone field in braces (`{Phone}`),\nseveral apart with commas. The message names fields in braces. **Send by** is\nSMS, or Viber, which your provider may send as an SMS to a phone that is not on\nViber.\n\nThe browser has no account to send texts with, so this step runs on the\n[server](#on-the-server): give `createAutomationServer` a `sendText`, which gets\n`{ to, text, channel }` and calls your SMS or Viber provider.\n\n```ts\nimport { createAutomationServer, type BaseTable } from '@svgrid/enterprise/base'\n\n// Your tables, and your SMS or Viber provider's client.\ndeclare const tables: BaseTable[]\ndeclare const texts: { send: (m: { phone: string; text: string; viber: boolean }) => Promise<unknown> }\n\nexport const automations = createAutomationServer({\n tables,\n sendText: ({ to, text, channel }) => Promise.all(to.map((phone) => texts.send({ phone, text, viber: channel === 'viber' }))),\n})\n```\n\n## Ask AI\n\nThe prompt names fields in braces: `Write a two-line summary of {Name} for\nthe weekly report.` The answer goes into a text field of the record when you\npick one, and is `{ai}` in the steps after it. In the page the model is the\nrunner's `ai` option, on the server `createAutomationServer({ ai })`: a\nfunction from a prompt to the answer, behind which you call your model, with\nyour key on your server.\n\n```ts\ncreateAutomationServer({ tables, ai: async (prompt) => (await anthropic.messages.create({ model, max_tokens: 1000, messages: [{ role: 'user', content: prompt }] })).content[0].text })\n```\n\n## Run a script\n\nA script is JavaScript with Airtable's automation scripting objects:\n\n```js\nconst { recordId, Status } = input.config() // the record's fields, as text, by name\nconst tasks = base.getTable('Tasks')\nconst query = await tasks.selectRecordsAsync()\nfor (const r of query.records) {\n if (r.getCellValueAsString('Status') === 'Blocked') await tasks.updateRecordAsync(r.id, { Owner: 'Ana Ruiz' })\n}\noutput.set('blocked', query.records.length) // {script.blocked} in the next steps\n```\n\n`base.getTable(name)` has `selectRecordsAsync`, `updateRecordAsync`,\n`updateRecordsAsync`, `createRecordAsync`, `createRecordsAsync`,\n`deleteRecordAsync` and `deleteRecordsAsync`; a record has `id`, `name`,\n`getCellValue` and `getCellValueAsString`. Values are written as the field\nshows them, as in \"Update the record\". `console.log` lines are the step's\ndetail in the run history, and `fetch` calls https addresses that allow it.\n\nIt runs in the browser, in a sandboxed iframe with no access to the page, its\ncookies or its storage, for up to 30 seconds and 1,000 calls to the base\n(`runScript` from `@svgrid/enterprise/base` runs one with a bridge of your\nown). The browser runner runs it in the page of the person who made the\nchange; the server runner (`createAutomationServer`) cannot run JavaScript of\na person's and fails the step, saying so. An app can hand a server run's\nscript to that person's page instead, as Artavolo does: pass\n`scriptsInPage` to `<SvBaseAutomations>` so the editor does not warn.\n\n## A webhook starts it\n\n\"A webhook is received\" gives the automation an address of its own: the\neditor shows it (`webhookUrl` on `<SvBaseAutomations>` turns the token into\nyour endpoint's URL) and makes a new one on request. Your endpoint hands the\nrequest to the server runner:\n\n```ts\n// POST /hooks/[token]\nexport const POST = async ({ params, request }) => json(await automations.webhookReceived(params.token, await request.json()))\n```\n\nThe JSON body's values are `{webhook.name}` in the steps, `{webhook.order.id}`\ninside objects and `{webhook.items.0.sku}` in lists; `{webhook}` is the whole\nbody. The run has no record: \"Create a record\" with values from the body is\nthe usual first step. Anyone with the address can start the automation, so\nkeep it secret, and limit how often your endpoint takes a request.\n\n## Runs\n\nEvery run is listed under Runs, newest first, with what each action did and\nthe record it ran on. A failed action stops the run there and says why.\n\nEdit fields on more than 10,000 records asks first, and that question says how many\nruns the change can start in the page and how long they will likely take: at the rate\nruns went in this tab, or, before any did, from how long the server takes to answer. Untick\n\"Also run automations\" to make the change without them. The choice holds for that change\nonly. An automation that runs on the server is not counted and cannot be skipped from here.\n\nRuns in the page go one at a time, in the tab, after the change is saved. From 20 runs on, the top\nbar says how far they are and about how long is left, with a Stop button. Stop drops the runs\nnot started and says how many, and those do not run later. Runs left when the tab closes do\nnot happen either, so the browser asks before it closes. For a change of hundreds of thousands of records,\nrun the automation on the server (`runOn: 'server'`).\n\n\n\n## In code\n\nA table's automations are its `automations`, plain data you can store with\nthe rest of the table:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nconst statusIs = (value: string) => ({\n kind: 'fieldFilter' as const,\n conjunction: 'and' as const,\n conditions: [{ column: 'status', kind: 'select' as const, op: 'is' as const, value }],\n})\n\nexport const taskAutomations: BaseAutomation[] = [\n {\n id: 'done',\n name: 'Done closes the task',\n enabled: true,\n trigger: { type: 'recordUpdated', fields: ['status'] },\n condition: statusIs('Done'),\n actions: [\n { type: 'updateRecord', values: { done: 'true', progress: '100%' } },\n { type: 'notify', message: '{Task} is done', severity: 'success' },\n ],\n },\n {\n id: 'blocked',\n name: 'Open an issue for a blocked task',\n enabled: true,\n trigger: { type: 'recordMatches' },\n condition: statusIs('Blocked'),\n actions: [{ type: 'createRecord', table: 'issues', values: { title: 'Unblock {Task}', owner: '{Assignee}' }, linkField: 'task' }],\n },\n]\n```\n\n```svelte\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { taskAutomations } from '$lib/automations'\n\n enableBase()\n let { tasks, issues }: { tasks: BaseTable; issues: BaseTable } = $props()\n let tables = $state.raw([{ ...tasks, automations: taskAutomations }, issues])\n</script>\n\n<SvBase bind:tables editable onTablesChange={(t) => console.log('save', t)} />\n<SvToaster />\n```\n\nAutomations edited in the dialog reach `onTablesChange` with the rest of the\ntable. Automations need `<SvBase tables>`; one table is a list of one.\nNotices show as a base's other notices do: see [Notices](./quick-start.md#notices).\n\n## Your own actions\n\n`registerAutomationAction` adds an action to the dialog's list. It runs in\nthe page, so call your own server for anything that needs a secret:\n\n```ts\nimport { registerAutomationAction } from '@svgrid/enterprise/base'\n\nregisterAutomationAction('post-to-chat', {\n label: 'Post to the team chat',\n run: async ({ record, text }) => {\n if (!record) return 'No record'\n const res = await fetch('/api/chat', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ message: `${text('Task')} needs a hand (${text('Assignee')})` }),\n })\n if (!res.ok) throw new Error(`Chat answered ${res.status}`)\n return 'Posted'\n },\n})\n```\n\nAn automation runs it with `{ type: 'run', action: 'post-to-chat' }`. What it\nreturns is the run's detail; what it throws is the run's error.\n\n## Where they run\n\nEach automation says where it runs, under \"Runs in\":\n\n- **This browser** (the default): in the page of the person who made the\n change, right away and once. A change that arrives from someone else\n through [realtime](./data.md#changes-made-elsewhere) does not run it again\n in your page. Scheduled ones run while the base is open.\n- **The server**: in your server, for every change to the database, whoever\n or whatever made it, with secrets and email. Set it up as below.\n\nEither way, a change an automation makes is an ordinary change: with a\n[source](./data.md), it is written to the database like an edit. What an\naction changes can set off other automations, up to four deep; past that the\nrun stops and says so, so two automations that answer each other cannot loop.\n\n## On the server\n\n\n\n`createAutomationServer` runs the automations set to \"The server\". It reads\nthe same tables, with the same automations, through sources of its own. It remembers\nthe last 10,000 records of a table it heard deleted: on a table with no `softDelete` an\nundo writes the record again, and only that memory tells it from a new one, so such an\nundo after a server restart reads as a creation.\nKeep the tables in one module both sides import, each side handing in its\nown way to reach the data:\n\n```ts\n// src/lib/tables.ts: the tables, for the browser and for the server.\nimport { baseSource, type BaseTable } from '@svgrid/enterprise/base'\nimport type { ServerDataSource } from '@svgrid/grid'\n\nexport function trackerTables(source: (table: string) => ServerDataSource<Record<string, unknown>>): BaseTable[] {\n return [\n {\n id: 'tasks',\n name: 'Tasks',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Task', fieldType: 'text' },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: [{ value: 'Todo' }, { value: 'Blocked' }, { value: 'Done' }] } },\n { field: 'owner_email', header: 'Owner email', fieldType: 'email' },\n ],\n automations: [\n {\n id: 'blocked',\n name: 'Tell the team about a blocked task',\n enabled: true,\n runOn: 'server',\n trigger: { type: 'recordMatches' },\n condition: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'is', value: 'Blocked' }] },\n actions: [\n { type: 'webhook', url: 'https://hooks.slack.com/services/{secret:SLACK_HOOK}', body: '{\"text\": \"{Task} is blocked\"}' },\n { type: 'email', to: '{Owner email}', subject: '{Task} is blocked', body: 'Someone marked {Task} as blocked.' },\n ],\n },\n ],\n source: baseSource(source('tasks')),\n },\n ]\n}\n```\n\nThe server side, in a SvelteKit app:\n\nThe code on this page is for SvelteKit 2. On SvelteKit 3,\n[these names differ](../../getting-started/sveltekit.md#on-sveltekit-3).\n\n```ts\n// src/lib/server/automations.ts\nimport pg from 'pg'\nimport { createAutomationServer } from '@svgrid/enterprise/base'\nimport { createSqlDataSource, type EntitySchema } from '@svgrid/enterprise'\nimport { env } from '$env/dynamic/private'\nimport { trackerTables } from '$lib/tables'\n\nconst pool = new pg.Pool({ connectionString: env.DATABASE_URL })\nconst schemas: Record<string, EntitySchema> = {\n tasks: {\n name: 'tasks',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'status', type: 'text' },\n { field: 'owner_email', type: 'text' },\n ],\n },\n}\n\n// Your mail provider's client.\ndeclare const mailer: { send: (m: { from: string; to: string[]; subject: string; text: string }) => Promise<unknown> }\n\nexport const automations = createAutomationServer({\n tables: trackerTables((table) =>\n createSqlDataSource({\n schema: schemas[table]!,\n table,\n dialect: { placeholders: '$', ilike: true },\n execute: async (sql, params) => (await pool.query(sql, params)).rows,\n }),\n ),\n // {secret:SLACK_HOOK} in a webhook reads this. List what automations may use:\n // whoever writes an automation can send any secret named here to any URL.\n secrets: { SLACK_HOOK: env.SLACK_HOOK },\n sendEmail: (m) => mailer.send({ from: 'tracker@example.com', ...m }),\n // \"Send a text message\": { to, text, channel } to your SMS or Viber provider.\n // sendText: (m) => texts.send(m),\n onRun: (run) => {\n if (run.status !== 'ok') console.error('automation failed', run)\n },\n})\n```\n\nThen tell it about changes, in whichever way fits your app:\n\n- **Through your endpoint.** Pass its `audit` hook to `createKitHandlers`:\n every create, update and delete through the endpoint reaches it, with the\n record as stored. It compares with what it read last, so it needs a server\n that stays up between requests. A server that has just started reads its\n tables before the first write reaches the database: the hook has a `before`\n that `createKitHandlers` waits for. So each record of a pasted block is\n judged by what it held, and a record the write left as it was runs nothing.\n Columns the row carries that no field names, such as a tenant, are not\n compared.\n\n To keep an audit hook of your own, pass it as the second argument,\n `automations.audit('tasks', (entry) => log(entry))`. It is called first with\n each entry. A hook that wraps this one loses `before`; then the server reads\n its tables after the first write, and each record of that request goes by\n the fields the write named.\n\n ```ts\n // src/routes/api/[table]/+server.ts\n import { createKitHandlers, createSqlDataSource, type EntitySchema } from '@svgrid/enterprise'\n import { automations } from '$lib/server/automations'\n\n declare const schema: EntitySchema\n declare const source: ReturnType<typeof createSqlDataSource>\n\n export const { POST } = createKitHandlers({ schema, source, audit: automations.audit('tasks') })\n ```\n\n- **From the database.** A Supabase database webhook, or a Postgres trigger\n that posts the old and new row, hands over both sides of the change.\n Nothing has to stay in memory, so it suits serverless hosts too:\n\n ```ts\n // src/routes/api/automations/changes/+server.ts\n import { error } from '@sveltejs/kit'\n import { env } from '$env/dynamic/private'\n import { automations } from '$lib/server/automations'\n\n export async function POST({ request }: { request: Request }) {\n if (request.headers.get('x-webhook-secret') !== env.WEBHOOK_SECRET) error(401, 'No')\n // Supabase sends { type, table, record, old_record }.\n const change = await request.json()\n await automations.recordChanged(change.table, { before: change.old_record, after: change.record })\n return new Response('ok')\n }\n ```\n\n- **By reading the table again**, when all you know is that it changed:\n `automations.tableChanged('tasks')`.\n\nScheduled automations run on `tick()`. Call it once a minute: from a cron\njob your host runs against an endpoint, or a timer in a long-running server.\nTwo ticks in one minute run them once.\n\n```ts\n// src/routes/api/automations/tick/+server.ts: called by your host's cron every minute.\nimport { automations } from '$lib/server/automations'\n\nexport async function POST() {\n const runs = await automations.tick()\n return new Response(JSON.stringify({ ran: runs.length }))\n}\n```\n\nThe server's runs show in the dialog next to the page's, tagged Server,\nwhen the base can fetch them:\n\n```ts\n// src/routes/api/automations/runs/+server.ts\nimport { json } from '@sveltejs/kit'\nimport { automations } from '$lib/server/automations'\n\nexport function GET() {\n return json(automations.runs)\n}\n```\n\n```svelte\n<SvBase bind:tables editable serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())} />\n```\n\n\n\nThe server ignores the echo of its own writes (the webhook the database\nsends for a change it made), so one change runs each automation once.\n\nThe [Postgres demo](./postgres.md) runs a server in the page, standing in\nfor yours: set a task to Blocked and its chat message shows under \"Sent by\nthe server\"; run `update tasks set status = 'Blocked' where id = 't9'` and it\nruns for that change too.\n\n## Every automation on the server\n\nAn app whose server hears of every change (people, its API, AI agents)\ncan run all of a base's automations there and none in the page:\n\n```svelte\n<SvBase\n bind:tables\n editable\n automationsOnServer\n serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())}\n runAutomation={(automation, tableId, recordId) =>\n fetch('/api/automations/run', { method: 'POST', body: JSON.stringify({ automation: automation.id, table: tableId, record: recordId }) })}\n/>\n```\n\nWith `automationsOnServer` the dialog offers no \"Runs in\", every\nautomation saved through it is `runOn: 'server'`, and none runs in the page.\n`runAutomation` is \"Run now\" in the dialog and what a Button field does:\nthe page asks the server to run the automation on that record (or on none),\nthen reads the server's runs. A Promise that rejects shows its message in\nthe dialog, or as a notice for a button. Without `runAutomation` the dialog\nsays the automation runs on the server, and a Button field that only server\nautomations listen to does nothing in the page.\n\n## A page of their own\n\nThe dialog shows one table's automations. `SvBaseAutomations` shows every\ntable's on a page, the way an app gives automations a section of their own:\n\n- **On the left**, every automation of the base, with its table, what sets it\n off and an on/off switch, \"+ Create automation\" and \"Run history\".\n- **In the middle**, the one picked as a flow of cards: its trigger, its\n condition, then its actions in order. A \"+\" between two cards adds an\n action there, and \"+ Add an action\" adds one at the end.\n- **On the right**, the settings of the card picked: the trigger and its\n table, the condition, or the action, with its order and Remove. Under them,\n Test on a record of the table, and Delete automation.\n\nChanging the trigger's table moves the automation to that table: its trigger\nstarts again there, and its condition and the fields its actions set go, as\nthey were the other table's fields.\n\n```svelte\n<script lang=\"ts\">\n import { SvBaseAutomations, enableBase, type BaseAutomation, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n\n let { tables }: { tables: BaseTable[] } = $props()\n\n // The page hands back a table's whole list after each change: store it with the table.\n function changed(tableId: string, automations: BaseAutomation[]) {\n tables = tables.map((t) => (t.id === tableId ? { ...t, automations } : t))\n void fetch(`/api/tables/${tableId}/automations`, { method: 'PUT', body: JSON.stringify(automations) })\n }\n</script>\n\n<SvBaseAutomations\n {tables}\n onChange={changed}\n onServer\n serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())}\n runOnServer={(automation, tableId, recordId) =>\n fetch('/api/automations/run', { method: 'POST', body: JSON.stringify({ automation: automation.id, table: tableId, record: recordId }) })}\n records={(tableId) => fetch(`/api/tables/${tableId}/rows?limit=200`).then((r) => r.json())}\n height=\"100%\"\n/>\n```\n\n| Prop | Type | What it does |\n|---|---|---|\n| `tables` | `BaseTable[]` | The base's tables, each with its `automations`. |\n| `onChange` | `(tableId, automations) => void` | A table's automations changed: its whole list, as `automations` on the table. |\n| `onServer` | `boolean` | Every automation runs on the server, as `automationsOnServer`: no \"Runs in\" to pick. |\n| `runOnServer` | `(automation, tableId, recordId) => Promise` | Test for an automation that runs on the server: your server runs it on that record (or on none). |\n| `serverRuns` | `() => Promise<AutomationRun[]>` | The server's runs, for Run history. |\n| `runner` | automation runner | Runs automations set to \"This browser\" when tested, and lists their runs. |\n| `records` | `(tableId) => Promise<Row[]>` | Records to test on, for a table whose rows are on a server. Without it, the table's `data`. |\n| `height` | `number \\| string` | The page's height (default `'100%'`). |\n\nThe page and the dialog edit the same `automations`. When both are on one\npage, keep one copy of the tables and hand each list the page gives back to\nthat copy, so a change in one is not undone by the other.\n\n## See also\n\n- [Keep a base in a database](./data.md)\n- [Field types](../fields.md): the view bar's filter, which conditions use\n"
|
|
5181
|
+
"markdown": "# Automations\n\nAn automation does something on its own when something happens to a\nrecord: a task set to Done ticks its Done box, a new request goes to Todo, a\nblocked task tells its owner, a button starts the work. Each table of a base\nhas its own, under \"Automations\" in the view bar.\n\n<div data-docs-demo=\"504-project-tracker\" data-height=\"680\"></div>\n\nIn the demo, set a task's Status to Done, press Start in the Kick off\ncolumn, or send the Request a task form, then open \"5 automations\" and look\nat Runs.\n\n\n\n## Add one\n\nOpen \"Automations\" in the view bar and press \"+ New automation\". The dialog\nhas three parts:\n\n- **When**: what sets it off.\n- **Only for records where**: a condition written with the view bar's\n filter, so it compares a select's option, a person, a linked record's name\n or \"within the past week\" the way the filter does. Leave it empty for\n every record.\n- **Do**: the actions, in order.\n\n\n\nEvery change is kept as you make it. \"Run now\" tries the automation on the\nrecord you pick, as if its trigger had happened.\n\n## When\n\n| Trigger | Runs |\n|---|---|\n| A record is created | When a record is added: \"+ Add row\", a form, a board lane, a calendar day, another automation. A record brought back by Restore or an undo of a delete is not created, and no rule runs for it |\n| A record changes | When a record is edited; pick fields to run only when one of them changes. A link made from the other table counts: adding a guest to an event from Guests changes the event's Guests field |\n| A record matches a condition | When a record starts to match the condition. It does not run again while the record keeps matching |\n| A form is sent | When a form view sends a record; pick the form, or any form of the table |\n| A button is pressed | When a Button field is pressed on a record |\n| At a scheduled time | Every day at 9, every Monday, every hour, or a cron expression: once for each record that matches the condition then, or once with no record |\n| A webhook is received | On the server: a request to the automation's own address, with no record. The body's values are `{webhook.name}` in the steps ([below](#a-webhook-starts-it)) |\n\nA paste or a fill that changes several cells of one record is one change to\nit. An undo or a redo is no change: it runs no automation.\n\n## Do\n\n| Action | What it does |\n|---|---|\n| Update the record | Sets fields of the record that set it off |\n| Create a record | Adds a record to any table of the base; \"Link it back\" fills a link field of the new record with the record that set it off |\n| Show a notice | A toast; `{Field name}` is that field of the record. `to` (user ids, or `field:<column id>` for the people a person field names) also sends it to their notifications when a server runs the automation |\n| Color the record while it matches | Colors the whole row, or some fields, for as long as the record matches the condition |\n| Call a webhook | POSTs the record (or a body you write) to a URL: a team chat, your API. Secrets as `{secret:NAME}`, read on the server only |\n| Send an email | To, subject and text with field names; sent by the [server](#on-the-server) |\n| Send a Slack, Teams or Google Chat message | A message to a channel through the address its chat app gave; only that app's own addresses ([below](#chat-messages)) |\n| Send a text message (SMS or Viber) | A text to phone numbers, or a phone field, by SMS or by Viber; sent by the [server](#on-the-server) through your provider ([below](#text-messages)) |\n| Find records and, for each, do | Steps run on every record of a table that matches a condition ([below](#if-and-find-records)) |\n| If a condition holds, do | Then steps when the record matches, Otherwise steps when it does not |\n| Ask AI | A prompt with field names; the answer goes into a field, and is `{ai}` in the next steps ([below](#ask-ai)) |\n| Run a script | JavaScript in a sandbox in the browser, as Airtable's automation scripts ([below](#run-a-script)) |\n| Your own actions | Anything the app adds with `registerAutomationAction` |\n\nA webhook's URL, headers and body name fields in braces, and secrets as\n`{secret:NAME}`; leave the body empty to send the record as JSON. A secret is\nnamed only by the automation: what a record holds is data, so `{secret:NAME}`\ntyped into a field goes out as that text.\n\nFrom the server a webhook does not call private or local addresses (`localhost`,\n`10.x`, `192.168.x`, `169.254.169.254`, a name that resolves to one, an IPv6 form\nthat wraps one) and does not follow redirects. On Node it connects to the\naddresses it checked, so a name cannot answer one way for the check and another\nfor the call; a name that does not resolve is not sent. A `fetch` of your own\npassed to `createAutomationServer` gets the check but not that pin, and neither\ndoes a runtime with no sockets of its own. For a webhook on your own network, set\n`allowInternalWebhooks: true` on `createAutomationServer`.\n\n\n\n\nValues are written as the field shows them:\n\n| Field | Write |\n|---|---|\n| Single or multiple select | The option's name: `Done`, `Bug, Risk` |\n| Person | The person's name: `Ana Ruiz` |\n| Checkbox | `true` or `false` |\n| Number | `42`; in a percent field, `100%` |\n| Date | `2026-11-01`, `today`, `today+7`, `today-1`, `now` |\n| Link | A record's name, several with commas, or `{record}` for the record that set it off |\n| Any text | Text with fields in braces: `{Task} follow-up` |\n| Any field | Nothing, to clear it |\n\n## If and Find records\n\n\"If a condition holds\" runs its Then steps when the record matches the\ncondition, and its Otherwise steps when it does not. With no record (a\nschedule, a webhook) only an \"If\" with no condition runs Then.\n\n\"Find records and, for each, do\" reads the records of a table that match a\ncondition, at most the number you set (100, up to 1,000), and runs its steps\non each: in them `{Field}` is the found record's field, `{trigger.Field}` the\nfield of the record that set the automation off, and `{found}` how many were\nfound. \"Update the record\" there updates the found record.\n\n```ts\n{ type: 'repeat', table: 'tasks', condition: statusIs('Todo'), limit: 50, actions: [\n { type: 'updateRecord', values: { note: 'Waiting on {trigger.Task}' } },\n] }\n{ type: 'if', condition: statusIs('Done'), then: [{ type: 'notify', message: 'Shipped' }], else: [] }\n```\n\nA step can be inside an \"If\" or a \"Find records\", and one of those inside\nanother, but no deeper. A script or a color is a step of the automation\nitself only.\n\n## Chat messages\n\nPaste the address the chat app gives for its channel:\n\n| App | Where the address comes from | What is sent |\n|---|---|---|\n| Slack | Apps, Incoming Webhooks, Add to a channel (`https://hooks.slack.com/...`) | `{ \"text\": ... }` |\n| Microsoft Teams | The channel's Workflows, \"Post to a channel when a webhook request is received\" (`*.logic.azure.com`, `*.powerplatform.com`) | An Adaptive Card with the text |\n| Google Chat | The space's Apps and integrations, Webhooks (`https://chat.googleapis.com/...`) | `{ \"text\": ... }` |\n\nThe text names fields in braces. A message goes only to its app's own https\naddresses, so a chat step cannot be pointed at any other server; an address\nmay name a secret (`{secret:SLACK_HOOK}`) on the server.\n\n## Text messages\n\n\"Send a text message\" sends a text to the numbers in **To**: written with their\ncountry code (`+359 88 123 4567`), or a phone field in braces (`{Phone}`),\nseveral apart with commas. The message names fields in braces. **Send by** is\nSMS, or Viber, which your provider may send as an SMS to a phone that is not on\nViber.\n\nThe browser has no account to send texts with, so this step runs on the\n[server](#on-the-server): give `createAutomationServer` a `sendText`, which gets\n`{ to, text, channel }` and calls your SMS or Viber provider.\n\n```ts\nimport { createAutomationServer, type BaseTable } from '@svgrid/enterprise/base'\n\n// Your tables, and your SMS or Viber provider's client.\ndeclare const tables: BaseTable[]\ndeclare const texts: { send: (m: { phone: string; text: string; viber: boolean }) => Promise<unknown> }\n\nexport const automations = createAutomationServer({\n tables,\n sendText: ({ to, text, channel }) => Promise.all(to.map((phone) => texts.send({ phone, text, viber: channel === 'viber' }))),\n})\n```\n\n## Ask AI\n\nThe prompt names fields in braces: `Write a two-line summary of {Name} for\nthe weekly report.` The answer goes into a text field of the record when you\npick one, and is `{ai}` in the steps after it. In the page the model is the\nrunner's `ai` option, on the server `createAutomationServer({ ai })`: a\nfunction from a prompt to the answer, behind which you call your model, with\nyour key on your server.\n\n```ts\ncreateAutomationServer({ tables, ai: async (prompt) => (await anthropic.messages.create({ model, max_tokens: 1000, messages: [{ role: 'user', content: prompt }] })).content[0].text })\n```\n\n## Run a script\n\nA script is JavaScript with Airtable's automation scripting objects:\n\n```js\nconst { recordId, Status } = input.config() // the record's fields, as text, by name\nconst tasks = base.getTable('Tasks')\nconst query = await tasks.selectRecordsAsync()\nfor (const r of query.records) {\n if (r.getCellValueAsString('Status') === 'Blocked') await tasks.updateRecordAsync(r.id, { Owner: 'Ana Ruiz' })\n}\noutput.set('blocked', query.records.length) // {script.blocked} in the next steps\n```\n\n`base.getTable(name)` has `selectRecordsAsync`, `updateRecordAsync`,\n`updateRecordsAsync`, `createRecordAsync`, `createRecordsAsync`,\n`deleteRecordAsync` and `deleteRecordsAsync`; a record has `id`, `name`,\n`getCellValue` and `getCellValueAsString`. Values are written as the field\nshows them, as in \"Update the record\". `console.log` lines are the step's\ndetail in the run history, and `fetch` calls https addresses that allow it.\n\nIt runs in the browser, in a sandboxed iframe with no access to the page, its\ncookies or its storage, for up to 30 seconds and 1,000 calls to the base\n(`runScript` from `@svgrid/enterprise/base` runs one with a bridge of your\nown). The browser runner runs it in the page of the person who made the\nchange; the server runner (`createAutomationServer`) cannot run JavaScript of\na person's and fails the step, saying so. An app can hand a server run's\nscript to that person's page instead, as Artavolo does: pass\n`scriptsInPage` to `<SvBaseAutomations>` so the editor does not warn.\n\n## A webhook starts it\n\n\"A webhook is received\" gives the automation an address of its own: the\neditor shows it (`webhookUrl` on `<SvBaseAutomations>` turns the token into\nyour endpoint's URL) and makes a new one on request. Your endpoint hands the\nrequest to the server runner:\n\n```ts\n// POST /hooks/[token]\nexport const POST = async ({ params, request }) => json(await automations.webhookReceived(params.token, await request.json()))\n```\n\nThe JSON body's values are `{webhook.name}` in the steps, `{webhook.order.id}`\ninside objects and `{webhook.items.0.sku}` in lists; `{webhook}` is the whole\nbody. The run has no record: \"Create a record\" with values from the body is\nthe usual first step. Anyone with the address can start the automation, so\nkeep it secret, and limit how often your endpoint takes a request.\n\n## Runs\n\nEvery run is listed under Runs, newest first, with what each action did and\nthe record it ran on. A failed action stops the run there and says why.\n\nEdit fields on more than 10,000 records asks first, and that question says how many\nruns the change can start in the page and how long they will likely take: at the rate\nruns went in this tab, or, before any did, from how long the server takes to answer. Untick\n\"Also run automations\" to make the change without them. The choice holds for that change\nonly. An automation that runs on the server is not counted and cannot be skipped from here.\n\nRuns in the page go one at a time, in the tab, after the change is saved. From 20 runs on, the top\nbar says how far they are and about how long is left, with a Stop button. Stop drops the runs\nnot started and says how many, and those do not run later. Runs left when the tab closes do\nnot happen either, so the browser asks before it closes. For a change of hundreds of thousands of records,\nrun the automation on the server (`runOn: 'server'`).\n\n\n\n## In code\n\nA table's automations are its `automations`, plain data you can store with\nthe rest of the table:\n\n```ts\nimport type { BaseAutomation } from '@svgrid/enterprise/base'\n\nconst statusIs = (value: string) => ({\n kind: 'fieldFilter' as const,\n conjunction: 'and' as const,\n conditions: [{ column: 'status', kind: 'select' as const, op: 'is' as const, value }],\n})\n\nexport const taskAutomations: BaseAutomation[] = [\n {\n id: 'done',\n name: 'Done closes the task',\n enabled: true,\n trigger: { type: 'recordUpdated', fields: ['status'] },\n condition: statusIs('Done'),\n actions: [\n { type: 'updateRecord', values: { done: 'true', progress: '100%' } },\n { type: 'notify', message: '{Task} is done', severity: 'success' },\n ],\n },\n {\n id: 'blocked',\n name: 'Open an issue for a blocked task',\n enabled: true,\n trigger: { type: 'recordMatches' },\n condition: statusIs('Blocked'),\n actions: [{ type: 'createRecord', table: 'issues', values: { title: 'Unblock {Task}', owner: '{Assignee}' }, linkField: 'task' }],\n },\n]\n```\n\n```svelte\n<script lang=\"ts\">\n import { SvToaster } from '@svgrid/grid'\n import { SvBase, enableBase, type BaseTable } from '@svgrid/enterprise/base'\n import { taskAutomations } from '$lib/automations'\n\n enableBase()\n let { tasks, issues }: { tasks: BaseTable; issues: BaseTable } = $props()\n let tables = $state.raw([{ ...tasks, automations: taskAutomations }, issues])\n</script>\n\n<SvBase bind:tables editable onTablesChange={(t) => console.log('save', t)} />\n<SvToaster />\n```\n\nAutomations edited in the dialog reach `onTablesChange` with the rest of the\ntable. Automations need `<SvBase tables>`; one table is a list of one.\nNotices show as a base's other notices do: see [Notices](./quick-start.md#notices).\n\n## Your own actions\n\n`registerAutomationAction` adds an action to the dialog's list. It runs in\nthe page, so call your own server for anything that needs a secret:\n\n```ts\nimport { registerAutomationAction } from '@svgrid/enterprise/base'\n\nregisterAutomationAction('post-to-chat', {\n label: 'Post to the team chat',\n run: async ({ record, text }) => {\n if (!record) return 'No record'\n const res = await fetch('/api/chat', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ message: `${text('Task')} needs a hand (${text('Assignee')})` }),\n })\n if (!res.ok) throw new Error(`Chat answered ${res.status}`)\n return 'Posted'\n },\n})\n```\n\nAn automation runs it with `{ type: 'run', action: 'post-to-chat' }`. What it\nreturns is the run's detail; what it throws is the run's error.\n\n## Where they run\n\nEach automation says where it runs, under \"Runs in\":\n\n- **This browser** (the default): in the page of the person who made the\n change, right away and once. A change that arrives from someone else\n through [realtime](./data.md#changes-made-elsewhere) does not run it again\n in your page. Scheduled ones run while the base is open.\n- **The server**: in your server, for every change to the database, whoever\n or whatever made it, with secrets and email. Set it up as below.\n\nEither way, a change an automation makes is an ordinary change: with a\n[source](./data.md), it is written to the database like an edit. What an\naction changes can set off other automations, up to four deep; past that the\nrun stops and says so, so two automations that answer each other cannot loop.\n\n## On the server\n\n\n\n`createAutomationServer` runs the automations set to \"The server\". It reads\nthe same tables, with the same automations, through sources of its own. It remembers\nthe last 10,000 records of a table it heard deleted: on a table with no `softDelete` an\nundo writes the record again, and only that memory tells it from a new one, so such an\nundo after a server restart reads as a creation.\nKeep the tables in one module both sides import, each side handing in its\nown way to reach the data:\n\n```ts\n// src/lib/tables.ts: the tables, for the browser and for the server.\nimport { baseSource, type BaseTable } from '@svgrid/enterprise/base'\nimport type { ServerDataSource } from '@svgrid/grid'\n\nexport function trackerTables(source: (table: string) => ServerDataSource<Record<string, unknown>>): BaseTable[] {\n return [\n {\n id: 'tasks',\n name: 'Tasks',\n primaryField: 'name',\n data: [],\n columns: [\n { field: 'name', header: 'Task', fieldType: 'text' },\n { field: 'status', header: 'Status', fieldType: 'singleSelect', fieldProps: { options: [{ value: 'Todo' }, { value: 'Blocked' }, { value: 'Done' }] } },\n { field: 'owner_email', header: 'Owner email', fieldType: 'email' },\n ],\n automations: [\n {\n id: 'blocked',\n name: 'Tell the team about a blocked task',\n enabled: true,\n runOn: 'server',\n trigger: { type: 'recordMatches' },\n condition: { kind: 'fieldFilter', conjunction: 'and', conditions: [{ column: 'status', kind: 'select', op: 'is', value: 'Blocked' }] },\n actions: [\n { type: 'webhook', url: 'https://hooks.slack.com/services/{secret:SLACK_HOOK}', body: '{\"text\": \"{Task} is blocked\"}' },\n { type: 'email', to: '{Owner email}', subject: '{Task} is blocked', body: 'Someone marked {Task} as blocked.' },\n ],\n },\n ],\n source: baseSource(source('tasks')),\n },\n ]\n}\n```\n\nThe server side, in a SvelteKit app:\n\nThe code on this page is for SvelteKit 2. On SvelteKit 3,\n[these names differ](../../getting-started/sveltekit.md#on-sveltekit-3).\n\n```ts\n// src/lib/server/automations.ts\nimport pg from 'pg'\nimport { createAutomationServer } from '@svgrid/enterprise/base'\nimport { createSqlDataSource, type EntitySchema } from '@svgrid/enterprise'\nimport { env } from '$env/dynamic/private'\nimport { trackerTables } from '$lib/tables'\n\nconst pool = new pg.Pool({ connectionString: env.DATABASE_URL })\nconst schemas: Record<string, EntitySchema> = {\n tasks: {\n name: 'tasks',\n fields: [\n { field: 'id', type: 'text', primaryKey: true },\n { field: 'name', type: 'text' },\n { field: 'status', type: 'text' },\n { field: 'owner_email', type: 'text' },\n ],\n },\n}\n\n// Your mail provider's client.\ndeclare const mailer: { send: (m: { from: string; to: string[]; subject: string; text: string }) => Promise<unknown> }\n\nexport const automations = createAutomationServer({\n tables: trackerTables((table) =>\n createSqlDataSource({\n schema: schemas[table]!,\n table,\n dialect: { placeholders: '$', ilike: true },\n execute: async (sql, params) => (await pool.query(sql, params)).rows,\n }),\n ),\n // {secret:SLACK_HOOK} in a webhook reads this. List what automations may use:\n // whoever writes an automation can send any secret named here to any URL.\n secrets: { SLACK_HOOK: env.SLACK_HOOK },\n sendEmail: (m) => mailer.send({ from: 'tracker@example.com', ...m }),\n // \"Send a text message\": { to, text, channel } to your SMS or Viber provider.\n // sendText: (m) => texts.send(m),\n onRun: (run) => {\n if (run.status !== 'ok') console.error('automation failed', run)\n },\n})\n```\n\nThen tell it about changes, in whichever way fits your app:\n\n- **Through your endpoint.** Pass its `audit` hook to `createKitHandlers`:\n every create, update and delete through the endpoint reaches it, with the\n record as stored. It compares with what it read last, so it needs a server\n that stays up between requests. A server that has just started reads its\n tables before the first write reaches the database: the hook has a `before`\n that `createKitHandlers` waits for. So each record of a pasted block is\n judged by what it held, and a record the write left as it was runs nothing.\n Columns the row carries that no field names, such as a tenant, are not\n compared.\n\n To keep an audit hook of your own, pass it as the second argument,\n `automations.audit('tasks', (entry) => log(entry))`. It is called first with\n each entry. A hook that wraps this one loses `before`; then the server reads\n its tables after the first write, and each record of that request goes by\n the fields the write named.\n\n ```ts\n // src/routes/api/[table]/+server.ts\n import { createKitHandlers, createSqlDataSource, type EntitySchema } from '@svgrid/enterprise'\n import { automations } from '$lib/server/automations'\n\n declare const schema: EntitySchema\n declare const source: ReturnType<typeof createSqlDataSource>\n\n export const { POST } = createKitHandlers({ schema, source, audit: automations.audit('tasks') })\n ```\n\n- **From the database.** A Supabase database webhook, or a Postgres trigger\n that posts the old and new row, hands over both sides of the change.\n Nothing has to stay in memory, so it suits serverless hosts too:\n\n ```ts\n // src/routes/api/automations/changes/+server.ts\n import { error } from '@sveltejs/kit'\n import { env } from '$env/dynamic/private'\n import { automations } from '$lib/server/automations'\n\n export async function POST({ request }: { request: Request }) {\n if (request.headers.get('x-webhook-secret') !== env.WEBHOOK_SECRET) error(401, 'No')\n // Supabase sends { type, table, record, old_record }.\n const change = await request.json()\n await automations.recordChanged(change.table, { before: change.old_record, after: change.record })\n return new Response('ok')\n }\n ```\n\n- **By reading the table again**, when all you know is that it changed:\n `automations.tableChanged('tasks')`.\n\nScheduled automations run on `tick()`. Call it once a minute: from a cron\njob your host runs against an endpoint, or a timer in a long-running server.\nTwo ticks in one minute run them once.\n\n```ts\n// src/routes/api/automations/tick/+server.ts: called by your host's cron every minute.\nimport { automations } from '$lib/server/automations'\n\nexport async function POST() {\n const runs = await automations.tick()\n return new Response(JSON.stringify({ ran: runs.length }))\n}\n```\n\nThe server's runs show in the dialog next to the page's, tagged Server,\nwhen the base can fetch them:\n\n```ts\n// src/routes/api/automations/runs/+server.ts\nimport { json } from '@sveltejs/kit'\nimport { automations } from '$lib/server/automations'\n\nexport function GET() {\n return json(automations.runs)\n}\n```\n\n```svelte\n<SvBase bind:tables editable serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())} />\n```\n\n\n\nThe server ignores the echo of its own writes (the webhook the database\nsends for a change it made), so one change runs each automation once.\n\nThe [Postgres demo](./postgres.md) runs a server in the page, standing in\nfor yours: set a task to Blocked and its chat message shows under \"Sent by\nthe server\"; run `update tasks set status = 'Blocked' where id = 't9'` and it\nruns for that change too.\n\n## Every automation on the server\n\nAn app whose server hears of every change (people, its API, AI agents)\ncan run all of a base's automations there and none in the page:\n\n```svelte\n<SvBase\n bind:tables\n editable\n automationsOnServer\n serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())}\n runAutomation={(automation, tableId, recordId) =>\n fetch('/api/automations/run', { method: 'POST', body: JSON.stringify({ automation: automation.id, table: tableId, record: recordId }) })}\n/>\n```\n\nWith `automationsOnServer` the dialog offers no \"Runs in\", every\nautomation saved through it is `runOn: 'server'`, and none runs in the page.\n`runAutomation` is \"Run now\" in the dialog and what a Button field does:\nthe page asks the server to run the automation on that record (or on none),\nthen reads the server's runs. A Promise that rejects shows its message in\nthe dialog, or as a notice for a button. Without `runAutomation` the dialog\nsays the automation runs on the server, and a Button field that only server\nautomations listen to does nothing in the page.\n\n## A page of their own\n\nThe dialog shows one table's automations. `SvBaseAutomations` shows every\ntable's on a page, the way an app gives automations a section of their own:\n\n- **On the left**, every automation of the base, with its table, what sets it\n off and an on/off switch, \"+ Create automation\" and \"Run history\".\n- **In the middle**, the one picked as a flow of cards: its trigger, its\n condition, then its actions in order. A \"+\" between two cards adds an\n action there, and \"+ Add an action\" adds one at the end.\n- **On the right**, the settings of the card picked: the trigger and its\n table, the condition, or the action, with its order and Remove. Under them,\n Test on a record of the table, and Delete automation.\n\nChanging the trigger's table moves the automation to that table: its trigger\nstarts again there, and its condition and the fields its actions set go, as\nthey were the other table's fields.\n\n```svelte\n<script lang=\"ts\">\n import { SvBaseAutomations, enableBase, type BaseAutomation, type BaseTable } from '@svgrid/enterprise/base'\n\n enableBase()\n\n let { tables }: { tables: BaseTable[] } = $props()\n\n // The page hands back a table's whole list after each change: store it with the table.\n function changed(tableId: string, automations: BaseAutomation[]) {\n tables = tables.map((t) => (t.id === tableId ? { ...t, automations } : t))\n void fetch(`/api/tables/${tableId}/automations`, { method: 'PUT', body: JSON.stringify(automations) })\n }\n</script>\n\n<SvBaseAutomations\n {tables}\n onChange={changed}\n onServer\n serverRuns={() => fetch('/api/automations/runs').then((r) => r.json())}\n runOnServer={(automation, tableId, recordId) =>\n fetch('/api/automations/run', { method: 'POST', body: JSON.stringify({ automation: automation.id, table: tableId, record: recordId }) })}\n records={(tableId) => fetch(`/api/tables/${tableId}/rows?limit=200`).then((r) => r.json())}\n height=\"100%\"\n/>\n```\n\n| Prop | Type | What it does |\n|---|---|---|\n| `tables` | `BaseTable[]` | The base's tables, each with its `automations`. |\n| `onChange` | `(tableId, automations) => void` | A table's automations changed: its whole list, as `automations` on the table. |\n| `onServer` | `boolean` | Every automation runs on the server, as `automationsOnServer`: no \"Runs in\" to pick. |\n| `runOnServer` | `(automation, tableId, recordId) => Promise` | Test for an automation that runs on the server: your server runs it on that record (or on none). |\n| `serverRuns` | `() => Promise<AutomationRun[]>` | The server's runs, for Run history. |\n| `runner` | automation runner | Runs automations set to \"This browser\" when tested, and lists their runs. |\n| `records` | `(tableId) => Promise<Row[]>` | Records to test on, for a table whose rows are on a server. Without it, the table's `data`. |\n| `height` | `number \\| string` | The page's height (default `'100%'`). |\n\nThe page and the dialog edit the same `automations`. When both are on one\npage, keep one copy of the tables and hand each list the page gives back to\nthat copy, so a change in one is not undone by the other.\n\n## See also\n\n- [Keep a base in a database](./data.md)\n- [Field types](../fields.md): the view bar's filter, which conditions use\n"
|
|
5182
5182
|
},
|
|
5183
5183
|
{
|
|
5184
5184
|
"slug": "help/base/collaboration",
|
|
5185
5185
|
"path": "docs/help/base/collaboration.md",
|
|
5186
5186
|
"title": "People, comments and files",
|
|
5187
5187
|
"section": "SvGrid Base",
|
|
5188
|
-
"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\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 is left out and the page says so, and with nobody left the\ncell keeps its value. With no list of people set the field takes what it is\ngiven. Copying a user cell writes the names, so a copy and paste between\nrecords keeps the people, and a copy in the same page keeps the very person when\ntwo share a name.\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\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. Text not sent stays with its record until the\n page reloads: stepping to the next record leaves it behind, and coming back finds it.\n Closing the record says so.\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 update?: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void\n remove?: (rowId: string, commentId: string, 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 comment's author sees Edit and Delete under it, with no one signed in that is\nwhoever is at the page. An edited comment shows \"(edited)\" and carries `editedAt`;\nsomeone newly mentioned in it hears of it once. A store without `update` or\n`remove` offers neither.\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\n// `update` and `remove` are optional: without them a comment stays as it was written.\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 shows\nas a base's other notices do: see [Notices](./quick-start.md#notices).\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\nEscape in the comment box leaves the box and keeps the text. On a comment\nbeing changed it is Cancel. While a comment has text not sent, or is being\nchanged, Escape does not close the record and says why, a click outside does\nnothing, and the Close button still closes it. An empty box holds nothing open.\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, pass `onMention` to `<SvBase>`, give the store an\n`onMention` hook, or call `setMentionHandler` (they work with the in-memory\ndefault 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. A PDF is framed only when the page could read its\nbytes and they are a PDF, so your storage has to allow the page's origin with CORS\n(`Access-Control-Allow-Origin`). A file it cannot read, or one that is not a PDF\nwhatever it calls itself, offers its Download link instead.\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, the new value and the one\nbefore it, and the record view writes it as \"Ana Ruiz changed Status\" over the\nold value and the new one as the cell shows them, or \"(cleared)\". Undo and redo\nare noted too, as \"You undid a change to Status\" and \"You redid a change to\nStatus\", so the log ends on what the record holds. 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\nBy default the log lives in memory and keeps the latest 50 changes of each\nrecord, for the 20,000 records of a table changed longest ago last: a bulk edit of a\nmillion records does not stay in the tab. In `<SvBase tables>` it is kept by base, table and record id, so it\nsurvives switching tabs; with one table it is kept per grid. Changes made by\nyour code replacing `tables` or `data` are not noted.\n\n### A history that lasts\n\nYour audit log already has every change. `setRecordHistory` lets the record\nview read it, and hands it each change made in the page to keep:\n\n```ts\nimport { setRecordHistory, type RecordChange } from '@svgrid/enterprise/base'\n\nsetRecordHistory({\n // Each time a record is opened. A promise is fine: the activity says\n // \"Loading the history...\" until it settles.\n list: async (rowId, { tableId }) => {\n const res = await fetch(`/api/history/${tableId}/${rowId}`)\n return (await res.json()) as RecordChange[]\n },\n // Each change made in this page, as it is made.\n add: (rowId, change, { tableId }) => {\n void fetch(`/api/history/${tableId}/${rowId}`, { method: 'POST', body: JSON.stringify(change) })\n },\n})\n```\n\nA change is `{ at, by, columnId, value, from? }` (`at` in milliseconds,\n`by` a user id from `setFieldUsers`), plus `automation` for a change an\nautomation made, `via` for a proposal someone accepted (\"CRM agent (accepted\nby Ana)\"), and `through` for a change a person made through an app as\nthemselves, an AI chat client say (\"Ana via Claude\"). The record view\nshows what `list` gave with this session's changes it does not have yet;\ngive back the `at` that `add` received, and a change shows once. A change\nmade elsewhere and read in through `realtime` is not passed to `add`:\nwhoever made it keeps it.\n\n`historyOf(ctrl, rowId)` gives a record's history as the record view shows\nit, for a panel of your own. `setRecordHistory(null)` goes back to memory.\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"
|
|
5188
|
+
"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\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 is left out and the page says so, and with nobody left the\ncell keeps its value. With no list of people set the field takes what it is\ngiven. Copying a user cell writes the names, so a copy and paste between\nrecords keeps the people, and a copy in the same page keeps the very person when\ntwo share a name.\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\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. Text not sent stays with its record until the\n page reloads: stepping to the next record leaves it behind, and coming back finds it.\n Closing the record says so.\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[]; files?: Attachment[]; internal?: boolean }\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 update?: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void\n remove?: (rowId: string, commentId: string, api: unknown, context: RecordCommentContext) => void\n onMention?: (event: MentionEvent) => void\n files?: boolean\n internal?: boolean\n}\n```\n\n### Files and internal notes\n\nA store with `files: true` gets an **Attach files** button in the comment\nbox. Each file goes through the app's attachment uploader\n(`setAttachmentUploader`, see [Upload files](#6-upload-files)) and the comment carries the\nresults in `files`; a comment of files alone has empty `text`. The record\nview lists them under the comment as links.\n\nA store with `internal: true` gets an **Internal note** box to tick. The\ncomment comes with `internal: true` and shows with an \"Internal\" mark. Hiding\nit from people outside the team (the clients of a portal, say) is the\nstore's job: `list` should leave it out for them, and the server should\nrefuse it from them.\n\n```ts\nimport { setRecordComments, type RecordComment } from '@svgrid/enterprise/base'\n\nconst kept: RecordComment[] = []\nsetRecordComments({ list: () => kept, add: (_rowId, comment) => kept.push(comment), files: true, internal: true })\n```\n\n### Saved replies\n\n`setCommentSnippets` gives the comment box a **Saved replies** button: a\nservice desk's standard answers. `list` is asked for the record open (its\ntable, its id and its values), so the app can fill each reply in from the\nrecord before it is shown (\"Hi Ana, we have your invoice\"). The person\nsearches, picks one, and its text (and its files) go into the box to change\nbefore sending; picking sends nothing. With `save`, the panel also offers\n**Save this text as a reply**, which hands the app the text and a name.\n\n```ts\nimport { setCommentSnippets } from '@svgrid/enterprise/base'\n\nsetCommentSnippets({\n list: async (tableId, { row }) => [\n { id: 'received', title: 'Invoice received', text: `Hi ${String(row.contact ?? '')}, we have your invoice and will pay it this week.` },\n ],\n save: async (tableId, { title, text }) => {\n await fetch('/replies', { method: 'POST', body: JSON.stringify({ tableId, title, text }) })\n },\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 comment's author sees Edit and Delete under it, with no one signed in that is\nwhoever is at the page. An edited comment shows \"(edited)\" and carries `editedAt`;\nsomeone newly mentioned in it hears of it once. A store without `update` or\n`remove` offers neither.\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\n// `update` and `remove` are optional: without them a comment stays as it was written.\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 shows\nas a base's other notices do: see [Notices](./quick-start.md#notices).\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\nEscape in the comment box leaves the box and keeps the text. On a comment\nbeing changed it is Cancel. While a comment has text not sent, or is being\nchanged, Escape does not close the record and says why, a click outside does\nnothing, and the Close button still closes it. An empty box holds nothing open.\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, pass `onMention` to `<SvBase>`, give the store an\n`onMention` hook, or call `setMentionHandler` (they work with the in-memory\ndefault 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. A PDF is framed only when the page could read its\nbytes and they are a PDF, so your storage has to allow the page's origin with CORS\n(`Access-Control-Allow-Origin`). A file it cannot read, or one that is not a PDF\nwhatever it calls itself, offers its Download link instead.\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, the new value and the one\nbefore it, and the record view writes it as \"Ana Ruiz changed Status\" over the\nold value and the new one as the cell shows them, or \"(cleared)\". Undo and redo\nare noted too, as \"You undid a change to Status\" and \"You redid a change to\nStatus\", so the log ends on what the record holds. 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\nBy default the log lives in memory and keeps the latest 50 changes of each\nrecord, for the 20,000 records of a table changed longest ago last: a bulk edit of a\nmillion records does not stay in the tab. In `<SvBase tables>` it is kept by base, table and record id, so it\nsurvives switching tabs; with one table it is kept per grid. Changes made by\nyour code replacing `tables` or `data` are not noted.\n\n### A history that lasts\n\nYour audit log already has every change. `setRecordHistory` lets the record\nview read it, and hands it each change made in the page to keep:\n\n```ts\nimport { setRecordHistory, type RecordChange } from '@svgrid/enterprise/base'\n\nsetRecordHistory({\n // Each time a record is opened. A promise is fine: the activity says\n // \"Loading the history...\" until it settles.\n list: async (rowId, { tableId }) => {\n const res = await fetch(`/api/history/${tableId}/${rowId}`)\n return (await res.json()) as RecordChange[]\n },\n // Each change made in this page, as it is made.\n add: (rowId, change, { tableId }) => {\n void fetch(`/api/history/${tableId}/${rowId}`, { method: 'POST', body: JSON.stringify(change) })\n },\n})\n```\n\nA change is `{ at, by, columnId, value, from? }` (`at` in milliseconds,\n`by` a user id from `setFieldUsers`), plus `automation` for a change an\nautomation made, `via` for a proposal someone accepted (\"CRM agent (accepted\nby Ana)\"), and `through` for a change a person made through an app as\nthemselves, an AI chat client say (\"Ana via Claude\"). The record view\nshows what `list` gave with this session's changes it does not have yet;\ngive back the `at` that `add` received, and a change shows once. A change\nmade elsewhere and read in through `realtime` is not passed to `add`:\nwhoever made it keeps it.\n\n`historyOf(ctrl, rowId)` gives a record's history as the record view shows\nit, for a panel of your own. `setRecordHistory(null)` goes back to memory.\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"
|
|
5189
5189
|
},
|
|
5190
5190
|
{
|
|
5191
5191
|
"slug": "help/base/custom-field-type",
|
|
@@ -5206,7 +5206,7 @@ export const docs = [
|
|
|
5206
5206
|
"path": "docs/help/base/forms.md",
|
|
5207
5207
|
"title": "Collect records with forms",
|
|
5208
5208
|
"section": "SvGrid Base",
|
|
5209
|
-
"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\n\nWhoever may change views can do all of this without code: \"Customize form\" in\nthe view bar opens a dialog with the title, the line under it, the button's text\nand every field a person can fill in, each with a switch to ask for it, arrows\nto move it and a box to require it. Each change shows in the form behind the\ndialog and is kept in the view as `formTitle`, `formDescription`,\n`formSubmitLabel`, `formFields` and `formRequired`.\n\nFor a form view, the view bar keeps the view menu, \"Customize form\" 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\n\nA form with nothing in any field does not send: it says \"Fill in at least one\nfield before you send this.\" and adds no record. A field filled by a default or\na link counts.\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| `richText` | An HTML string, sanitized (`null` when the editor was left empty) |\n| `number` | A number, as typed (an integer field: a whole number). Past 15 significant digits, text holding every digit |\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, and `formRequired` is one of them:\nnothing on a server knows of it. A table served by `createBaseEndpoint` is checked\nonly if you pass `validate` or `hooks` ([how](./quick-start.md#add-it-to-an-app-you-have)).\nAnyone can post to `/apply` without the form, 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`). A form on its own\nneeds one `<SvToaster />` from `@svgrid/grid` for the notice; inside a base it\nshows without one. 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. On a public form, say which fields a\nlink may fill: `prefillFields` on `SvBaseForm`, or a list for `formPrefill`\non a form view. A `prefill_` or `hide_` for any other field is ignored, so a\nlink cannot set the Source or the Owner you meant to fill yourself:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst apply: FieldView = {\n id: 'apply',\n name: 'Apply',\n type: 'form',\n formFields: ['name', 'email', 'role', 'source'],\n // A link may pick the role and say where the candidate came from, nothing else.\n formPrefill: ['Role', 'source'],\n formFooter: 'We keep your answers for 12 months. Write to jobs@example.com to have them removed.',\n}\n```\n\nCheck every value on the server as in\n[step 7](#7-check-it-again-on-the-server) all the same.\n\n## A footer under the button\n\n`formFooter` on a form view is a line of plain text under the submit button:\nwho reads the answers, how long they are kept. For more than a line (a logo,\nlinks to your terms), give `<SvBase>` a `formFooter` snippet; it gets the\nform view, so one snippet can serve every form:\n\n```svelte\n<SvBase bind:tables editable>\n {#snippet formFooter(view)}\n <p>By sending {view.name.toLowerCase()} you agree to our <a href=\"/terms\">terms</a>.</p>\n {/snippet}\n</SvBase>\n```\n\nOn a page of your own, `SvBaseForm` takes the same as `footerText` and a\n`footer` snippet.\n\n## One question at a time\n\n`layout=\"steps\"` asks one question at a time, as a conversation: a progress\nbar, \"Question 2 of 6\", Back and Next. Each answer is checked before the next\nquestion comes (a required field left empty, or an e-mail that is not one,\nstays with its message). Enter after an answer goes on, and on the last\nquestion sends the form. Shift+Enter, or Enter in a long text, starts a new\nline. A send that finds a problem goes back to the question it is on.\n\nThe next question slides in from the side it is on (`transition=\"slide\"`),\nfades in (`\"fade\"`) or just appears (`\"none\"`). A visitor who asks the system\nfor less motion gets none, whatever the form says.\n\n```svelte\n<SvBaseForm {api} fields={['name', 'email', 'role', 'note']} required={['name', 'email']}\n layout=\"steps\" transition=\"slide\" title=\"Apply\" />\n```\n\nConditions work as in the list: a question whose condition fails is skipped,\nand the count follows.\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| `prefillFields` | `ReadonlyArray<string>` | every field asked for | The fields `prefill` may fill or hide, by field name or column id. |\n| `footerText` | `string` | | A line under the submit button. |\n| `labels` | `Record<string, string>` | | Column id -> the question this form asks for that field, in place of the field's name. The required message uses it too. |\n| `help` | `Record<string, string>` | | Column id -> the help under that field on this form, in place of its description. An empty string shows none. |\n| `footer` | `Snippet` | | What goes under the submit button, after `footerText`. |\n| `layout` | `'list' \\| 'steps'` | `'list'` | `steps` asks one question at a time, with Back and Next ([One question at a time](#one-question-at-a-time)). |\n| `transition` | `'slide' \\| 'fade' \\| 'none'` | `'slide'` | How the next question comes in, with `layout=\"steps\"`. None for visitors who ask for less motion. |\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`; a list of field names or column ids lets the link fill only those |\n| `formFooter` | A line of plain text under the submit button |\n| `formLabels` | Column id -> the question asked for that field, as `labels` on `SvBaseForm` |\n| `formHelp` | Column id -> the help under that field, as `help` 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 a screen reader and a browser get\n\nA field that takes typed text (text, long text, number, email, URL, phone) is a\nreal `<input>` or `<textarea>` with a `<label>` from the start, and a checkbox a\nreal checkbox. A required field has `aria-required`. Fields with a picker (a\nselect, a date, a file, a link) are a labelled button until opened, and their\nname says when they are required.\n\nA field in error gets `aria-invalid` and its message through `aria-describedby`.\nA submit that fails says how many fields need attention, and focus goes to the\nfirst of them.\n\nEmail, phone and URL fields carry their `autocomplete` purpose, so a browser can\nfill them in. A text field gets one from an English name (Name, First name, Last\nname, Company, Address, City, Zip, Country). For any other name or language, set\nit on the field:\n\n```ts\n{ field: 'nombre', header: 'Nombre', fieldType: 'text', fieldProps: { autocomplete: 'name' } }\n```\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 stored as\n typed; precision is how it shows, and only an integer field rounds.\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"
|
|
5209
|
+
"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\n\nWhoever may change views can do all of this without code: \"Customize form\" in\nthe view bar opens a dialog with the title, the line under it, the button's text\nand every field a person can fill in, each with a switch to ask for it, arrows\nto move it and a box to require it. Each change shows in the form behind the\ndialog and is kept in the view as `formTitle`, `formDescription`,\n`formSubmitLabel`, `formFields` and `formRequired`.\n\nFor a form view, the view bar keeps the view menu, \"Customize form\" 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\n\nA form with nothing in any field does not send: it says \"Fill in at least one\nfield before you send this.\" and adds no record. A field filled by a default or\na link counts.\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| `richText` | An HTML string, sanitized (`null` when the editor was left empty) |\n| `number` | A number, as typed (an integer field: a whole number). Past 15 significant digits, text holding every digit |\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, and `formRequired` is one of them:\nnothing on a server knows of it. A table served by `createBaseEndpoint` is checked\nonly if you pass `validate` or `hooks` ([how](./quick-start.md#add-it-to-an-app-you-have)).\nAnyone can post to `/apply` without the form, 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`). A form on its own\nneeds one `<SvToaster />` from `@svgrid/grid` for the notice; inside a base it\nshows without one. 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. On a public form, say which fields a\nlink may fill: `prefillFields` on `SvBaseForm`, or a list for `formPrefill`\non a form view. A `prefill_` or `hide_` for any other field is ignored, so a\nlink cannot set the Source or the Owner you meant to fill yourself:\n\n```ts\nimport type { FieldView } from '@svgrid/enterprise/base'\n\nconst apply: FieldView = {\n id: 'apply',\n name: 'Apply',\n type: 'form',\n formFields: ['name', 'email', 'role', 'source'],\n // A link may pick the role and say where the candidate came from, nothing else.\n formPrefill: ['Role', 'source'],\n formFooter: 'We keep your answers for 12 months. Write to jobs@example.com to have them removed.',\n}\n```\n\nCheck every value on the server as in\n[step 7](#7-check-it-again-on-the-server) all the same.\n\n## A footer under the button\n\n`formFooter` on a form view is a line of plain text under the submit button:\nwho reads the answers, how long they are kept. For more than a line (a logo,\nlinks to your terms), give `<SvBase>` a `formFooter` snippet; it gets the\nform view, so one snippet can serve every form:\n\n```svelte\n<SvBase bind:tables editable>\n {#snippet formFooter(view)}\n <p>By sending {view.name.toLowerCase()} you agree to our <a href=\"/terms\">terms</a>.</p>\n {/snippet}\n</SvBase>\n```\n\nOn a page of your own, `SvBaseForm` takes the same as `footerText` and a\n`footer` snippet.\n\n## One question at a time\n\n`layout=\"steps\"` asks one question at a time, as a conversation: a progress\nbar, \"Question 2 of 6\", Back and Next. Each answer is checked before the next\nquestion comes (a required field left empty, or an e-mail that is not one,\nstays with its message). Enter after an answer goes on, and on the last\nquestion sends the form. Shift+Enter, or Enter in a long text, starts a new\nline. A send that finds a problem goes back to the question it is on.\n\nThe next question slides in from the side it is on (`transition=\"slide\"`),\nfades in (`\"fade\"`) or just appears (`\"none\"`). A visitor who asks the system\nfor less motion gets none, whatever the form says.\n\n```svelte\n<SvBaseForm {api} fields={['name', 'email', 'role', 'note']} required={['name', 'email']}\n layout=\"steps\" transition=\"slide\" title=\"Apply\" />\n```\n\nConditions work as in the list: a question whose condition fails is skipped,\nand the count follows.\n\n## Suggest answers before it is sent\n\nA help desk's request form can show the help articles that may already\nanswer the question, before anyone sends it. `setFormSuggestions` gives every\nform that: once the first text field (the subject) holds a few words, `list`\nis asked with the table, that text and the answers so far, and up to five\nsuggestions show under the field. Each opens in place; **This solved it** calls\n`solved` and ends the form with nothing added, and **Ask something else**\nstarts again.\n\n```ts\nimport { setFormSuggestions } from '@svgrid/enterprise/base'\n\nsetFormSuggestions({\n list: async (tableId, text) => {\n const res = await fetch(`/articles?q=${encodeURIComponent(text)}`)\n return (await res.json()) as Array<{ id: string; title: string; text: string }>\n },\n solved: (tableId, id) => {\n void fetch(`/articles/${id}/solved`, { method: 'POST' })\n },\n})\n```\n\nA text field takes its value when it is left (Tab, Enter, or a click\nelsewhere), so the suggestions come then, not on every key.\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| `prefillFields` | `ReadonlyArray<string>` | every field asked for | The fields `prefill` may fill or hide, by field name or column id. |\n| `footerText` | `string` | | A line under the submit button. |\n| `labels` | `Record<string, string>` | | Column id -> the question this form asks for that field, in place of the field's name. The required message uses it too. |\n| `help` | `Record<string, string>` | | Column id -> the help under that field on this form, in place of its description. An empty string shows none. |\n| `footer` | `Snippet` | | What goes under the submit button, after `footerText`. |\n| `layout` | `'list' \\| 'steps'` | `'list'` | `steps` asks one question at a time, with Back and Next ([One question at a time](#one-question-at-a-time)). |\n| `transition` | `'slide' \\| 'fade' \\| 'none'` | `'slide'` | How the next question comes in, with `layout=\"steps\"`. None for visitors who ask for less motion. |\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`; a list of field names or column ids lets the link fill only those |\n| `formFooter` | A line of plain text under the submit button |\n| `formLabels` | Column id -> the question asked for that field, as `labels` on `SvBaseForm` |\n| `formHelp` | Column id -> the help under that field, as `help` 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 a screen reader and a browser get\n\nA field that takes typed text (text, long text, number, email, URL, phone) is a\nreal `<input>` or `<textarea>` with a `<label>` from the start, and a checkbox a\nreal checkbox. A required field has `aria-required`. Fields with a picker (a\nselect, a date, a file, a link) are a labelled button until opened, and their\nname says when they are required.\n\nA field in error gets `aria-invalid` and its message through `aria-describedby`.\nA submit that fails says how many fields need attention, and focus goes to the\nfirst of them.\n\nEmail, phone and URL fields carry their `autocomplete` purpose, so a browser can\nfill them in. A text field gets one from an English name (Name, First name, Last\nname, Company, Address, City, Zip, Country). For any other name or language, set\nit on the field:\n\n```ts\n{ field: 'nombre', header: 'Nombre', fieldType: 'text', fieldProps: { autocomplete: 'name' } }\n```\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 stored as\n typed; precision is how it shows, and only an integer field rounds.\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"
|
|
5210
5210
|
},
|
|
5211
5211
|
{
|
|
5212
5212
|
"slug": "help/base/formulas",
|
|
@@ -5304,7 +5304,7 @@ export const docs = [
|
|
|
5304
5304
|
"path": "docs/help/base/views.md",
|
|
5305
5305
|
"title": "Views for every team",
|
|
5306
5306
|
"section": "SvGrid Base",
|
|
5307
|
-
"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\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\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\nSort the view by a number field and a card dropped elsewhere in its lane takes\na number between its neighbours', so the order is the table's and lasts.\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 Gantt chart, and a timeline in lanes\n\n```ts\nconst plan: FieldView = {\n id: 'gantt',\n name: 'Gantt',\n type: 'gantt',\n dateField: 'start',\n endField: 'target',\n color: { mode: 'field', field: 'status' },\n}\n```\n\nEach feature is a bar from its start to its target date, beside a table of\nnames and dates. Drag a bar to move both dates; drag its edge to change the\ntarget. One drag is one Ctrl+Z. `type: 'calendar'` with the same fields shows\nthe features on a month instead: a date field without a time shows as all-day\nevents. The end of a bar or an event is exclusive, so the record keeps the last\nday: 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\nA timeline puts the same bars in lanes: one row per value of `laneField`, so\nrecords that share a person, a property or a channel share a row, and the gaps\nbetween them show where there is room.\n\n```ts\nconst occupancy: FieldView = {\n id: 'occupancy',\n name: 'Occupancy',\n type: 'timeline',\n dateField: 'checkIn',\n endField: 'checkOut',\n laneField: 'property',\n zoom: 'month',\n}\n```\n\nDay, Week, Month and Year at the top right set the span. A bar dragged along\nits lane changes its dates; dragged to another lane it changes `laneField` too,\nin the same step, so one Ctrl+Z takes both back. For a link field with several\nrecords the record of the lane it left is swapped for the one it lands on, and\nthe others stay. A double-click in a lane adds a record there, in that lane.\nWith a single select or a person field every option or person is a lane, empty\nor not; with a link field the lanes are the records the rows link to, named by\nthe linked table's primary field.\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, plan, 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### Text, buttons, images, dividers and a record picker\n\nA dashboard can also say, show and link to things, which makes it a page of\nan app rather than only a summary (Airtable's \"blank\" interface layout):\n\n```ts\nconst home: FieldView = {\n id: 'home',\n name: 'Home',\n type: 'dashboard',\n dashboard: [\n { id: 'hello', kind: 'text', text: '# Welcome\\nYour open requests are below. See [the guide](https://example.com/guide).' },\n { id: 'help', kind: 'button', label: 'Ask for help', url: 'https://example.com/help' },\n { id: 'logo', kind: 'image', url: '/img/office.jpg', alt: 'Our office', fit: 'cover' },\n { id: 'sec', kind: 'divider', title: 'By account' },\n { id: 'account', kind: 'picker', table: 'accounts', title: 'Account', fields: ['city', 'owner'] },\n { id: 'deals', kind: 'number', title: 'Deals', pickedBy: { tile: 'account', field: 'account' } },\n ],\n}\n```\n\n- **`'text'`**: `text` in a small part of Markdown: a line starting with `#`\n is a heading, a blank line starts a paragraph, `**bold**` and\n `[words](https://...)` links inside lines. It is drawn as text, never as\n HTML, so what anyone types shows as typed.\n- **`'button'`**: `label` (default \"Open\") and `url`. An address on another\n site opens in a new tab; a path (`/...`) in the same one.\n- **`'image'`**: `url` and `alt` (said to people who cannot see it); `fit` is\n `'contain'` (the whole picture, default) or `'cover'` (the tile filled).\n- **`'divider'`**: a line across the whole dashboard with its `title` over\n it, to start a section.\n- **`'picker'`**: the records of its `table` to choose from by name; the one\n picked shows its `fields` (default: the next four after its name) and an\n \"Open the record\" button.\n\nLinks and pictures go only to `https:`, `http:`, `mailto:` (a link) or a path\non the site: a `javascript:` or `data:` address is shown as words, not\nfollowed.\n\nA number, chart, list or progress tile with `pickedBy: { tile, field }` is\nnarrowed by that picker: once a record is picked, it counts only the records\nwhose link field `field` holds it (\"the deals of the account picked\"), and\n\"Every record\" counts them all again. The pick is the viewer's and is not\nsaved. Under the hood the tile's filter gains a condition of the kind\n`'linked'`:\n\n```ts\nconst narrowing = { column: 'account', kind: 'linked', op: 'hasAnyOf', value: ['a1'] } // the link holds record a1, by id\n```\n\nFor a table the page holds, the page applies it. For a table read from a\nserver (`serverRows`), the server must apply it too: `fieldFilterToSql` and\n`fieldFilterToPostgrest` answer that they cannot (the tile then shows what\nthe server sends), so a server of your own reads `kind: 'linked'` and matches\nthe link's record ids.\n\nIn the tile dialog, \"Shows\" offers these kinds too; a picker's tile picks its\nfields, and the tiles it can narrow offer \"Narrowed by\" with each picker the\ntile's table links to. Dividers take one row across the dashboard; the other\ntiles keep their sizes.\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. A tree of tasks\n\n```ts\nconst tree: FieldView = {\n id: 'tree',\n name: 'Work breakdown',\n type: 'tree',\n parentField: 'parent',\n}\n```\n\nA tree is a grid whose records nest under their parent: `parentField` is a\nlink field to the same table, and a record sits under the one record it\nnames, with an expander on the primary field. It opens unfolded. A record\nwhose link names several records is at the top level, so no record goes\nmissing. The records stay records: every cell edits as in a grid, and the\nfooter and the view bar count them all, folded or not.\n\nBuilding it by hand, every change is a write to `parentField`, so undo, the\ndatabase and automations see a plain edit:\n\n- **Add subtask** on a row's menu, and the \"+\" at the end of its name: a record\n under it, last, opened for its name. **Enter** on that name keeps it and\n starts the next one beside it; **Escape**, or Enter with no name, ends the\n list and the empty record goes.\n- **Insert record above** and **below** keep the row's parent: a sibling.\n- **Alt+Shift+Right** puts the record under the one above it at its level;\n **Alt+Shift+Left** moves it up a level.\n- A row dragged by its number onto the middle of another goes under it;\n between two rows, beside them; below the last, to the top level.\n\nA record never goes under itself or one of its own subtasks: the move is\nrefused with a notice.\n\nThe first time the view is kept, `parentField` gets its field back in the same\ntable, **Subtasks** (`addSubtasks(tables, tableId, fieldId)` from\n`@svgrid/enterprise/base` does the same in code). It lists the records under\neach one, so a count or rollup of it adds them up: subtasks, their hours,\ntheir progress. It reads one level, the records directly under a record.\n\nA filter or a search keeps each matching record under its parents: the\nparents that do not match stay in the tree, greyed, and are not counted (the\ngrid's `treeData.keepAncestors`). A sort orders each level and keeps\nsubtasks under their parent.\n\nCreating a tree view asks for the link field. A table without a link to\nitself cannot have one: the type is greyed out, and says why. A table read a\npart at a time (`serverRows`) has no tree, since a tree needs every record at\nonce: an existing tree view shows its records as a list.\n\n## 13. A pivot of effort\n\n```ts\nconst pivot: FieldView = {\n id: 'pivot',\n name: 'Hours by status and team',\n type: 'pivot',\n pivot: {\n rows: ['status'],\n cols: ['team'],\n values: [{ agg: 'count' }, { agg: 'sum', field: 'hours' }],\n },\n}\n```\n\nA pivot adds up the records the view shows (its filter applies) by the fields\ndown the side (`rows`, outermost first) and the one across the top (`cols`):\na count of records, or a number field's `'sum'`, `'avg'`, `'min'` or `'max'`.\nFields are grouped as a chart groups them: options in their order, people and\nlinked records by name, dates by month, and a record with two options counts\nunder each. Subtotals, a total row and, with a field across the top, a total\ncolumn come with it.\n\nIts own bar, over the table, changes the rows, the column field and the\nvalues; the view keeps them (`onViewsChange`). On a table read from a server\na page at a time, it adds up the records loaded and says how many of how many.\n\n## 14. 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, each name beside its value so several records fit on\nthe screen, 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.\n\nA card keeps what a row can do. A long press, the button on the card, a\nright-click, the Menu key or Shift+F10 opens the record's menu: expand, comment,\nselect, insert above or below, duplicate and delete. A record selected this way\nshows on its card, as a ring on its list row, and in the selection bar. Copy and\npaste work on a cell, so they stay with the table. A gallery view and a list view\nhave the same menu.\n\nFields are added and changed from the fields button (Hide fields), since the\ncards have no column headers: \"Add a field\" at the foot of its list, and a\npencil on each field to rename it or change its type. Both are there wherever\nfields may be changed (`columnAdder`, off without `canEditSchema`), on any\nscreen, and open the same field editor as the header's \"+\" and field menu.\n\nA Kanban lane takes the table's width, the next lane a swipe away and\nsnapped into place. A calendar opens in its agenda, the days listed one under\nanother, since a month of seven columns has no room for a title; Month, Week\nand Day are a tap away. Gallery cards stand one per row, and a form is one\ncolumn at any width.\n\n`phoneLayout` on `SvBase` moves the breakpoint (`phoneLayout={480}`), turns\nthe cards on at every width (`true`) or keeps the grid (`false`).\n`phoneGrid=\"grid\"` keeps a grid view a grid on a phone while the other views\nkeep their phone layouts: a spreadsheet to scroll both ways, its first field\npinned and drawn at most about two fifths of the width\n(`maxPinnedColumnWidth` on the grid, the field's own width kept), with \"+\"\nto add a record. A tap selects a cell and a second tap edits it.\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| `'timeline'` | `dateField`, `endField`, `laneField` (a single select, person or link field), `zoom` (`day`, `week`, `month`, `year`), `color` | Hide fields, Filter, Sort, Color, Customize timeline |\n| `'gantt'` | `dateField`, `endField`, `progressField`, `dependencyField`, `zoom`, `color` | Hide fields, Filter, Sort, Color, Customize Gantt |\n| `'tree'` | `parentField`: a link field to the same table | Hide fields, Filter, Sort, Color, Row height |\n| `'gallery'` | `coverField`: an attachment field | Hide fields, Filter, Sort |\n| `'chart'` | `chart`: `kind`, `x`, `y`, `aggregation` | Filter, Customize chart |\n| `'pivot'` | `pivot`: `rows`, `cols`, `values` (`{ agg, field }`) | Filter; its own bar for rows, columns and values |\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 chart (`type: 'gantt'`) is one bar per record with a task table beside the bars.\n\"Create\" offers it as Gantt in every base, and its renderer loads the first\ntime one is shown. A timeline (`type: 'timeline'`) is the other kind of plan:\nrecords in lanes by `laneField`, several to a lane, as Airtable's Timeline view\ndraws them; an Airtable Timeline view converts to it, and an Airtable Gantt to a Gantt. Its bars take 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\nA record's dates are its own: a drop on a Sunday stays on the Sunday. By keyboard a\nbar works as a calendar event does: Space picks it up, Left and Right carry it a day\n(Shift, a week), Space puts it down and Escape puts it back. Enter opens the record,\nShift+F10 opens its menu, and Delete asks first, as a row's menu does.\n\n## When an edit changes where a record belongs\n\nA view's filter, sort and groups apply again after an edit, with one pause. In a\ngrid the row you are working in stays where it is while it is the active row, so\nit does not leap away under the cursor; it takes its place when you move to\nanother row, click outside the grid, or close its record. The record count follows\nat the same moment. An undo, a paste and a fill apply at once. A board, a calendar,\na timeline, a gallery and a list show the change as soon as it is made, or when a\nrecord dialog closes. On a table read a page at a time the database is asked again\nat that moment, once it has the edit.\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. Delete asks in the view's own row, and nothing moves\n until the answer. A deleted view goes to the trash and is one step of undo. The\n 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 list keeps its order while you switch fields, and hidden\n fields sit where they are in the table. 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## Sections in the views menu\n\nA table with many views groups them in sections, as Airtable does: a shared\nview's `section` lists it under that heading in the views menu, after the\nviews with none and before \"My views\". A heading folds its views, except the\none on screen. Whoever may manage views moves one into a section, or out of\nit, with the folder button on its row; the box offers the sections there are.\n\n```ts\nviews: [\n { id: 'all', name: 'All tasks', type: 'grid' },\n { id: 'q1', name: 'Q1 plan', type: 'grid', section: 'Planning' },\n { id: 'late', name: 'Late', type: 'grid', section: 'Reports' },\n]\n```\n\n## Your own actions on a view\n\n`setViewActions` adds buttons of the app's to each saved view in the views\nmenu, beside rename and duplicate, for everyone who sees the view: \"Subscribe\nin your calendar app\" on a calendar view, \"Copy a link\", \"Export\". The\nfunction is called for each view with its table's id and answers the\nview's actions (none: `[]`).\n\n```ts\nimport { setViewActions } from '@svgrid/enterprise/base'\n\nsetViewActions((view, tableId) =>\n view.type === 'calendar'\n ? [{ id: 'feed', label: 'Subscribe in your calendar app', icon: 'M4 6h16v14H4zM4 10h16M8 3v4M16 3v4', run: () => openFeed(tableId, view.id) }]\n : [],\n)\n```\n\n`icon` is an SVG path on a 24 by 24 box. `setViewActions(null)` takes them\naway; a function that throws gives none.\n\n## Your own actions on a record\n\n`setRecordActions` does the same for records: the app's actions show in a\nrecord's right-click menu (a grid row, a card) and at the top of the record\nview, and run with the table's id, the record's id and the record.\n\n```ts\nimport { setRecordActions } from '@svgrid/enterprise/base'\n\nsetRecordActions((tableId) => [\n { id: 'print', label: 'Print', icon: 'M4.5 6V2.5h7V6M4.5 12H3V7.5h10V12h-1.5M5 10h6v4H5z', run: ({ tableId, rowId }) => window.open(`/print/${tableId}/${rowId}`) },\n])\n```\n\n`icon` is an SVG path on a 16 by 16 box. `setRecordActions(null)` takes them away.\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"
|
|
5307
|
+
"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\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\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\nSort the view by a number field and a card dropped elsewhere in its lane takes\na number between its neighbours', so the order is the table's and lasts.\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 Gantt chart, and a timeline in lanes\n\n```ts\nconst plan: FieldView = {\n id: 'gantt',\n name: 'Gantt',\n type: 'gantt',\n dateField: 'start',\n endField: 'target',\n color: { mode: 'field', field: 'status' },\n}\n```\n\nEach feature is a bar from its start to its target date, beside a table of\nnames and dates. Drag a bar to move both dates; drag its edge to change the\ntarget. One drag is one Ctrl+Z. `type: 'calendar'` with the same fields shows\nthe features on a month instead: a date field without a time shows as all-day\nevents. The end of a bar or an event is exclusive, so the record keeps the last\nday: 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\nA timeline puts the same bars in lanes: one row per value of `laneField`, so\nrecords that share a person, a property or a channel share a row, and the gaps\nbetween them show where there is room.\n\n```ts\nconst occupancy: FieldView = {\n id: 'occupancy',\n name: 'Occupancy',\n type: 'timeline',\n dateField: 'checkIn',\n endField: 'checkOut',\n laneField: 'property',\n zoom: 'month',\n}\n```\n\nDay, Week, Month and Year at the top right set the span. A bar dragged along\nits lane changes its dates; dragged to another lane it changes `laneField` too,\nin the same step, so one Ctrl+Z takes both back. For a link field with several\nrecords the record of the lane it left is swapped for the one it lands on, and\nthe others stay. A double-click in a lane adds a record there, in that lane.\nWith a single select or a person field every option or person is a lane, empty\nor not; with a link field the lanes are the records the rows link to, named by\nthe linked table's primary field.\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, plan, 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### Text, buttons, images, dividers and a record picker\n\nA dashboard can also say, show and link to things, which makes it a page of\nan app rather than only a summary (Airtable's \"blank\" interface layout):\n\n```ts\nconst home: FieldView = {\n id: 'home',\n name: 'Home',\n type: 'dashboard',\n dashboard: [\n { id: 'hello', kind: 'text', text: '# Welcome\\nYour open requests are below. See [the guide](https://example.com/guide).' },\n { id: 'help', kind: 'button', label: 'Ask for help', url: 'https://example.com/help' },\n { id: 'logo', kind: 'image', url: '/img/office.jpg', alt: 'Our office', fit: 'cover' },\n { id: 'sec', kind: 'divider', title: 'By account' },\n { id: 'account', kind: 'picker', table: 'accounts', title: 'Account', fields: ['city', 'owner'] },\n { id: 'deals', kind: 'number', title: 'Deals', pickedBy: { tile: 'account', field: 'account' } },\n ],\n}\n```\n\n- **`'text'`**: `text` in a small part of Markdown: a line starting with `#`\n is a heading, a blank line starts a paragraph, `**bold**` and\n `[words](https://...)` links inside lines. It is drawn as text, never as\n HTML, so what anyone types shows as typed.\n- **`'button'`**: `label` (default \"Open\") and `url`. An address on another\n site opens in a new tab; a path (`/...`) in the same one.\n- **`'image'`**: `url` and `alt` (said to people who cannot see it); `fit` is\n `'contain'` (the whole picture, default) or `'cover'` (the tile filled).\n- **`'divider'`**: a line across the whole dashboard with its `title` over\n it, to start a section.\n- **`'picker'`**: the records of its `table` to choose from by name; the one\n picked shows its `fields` (default: the next four after its name) and an\n \"Open the record\" button.\n\nLinks and pictures go only to `https:`, `http:`, `mailto:` (a link) or a path\non the site: a `javascript:` or `data:` address is shown as words, not\nfollowed.\n\nA number, chart, list or progress tile with `pickedBy: { tile, field }` is\nnarrowed by that picker: once a record is picked, it counts only the records\nwhose link field `field` holds it (\"the deals of the account picked\"), and\n\"Every record\" counts them all again. The pick is the viewer's and is not\nsaved. Under the hood the tile's filter gains a condition of the kind\n`'linked'`:\n\n```ts\nconst narrowing = { column: 'account', kind: 'linked', op: 'hasAnyOf', value: ['a1'] } // the link holds record a1, by id\n```\n\nFor a table the page holds, the page applies it. For a table read from a\nserver (`serverRows`), the server must apply it too: `fieldFilterToSql` and\n`fieldFilterToPostgrest` answer that they cannot (the tile then shows what\nthe server sends), so a server of your own reads `kind: 'linked'` and matches\nthe link's record ids.\n\nIn the tile dialog, \"Shows\" offers these kinds too; a picker's tile picks its\nfields, and the tiles it can narrow offer \"Narrowed by\" with each picker the\ntile's table links to. Dividers take one row across the dashboard; the other\ntiles keep their sizes.\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. A tree of tasks\n\n```ts\nconst tree: FieldView = {\n id: 'tree',\n name: 'Work breakdown',\n type: 'tree',\n parentField: 'parent',\n}\n```\n\nA tree is a grid whose records nest under their parent: `parentField` is a\nlink field to the same table, and a record sits under the one record it\nnames, with an expander on the primary field. It opens unfolded. A record\nwhose link names several records is at the top level, so no record goes\nmissing. The records stay records: every cell edits as in a grid, and the\nfooter and the view bar count them all, folded or not.\n\nBuilding it by hand, every change is a write to `parentField`, so undo, the\ndatabase and automations see a plain edit:\n\n- **Add subtask** on a row's menu, and the \"+\" at the end of its name: a record\n under it, last, opened for its name. **Enter** on that name keeps it and\n starts the next one beside it; **Escape**, or Enter with no name, ends the\n list and the empty record goes.\n- **Insert record above** and **below** keep the row's parent: a sibling.\n- **Alt+Shift+Right** puts the record under the one above it at its level;\n **Alt+Shift+Left** moves it up a level.\n- A row dragged by its number onto the middle of another goes under it;\n between two rows, beside them; below the last, to the top level.\n\nA record never goes under itself or one of its own subtasks: the move is\nrefused with a notice.\n\nThe first time the view is kept, `parentField` gets its field back in the same\ntable, **Subtasks** (`addSubtasks(tables, tableId, fieldId)` from\n`@svgrid/enterprise/base` does the same in code). It lists the records under\neach one, so a count or rollup of it adds them up: subtasks, their hours,\ntheir progress. It reads one level, the records directly under a record.\n\nA filter or a search keeps each matching record under its parents: the\nparents that do not match stay in the tree, greyed, and are not counted (the\ngrid's `treeData.keepAncestors`). A sort orders each level and keeps\nsubtasks under their parent.\n\nCreating a tree view asks for the link field. A table without a link to\nitself cannot have one: the type is greyed out, and says why. A table read a\npart at a time (`serverRows`) has no tree, since a tree needs every record at\nonce: an existing tree view shows its records as a list.\n\n## 13. A pivot of effort\n\n```ts\nconst pivot: FieldView = {\n id: 'pivot',\n name: 'Hours by status and team',\n type: 'pivot',\n pivot: {\n rows: ['status'],\n cols: ['team'],\n values: [{ agg: 'count' }, { agg: 'sum', field: 'hours' }],\n },\n}\n```\n\nA pivot adds up the records the view shows (its filter applies) by the fields\ndown the side (`rows`, outermost first) and the one across the top (`cols`):\na count of records, or a number field's `'sum'`, `'avg'`, `'min'` or `'max'`.\nFields are grouped as a chart groups them: options in their order, people and\nlinked records by name, dates by month, and a record with two options counts\nunder each. Subtotals, a total row and, with a field across the top, a total\ncolumn come with it.\n\nIts own bar, over the table, changes the rows, the column field and the\nvalues; the view keeps them (`onViewsChange`). On a table read from a server\na page at a time, it adds up the records loaded and says how many of how many.\n\n## 14. 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, each name beside its value so several records fit on\nthe screen, 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.\n\nA card keeps what a row can do. A long press, the button on the card, a\nright-click, the Menu key or Shift+F10 opens the record's menu: expand, comment,\nselect, insert above or below, duplicate and delete. A record selected this way\nshows on its card, as a ring on its list row, and in the selection bar. Copy and\npaste work on a cell, so they stay with the table. A gallery view and a list view\nhave the same menu.\n\nFields are added and changed from the fields button (Hide fields), since the\ncards have no column headers: \"Add a field\" at the foot of its list, and a\npencil on each field to rename it or change its type. Both are there wherever\nfields may be changed (`columnAdder`, off without `canEditSchema`), on any\nscreen, and open the same field editor as the header's \"+\" and field menu.\n\nA Kanban lane takes the table's width, the next lane a swipe away and\nsnapped into place. A calendar opens in its agenda, the days listed one under\nanother, since a month of seven columns has no room for a title; Month, Week\nand Day are a tap away. Gallery cards stand one per row, and a form is one\ncolumn at any width.\n\n`phoneLayout` on `SvBase` moves the breakpoint (`phoneLayout={480}`), turns\nthe cards on at every width (`true`) or keeps the grid (`false`).\n`phoneGrid=\"grid\"` keeps a grid view a grid on a phone while the other views\nkeep their phone layouts: a spreadsheet to scroll both ways, its first field\npinned and drawn at most about two fifths of the width\n(`maxPinnedColumnWidth` on the grid, the field's own width kept), with \"+\"\nto add a record. A tap selects a cell and a second tap edits it.\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| `'timeline'` | `dateField`, `endField`, `laneField` (a single select, person or link field), `zoom` (`day`, `week`, `month`, `year`), `color` | Hide fields, Filter, Sort, Color, Customize timeline |\n| `'gantt'` | `dateField`, `endField`, `progressField`, `dependencyField`, `zoom`, `color` | Hide fields, Filter, Sort, Color, Customize Gantt |\n| `'tree'` | `parentField`: a link field to the same table | Hide fields, Filter, Sort, Color, Row height |\n| `'gallery'` | `coverField`: an attachment field | Hide fields, Filter, Sort |\n| `'chart'` | `chart`: `kind`, `x`, `y`, `aggregation` | Filter, Customize chart |\n| `'pivot'` | `pivot`: `rows`, `cols`, `values` (`{ agg, field }`) | Filter; its own bar for rows, columns and values |\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 chart (`type: 'gantt'`) is one bar per record with a task table beside the bars.\n\"Create\" offers it as Gantt in every base, and its renderer loads the first\ntime one is shown. A timeline (`type: 'timeline'`) is the other kind of plan:\nrecords in lanes by `laneField`, several to a lane, as Airtable's Timeline view\ndraws them; an Airtable Timeline view converts to it, and an Airtable Gantt to a Gantt. Its bars take 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\nA record's dates are its own: a drop on a Sunday stays on the Sunday. By keyboard a\nbar works as a calendar event does: Space picks it up, Left and Right carry it a day\n(Shift, a week), Space puts it down and Escape puts it back. Enter opens the record,\nShift+F10 opens its menu, and Delete asks first, as a row's menu does.\n\n## When an edit changes where a record belongs\n\nA view's filter, sort and groups apply again after an edit, with one pause. In a\ngrid the row you are working in stays where it is while it is the active row, so\nit does not leap away under the cursor; it takes its place when you move to\nanother row, click outside the grid, or close its record. The record count follows\nat the same moment. An undo, a paste and a fill apply at once. A board, a calendar,\na timeline, a gallery and a list show the change as soon as it is made, or when a\nrecord dialog closes. On a table read a page at a time the database is asked again\nat that moment, once it has the edit.\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. Delete asks in the view's own row, and nothing moves\n until the answer. A deleted view goes to the trash and is one step of undo. The\n 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 list keeps its order while you switch fields, and hidden\n fields sit where they are in the table. 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## Sections in the views menu\n\nA table with many views groups them in sections, as Airtable does: a shared\nview's `section` lists it under that heading in the views menu, after the\nviews with none and before \"My views\". A heading folds its views, except the\none on screen. Whoever may manage views moves one into a section, or out of\nit, with the folder button on its row; the box offers the sections there are.\n\n```ts\nviews: [\n { id: 'all', name: 'All tasks', type: 'grid' },\n { id: 'q1', name: 'Q1 plan', type: 'grid', section: 'Planning' },\n { id: 'late', name: 'Late', type: 'grid', section: 'Reports' },\n]\n```\n\n## Your own actions on a view\n\n`setViewActions` adds buttons of the app's to each saved view in the views\nmenu, beside rename and duplicate, for everyone who sees the view: \"Subscribe\nin your calendar app\" on a calendar view, \"Copy a link\", \"Export\". The\nfunction is called for each view with its table's id and answers the\nview's actions (none: `[]`).\n\n```ts\nimport { setViewActions } from '@svgrid/enterprise/base'\n\nsetViewActions((view, tableId) =>\n view.type === 'calendar'\n ? [{ id: 'feed', label: 'Subscribe in your calendar app', icon: 'M4 6h16v14H4zM4 10h16M8 3v4M16 3v4', run: () => openFeed(tableId, view.id) }]\n : [],\n)\n```\n\n`icon` is an SVG path on a 24 by 24 box. `setViewActions(null)` takes them\naway; a function that throws gives none.\n\n## Your own actions on a record\n\n`setRecordActions` does the same for records: the app's actions show in a\nrecord's right-click menu (a grid row, a card) and at the top of the record\nview, and run with the table's id, the record's id and the record.\n\n```ts\nimport { setRecordActions } from '@svgrid/enterprise/base'\n\nsetRecordActions((tableId) => [\n { id: 'print', label: 'Print', icon: 'M4.5 6V2.5h7V6M4.5 12H3V7.5h10V12h-1.5M5 10h6v4H5z', run: ({ tableId, rowId }) => window.open(`/print/${tableId}/${rowId}`) },\n])\n```\n\n`icon` is an SVG path on a 16 by 16 box. `setRecordActions(null)` takes them away.\n\nIn the record view the function is also told the record it shows, so an\naction can depend on it: \"Stop notifications\" on a record you follow, \"Notify\nme\" on one you do not. The right-click menu tells it no record; return none\nthere for actions that need one.\n\n```ts\nsetRecordActions((tableId, record) =>\n record ? [{ id: 'follow', label: followed.has(record.rowId) ? 'Stop notifications' : 'Notify me', run: ({ rowId }) => toggleFollow(rowId) }] : [],\n)\n```\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"
|
|
5308
5308
|
},
|
|
5309
5309
|
{
|
|
5310
5310
|
"slug": "help/benchmarks",
|
|
@@ -8826,7 +8826,7 @@ export const apiReference = {
|
|
|
8826
8826
|
};
|
|
8827
8827
|
export const apiSurface = {
|
|
8828
8828
|
"gridVersion": "3.0.36",
|
|
8829
|
-
"enterpriseVersion": "3.1.
|
|
8829
|
+
"enterpriseVersion": "3.1.44",
|
|
8830
8830
|
"grid": {
|
|
8831
8831
|
"values": [
|
|
8832
8832
|
"ALL_FILTER_OPERATORS",
|
package/dist/preview.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export declare const UI_MIME_TYPE = "text/html;profile=mcp-app";
|
|
|
8
8
|
* start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
|
|
9
9
|
* against the workspace so they cannot quietly rot either.
|
|
10
10
|
*/
|
|
11
|
-
export declare const PREVIEW_GRID_WC_VERSION = "3.0.
|
|
11
|
+
export declare const PREVIEW_GRID_WC_VERSION = "3.0.53";
|
|
12
12
|
export declare function previewResource(): {
|
|
13
13
|
uri: string;
|
|
14
14
|
name: string;
|
package/dist/preview.js
CHANGED
|
@@ -27,7 +27,7 @@ export const UI_MIME_TYPE = 'text/html;profile=mcp-app';
|
|
|
27
27
|
* start failing in a way nobody is watching for. `tools/mcp-tools.test.ts` checks these
|
|
28
28
|
* against the workspace so they cannot quietly rot either.
|
|
29
29
|
*/
|
|
30
|
-
export const PREVIEW_GRID_WC_VERSION = '3.0.
|
|
30
|
+
export const PREVIEW_GRID_WC_VERSION = '3.0.53';
|
|
31
31
|
const EXT_APPS_VERSION = '1.7.5';
|
|
32
32
|
const CDN = 'https://cdn.jsdelivr.net/npm';
|
|
33
33
|
/**
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"type": "commercial",
|
|
6
6
|
"url": "https://svgrid.com/pricing"
|
|
7
7
|
},
|
|
8
|
-
"version": "3.0.
|
|
8
|
+
"version": "3.0.48",
|
|
9
9
|
"description": "Model Context Protocol server for SvGrid, the Svelte 5 data grid: checks the code your AI writes against the real API surface, plus version-pinned docs, API reference and the source of every live demo.",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"author": "jQWidgets <sales@jqwidgets.com>",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"svelte": "^5.57.3",
|
|
42
42
|
"@types/node": "^22.10.7",
|
|
43
43
|
"typescript": "6.0.3",
|
|
44
|
-
"@svgrid/enterprise": "^3.1.
|
|
44
|
+
"@svgrid/enterprise": "^3.1.44"
|
|
45
45
|
},
|
|
46
46
|
"engines": {
|
|
47
47
|
"node": ">=18"
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "com.svgrid/svgrid",
|
|
4
4
|
"title": "SvGrid",
|
|
5
5
|
"description": "Checks AI-written SvGrid code against the real API, plus version-pinned Svelte 5 grid docs.",
|
|
6
|
-
"version": "3.0.
|
|
6
|
+
"version": "3.0.48",
|
|
7
7
|
"websiteUrl": "https://svgrid.com/docs/help/mcp-server/",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/sv-grid/sv-grid",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"registryType": "npm",
|
|
16
16
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
17
17
|
"identifier": "@svgrid/mcp",
|
|
18
|
-
"version": "3.0.
|
|
18
|
+
"version": "3.0.48",
|
|
19
19
|
"runtimeHint": "npx",
|
|
20
20
|
"transport": {
|
|
21
21
|
"type": "stdio"
|