@protobase/cli 0.55.3 → 0.55.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/db/keys.js +5 -1
- package/dist/doctor/check.js +17 -2
- package/package.json +7 -7
- package/skills/protobase/references/features/data-model.md +1 -0
- package/skills/protobase/references/features/navigation.md +1 -1
- package/skills/protobase/references/features/your-own-code.md +2 -1
- package/skills/protobase/references/reference/api.md +1 -1
- package/skills/protobase/references/reference/cli.md +1 -1
- package/skills/protobase/references/reference/custom-components.md +4 -2
- package/skills/protobase/references/reference/data-config.md +27 -0
- package/skills/protobase/references/reference/sidebar.md +31 -1
- package/skills/protobase/references/reference/ui-config.md +8 -0
package/dist/cli/package.js
CHANGED
package/dist/db/keys.js
CHANGED
|
@@ -10,6 +10,10 @@ const isUniqueSet = (table, columns) => table.indexes.some((index) => {
|
|
|
10
10
|
const indexed = plainColumns(index.columns);
|
|
11
11
|
return index.unique && !index.partial && indexed && indexed.every((column) => columns.includes(column));
|
|
12
12
|
});
|
|
13
|
+
const hasUniqueIndexOn = (table, columns) => table.indexes.some((index) => {
|
|
14
|
+
const indexed = plainColumns(index.columns);
|
|
15
|
+
return index.unique && !index.partial && indexed?.length === columns.length && indexed.every((column) => columns.includes(column));
|
|
16
|
+
});
|
|
13
17
|
const coverageIndexes = (table) => table.indexes.map((index) => ({
|
|
14
18
|
name: index.name,
|
|
15
19
|
method: index.method,
|
|
@@ -21,4 +25,4 @@ const coverageIndexes = (table) => table.indexes.map((index) => ({
|
|
|
21
25
|
}))
|
|
22
26
|
}));
|
|
23
27
|
//#endregion
|
|
24
|
-
export { coverageIndexes, isUniqueSet, keyColumns };
|
|
28
|
+
export { coverageIndexes, hasUniqueIndexOn, isUniqueSet, keyColumns };
|
package/dist/doctor/check.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { tableKey } from "../db/model.js";
|
|
2
|
-
import { isUniqueSet, keyColumns } from "../db/keys.js";
|
|
2
|
+
import { hasUniqueIndexOn, isUniqueSet, keyColumns } from "../db/keys.js";
|
|
3
3
|
import { checkEnumValues } from "../infer/check-values.js";
|
|
4
4
|
import { columnDefault } from "../infer/defaults.js";
|
|
5
5
|
import { inferKind } from "../infer/type-map.js";
|
|
@@ -57,6 +57,17 @@ const checkKey = (model, table) => {
|
|
|
57
57
|
message: `primary key (${columns.join(", ")}) is not backed by a unique index`
|
|
58
58
|
}];
|
|
59
59
|
};
|
|
60
|
+
const checkOpenExisting = (model, table) => {
|
|
61
|
+
if (!model.openExisting || table.kind !== "table") return [];
|
|
62
|
+
const columns = model.openExisting.map((name) => model.fields[name].column);
|
|
63
|
+
if (hasUniqueIndexOn(table, columns)) return [];
|
|
64
|
+
return [{
|
|
65
|
+
severity: "error",
|
|
66
|
+
resource: model.name,
|
|
67
|
+
message: `openExisting (${columns.join(", ")}) is not the columns of a unique index, so every create would fail`,
|
|
68
|
+
suggestion: `ALTER TABLE ${quoteIdent(table.schema)}.${quoteIdent(table.name)} ADD UNIQUE (${columns.map(quoteIdent).join(", ")});`
|
|
69
|
+
}];
|
|
70
|
+
};
|
|
60
71
|
const checkResource = (model, tables) => {
|
|
61
72
|
const schema = model.table.schema ?? "public";
|
|
62
73
|
const table = tables.find((t) => t.schema === schema && t.name === model.table.name);
|
|
@@ -65,7 +76,11 @@ const checkResource = (model, tables) => {
|
|
|
65
76
|
resource: model.name,
|
|
66
77
|
message: `table ${schema}.${model.table.name} does not exist`
|
|
67
78
|
}];
|
|
68
|
-
return [
|
|
79
|
+
return [
|
|
80
|
+
...Object.keys(model.fields).flatMap((name) => checkField(model, table, name)),
|
|
81
|
+
...checkKey(model, table),
|
|
82
|
+
...checkOpenExisting(model, table)
|
|
83
|
+
];
|
|
69
84
|
};
|
|
70
85
|
//#endregion
|
|
71
86
|
export { checkResource };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.55.
|
|
3
|
+
"version": "0.55.5",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -42,12 +42,12 @@
|
|
|
42
42
|
"dependencies": {
|
|
43
43
|
"@better-auth/core": "^1.7.12",
|
|
44
44
|
"@hono/node-server": "^2.1.3",
|
|
45
|
-
"@protobase/config": "0.55.
|
|
46
|
-
"@protobase/layout": "0.55.
|
|
47
|
-
"@protobase/query": "0.55.
|
|
48
|
-
"@protobase/schema": "0.55.
|
|
49
|
-
"@protobase/server": "0.55.
|
|
50
|
-
"@protobase/ui": "0.55.
|
|
45
|
+
"@protobase/config": "0.55.5",
|
|
46
|
+
"@protobase/layout": "0.55.5",
|
|
47
|
+
"@protobase/query": "0.55.5",
|
|
48
|
+
"@protobase/schema": "0.55.5",
|
|
49
|
+
"@protobase/server": "0.55.5",
|
|
50
|
+
"@protobase/ui": "0.55.5",
|
|
51
51
|
"@react-email/render": "^2.1.0",
|
|
52
52
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
53
53
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -14,6 +14,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
|
|
|
14
14
|
- [Record authors](../reference/data-config.md#resource): A record can keep who created it. The server sets it to the signed-in user on every create, and no request can set or change it.
|
|
15
15
|
- [Record search](../reference/data-config.md#resource): You choose which fields text search and the global search look in. Partial words match, and phone numbers match by their last digits.
|
|
16
16
|
- [Manual order](../reference/data-config.md#resource): Records can be kept in an order set by hand, also per parent record, such as the lines of an invoice.
|
|
17
|
+
- [Opening an existing record](../reference/data-config.md#opening-an-existing-record): A create that repeats a record's unique values, such as a direct message with the same people, opens that record instead of failing, for whoever may read it; anyone else gets the usual conflict, which does not say the record exists.
|
|
17
18
|
- [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
|
|
18
19
|
- [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
|
|
19
20
|
- [Sensitive fields](../reference/data-config.md#sensitive-fields): Values such as bank account numbers are left out of every response and shown masked. A permitted user reveals one value at a time, and each reveal is audited.
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
The sidebar, the user menu, the bottom bar on phones and the global search.
|
|
6
6
|
|
|
7
7
|
- [Sidebar](../reference/sidebar.md): Resources and pages in groups, in the order you set.
|
|
8
|
-
- [Recent records](../reference/sidebar.md#recent-records): A sidebar entry lists a few records under it, with status dots or as titles alone.
|
|
8
|
+
- [Recent records](../reference/sidebar.md#recent-records): A sidebar entry lists a few records under it, with status dots or as titles alone, and marked per reader, such as unread ones in bold with a count.
|
|
9
9
|
- [Create link](../reference/sidebar.md#create-link): A sidebar entry links to its create form, such as "New message" under Direct messages, for whoever may create.
|
|
10
10
|
- [The current organization](../reference/sidebar.md#the-current-organization): A sidebar entry opens its list on the organization you work in, which you can clear to see every organization you are a member of.
|
|
11
11
|
- [User menu](../reference/user-menu.md): Account pages, help links, security settings, the theme switch and Sign out.
|
|
@@ -13,8 +13,9 @@ React components, field types, pages and handlers of your own, loaded as plugins
|
|
|
13
13
|
- [Form parts](../reference/custom-components.md#form-parts): Build your own forms from the app's fields, pickers, switches, buttons and dialogs.
|
|
14
14
|
- [Image carousel](../reference/custom-components.md#image-carousel): Step through screenshots or a record's files in your own components by swiping or with arrows, as cards step through photos.
|
|
15
15
|
- [Assistant parts](../reference/assistant.md#in-the-ui): The assistant's panel, chat messages, composer and action cards for your own components, with a frameless action card for a page that is already framed.
|
|
16
|
-
- [Chat parts](../reference/custom-components.md#chat-parts): A chat between people from the app's parts: messages with their author, avatar, time and a status line, day and new-message lines, a thread that loads earlier messages, keeps the reader's place and jumps to the end when they send, and a composer of several lines with @mentions.
|
|
16
|
+
- [Chat parts](../reference/custom-components.md#chat-parts): A chat between people from the app's parts: messages with their author, avatar, time and a status line, day and new-message lines, a thread that loads earlier messages, keeps the reader's place, opens on the new-message line, says when the reader has read to the end and jumps to the end when they send, and a composer of several lines with @mentions and slots for an attach button and a tray of picked files, which sends files without text and takes pasted and dropped files.
|
|
17
17
|
- [Members' names](../reference/custom-components.md#members-names): The names and photos of the organization's members by user id, for message authors and @mentions in your own components; every member reads them, without email addresses.
|
|
18
|
+
- [Signed-in user](../reference/custom-components.md#members-names): The signed-in person's user id and name in your own components, such as for a filter on their own messages.
|
|
18
19
|
- [Action handlers](../reference/custom-components.md#action-handlers): Your own code for a named action, with the record, the API client and the action's inputs.
|
|
19
20
|
- [Shell slots](../reference/custom-components.md#shell-slots): Your own components in the top bar, in a panel beside every page, or as the sidebar logo.
|
|
20
21
|
- [Plugins](../reference/plugins.md#how-a-plugin-stays-working): Your React code is a plugin that the app loads at start and that keeps working across Protobase releases without changes.
|
|
@@ -208,7 +208,7 @@ The API sends no CORS headers until it has something to allow: other websites in
|
|
|
208
208
|
|
|
209
209
|
## Errors
|
|
210
210
|
|
|
211
|
-
Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
|
|
211
|
+
Every error is `application/problem+json` (RFC 9457) with `type` (`urn:protobase:problem:<slug>`), `title`, `status`, `detail`, `instance`. Filter and `order_by` errors add `parameter` and `errors: [{ code, message, hint, span: { start, end } }]`; invalid parameters add `errors: [{ parameter, message }]`. A create or update whose body fails the checks is `invalid-record` with `errors: [{ field, code, message, params }]`, `code` one of `required`, `invalid-value`, `read-only`, `unknown-field` and `invalid-record` (a `.validate()` rule); `params` is the limit an invalid value broke, such as `{ min }`, `{ max }` or a decimal's `{ precision, scale }`. Database constraint failures map to `409` or `400` without the raw message. A create or update that writes the position of a resource with `after` so a record ranks at or above one it depends on is a `409` `ranks-above-dependency`, as in a [`reorder`](#batch-writes). A create that repeats the values of a resource's [`.openExisting()`](data-config.md#opening-an-existing-record) unique key is a `409` `conflict` with `existing: { key }`, the key of the record holding them as its address writes it, only when the caller may read that record; otherwise it is the plain `409`, as any unique conflict is. A delete that other records still point at is a `409` `conflict` with `blockedBy: { resource, field? }`: their resource, when the caller may list it, and its relation field pointing at the record, when they may filter by it, so a client can open those records; the admin app's toast names them, such as "Orders still point at this company.", with a link to that list. Postgres names one table of them only, so `blockedBy` holds one resource; anything unexpected is a `500` with a fixed detail, reported to the app's error hook (`hooks/error.ts`, `createAdmin`'s `options.onUnhandledError`) and, when it is set, the [error tracker](#error-reporting).
|
|
212
212
|
|
|
213
213
|
| Status | Slugs |
|
|
214
214
|
| --- | --- |
|
|
@@ -109,7 +109,7 @@ The URL comes as for [`scaffold`](#scaffold): the connection string, the variabl
|
|
|
109
109
|
|
|
110
110
|
Imports `config/index.ts` and the views of `config/*/ui.ts`, as the config module has them by convention, and checks every exported resource against the database:
|
|
111
111
|
|
|
112
|
-
- error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index, relation to a resource the config does not declare
|
|
112
|
+
- error: missing table or column, field type that does not fit the column (a file field needs a text column), table without a usable key, configured key not backed by a unique index, `.openExisting()` fields that are not the columns of a unique index, relation to a resource the config does not declare
|
|
113
113
|
- error: a read the [scan guard](api.md#safety) refuses, because no index serves a column it filters, sorts, searches or counts by. Doctor reads each table's indexes from the catalog, as the server does, and judges with the scan guard's own rule every read the API takes and the app makes: a filter on each `.filterable()` field, a sort by each `.sortable()` one, `search()` over the search fields, a role's own records (`.owner()`) and the names a relation shows; each view's list in its order and with the filter it opens with, its filter widgets and their counts, its chart, its map, board, calendar and timeline, its card photos, its order by hand, its related sections, galleries and charts, its named lists, its recent records and a saved search's new records; and each block of a [composed page](layouts.md) that lists records, and each `Chart` block's grouped and split fields. Each error is an index to add, with every request that needs it and where it comes from:
|
|
114
114
|
|
|
115
115
|
```
|
|
@@ -275,10 +275,10 @@ A chat between people, such as a team's channels, is built from the parts the [a
|
|
|
275
275
|
|
|
276
276
|
| | |
|
|
277
277
|
| --- | --- |
|
|
278
|
-
| `ChatThread` | The scrolling list of messages: `length`, the number of messages, and `empty`, shown while there are none. A reader at the end follows new messages; one who scrolled back stays where they are, until `followKey` changes: change it when the reader sends, such as to a count of their sends, and the thread goes to the end and follows their message in. `onLoadEarlier` adds **Load earlier messages** at the top, with `loadingEarlier` while they come; the earlier messages keep the reader on the message they were reading, never on a `ChatDivider`, which moves when earlier messages of its day load above it. It scrolls inside itself, so the composer under it stays in view. |
|
|
278
|
+
| `ChatThread` | The scrolling list of messages: `length`, the number of messages, and `empty`, shown while there are none. A reader at the end follows new messages; one who scrolled back stays where they are, until `followKey` changes: change it when the reader sends, such as to a count of their sends, and the thread goes to the end and follows their message in. `onLoadEarlier` adds **Load earlier messages** at the top, with `loadingEarlier` while they come; the earlier messages keep the reader on the message they were reading, never on a `ChatDivider`, which moves when earlier messages of its day load above it. It opens on its `ChatDivider tone="new"` line, near the top, when the messages it first gets hold one, and at the end otherwise. `onReadToEnd` is called while the page shows and the reader is at the end: when it opens there, when a message arrives as they follow, when they scroll to the end and when the page shows again with them there, such as to move their read position. It scrolls inside itself, so the composer under it stays in view. |
|
|
279
279
|
| `ChatMessage` | One message. `author` (`{ id, name }`) draws it on the left beside the author's avatar, under their name and `time`, an ISO timestamp shown on the viewer's clock; `avatar` replaces the initials, such as with a photo, and `continued` leaves out avatar, name and time for a message that follows the same author's. `from: 'user' \| 'assistant'` draws an assistant chat's sides instead. `footer` adds a small line under either, such as whether it was read. |
|
|
280
280
|
| `ChatDivider` | A line across the chat with a label: `label` for a day, such as `chatDayLabel(time)` ("Today", "Yesterday" or the date, on the viewer's calendar) between two messages for which `sameChatDay(a, b)` is false; `tone="new"` for the red **New messages** line. |
|
|
281
|
-
| `Composer` | The box under the chat, which grows with its text: Enter or the button sends, Shift+Enter starts a new line. `onSend` gets the trimmed text and the ids of the people it mentions. With `searchPeople`, a function that returns the `{ id, name }` people whose name matches the text typed after `@`, such as a channel's members, typing `@` lists them above the box: the arrows move, Enter or Tab picks, Escape closes. `busy` keeps the text from being sent. |
|
|
281
|
+
| `Composer` | The box under the chat, which grows with its text: Enter or the button sends, Shift+Enter starts a new line. `onSend` gets the trimmed text and the ids of the people it mentions. With `searchPeople`, a function that returns the `{ id, name }` people whose name matches the text typed after `@`, such as a channel's members, typing `@` lists them above the box: the arrows move, Enter or Tab picks, Escape closes. `busy` keeps the text from being sent. For a message that carries files, `actions` draws an attach button left of the box and `attachments` a tray of the picked files above it, `canSendEmpty` lets Enter and the button send with no text, `onSend('', [])`, and `onFiles` gets the files pasted into the box or dropped on the composer, which uploads nothing itself; a paste that holds text stays text. |
|
|
282
282
|
| `MentionBox`, `MentionedText` | The text box with `@` mentions that the composer and [comments](comments.md) are built from, for a box of your own: `value` and `onChange` hold the text and the people picked (`emptyDraft` to start), and `mentionedIds(text, picked)` the ids still mentioned. `MentionedText` shows a message's `text` with each `@name` of its `mentions` picked out. |
|
|
283
283
|
|
|
284
284
|
The messages' author comes from the server: give the resource [`.author()`](data-config.md#resource), and each create stores the signed-in user's id, never a value the client sends.
|
|
@@ -335,6 +335,8 @@ export const ChannelComposer = ({ onSend }: { onSend: (text: string, mentions: s
|
|
|
335
335
|
|
|
336
336
|
`searchPeople` filters the list in the browser and shows at most 8, as comments' mentions do. <gap>`useMembers()` cannot page or search on the server because a server-side people resource is not implemented, so the whole list loads in the browser, which suits a team, not thousands of members.</gap> <gap>Old messages of someone who has left the organization cannot show their name because looking up former members is not implemented.</gap> A person who works in an organization without being a member of it, through a global role, gets no list.
|
|
337
337
|
|
|
338
|
+
`useSignedInUser()` from `@protobase/ui` gives the signed-in person as `{ id, name? }`, `id` being the user id `.author()` stores and mentions hold, such as for a filter on their own messages (`author_id != "<id>"`) or mentions of them; it is `undefined` while the session loads, for a visitor and when nobody is signed in.
|
|
339
|
+
|
|
338
340
|
## Components in the chat
|
|
339
341
|
|
|
340
342
|
The same components draw the assistant's [widget parts](assistant.md#widget-parts): a part names a component, and the dock draws it with the part's props, so one component can sit on a page and in the chat. In the chat there is no record around it, so a component that needs `useLayoutRecord()` works only on pages; take ids as props instead. Besides the API hooks, a widget can read the assistant backend with [`useBackendData`](assistant.md#reading-the-backend-from-a-widget).
|
|
@@ -65,6 +65,7 @@ export const repairs = resource('repairs')
|
|
|
65
65
|
| `.search((r) => [r.number, r.name])` | The fields that `search("...")` and bare words in a filter match, and what the admin's [global search](client.md#global-search) looks in. Every word of the text must appear in one of them, ignoring case, and part of a word is enough: `port` finds "Portfolio". `r.phone.digitsEnd()` matches only the end of a field's digits instead, ignoring spaces, `+` and dashes, and only words written like phone numbers: `9623`, `47069623` and `+31 6 47069623` find "+31 6 47069623", `4706` and `+316` do not. Each field needs a pg_trgm index (`using gin (name gin_trgm_ops)`), a `digitsEnd` one on `regexp_replace(phone, '[^0-9]', '', 'g')`, or the API refuses the search. |
|
|
66
66
|
| `.position((r) => r.position, { within?, after? })` | The integer field holding the records' order by hand, 1 the first, which a list's **Reorder** button changes by dragging; with `within: (r) => r.invoice_id`, a filterable relation, each parent's records have an order of their own, sorted in its related section; with `after`, a record never ranks above the records it depends on. The field must be sortable. See [Reordering by hand](ui-config.md#reordering-by-hand) and [Ranked after what they depend on](ui-config.md#ranked-after-what-they-depend-on). |
|
|
67
67
|
| `.parent((r) => r.vm_id, 'update')` | The relation whose record each record belongs to, and the access on it (`'read'` or `'update'`) that creating, changing, deleting and undeleting a record needs, checked with the caller's own rules on that resource. With `'read'`, every read of its records also keeps to those whose parent the caller reads. The relation is one column, to a resource with a key of one field. See [Records that belong to another](access.md#records-that-belong-to-another). |
|
|
68
|
+
| `.openExisting((r) => [r.organization_id, r.member_key])` | A unique key of the table whose conflict on create opens the record already holding those values, such as a direct message with the same members. See [Opening an existing record](#opening-an-existing-record). |
|
|
68
69
|
| `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
|
|
69
70
|
| `.access({ ... })` | Rules per operation. See [Access](#access). |
|
|
70
71
|
| `.events((e, r) => [...])` | What changes of its records mean, such as `orders.created`, captured in the database for every write. See [Events](events.md). |
|
|
@@ -312,6 +313,32 @@ What a move leaves behind: webhooks already sent carried the old values to their
|
|
|
312
313
|
|
|
313
314
|
It protects the values from database dumps, backups, replicas, and readers of raw SQL and realtime changes, who see only ciphertext. It does not protect them from whoever holds the key or the app's environment, or can run code in the server. Someone who can write to the database can change a row's tenant or roles, or put back an older value of the same record and field, from a backup say, which still opens. The ciphertext shows whether a value is empty, its length and when it changed. A key seals at most about 2³² values safely, as each gets a random IV; rotating starts a new key's count.
|
|
314
315
|
|
|
316
|
+
## Opening an existing record
|
|
317
|
+
|
|
318
|
+
A resource whose records are unique by some of their values, such as a direct message by its members, can have a create that repeats those values open the record that holds them instead of failing. `.openExisting()` names the unique key, as its fields:
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
resource('direct_messages')
|
|
322
|
+
.table('direct_messages')
|
|
323
|
+
.fields({
|
|
324
|
+
id: f.integer().readOnly().dbDefault(),
|
|
325
|
+
organization_id: f.relation('organizations'),
|
|
326
|
+
member_ids: f.json(),
|
|
327
|
+
// generated always as (...) stored: the members sorted, without repeats
|
|
328
|
+
member_key: f.text().readOnly().dbDefault(),
|
|
329
|
+
})
|
|
330
|
+
.primaryKey((r) => r.id)
|
|
331
|
+
.tenant((r) => r.organization_id)
|
|
332
|
+
.openExisting((r) => [r.organization_id, r.member_key])
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
- The fields are exactly the columns of a unique index or constraint that covers every row, in any order, such as `unique (organization_id, member_key)`; a column the database generates counts. A create that conflicts on another unique key answers as without the option. Without such an index every create of the resource fails with a server error naming it, and [`protobase doctor`](cli.md#doctor) reports it.
|
|
336
|
+
- A create that conflicts on the key answers the [`409` `conflict`](api.md#errors) any unique violation answers, with `existing: { key }`, the key of the record holding those values, but only when the caller may read that record: in their tenant, inside their row filter and the parents they read, and passing a record-level read rule, as a `GET` of it checks. Otherwise the answer is the same plain `409`, so it never tells anyone that a record they cannot see exists. A soft-deleted record counts as one they cannot read.
|
|
337
|
+
- The create finds the record with `insert ... on conflict (...) do update ... where` a condition that only notes its key and is false, so nothing is updated and no update trigger runs, but the app's database role needs the update privilege on the table, as for any `on conflict do update`.
|
|
338
|
+
- Two creates of the same values at the same moment both end on one record: the second waits for the first and then answers with its key.
|
|
339
|
+
- The [create form](ui-config.md#opening-the-existing-record) then opens that record instead of saying it could not save.
|
|
340
|
+
- An encrypted or file field cannot be part of the key: the API stores those as values that never match another record's.
|
|
341
|
+
|
|
315
342
|
## Keys and relations
|
|
316
343
|
|
|
317
344
|
A key of several columns is a list, and a record's address joins its parts with a comma (`/stock/CHAIN-11,L`). A relation to such a resource names its columns, in the order of that key:
|
|
@@ -69,6 +69,7 @@ export const channelsView = view<typeof channels>('channels').nav({ recent: { or
|
|
|
69
69
|
| `filter` | Which records qualify, as AIP-160 text, exactly as `?filter=` on the list API. Use it to leave out finished or inactive records, or to keep them while they are recent: `status != "stopped" OR updated_at > now() - 7d`. |
|
|
70
70
|
| `orderBy` | AIP-132 order, as `?order_by=`; the list's `sort` when omitted. |
|
|
71
71
|
| `limit` | How many records, 1 to 20; 3 when omitted. |
|
|
72
|
+
| `marks` | The name of a hook in the UI config's `marks` that marks each record for the person reading, such as an unread conversation in bold with a count. See [Marks per reader](#marks-per-reader). Optional. |
|
|
72
73
|
|
|
73
74
|
The entry then works like this:
|
|
74
75
|
|
|
@@ -79,9 +80,38 @@ The entry then works like this:
|
|
|
79
80
|
|
|
80
81
|
The records come from the list API with the caller's token, so they follow the same access rules as the list page: row filters such as `.own` apply, and when the list is refused the group says it could not load. Any write to the resource made in the admin refreshes them, and so does returning to the window, unless a record has unsaved changes, so statuses changed elsewhere show up. A record read anew, by its record page or by project code refetching `useRecord`, refreshes its group too when it shows another status or title than the group's row.
|
|
81
82
|
|
|
83
|
+
### Marks per reader
|
|
84
|
+
|
|
85
|
+
A record can stand out for the person reading, such as a channel with messages they have not read: in bold, with a count at the end of its row. The group names a hook under `marks` in `protobase.ui.tsx`, and the sidebar calls it with the resource's name while it shows the records. It returns each record's mark by the record's key as its address carries it, or `undefined` while it loads, so it can read the API as the reader with `useList`, `useClient` or live updates, and its marks follow them:
|
|
86
|
+
|
|
87
|
+
```tsx
|
|
88
|
+
// protobase.views.ts
|
|
89
|
+
view<typeof channels>('channels').nav({ recent: { orderBy: 'name asc', limit: 20, marks: 'unread' } })
|
|
90
|
+
|
|
91
|
+
// protobase.ui.tsx
|
|
92
|
+
import { defineUi, useList } from '@protobase/ui'
|
|
93
|
+
|
|
94
|
+
const useUnreadMarks = () => {
|
|
95
|
+
// unread_channels: a resource of the project's own, one row per channel the reader has unread messages in
|
|
96
|
+
const unread = useList('unread_channels', { pageSize: 100 })
|
|
97
|
+
if (unread.isPending) return
|
|
98
|
+
return Object.fromEntries(unread.items.map((row) => [String(row.channel_id), { strong: true, count: Number(row.mentions), label: `${row.mentions} mentions` }]))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export default defineUi({ marks: { unread: useUnreadMarks } })
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
| Mark | Meaning |
|
|
105
|
+
| --- | --- |
|
|
106
|
+
| `strong` | The record's title shows bold and in the foreground colour, not muted. |
|
|
107
|
+
| `count` | A small badge at the end of the row, the pill of the notification bell's count; `99+` above 99, none at 0. |
|
|
108
|
+
| `label` | Added to the record's name for screen readers and its tooltip, such as "3 mentions". |
|
|
109
|
+
|
|
110
|
+
The records keep the group's order. A mark is presentation only: it is no field, filter or sort key, and the server computes nothing for it; what it counts comes from the requests the hook makes as the reader. Icon sidebars show no records, so no marks either. A group whose name no UI config registers, such as a plugin's that is turned off, shows its records unmarked. <gap>A marks hook that throws cannot be confined to its own group because an error boundary around a group's marks is not implemented, so it stops the sidebar as a throwing component would.</gap>
|
|
111
|
+
|
|
82
112
|
### Checks
|
|
83
113
|
|
|
84
|
-
`createAdmin` refuses to start when a group does not fit its resource: an unknown `status` field, `pulse` without a `status`, a tone outside the palette, a `limit` outside 1 to 20, or a `filter` or `orderBy` the list API would reject (unknown, non-filterable or non-sortable fields, bad syntax). `view.toModel(resourceModel)` runs the same checks.
|
|
114
|
+
`createAdmin` refuses to start when a group does not fit its resource: an unknown `status` field, `pulse` without a `status`, a tone outside the palette, a `limit` outside 1 to 20, `marks` without a name, or a `filter` or `orderBy` the list API would reject (unknown, non-filterable or non-sortable fields, bad syntax). `view.toModel(resourceModel)` runs the same checks.
|
|
85
115
|
|
|
86
116
|
`/meta` drops the group, and keeps the rest of `nav`, for a caller who cannot read a field it uses (its status when it has one, or a field in its filter or order), so it never names a hidden field.
|
|
87
117
|
|
|
@@ -85,6 +85,10 @@ The derived title names the record wherever `.title` would: the sidebar's [recen
|
|
|
85
85
|
|
|
86
86
|
<gap>An export of shown values and a chart grouped by a relation cannot name a record by its derived title because titling them per reader is not implemented.</gap>
|
|
87
87
|
|
|
88
|
+
### Sidebar marks per reader
|
|
89
|
+
|
|
90
|
+
`.nav({ recent: { marks: 'unread' } })` marks a sidebar group's records for the person reading by a hook under `marks` in `protobase.ui.tsx`, such as an unread channel in bold with a count of its mentions: `defineUi({ marks: { unread: useUnreadMarks } })`, where `useUnreadMarks(resource)` returns `{ strong?, count?, label? }` by record key. Like a derived title it is presentation only. See [Marks per reader](sidebar.md#marks-per-reader).
|
|
91
|
+
|
|
88
92
|
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.
|
|
89
93
|
|
|
90
94
|
Field hints:
|
|
@@ -577,6 +581,10 @@ view<typeof repairs>('repairs').create({ page: 'book-repair' })
|
|
|
577
581
|
|
|
578
582
|
[A create page of your own](../guides/create-page.md) builds one step by step.
|
|
579
583
|
|
|
584
|
+
### Opening the existing record
|
|
585
|
+
|
|
586
|
+
The create form at `/<resource>/new`, not a page of the app's own, can open the record a create repeats. When the resource has [`.openExisting()`](data-config.md#opening-an-existing-record), and the server answers the create form's save with that record's key, the form opens that record at its own address, as it opens a record it created, with no error. A start of a direct message with the same people opens the conversation there is. A user who may not read that record gets the usual "Could not save" toast, as for any record with the same unique value.
|
|
587
|
+
|
|
580
588
|
## Sign-in prompts
|
|
581
589
|
|
|
582
590
|
`.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.
|