@protobase/cli 0.22.12 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/main.js +2 -0
  2. package/dist/package.js +1 -1
  3. package/dist/skill/install.js +29 -0
  4. package/dist/skill/register.js +14 -0
  5. package/package.json +8 -7
  6. package/skills/protobase/SKILL.md +89 -0
  7. package/skills/protobase/references/getting-started.md +78 -0
  8. package/skills/protobase/references/guides/api-functions.md +240 -0
  9. package/skills/protobase/references/guides/billing-page.md +288 -0
  10. package/skills/protobase/references/guides/create-page.md +108 -0
  11. package/skills/protobase/references/guides/deploy.md +52 -0
  12. package/skills/protobase/references/guides/export-a-list.md +44 -0
  13. package/skills/protobase/references/guides/field-type.md +131 -0
  14. package/skills/protobase/references/guides/first-composed-page.md +230 -0
  15. package/skills/protobase/references/guides/first-plugin.md +166 -0
  16. package/skills/protobase/references/guides/import-records.md +43 -0
  17. package/skills/protobase/references/guides/plugin-build.md +64 -0
  18. package/skills/protobase/references/guides/record-card.md +70 -0
  19. package/skills/protobase/references/guides/remote-resources.md +185 -0
  20. package/skills/protobase/references/guides/table-to-admin.md +205 -0
  21. package/skills/protobase/references/guides/theme-an-app.md +87 -0
  22. package/skills/protobase/references/reference/access.md +115 -0
  23. package/skills/protobase/references/reference/ai.md +106 -0
  24. package/skills/protobase/references/reference/api.md +231 -0
  25. package/skills/protobase/references/reference/architecture.md +63 -0
  26. package/skills/protobase/references/reference/assistant.md +157 -0
  27. package/skills/protobase/references/reference/auth.md +462 -0
  28. package/skills/protobase/references/reference/blocks.md +341 -0
  29. package/skills/protobase/references/reference/bottom-bar.md +44 -0
  30. package/skills/protobase/references/reference/cli.md +493 -0
  31. package/skills/protobase/references/reference/client.md +38 -0
  32. package/skills/protobase/references/reference/comments.md +83 -0
  33. package/skills/protobase/references/reference/custom-components.md +285 -0
  34. package/skills/protobase/references/reference/data-config.md +266 -0
  35. package/skills/protobase/references/reference/email.md +166 -0
  36. package/skills/protobase/references/reference/events.md +121 -0
  37. package/skills/protobase/references/reference/files.md +291 -0
  38. package/skills/protobase/references/reference/forms.md +133 -0
  39. package/skills/protobase/references/reference/history.md +86 -0
  40. package/skills/protobase/references/reference/jobs.md +174 -0
  41. package/skills/protobase/references/reference/layouts.md +126 -0
  42. package/skills/protobase/references/reference/plugins.md +328 -0
  43. package/skills/protobase/references/reference/remote-resources.md +198 -0
  44. package/skills/protobase/references/reference/sidebar.md +51 -0
  45. package/skills/protobase/references/reference/theme.md +132 -0
  46. package/skills/protobase/references/reference/ui-config.md +880 -0
  47. package/skills/protobase/references/reference/user-menu.md +38 -0
  48. package/skills/protobase/references/reference/versioning.md +91 -0
  49. package/skills/protobase/references/reference/webhooks.md +136 -0
