Client
// src/routes/rooms/$room.tsx
import { id, page, useQuery } from "canica/client"
import { Conversation, ErrorState, Loading, Message, MessageInput, PageHeader } from "canica/ui"
import { messageBody } from "../../../shared/fields.ts"
export default page({
params: { room: id("rooms") }, // validated; a bad URL shows 404.tsx
view: ({ params }) => {
const messages = useQuery("messages", { room: params.room })
// Chat thread composer. `send` takes { room, body }: body is the message, room is fixed.
const composer = <MessageInput mutation="send" arg="body" args={{ room: params.room }} field={messageBody} label="Message" hideLabel />
return (
<>
<PageHeader title="Room" />
{messages.match({
loading: () => <Loading shape="list" />,
failure: (e) => <ErrorState error={e} />,
success: (list) => (
<Conversation empty="No messages yet." composer={composer}>
{list.map((m) => <Message key={m.id} author={m.author} at={m.createdAt}>{m.body}</Message>)}
</Conversation>
),
})}
</>
)
},
})
useQuery(name, args): live, fully typed (value and errors)..match({ loading, failure, success })(hooks go in a component rendered from a case, never in the case); infailure,<ErrorState error={e} states={{ NotFound: { title, description, action } }} />designs each of your errors (others get a readable default). Types for props:QueryValue<"rooms">[number],QueryError<…>,MutationArgs<…>.useMutation(name):(args) => Promise<{ _tag: "Success" | "Failure" }>, resolves after live queries updated;.waiting,.status→<ActionStatus status={rename.status} success="Saved" />for feedback outside a form.useAction(name)is the same for actions (slower: show.waiting); what it saved shows through live queries. A mutation whose reply was lost (the socket dropped) is resent once with the same id and runs at most once; if that fails too it ends withConnectionLost("it may have been saved"), never "try again".FormFieldgives its control an id itself: do not setidon the input.- Pages show data; forms live in modals.
useFormand<Form>go only in a modal's own component (the function passed tomodal()(); lintform-in-modal). A create form is a button on the page (thePageHeaderaction, witharia-haspopup="dialog") that opens a modal; an edit form is in the item's details modal. The only inputs on a page for entering text are<SearchInput>for search/filter and<MessageInput>only for chat or comment threads. Anything that creates or edits an entity (todos, notes, habits, items, links…) opens a modal, even a one-field "quick add" or "quick capture". Use a prominent "New …" button and autofocus the modal's first field. Existing controls that act at once (Checkbox,CheckButton,FileInput) may stay on the page.// src/components/new-room.tsx export const NewRoom = modal<Id<"rooms">>()(() => { const close = NewRoom.useClose() const create = useMutation("createRoom") const form = useForm("create room", { name: roomName }, (v) => create(v), { onSuccess: close }) // closes with the id return ( <> <ModalTitle>New room</ModalTitle> <Form form={form} describeError={(e) => (e._tag === "NameTaken" ? `“${e.name}” is taken.` : undefined)}> <FormField form={form} name="name" label="Name"><Input name="name" autoComplete="off" autoFocus /></FormField> <ModalActions><Button type="button" variant="outline" onClick={close.cancel}>Cancel</Button><SubmitButton form={form}>Create</SubmitButton></ModalActions> </Form> </> ) }) // the page (const goToRoom = useNavigate("/rooms/$room")): <PageHeader title="Rooms" actions={<Button aria-haspopup="dialog" onClick={async () => { const r = await NewRoom.open() if (r._tag === "Done") goToRoom({ room: r.value }) }}>New room</Button>} /> useForm(name, fields, onSubmit, { onSuccess }): native inputs (name=,defaultValue=), validated with the fields.<Form>+<FormField name label>+<SubmitButton>;describeErrorwords your typed errors. Hooks go at the top of the component, never insidematchcallbacks: an edit form'suseFormtakes the id from props or params, and its<Form key={todo.updatedAt}>withdefaultValues goes insidesuccess(fields show the latest values). Choices:RadioGroup/Checkboxwithname(values are strings:value={String(n)}; anumber()field parses them back); several checkboxes with onename→ anarray(…)field; selects areNativeSelect+NativeSelectOption(scenes pick withchoose); a variable number of values (poll options) is<RepeatInput name="options" label="Option" min={2} max={8} />with anarray(…)field.<MessageInput>is only for conversation: sending messages to a chat feed or comments to a thread. Never use it to create todos, notes, habits, items or other entities, even when there is only one text field. Open the entity's "New …" modal instead.canica/form-in-modalalso flags a composer whose mutation is used by a modal'suseForm, including when the modal is in another file.<MessageInput mutation="send" arg="body" args={{ room }} field={messageBody} label="Message" hideLabel />: the mutation by name, the arg that is the text (a string; the types check it), its other args (fixed), andfield, the arg's field fromshared/(its messages show here; its.max(n)shows a counter near the limit). Enter sends, Shift+Enter is a new line (phones: Enter is a new line, the button sends); it trims and refuses empty text, clears and keeps focus on success, keeps the text and words the error on failure (describeErrorfor your typed errors).onSend={(text) => post({ text })}instead ofmutation/argto call it yourself (return the result).submit="Reply"renames the button. Scenes:type(role("textbox", { name: "Message" }), "hi{Enter}").<SearchInput param="q" label="Search todos" />filters the page. The text lives in the URL (/?q=milk, so it can be shared and reloaded): the page declares it,page({ search: { q: string().trim().optional() }, view: ({ search }) => … }), and passessearch.qto its query (filter on the server). Search params are optional or have a default; a missing or invalid one is absent. Typing updates the URL after a pause (no history entry per letter; the page re-renders, it does not remount); ✕ and Escape clear it; it submits nothing. Scenes:visit("/?q=milk"),type(role("searchbox", { name: "Search todos" }), "milk").- There is no component state: data comes from queries, input lives in forms (in modals), steps in modals. The URL is
the route, its params and the search params the page declares. No
useState/useEffect/fetch/Date.now()insrc/(lint). Only whenserver/index.tsalready saysapp({ ui: "own" })(the owner's choice for an app with its own components, never a way around lint) maysrc/use React's hooks,createPortal, timers and plain elements with any classes;fetch, storage,Date.now()and data outside canica/client stay out. - Navigation:
<Link to="/rooms/$room" params={{ room }}>,useNavigate("/rooms/$room"), andredirect("/rooms/$room", { room })returned instead of JSX. - Modals are awaited components.
confirm/promptfromcanica/ui:const r = await confirm({ title, confirm: "Delete" }),prompt({ title, label, field }). Your own:modal<Result>()(Component); its props are whatopentakes:
Everything that closes the modal lives in its own component:export const TodoDetails = modal<"closed" | "deleted">()(({ id }: { id: Id<"todos"> }) => { const close = TodoDetails.useClose() // close("deleted"), close.cancel() const todo = useQuery("todo", { id }) return <><ModalTitle>Todo</ModalTitle>…<ModalActions><Button onClick={() => close("closed")}>Close</Button></ModalActions></> }) const r = await TodoDetails.open({ id }) // r.match({ done, cancelled }); `modal({ alert: true })` for a confirmationuseClose()fails in a child component, and lint rejects passingclosedown. Pass ids and read live data inside withuseQuery. Give the opening buttonaria-haspopup="dialog". In scenes aconfirm()isrole("alertdialog"), other modalsrole("dialog"). Open modals are a stack of independent modals: only the last opened shows (the others wait hidden, typed input kept), and closing one (its button, Escape, Back, or its own code) closes only that one, gives its caller the result and shows the one under it again. On phones a modal is a bottom sheet (a form or long content opens nearly full height, a confirm at its own height; its title stays at the top, dragging the top down closes it) that stays above the on-screen keyboard with the focused field in view (its content scrolls inside): do not position, resize or scroll modals yourself, for the keyboard or otherwise. A flow of steps that belong together is one modal with steps, not a modal that opens another; the first step's form keeps its values:export const NewRoom = modal<Id<"rooms">>()(() => { const close = NewRoom.useClose() const create = useMutation("createRoom") const details = useForm("room name", { name: string().trim().min(1) }, (v) => v) // step 1 keeps its values const name = details.status._tag === "Success" ? details.status.value.name : undefined const finish = useForm("create room", {}, () => create({ name: name! }), { onSuccess: close }) // step 2 if (name === undefined) return <Form form={details}>…<SubmitButton form={details}>Next</SubmitButton></Form> return <Form form={finish}><ModalText>Create {name}?</ModalText><SubmitButton form={finish}>Create</SubmitButton></Form> }) - Time:
useToday()("YYYY-MM-DD", pass it to queries that need "today"),useNow("minute"),useRelativeFormatter()→(ms) => "5 minutes ago". - Who is using the app:
useAuth()→{ userId, isSignedIn, profile }(e.g.m.author === auth.userIdfor "mine").<UserMenu />in the header: the account, sign out, connect an agent. See Access.
UI (canica/ui, shadcn API: https://ui.shadcn.com/docs/components; icons from canica/icons). Lint enforces
components over raw HTML, theme tokens over colors, no restyling of components (wrap text in a <span> instead).
Page patterns: AppHeader (in __root.tsx; its size is every page's width), PageHeader title description actions,
Section, List + Item/ItemContent/ItemTitle/ItemDescription/ItemActions, Stats/Stat, ResultBar,
CheckButton, ChoiceRow (share/highlight draw the result bar in the same row: vote and results
in one place), Conversation/Message (with a MessageInput composer), SearchInput, CopyButton, EmptyBlock,
Loading, ErrorState, ActionStatus, ModalTitle/ModalText/ModalActions, FileInput/Thumbnail (see Files).
Design rules reviewers check:
- Content first: the page shows data; create forms go in a modal opened from the
PageHeaderaction (and from the empty state'saction). - Lists use
List+Itemwith real facts (counts, status, last activity). To make a row open something, put a<Link>on its title; keep buttons and menus out of links. - Every state designed:
Loadingshaped like the content,EmptyBlockwith the next action, typed errors worded. - Every action gives feedback; destructive ones ask with
confirm. One primary button per view. - Numbers in
Stat/ResultBarare already aligned; elsewhere wrap them in<span className="tabular-nums">. - Works at 390px; long text truncates on purpose; a detail page's title is the object's name.