Custom components
Layouts are data; a project’s React code lives in one module: protobase.ui.tsx at the project root, beside protobase.config.ts. It exports each custom component under the name its layouts declare, each from a file of its own, and default-exports defineUi({ actions }) from @protobase/ui for the rest, so the project depends on @protobase/ui, and on react for its JSX. This is the ERP example’s:
import { defineUi, type ActionContext } from '@protobase/ui'
// The custom components, each in a file of its own, exported by the name their layouts declare.export { OrdersPerDay } from './components/orders-per-day'
/** "Send reminder" on an invoice: opens a mail to the customer, and marks a draft invoice as sent. */const send = async ({ record, recordKey, etag, client }: ActionContext) => { const company = await client.get('companies', String(record!.company_id)) const subject = encodeURIComponent(`Invoice ${String(record!.number)}`) window.location.assign(`mailto:${String(company.record.email ?? '')}?subject=${subject}`) if (record!.status === 'draft') await client.update('invoices', recordKey!, { status: 'sent' }, etag ?? '*')}
export default defineUi({ actions: { send } })import { useSeries } from '@protobase/ui'
/** Bars for orders per day; the custom component behind `<OrdersPerDay>` in config/overview/page.tsx. */export const OrdersPerDay = ({ days }: { days: 7 | 30 | 90 }) => { const series = useSeries('orders', { field: 'created_at', range: `${days}d`, granularity: 'day' }) if (series.isPending) return <p className="text-muted-foreground">Loading</p> if (series.error) return <p className="text-danger-text">Could not load the orders</p> const points = series.data.points const highest = Math.max(1, ...points.map((point) => point.count)) const total = points.reduce((sum, point) => sum + point.count, 0) return ( <figure> <div className="flex h-24 items-end gap-0.5" role="img" aria-label={`${total} orders in ${days} days`}> {points.map((point) => ( <div key={point.bucket} title={`${point.bucket.slice(0, 10)}: ${point.count}`} className="flex-1 rounded-t-sm bg-primary/70" style={{ height: `${(point.count / highest) * 100}%` }} /> ))} </div> <figcaption className="mt-2 text-xs text-muted-foreground">{total.toLocaleString('en-IE')} orders</figcaption> </figure> )}protobase dev serves it with hot reload, and protobase build builds it as the plugin app in the bundle’s public/plugins/app/, beside the prebuilt admin app, which loads it when someone signs in. It is the only project code that reaches the browser, so keep secrets out of it. definePlugin types its default export as well as defineUi, which stays as its alias. The same exports can come from other plugins too, which the app loads at runtime and which keep working when the app moves to a newer release.
Components
Section titled “Components”Declare a component in the layout with component(name) from @protobase/layout, typing its props:
/** @jsxImportSource @protobase/layout */import { Card, component, page, Page } from '@protobase/layout'
export const OrdersPerDay = component<{ days: 7 | 30 | 90 }>('OrdersPerDay')
export const overview = page('overview', <Page title="Overview"><Card title="Orders per day"><OrdersPerDay days={30} /></Card></Page>)The element stays data, { type: 'OrdersPerDay', props: { days: 30 }, children: [], custom: true }, so its props follow the same rules as any block’s. The name must be PascalCase and not a built-in block’s.
protobase.ui.tsx exports the React component under the same name. It gets the props, and the rendered children when the element has any. Inside it:
- the hooks of
@protobase/ui(useList,useRecord,useSeries,useFacets,useHistogram,useClient, …) read the API with the user’s token, under the same access rules as everything else; useUpdateRecordrejects with an error thatisConflict(error)recognises when someone changed the record since it was read (a412), so the component can load it again;useLayoutRecord()gives the record around it in aRecordCardorCardRow({ model, record, key, etag, permissions }), andundefinedelsewhere.
A component that asks for a one-time code uses OtpInput from @protobase/ui, the field of the app’s own code pages: a box per digit drawn over one real input, so pasting a whole code into any box, the system’s code autofill from a mail or a text message, and the phone’s digit keyboard all work. It takes value and onChange, length (6 by default), invalid and disabled, and onComplete gets the code once its last digit is in, to check it at once. Ask for a code on a step of its own, before anything else.
A component that shows markdown, such as a chat message, uses Markdown from @protobase/ui, which markdown fields draw with: source is the markdown, in GitHub’s flavour with line breaks kept, shown in the theme’s styles. Raw HTML in it shows as text, links open in a new tab, and only links and images to web, mail and phone addresses or relative ones stay. className adds classes to its outer element, and inLink draws it as running text inside a link, such as a card, with its links and images as their text.
protobase build fails when the config declares a component that protobase.ui.tsx does not export, naming it; while you work, protobase dev draws a warning in its place. A component a plugin provides is declared with the plugin’s name, component('DraftOrders', { plugin: 'sales-tools' }), and the build does not look for it in protobase.ui.tsx. A component that throws while drawing shows a warning in its own place, not a blank app. The object form, defineUi({ components: { OrdersPerDay } }), still works, and a name given both ways must be the same component.
Fallbacks
Section titled “Fallbacks”A client that cannot draw a component, such as a native app without React or the admin app without the plugin that provides it, draws the component’s fallback in its place. Declare it with component(), as elements or [] to draw nothing:
export const SeatChart = component('SeatChart', { fallback: <Progress label="Seats" value="seats_used" max="plan.seats" /> })export const SystemMap = component('SystemMap', { fallback: <Image function="system-map" /> })export const Confetti = component('Confetti', { fallback: [] })A visual component, such as a map, falls back to the picture an API function draws of it; with no alt, a client that shows text only draws nothing in its place.
The admin app draws the fallback too when the component is missing or throws while drawing; protobase dev also shows the warning above it. Without a fallback, the warning stands in the component’s place, as above. A record section takes fallback in l.custom.
A component that reads records says which of its props name what it reads, so its read is in the page’s read plan with the other blocks’, starts with them as the page opens, and protobase doctor checks its indexes. The component then only draws: useComponentReads() from @protobase/ui gives it what each read holds, and it fetches nothing itself.
export const TaskBoard = component<{ resource: string; filter?: string; limit?: number }>('TaskBoard', { reads: { resource: 'resource', filter: 'filter', limit: 'limit' },})import { useComponentReads } from '@protobase/ui'
export const TaskBoard = () => { const { resource } = useComponentReads() if (!resource || resource.isPending) return null return <ul>{resource.rows.map((row) => <li key={String(row.id)}>{String(row.title)}</li>)}</ul>}reads takes resource, the one prop it needs, and filter, sort, fields and limit. fields is a prop holding a list of field names, or a list of props, each holding one field name or a list of them; the read asks for those fields and the key, and every field without fields. Without a limit, a read holds as many records as one read of the API does, 500. A list declares several reads, each named by the prop of its resource, which may not be calls, chosen or condition:
export const Board = component<{ cards: string; lanes: string; title: string; lane: string; select?: string }>('Board', { reads: [ { resource: 'cards', fields: ['title', 'lane'], select: 'select' }, { resource: 'lanes' }, ],})The build checks that each of those props names a resource and each field prop a field of it, and refuses a {{path}} in any of them, or in sort or limit: a read’s shape is fixed in the layout, and only its filter takes values from the records around it. select, in one read at most, is the prop naming the page parameter that holds the key of the record chosen among that read’s records, as a Table’s select does: the element’s children draw inside that record, and nothing while none is chosen.
From @protobase/ui |
|
|---|---|
useComponentReads() |
Each read the component declares, by the prop of its resource (resource, cards): { model, view, rows, isPending, error }. A read comes from the page’s plan; where the page plans none, such as in a record view, it is read here, its filter’s {{path}}s filled from the records around it. |
useComponentSelect() |
{ chosen, linkTo } for the component’s select: the chosen record’s key as the address holds it, and linkTo(key), the page with another chosen, for a RouteLink; undefined without select or outside a composed page. |
A component without reads is outside the plan, which lists it as such (page.reads.outside), and doctor does not check its reads.
Fields and resources in props
Section titled “Fields and resources in props”A prop that names a field is a field reference, fieldRef('plan.name') from @protobase/layout, read from the record around the element or the resource its resource prop names. The component gets the plain name ('plan.name'), and the names are checked when the server starts. A resource prop names a resource the way a block’s does.
<RecordCard resource="subscriptions"> <SeatsChart value={fieldRef('seats_used')} max={fieldRef('plan.seats')} /></RecordCard>/api/meta leaves a component out for a user who cannot read a field it references or see the resource it names, as it leaves out a Field, so a hidden name never reaches their browser. A field written as plain text is not checked or hidden this way.
List displays
Section titled “List displays”A list can show its rows with a component of the project’s own, declared in the view with d.custom. The list page loads the rows, with the filter, search and order of the address, and the component draws them: useListDisplay() gives them, RecordLink opens one. A board in columns of an enum field, with cards dragged between them, is built in as d.board, a month or week calendar of a date field as d.calendar, and a Gantt-style timeline of bars from a start to an end date as d.timeline; the board below draws its own.
// components/repair-board.tsx, exported from protobase.ui.tsx: export { RepairBoard } from './components/repair-board'import { RecordLink, useListDisplay } from '@protobase/ui'
export const RepairBoard = ({ by }: { by: string }) => { const list = useListDisplay() const columns = [...new Set(list.rows.map((row) => String(row.record[by])))] return ( <div className="grid grid-flow-col gap-3"> {columns.map((value) => ( <section key={value} aria-label={value}> {list.rows.filter((row) => String(row.record[by]) === value).map((row) => ( <RecordLink key={row.key} row={row}>{String(row.record.number)}</RecordLink> ))} </section> ))} </div> )}useListDisplay() |
|
|---|---|
resource |
The list’s resource. |
rows |
{ key, record, labels } per record: its key, the record as the list API gives it, and the name of the record each relation the display shows points at (labels.customer_id). |
total |
How many records match. |
loading, error |
While the first rows load, and why they did not. |
more, loadMore() |
Whether there are more rows, and loading the next page of them. |
A display never fetches its list, changes the address or keeps its own history: that is what keeps it at /<resource> with every other display, its filters and its links.
Record sections
Section titled “Record sections”A record page can hold a component of the project’s own beside its sections, declared in the view with l.custom. useLayoutRecord() gives it the record the page shows, as inside a RecordCard, so one component works in both. It reads more through the hooks (useList, useRecord), and acts through named actions or the API. Breadcrumbs, the heading, Save, the action rail with Edit and Delete, and the related records stay the page’s.
import { RecordLink, useLayoutRecord, useList } from '@protobase/ui'
export const CustomerRepairs = ({ limit }: { limit: number }) => { const { record } = useLayoutRecord()! const earlier = useList('repairs', { filter: `customer_id = ${record.customer_id} AND id != ${record.id}`, orderBy: 'booked_on desc', pageSize: limit }) return <ul>{earlier.items.map((repair) => <li key={String(repair.id)}><RecordLink recordKey={repair.id as number}>{String(repair.number)}</RecordLink></li>)}</ul>}A list that should stay live polls: useList('repairs', { refetchInterval: 5000 }) refetches every 5 seconds. It is TanStack Query’s refetchInterval, so it also takes false to stop, or a function of the query, and pauses while the tab is in the background.
Record section fallbacks
Section titled “Record section fallbacks”fallback gives what shows in the section’s place, its title included, where the component cannot be drawn, such as on a watch: any item of the main column, conversations and other custom components included, sidebar maps and sidebar custom components in the sidebar, or [] for nothing. Each item shows by its when and is checked and left out per user as it is elsewhere on the page, so /api/meta sends the fallback without a thread the user cannot read or a composer that cannot create their messages, as fallbacks of composed pages. l.sidebar summary card because merging a fallback’s fields into the page’s one summary is not implemented.
l.custom(CustomerRepairs, { title: 'Earlier repairs', props: { limit: 5 }, fallback: [l.section('Customer', [r.customer_id])] })l.custom(RepairChat, { fallback: [ l.thread('Chat', { resource: 'repair_messages', field: 'repair_id', sender: 'author_id', time: 'sent_at', text: 'body' }), l.composer({ resource: 'repair_messages', field: 'repair_id', text: 'body' }), ],})Full-area record pages
Section titled “Full-area record pages”A view can make a component the whole record page with .record({ component }). It gets the record from useLayoutRecord(), as a record section does, and fills the area beside the sidebar and under the top bar, where the page does not scroll: a list in it scrolls in a box of its own with min-h-0 flex-1 overflow-y-auto, and what follows the list stays at the bottom. It links to the record’s standard page, which keeps the form, the related records, Edit and Delete:
// components/channel-chat.tsx, exported from protobase.ui.tsx: export { ChannelChat } from './components/channel-chat'import { AppLink, useLayoutRecord } from '@protobase/ui'
export const ChannelChat = () => { const { model, key, record } = useLayoutRecord()! return ( <section className="flex min-h-0 flex-col"> <header className="flex justify-between border-b px-4 py-2"> {String(record.name)} <AppLink to={{ kind: 'record', resource: model.name, key, standard: true }}>Details</AppLink> </header> <ol className="min-h-0 flex-1 overflow-y-auto">{/* the messages */}</ol> {/* the composer */} </section> )}Focus pages
Section titled “Focus pages”A focus page knows nothing of what it shows: whatever draws the surface fills the page’s parts from anywhere inside it, and the framework adds the record’s Save and actions. All of it comes from @protobase/ui, for a field type’s editor, a .record({ component, focus: true }) component, or a page of your own that draws FocusPage itself:
| Part | |
|---|---|
<FocusPage label> |
The page: bar, notice, surface and panels. It takes the content area and stops the page scrolling. .record(...) draws it for you. |
<FocusSlot zone> |
Draws its children in the bar: mode says what shows and picks it, controls holds tools for the surface, state says how the work stands, secondary and primary hold the page’s own buttons. A primary of yours moves Save to secondary; a state of yours replaces the framework’s. fallback shows it only while nothing else fills the zone. |
<FocusActions actions> |
Adds actions, an action rail’s { name, icon, onRun, blocked, tone, render }: inBar shows at most two by name while there is room, and the rest go behind “…”. |
<FocusNotice level actions> |
One strip under the bar, which pushes the surface down. One shows at a time, in the order refused, conflict, draft, info, and the next returns as one clears. |
<FocusPanel side title onClose footer takesFocus> |
A panel beside the surface, end by default, which the surface makes room for; with too little room it lies over the surface’s edge, and below md it covers the screen. Its content scrolls on its own. takesFocus is for a panel a button opens: it takes the keyboard and hands it back. |
useFocusPage() |
{ size }, how much room the bar has, by its own width: wide, medium, narrow or compact. |
useFocusZoneFilled(zone) |
Whether something fills a zone. |
useFocusRecord() |
On a record’s focus page: the record, its draft (value, change, dirty, saving, refused), save(), which resolves to whether it saved, discard(), readOnly and mayUpdate. |
<SearchPicker groups onPick> |
A searchable list to pick from, for a panel or a dialog: { title, items } groups of { id, title, description, keywords, icon }, with the arrow keys and Enter. |
useCreateForm({ resource, onCreated }), <InPlaceForm form fields submit> |
A create form that stays where it is, so an action is done beside what it acts on: the view’s fields you name, its failure and its submit button. onCreated says what comes next. |
// A field type's editor that fills the surface: it owns its state, and hands the framework the partsimport { Button, FocusActions, FocusPanel, FocusSlot, SearchPicker, type FieldWidgetEditorProps } from '@protobase/ui'import { Eraser } from 'lucide-react'import { useState } from 'react'
export const PinBoard = ({ value, onChange }: FieldWidgetEditorProps<string[]>) => { const pins = value ?? [] const [adding, setAdding] = useState(false) return ( <div className="h-full p-6"> <FocusSlot zone="controls"><Button onClick={() => setAdding(true)}>Add pin</Button></FocusSlot> <FocusActions actions={[{ name: 'Clear the board', icon: Eraser, onRun: () => onChange([]) }]} /> {pins.map((pin) => <p key={pin}>{pin}</p>)} {adding && ( <FocusPanel title="Add a pin" onClose={() => setAdding(false)} takesFocus> <SearchPicker autoFocus groups={[{ title: 'Places', items: [{ id: 'lisbon', title: 'Lisbon' }] }]} onPick={(item) => onChange([...pins, item.id])} /> </FocusPanel> )} </div> )}Record cards
Section titled “Record cards”A cards display can draw each card’s content with a component, declared in the view with d.cards(fields, { card }). The card stays a link to the record, with the display’s frame; the component draws what is inside it from row, the record with the fields the display names, so name every field the card shows:
export const RepairCard = component('RepairCard')// in .list((r, d) => ...):d.cards({ title: r.bike, subtitle: r.customer_id, badge: r.status, meta: [r.number, r.estimate] }, { card: RepairCard })// components/repair-card.tsx, exported from protobase.ui.tsx: export { RepairCard } from './components/repair-card'import type { RecordCardProps } from '@protobase/ui'
export const RepairCard = ({ row }: RecordCardProps) => ( <span className="flex flex-col gap-1"> <span className="font-medium">{String(row.record.bike)}</span> <span className="text-muted-foreground">{row.labels.customer_id}</span> </span>)row is { key, record, labels }, as a list display’s rows are. A card is inside a link, so it holds no buttons or links of its own. Without the component, from a plugin that is off for instance, and when it throws, each card is the built-in one: the title, subtitle, badge and meta fields. A custom record card builds one step by step.
Field types
Section titled “Field types”A field type shows and edits a field everywhere the app shows it: a view picks one with r.status.widget('steps'), and protobase.ui.tsx registers it under that name in fields:
export default definePlugin({ fields: { steps: { of: ['enum'], display: StepsDisplay, editor: StepsEditor } } })Plugins describes the contract, and Adding a field type builds one.
Addresses
Section titled “Addresses”Every place in the app has an address, and a component never writes a path or reads the query string itself, so the address can change shape in one place. useAppAddress() from @protobase/ui gives the current one as values, with the list’s defaults filled in, and moves the app:
const { address, set, listTo, go, href } = useAppAddress()// address: { kind: 'list', resource: 'repairs', display: 'board', filter: 'status = "ready"', orderBy: 'booked_on desc', filterLayout: 'bar' }set({ display: 'cards' }) // changes this list in placelistTo({ display: 'cards' }) // this list changed, as an AppLink's `to`go({ kind: 'record', resource: 'repairs', key: 42 }) // moves to another addresshref({ kind: 'create', resource: 'repairs' }) // for an <a href>, with the base pathRecordLink (a record, from a display’s row or a recordKey) and AppLink (to any address) are links written the same way. Code outside React builds and reads addresses with appPath(address, basePath?) and readAppPath(path, pages) from @protobase/schema, whose words (filter, order_by, display) are in addressWords.
Create pages
Section titled “Create pages”A view whose records a page of the app’s own creates names it with .create({ page }), and /<resource>/new shows that page. The address keeps its values: a component on the page reads them from useAppAddress(), and writes its answers back with go(..., { replace: true }), so a reload, a link, or a round trip through another site, such as an install page that sends the user back, keeps them:
const { address, go } = useAppAddress()const values = address?.kind === 'create' ? (address.values ?? {}) : {}const answer = (patch: Record<string, string>) => go({ kind: 'create', resource: 'repairs', values: { ...values, ...patch } }, { replace: true })The same page at its own address, /<page>, starts without values.
Form parts
Section titled “Form parts”A component that asks for input looks like the app’s own forms when it is built from the parts they use, all from @protobase/ui:
Form |
The create form’s frame: submit, the button’s label; onSubmit; saving and disabled for the button; onCancel, which adds Cancel; and error with errorTitle, a failure that belongs to no field, where an ApiError shows its messages. With title (and eyebrow, the line above it) the form is the whole page, its buttons beside the heading, as the create form is. Without, it sits in a composed page under the page’s heading, its buttons after the sections. |
Section |
A titled part of a form or page: title, help, actions. Sections in a Form have a line between them. |
Field |
A label over its input: label, required, help, example, error, name for the browser’s autofill, and wide for both columns of a grid of two. An Input, Textarea or Select inside takes its label, name, help and error from it, and whether it is invalid or required; another control spreads useFieldControl() on its element. |
Input, Textarea, Select |
A text box, with leading and trailing content and invalid; a box of several lines that grows with its text; a native select with invalid. |
Choices |
One of a few options, each a card in a row of its own with a description: name, label, options, value, onChange. A disabled option shows and cannot be chosen. |
RecordPicker |
Records of another resource, picked as the create form picks a relation: type to narrow them by their search fields or title, scroll for more, or use the keyboard. resource names the resource, whose model it reads from the app; value is the chosen record’s key as text and onChange gets the new one. With multiple, value and onChange hold several keys, such as the objectives a task serves through a join resource: each shows as a token that can be taken off. |
Segmented, MenuSelect |
A switch between a few short options in a row (size, iconOnly), and the same options in a menu. |
Button, buttonClass |
A button (variant primary, secondary, ghost or danger, size sm, md or icon, a square for an icon alone, loading, and busyLabel, what it says while loading, as a status a screen reader announces), and its classes for a link that looks like one. |
MenuSurface, usePopoverMenu, menuItemClass |
A menu of your own that looks and behaves like the app’s: usePopoverMenu() gives open, setOpen, the button and menu refs and place, the menu’s fixed top, right and maxWidth beside its button (undefined for its first, hidden frame), and closes it on a click outside, Escape, a scroll or a resize; MenuSurface draws the menu beside its button on a desktop and in a sheet from the bottom of a phone; menuItemClass styles each row as the app’s menu items. |
useToast |
Brief notices at the bottom of the page, such as “Text copied”: show({ state, title, description, action }) returns an id for update and dismiss; state is success, info, warning, error or loading, which stays until updated. |
Dialog, ResponsiveDialog |
A modal with a title, description, actions and a body, which Escape and a click outside close with onClose; the responsive one becomes a sheet from the bottom of a phone, which follows a finger dragging it down by its header, or by its content once that is scrolled to its top, and closes when flung or let go past a third of its height. |
// components/book-repair.tsx, exported from protobase.ui.tsximport { Choices, Field, Form, Input, Section } from '@protobase/ui'
export const BookRepair = () => { // values and answer as above return ( <Form submit="Book repair" disabled={!values.bike || !values.kind} onSubmit={() => void book(values)}> <Section title="The bike"> <div className="flex flex-col gap-5"> <Field label="Bike" required> <Input value={values.bike ?? ''} onChange={(event) => answer({ bike: event.target.value })} /> </Field> <Field label="What it needs" required> <Choices name="kind" label="What it needs" options={kinds} value={values.kind} onChange={(kind) => answer({ kind })} /> </Field> </div> </Section> </Form> )}Image carousel
Section titled “Image carousel”Carousel from @protobase/ui steps through images the way a card steps through a record’s photos, outside a card too: a row that snaps image by image, swiped on a touch screen or moved by arrows that show on hover, with dots marking the image in view. One image shows without arrows or dots.
images |
The images in order: { src, alt }, a link with what it shows, or a file field’s value as records carry it, with an optional alt. A file’s smallest variant that is sharp enough is drawn; a missing file or one that is no raster image is left out. |
label |
What the images are, read out with the carousel. |
fit |
cover, the default, fills the frame and crops what overflows it; contain shows each image whole. |
swipe |
Off, a swipe scrolls what the carousel sits in, such as a row that scrolls sideways, and the arrows always show on a touch screen. On by default. |
className |
The frame’s classes, such as its aspect ratio, border and rounding; it has none of its own. |
import { Carousel } from '@protobase/ui'
export const PresetShots = () => ( <Carousel label="Bike repairs" fit="contain" className="aspect-[8/5] rounded-lg border border-border" images={[ { src: '/shots/repairs-board.png', alt: 'The repairs board' }, { src: '/shots/repair.png', alt: 'A repair' }, ]} />)Chat parts
Section titled “Chat parts”A chat between people, such as a team’s channels, is built from the parts the assistant uses, all from @protobase/ui:
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. |
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. |
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. |
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. onDraft gets the box’s text each time it changes, such as for typing. |
MentionBox, MentionedText |
The text box with @ mentions that the composer and comments 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 comments’ formatting: bold, italic, strikethrough, code, code blocks, lists, quotes and web addresses as links, each @name of its mentions picked out. Until its renderer has loaded, it shows the text as typed, its lines and paragraphs taking the same room; MentionedText.useLoaded() is true once the renderer has loaded or failed to, for a page that shows its messages only then, so none changes as it formats. |
The messages’ author comes from the server: give the resource .author(), and each create stores the signed-in user’s id, never a value the client sends.
import { Fragment } from 'react'import { ChatDivider, ChatMessage, ChatThread, Composer, MentionedText, chatDayLabel, sameChatDay } from '@protobase/ui'
export const Channel = ({ messages, sent, members, onSend, onLoadEarlier }: ChannelProps) => ( <div className="flex h-full flex-col"> <ChatThread length={messages.length} followKey={sent} onLoadEarlier={onLoadEarlier}> {messages.map((message, index) => { const previous = messages[index - 1] const newDay = !previous || !sameChatDay(previous.sent_at, message.sent_at) return ( <Fragment key={message.id}> {newDay && <ChatDivider label={chatDayLabel(message.sent_at)} />} <ChatMessage author={message.author} time={message.sent_at} continued={!newDay && previous?.author.id === message.author.id}> <MentionedText text={message.body} mentions={message.mentions} /> </ChatMessage> </Fragment> ) })} </ChatThread> <div className="p-3"> <Composer placeholder="Message #general" onSend={onSend} searchPeople={members} /> </div> </div>)Members’ names
Section titled “Members’ names”The author is a user id, and useMembers() from @protobase/ui turns it into a name: the members of the organization the signed-in person works in, { id, name, image? } by name, with id the user id that .author() stores and that onSend’s mentions hold. Every member reads it, owners, admins and members alike; it holds no email addresses. It is a TanStack Query result (data, isLoading, error) with member(id), which finds one and, for an id it does not know, such as a newcomer’s first message, reads the list again once it is 10 seconds old; it is also read again when the window regains focus and the list is 30 seconds old. It needs organizations: without them, error says so. In an app with status, each member carries their status too, read again every 15 seconds.
import { ChatMessage, Composer, MentionedText, useMembers } from '@protobase/ui'
export const Message = ({ message }: { message: { author_id: string; body: string; mentions: string[]; sent_at: string } }) => { const { member } = useMembers() return ( <ChatMessage author={{ id: message.author_id, name: member(message.author_id)?.name ?? '' }} time={message.sent_at}> <MentionedText text={message.body} mentions={message.mentions.map((id) => ({ name: member(id)?.name }))} /> </ChatMessage> )}
export const ChannelComposer = ({ onSend }: { onSend: (text: string, mentions: string[]) => void }) => { const { data: members = [] } = useMembers() const searchPeople = async (query: string) => members.filter((person) => person.name.toLowerCase().includes(query.toLowerCase())).slice(0, 8) return <Composer onSend={onSend} searchPeople={searchPeople} />}searchPeople filters the list in the browser and shows at most 8, as comments’ mentions do. 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.
Typing
Section titled “Typing”In an app with the realtime relay, a chat of your own shows who types and says when its reader types, over the same socket the admin app’s pages use, on the record’s channel, <resource>/<key>:
TypingLine |
The line above the box saying who else types on channel, by the names useMembers() gives; it keeps its height while nobody does, so the box does not move. |
useTypers(channel) |
The user ids of the others who type on the channel now, outside threads, each until six seconds after the last they sent; empty without the relay or while it is down. |
useTypingSender(channel) |
onText, to call with the box’s text as it changes, and onSent, once a message went: it sends typing events at most every three seconds, and that the reader stopped when they empty the box, send or leave. Nothing goes before the channel is joined. |
useViewChannel(channel) |
Says the page shows the channel while it is drawn, so only its notices read the page again, and joins it when the connect ticket did not list it, such as a conversation the reader joined since. |
import { Composer, TypingLine, useTypingSender, useViewChannel } from '@protobase/ui'
export const RoomComposer = ({ room, onSend }: { room: number; onSend: (text: string, mentions: string[]) => Promise<boolean> }) => { const channel = `rooms/${room}` useViewChannel(channel) const typing = useTypingSender(channel) const send = async (text: string, mentions: string[]) => { const sent = await onSend(text, mentions) if (sent) typing.onSent() return sent } return ( <> <TypingLine channel={channel} /> <Composer onSend={send} onDraft={typing.onText} /> </> )}The relay must allow the typing event on the channel resource, as for a conversation page. For anything else, such as an event of your own, useClient().relay is the same socket (see From code).
Signed-in user
Section titled “Signed-in user”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.
Components in the chat
Section titled “Components in the chat”The same components draw the assistant’s 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.
Action handlers
Section titled “Action handlers”A named action declared with a.action(name, ...) in a view has no built-in behaviour: its button runs actions[name] from protobase.ui.tsx. The handler gets:
resource |
The action’s resource. |
record, recordKey, etag |
The record around the button, when there is one. |
client |
The API client (@protobase/client) of the API that serves the resource, with the user’s token: the app’s own, or a source’s for a remote resource, whose functions invoke then calls. |
navigate(to) |
Moves the app to an address, such as { kind: 'record', resource: 'orders', key: 42 }. |
values |
The answers to the action’s inputs, by input name, when it has some. |
When the handler resolves, everything shown of the resource reloads and a toast says it is done; when it throws, the toast shows the error, or for an action with inputs its dialog does, under the inputs an ActionInputError names. Without a handler the button is disabled. Actions with built-in behaviour (a.update, a.remove, a.link) do not need one.
Shell slots
Section titled “Shell slots”shell adds components to the shell around every page: actions at the end of the top bar, and rightPanel beside the page, such as a SidePanel from @protobase/ui (see the primitives). They take no props and use the same hooks as custom components:
export default defineUi({ shell: { actions: NotesButton, rightPanel: Notes } })When the app has an assistant, its button follows the project’s actions and its dock the project’s panel.
bell replaces the notification bell of the top bar with your own, drawn where it would be, and takes no props either; the bell’s slot lists the hooks it reads the user’s notifications with. With a bell from a plugin and one from the project, the project’s shows.
logo replaces Protobase’s logo at the top of the sidebar with the app’s own. It gets compact, true when the sidebar shows only icons, so it draws a mark alone, workspace, the name of the user’s organization that Protobase’s logo shows under it, appName, the app’s name, which Protobase’s logo shows beside its mark, and appIcon, the path of the project’s own icon when it has one (ShellLogoProps). Its colors follow the theme, and a dark: class gives dark its own. When it throws, Protobase’s logo shows instead. The tab’s icon is the favicon.
import { defineUi, type ShellLogoProps } from '@protobase/ui'
const Logo = ({ compact }: ShellLogoProps) => ( <div className="flex items-center gap-2.5"> <img src="https://cdn.example.com/rijnland-mark.svg" alt="Rijnland Industrial" className="size-7" /> {!compact && <span className="font-semibold">Rijnland Industrial</span>} </div>)
export default defineUi({ shell: { logo: Logo } })Without protobase dev
Section titled “Without protobase dev”<App ui={...} /> from @protobase/ui takes the same object, for an app that mounts the admin itself, and so do stories. Outside <App>, <ApiProvider baseUrl="/api/v1" token={...}> gives components the API client and the query cache the hooks read through, as <App> does.
Below 1.0, a project built before 0.12 had its protobase.ui.tsx built into the admin app; Moving onto the plugin build says what changes.