@@ -0,0 +1,880 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/ui-config.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # UI config
4
+
5
+ Views in ui.ts, with names, list columns, editing in the list, sorting records by hand (also an invoice's items), filters, charts (graphs of records per day or per value), exports to Excel and CSV, record layouts, related records (in a section or as dots in a list column), field hints, actions (with a dialog of inputs when they ask for some) and views per role.
6
+
7
+ 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](data-config.md#access)), and `/api/meta` removes from each user's view every field they cannot read.
8
+
9
+ ```ts
10
+ import { view } from '@protobase/schema'
11
+ import type { repairs } from './data'
12
+
13
+ export const repairsView = view<typeof repairs>('repairs')
14
+ ```
15
+
16
+ [`view<typeof resource>(name)`](https://docs.protobase.net/api/schema/functions/view/)) takes the resource's type, so every field reference below (`r.status`) is checked by TypeScript. A view is immutable: each [method](https://docs.protobase.net/api/schema/interfaces/viewbuilder/)) returns a new view, so one view can build on another. The examples are the files of the [bike shop guide](../guides/table-to-admin.md)), where each step builds on the last.
17
+
18
+ ## Names and columns
19
+
20
+ ```ts title="docs-examples/bike-shop/step-2.ts"
21
+ import { view } from '@protobase/schema'
22
+ import type { customers, repairs } from './data'
23
+
24
+ // Step 2: names, what a record is called, the columns the workshop reads, and how values look.
25
+
26
+ export const customersView = view<typeof customers>('customers')
27
+ .names({ singular: 'Customer', plural: 'Customers' })
28
+ .title((r) => r.name)
29
+ .list((r) => ({ columns: [r.name, r.phone, r.email], sort: [[r.name, 'asc']] }))
30
+
31
+ export const repairsView = view<typeof repairs>('repairs')
32
+ .names({ singular: 'Repair', plural: 'Repairs' })
33
+ .title((r) => r.number)
34
+ .fields((r) => ({
35
+ number: r.number.format('code'),
36
+ customer_id: r.customer_id.label('Customer'),
37
+ status: r.status.format('badge'),
38
+ estimate: r.estimate.prefix('€').decimals(2),
39
+ booked_on: r.booked_on.label('Booked on'),
40
+ }))
41
+ .list((r) => ({
42
+ columns: [r.number, r.customer_id, r.bike, r.status, r.mechanic, r.estimate, r.booked_on],
43
+ sort: [[r.booked_on, 'desc']],
44
+ search: [r.number, r.bike],
45
+ }))
46
+ ```
47
+
48
+ | Method | |
49
+ | --- | --- |
50
+ | `.names({ singular, plural })` | "New repair", "Repairs" in the sidebar, breadcrumbs and browser tabs. Default: the resource name in words. |
51
+ | `.title((r) => r.number)` | The field that names a record: in breadcrumbs, browser tabs, the record page's heading, relation links and search results. |
52
+ | `.searchResult((r) => ({ title?, subtitle? }))` | A record in the [global search](client.md#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. |
53
+ | `.list((r, d, c) => ({ columns, sort?, search?, filter?, editable?, displays?, default? }))` | The list's columns in order, fields or [related records](#related-records-in-a-list) (`c.related`); the `filter` it [opens with](#a-filter-the-list-opens-with); its starting `sort` as `[[field, 'asc' \| 'desc'], ...]`, on `.sortable()` fields; 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](#editing-in-the-list); other ways to show it, see [List displays](#list-displays). `protobase build` fails on a sort or search field outside those. |
54
+ | `.fields((r) => ({ name: r.name.label(...) }))` | Hints per field, below. Calls add up. |
55
+ | `.help(text)` | A line under the list's title. |
56
+ | `.nav({ group, order, hidden, recent })` | Where the resource sits in the sidebar, and its [recent-record group](sidebar.md#recent-records)). |
57
+ | `.icon(name)` | Carried in `/meta` for apps that render their own shell; the admin picks sidebar icons by resource name. |
58
+ | `.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](#favorites). |
59
+ | `.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](#sign-in-prompts). |
60
+ | `.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](forms.md)). |
61
+
62
+ A browser tab names what it shows, then the app's name ([`appName`](auth.md#configuration))): `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.
63
+
64
+ 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.
65
+
66
+ Field hints:
67
+
68
+ | Hint | |
69
+ | --- | --- |
70
+ | `.label(text)` | Instead of the name in words (`customer_id` would be "Customer" anyway). |
71
+ | `.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](#help-while-editing). |
72
+ | `.format(format)` | `badge` shows statuses as coloured badges, `code` sets identifiers in monospace, `percent` adds a % sign. 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), 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, and the admin does not use them yet. |
73
+ | `.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, a page's field blocks and a card's subtitle keep its line breaks (a card shows the first three lines). 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. |
74
+ | `.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, a page's field blocks and the sidebar show it rendered as GitHub does, line breaks kept; raw HTML shows as text, links and images keep only http(s), mailto, tel and relative addresses, and links open in a new tab. A card's subtitle shows its first three lines rendered, its links as text; the list's table and a card's other lines show its text on one line without the marks. On the record page and the create form it takes the whole width of its section. Only a text field takes it, and the renderer loads with the first markdown shown. |
75
+ | `.prefix(text)`, `.suffix(text)`, `.decimals(n)` | Money and measures: `€` 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. |
76
+ | `.icon(name)` | An icon before the value on a card's meta row: `bath`, `bed`, `bell`, `bookmark`, `calendar`, `door-open`, `external-link`, `file-text`, `heart`, `house`, `key`, `land-plot`, `leaf`, `ruler`, `send`, `tag` or `wallet`, as for [actions](layouts.md#named-actions)), and above the value in a section of [key facts](#key-facts). Nowhere else shows it. |
77
+ | `.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. |
78
+ | `.valueColors({ value: '#hex' })`, `.badgeShape('arrow')` | An enum's badges filled with a colour per value (the text turns white or black, whichever reads), and drawn as arrows pointing right, as on a rating scale. 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. |
79
+ | `.widget(name, props?)` | Shows and edits the field with a [field type](plugins.md#field-types)) of the project or a plugin, such as `r.status.widget('steps')` or `r.score.widget('rating', { max: 5 })`; `props` are plain data. Without it, or on a storage type it does not show, the field shows as it would without the hint. |
80
+
81
+ 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)`](https://docs.protobase.net/api/schema/functions/enumlabel/)) 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.
82
+
83
+ 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 the choice is kept. Embedded lists and a page's `Table` blocks size their columns the same way.
84
+
85
+ ### Related records in a list
86
+
87
+ 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`:
88
+
89
+ ```ts
90
+ view<typeof objectives>('objectives').list((r, d, c) => ({
91
+ columns: [
92
+ r.title,
93
+ c.related('tasks', { resource: 'tasks', field: 'id', through: { resource: 'objective_tasks', field: 'objective_id', key: 'task_id' }, status: 'status', sort: 'position' }),
94
+ r.quarter,
95
+ ],
96
+ }))
97
+ ```
98
+
99
+ | Option | |
100
+ | --- | --- |
101
+ | `resource`, `field`, `through`, `filter` | Which records each row shows, as a [related section](#related-records) 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. |
102
+ | `status` | An enum field of `resource`. Each dot is filled with the colour its value has in the resource's view (`.valueColors(...)`), else in the value's badge tone. Required. |
103
+ | `sort` | The dots' order, AIP-132 on `resource`. |
104
+ | `label` | The column's header; default the name in words. The name must not be a field of the resource. |
105
+
106
+ 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".
107
+
108
+ 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.
109
+
110
+ 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.
111
+
112
+ ```ts
113
+ view<typeof objectives>('objectives').list((r, d, c) => {
114
+ const tasks = c.related('tasks', { resource: 'tasks', field: 'id', through: { resource: 'objective_tasks', field: 'objective_id', key: 'task_id' }, status: 'status', sort: 'position' })
115
+ return { columns: [r.title, tasks, r.quarter], displays: [d.cards({ title: r.title, footer: [r.quarter], dots: [tasks] })] }
116
+ })
117
+ ```
118
+
119
+ ### Editing in the list
120
+
121
+ The list's table can edit some of its columns in place, as a spreadsheet does: `editable` names them, among the `columns`.
122
+
123
+ ```ts
124
+ view<typeof products>('products').list((r) => ({
125
+ columns: [r.sku, r.name, r.price, r.status, r.active],
126
+ editable: [r.price, r.status, r.active],
127
+ }))
128
+ ```
129
+
130
+ 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](plugins.md#field-types))'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.
131
+
132
+ 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.
133
+
134
+ 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.
135
+
136
+ 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.
137
+
138
+ ### Sorting by hand
139
+
140
+ 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(...)`](data-config.md#resource)), 1 the first; with `within`, a relation, each parent's records have an order of their own:
141
+
142
+ ```ts title="docs-examples/reference/invoice-items.ts"
143
+ import { f, l, resource, view } from '@protobase/schema'
144
+
145
+ // Records in an order of their own, sorted by hand: the products in the order the shop lists them, sorted on their
146
+ // list, and each invoice's items in the order the invoice prints them, sorted on the invoice's page.
147
+
148
+ export const products = resource('products')
149
+ .table('products')
150
+ .fields({
151
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
152
+ name: f.text(),
153
+ rank: f.integer().sortable(),
154
+ })
155
+ .primaryKey((r) => r.id)
156
+ .position((r) => r.rank)
157
+
158
+ export const invoices = resource('invoices')
159
+ .table('invoices')
160
+ .fields({
161
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
162
+ number: f.text(),
163
+ customer: f.text(),
164
+ })
165
+ .primaryKey((r) => r.id)
166
+
167
+ export const invoiceItems = resource('invoice_items')
168
+ .table('invoice_items')
169
+ .fields({
170
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
171
+ invoice_id: f.relation('invoices').filterable(),
172
+ position: f.integer().sortable(),
173
+ description: f.text(),
174
+ amount: f.decimal({ precision: 12, scale: 2 }),
175
+ })
176
+ .primaryKey((r) => r.id)
177
+ .position((r) => r.position, { within: (r) => r.invoice_id })
178
+
179
+ export const productsView = view<typeof products>('products')
180
+ .title((r) => r.name)
181
+ .list((r) => ({ columns: [r.name], sort: [[r.rank, 'asc']] }))
182
+
183
+ export const invoicesView = view<typeof invoices>('invoices')
184
+ .title((r) => r.number)
185
+ .layout((r) => [
186
+ l.section('Invoice', [r.number, r.customer]),
187
+ l.related('Items', { resource: 'invoice_items', field: 'invoice_id', sort: 'position' }),
188
+ ])
189
+
190
+ export const invoiceItemsView = view<typeof invoiceItems>('invoice_items')
191
+ .names({ singular: 'Item', plural: 'Items' })
192
+ .title((r) => r.description)
193
+ .list((r) => ({ columns: [r.description, r.amount], sort: [[r.position, 'asc']] }))
194
+ ```
195
+
196
+ The list of a resource ordered as one, such as the products, has a **Sort** 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. **Sort** 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.
197
+
198
+ Each drop shows at once and is saved straight away: one [batch `reorder`](api.md#batch-writes)) numbers the records 1, 2, 3, ... in their new order, writing those whose number changes with the ETags they were listed with, so a gap or a tie left by an earlier write is closed too. Drops made while one saves are saved after it. A refusal, such as a record someone else changed since, puts the rows back as the server has them, with the reason. Every list of the resource reloads afterwards.
199
+
200
+ A user who may not update the resource or write the field gets no **Sort**, 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. At most 500 records are sorted at once, the list API's largest page; with more, **Sort** says so instead. The field must be `.sortable()` and `within` a `.filterable()` relation, checked when the config loads, and [`protobase doctor`](cli.md#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.
201
+
202
+ ## A filter the list opens with
203
+
204
+ ```ts
205
+ view('repairs').list((r) => ({
206
+ columns: [r.number, r.status],
207
+ filter: 'in(status, "todo", "doing")',
208
+ })).filters((r, w) => [w.facets(r.status)])
209
+ ```
210
+
211
+ `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`](cli.md#doctor)) checks that an index serves it.
212
+
213
+ ## More than one list
214
+
215
+ ```ts
216
+ view<typeof changelog>('changelog')
217
+ .names({ singular: 'Changelog entry', plural: 'Changelog' })
218
+ .list(...)
219
+ .namedList('updates', (v) => v
220
+ .names({ singular: 'Update', plural: 'Updates' })
221
+ .nav({ group: historyNav, order: 1 })
222
+ .list((r) => ({ columns: [r.closed_on, r.title], sort: [[r.closed_on, 'desc']] }))
223
+ .filters((r, w) => [w.dateRange(r.closed_on)]))
224
+ ```
225
+
226
+ `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`](cli.md#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.
227
+
228
+ ## Filters and the chart
229
+
230
+ ```ts title="docs-examples/bike-shop/step-3.ts"
231
+ import { customersView, repairsView as named } from './step-2'
232
+
233
+ // Step 3: the filters the front desk reaches for, and a chart of bookings above the list.
234
+
235
+ export { customersView }
236
+
237
+ export const repairsView = named
238
+ .filters((r, w) => [
239
+ w.facets(r.status),
240
+ w.facets(r.mechanic, { search: true }),
241
+ w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] }),
242
+ w.range(r.estimate, { histogram: true }),
243
+ w.toggle(r.paid),
244
+ ])
245
+ .chart((r) => ({ field: r.booked_on, range: '30d', granularity: 'day' }))
246
+ ```
247
+
248
+ `.filters((r, w) => [...])` puts widgets above the list, in order. Each needs a field that is `.filterable()`, which [`protobase build`](cli.md#build)) checks, and an index that serves it, as the [scan guard](api.md#safety)) and [`protobase doctor`](cli.md#doctor)) check; together they write the list's `?filter=`, so a filtered list can be bookmarked and shared.
249
+
250
+ | Widget | |
251
+ | --- | --- |
252
+ | `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. |
253
+ | `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`. |
254
+ | `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. |
255
+ | `w.toggle(r.paid)` | A switch for a boolean field. |
256
+ | `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. |
257
+
258
+ 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.
259
+
260
+ 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.
261
+
262
+ ### Charts (graphs): records per day, week or month, or per value, above a list
263
+
264
+ A list can show a graph of how many of its records fall on each hour, day, week or month, such as a daily graph of new listings. `.chart((r) => ({ field, range, granularity }))` draws records per day or week over a date or timestamp field above the list, following its filters: `range` is `7d`, `30d`, `90d`, `1y` or `all`, `granularity` `hour`, `day`, `week` or `month`.
265
+
266
+ 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`](blocks.md#chart)) block.
267
+
268
+ ## List displays
269
+
270
+ 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, 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.
271
+
272
+ ```ts title="docs-examples/reference/workshop.ts"
273
+ import { component } from '@protobase/layout'
274
+ import { l } from '@protobase/schema'
275
+ import { repairsView as daily } from '../bike-shop/step-5'
276
+
277
+ // The bike shop's repairs as cards, as a workshop board and on a calendar of their booking days beside the table, and a
278
+ // repair's page with the customer's earlier repairs: a custom component inside the standard `/repairs/<key>` page.
279
+
280
+ /** The other repairs of the repair's customer, drawn by the `CustomerRepairs` export of protobase.ui.tsx. */
281
+ export const CustomerRepairs = component<{ limit: number }>('CustomerRepairs')
282
+
283
+ export const repairsView = daily
284
+ .list((r, d) => ({
285
+ columns: [r.number, r.customer_id, r.bike, r.status, r.estimate, r.booked_on],
286
+ sort: [[r.booked_on, 'desc']],
287
+ search: [r.number, r.bike],
288
+ displays: [
289
+ d.cards({ title: r.bike, subtitle: r.customer_id, badge: r.status, meta: [r.number, r.booked_on] }),
290
+ d.board({ by: r.status, title: r.number, subtitle: r.bike, meta: [r.mechanic] }),
291
+ d.calendar({ start: r.booked_on, title: r.number }),
292
+ ],
293
+ default: 'board',
294
+ }))
295
+ .layout((r) => [
296
+ l.section('The bike', [r.customer_id, r.bike, r.problem]),
297
+ l.section('In the workshop', [r.status, r.mechanic, r.notes]),
298
+ l.custom(CustomerRepairs, { title: 'Earlier repairs of this customer', props: { limit: 5 } }),
299
+ l.sidebar([r.status, r.estimate, r.booked_on]),
300
+ ])
301
+ ```
302
+
303
+ | Display | |
304
+ | --- | --- |
305
+ | `d.cards({ image?, title?, subtitle?, amount?, badge?, meta?, footer?, flags?, dots? }, { name?, label?, icon?, card?, photos?, favorite? })` | A card per record, opening it: `image`, a [file field](files.md)), 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, 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](#related-records-in-a-list) 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](custom-components.md#record-cards))). With `photos`, the picture steps through more photos, by swipe or arrows (see [Card photos](#card-photos)). With `favorite`, a heart in the card's top right corner saves the record (see [Favorites](#favorites)). Named `cards` unless `name` says otherwise. |
306
+ | `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`](api.md#maps)). 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](#approximate-positions). Named `map` unless `name` says otherwise. See [Maps](#maps). |
307
+ | `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. Dragging a card to another column, or moving it with the keyboard, saves the record with that column's value. Within a column, cards are reordered when the resource has a `.position()`. Named `board` unless `name` says otherwise. See [Boards](#boards). |
308
+ | `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](#calendars). |
309
+ | `d.custom(Component, { name, label, fields, props?, icon? })` | The rows drawn by a [custom component](custom-components.md#list-displays)). `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. |
310
+
311
+ 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` or `calendar`). 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), a list with a cards display opens in it instead: the `default` when that is a cards display, else the first. A list without one 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.
312
+
313
+ The table, the cards, a board and a calendar 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, and Back returns to the same ones. 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.
314
+
315
+ 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](data-config.md#sensitive-fields)). 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.
316
+
317
+ ### Boards
318
+
319
+ `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.
320
+
321
+ 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.
322
+
323
+ 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`](layouts.md#named-actions)) sends. So the resource's [access rules](access.md)) 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](access.md#restricted-model-and-row-filters)) keep them from updating, can open its card but not move it.
324
+
325
+ A resource with a [`.position(...)`](data-config.md#resource)) and no `within` has its board's columns in that order instead of the list's, so the board has no sort menu:
326
+
327
+ ```ts title="docs-examples/reference/ranked-board.ts"
328
+ import { f, resource, view } from '@protobase/schema'
329
+
330
+ // A team's tasks on a board in the order of their rank, each column sorted by dragging its cards.
331
+
332
+ export const tasks = resource('tasks')
333
+ .table('tasks')
334
+ .fields({
335
+ id: f.integer().readOnly().filterable().sortable().dbDefault(),
336
+ title: f.text(),
337
+ status: f.enum(['todo', 'doing', 'done']).filterable().sortable(),
338
+ rank: f.integer().sortable(),
339
+ })
340
+ .primaryKey((r) => r.id)
341
+ .position((r) => r.rank)
342
+
343
+ export const tasksView = view<typeof tasks>('tasks')
344
+ .title((r) => r.title)
345
+ .list((r, d) => ({ columns: [r.title, r.status], displays: [d.board({ by: r.status })], default: 'board' }))
346
+ ```
347
+
348
+ 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](api.md#batch-writes)): in another column first the update of `by` with the card's ETag, then a `reorder` numbering the column's cards 1, 2, 3, ... down to the last one that moved, each with its ETag. So access, `validate` and a stale ETag refuse it as they do a column move, and a refusal puts the cards back with the reason. 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 **Sort** does; a user without it moves cards between columns only, as on a board without a position. A resource without a position, or with `within`, keeps the list's order.
349
+
350
+ `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`](cli.md#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.
351
+
352
+ ### Calendars
353
+
354
+ `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.
355
+
356
+ 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.
357
+
358
+ 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](access.md)) 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.
359
+
360
+ `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`](cli.md#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.
361
+
362
+ ### Card photos
363
+
364
+ `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`](api.md#card-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.
365
+
366
+ ```ts
367
+ d.cards({ image: r.photo, title: r.address }, { photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } })
368
+ ```
369
+
370
+ 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](api.md#safety)) 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.
371
+
372
+ ### Favorites
373
+
374
+ `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.
375
+
376
+ A visitor who is not signed in gets the heart too, when the view of `resource` has a [sign-in prompt](#sign-in-prompts): pressing it tells them what signing in gives, in a modal on a desktop and a sheet from the bottom on a phone.
377
+
378
+ 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.
379
+
380
+ ```ts
381
+ // listings/ui.ts
382
+ d.cards({ image: r.photo, title: r.address }, { favorite: { resource: 'favorites', field: 'listing_id', label: 'Save to favorites' } })
383
+
384
+ // favorites/ui.ts
385
+ view<typeof favorites>('favorites').names({ singular: 'Favorite', plural: 'Favorites' }).listOf((r) => r.listing_id)
386
+ ```
387
+
388
+ The server checks `favorite` when it starts: `resource` has an [owner](data-config.md#access)) (`.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.
389
+
390
+ ### Saved searches
391
+
392
+ `.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](#sign-in-prompts), which a press opens.
393
+
394
+ 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`](blocks.md#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`).
395
+
396
+ 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.
397
+
398
+ 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.
399
+
400
+ ```ts
401
+ // listings/ui.ts
402
+ view<typeof listings>('listings').saveSearch({ resource: 'saved_searches' })
403
+
404
+ // saved_searches/ui.ts
405
+ view<typeof savedSearches>('saved_searches').searchesOf((r) => ({
406
+ resource: 'listings',
407
+ filter: r.filter,
408
+ name: r.name,
409
+ controls: [r.alert_frequency],
410
+ unseen: { seenAt: r.seen_at, field: 'published_at' },
411
+ }))
412
+ ```
413
+
414
+ 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](data-config.md#access)), 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`.
415
+
416
+ 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](email.md)). The [property portal example](https://github.com/PrototeamHQ/protobase/tree/main/examples/property-portal#alerts) mails at once or in a daily digest.
417
+
418
+ ### Exports
419
+
420
+ 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.
421
+
422
+ 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](api.md#safety)), the role's row filter and its readable fields apply as on the list; a [sensitive field](data-config.md#sensitive-fields)) is never offered. The selected rows are found again by their key, so a resource with a composite key offers only the list's rows. The browser builds the file in a Web Worker, the server only answering the pages it reads anyway, and writes it as it goes: to the file the user picks where the browser has the [File System Access API](https://developer.mozilla.org/docs/Web/API/File_System_API), as a download otherwise. A progress dialog counts the rows, and **Cancel** stops after the page being read and discards the file.
423
+
424
+ 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`.
425
+
426
+ `.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](data-config.md#access)), and the API serves it as it does to the list.
427
+
428
+ ```ts
429
+ view<typeof orders>('orders').export({ maxRows: 50_000 })
430
+ view<typeof auditLog>('audit_log').export(false)
431
+ ```
432
+
433
+ ## Importing records
434
+
435
+ 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. It opens a dialog that creates or updates records from an Excel workbook (`.xlsx`) or a CSV file (UTF-8, its delimiter a comma, semicolon or tab, found from the first line). See [Importing records from a spreadsheet](../guides/import-records.md)) for a walk through.
436
+
437
+ ```ts
438
+ view<typeof invoices>('invoices').import(false)
439
+ ```
440
+
441
+ 1. **File.** The first row names the columns; a workbook with several sheets asks which one to read. A Web Worker reads the file, a CSV and a sheet's rows as they stream in, so a large file neither holds up the page nor is held whole in memory, and the file itself never goes to the server: only the writes of its rows do.
442
+ 2. **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 JSON or files, 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.56` or `1.234,56`, the day or the month first; they start from the browser's language. Dates written as `2026-12-31` read the same either way, and a time without a zone is the browser's.
443
+ 3. **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.
444
+ 4. **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](#names-and-columns) or values, and related records found by exactly one match convert, and anything else is a problem on its row. The import skips those rows.
445
+ 5. **Import.** The rows are written in batches of 100 with [`POST /api/v1:batchWrite`](api.md#batch-writes)), 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.
446
+
447
+ ## Create pages
448
+
449
+ 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](layouts.md)) of the app's own that creates them, with `.create({ page })`:
450
+
451
+ ```ts
452
+ view<typeof repairs>('repairs').create({ page: 'book-repair' })
453
+ ```
454
+
455
+ - `/<resource>/new` shows that page instead of the create form, so the list's **New** button and every [create address](layouts.md#addresses)) open it. The breadcrumb reads the resource and **New**, as for the form.
456
+ - **New** shows to whoever `/api/meta` gives the page, as its `roles` say, whatever the resource's `create` access. The resource's API can then refuse creates (`create: () => false`) while the page creates through an [API function](../guides/api-functions.md)) that writes with `db`. Someone without the page gets no **New**, and `/<resource>/new` tells them they cannot create there: the create form never shows. **Import** still follows the resource's `create` access.
457
+ - The address's `values` stay in it. A component on the page reads them with `useAppAddress()` 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](custom-components.md#create-pages)).
458
+ - The server refuses a page that does not exist when it starts.
459
+
460
+ [A create page of your own](../guides/create-page.md)) builds one step by step.
461
+
462
+ ## Sign-in prompts
463
+
464
+ `.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](#favorites) that saves to the resource, and a list's [Save search](#saved-searches) button that saves to it, open the same prompt as a dialog, with **Not now** to close it. With [open sign-up](auth.md#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.
465
+
466
+ ```ts
467
+ view<typeof favorites>('favorites').signIn({
468
+ title: 'Keep the homes you like',
469
+ description: 'Sign in to save listings to your favorites and find them again on any device.',
470
+ benefits: ['Save a listing with the heart on its card', 'See all your saved homes on one page'],
471
+ icon: 'heart',
472
+ })
473
+ ```
474
+
475
+ 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](bottom-bar.md)) and the [user menu](user-menu.md)). 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.
476
+
477
+ ## The record page
478
+
479
+ ```ts title="docs-examples/bike-shop/step-4.ts"
480
+ import { l } from '@protobase/schema'
481
+ import { customersView, repairsView as filtered } from './step-3'
482
+
483
+ // Step 4: a record page that reads like the paper repair card: what is wrong, who works on it, what it costs.
484
+
485
+ export { customersView }
486
+
487
+ export const repairsView = filtered
488
+ .fields((r) => ({
489
+ problem: r.problem.help('In the customer’s words; the mechanic adds findings to the notes.'),
490
+ notes: r.notes.label('Workshop notes').help('Only the workshop reads these.'),
491
+ paid: r.paid.help('Set when the customer pays at the desk.'),
492
+ }))
493
+ .layout((r) => [
494
+ l.section('The bike', [r.customer_id, r.bike, r.problem]),
495
+ l.section('In the workshop', [r.status, r.mechanic, r.notes], { help: 'Pick up a repair by putting your name on it.' }),
496
+ l.section('Money', [r.estimate, r.currency, r.paid]),
497
+ l.sidebar([r.status, r.estimate, r.booked_on]),
498
+ ])
499
+ .saveFeedback('button')
500
+ ```
501
+
502
+ `.layout((r) => [...])` with [`l`](https://docs.protobase.net/api/schema/variables/l/)) from `@protobase/schema`:
503
+
504
+ | Item | |
505
+ | --- | --- |
506
+ | `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](#key-facts). |
507
+ | `l.group(title, items, { collapsed?, when? })` | A heading over sections and related tables, closed until opened with `collapsed: true`. `when` also takes a [condition](#form-and-read-view). See [Groups](#groups). |
508
+ | `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](#tabs). |
509
+ | `l.sidebar(fields, { when? })` | A summary card beside it, read-only. `when` also takes a [condition](#form-and-read-view). |
510
+ | `l.related(title, { ... })` | A table of the records of another resource that point at this one, in the main column. See [Related records](#related-records). |
511
+ | `l.custom(Component, { title?, props?, sidebar?, when? })` | A [custom component](custom-components.md#record-sections)) where it is listed: in the main column under `title`, or with `sidebar: true` as a sidebar card. |
512
+ | `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](#maps). |
513
+ | `l.gallery(title, { image?, photos?, when? })` | The record's photos as tiles, opening a lightbox. See [Galleries](#galleries). |
514
+ | `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](history.md#on-the-record-page)). |
515
+ | `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](comments.md#on-the-record-page)). |
516
+
517
+ 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:
518
+
519
+ Without a layout the record page shows one section with every field the user may change; its [read view](#read-view-and-edit), 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. 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. `.saveFeedback('button')` shows saving on the Save button instead of a toast (`'toast'`, the default). A [sensitive field](data-config.md#sensitive-fields)) in a section is masked, with an eye button that reveals it.
520
+
521
+ 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.
522
+
523
+ ### Read view and edit
524
+
525
+ `.recordMode(mode)` says how the record page opens to a user who may change the record:
526
+
527
+ | Mode | |
528
+ | --- | --- |
529
+ | `'edit'` | The form, ready to change, as without the setting. The default. |
530
+ | `'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](#key-facts). **Edit**, among the record's actions, opens the form. |
531
+ | `'locked'` | The form, its fields locked until **Edit** is pressed, for records where reading and editing look alike but a change should be meant. |
532
+
533
+ 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.
534
+
535
+ ```ts
536
+ view<typeof listings>('listings').recordMode('read')
537
+ ```
538
+
539
+ ### Groups
540
+
541
+ `l.group(title, items, { 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.
542
+
543
+ 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.
544
+
545
+ ### Tabs
546
+
547
+ `l.tab(title, items)` splits the record page into tabs. A tab holds any main-column item: sections, groups, related tables, custom components, maps, galleries, history and comments. 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.
548
+
549
+ 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.
550
+
551
+ 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.
552
+
553
+ ```ts
554
+ view<typeof listings>('listings').layout((r) => [
555
+ l.sidebar([r.status]),
556
+ l.tab('Details', [l.section('Home', [r.title, r.price])]),
557
+ l.tab('History', [l.history('Changes'), l.comments('Comments')]),
558
+ ])
559
+ ```
560
+
561
+ ### Key facts
562
+
563
+ `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-and-columns) 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.
564
+
565
+ ```ts
566
+ view<typeof listings>('listings')
567
+ .recordMode('read')
568
+ .fields((r) => ({
569
+ purchase_price: r.purchase_price.prefix('€').icon('tag'),
570
+ living_area: r.living_area.suffix(' m²').icon('ruler'),
571
+ bedrooms: r.bedrooms.icon('bed'),
572
+ energy_label: r.energy_label.format('badge').icon('leaf'),
573
+ }))
574
+ .layout((r) => [l.section('Key facts', [r.purchase_price, r.living_area, r.bedrooms, r.energy_label, r.garden], { presentation: 'facts' })])
575
+ ```
576
+
577
+ ### Help while editing
578
+
579
+ 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.
580
+
581
+ ```ts
582
+ view<typeof listings>('listings')
583
+ .recordMode('read')
584
+ .helpWhen('editing')
585
+ .fields((r) => ({
586
+ price: r.price.help('The asking price, without costs.'),
587
+ agent_phone: r.agent_phone.help('Call to plan a viewing.', { when: 'always' }),
588
+ }))
589
+ ```
590
+
591
+ ### Form and read view
592
+
593
+ 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:
594
+
595
+ | `when` | |
596
+ | --- | --- |
597
+ | `'always'` | On both, as without the setting. The default. |
598
+ | `'editing'` | Only while the record is edited: on its form and the create form, not on the read view or a locked form. |
599
+ | `'reading'` | Only while it is not: on the read view and the locked form, and in a gallery's photo details. |
600
+ | 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>`](layouts.md#conditions)) 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. |
601
+
602
+ ```ts
603
+ view<typeof listings>('listings')
604
+ .recordMode('read')
605
+ .fields((r) => ({ cover: r.cover.when('editing') }))
606
+ .layout((r) => [
607
+ l.gallery('Photos', { image: r.cover, photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' }, when: 'reading' }),
608
+ l.section('Listing', [r.address, r.price, r.cover]),
609
+ l.related('Photos', { resource: 'listing_photos', field: 'listing_id', when: 'editing' }),
610
+ ])
611
+ ```
612
+
613
+ 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: 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.
614
+
615
+ 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,50` is 12.50 and `1.234` is 1234, with the point taken as a decimal one too when the number cannot be grouped (`12.50`); in English `1,234.5` is 1234.5.
616
+
617
+ ### Galleries
618
+
619
+ `l.gallery(title, { image?, photos? })` shows a record's photos as tiles in the main column: one large, the next 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`](#card-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.
620
+
621
+ ```ts
622
+ .layout((r) => [
623
+ l.gallery('Photos', { image: r.photo, photos: { resource: 'listing_photos', field: 'listing_id', image: 'photo', sort: 'position' } }),
624
+ l.section('Listing', [r.address, r.price]),
625
+ ])
626
+ ```
627
+
628
+ 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`](cli.md#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.
629
+
630
+ ### Maps
631
+
632
+ `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.
633
+
634
+ ```ts
635
+ .layout((r) => [
636
+ l.map('Location', { latitude: r.latitude, longitude: r.longitude }),
637
+ l.section('Coordinates', [r.latitude, r.longitude]),
638
+ ])
639
+ ```
640
+
641
+ The map is drawn with [MapLibre](https://maplibre.org) from the style the server names: `createAdmin`'s `options.maps.style`, else `PROTOBASE_MAP_STYLE_URL`, an http(s) URL of a MapLibre style. The style's sources may be [PMTiles](https://docs.protomaps.com/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.
642
+
643
+ 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.
644
+
645
+ #### Approximate positions
646
+
647
+ 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.
648
+
649
+ 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.
650
+
651
+ ```ts
652
+ d.map(
653
+ { latitude: r.latitude, longitude: r.longitude, exact: r.coordinates_exact, radius: r.accuracy_m, area: r.street_outline },
654
+ { label: 'Map', defaultRadius: 250 },
655
+ )
656
+ ```
657
+
658
+ `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.
659
+
660
+ A map does not edit the position: list the fields in a section as well when users should change them. The [property portal example](https://github.com/PrototeamHQ/protobase/tree/main/examples/property-portal) shows a listing on a map, and its listings on one.
661
+
662
+ #### Map layers
663
+
664
+ `options.maps.layers` 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.
665
+
666
+ ```ts
667
+ createAdmin({
668
+ // ...
669
+ options: {
670
+ maps: {
671
+ layers: [
672
+ {
673
+ id: 'aerial_nl',
674
+ label: 'Aerial (NL)',
675
+ tiles: 'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg',
676
+ attribution: 'Luchtfoto <a href="https://www.beeldmateriaal.nl/">Beeldmateriaal Nederland</a>, CC BY 4.0, via <a href="https://www.pdok.nl/">PDOK</a>',
677
+ bounds: [3.2, 50.7, 7.3, 53.7],
678
+ maxzoom: 21,
679
+ },
680
+ ],
681
+ },
682
+ },
683
+ })
684
+ ```
685
+
686
+ | Field | What it is |
687
+ | --- | --- |
688
+ | `id` | Lowercase letters, digits and `_`, unique: what the browser remembers. |
689
+ | `label` | What the switch says. |
690
+ | `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. |
691
+ | `attribution` | The credit the tiles' licence asks for; it may hold links. |
692
+ | `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. |
693
+ | `maxzoom` | Optional deepest zoom of the tiles, from 0 to 24 (default 22); closer in, the map enlarges them. |
694
+
695
+ 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](https://www.pdok.nl/-/open-data-hr-luchtfoto) and Spain's [PNOA](https://pnoa.ign.es/) from the IGN, both CC BY 4.0, free and without a key; the [property portal example](https://github.com/PrototeamHQ/protobase/tree/main/examples/property-portal) offers both.
696
+
697
+ ### Related records
698
+
699
+ 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, the lines drawn on the page, and a relation an `l.related` section of the page already lists.
700
+
701
+ `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](blocks.md#table)) 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`:
702
+
703
+ | Option | |
704
+ | --- | --- |
705
+ | `resource` | The records listed. Required. |
706
+ | `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. |
707
+ | `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. |
708
+ | `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) pick the listed records. All of them are read. |
709
+ | `filter`, `sort` | AIP-160 and AIP-132 on `resource`, as in the list API. `filter` narrows the listed records, `through.filter` the join records. |
710
+ | `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. |
711
+ | `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. |
712
+ | `limit` | How many records it shows, 1 to 100; default 10. 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. |
713
+ | `display` | The display of `resource`'s list it opens in, such as `cards`; default the list's. |
714
+ | `help`, `empty` | A line under the title, and the text when nothing matches (default "Nothing here yet."). |
715
+ | `hideEmpty` | `true` leaves the section off the page while it has no records. |
716
+
717
+ 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:
718
+
719
+ ```ts title="examples/real-estate/config/units/ui.ts"
720
+ import { l, view } from '@protobase/schema'
721
+ import type { units } from './data'
722
+
723
+ /** A lease that covers today; `end_date` is its last day. */
724
+ const running = 'start_date <= now() AND (isNull(end_date) OR end_date >= now())'
725
+
726
+ export const unitsView = view<typeof units>('units')
727
+ .title((r) => r.label)
728
+ .names({ singular: 'Unit', plural: 'Units' })
729
+ .nav({ recent: { status: 'status', tones: { vacant: 'warning', renovation: 'info' }, filter: 'status != "let"' } })
730
+ .fields((r) => ({
731
+ property_id: r.property_id.label('Property'),
732
+ area_m2: r.area_m2.label('Area').help('Living area in m².').suffix(' m²'),
733
+ energy_label: r.energy_label.format('badge'),
734
+ base_rent: r.base_rent.label('Market rent').help('What a new lease would ask today, per month.').prefix('€').decimals(2),
735
+ status: r.status.help('Let while a lease runs; vacant or under renovation between leases.').format('badge').valueLabels({ let: 'Let', vacant: 'Vacant', renovation: 'Renovation' }),
736
+ }))
737
+ .list((r) => ({ columns: [r.label, r.property_id, r.status, r.bedrooms, r.area_m2, r.energy_label, r.base_rent], search: [r.label] }))
738
+ .filters((r, w) => [w.facets(r.status), w.facets(r.energy_label), w.range(r.base_rent, { histogram: true })])
739
+ .layout((r) => [
740
+ l.section('Unit', [r.property_id, r.label, r.floor, r.bedrooms, r.area_m2, r.energy_label]),
741
+ l.section('Letting', [r.status, r.base_rent]),
742
+ l.related('Let to', {
743
+ resource: 'lease_tenants',
744
+ field: 'lease_id',
745
+ through: { resource: 'leases', field: 'unit_id', filter: running },
746
+ // `primary` sorts after `co_signer`, so the primary tenant comes first
747
+ sort: 'role desc',
748
+ columns: ['tenant_id', 'role', 'tenant_id.email', 'tenant_id.phone'],
749
+ help: 'The primary tenant and co-signers of the running lease.',
750
+ empty: 'Vacant: no lease runs today.',
751
+ }),
752
+ l.related('Running lease', {
753
+ resource: 'leases',
754
+ field: 'unit_id',
755
+ filter: running,
756
+ columns: ['number', 'term', 'start_date', 'end_date', 'monthly_rent', 'service_costs'],
757
+ empty: 'Vacant: no lease runs today.',
758
+ }),
759
+ l.sidebar([r.status, r.base_rent]),
760
+ ])
761
+ ```
762
+
763
+ When `resource` is ordered by hand within the record on the page (`.position(..., { within })` names `field`), the section has a **Sort** button that puts its records in order by dragging them; see [Sorting by hand](#sorting-by-hand).
764
+
765
+ 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.
766
+
767
+ ## Actions and views per role
768
+
769
+ ```ts title="docs-examples/bike-shop/step-5.ts"
770
+ import { l } from '@protobase/schema'
771
+ import { customersView, repairsView as laidOut } from './step-4'
772
+
773
+ // Step 5: buttons for the moves the shop makes all day, and a quieter view for the mechanics.
774
+
775
+ export { customersView }
776
+
777
+ export const repairsView = laidOut.actions((a) => [
778
+ a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } }),
779
+ a.update('collect', { label: 'Collected and paid', icon: 'wallet', set: { status: 'collected', paid: true }, confirm: 'Has the customer paid and taken the bike?' }),
780
+ a.link('customerRepairs', { label: 'Other repairs of this customer', icon: 'file-text', to: { kind: 'list', resource: 'repairs', filter: 'customer_id = {customer_id}' } }),
781
+ ])
782
+
783
+ /** What mechanics get instead: no money, and their own move. */
784
+ export const workshopRepairsView = laidOut
785
+ .forRoles(['mechanic'])
786
+ .list((r) => ({ columns: [r.number, r.bike, r.problem, r.status, r.mechanic], sort: [[r.booked_on, 'asc']], search: [r.number, r.bike] }))
787
+ .filters((r, w) => [w.facets(r.status), w.facets(r.mechanic, { search: true }), w.dateRange(r.booked_on, { presets: ['7d', '30d', 'month'] })])
788
+ .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])])
789
+ .actions((a) => [a.update('ready', { label: 'Ready for pickup', icon: 'send', set: { status: 'ready' } })])
790
+ ```
791
+
792
+ `.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`](ai.md#ai-actions)), 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](#actions-that-ask-for-input) first when they have some. They are described with [named actions](layouts.md#named-actions)).
793
+
794
+ `.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.
795
+
796
+ The ERP's orders view uses most of this page at once, with a recent-record group in the sidebar:
797
+
798
+ ```ts title="examples/erp/config/orders/ui.ts"
799
+ import { view } from '@protobase/schema'
800
+ import type { orders } from './data'
801
+
802
+ export const ordersView = view<typeof orders>('orders')
803
+ .title((r) => r.number)
804
+ .names({ singular: 'Order', plural: 'Orders' })
805
+ .nav({
806
+ recent: {
807
+ status: 'status',
808
+ tones: { draft: 'neutral', confirmed: 'info', picking: 'warning', shipped: 'success' },
809
+ pulse: ['picking'],
810
+ filter: 'status != "delivered" AND status != "cancelled"',
811
+ orderBy: 'created_at desc',
812
+ },
813
+ })
814
+ .fields((r) => ({
815
+ status: r.status.help('Where the order is in its life. Moving it forward can notify the customer.').format('badge')
816
+ .valueLabels({ draft: 'Draft', confirmed: 'Confirmed', picking: 'Picking', shipped: 'Shipped', delivered: 'Delivered', cancelled: 'Cancelled' }),
817
+ total: r.total.help('Order total including VAT.').prefix('€').decimals(2),
818
+ discount_percent: r.discount_percent.label('Discount').help('Percentage taken off the order total.').format('percent'),
819
+ paid: r.paid.help('Set when the payment has been received.'),
820
+ created_at: r.created_at.label('Created').format('absolute'),
821
+ }))
822
+ .list((r) => ({
823
+ columns: [r.number, r.company_id, r.status, r.total, r.discount_percent, r.paid, r.owner_id, r.created_at],
824
+ sort: [[r.created_at, 'desc']],
825
+ search: [r.number],
826
+ }))
827
+ .filters((r, w) => [
828
+ w.facets(r.status),
829
+ w.facets(r.owner_id),
830
+ w.dateRange(r.created_at, { presets: ['7d', '30d', '90d', 'quarter', 'year'] }),
831
+ w.range(r.total, { histogram: true }),
832
+ w.toggle(r.paid),
833
+ ])
834
+ .chart((r) => ({ field: r.created_at, range: '30d', granularity: 'day' }))
835
+ .saveFeedback('toast')
836
+ .actions((a) => [
837
+ a.update('markPaid', { label: 'Mark as paid', icon: 'wallet', set: { paid: true }, confirm: 'Record that the customer paid this order?' }),
838
+ a.action('createInvoice', { label: 'Create invoice', icon: 'file-text' }),
839
+ ])
840
+ ```
841
+
842
+ ### Actions that ask for input
843
+
844
+ `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:
845
+
846
+ ```ts
847
+ .actions((a) => [
848
+ a.action('remind', {
849
+ label: 'Send reminder',
850
+ icon: 'mail',
851
+ inputs: (i) => [
852
+ i.choice('channel', { label: 'Send by', options: [{ value: 'email', label: 'Email' }, { value: 'letter', label: 'Letter' }], default: 'email' }),
853
+ i.text('note', { label: 'Note', multiline: true, optional: true, when: "channel = 'email'" }),
854
+ ],
855
+ }),
856
+ ])
857
+ ```
858
+
859
+ 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:
860
+
861
+ ```ts
862
+ a.update('answer', { label: 'Answer', inputs: (i) => [i.text('answer', { label: 'Answer', multiline: true })], set: { answer: '{answer}' } })
863
+ ```
864
+
865
+ | Input | Asks for |
866
+ | --- | --- |
867
+ | `i.text(name, o)` | A line of text, or several with `multiline: true`; `max` is the most characters it may have. |
868
+ | `i.integer(name, o)` | A whole number, which the handler gets as a number. |
869
+ | `i.decimal(name, o)` | A number with decimals, which the handler gets as text, as the API gives decimals, so no digit is lost. |
870
+ | `i.boolean(name, o)` | A switch, `true` or `false`, so it is never required. |
871
+ | `i.date(name, o)` | A date, `YYYY-MM-DD`. |
872
+ | `i.choice(name, { options })` | One of `options`, each a `value` with the `label` it reads as. |
873
+ | `i.choice(name, { resource })` | A record of `resource`, picked as the create form picks a relation; the handler gets its key. |
874
+ | `i.custom(name, { component, props? })` | What a [component](custom-components.md)) of the app's `protobase.ui.tsx`, by the name it is registered under, edits. |
875
+
876
+ 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>`](layouts.md#conditions)) is over a record: `"start = 'github' OR code = 'github'"`. 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.
877
+
878
+ 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](../guides/api-functions.md)) 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.
879
+
880
+ 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](custom-components.md#field-types)) 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.