UI config
A view says how the admin shows one resource: what its records are called, which columns the list has, which filters sit above it, how the record page is laid out, and which buttons it offers. It lives in config/<resource>/ui.ts; by convention every export of a ui.ts is picked up, and config/index.ts may export views too. A view only presents: what a user may see and do is decided by the data config’s access rules, and /api/meta removes from each user’s view every field they cannot read.
import { view } from '@protobase/schema'import type { repairs } from './data'
export const repairsView = view<typeof repairs>('repairs')view<typeof resource>(name) takes the resource’s type, so every field reference below (r.status) is checked by TypeScript. A view is immutable: each method returns a new view, so one view can build on another. The examples are the files of the bike shop guide, where each step builds on the last.
Names and columns
Section titled “Names and columns”import { view } from '@protobase/schema'import type { customers, repairs } from './data'
// Step 2: names, what a record is called, the columns the workshop reads, and how values look.
export const customersView = view<typeof customers>('customers') .names({ singular: 'Customer', plural: 'Customers' }) .title((r) => r.name) .list((r) => ({ columns: [r.name, r.phone, r.email], sort: [[r.name, 'asc']] }))
export const repairsView = view<typeof repairs>('repairs') .names({ singular: 'Repair', plural: 'Repairs' }) .title((r) => r.number) .fields((r) => ({ number: r.number.format('code'), customer_id: r.customer_id.label('Customer'), status: r.status.format('badge'), estimate: r.estimate.prefix('€').currency('EUR').decimals(2), booked_on: r.booked_on.label('Booked on'), })) .list((r) => ({ columns: [r.number, r.customer_id, r.bike, r.status, r.mechanic, r.estimate, r.booked_on], sort: [[r.booked_on, 'desc']], search: [r.number, r.bike], }))| Method | |
|---|---|
.names({ singular, plural }) |
“New repair”, “Repairs” in the sidebar, breadcrumbs and browser tabs. Default: the resource name in words. |
.title((r) => r.number) |
The field that names a record: in browser tabs, the record page’s heading, relation links and search results. |
.titleFrom(rule, (r) => [r.member_ids]) |
A title derived in the browser for the person reading it, in place of .title, by the function rule names in the UI config’s titles, from the fields picked. See Titles per reader. |
.searchResult((r) => ({ title?, subtitle? })) |
A record in the global search: title is one field or several joined by spaces ([r.first_name, r.last_name], default: .title), subtitle the line under it (default: the first search field not in the title), replaced by the search field the text matched when neither line shows it. |
.list((r, d, c) => ({ columns, sort?, search?, filter?, editable?, displays?, default? })) |
The list’s columns in order, fields or related records (c.related); the filter it opens with; its starting sort as [[field, 'asc' | 'desc'], ...], on .sortable() fields, else the primary key’s order when it is .sortable(), else none, which the API orders by the key; the fields the search box suggests, among the resource’s .search fields, which decide what search matches on the server; the columns edited in their cell; other ways to show it, see List displays. protobase build fails on a sort or search field outside those. |
.fields((r) => ({ name: r.name.label(...) })) |
Hints per field, below. Calls add up. |
.help(text) |
A line under the list’s title. |
.nav({ group, order, hidden, recent, tenant }) |
Where the resource sits in the sidebar, its recent-record group, and with tenant: 'current' that it opens on the current organization. |
.icon(name) |
The resource’s icon in the sidebar, bottom bar and user menu; a table icon without one. See Sidebar icons. |
.listOf((r) => r.listing_id) |
The list page shows the records this relation points at instead of the resource’s own rows, such as the listings among a member’s favorites. See Favorites. |
.signIn({ title, description, benefits?, icon?, signUp? }) |
What a visitor who is not signed in is told about the resource, in place of its list and by a card’s favorite button. See Sign-in prompts. |
.form((r) => ({ name, fields, thanks, title?, perMinute? })) |
A public form at /-/forms/<name> that creates a record for anyone, signed in or not, behind a rate limit and a bot check. See Public forms. |
A browser tab names what it shows, then the app’s name (name): Nordlicht GmbH · Companies · Protobase on a record page, the plural on a list, New company · Companies · Protobase on the create form, and a composed page’s title on that page, after the label of its tab when it has tabs.
Breadcrumbs
Section titled “Breadcrumbs”The top bar shows where a page is: the sidebar group and the list, each a link back. A record page’s trail ends at its list, such as Sales › Orders, and the heading below names the record. On a phone the top bar shows only the current page, with a back button before it to the page above; on a record page that button names the list it goes back to.
Titles per reader
Section titled “Titles per reader”Some records hold no name of their own, such as a direct message, which holds its members’ user ids. With .titleFrom, each reader sees such a record named for them: Maya sees the conversation as “Sam Okafor”, Sam the same record as “Maya Jansen”. The view names a function under titles in protobase.ui.tsx and the fields it reads; the function gets the record and the reader, the signed-in user and member(id), the organization’s members by user id as useMembers() gives them, and returns the title:
view<typeof directMessages>('direct_messages').titleFrom('memberNames', (r) => [r.member_ids])
// protobase.ui.tsxexport default defineUi({ titles: { memberNames: (record, { user, member }) => { const others = (record.member_ids as string[]).filter((id) => id !== user?.id).map((id) => member(id)?.name) return others.every(Boolean) ? others.join(', ') : undefined }, },})The rule members is built in and needs no function: .titleFrom('members', (r) => [r.member_ids]) names the record after the people in a JSON field of user ids other than the reader, in the order they were added, joined by commas. A conversation page with members titles its record this way unless the view sets its own .titleFrom.
The derived title names the record wherever .title would: the sidebar’s recent records, whose list request reads the picked fields too, the record page’s heading, the browser tab, the links of a record page’s relation fields, related cards, the global search, unless the view’s .searchResult gives a title, and every relation that points at such a record: a list’s relation column and a card’s relation field, which read the picked fields of a page’s records in one request, the relation picker’s options and a relation filter’s values. The picker’s typed text still matches the resource’s search fields, or, without any, the derived titles of the records it loads. The record’s key shows while the function returns nothing, such as while the members’ names load, and when the reader cannot read a field it picks, or the UI config registers no function of that name. It is presentation only: no field, filter or sort reads it, and the search does not match it. Other members’ names come only with organizations; without them, member finds no one.
Sidebar marks per reader
Section titled “Sidebar marks per reader”.nav({ recent: { marks: 'unread' } }) marks a sidebar group’s records for the person reading by a hook under marks in protobase.ui.tsx, such as an unread channel in bold with a count of its mentions: defineUi({ marks: { unread: useUnreadMarks } }), where useUnreadMarks(resource) returns { strong?, count?, label? } by record key. Like a derived title it is presentation only. See Marks per reader.
A click on a row of a list’s table opens its record. Its title cell, the .title column or else the first, is a link to the record, so Cmd- or Ctrl-click, a middle click and the browser’s link menu open it in a new tab or copy its address; embedded lists and the table of a list sorted by hand do the same.
Field hints:
| Hint | |
|---|---|
.label(text) |
Instead of the name in words (customer_id would be “Customer” anyway). |
.help(text, { when? }) |
A line under the field on the record page and in forms. when: 'editing' shows it only while the record is edited; see Help while editing. |
.notOnCreate() |
Leaves the field off the create form, for one that makes sense only once the record exists, such as a choice among records added after it: the create leaves it empty or to its default, and the record page shows it as usual. The server stops at startup on a field a create needs, one that is not optional and has no default, a boolean too. |
.confirm(question) |
Asks question before a person changes the value in a form or a list cell, and Cancel keeps it. See Confirming a change. |
.format(format) |
badge shows statuses as coloured badges, code sets identifiers in monospace, as the list’s identifier column too, percent adds a % sign, and signed shows a whole number in a list with its sign, green above zero and red below, such as a stock change of +12 or −3; it needs an integer field. On a text field, email, phone and url show the value as a link that writes to it (mailto:), calls it (tel:, its digits and a leading +) or opens it in a new tab (only an http or https address; anything else stays text), and .format('url', { text }) gives the link its own text, on the record page, in its sidebar and in the list’s cells but the title’s, which links to the record; forms edit it in an email, phone or web address input, which brings up the keyboard for it on a mobile screen and offers the browser’s autofill. Another field type with one of them stops the server at startup. relative on a timestamp shows it as “5 minutes ago” or “in 2 hours” in lists and on the record page, with the exact time on hover; absolute and compact are accepted and carried in /meta for apps that render their own lists. absolute and compact formats yet. |
.multiline() |
A text of several lines, such as a description: forms edit it in a box that grows with the text, so the page scrolls rather than the box, and the record page’s sections, a page’s field blocks and a card’s subtitle keep its line breaks (a card shows the first three lines); the record’s sidebar shows it on one line. On the record page and the create form it takes the whole width of its section. Only a text field takes it; the list’s table shows the text on one line. |
.markdown() |
Markdown, such as a task’s notes: forms edit its source in a box that grows with it, with a Write and Preview switch above it, and store it exactly as typed. The record page’s sections, a page’s field blocks and a conversation’s messages show it rendered as GitHub does, line breaks kept, a heading in a section one level under the section’s title and no larger than the text, so # and ## show as h3, ### as h4 and so on to h6, one level lower in a section inside a group (### cannot start at h3 because numbering from the value’s own top heading is not implemented. |
.prefix(text), .suffix(text), .decimals(n) |
Text around a number and its decimals: € and 2 show €1,234.50, .suffix(' m²') shows 120 m². They show wherever the number does: records, cards, table cells, forms and the range filter. A prefix is plain text, so a list does not show € as money; .currency() does. |
.currency(code) |
The currency a decimal is an amount of, as an ISO 4217 code such as EUR: the list shows it as money in that currency, in its table and its range filter. See Value tones and currencies. |
.icon(name) |
An icon before the value on a card’s meta row: one of the names actions take, such as bed, calendar or cpu, and above the value in a section of key facts. Nowhere else shows it. |
.valueLabels({ value: text }) |
How an enum’s values read: r.method.valueLabels({ ideal: 'iDEAL' }). Only the enum’s values are accepted. A value without a label shows as stored (direct_debit), so label every value that should read as words. |
.valueColors({ value: tone or '#hex' }), .badgeShape('arrow') |
An enum’s badges in a tone per value, or filled with a colour (the text turns white or black, whichever reads), and drawn as arrows pointing right, as on a rating scale. See Value tones and currencies. The property portal’s energy label: r.energy_label.format('badge').valueColors({ a: '#00a651', g: '#ed1c24' }).badgeShape('arrow'). Only the enum’s values are accepted. |
.waitingValues([value]) |
Enum values that mark a wait rather than work, such as r.phase.waitingValues(['ci']): a Timeline draws their segments striped, so a wait never reads as work. Only the enum’s values are accepted. |
.widget(name, props?) |
Shows and edits the field with a field type of the project or a plugin, such as r.status.widget('steps') or r.score.widget('rating', { max: 5 }), or with the built-in members, which picks an organization’s members into a JSON array of user ids; props are plain data. Without it, or on a storage type it does not show, the field shows as it would without the hint. |
An enum’s value labels show everywhere the admin shows its values: badges, select options, list and related-table cells, filter options and chips, record titles, the sidebar and search results. They are part of the view in /api/meta, so an app with its own screens can show them too, and enumLabel(value, labels) from @protobase/schema reads a value the same way. A label for a value the enum does not have stops the server at startup, so renaming a value cannot leave a stale label behind.
Value tones and currencies
Section titled “Value tones and currencies”An enum value’s badge takes the tone or colour its view gives it, and a money field shows in the ISO 4217 currency its view names. Nothing is read from the names of values or fields: a value the view gives no tone is neutral, and a decimal without a currency is a number.
.valueColors(...) gives each value one of the badge tones, neutral, blue, green, amber, red or violet, or a hex colour that fills the badge. The tone shows on the value’s badges in lists, boards and the record page, in the record page’s heading and in a list’s related dots and on the edge of related cards; a hex colour colours a chart’s group too. Anything else throws when the view is built.
.currency('EUR') on a decimal field makes the list show it as money in that currency, with the currency’s sign and grouping for the language, in the table and in its range filter. A currency on another field type stops the server at startup, as does .format('signed') on a field that is not an integer.
view<typeof orders>('orders').fields((r) => ({ number: r.number.format('code'), status: r.status.valueColors({ confirmed: 'blue', shipped: 'violet', delivered: 'green', cancelled: 'red' }), total: r.total.prefix('€').currency('EUR').decimals(2),})).currency() outside lists is not implemented..prefix(), so a money field takes both, as above.
The table’s columns take their width from the first rows it shows, and keep it while it scrolls, filters and sorts: the .title column gets the largest share, other text a share as long as its values, and short values such as enums, booleans, numbers, amounts and dates their own width whole. A value cut short shows whole when hovered. On a desktop the title column is pinned to the left by default, with the column before it when it is the second, so it stays in view when the table scrolls sideways; the column menu unpins it, and pins any other column to the left edge, and the choice is kept in the browser for that list. A column of the table is made wider or narrower by dragging its header’s right edge, or with the left and right arrow keys on that edge, down to 64 pixels; the other columns keep their width, a drag never sorts, and the widths last until the page is left or reloaded. The row menu stays at the table’s right edge as it scrolls sideways. Embedded lists and a page’s Table blocks size their columns the same way.
JSON fields and link text
Section titled “JSON fields and link text”Tables show JSON fields readably, and links can carry their own text. A JSON field, such as a tool call’s input, shows in a list’s table, a related table, a page’s Table block and on cards and the mobile rows as a short summary on one line: an object as its keys and values, plain values before nested ones, command: ls -la, cwd: /tmp, env: {…}, a list of plain values as those values, and a list of objects as how many it holds, 3 items. An object or list inside another shows as {…} or […], an empty text as "", each value is cut at 40 characters so one long value leaves room for the rest, and the summary at 160. The keys keep the order the database returns, which for a jsonb column is shortest first. The record page shows the value written out on several lines across the width of its section; a value of more than 20 lines shows its first 20 with a “Show all” button that shows the rest.
A url field’s link shows its address unless you give it a text. .format('url', { text }) takes a fixed text, or one with {{field}} placeholders the record fills in, each as the record page shows it, such as an enum value by its label and a relation by the name of the record it points at:
view<typeof errors>('errors').fields((r) => ({ report: r.report.format('url', { text: 'Error report' }), trace: r.trace.format('url', { text: '{{title}}' }),}))The link still opens the address in a new tab, in the list’s cells, related tables, the record page and its sidebar; cards and the mobile rows show the text too. When a field it names is empty, the link shows its address rather than a text with a gap, and so does it for a reader who cannot read a field it names. The list loads the fields a link’s text names along with its columns. A text on another format, or one naming a field the resource does not have, stops the server at startup; a later .format() with another format drops the text.
{{field}} naming a relation with the related record’s name because resolving those names for link text outside the record page is not implemented; they show its key.Related records in a list
Section titled “Related records in a list”A list column can show the records of another resource that point at each row, as a dot per record: the tasks that serve an objective, say, each in its status’s colour, so an objective’s dots turn green as its tasks get done. c, the list’s third argument, makes the column, and its name goes among the columns:
view<typeof objectives>('objectives').list((r, d, c) => ({ columns: [ r.title, c.related('tasks', { resource: 'tasks', field: 'id', through: { resource: 'objective_tasks', field: 'objective_id', key: 'task_id' }, status: 'status', sort: 'position' }), r.quarter, ],}))| Option | |
|---|---|
resource, field, through, filter |
Which records each row shows, as a related section finds them: those whose relation field holds the row’s key, or, through a join resource, those through’s records pick, so a task can serve several objectives. |
status |
An enum field of resource. Each dot is filled with the colour or tone its value has in the resource’s view (.valueColors(...)), neutral without one. Required. |
sort |
The dots’ order, AIP-132 on resource. |
label |
The column’s header; default the name in words. The name must not be a field of the resource. |
Each dot is a link to its record. Hovering or focusing it shows the record’s card: the first cards display of the resource’s view, without photos or a favorite button, else its title with its status as the badge. On a touch screen the first tap on a dot shows the card, and the card opens the record. Each dot reads as its record’s title and status to a screen reader, and the column says how many records have each status, such as “4 tasks: 2 To do, 1 Doing, 1 Done”.
The records load with each page of the list’s rows, in two requests for the page through a join resource (one without), as the user may read them. Each request reads all of the page’s join records or records, page by page, so a row never misses a dot. A user who cannot read the resources, status or a field the column filters or sorts on does not get the column. The column shows in the list page’s table; an embedded list leaves it out.
The list’s cards show the same dots when a cards display names the column in dots: a line of them at the card’s bottom for each column, with the colours, order and hover cards they have in the table. A card shows no line for a column without records, and the cards a map or a saved search shows, which load without the column, show none.
view<typeof objectives>('objectives').list((r, d, c) => { const tasks = c.related('tasks', { resource: 'tasks', field: 'id', through: { resource: 'objective_tasks', field: 'objective_id', key: 'task_id' }, status: 'status', sort: 'position' }) return { columns: [r.title, tasks, r.quarter], displays: [d.cards({ title: r.title, footer: [r.quarter], dots: [tasks] })] }})Editing in the list
Section titled “Editing in the list”The list’s table can edit some of its columns in place, as a spreadsheet does: editable names them, among the columns.
view<typeof products>('products').list((r) => ({ columns: [r.sku, r.name, r.price, r.status, r.active], editable: [r.price, r.status, r.active],}))A click on an editable cell chooses it instead of opening the record, and a second click, a double-click, Enter or F2 opens the field’s editor in the cell: the one the record page uses, a field type’s editor included. Enter, Tab or a click elsewhere saves the change, and Escape leaves the value as it was; a switch or a choice from a list saves as soon as it changes. The arrow keys move between the cells, Tab and Shift+Tab along the row, and Tab from an editor saves it and goes on to the row’s next editable cell. Enter on a cell that is not editable opens its record. An editable title cell is no link to the record; the row’s other cells still open it.
Each change is a PATCH of that one field with the row’s ETag, so it is refused when someone else changed the record since the list loaded it. The cell shows the new value while it saves; when the server refuses, the cell gets its old value back, or the record’s current one when someone else changed it, and a toast says why, such as the field’s validation message.
Access needs nothing more: /meta keeps editable to the fields the user may write, and the table edits only the rows they may change, so a user who may not change the records gets the table as before, whose rows open their record. Every save is checked again by the server.
An editable column is a field of the resource with an editor of one line that the API may write: text that is neither .multiline() nor .markdown(), a number, a date, an enum, a boolean, a currency or a country. A relation is chosen and a file uploaded on the record page. The server refuses at startup an editable field outside the columns, a read-only one, or one of another type, and .list(...) throws on one that is not among its columns. Cards, maps and embedded lists show the values without editing them.
Reordering by hand
Section titled “Reordering by hand”Records with an order of their own, such as the products in the order a shop lists them or an invoice’s items in the order it prints them, are put in order by dragging them. The resource names the integer field that holds the order with .position(...), 1 the first; with within, a relation, each parent’s records have an order of their own:
import { f, l, resource, view } from '@protobase/schema'
// Records in an order of their own, sorted by hand: the products in the order the shop lists them, sorted on their// list, and each invoice's items in the order the invoice prints them, sorted on the invoice's page.
export const products = resource('products') .table('products') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), name: f.text(), rank: f.integer().sortable(), }) .primaryKey((r) => r.id) .position((r) => r.rank)
export const invoices = resource('invoices') .table('invoices') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), number: f.text(), customer: f.text(), }) .primaryKey((r) => r.id)
export const invoiceItems = resource('invoice_items') .table('invoice_items') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), invoice_id: f.relation('invoices').filterable(), position: f.integer().sortable(), description: f.text(), amount: f.decimal({ precision: 12, scale: 2 }), }) .primaryKey((r) => r.id) .position((r) => r.position, { within: (r) => r.invoice_id })
export const productsView = view<typeof products>('products') .title((r) => r.name) .list((r) => ({ columns: [r.name], sort: [[r.rank, 'asc']] }))
export const invoicesView = view<typeof invoices>('invoices') .title((r) => r.number) .fields((r) => ({ number: r.number.format('code') })) .layout((r) => [ l.section('Invoice', [r.number, r.customer]), l.related('Items', { resource: 'invoice_items', field: 'invoice_id', sort: 'position' }), ])
export const invoiceItemsView = view<typeof invoiceItems>('invoice_items') .names({ singular: 'Item', plural: 'Items' }) .title((r) => r.description) .list((r) => ({ columns: [r.description, r.amount], sort: [[r.position, 'asc']] }))The list of a resource ordered as one, such as the products, has a Reorder button beside its other buttons; a related section of records ordered within the page’s record, such as the invoice’s items, has one at the end of its title’s line. Reorder shows every record in its order in the list’s table, without the filters, search, chart and display switch, with a drag handle in each row where its checkbox was, and the page scrolls them; Done goes back. A row moves by dragging its handle, by a long press and drag on a touch screen, or from the keyboard: Space on a handle picks the row up, the up and down arrow keys move it, Space or Enter drops it and Escape puts it back, and a screen reader is told each step. The rest of the row still opens its record.
Each drop shows at once and is saved straight away as one batch move, anchored to the record above where it was dropped: it saves while the record after that one is still the one that was below the drop, whatever else changed since the list loaded, such as another field of the records or records added elsewhere. The server numbers only the stretch whose place changed, from the record before it on; it reaches further only where a gap or a tie left by an earlier write needs it, so a list of thousands saves a short move as a few records. Drops made while one saves are saved after it, together. A saved drop says so in a toast with Undo, which puts back the positions it changed; see Dragging in the list. When someone else changed the list where the record was dropped, the move is not saved and a warning names the record and says the list now shows the current order; otherwise a refusal says why. Either way the rows go back to the order the server has, and every list of the resource reloads by itself, so the next move works from the current order.
A user who may not update the resource or write the field gets no Reorder, and /api/meta leaves out position for one who cannot read its field or its within. A related section offers it only when it lists all of the parent’s records: its field is the within relation, without a filter or through. The list page does not offer it for a resource ordered within a parent, since its list mixes the parents. The field must be .sortable() and within a .filterable() relation, checked when the config loads, and protobase doctor checks that an index serves each read in the field’s order, such as (invoice_id, position). Records created later are not numbered for you: give them a position, or the next drop numbers them, after the others when the field is empty; the record lines table numbers the lines it adds.
Dragging in the list
Section titled “Dragging in the list”Nothing in a list moves by dragging unless its .list(...) says so with drag, each part on its own:
drag |
What it lets a user drag |
|---|---|
rank: true |
The records of a resource with a .position(...) and no within, at any time: the table’s rows by their handles while the list shows every record in the position’s order, ascending, without a filter or search, instead of after Reorder; and a board’s cards to their place in a column. |
board: true |
A board’s card to another column, which saves the record with that column’s value. |
board: { set?, columns? } |
A board’s card between the columns it names, by value, or every column, which saves the column’s value in the field set, or in by when it names none. See Moving cards by another field. |
board: 'name' |
A board’s card between the columns the board drop of that name in the UI config’s boardDrops lists, each running its own write. See Board drops. |
rule: 'name' |
Where the table’s rows may land when re-ranked, by Reorder or rank: the drop rule of that name in the UI config’s dropRules. See Drop rules. |
.list((r, d) => ({ columns: [r.title, r.status], sort: [[r.rank, 'asc']], displays: [d.board({ by: r.status })], drag: { rank: true, board: true } }))A board may let cards move between columns without re-ranking (board alone), or be re-ranked within its columns without moving cards between them (rank alone). A list sorted another way, filtered or searched shows its own table, and Reorder stays for it. A named list has its own drag. Either part needs the right to update the field it writes, as Reorder does: a user without it drags nothing.
On a touch screen a card or a row’s handle lifts only after a short hold, a quarter of a second, so a swipe across the board scrolls it instead of moving a card; a mouse or trackpad drags it straight away. Every saved drag says so in a toast with Undo, which puts back what it changed, the column and every position it renumbered, with the ETags the save gave the records, so a record changed again since is refused rather than overwritten. Only the latest drag can be undone: a new one replaces the toast.
Drop rules
Section titled “Drop rules”Some orders must hold, such as a task never ranked above one it waits for. A drop rule, a function in protobase.ui.tsx under dropRules, gets the dropped record, the records in the order the drop would leave them and the record’s place among them, 0 the first, as the API gives them, every field the user may read; it returns why the record may not be there, or nothing when it may:
export default defineUi({ dropRules: { afterWhatItWaitsFor: ({ record, order, index }) => { const waited = order.find((task) => task.id === record.waits_for_id) if (!waited || order.indexOf(waited) < index) return undefined return `${record.title} waits for ${waited.title}.` }, },})The list names it with drag: { rank: true, rule: 'afterWhatItWaitsFor' }. A drop the rule refuses lands in the first place below that it allows, and a warning says where with the rule’s reason; with no such place the row stays where it was, with the same warning. The rule only guides the drag: the server’s access rules and validate still decide what is saved. A list naming a rule the UI config does not register says so in place of its rows.
Ranked after what they depend on
Section titled “Ranked after what they depend on”Some records wait for others, such as a task blocked by another task. With after, the resource’s position keeps each record below the records it depends on, through a join resource, for as long as they match while:
.position((r) => r.position, { after: { resource: 'task_dependencies', field: 'task_id', key: 'depends_on_id', filter: 'type = "blocked-by"', while: 'status != "done"' },})field and key are filterable relations of the join resource to the ranked one: field holds the record that waits, key the record it waits for. filter narrows the join records and while the records waited for, both optional. The ranked resource needs a key of one field; the config is checked when it loads.
The server’s reorder, and a create or update that writes the position, refuse an order that puts a record at or above a pending record it depends on, or one of those at or below it. Pairs already out of order, such as a dependency added after the ranking, do not block other moves. The list’s drag: { rank: true } follows it on the table and the board without another option. Before it saves a drop, it reads the record’s dependencies through the list API, so the join resource’s field and key need an index. A card or row dropped above a record it depends on lands in the first place below that keeps the order, and a warning names that record by its title. On a board the ranks are those of every column, so a card whose dependency in another column ranks above its whole column takes the last place, with a rank just above that dependency. With no such place, it stays where it was, with the same warning.
Board drops
Section titled “Board drops”Some boards are by a field that cannot be written, such as a status the database computes from other records. A board drop, in protobase.ui.tsx under boardDrops, says which columns take a card and what a drop on each writes instead: by the column’s value, a function that gets the card’s record as listed, its key and ETag, the column’s value as to, and the API client. It resolves a function that undoes the write, or nothing when it cannot be undone:
export default defineUi({ boardDrops: { decide: { approved: async ({ record, client }) => { const created = await client.create('decisions', { quote_id: record.id, verdict: 'approve' }) return async () => { await client.remove('decisions', created.record.id as number) } }, }, },})The list names it with drag: { board: 'decide' }, which works when by is read-only. A card moves only from and to the columns the board drop lists: one in another column stays in it, as does a card dropped on another column, or on the column of records without a value. After the write the record is read again, and the card lands in the column its value now puts it in, which may not be the one it was dropped on; the toast says which, with Undo when the write gave an undo. A refused write puts the card back with the reason. Moving a card still takes the right to update the resource and the record, and on a ranked board a card dropped in another column lands where its rank puts it. A list naming a board drop the UI config does not register says so in place of its board.
Moving cards by another field
Section titled “Moving cards by another field”Some boards are by a field the database computes, such as a task’s status, from a field people do write, such as the lane a task waits in. drag: { board: { set, columns } } saves the column’s value in that field instead, and only in the columns it names:
.list((r, d) => ({ columns: [r.title, r.status], displays: [d.board({ by: r.status })], drag: { board: { set: 'lane', columns: ['parked', 'queued'] } } }))A card moves only from and to the columns columns names, every column when it is left out: a card in another column stays in it, as does one dropped on another column. A drop is one update of the record, set set to the column’s value with the ETag the card was listed with, which the resource’s access rules, validate and the database’s triggers decide. After the update the record is read again, and the card lands in the column its by value now puts it in, which may not be the one it was dropped on; the toast says which, with Undo, which puts back the value set had with the ETag of the record as read again, so a trigger that wrote the record again after the update does not make it stale. On a ranked board a card dropped in another column lands where its rank puts it. set must be a field the API writes, and every column a value it takes, or the view is refused; without set the drop saves by, which must be writable.
A trigger refuses a drop by naming a check the resource declares with .checks(), so the card goes back with that check’s label, filled with the card’s values; a check it does not declare says only that the database refused the change:
raise exception 'Task % waits until %', new.id, new.waits_until using errcode = 'check_violation', constraint = 'tasks_parked_by_hand';A filter the list opens with
Section titled “A filter the list opens with”view('repairs').list((r) => ({ columns: [r.number, r.status], filter: 'in(status, "todo", "doing")',})).filters((r, w) => [w.facets(r.status)])filter is an AIP-160 filter the list opens with when its address names none, whichever display it shows. Written in the form the widgets read (status = "todo" or in(status, "todo", "doing") on a facets field), it shows as the widgets’ chips, which the person can clear or change; the change is kept in the page’s address (an empty ?filter= is a list cleared of it), and opening the list from the menu starts from the default again. A link’s own filter replaces it, and so do “View all”, a stat or a chart slice, which open on exactly what they counted. A board leaves out the columns a top-level = or in(...) clause on its field rules out. protobase build checks the filter against the resource, and protobase doctor checks that an index serves it.
More than one list
Section titled “More than one list”view<typeof changelog>('changelog') .names({ singular: 'Changelog entry', plural: 'Changelog' }) .list(...) .namedList('updates', (v) => v .names({ singular: 'Update', plural: 'Updates' }) .nav({ group: historyNav, order: 1 }) .list((r) => ({ columns: [r.closed_on, r.title], sort: [[r.closed_on, 'desc']] })) .filters((r, w) => [w.dateRange(r.closed_on)]))namedList(name, build) adds another list of the same resource, with a sidebar entry of its own at /<resource>?list=<name>. The callback gets a fresh view and sets its names (the entry’s label, required), nav, help, list, filters and chart; none of them come from the view’s own list, so it has its own columns, opening filter and displays. Everything else stays the view’s: field hints, title, actions, the record page, export, import, create and saved searches. A record opened from a named list lives at the resource’s one address, /<resource>/<key>, and the sidebar marks the resource’s main entry there. protobase build and protobase doctor check a named list like the view’s own list, and /meta prunes it the same way. The builder throws on a name that does not fit an address, a repeated name, a missing names, anything else set in the callback and nav.recent; a view with listOf or searchesOf cannot have named lists. A named list is not offered in the bottom bar, the user menu or a page’s blocks.
Filters and the chart
Section titled “Filters and the chart”import { customersView, repairsView as named } from './step-2'
// Step 3: the filters the front desk reaches for, and a chart of bookings above the list.
export { customersView }
export const repairsView = named .filters((r, w) => [ w.facets(r.status), w.facets(r.mechanic, { search: true }), w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] }), w.range(r.estimate, { histogram: true }), w.toggle(r.paid), ]) .chart((r) => ({ field: r.booked_on, range: '30d', granularity: 'day' })).filters((r, w) => [...]) puts widgets above the list, in order. Each needs a field that is .filterable(), which protobase build checks, and an index that serves it, as the scan guard and protobase doctor check; together they write the list’s ?filter=, so a filtered list can be bookmarked and shared.
| Widget | |
|---|---|
w.facets(r.status, { search? }) |
A menu of the field’s 50 most frequent values with counts, never all of them; search adds a search box that narrows those. On a relation it is a dropdown that shows the 50 most frequent too and searches the referenced records as you type, the first 20 matches, through the related resource’s search fields (without any, the box narrows the 50 by name); on a number field, a range slider. |
w.dateRange(r.booked_on, { presets? }) |
Buttons for today, yesterday, 24h (the last 24 hours, rolling), 7d, 30d, 90d, month, quarter, year. Without presets: today, 7d, 30d, year. |
w.range(r.estimate, { histogram? }) |
A slider between the lowest and highest value; histogram draws the values’ histogram behind it. The list filters when a thumb is let go of, or has rested a second. |
w.toggle(r.paid) |
A switch for a boolean field. |
w.flags([r.for_sale, r.for_rent], { label }) |
A menu of boolean fields under one label, with how many records have each: a record shows when any chosen field is true, so one that is both shows under each. |
A list without rows says why, in the table, the cards and the phone’s List alike: No repairs match “zzzqqq”. with Clear search after a search, and Clear filters too while filters are set; No repairs match these filters. with Clear filters; and No repairs yet. with the New button for a user who may create one. Clear filters keeps the search.
Every widget takes secondary: true (e.g. w.facets(r.agent, { secondary: true })): it waits behind the bar’s More filters menu until it is picked there, and shows in the bar whenever it is set, such as from the address. The panel layout and the phone’s filter sheet show every filter.
The widgets’ counts and ranges and the list’s chart load together as one :batchAggregates request, so a page with many filters reads a large table a few times rather than once per filter. Counts that could not be loaded say Could not load the counts in their menu, and a chart that could not be loaded says Could not load the chart., never zero counts or empty bars.
Charts (graphs): records per day or week, or per value, above a list
Section titled “Charts (graphs): records per day or week, or per value, above a list”A list can show a graph of how many of its records fall on each day or week, such as a daily graph of new listings. .chart((r) => ({ field, range, granularity })) draws the list’s records per day over a date or timestamp field as bars above the list, following its filters, headed by their total and how much the second half of the bars differs from the first. range is how far back it reaches: 7d, 30d, 90d, 1y or all. A Day and Week switch changes the bars, and Week shows the last 12 weeks whatever the range; granularity: 'week' opens it on weeks. hour and month are accepted and show days, as hourly and monthly bars are not built.
It can show the list’s records per value of a field instead, such as orders per status or revenue per customer: .chart((r) => ({ groupBy: r.status, type: 'donut' })). groupBy is a filterable field that is no date, such as an enum, a boolean or a relation, with an index that serves it; type is bar (the default, the largest first) or donut; sum: r.total or average: r.total adds up a numeric field instead of counting (a donut takes no average); limit is how many values it shows, 10 by default. Each value links to the list filtered to it, and follows the list’s filters, its own terms on groupBy included. A date, file or JSON groupBy, or a sum of a field that is no number, stops the server at startup, and a user who cannot read one of its fields sees no chart. A page shows the same with the Chart block.
List displays
Section titled “List displays”Besides its table, a list can show as cards, on a map, as a board in columns of its status, on a calendar of a date, as a timeline of bars from a start to an end date, or as a component of the project’s own. The list stays at /<resource>, read through the list API, with its search, filters, chart, order and New button; only the way the rows are drawn changes.
import { component } from '@protobase/layout'import { l } from '@protobase/schema'import { repairsView as daily } from '../bike-shop/step-5'
// The bike shop's repairs as cards, as a workshop board and on a calendar of their booking days beside the table, and a// repair's page with the customer's earlier repairs: a custom component inside the standard `/repairs/<key>` page.
/** The other repairs of the repair's customer, drawn by the `CustomerRepairs` export of protobase.ui.tsx. */export const CustomerRepairs = component<{ limit: number }>('CustomerRepairs')
export const repairsView = daily .list((r, d) => ({ columns: [r.number, r.customer_id, r.bike, r.status, r.estimate, r.booked_on], sort: [[r.booked_on, 'desc']], search: [r.number, r.bike], displays: [ d.cards({ title: r.bike, subtitle: r.customer_id, badge: r.status, meta: [r.number, r.booked_on] }), d.board({ by: r.status, title: r.number, subtitle: r.bike, meta: [r.mechanic] }), d.calendar({ start: r.booked_on, title: r.number }), ], default: 'board', // A repair moves to another column of the board by dragging it drag: { board: true }, })) .layout((r) => [ l.section('The bike', [r.customer_id, r.bike, r.problem]), l.section('In the workshop', [r.status, r.mechanic, r.notes]), l.custom(CustomerRepairs, { title: 'Earlier repairs of this customer', props: { limit: 5 } }), l.sidebar([r.status, r.estimate, r.booked_on]), ])| Display | |
|---|---|
d.cards({ image?, title?, subtitle?, amount?, badge?, code?, meta?, footer?, flags?, dots? }, { name?, label?, icon?, card?, photos?, favorite? }) |
A card per record, opening it: image, a file field, as a picture across the card’s top (a raster image; anything else leaves the frame empty), then title (default: the view’s .title) over subtitle, badge drawn as a badge with its value labels, amount the first of its fields with a value in bold (its suffix, such as /month, not), such as a purchase price or else a rent, code its value in full as a block of monospaced text that wraps its long lines, never cut off, such as a shell command, left out when empty, and a few small meta fields such as dates, each only when it has a value, after its field’s .icon and as a badge when its field’s format is badge. footer is a line at the card’s bottom of its fields with a value, joined by bullets, such as a place and an agent. flags are boolean fields shown as small badges of their labels when true, such as a garden or parking. dots are related columns of the list, each a line of its dots at the card’s bottom. A relation shows the name of the record it points at. With card, a component declared with component('RepairCard') draws each card’s content from the row of those fields instead (see Record cards). With photos, the picture steps through more photos, by swipe or arrows (see Card photos). With favorite, a heart in the card’s top right corner saves the record (see Favorites). Named cards unless name says otherwise. |
d.map({ latitude, longitude, approximate?, exact?, radius?, area? }, { name?, label?, icon?, cards?, defaultRadius? }) |
The matching records in the map’s view, with how many there are below it; it asks again as it pans and zooms, through the list API’s :map. From far out it shows a count for each part of the map, which zooms in when chosen; close in, or with few records in view, the records themselves. Nearby records share a marker with their count; choosing one shows the record’s card at the map’s bottom, with arrows through the marker’s records, and choosing the map elsewhere or closing the card clears it. The card is the one of the cards display cards names, else the list’s first cards display, else the record’s title. A record at an approximate position has a hollow marker and the area around it; see Approximate positions. Named map unless name says otherwise. See Maps. |
d.board({ by, title?, subtitle?, badge?, meta? }, { name?, label?, icon? }) |
A column per value of the enum field by, each with how many records have it, and a card per record that opens it: title (default: the view’s .title) over subtitle, with badge and a few small meta fields, as the built-in card of d.cards draws them. With the list’s drag: { board: true }, dragging a card to another column, or moving it with the keyboard, saves the record with that column’s value, or with drag: { board: 'name' } runs that board drop’s write; with drag: { rank: true }, cards are reordered within a column when the resource has a .position(). Named board unless name says otherwise. See Boards. |
d.calendar({ start, end?, title? }, { name?, label?, icon? }) |
The records on the days from their date or timestamp field start to end, or on their start day alone, in a month grid or a week grid, each event a link to its record showing title (default: the view’s .title). Dragging an event to another day, or moving it with the keyboard, saves the record with start and end moved by the same days. Named calendar unless name says otherwise. See Calendars. |
d.timeline({ start, end?, group?, title? }, { name?, label?, icon? }) |
A Gantt-style timeline: each record a row with a bar from its date or timestamp field start to end, or on its start day alone, over a week, a month or a quarter, in lanes by the values of group. Each bar is a link to its record showing title (default: the view’s .title). Dragging a bar along its row, or moving it with the keyboard, saves the record with start and end moved by the same days. Named timeline unless name says otherwise. See Timelines. |
d.custom(Component, { name, label, fields, props?, icon? }) |
The rows drawn by a custom component. fields are the fields it shows, loaded with the names of the records relations point at; props are plain data, with r.field where it takes a field. |
With displays, the list page has a switch at the right of its title: the table first, then each display by its label, with its icon (table, cards, kanban, board, list, calendar, timeline or map). Below the md breakpoint (768px) the switch is a menu of the same choices. The choice is in the address, /repairs?display=cards, so a reload, a bookmark or a shared link opens the same display; default names the display /repairs opens in, the table when it is left out. On a phone, below Tailwind’s sm breakpoint (640px), the list opens in its default too, the table included; a list without a default opens in its first cards display there instead. A list with neither opens in a built-in List there: a row per record with its .title, the first enum column as a badge on its right, and the next two columns but booleans on a muted line below, at ?display=rows. The display menu offers the table beside it. A ?display= in the address wins on any screen. A display without column headers has a sort menu over the sortable fields it shows, beside the filters, or below md in the filters sheet, whose button sits left of the search box. Selecting rows, deleting them in bulk and the row menu stay on the table, which every list keeps.
The table, the cards, a board, a calendar and a timeline scroll with the page, which is as tall as all their rows, with the browser’s own scrolling: only the rows and cards in view are drawn and loaded, so a list of any length scrolls at once. Coming back to the table or the cards, by Back or by a link to the same list, shows the same rows at the same height, after a reload too; another sort or filter starts at the top. The table’s header stays below the top bar while the page scrolls. Every card is as tall as the tallest one drawn at that width. A custom display scrolls with the page as well, as every other page of the app does; the map fills the screen between the top bar and a phone’s bottom bar instead, and does not scroll. Where scrollbars take room, as on Windows, the page keeps room for one even while it fits, so the cards keep their width as the scrollbar comes and goes.
Display names are checked when the config loads: unique, not table, and default names one. Their fields are checked when the server starts, and may not be sensitive. In /api/meta, a user’s displays lose the fields they cannot read, and a custom display whose props name one is left out; the list then opens in the table when its default display went.
Boards
Section titled “Boards”d.board({ by: r.status }) shows the list as columns, one per value of the enum field by, in the order the field lists its values. Each column is headed by its value, as a badge with the view’s valueLabels and valueColors, and by how many of the list’s records have it. When by may be empty (.optional()), a last column holds the records without a value, while there are any. default: 'board' opens the list in it, as the workshop above does.
Each column reads its own records through the list API, with the list’s filter, search and order and its value added, such as (search("brompton")) AND status = "ready", page by page with Show more at its bottom. A filter on by itself leaves the other columns empty. The sort menu orders the cards in every column, unless the resource has a position. In an embedded list each column shows its first records, up to the list’s limit, and View all opens the whole board.
With the list’s drag: { board: true } (see Dragging in the list), a card moves to another column by dragging it, by a long press and drag on a touch screen, or from the keyboard: Space on a card picks it up, the left and right arrow keys move it between columns, Space or Enter drops it and Escape puts it back; a screen reader is told each step. A move is one update of the record, by set to the column’s value with the ETag the card was listed with, the same request a named a.update sends. So the resource’s access rules and validate decide: the card shows in its new column at once, a refused move puts it back with the server’s reason, such as validate’s message, and a record changed by someone else since it was listed is refused too, as a stale ETag is. Every list of the resource reloads afterwards. A user who may not update the resource, or the by field, or a record its row filters keep them from updating, can open its card but not move it.
A resource with a .position(...) and no within has its board’s columns in that order instead of the list’s, so the board has no sort menu:
import { f, resource, view } from '@protobase/schema'
// A team's tasks on a board in the order of their rank, each card dragged to its place in a column or to another// column, and the table in the same order, its rows dragged too.
export const tasks = resource('tasks') .table('tasks') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), title: f.text(), status: f.enum(['todo', 'doing', 'done']).filterable().sortable(), rank: f.integer().sortable(), }) .primaryKey((r) => r.id) .position((r) => r.rank)
export const tasksView = view<typeof tasks>('tasks') .title((r) => r.title) .list((r, d) => ({ columns: [r.title, r.status], sort: [[r.rank, 'asc']], displays: [d.board({ by: r.status })], default: 'board', drag: { rank: true, board: true }, }))With the list’s drag: { rank: true }, a card then moves within its column by dragging it, or from the keyboard: Space, the up and down arrow keys, and Space again. In another column it lands where it is dropped, before the card under it or after the last one; the left and right arrow keys put it at the top. A screen reader is told the column and the place. A drop is one batch write: in another column first the update of by, then a move of the card among the column’s cards, anchored to the card above it as on a list sorted by hand, so it saves whatever else changed meanwhile. Access and validate refuse it as they do a column move; a refusal puts the cards back with the reason, or warns that the card was not moved because the board changed where it was dropped, and the columns reload by themselves. The numbers are per column after a drop, so a unique index on the position alone would clash, while one that includes by is fine. Changing the order takes the right to update the position field, as Reorder does; a user without it, or a board without rank, moves cards between columns only, as on a board without a position, and one without board keeps each card in its column. A resource without a position, or with within, keeps the list’s order.
by must be a filterable enum field, checked when the config loads and when the server starts, since each column filters by it. protobase doctor checks that an index serves each column’s filter in the list’s order, or the position’s, as it does the list’s. In /api/meta, a user who cannot read by gets the list without the board, opening in the table when it was the default, and a card loses the fields they cannot read.
Calendars
Section titled “Calendars”d.calendar({ start: r.booked_on, title: r.number }) shows the list’s records on the days of a month or a week: a month in whole weeks, from the Monday on or before its 1st to the Sunday on or after its last day, the days around it dimmed, or a week of seven days. A date field’s record is on its own day and a timestamp’s on the viewer’s day, in their browser’s time zone, as the app shows every time, and weeks start on Monday. A record with an end shows on every day from its start through its end; a timestamp end is the instant it is over, so one ending at midnight is not on the next day. A timestamp event shows its time first. A day of a month shows three events, then +N more, which opens its week with all of them. The view is in the address, /repairs?display=calendar&calendar=month,2026-10-01 or calendar=week,2026-10-12, and the previous, today’s and next month or week, and Month and Week, are links to it; without it the calendar shows this month. An embedded list keeps its calendar’s view to itself.
The calendar reads the days it shows alone through the list API, with the list’s filter and search and the days added, in start order: (search("brompton")) AND (booked_on >= "2026-09-28" AND booked_on < "2026-11-02"), and with an end also the records starting before the first day and ending on or after it, OR (booked_on < "2026-09-28" AND ready_on >= "2026-09-28"). It loads at most 500 records for a month or week, and says so when more match, asking for a narrower filter. Its order is fixed, so it has no sort menu. A record without a start value is on no day, and does not show.
An event moves to another day by dragging it, by a long press and drag on a touch screen, or from the keyboard: Space on an event picks it up, the left and right arrow keys move it a day and the up and down keys a week, Space or Enter drops it and Escape puts it back; a screen reader is told each day. A move is one update of the record with the ETag the event was listed with, start, and end when it has one, moved by the same days, a timestamp keeping its time of day. So the resource’s access rules and validate decide, as they do a board’s moves: the event shows on its new day at once, and a refused move puts it back with the server’s reason. A user who may not update the resource, start or end, or the record, can open its event but not move it.
start must be a filterable date or timestamp field, and end a filterable field of the same type, checked when the config loads and when the server starts. protobase doctor checks that indexes serve the days’ filter on start, and on end when it is set. In /api/meta, a user who cannot read start gets the list without the calendar, opening in the table when it was the default, and one who cannot read end or title gets the calendar without them.
Timelines
Section titled “Timelines”d.timeline({ start: r.starts_on, end: r.ends_on, group: r.crew_id, title: r.number }) shows the list’s records as a Gantt chart: a row per record, its title on the left (above its bar on a phone), and a bar over the days from its start through its end, or its start day alone without an end. Days, weeks and a timestamp end work as on a calendar. The timeline shows a week of seven days from Monday, a month, or a quarter from January, April, July or October, today’s day shaded; a bar that starts before the days shown or ends after them is cut square at that edge. With group, the rows are in lanes, one for each value a record shown has, each headed by the value and its count: an enum’s lanes in the order the field lists its values, headed by their value labels; a relation’s by the names of the records it points at; others by value; and last the records without a value, under No and the field’s label. Within a lane the rows are in start order.
The period is in the address, /jobs?display=timeline&timeline=quarter,2026-10-01, or timeline=week,2026-10-12 or month,2026-10-01, and the previous, today’s and next period, and Week, Month and Quarter, are links to it; without it the timeline shows this month. Switching the scale opens the period holding today when the one shown holds it, else the one holding its first day. An embedded list keeps its timeline’s period to itself. It reads the days it shows as a calendar does, through the list API with the list’s filter and search, the same 500 records at most and no sort menu.
A bar moves along its row by dragging it, by a long press and drag on a touch screen, or from the keyboard: Space on a bar picks it up, the left and right arrow keys move it a day, Space or Enter drops it and Escape puts it back; a screen reader is told the day it starts on. The move saves the record as a calendar’s does, with start and end moved by the same days, so the resource’s access rules and validate decide, and a refused move puts the bar back with the server’s reason. A bar keeps its length; to change it, edit end on the record.
start and end are checked as a calendar’s are, and group may be any field the view may show. protobase doctor checks the indexes of its filter as it does a calendar’s. In /api/meta, a user who cannot read start gets the list without the timeline, and one who cannot read end, group or title gets the timeline without them, in one lane when it is group.
Card photos
Section titled “Card photos”photos: { resource, field, image, sort? } names where a card’s further photos come from: the records of resource whose relation field points at the card’s record, in sort order, each shown by its file field image. The card’s picture snaps photo by photo as it is swiped on a touch screen, and shows a left and a right arrow while the pointer is over it. The photos come with the list’s records, in the same request through the list API’s photos, so every card on the page has them from the start, and a map’s card too. The card’s own image comes first and is not shown twice when it is among the photos too, and a card steps through ten pictures at most, its own among them; the arrows wrap around at both ends, dots under the picture mark the photo shown, and a card with no further photos has no arrows. Swiping or pressing an arrow does not open the record; tapping the picture does. In a row that scrolls sideways, as an embedded list shows its cards on a phone, a swipe scrolls the row instead, and the arrows show at all times on a touch screen. A card drawn by a card component has no arrows.
d.cards({ image: r.photo, title: r.address }, { photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } })The server checks photos when it starts: field is a filterable relation to the list’s resource, image a file field and sort a valid order on resource, and every cards display of the list names the same photos, since its records load with one set. One query reads the photos of the whole page, the first of each record by an index on field and the sorted fields, such as unique (listing_id, position); the scan guard checks that one serves it, as it does a list’s filter. In /api/meta, a user who cannot list those photos, or read field, image or the sorted fields, gets the cards without them, and the list API brings them only the photos they could list themselves.
Favorites
Section titled “Favorites”favorite: { resource, field, label? } puts a heart in each card’s top right corner that saves the card’s record for the signed-in user: a record of resource whose relation field points at the card’s record is created on a press and deleted on the next. The heart fills while the record is saved, at once on screen; a refused write puts it back and says why in a toast. It is a toggle button named label (“Favorite” by default) with aria-pressed, and like the photo arrows it sits over the card’s link, so pressing it does not open the record. All of the user’s saved records load once, page by page, for every card of the list.
A visitor who is not signed in gets the heart too, when the view of resource has a sign-in prompt: pressing it tells them what signing in gives, in a modal on a desktop and a sheet from the bottom on a phone.
The view of the saved records’ resource can list what they point at with .listOf: its list page then shows those records in their own resource’s list, with its displays, filters, sort and search, under its own title and help. Unsaving a record there takes its card away. Its record pages and /api/meta model stay its own.
d.cards({ image: r.photo, title: r.address }, { favorite: { resource: 'favorites', field: 'listing_id', label: 'Save to favorites' } })
// favorites/ui.tsview<typeof favorites>('favorites').names({ singular: 'Favorite', plural: 'Favorites' }).listOf((r) => r.listing_id)The server checks favorite when it starts: resource has an owner (.owner(...)), so the API lists and creates each user’s own, and field is a filterable, writable relation to the list’s resource, which has a single-column key; .listOf needs a relation to a resource with a single-column key. In /api/meta, a signed-in user who cannot list, create and delete those records, or write field, gets the cards without the heart.
Saved searches
Section titled “Saved searches”.saveSearch({ resource, label? }) on a view puts a Save search button beside the list’s title while its filters or search narrow it. A press asks for a name, which may be left empty unless the name field of .searchesOf has no .optional(), showing the filter’s chips, then saves the list’s filter, as the address holds it, as a record of resource, the signed-in user’s own, with the name as given or null; the button is a toggle named label (“Save search” by default) with aria-pressed, pressed while that filter is saved, and the next press takes the search off again. Without a name field it saves at once. A visitor gets the button too when the view of resource has a sign-in prompt, which a press opens.
The view of resource says what a saved search is with .searchesOf(...), and its list page then shows the user’s searches instead of rows, in its list’s order. Each has its name, which links to its record page, and the filter’s chips, which are its title instead when it has no name; its controls, enum fields as a menu and booleans as a switch, each saved as soon as it changes, which a toast confirms, a rename button, which asks for the name as saving does, a delete button, and the records the search finds, as a RecordRow shows them: how many, and the searched resource’s cards in one row that scrolls sideways and loads more as it scrolls, up to limit when it is set. View all results opens the searched list with the search’s filter, and names the search in the address, ?saved_search=<key> (addressWords.savedSearch).
While the list’s filter differs from the search it was opened from, and no other search has it, the button reads Update with the search’s name, beside Save as new search (the noun from the names of the view of resource). Update asks first, in a dialog: each filter added, removed or changed, as the panel’s chips name them, how many more or fewer records the search finds, and the records it would add and drop, the first 12 of each with their counts, drawn as its results are. Those come from the list API, with the filters new AND NOT old and old AND NOT new, where each condition of the negated filter also asks that its field has a value, so that a record the old filter cannot decide (a range on a rent it has none of) counts as not found by it, as the list shows. The dialog updates the search, saves the list’s filter as a new one, asking for its name, or does nothing.
With unseen: { seenAt, field } the row is newest first by field, a timestamp of the searched resource, and the records new to the user, those whose field is after the search’s seenAt, are marked New in their card’s top left corner; when none are, the search says so beside its count. View all results sets seenAt to now. A search saved today marks what is published from today.
view<typeof listings>('listings').saveSearch({ resource: 'saved_searches' })
// saved_searches/ui.tsview<typeof savedSearches>('saved_searches').searchesOf((r) => ({ resource: 'listings', filter: r.filter, name: r.name, controls: [r.alert_frequency], unseen: { seenAt: r.seen_at, field: 'published_at' },}))The view checks its own fields when the config loads: filter and name are text fields, seenAt a timestamp and each control an enum or boolean. The server checks the rest when it starts: resource has an owner, the fields a save or a control writes are writable, unseen.field is a filterable timestamp or date of the searched resource, and a view of the resource a list saves to has searchesOf for that list. In /api/meta, a user who cannot list the searched resource or read filter gets the view without searchesOf, and its controls and unseen narrow to what they can write. A search’s filter is checked like any list’s when its records load; checking it on a write, against the searched resource, is the data config’s: a .validate rule with parseFilter and checkFilter.
To tell users of new records, a job matches each new record against the saved filters with evaluateFilter, given the searched resource as search so that a search text in the filter looks in its search fields too, and sends an email. The property portal example mails at once or in a daily digest.
Exports
Section titled “Exports”Every list has an Export button beside its title, and Export N beside Delete N for the rows selected in its table. Both open one dialog that asks for the format, Excel (.xlsx) or CSV; the rows, those the list finds with its filters, search and sort, or the selected ones; the columns, the list’s own in its order to start with, then any field the user may read, each moved up or down; and the values, As shown, as the list shows them (enum value labels, the names of related records, dates and numbers formatted with the view’s prefix, suffix and decimals), or Raw values, as the API stores them (keys, codes, ISO dates). It says how many rows that is before it starts: counted exactly up to 10,000, the planner’s estimate above.
The rows come through the list API as the user may read them, page by page with its page tokens (POST /{resource}:search, 500 a page), so the scan guard, the role’s row filter and its readable fields apply as on the list; a sensitive field is never offered. The selected rows are found again by their key.
A workbook has one sheet named after the records, a bold header row of the columns’ labels that stays in view, columns as wide as their header and the first page’s values, and typed cells: numbers, dates and times with a number format (as shown, the list’s format; raw, yyyy-mm-dd), booleans as TRUE and FALSE, and text. As shown, a time is on the viewer’s clock, as the list shows it; raw, in UTC, as the API sends it; a 64-bit integer past 2^53 stays text so that no digit is lost, and a text is cut at Excel’s 32,767 characters. A sheet holds at most 1,048,575 rows. A CSV file is UTF-8 with a byte order mark, so Excel reads it as such, quoted as RFC 4180 has it, with a text that starts with =, +, -, @, a tab or a carriage return written after an apostrophe, so that a spreadsheet does not run it as a formula. The file is named after the records and the day, as Orders 2026-10-16.xlsx.
.export(false) takes Export off a view’s list, and .export({ maxRows }) limits how many rows a file holds: the dialog says when the list finds more, and the toast that ends the export says the file holds only the first rows. Like the rest of a view, this only shapes the page: what a user may read is the data config’s access rules, and the API serves it as it does to the list.
view<typeof orders>('orders').export({ maxRows: 50_000 })view<typeof auditLog>('audit_log').export(false)Importing records
Section titled “Importing records”A list page offers Import beside New to a user who may create the resource’s records; .import(false) on the view turns it off, and .import('table') makes it a new table from the file instead, as the Tables list of user tables does. It opens a dialog that creates or updates records from an Excel workbook (.xlsx), a CSV file (UTF-8, its delimiter a comma, semicolon or tab, found from the first line) or a JSON file (.json, UTF-8) that holds an array of objects. See Importing records from a spreadsheet for a walk through.
view<typeof invoices>('invoices').import(false)- File. The first row names the columns; a workbook with several sheets asks which one to read. In a JSON file each object is a row and the columns are the objects’ keys, in the order they first appear; a key an object lacks is an empty cell. Strings, numbers and booleans are kept as the file states them, so
"007"stays text, and a nested object or array is a JSON value. A whole number past 2^53 keeps its digits as text where the browser gives JSON parsing the number’s source text.Import cannot keep every digit of a whole number past 2^53 in a browser without JSON source text access because a JSON parser of its own is not implemented. A file that is not an array of objects is refused.Import cannot read JSON Lines or an array inside a JSON object because readers for those shapes are not implemented. A Web Worker reads the file, so a large file does not hold up the page, and the file itself never goes to the server: only the writes of its rows do. A CSV and a sheet’s rows are read as they stream in, so they are never held whole in memory; a JSON file is read whole, so its size is bounded by the browser’s memory. - Columns. A column whose header is a field’s label or name, ignoring case and spacing, fills that field; each mapping can be changed, or the column skipped. The fields are those the import can write: not read-only, not the tenant, not files, JSON fields only from a JSON file, and relations to records with a key of one field. The fields a new record needs (not optional, without a default) that no column fills are listed, and a create waits for them. A relation’s column holds the related record’s key, or the value of a field the user picks under it, such as a customer’s email. Numbers and Dates say how the file writes what text leaves open:
1,234.56or1.234,56, the day or the month first; they start from the browser’s language. Dates written as2026-12-31read the same either way, and a time without a zone is the browser’s. - Rows. Create makes a record of each row. A user who may also update records can choose Update, which finds each row’s record by a column the user picks, holding its key or a field no two records share (filterable, not sensitive), and skips a row that finds none, or Create or update, which creates that record instead.
- Check. The whole file is read and every row converted before anything is written: the first rows as they will be saved, and each row’s problems, also as a file to download. Nothing is guessed: an empty cell is
null, never the field’s default; numbers and dates in the chosen formats, true or false (true,false,yes,no,1,0), enum values by their value labels or values, related records found by exactly one match, and a JSON file’s values in a JSON field as they are convert, and anything else is a problem on its row, such as a nested value mapped to a field that is not JSON. The import skips those rows. - Import. The rows are written in batches of 100 with
POST /api/v1:batchWrite, so the server validates each and checks the user’s access as it does a single write; an update is sent with the ETag*. Each batch is a transaction of its own, so an import is not all or nothing: a row the server refuses is set aside with the server’s reason, and the rest of its batch is sent again. Cancel import stops between two batches, keeping what was written, and so does an error such as an expired session. The summary counts the rows created, updated, skipped (with problems in the file) and failed (refused by the server), and downloads the rows not imported as a CSV, the file’s own columns followed by each row’s line in the file and its problems, to fix and import again.
Create pages
Section titled “Create pages”When a resource’s records are made by a process rather than a form, such as an app a server sets up or an order from a cart, its view names a composed page of the app’s own that creates them, with .create({ page }):
view<typeof repairs>('repairs').create({ page: 'book-repair' })/<resource>/newshows that page instead of the create form, so the list’s New button and every create address open it. The breadcrumb reads the resource and New, as for the form.- New shows to whoever
/api/metagives the page, as itsrolessay, whatever the resource’screateaccess. The resource’s API can then refuse creates (create: () => false) while the page creates through an API function that writes withdb. Someone without the page gets no New, and/<resource>/newtells them they cannot create there: the create form never shows. Import still follows the resource’screateaccess. - The address’s
valuesstay in it. A component on the page reads them withuseAppAddress()and can keep its answers there as they are given, so a reload, a link, or a round trip through another site keeps them. See Create pages. - A create address’s
valuesmay name what is not a field of the resource, such as{ kind: 'create', resource: 'tasks', values: { objective_id: '{{id}}' } }for a task’s objectives kept in a join resource, since the page reads them. Its{{field}}placeholders are still checked against the record the link sits on. A resource without a create page still refuses such values, as its create form would drop them. - The server refuses a page that does not exist when it starts.
A create page of your own builds one step by step.
Opening the existing record
Section titled “Opening the existing record”The create form at /<resource>/new, not a page of the app’s own, can open the record a create repeats. When the resource has .openExisting(), and the server answers the create form’s save with that record’s key, the form opens that record at its own address, as it opens a record it created, with no error. A start of a direct message with the same people opens the conversation there is. A user who may not read that record gets the usual “Could not save” toast, as for any record with the same unique value.
Sign-in prompts
Section titled “Sign-in prompts”.signIn({ title, description, benefits?, icon?, signUp? }) on a view tells a visitor who is not signed in what they could do with the resource once signed in. Where a signed-in user sees the list, the visitor sees the prompt: an icon (icon, as for field hints, a sign-in icon by default), title, description and a line per benefits, with Sign in, which opens the sign-in page and comes back to the same address. A card’s favorite button that saves to the resource, and a list’s Save search button that saves to it, open the same prompt as a dialog, with Not now to close it. With open sign-up on the server, the prompt also offers Create an account, which opens the app’s own sign-up page. signUp: { label, href } names a page elsewhere instead, https://, http:// or mailto:, opened in a new tab. A visitor is most likely new, so where the prompt offers to make an account, that is its primary action and Sign in the secondary one.
view<typeof favorites>('favorites').signIn({ title: 'Keep the homes you like', description: 'Sign in to save listings to your favorites and find them again on any device.', benefits: ['Save a listing with the heart on its card', 'See all your saved homes on one page'], icon: 'heart',})Only a caller without a token gets the prompts, in /api/meta as signIn, for the resources they cannot see whose view for the anonymous role has one: its names, its sidebar place and the prompt. Those resources keep their place in the sidebar, the bottom bar and the user menu. Pages of the project can show a prompt too: SignInPrompt from @protobase/ui takes it as="page" or as="dialog", and ResponsiveDialog is the modal that becomes a sheet on a phone.
The record page
Section titled “The record page”import { l } from '@protobase/schema'import { customersView, repairsView as filtered } from './step-3'
// Step 4: a record page that reads like the paper repair card: what is wrong, who works on it, what it costs.
export { customersView }
export const repairsView = filtered .fields((r) => ({ problem: r.problem.help('In the customer’s words; the mechanic adds findings to the notes.'), notes: r.notes.label('Workshop notes').help('Only the workshop reads these.'), paid: r.paid.help('Set when the customer pays at the desk.'), })) .layout((r) => [ l.section('The bike', [r.customer_id, r.bike, r.problem]), l.section('In the workshop', [r.status, r.mechanic, r.notes], { help: 'Pick up a repair by putting your name on it.' }), l.section('Money', [r.estimate, r.currency, r.paid]), l.sidebar([r.status, r.estimate, r.booked_on]), ]) .saveFeedback('button').layout((r) => [...]) with l from @protobase/schema:
| Item | |
|---|---|
l.section(title, fields, { help?, helpWhen?, presentation?, when? }) |
A titled group of fields in the main column, editable where the user may write. presentation: 'facts' shows them on the read view as a row of key facts. |
l.group(title, items, { collapsed?, when? }) |
A heading over sections and related tables, closed until opened with collapsed: true. when also takes a condition. See Groups. |
l.tab(title, items) |
A tab holding main-column items; a view’s tabs show as one strip on the read view and the form. See Tabs. |
l.sidebar(fields, { when? }) |
A summary card beside it, read-only, each value on one line, cut off with an ellipsis when it does not fit and shown whole on hover. The record’s created and updated times show in a Details card below it, but for those the summary lists. when also takes a condition. |
l.related(title, { ... }) |
A table or cards of the records of another resource that point at this one, in the main column. See Related records. |
l.custom(Component, { title?, props?, sidebar?, when?, fallback? }) |
A custom component where it is listed: in the main column under title, or with sidebar: true as a sidebar card. fallback shows in its place where it cannot be drawn. |
l.map(title, { latitude, longitude, zoom?, sidebar?, when? }) |
A map with a pin at the record’s position, in the main column or with sidebar: true as a sidebar card. See Maps. |
l.chart(title, { resource, field, at, series, range?, help?, when? }) |
Line graphs of numbers of the records that point at this one, such as a machine’s samples, over the last hour, day or week. See Charts of related records. |
l.thread(title, { resource, field, sender?, time, text, status?, working?, limit?, empty?, help?, when? }) |
The record’s conversation: the latest messages that point at it, oldest first, under each sender’s name and time. See Conversations. |
l.blocks(tree, { when? }) |
A tree of layout blocks, written in JSX as a composed page’s, that reads the record as @root. |
l.composer({ resource, field, text, placeholder?, when? }) |
A box that sends a message about the record, which the thread then shows. See Conversations. |
l.gallery(title, { image?, photos?, when? }) |
The record’s photos as tiles, opening a lightbox. See Galleries. |
l.history(title?, { limit?, when? }) |
The record’s changes, newest first, with who made each and the fields before and after; needs .history() on the resource, and a view without a layout shows it last by itself. See Record history. |
l.comments(title?, { when? }) |
The record’s comments, oldest first, with a box to write one that @mentions people; needs .comments() on the resource, and a view without a layout shows it last by itself. See Record comments. |
A custom component draws only its part: the page around it stays the record page, at /<resource>/<key>, with its breadcrumbs, Save, the action rail with Edit and Delete, and the related records, and a layout may hold only custom components. The repairs above list the customer’s earlier repairs under the bike:
Without a layout the record page shows one section with every field the user may change; its read view, which is what a user who may change none gets, shows every field. A section or sidebar card with no field the user may see is left out. On a wide screen the sidebar cards stay in view beside the main column as the page scrolls, below the top bar. The record’s title is the page’s heading, above the sections, with an enum status as a badge beside it unless the sidebar shows it already, or the field .titleBadge(...) names. .saveFeedback('button') shows saving on the Save button instead of a toast ('toast', the default). A sensitive field in a section is masked, with an eye button that reveals it. A write-only field is on the form only where a section names it, never in the section without a layout, and shows as an empty input to set a new value in.
A record opened from a list, by its row or its card, shows the fields the list loaded at once, with placeholders for the others, and takes input once the whole record has loaded; actions, custom components, maps and galleries wait for it. What the page shows is read again whenever the browser tab or window regains focus, as are the lists, unless the record has unsaved changes, which keep the version they were made to.
Page width
Section titled “Page width”The record page sits in a centred column about 1100px wide. .recordWidth('full') makes it fill the content pane beside the sidebar instead, with the sidebar cards still on the right, for a record with wide sections or related tables, and makes its create form as wide; 'column' is the default. On a phone both look the same.
view<typeof objectives>('objectives').recordWidth('full')Read-only values and a title badge
Section titled “Read-only values and a title badge”On the form, a field nobody may change there, such as a .readOnly() field or one the user may only read, shows as its value rather than a greyed input, as the read view shows it: at full text contrast, an enum or a field with .format('badge') as a badge in the view’s valueLabels and valueColors, a timestamp with .format('relative') as “3 hours ago” with the exact time on hover, and a missing value as a dash that screen readers read as “No value”. Its label is text rather than a form label, since there is no control for it to name.
.titleBadge(...) shows one field as a badge beside the record’s title, in its valueLabels and valueColors, such as an objective’s verdict, in place of the enum status the page shows there otherwise. It shows even when the sidebar lists the field, changes as the record does, and is left out while the field has no value or for a reader who cannot read it. .titleBadge(...) throws when the field does not exist, or is neither an enum nor shown with .format('badge'), so a long text never fills the header.
view<typeof objectives>('objectives') .fields((r) => ({ verdict: r.verdict.label('Verdict').valueColors({ moving: 'green', stuck: 'red' }) })) .titleBadge((r) => r.verdict)A record page that opens another
Section titled “A record page that opens another”.recordOpens(to) sends a record’s page to another address in its place, its {{field}}s, in the resource, the key and run, filled from the record, replacing the record’s address in the history so Back skips it: a workflow run’s page opens its workflow’s page with the run on the graph. A caller who cannot follow it, such as one who may not read the resource it names or open the page it names, gets the record’s own page, and so does a record without a value for a field it names, such as a custom step’s test run, which has no workflow. A list of addresses opens the first the record fits. The record’s own page stays at its address with ?standard=true.
view<typeof workflowRuns>('workflow_runs').recordOpens({ kind: 'record', resource: 'workflows', key: '{{workflow_id}}', run: '{{id}}' })A record address can also carry version, an earlier saved version of the record shown by a field type that keeps versions, such as the workflow field type: the record page then shows its read view, without Save or Edit.
Open elsewhere
Section titled “Open elsewhere”A record that is read and used on another page, such as a chat message in its channel, can open there wherever it is found. Give .recordOpens(...) a list of addresses built from the record’s fields: the first whose {{field}}s all have a value in the record opens in place of the record’s own page, as a row button picks its choice. A record that fits none shows its own page.
view<typeof messages>('messages').recordOpens([ { kind: 'record', resource: 'channels', key: '{{channel_id}}' }, { kind: 'record', resource: 'direct_messages', key: '{{direct_message_id}}' },])- The record is read first, with the reader’s own access: a record they may not read shows the usual not-found notice, and the page it opens applies its own access rules. A choice the reader cannot follow, such as one naming a resource or field they may not read, is skipped.
- The top bar’s search results link straight to the address their record opens, so the link preview shows where it goes. Any other link to
/<resource>/<key>opens the record’s address first and then replaces it in the history with the target, so Back returns to the page before. - The record’s own page stays at its address with
?standard=true.
Full-area record pages
Section titled “Full-area record pages”.record({ component }) makes the record page at /<resource>/<key> a custom component of the app’s own, for a record that is used rather than filled in, such as a chat channel. The component fills the content area, at full width beside the sidebar and down to the bottom bar on a phone, and the page does not scroll, so the component scrolls its own parts, such as messages above a box that stays at the bottom. The sidebar, the top bar with its breadcrumb naming the record, since the page has no heading, the bottom bar and a right panel stay; the heading, Save, the action rail, the sections, the related records and the Details card are not drawn. A record that does not exist, or that the user may not read, shows the record page’s usual notice, and the component is never drawn.
export const ChannelChat = component('ChannelChat')
view<typeof channels>('channels').record({ component: ChannelChat })The standard record page, with the layout’s sections, the related records, Edit and Delete, stays at the record’s address with ?standard=true ({ kind: 'record', resource, key, standard: true }), which the component links to. Links to the record, from relations, search and notifications, open the component’s page. Without the component, from a plugin that is off for instance, and when it throws, the standard page shows instead. .record are not implemented.
Conversation pages
Section titled “Conversation pages”.record({ conversation }) makes the record page the record’s conversation, for a record that holds one, such as a chat channel, a direct message or a support case, with no component of the app’s own. It fills the content area as a full-area record page does, on the web and at mobile width: a header row, the messages that point at the record, and a box that sends one, which stays in view while the messages scroll above it. The messages it opens on, and a thread’s, show once their reactions, files and formatted text are ready, and an image whose width and height are stored keeps its room while it loads, so nothing moves under the reader while the page loads. width and height cannot keep its room while it loads because reading an image’s size before it loads is not implemented.
view<typeof channels>('channels').record({ conversation: { resource: 'messages', field: 'channel_id', sender: 'author_id', time: 'sent_at', text: 'body', edited: 'edited_at', mentions: 'mentions', subtitle: 'topic', readPosition: { resource: 'read_positions', field: 'channel_id', message: 'last_read_id' }, placeholder: 'Message the channel', edit: true, delete: { unless: 'reply_count > 0' }, reactions: { resource: 'reactions', field: 'message_id', user: 'user_id', emoji: 'emoji', labels: { thumbs_up: { symbol: '👍', name: 'Thumbs up' }, heart: { symbol: '❤️', name: 'Heart' } }, }, thread: { field: 'thread_id', count: 'reply_count', last: 'last_reply_at' }, attachments: { resource: 'attachments', field: 'message_id', file: 'file', width: 'width', height: 'height' }, call: 'call', },})conversation option |
|
|---|---|
resource |
The message resource. |
field |
The filterable relation of the messages that holds the record’s key; each message sent gets it too. |
sender |
Who wrote each message: a relation, named as the record it points at, or a text field of user ids, such as the resource’s .author(), named after the organization’s members. |
time |
When each message was sent: a sortable date or timestamp field. |
text |
The message: a text field the sender may set. |
edited |
A date or timestamp field set when a message changes: a changed message says “(edited)”, with the time on hover. |
mentions |
A JSON field for the user ids a message mentions: @ in the box lists the organization’s members by name, the ids of those picked land in it, and the text shows each mention picked out. |
subtitle |
A text field of the record shown beside its title, such as a channel’s topic. |
members |
A JSON field of the record holding user ids: the header names the other people in it, each with their presence and status, the status text in full beside one person and on hover beside several. The record is titled after them everywhere, as the members title rule does. |
readPosition |
Where each reader’s read position is kept: { resource, field, message }. |
placeholder |
The hint in the empty box. |
empty |
What the conversation says while it has no messages. |
edit |
true: a message’s author changes its text and mentions in place, as the message resource’s update access allows. |
delete |
true: anyone the message resource’s delete access allows deletes a message, after confirming; or { unless }, a condition on the message’s own fields that keeps it, such as reply_count > 0. |
reactions |
Emoji reactions under each message: { resource, field, user, emoji, labels }. |
thread |
Replies in a thread under a message, in a panel beside the conversation: { field, count, last }. |
attachments |
Files a message carries, kept in a resource of their own: { resource, field, file, width, height }. |
call |
The record’s call, by the name of the API function that admits people to it. |
typing |
true: a line above the box says who else types, by their names among the organization’s members, and the others hear while the reader types, each shown until six seconds after the last they sent or until they send or empty the box; a thread’s panel says who types in that thread alone. It works with or without a relay: through the app’s realtime relay when it has one, whose channel resources then include the record’s resource, and otherwise over the record’s own channel, which only those who may read the record join. |
The header shows the record’s title, which the top bar repeats at mobile width and so shows there only with members, the subtitle, the call with call, and Details, a link to the record’s standard page at ?standard=true, with its sections, Edit and Delete. The latest 50 messages show oldest first, with Load earlier messages at the top for more. A day divider opens each day, and one person’s messages sent within five minutes of each other show under their name once. A message resource with .live() shows new, changed and deleted messages as they happen. Every read goes through the reader’s own access: a message they may not read never shows, and a reader who may not read the messages, a field each one needs or the fields of thread gets the standard page. The box shows for a reader who may create messages.
With readPosition, the conversation opens on a New messages line above the first message someone else wrote since the reader’s position, and moves the position to the highest message key shown whenever they read to the end; it never moves back, even when another tab of the same reader moved it further. The read position resource keeps one record per reader and record: its .author() is the reader, a filterable field, field is a filterable relation to the record and message an integer field holding the key of the newest message read, both writable, so the message resource’s key is one integer column that grows as messages arrive. The page reads and writes only the reader’s own position. readPosition, there is no line and nothing is written.
Reactions, edits, deletes and threads
Section titled “Reactions, edits, deletes and threads”With reactions, edit, delete or thread, people act on the messages where they read them. With a pointer, a bar over a message’s corner shows while they point at it or move into it with the keyboard: an emoji they have not reacted with yet, Reply in thread, Edit and Delete. On a touch screen, a tap or a long-press of half a second opens the same actions in a sheet from the bottom at mobile width, with every emoji and Copy text; a tap while the reader types only lowers the keyboard, and a button that only a keyboard or screen reader reaches opens the sheet too. The message’s own links and buttons keep their tap and click. Each action shows only where the reader’s access allows it, and the server checks every write again: a refused one changes nothing and shows the server’s reason.
- Reactions:
resourcekeeps one record per person, message and emoji:fieldis its filterable relation to the message,userthe text field of the user id of the person who reacted, set by the server, such as its.author(), andemojian enum field whose values, in their order, are the emoji offered.labelsgives each value itssymboland itsname, which a screen reader reads. Under a message, one chip per emoji shows how many reacted, naming them on hover: pressing your own takes it back, and another’s adds yours. The reactions of a page of messages are read together with it, and with.live()they change as people react. - Edit: Edit turns the author’s message into a box with its mentions kept: Enter saves, Shift+Enter starts a new line and Escape cancels.
- Delete: Delete asks before the message goes for everyone. A reader who may not read the fields
unlessreads gets no Delete. - Threads:
fieldis the filterable relation of the messages to themselves that holds a reply’s first message, empty for a message of the conversation itself,countan integer field holding a first message’s number of replies andlasta date or timestamp field holding when its last reply came, both kept by the database, such as by a trigger. The conversation shows only messages outside threads; under a message with replies, a link names how many and when the last came. It and Reply in thread open the thread at?thread=<key>, so a link can open it too: in a panel beside the conversation, covering the screen at mobile width, with the first message, its replies and a box of its own that replies in the thread. An address naming a message of another conversation opens no thread there. A reply gets its first message’s conversation from the box, so keep the two the same in the database, such as by a check in the trigger that counts the replies, as an API create can set them apart.
Files in messages
Section titled “Files in messages”With attachments, people share files in a message and see them under it. A button left of the box opens the file picker, and files pasted into the box or dropped on it join the message too. Each file uploads as soon as it is picked and shows above the box with its size, how far its upload is, or why it was refused, with a button that takes it off: a file larger than the file field’s maxSize is refused before it uploads, and one the server refuses shows the server’s reason. The message waits for the uploads still on their way, and once a file is uploaded it may go without text. The message and its files are written in one batch, so the message never shows without them.
Under a message, an image shows as a preview at most 240 pixels high that opens it in a new tab, and any other file as a link with its name and size that downloads it. The files of a page of messages are read together with it, through the reader’s own access, and their links are those the API signs for the reader. Delete deletes a message’s files first, in the same batch.
resourcekeeps one record per file:fieldis its filterable relation to the message andfileits file field, whose value gives the file’s name, type and size.widthandheightare integer fields of an image’s size in pixels, such as those a.derive({ width: imageSize('width'), height: imageSize('height') })on the file fills, so an image takes its place before it loads. Both are optional.
A message of files alone has no text, so the message resource’s text field is optional. A reader who may not read field or file sees no files, and the box offers none.
With call, people start or join the record’s call from the conversation’s header, and talk in it beside the messages, while what they write stays the conversation’s own messages. call names the API function that admits people to the call with calls.join, as in Admitting members; the page opens its socket with the record’s key as key:
import { defineFunction } from '@protobase/server'
export default defineFunction(async (request, { session, acceptWebSocket, calls }) => { const key = new URL(request.url).searchParams.get('key')! return acceptWebSocket(await calls.join({ record: { resource: 'channels', key }, member: String(session.user.id), publish: true }))})The header shows Start call while no call goes on, and “Call in progress · 3 · Join” while one does, live, as the call mark does. Start call and Join are links to the record’s page joining its call, ?call=join, which shows the call view beside the messages, or above them at mobile width, each taking half the space, so the box stays in view. People in the call are named after the organization’s members. A thread opens after both, covering the screen at mobile width while the call goes on under it, and opening or closing a thread keeps the call. Leave goes back to the conversation alone.
sender is a relation because matching a related record to the reader is not implemented; a sender of user ids, such as the resource’s .author(), gets it.Focus pages
Section titled “Focus pages”A focus page is for work on one big thing, such as a graph, a map or a canvas: a thin bar under the top bar, one notice at a time, a surface that takes the rest, and at most a panel on each side. The page does not scroll, so the surface is the window, and it is a sibling of the form rather than a change to it. Any record can have one:
// One field fills the page, drawn by its field type, and the framework saves itview<typeof boards>('boards').record((r) => ({ surface: r.pins }))
// A component of the app's own, in the same frameview<typeof reports>('reports').record({ component: component('ReportStudio'), focus: true })The bar gets the record’s state, Save, its actions behind “…”, Discard changes while there are any, and a link to the form at ?standard=true, named after the record, such as Workflow details, where the layout’s sections and related records stay. A refused save, a conflict and a restored draft show in the notice, a reader who may not change the record gets no Save, and the form shows instead when the surface throws. A caller who may not read the surface’s field gets the form. The record’s name is in the breadcrumb, with a hidden heading for screen readers. What fills the bar and panels, and how a surface reaches them, is under Focus pages. .record(...) with surface needs a field type that draws the whole area; the built-in workflow field is one.
A create address can open a page in place of the form too, for a record made where it is used, as a workflow’s test run is made in the workflow’s page. .createOpens(to) replaces the address, its {{field}}s filled from the address’s values; when the address’s values lack any of those {{field}}s, or the caller may not open the page, the create address shows what the view shows without it: its .create(...) page when it has one, else the form. A record address’s panel (?panel=<name>) names a panel its surface opens with.
Read view and edit
Section titled “Read view and edit”.recordMode(mode) says how the record page opens to a user who may change the record:
| Mode | |
|---|---|
'edit' |
The form, ready to change, as without the setting. The default. |
'read' |
A read view: each section a table of labels on the left and values on the right, as a property’s features on a real estate site, and a text of several lines under its label, or a row of key facts. Edit, among the record’s actions, opens the form. |
'locked' |
The form, its fields locked until Edit is pressed, for records where reading and editing look alike but a change should be meant. |
The form that Edit opens has its own address, the record’s with ?edit=true ({ kind: 'record', resource, key, edit: true }), so it opens in a new tab and Back leaves it. It has Cancel, which drops the changes and goes back to the record, and Save, which goes back once the record saved. A user who may not change the record, such as a visitor who is not signed in, never gets the form, at that address too: they get the read view in every mode, without Edit. Values on the read view show as they do everywhere else, an empty one as — (key facts leave it out) and a boolean as Yes or No, and a sensitive field stays masked behind its eye. Changes not saved stay in the browser, as they do on the form: the read view then offers to continue editing them or discard them.
view<typeof listings>('listings').recordMode('read')Groups
Section titled “Groups”l.group(title, items, { help?, count?, collapsed?, when? }) puts a heading over sections and related tables, so a long record page shows what matters first and tucks rarely needed parts away. A group holds only l.section and l.related items, and not another group. With collapsed: true it shows only its heading until the person clicks it; clicking again closes it. A closed group draws nothing, so its related tables load nothing until it opens. Without collapsed it is a plain heading over its items. Its heading is an h2 and its items’ titles are h3, so a screen reader lists them inside the group. help is a line under the heading, shown while the group is closed too, and count: true shows beside the heading how many records its related tables hold together; see Counts in headings.
helpWhen on l.group is not implemented.The open groups are in the address, as ?open=<title> once per group, so a link, a copied URL or a new tab opens the page with the group open. Titles are unique among a view’s groups, as the address names a group by its title. The page scrolls as a whole; opening a group adds no scroll box. On the form, a group that holds a field with an error or a conflict opens by itself. The create form shows the sections of a group as plain sections.
l.tab(title, items) splits the record page into tabs. A tab holds any main-column item: sections, groups, related tables, custom components, maps, charts, trends, galleries, history, comments, conversations and block trees. It refuses a sidebar item, another tab, and a custom component or map with sidebar: true, since the sidebar stays beside the tabs on every tab.
A view’s tabs stand together in the layout and show as one strip; items before them show above the strip and items after them below it, on every tab. Tab titles are unique among a view’s tabs, and group titles are unique across the whole layout, groups inside tabs too. The read view and the form show the same tabs.
The shown tab is in the address, as ?tab=<title>, so a link, a copied URL or a new tab opens the record on that tab. The first tab is the default and its link has no tab. An unknown title shows the first tab. Edit, Cancel and Save keep the tab. Only the shown tab’s items are drawn, so its related tables load when it opens; the form keeps the values of the fields on the other tabs. When a save is turned down for a field on another tab, the form moves to that tab and focuses the field. The create form shows the sections of a tab as plain sections.
view<typeof listings>('listings').layout((r) => [ l.sidebar([r.status]), l.tab('Details', [l.section('Home', [r.title, r.price])]), l.tab('History', [l.history('Changes'), l.comments('Comments')]),])Key facts
Section titled “Key facts”presentation: 'facts' on a section shows its fields on the read view as a real estate site shows a home’s key facts: side by side, wrapping onto more rows as needed, each value under the icon its field’s .icon(name) names, or under the field’s label without one. A fact with an icon still has its label, for screen readers and as the tooltip. On a mobile screen, below the sm breakpoint (640px), the facts sit two to a row. A field without a value is left out rather than shown as —, and a section with none left is left out; a value of 0 or No stays. The form edits the section as any other, its fields under their labels.
view<typeof listings>('listings') .recordMode('read') .fields((r) => ({ purchase_price: r.purchase_price.prefix('€').icon('tag'), living_area: r.living_area.suffix(' m²').icon('ruler'), bedrooms: r.bedrooms.icon('bed'), energy_label: r.energy_label.format('badge').icon('leaf'), })) .layout((r) => [l.section('Key facts', [r.purchase_price, r.living_area, r.bedrooms, r.energy_label, r.garden], { presentation: 'facts' })])Help while editing
Section titled “Help while editing”Help lines show on the record page and in forms by default. Those meant for whoever changes the record, such as where a value comes from, can show only while it is edited: on its form and the create form, not on the read view or a locked form. .helpWhen('editing') on the view says so for all of its fields and sections; a field’s .help(text, { when }) and a section’s helpWhen say it for their own, and win over the view’s.
view<typeof listings>('listings') .recordMode('read') .helpWhen('editing') .fields((r) => ({ price: r.price.help('The asking price, without costs.'), agent_phone: r.agent_phone.help('Call to plan a viewing.', { when: 'always' }), }))Confirming a change
Section titled “Confirming a change”A field that is easy to set by mistake, but that people may still need to change, can ask before it changes instead of being locked away with access rules. .confirm(question) shows a dialog titled “Change” and the field’s label, with the question under it, as the value first moves away from the saved one: when a switch is turned, a choice is picked or a record is chosen, and at the first key typed into a text or a number, not at every key after. Cancel, Escape or a click outside the dialog keeps the value; Change takes the new one, which saves as the editor saves it: with Save on the record page, at once for a switch or a choice in a list cell. A field set back to its saved value asks again when it is changed once more.
It asks on the record page’s form, in a list’s editable cells, on the create form and in a page’s settings and form blocks. It only asks: the API writes the field as any other, so a rule that must hold belongs in the field’s access or the resource’s .validate().
view<typeof tasks>('tasks').fields((r) => ({ researched: r.researched.confirm('The research job sets this once it is done. Set it by hand only to skip the research.'),}))Form and read view
Section titled “Form and read view”The read view and the form share the layout, so every item and field shows on both by default. when on an item, l.related(title, { ..., when }) included, shows it only on one of them, and a field’s .when(...) does so for the field wherever the record page shows it:
when |
|
|---|---|
'always' |
On both, as without the setting. The default. |
'editing' |
Only while the record is edited: on its form and the create form, not on the read view or a locked form. |
'reading' |
Only while it is not: on the read view and the locked form, and in a gallery’s photo details. |
a condition, such as 'status = "done"' |
Only l.section, l.related and l.sidebar take it: they show while the condition holds for the saved record, as <Show when> reads it, and change once the record is saved, not while the user types. They stay off the create form, which has no saved record, so a conditional section’s fields go under “Other fields” there. A condition that does not parse, or names a field the record does not have, stops startup. |
view<typeof listings>('listings') .recordMode('read') .fields((r) => ({ cover: r.cover.when('editing') })) .layout((r) => [ l.gallery('Photos', { image: r.cover, photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' }, when: 'reading' }), l.section('Listing', [r.address, r.price, r.cover]), l.related('Photos', { resource: 'listing_photos', field: 'listing_id', when: 'editing' }), ])The read view shows the gallery; the form shows the cover photo’s field and the table of photos to manage instead. The create form still offers every field the user may set but those .notOnCreate() leaves off: one only in items or fields meant for reading lands in its last section. A gallery’s photo details leave out what the photo’s own view shows only while editing. Lists, cards and filters show a field either way.
Editing a record
Section titled “Editing a record”The record’s form and the create form edit each field as its type asks, under its label, with its help line and its error tied to the input for screen readers.
- Relations. A relation the user may change is picked from a list that opens under its box: typing narrows it, by the other resource’s search fields, or else by its title, scrolling loads more, the arrow keys and Enter choose, and Escape closes it. On the record’s form a link beside the box opens the chosen record. A relation the user may not change stays a link.
- Numbers. On a phone, an integer field brings up a number keyboard and a decimal field a decimal one. A number field reads a number as the browser’s language writes it: in Dutch or German
12,50is 12.50 and1.234is 1234, with the point taken as a decimal one too when the number cannot be grouped (12.50); in English1,234.5is 1234.5. - A refused save. When the server turns a save down, each field it names says what is wrong under it, in the words of its label, such as “Country is required” or “Enter a date”, the toast, or with
.saveFeedback('button')a banner over the form, says how many fields to check, and the first of them takes the focus, on its own tab when the page has tabs. A.validate()rule’s message shows as the rule words it. - Save conflicts. When someone else saved the record after it was opened, Save writes nothing over their change: the form takes in the record as it is now, keeps your changes, and each field you both changed shows the value saved in the meantime, with Keep mine and Use theirs. The next Save writes what you kept.
- Leaving. Leaving a page with changes not yet saved, by a link, a reload or closing the tab, asks first. The record’s form keeps its changes in the browser, so they come back when the record opens again; the create page, a
ModalFormand a comment being written lose theirs, and the question says so.
Record lines
Section titled “Record lines”A record with numbered lines, such as an invoice, shows all of them on its page as one table, without paging. The lines are the related table the record’s view marks with lines: true, where the layout lists it: the records of resource whose field holds the record’s key, ordered by hand within the record, so resource names field as the within of its .position().
view<typeof invoices>('invoices').layout((r) => [ l.section('Billing details', [r.company_id, r.issued_at]), l.related('Lines', { resource: 'invoice_lines', field: 'invoice_id', lines: true, help: 'What the invoice bills for.' }),])The table’s columns are the lines’ list columns (.list({ columns }) of their view, or their first fields), without the line’s key, its tenant, the relation to the record and the position field, which is the order of the rows. Beside resource, field and lines, the section takes only help and when, since the table shows every line, and a view has one section of lines; both are checked when the config loads.
On the record’s form the lines are edited in place, each field with the form’s own editor and a relation with its picker. Add line adds an empty line at the end, which gets the record’s key and the place after the last line when saved, and the database’s defaults fill what is left empty. Remove line, in a line’s menu, removes it, and the drag handle or Move up and Move down change the order, as in Reordering by hand.
Nothing is written until Save, which writes the record and its lines in one batch, all or nothing: the removed lines are deleted, the changed fields of a line updated with the ETag it was read with, the new lines created and the order written with reorder. A line the server turns down says why, under the field it names or under the line, and the changes stay to put right. When someone else changed the lines in the meantime, nothing is written and the lines load again.
Add line is there for a user who may create lines, a line’s fields and the order change for one who may update them, and Remove line for one who may delete them, as each line’s own permissions allow. On the read view, and on a record the user may not update, such as a sent invoice whose rule allows updates to drafts only, the lines only show. The table loads up to 1,000 lines; a record with more shows them, the first 1,000, read-only.
Deleting a record
Section titled “Deleting a record”Delete, in the action rail of a user who may delete the record, asks first. A resource with a soft delete deletes at once instead, and the toast offers Undo, which brings the record back. When someone saved the record after it was opened, the delete stops and says so, with Review changes, which shows the record as it is now, and Delete anyway. When other records still point at it, the delete is refused and the toast names them, such as “Orders still point at this company.”, with a link to their list filtered on this record when the user may read it. Deleting a list’s selected rows asks once, deletes only the rows that did not change since the list loaded, and lists each record it kept and why.
Galleries
Section titled “Galleries”l.gallery(title, { image?, photos? }) shows a record’s photos as tiles in the main column: one large and up to four smaller beside it, the last counting the photos not drawn (“+12”). On a mobile screen it draws the large one with the number of photos. A tile opens a lightbox at its photo, at full size over the page, with a counter, arrows and the left and right keys to step through them all, stopping at the first and the last, a sideways swipe on a touch screen, and Escape or the close button to return. image is a file field of the record, shown first; photos names the records holding the further photos, as a cards display’s photos does: those of resource whose relation field points at the record, in sort order, each shown by its file field image. A photo that is also the record’s image is shown once, and files that are no image are left out. A record without photos has no gallery.
.layout((r) => [ l.gallery('Photos', { image: r.photo, photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } }), l.section('Listing', [r.address, r.price]),])The photos are read with the list API under the user’s own access, up to 500, so an index on field and the sorted fields serves them, which protobase doctor checks. In the lightbox, a photo held by a record of a resource the user may read has an info button, which shows that record’s details, as does the i key: in a sidebar beside the photo, or on a mobile screen in a sheet over the lower part of the screen, which Escape, its close button or a swipe down on its header closes. The details start closed, and the browser remembers whether they were left open for the next photo and gallery. They are the fields its record page’s sections show, less its file and the field pointing at the record, as a table of labels and values, as the record API answers the user, so the server decides what they see, and a link to its record page. A user who may not read that resource sees the photo alone, without the info button, as everyone does when it has no other field to show. In /api/meta, a user who cannot read image gets the gallery without it, and one who cannot list the photos without them; a gallery left with neither is left out. The server checks when it starts that image is a file field and that photos fits the resources.
l.map(title, { latitude, longitude }) draws a map centred on a pin at the record’s position, read from two number fields (integer, bigint or decimal) in decimal degrees, WGS84, at zoom (default 15, from 0 to 22). It pans and zooms with two fingers on a phone, and with Ctrl or Cmd and the wheel elsewhere, so the page scrolls past it.
.layout((r) => [ l.map('Location', { latitude: r.latitude, longitude: r.longitude }), l.section('Coordinates', [r.latitude, r.longitude]),])The map is drawn with MapLibre from the style the server names: maps.style in protobase.config.ts, else PROTOBASE_MAP_STYLE_URL, an http(s) URL of a MapLibre style; maps: false turns maps off whatever the variable says, and a style that is no http(s) URL stops the server at startup. The style’s sources may be PMTiles archives (pmtiles://https://...), so the tiles can be one file on a bucket of your own. The tiles, sprites and fonts are fetched by the browser, so their host must answer the app’s origins with CORS, and an archive with range requests. Without a style there is no map, nor is there one for a record whose fields hold no position or for a user who may not read them. MapLibre loads with the first map drawn, so a page without one does not load it.
A map display takes two number fields that are .filterable(), since it asks for the records inside its view with a filter on them, and the server refuses to start otherwise; an index on them, such as (latitude, longitude), lets Postgres find those records. The filter and search of the list narrow what it shows. Where it looks is in the address, /listings?display=map&map=52.37,4.89,12 (latitude, longitude, zoom), so Back, a reload or a shared link opens the same view; without one it fits every matching record. When none is in view, Show all fits them again.
Approximate positions
Section titled “Approximate positions”Some records know their position only roughly, such as a listing that gives its street but not its number. A map display marks those positions by a boolean field: approximate, true for an approximate position, or exact, false for one. Their markers are hollow with a dashed edge, a marker’s label to a screen reader says the position is approximate, and the chosen record’s card says Approximate position. Without the field, or where it holds neither, a position is exact.
Around an approximate position the map draws the area the record states: the GeoJSON Polygon, MultiPolygon, LineString or MultiLineString its area field holds, as a json field or the text of one, a geometry or a feature of one, such as a block or the street; else a circle of its radius field, a number of metres; else a circle of defaultRadius metres when the display names one. A record that states none of them on a display without a default has only its hollow marker, so the map shows no more than the data says. An area is drawn faintly in the markers’ colour, a line as a wide stroke, and the chosen record’s darker. It fades in as the map zooms close enough for it to be wider than a marker, and only the records in view have theirs drawn.
d.map( { latitude: r.latitude, longitude: r.longitude, exact: r.coordinates_exact, radius: r.accuracy_m, area: r.street_outline }, { label: 'Map', defaultRadius: 250 },)radius, area and defaultRadius need approximate or exact, and the server refuses to start when a field is of another type. A user who may not read the field that marks the positions sees them as exact.
Map layers
Section titled “Map layers”maps.layers in the config adds other maps of raster tiles, such as aerial photos, next to the style. With layers, every map (l.map and d.map) has a switch in its top left corner between Map, the style’s map and the default, and each layer by its label. The choice is remembered in the browser for every map, and a layer the app no longer offers falls back to the default. The chosen layer is drawn over the style’s map, under the areas and markers, and its attribution shows in the map’s corner while it is.
export default defineConfig({ maps: { layers: [ { id: 'aerial_nl', label: 'Aerial (NL)', tiles: 'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg', attribution: 'Luchtfoto <a href="https://www.beeldmateriaal.nl/">Beeldmateriaal Nederland</a>, CC BY 4.0, via <a href="https://www.pdok.nl/">PDOK</a>', bounds: [3.2, 50.7, 7.3, 53.7], maxzoom: 21, }, ], },})| Field | What it is |
|---|---|
id |
Lowercase letters, digits and _, unique: what the browser remembers. |
label |
What the switch says. |
tiles |
The http(s) URL of 256-pixel Web Mercator tiles with {z}, {x} and {y}: an XYZ service, or a WMTS GetTile URL in its GoogleMapsCompatible or EPSG:3857 tile matrix set, with {z} as the tile matrix, {y} the row and {x} the column. |
attribution |
The credit the tiles’ licence asks for; it may hold links. |
bounds |
Optional [west, south, east, north] in degrees, where the tiles are. The layer is offered everywhere; outside its bounds no tiles are asked for and the style’s map shows through. |
maxzoom |
Optional deepest zoom of the tiles, from 0 to 24 (default 22); closer in, the map enlarges them. |
The browser fetches the tiles, so their host must answer the app’s origins with CORS. Layers need a style: without one there is no map to switch. A layer that is not as above stops the server at startup. Use only tiles whose terms allow it: open aerial photos are published per country, such as the Netherlands’ PDOK Luchtfoto and Spain’s PNOA from the IGN, both CC BY 4.0, free and without a key; the property portal example offers both.
Related records
Section titled “Related records”Without any configuration, the record page’s rail has a Related records card that counts the records pointing at this one: per resource, and per relation when one resource has two, such as Orders (Customer) and Orders (Supplier), how many there are, linking to its list filtered on this record (/orders?filter=customer_id = "7"). It counts each filterable relation to a resource with a one-field key, so an index serves the count, and leaves out a resource’s tenant, a resource the user cannot list or whose relation they cannot read, and a relation an l.related section of the page already lists, its lines included. A custom component’s fallback counts only where the page draws it, when the app has no component of that name.
l.related(title, options) lists the first records of resource that point at the record on the page, in the table or display the resource’s list page uses (with its switch, and on a phone its cards in one sideways row, as a Table block shows them), and links to all of them in that list. They point at it directly, through a relation field, or through a join resource (through), such as the leases a tenant signed through lease_tenants:
| Option | |
|---|---|
resource |
The records listed. Required. |
field |
Without through or from: the relation on resource that holds this record’s key. With from: the field of resource that holds that value. With through: the field of resource matched against the keys the join records hold. Filterable. Required. |
from |
A field of this record whose value field must hold, instead of this record’s key, such as the task of a question, to list the task’s links: { resource: 'task_links', field: 'task_id', from: 'task_id' }. Same type as field (a relation to the same resource), not sensitive, and not with through. A record with no value lists nothing. |
through |
{ resource, field, key?, filter? }: the join records whose field (a filterable relation) holds this record’s key; their key values (default their primary key, filterable, and pointing at one resource with field) pick the listed records, in one read with related(), so an index must serve key too. |
filter, sort |
AIP-160 and AIP-132 on resource, as in the list API. filter narrows the listed records, through.filter the join records. |
columns |
Fields of resource, through relations too (unit_id.property_id); default the view’s list columns without field. The first links to the record a row opens. With presentation: 'cards' or 'compact', the fields each card shows; with presentation: 'record', the fields of the record it shows. |
presentation |
'cards' shows the records as cards instead of the table or display; 'compact' as compact cards of a line or two; 'record' shows one record in full. |
actions |
Named actions of resource’s view, by name, as buttons on each card; only with presentation: 'cards' or 'compact'. A screen reader names each button by its label and the card’s title, such as Mark clear: Lists lose their place. |
time |
A date or timestamp field of resource each compact card shows beside its title, as its view formats it; only with presentation: 'compact'. |
tone |
An enum field of resource whose value colours each card’s left edge, by its view’s valueColors; only with presentation: 'cards' or 'compact'. |
button |
{ label, to } or { label, href }, or a list of them of which each row shows the first whose fields it holds: a button on each row, or each card, to an address the row’s fields name, its tab or list filter too, or to the outside page a field holds, such as { label: '{{verb}}', to: { kind: 'record', resource: 'tasks', key: '{{task_id}}', tab: 'Review' } }; a row without a value for a field it names shows none. Not with lines. |
open |
The relation of resource whose record a row opens, for rows that link this record to another. By default the one relation in resource’s primary key besides field, when there is exactly one (a join resource such as task_dependencies keyed on [task_id, type, depends_on_id]); otherwise rows open their own records. The row’s menu then has Open for the other record and Edit for the link itself. |
limit |
How many records it shows, 1 to 100; default 10. Not with presentation: 'record'. When there are more, the section says so beside View all, such as “The first 10 of 37.”. Before 0.13 this was pageSize, rows per page; rename it. |
display |
The display of resource’s list it opens in, and View all opens, such as cards; default the list’s. Not with presentation: 'record'. |
help, empty |
A line under the title, and the text when nothing matches (default “Nothing here yet.”). |
hideEmpty |
true leaves the section off the page while it has no records. |
count |
true shows how many records match beside the title; see Counts in headings. |
lines |
true makes the section the record’s lines, edited in place with the record. |
The real estate example lists who a unit is let to (the primary tenant and co-signers of the lease that runs today) and that lease:
import { l, view } from '@protobase/schema'import type { units } from './data'
/** A lease that covers today; `end_date` is its last day. */const running = 'start_date <= now() AND (isNull(end_date) OR end_date >= now())'
export const unitsView = view<typeof units>('units') .title((r) => r.label) .names({ singular: 'Unit', plural: 'Units' }) .nav({ recent: { status: 'status', tones: { vacant: 'warning', renovation: 'info' }, filter: 'status != "let"' } }) .fields((r) => ({ property_id: r.property_id.label('Property'), area_m2: r.area_m2.label('Area').help('Living area in m².').suffix(' m²'), energy_label: r.energy_label.format('badge'), base_rent: r.base_rent.label('Market rent').help('What a new lease would ask today, per month.').prefix('€').currency('EUR').decimals(2), status: r.status.help('Let while a lease runs; vacant or under renovation between leases.').format('badge').valueLabels({ let: 'Let', vacant: 'Vacant', renovation: 'Renovation' }), })) .list((r) => ({ columns: [r.label, r.property_id, r.status, r.bedrooms, r.area_m2, r.energy_label, r.base_rent], search: [r.label] })) .filters((r, w) => [w.facets(r.status), w.facets(r.energy_label), w.range(r.base_rent, { histogram: true })]) .layout((r) => [ l.section('Unit', [r.property_id, r.label, r.floor, r.bedrooms, r.area_m2, r.energy_label]), l.section('Letting', [r.status, r.base_rent]), l.related('Let to', { resource: 'lease_tenants', field: 'lease_id', through: { resource: 'leases', field: 'unit_id', filter: running }, // `primary` sorts after `co_signer`, so the primary tenant comes first sort: 'role desc', columns: ['tenant_id', 'role', 'tenant_id.email', 'tenant_id.phone'], help: 'The primary tenant and co-signers of the running lease.', empty: 'Vacant: no lease runs today.', }), l.related('Running lease', { resource: 'leases', field: 'unit_id', filter: running, columns: ['number', 'term', 'start_date', 'end_date', 'monthly_rent', 'service_costs'], empty: 'Vacant: no lease runs today.', }), l.sidebar([r.status, r.base_rent]), ])When resource is ordered by hand within the record on the page (.position(..., { within }) names field), the section has a Reorder button that puts its records in order by dragging them; see Reordering by hand.
Every name is checked when the config loads. In /meta a caller who cannot read a resource the section names, or a field its filter or sort uses, does not get the section, and columns they cannot read are left out; the rows come from the list API with the caller’s token, so row filters apply as everywhere else.
Related records as cards
Section titled “Related records as cards”With presentation: 'cards' the section shows each record as a card, the cards stacked full width so a long value has room: the record’s title, a link to its page, then each of columns under its label as the record page shows it (a markdown field rendered, a relation by its name), leaving out a field the record has no value for, a button for each of actions, and button before them. A value taller than a few lines is cut short with Show more, which shows it all. The buttons run the actions as the record page does: one with confirm asks first, one with inputs opens its dialog (a sheet on a phone), and an a.action runs the app’s handler; a card leaves out an action the user does not get and disables one they cannot run on that record. After an action the section loads again, so a record it no longer matches leaves it, and with hideEmpty the section goes once nothing matches.
l.related('Waiting on you', { resource: 'task_preconditions', field: 'task_id', filter: 'state = "waiting"', presentation: 'cards', columns: ['plan'], actions: ['approve', 'request_changes'], hideEmpty: true,})An action that actions names must be a named action of resource’s view. The cards have no display switch or Reorder; View all opens the list as a table section would.
Compact related cards
Section titled “Compact related cards”With presentation: 'compact' each card takes a line or two, for a short list where every record needs a glance and an act, such as the causes holding an objective up. The first line holds the record’s title, a link to its page, and its time at the end of the line; the second holds columns side by side without their labels, a dot between them, leaving out a field the record has no value for. The buttons of actions and button sit beside both lines, or beside the second where the card is narrow, such as on a phone, with the title on a line of its own. The buttons work as on cards, and so does View all.
With tone, each card’s left edge takes the colour its value has in the view’s valueColors, a tone or a hex colour as its badge does, and the value’s badge shows first among the card’s values, unless columns places it elsewhere, so the colour is never all that says it. An action that changes the value changes the edge as the section loads again. tone works on presentation: 'cards' too.
When an action takes its card out of the section, such as Mark clear under filter: 'state != "clear"', focus moves to the next card’s first enabled action, else its title’s link, else the previous card’s, else the section’s heading, and a screen reader hears Done: Mark clear, <title>. It has left this list. This holds for presentation: 'cards' too. A section with hideEmpty: true goes away with its last card, so then focus has no heading to go to and nothing is announced.
l.related('Holding it up', { resource: 'objective_causes', field: 'objective_id', presentation: 'compact', time: 'since', tone: 'state', columns: ['owner', 'tasks'], actions: ['clear'],})A time or tone field the caller cannot read is left out of their cards. time or tone through a relation, such as task_id.updated_at, because reading them through one is not implemented.
Counts in headings
Section titled “Counts in headings”With count: true a related section shows beside its title how many records match, such as Doing 2, so the reader sees what is behind each heading without scrolling. A group with count: true shows how many records its related tables hold together, while it is closed too, so a closed group still says whether opening it is worth it. A section with no records shows 0. The count is the records the reader may see, as the list API counts them with their access rules, and it follows the page’s own changes and, on a live resource, everyone else’s. The count is a quiet pill after the title, 0 as an outline, and a screen reader hears it with the records’ name, such as “Doing (2 tasks)”; while it loads, a placeholder of its size holds its place, and a count that cannot be read shows no pill rather than 0. help puts a line under the heading of either.
l.group('Open tasks', [ l.related('Blocked', { resource: 'tasks', field: 'objective_id', filter: 'status = "blocked"', presentation: 'compact', count: true }), l.related('Doing', { resource: 'tasks', field: 'objective_id', filter: 'status = "doing"', presentation: 'compact', count: true }),], { help: 'What is left before the objective is met.', count: true })A related record in full
Section titled “A related record in full”With presentation: 'record' the section shows one related record as part of the page, for a tab meant for reading, such as an objective’s notes kept in a record of their own: no card, no title of the record, nothing cut short with Show more, and no View all while there is only the one record. It shows the first record in sort order, each of columns in full as the record page shows it (a markdown field rendered), leaving out a field the record has no value for. On the heading’s line, a link Open and the singular name of resource’s view, such as Open note, goes to the record’s own page, with button before it. When more records match, View all under the record opens them all in the list, so a section such as the latest review does not hide the older ones. With one column the value stands alone, without its label; with several each is under its label. Without a record it shows empty, or with hideEmpty nothing; to whoever may create a record of resource, as the list offers New, its heading then has Add and the singular name, such as Add note, a link to the create form with field filled in with the value it matches, this record’s key or its from field’s. It has none when that value is empty, or with through, whose field holds the join resource’s key. A change to the record shows as soon as the page hears of it, as in every related section of a live resource.
l.tab('Notes', [ l.related('Coordinator notes', { resource: 'objective_notes', field: 'objective_id', presentation: 'record', columns: ['notes'], }),])It takes no limit, display or actions.
Charts of related records
Section titled “Charts of related records”l.chart(title, options) draws line graphs of numeric fields of the records that point at the record on the page, over a timestamp of theirs, as a virtual machine’s page graphs its CPU and network from the samples an app keeps of it, about one a minute. The section has a switch between the last Hour, per minute, the last Day, per 5 minutes, and the last Week, per hour, and one between the Average and the Maximum of each bucket. A bucket without a sample is a gap in the line, never 0. Each series is a line of its own colour, with a legend when there are several, and the tooltip shows each value with its field’s prefix, suffix and decimals; the axis has one scale, so a chart holds series of one unit, such as bytes in and out.
| Option | |
|---|---|
resource |
The records charted, such as host_samples. Required. |
field |
The filterable relation on resource that holds this record’s key. Required. |
at |
The filterable timestamp field of resource the records are placed by. Required. |
series |
The numeric fields of resource it draws, one line each, labelled as resource’s view labels them. At least one. |
range |
The range it opens on: 1h (the default), 24h or 7d. |
help, when |
A line under the title, and whether it shows on the form, the read view or both. |
view<typeof hosts>('hosts').layout((r) => [ l.section('Host', [r.name, r.address]), l.chart('CPU', { resource: 'host_samples', field: 'host_id', at: 'sampled_at', series: ['cpu_percent'] }), l.chart('Network', { resource: 'host_samples', field: 'host_id', at: 'sampled_at', series: ['net_in', 'net_out'], help: 'Bytes per second.' }),])Each series is read through :aggregate, grouped by at with field = <this record's key> as its filter, so the user’s access applies as on the list, and a user who cannot read field, at or any series gets no chart (one who cannot read some series gets the others). That filter and grouping need an index on (field, at), such as create index on host_samples (host_id, sampled_at), which protobase doctor checks. A field that is no relation to this resource, an at that is no timestamp or not filterable, or a series that is no number or is sensitive stops the server at startup. Keeping the samples, and removing old ones, is the app’s own work.
Trends of related records
Section titled “Trends of related records”l.trend(title, options) draws bars of how many records point at the record on the page, per day, week or month of a date of theirs, as a list’s chart counts them, such as an objective’s shipped tasks per week over the last 90 days. It takes the options of a list’s chart, range and granularity, and counts only this record’s records. Records without a value in at, such as tasks not shipped yet, are not counted. A line over the bars gives their total over the range, such as 4 in the last 90 days, or None in the last 90 days over flat bars, and a chart that could not load offers Try again. A bar’s tooltip names its whole week or month, such as 24 – 30 Aug 2026, and the bar still filling up is outlined with a dash and runs to today, or reads Today for a day. The chart takes focus: the left and right arrow keys move the tooltip from bar to bar and Escape closes it, and a screen reader reads the bars as a table; a Chart block over a date and l.chart do the same. Name what at means in the title or the help, such as “Shipped per week”.
| Option | |
|---|---|
resource |
The records counted, such as tasks. Required. |
field |
The filterable relation on resource that holds this record’s key. Required. |
at |
The filterable date or timestamp field of resource the records are counted by. Required. |
range |
How far back it reaches: 7d, 30d, 90d, 1y or all. Required. |
granularity |
How long each bar is: hour, day, week (from Monday) or month. Required. |
help, when |
A line under the title, and whether it shows on the form, the read view or both. |
view<typeof objectives>('objectives').layout((r) => [ l.section('Objective', [r.name]), l.trend('Shipped per week', { resource: 'tasks', field: 'objective_id', at: 'shipped_at', range: '90d', granularity: 'week' }), l.related('Tasks', { resource: 'tasks', field: 'objective_id' }),])The counts are read through :aggregate, grouped by at with field = <this record's key> as its filter, so the user’s access applies as on the list, and a user who cannot read field or at gets no trend. They are read again when the user adds, changes or deletes such a record, and, for a live resource, when anyone does. An index on (field, at), such as create index on tasks (objective_id, shipped_at), keeps it fast, which protobase doctor checks. A field that is no relation to this resource, or an at that is no date or timestamp or is not filterable, stops the server at startup.
Conversations
Section titled “Conversations”l.thread(title, options) shows the messages that point at the record on the page, as a task’s chat between the people working on it, and l.composer(options) below it writes one. They are the record page’s form of the Thread and Composer blocks of composed pages, scoped to the record by a relation of the messages: the thread reads only the messages whose field holds this record’s key, and each message the composer sends gets that key in field. /meta describes both as data, so every client can draw the conversation with no component of the app’s own.
The thread shows the latest messages oldest first, each under its sender’s name and the time it was sent, with a line between days, and Load earlier messages reads the ones before; it scrolls in a box of its own, opening at the newest and following what arrives, as the Thread block does; others’ new messages arrive without a reload when the message resource is live (.live()), and otherwise once the page is read again. A message whose text field the message resource’s view marks .markdown() shows rendered, its raw HTML as text. The composer sends with Enter, starts a new line with Shift+Enter, and keeps a refused message in the box under the reason. A message carries its sender only when the message resource marks its author with .author(), which every create sets to the signed-in user, so the thread’s sender names that field, such as author_id. It sends only field and text, so every other required field of the message, such as its time, needs a default, such as sent_at timestamptz not null default now().
l.thread option |
|
|---|---|
resource |
The message resource, such as task_messages. Required. |
field |
The filterable relation of resource that holds this record’s key. Required. |
sender |
Who wrote each message: a relation, named as the record it points at, or a text field. Without it, the thread is one author’s, such as a log: each message shows under the time it was sent, with no name or avatar. |
time |
When each was sent: a date or timestamp field the API can sort by, which orders them. Required. |
text |
The message, a text field. Required. |
status |
A short line under each message, such as whether it was delivered: a text or enum field. See Message status and a working indicator. |
working |
A condition on this record, such as state = 'working', while which the thread ends in a working indicator. |
calls |
Tool calls shown between the messages in time order: the resource that holds them, the filterable relation field of it that holds this record’s key, and the fields the Thread block’s calls names, name, time, status, input, result and error. A field that is no relation to this resource, a field the calls do not have or of the wrong type, or a sensitive one stops the server at startup. |
limit |
How many of the latest it shows at first, and how many each Load earlier messages adds: 1 to 500, the API’s largest page; default 50. |
empty |
Text while there are no messages. |
help, when |
A line under the title, and whether it shows on the form, the read view or both. |
l.composer option |
|
|---|---|
resource |
The message resource. Required. |
field |
The relation of resource each message gets this record’s key in. Required. |
text |
The text field the message goes in. Required. |
placeholder |
The box’s text while empty. |
when |
Whether it shows on the form, the read view or both. |
view<typeof task_messages>('task_messages').fields((r) => ({ body: r.body.markdown() }))
view<typeof tasks>('tasks').layout((r) => [ l.section('Task', [r.title]), l.thread('Conversation', { resource: 'task_messages', field: 'task_id', sender: 'author_id', time: 'sent_at', text: 'body' }), l.composer({ resource: 'task_messages', field: 'task_id', text: 'body', placeholder: 'Message about this task' }),])The messages are read with field = <this record's key> as the filter, newest first by time, so the user’s access applies as on the list. That read needs an index on (field, time), such as create index on task_messages (task_id, sent_at), which protobase doctor checks. Tool calls are read the same way, by their own field and time. A user who cannot read field, sender, time or text gets no thread, and one who may not create a message with field and text gets no composer. A field that is no relation to this resource, a time that is no date or timestamp the API can sort by, a sender that is no relation or text field, a thread text that is no text field, a sensitive field in the thread, or a composer text that is no writable text field stops the server at startup. As with a related section, the record page’s count of the records that point at it leaves out the messages and tool calls its thread shows.
Message status and a working indicator
Section titled “Message status and a working indicator”A thread can say whether each message arrived and whether a reply is on its way, as a chat with an assistant or a teammate does. status names a text or enum field of the messages, such as delivery, shown in small type under each message that has a value, with the labels the message resource’s view gives its enum values; a message without one shows no line, and a value the view colours red with .valueColors(), such as a failed send, shows in red beside an alert icon. working is a condition on the record the thread belongs to, written as for conditional sections, such as state = 'working': while it holds, the thread ends in three pulsing dots and “Writing a reply…”, which screen readers announce, and a reader at the end of the thread keeps seeing them.
view<typeof chat_messages>('chat_messages').fields((r) => ({ delivery: r.delivery.valueLabels({ sent: 'Sent', delivered: 'Delivered', failed: 'Not sent' }).valueColors({ failed: 'red' }) }))
view<typeof chats>('chats').layout((r) => [ l.thread('Conversation', { resource: 'chat_messages', field: 'chat_id', sender: 'sender', time: 'sent_at', text: 'body', status: 'delivery', working: "state = 'working'" }), l.composer({ resource: 'chat_messages', field: 'chat_id', text: 'body' }),])Both change without a reload when their resources are live: a status as its message changes, and the indicator as the record does. A user who cannot read the status field sees the thread without the line, and one who cannot read what working names sees it without the indicator. A status that is no text or enum field, or is sensitive, and a working that does not parse or names a field the record does not have, stop the server at startup.
Actions and views per role
Section titled “Actions and views per role”import { l } from '@protobase/schema'import { customersView, repairsView as laidOut } from './step-4'
// Step 5: buttons for the moves the shop makes all day, and a quieter view for the mechanics.
export { customersView }
export const repairsView = laidOut.actions((a) => [ a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } }), a.update('collect', { label: 'Collected and paid', icon: 'wallet', set: { status: 'collected', paid: true }, confirm: 'Has the customer paid and taken the bike?' }), a.link('customerRepairs', { label: 'Other repairs of this customer', icon: 'file-text', to: { kind: 'list', resource: 'repairs', filter: 'customer_id = {{customer_id}}' } }),])
/** What mechanics get instead: no money, and their own move. */export const workshopRepairsView = laidOut .forRoles(['mechanic']) .list((r) => ({ columns: [r.number, r.bike, r.problem, r.status, r.mechanic], sort: [[r.booked_on, 'asc']], search: [r.number, r.bike] })) .filters((r, w) => [w.facets(r.status), w.facets(r.mechanic, { search: true }), w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] })]) .layout((r) => [l.section('The bike', [r.bike, r.problem]), l.section('In the workshop', [r.status, r.mechanic, r.notes]), l.sidebar([r.status, r.booked_on])]) .actions((a) => [a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } })]).actions((a) => [...]) names the moves a record page offers in its action rail, between Edit, when the record opens as a read view or locked, and Delete, for a user who may delete it, unless an a.remove deletes already; composed pages can put the same actions on buttons. On the form, Save leads the sidebar, above the rail, with Cancel under it when Edit opened the form; on a mobile screen they sit in a bar under the form instead. On a mobile screen, below md (768px), the rail’s actions, Edit and Delete among them, sit in the top bar’s Record actions menu (the ⋮ button), at hand however long the record is. a.update, a.remove, a.link and a.ai, which has the model write a field, work without code; a.action runs a handler the app registers; it and a.update ask for their inputs first when they have some. They are described with named actions.
.forRoles([...]) makes a view for users with one of those roles: each user gets the first such view that matches their roles, and the view without roles otherwise. A per-role view is a whole view, so build it from another (laidOut.forRoles(...) above) and change what differs.
The ERP’s orders view uses most of this page at once, with a recent-record group in the sidebar:
import { view } from '@protobase/schema'import type { orders } from './data'
export const ordersView = view<typeof orders>('orders') .title((r) => r.number) .names({ singular: 'Order', plural: 'Orders' }) .icon('shopping-cart') .nav({ recent: { status: 'status', tones: { draft: 'neutral', confirmed: 'info', picking: 'warning', shipped: 'success' }, pulse: ['picking'], filter: 'status != "delivered" AND status != "cancelled"', orderBy: 'created_at desc', }, }) .fields((r) => ({ number: r.number.format('code'), status: r.status.help('Where the order is in its life. Moving it forward can notify the customer.').format('badge') .valueLabels({ draft: 'Draft', confirmed: 'Confirmed', picking: 'Picking', shipped: 'Shipped', delivered: 'Delivered', cancelled: 'Cancelled' }) .valueColors({ confirmed: 'blue', picking: 'amber', shipped: 'violet', delivered: 'green', cancelled: 'red' }), total: r.total.help('Order total including VAT.').prefix('€').currency('EUR').decimals(2), discount_percent: r.discount_percent.label('Discount').help('Percentage taken off the order total.').format('percent'), paid: r.paid.help('Set when the payment has been received.'), created_at: r.created_at.label('Created').format('absolute'), })) .list((r) => ({ columns: [r.number, r.company_id, r.status, r.total, r.discount_percent, r.paid, r.owner_id, r.created_at], sort: [[r.created_at, 'desc']], search: [r.number], })) .filters((r, w) => [ w.facets(r.status), w.facets(r.owner_id), w.dateRange(r.created_at, { presets: ['7d', '30d', '90d', 'quarter', 'year'] }), w.range(r.total, { histogram: true }), w.toggle(r.paid), ]) .chart((r) => ({ field: r.created_at, range: '30d', granularity: 'day' })) .saveFeedback('toast') .actions((a) => [ a.update('markPaid', { label: 'Mark as paid', icon: 'wallet', set: { paid: true }, confirm: 'Record that the customer paid this order?' }), a.action('createInvoice', { label: 'Create invoice', icon: 'file-text' }), ])Actions that ask for input
Section titled “Actions that ask for input”inputs on an a.action or an a.update makes its button open a dialog that asks for them first, each edited as the create form edits a field, with the action’s confirm text above them and its label on the button that runs it. An a.action’s handler gets the answers as values, by input name:
.actions((a) => [ a.action('remind', { label: 'Send reminder', icon: 'mail', inputs: (i) => [ i.choice('channel', { label: 'Send by', options: [{ value: 'email', label: 'Email' }, { value: 'letter', label: 'Letter' }], default: 'email' }), i.text('note', { label: 'Note', multiline: true, optional: true, when: "channel = 'email'" }), ], }),])An a.update writes the answers with no code: a set value that is exactly '{{name}}' is the answer of the input called name. An empty answer writes null, an input that is hidden by when leaves its field as it is, and a '{{name}}' that names no input stops the config from loading. An update that asks for input is always offered, since the answer can always change the record. This button works the same on a composed page, so a dashboard can answer in place:
a.update('answer', { label: 'Answer', inputs: (i) => [i.text('answer', { label: 'Answer', multiline: true })], set: { answer: '{{answer}}' } })| Input | Asks for |
|---|---|
i.text(name, o) |
A line of text, or several with multiline: true; max is the most characters it may have. |
i.integer(name, o) |
A whole number, which the handler gets as a number. |
i.decimal(name, o) |
A number with decimals, which the handler gets as text, as the API gives decimals, so no digit is lost. |
i.boolean(name, o) |
A switch, true or false, so it is never required. |
i.date(name, o) |
A date, YYYY-MM-DD. |
i.secret(name, o) |
A secret, such as an API key, in a masked field; the handler gets it exactly as typed. |
i.choice(name, { options }) |
One of options, each a value with the label it reads as. |
i.choice(name, { resource }) |
A record of resource, picked as the create form picks a relation; the handler gets its key. |
i.checklist(name, { items }) |
Boxes to tick, every one, before the action runs: the same items for every record. The answer is the list of their texts. |
i.checklist(name, { from }) |
The same, with each record’s own boxes, which its JSON field from holds as a list of texts. See signing several records off at once. |
i.custom(name, { component, props? }) |
What a component of the app’s protobase.ui.tsx, by the name it is registered under, edits. |
Each takes label, and optionally help, a default, optional: true to allow an empty answer (every other input is required) and when, an AIP-160 condition over the inputs before it, as <Show when> is over a record: "start = 'github' OR code = 'github'". A checklist takes neither default nor optional: true: it starts unticked and needs every box. An input whose condition does not hold is hidden, not required and left out of values, and the inputs after it read it as empty. A when that names no input before it, a default that is not one of the options and a name given twice stop the config from loading; so does a choice of a resource the app does not have, when the server starts.
An empty answer is null. Before the handler runs, the dialog refuses a required answer left empty, a number that is none, a date that is not YYYY-MM-DD and a text longer than max, each under its input. When the handler throws an ActionInputError from @protobase/ui, such as new ActionInputError({ email: 'No user has this address' }), or an API error, such as a function’s answer, whose errors name an input as their field, each message shows under its input and the dialog stays open; another error shows above the inputs. When it resolves, the dialog closes and the action ends as any other: everything shown of the resource reloads and a toast says it is done.
A custom input’s component gets the answer as value (null when empty), onChange, invalid while its answer is refused, the input’s props and the input itself (ActionInputProps), as a field type’s editor does. Without that component the button is disabled, with the reason as its tooltip. In /api/meta, a user who cannot read the resource of a choice does not get the action.
Secret inputs
Section titled “Secret inputs”i.secret(name, { label, help }) asks for a value that must not be seen or kept, such as an API key, so an app takes one without a custom component. The field draws what you type as discs, and browsers and password managers do not offer to save it, fill it, correct it or keep it in their form history. The value goes only to the handler, as values[name]:
a.action('connect_carrier', { label: 'Connect carrier', icon: 'key', inputs: (i) => [i.secret('api_key', { label: 'API key', help: 'From the carrier’s settings page.' })],})It is never sent back: when the handler’s error or an input’s message holds the value, the dialog or the toast shows discs in its place. A secret takes no default, a later input’s when cannot read it, and an a.update whose set writes it stops the config from loading, since the update would store the value and send it back; the handler decides what to do with it.
Actions that send from someone’s mailbox
Section titled “Actions that send from someone’s mailbox”An a.action whose handler sends mail from the signed-in person’s own mailbox, such as an invoice from their Gmail, says so with mailbox: true. While they have linked no mailbox, its dialog offers to connect one instead of running: Connect Gmail starts the same sign-in as the account page’s and comes back to the page they were on, where the action runs. Someone who signs in with Google without having allowed it to send mail is told that sign-in is no mailbox. The check needs a dialog, so give the action confirm or inputs:
a.action('send_invoice', { label: 'Send', icon: 'send', mailbox: true, confirm: 'Send the invoice from your own mailbox?' })Any action whose handler fails with a function’s mailbox problem (not_linked or link_expired) gets the same offer in place of the bare error, worded Connect Gmail again for an expired link: in its dialog, or as its error toast’s button. A failure that is not about the mailbox shows as it is.
Where an action applies
Section titled “Where an action applies”when limits an action to the records it applies to, with the same AIP-160 conditions a section’s when takes, over the record’s own fields: status = 'running', status != 'stopped' AND locked = false. On a record it does not hold for, the button is left out, or, with otherwise: 'disable', shown disabled with reason as its tooltip. variant: 'danger' draws the button in red, as Delete is, and its question’s button too:
.actions((a) => [ a.update('start', { label: 'Start', icon: 'play', when: "status = 'stopped'", set: { status: 'starting' }, bulk: true }), a.action('reboot', { label: 'Reboot', icon: 'restart', when: "status = 'running'", bulk: true }), a.action('force_off', { label: 'Force off', icon: 'power', when: "status = 'running'", otherwise: 'disable', reason: 'The VM is not running', variant: 'danger', confirm: 'The VM loses what it has not saved.', }),])Besides the record page, the list’s row menu offers each named action without inputs on the rows it applies to, disabled where it is disabled on the record page, and in red when it is a delete or a danger action; a link is a link there, or a disabled item without one where it is disabled. An a.update or a.action with bulk is also offered for the selected rows, as Start (2), while one of them applies: it asks its confirm or its inputs once, with the count in the dialog’s title; an inputs dialog for two or more records also lists their titles, while the confirm question and a dialog for one record show the count alone. confirm question cannot list the records it runs on because passing their titles to the confirm dialog is not implemented.a.action’s handler is called once per row. A row the person may not change is refused, by its record’s permissions or by the API’s 403, while the others run, and the toast names each refused record by its title. The rows stay selected while the dialog is open, and all of them when it is cancelled; once the run ends, only the rows it refused or skipped stay selected, showing what is still open. The list’s own Delete N and Export N keep the selection the same way: all of it when their dialog is cancelled, none once the export is written, and the rows a delete could not remove once it ends. Table with bulk offers them there.
A condition reads only the record’s own fields, so the list decides it for each row from the row itself: protobase build refuses one that names a relation’s field (host_id.name), counts records (hosts.count) or names a field the resource does not have, a disabled button without a reason, and a reason or otherwise without when. In /api/meta, a user who cannot read a field the condition reads does not get the action. The condition only decides what the buttons show: the resource’s access rules decide what the API lets the user do.