Live
Shared counters, a public feed and private notes: what live queries do, side by side.
15 files, 729 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in examples/live.
Files
server/index.ts153server/seed.ts21shared/fields.ts6src/main.tsx6src/routes/__root.tsx24src/routes/index.tsx33src/routes/me.tsx57src/components/counter-card.tsx37src/components/feed.tsx91src/components/notes.tsx111src/components/whoami.tsx33src/styles.css4src/theme.css60server/index.test.ts39src/app.test.tsx54
server/index.ts153 lines
import {
boolean,
count,
desc,
eq,
id,
lt,
mutation,
NotFound,
number,
query,
requireSignIn,
schema,
sql,
string,
table,
userId,
Viewer,
type Id,
} from "canica/server"
import { counterName, messageText, noteText } from "../shared/fields.ts"
/**
* A lab for live queries. A query re-runs only when a write touches what it read: open the page in two
* windows and the dev tools (⚡ bottom right) to watch it happen. Reads filtered with `eq` are fine-grained
* (`notes.owner="…"`); reads without one depend on the whole table (`messages`).
*/
export const { app, Db, tables } = schema({
// Shared by everyone: one row per counter.
counters: table({ name: counterName, value: number().int() }).unique("by_name", ["name"]),
// Public feed.
messages: table({ author: userId(), authorName: string(), text: messageText }).index("by_author", ["author"]),
// Private: only the owner sees them, and only when signed in.
notes: table({ owner: userId(), text: noteText, done: boolean().default(false) }).index("by_owner", ["owner"]),
})
const { counters, messages, notes } = tables
const displayName = (viewer: { isSignedIn: boolean; profile?: { name?: string } }) =>
viewer.isSignedIn ? (viewer.profile?.name ?? "Someone") : "A guest"
/** A note the viewer owns. Someone else's note looks like it does not exist. */
function* ownNote(note: Id<"notes">) {
const me = yield* requireSignIn
const db = yield* Db
const row = yield* db.get(notes, note)
if (row.owner !== me.userId) return yield* new NotFound({ table: "notes", id: note })
return row
}
export default app({
name: "Live lab",
icon: "radio",
// Public: this lab shows guests and accounts side by side (a guest's feed posts, account-only notes with
// requireSignIn, the /me page behind page({ auth: "signedIn" }), the guest's data kept on signing in).
access: "public",
queries: {
/** Reads one counter by name: re-runs only when that counter changes. */
counter: query({ name: counterName }, function* ({ name }) {
const db = yield* Db
const [row] = yield* db.select().from(counters).where(eq(counters.name, name)).limit(1)
return row?.value ?? 0
}),
/** Reads the last 20 messages: re-runs when any message is added, changed or deleted. */
feed: query(function* () {
const db = yield* Db
const viewer = yield* Viewer
const rows = yield* db.select().from(messages).orderBy(desc(messages.createdAt)).limit(20)
return rows.reverse().map((m) => ({ id: m.id, author: m.authorName, text: m.text, at: m.createdAt, mine: m.author === viewer.userId }))
}),
/** An aggregate (GROUP BY in the database): re-runs on any message change. */
feedStats: query(function* () {
const db = yield* Db
const byAuthor = yield* db
.select({ name: messages.authorName, n: count() })
.from(messages)
.groupBy(messages.authorName)
.orderBy(desc(count()))
const total = byAuthor.reduce((sum, a) => sum + a.n, 0)
return { total, byAuthor }
}),
/** Private and account-only: guests get Unauthenticated. Re-runs only for this user's notes. */
myNotes: query(function* () {
const me = yield* requireSignIn
const db = yield* Db
return yield* db.select().from(notes).where(eq(notes.owner, me.userId)).orderBy(notes.createdAt)
}),
/** What the server sees for this connection. Changes when you sign in or out (the queries re-run). */
whoami: query(function* () {
const viewer = yield* Viewer
return { userId: viewer.userId, isSignedIn: viewer.isSignedIn, name: viewer.profile?.name ?? null, email: viewer.profile?.email ?? null }
}),
},
mutations: {
bump: mutation({ name: counterName }, function* ({ name }) {
const db = yield* Db
yield* db
.insert(counters)
.values({ name, value: 1 })
.onConflictDoUpdate({ target: counters.name, set: { value: sql`${counters.value} + 1` } })
}),
post: mutation({ text: messageText }, function* ({ text }) {
const db = yield* Db
const viewer = yield* Viewer
const [message] = yield* db
.insert(messages)
.values({ author: viewer.userId, authorName: displayName(viewer), text })
.returning({ id: messages.id })
return message!.id
}),
deleteMessage: mutation({ message: id("messages") }, function* ({ message }) {
const db = yield* Db
const viewer = yield* Viewer
const row = yield* db.get(messages, message)
if (row.author !== viewer.userId) return yield* new NotFound({ table: "messages", id: message })
yield* db.delete(messages).where(eq(messages.id, message))
}),
addNote: mutation({ text: noteText }, function* ({ text }) {
const me = yield* requireSignIn
const db = yield* Db
const [note] = yield* db.insert(notes).values({ owner: me.userId, text }).returning({ id: notes.id })
return note!.id
}),
toggleNote: mutation({ note: id("notes") }, function* ({ note }) {
const row = yield* ownNote(note)
const db = yield* Db
yield* db.update(notes).set({ done: !row.done }).where(eq(notes.id, note))
}),
deleteNote: mutation({ note: id("notes") }, function* ({ note }) {
yield* ownNote(note)
const db = yield* Db
yield* db.delete(notes).where(eq(notes.id, note))
}),
},
internal: {
/** The feed shows 20; keep the newest 200 so the public table cannot grow forever. */
trimFeed: mutation(function* () {
const db = yield* Db
const [oldest] = yield* db.select({ at: messages.createdAt }).from(messages).orderBy(desc(messages.createdAt)).limit(1).offset(199)
if (oldest) yield* db.delete(messages).where(lt(messages.createdAt, oldest.at))
}),
},
crons: { trimFeed: { every: "1 hour", run: "trimFeed" } },
})
server/seed.ts21 lines
import { defineSeed, MINUTE } from "canica/testing"
import app from "./index.ts"
export default defineSeed(app, ({ as, at, advance }) => {
const me = as("viewer")
const ana = as("Ana")
const marc = as("Marc")
at(0, "09:10")
for (let i = 0; i < 7; i++) ana.mutationOk("bump", { name: "red" })
for (let i = 0; i < 4; i++) marc.mutationOk("bump", { name: "blue" })
ana.mutationOk("post", { text: "Open this page in a second window and click +1 there." })
advance(4 * MINUTE)
marc.mutationOk("post", { text: "Then open the dev tools (⚡ bottom right) and look at Mutations." })
advance(3 * MINUTE)
me.mutationOk("post", { text: "Only the queries that read what changed re-run." })
advance(MINUTE)
me.mutationOk("addNote", { text: "Sign in with another account in another window: these stay private" })
const n = me.mutationOk("addNote", { text: "Bump red and watch counter(blue) not re-run" })
me.mutationOk("toggleNote", { note: n })
})
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"
start(routes)
src/routes/__root.tsx24 lines
import { layout, Link } from "canica/client"
import { AppHeader, UserMenu } from "canica/ui"
import { ActivityIcon } from "canica/icons"
export default layout({
view: ({ children }) => (
<div className="min-h-screen">
<AppHeader
size="lg"
brand={
<Link to="/" className="flex items-center gap-2">
<ActivityIcon className="size-4 text-primary" /> Live lab
</Link>
}
>
<Link to="/">Lab</Link>
<Link to="/me">Account</Link>
<UserMenu />
</AppHeader>
{children}
</div>
),
})
src/routes/index.tsx33 lines
import { page } from "canica/client"
import { PageContainer, PageHeader } from "canica/ui"
import { CounterCard } from "../components/counter-card.tsx"
import { Feed, FeedStats } from "../components/feed.tsx"
import { Notes } from "../components/notes.tsx"
import { WhoAmI } from "../components/whoami.tsx"
export default page({
title: "Live lab",
view: () => (
<PageContainer>
<PageHeader
title="Live queries, step by step"
description="Open this page in two windows (one private, as another user) and open the dev tools with the ⚡ button or Alt+S. Every click shows which live queries re-ran and which did not."
/>
<div className="grid gap-8 lg:grid-cols-3">
<div className="flex flex-col gap-8 lg:col-span-2">
<div className="grid gap-4 sm:grid-cols-2">
<CounterCard name="red" />
<CounterCard name="blue" />
</div>
<Feed />
</div>
<div className="flex flex-col gap-8">
<WhoAmI />
<FeedStats />
<Notes />
</div>
</div>
</PageContainer>
),
})
src/routes/me.tsx57 lines
import { page, useAuth, useQuery } from "canica/client"
import {
Avatar,
AvatarFallback,
AvatarImage,
ErrorState,
Loading,
PageContainer,
PageHeader,
Section,
Stat,
Stats,
} from "canica/ui"
/** A page only signed-in users can open: `auth: "signedIn"` shows the sign-in screen to guests. */
export default page({
title: "Your account",
auth: "signedIn",
view: () => {
const auth = useAuth()
const notes = useQuery("myNotes")
const name = auth.profile?.name ?? "You"
return (
<PageContainer>
<PageHeader
title={
<span className="flex items-center gap-3">
<Avatar className="size-10">
{auth.profile?.picture && <AvatarImage src={auth.profile.picture} alt="" />}
<AvatarFallback>{name.slice(0, 1)}</AvatarFallback>
</Avatar>
{name}
</span>
}
description={auth.profile?.email ?? "Signed in"}
/>
<Section
title="Your data"
description="Live: add or complete a note on the home page and these numbers follow."
>
{notes.match({
loading: () => <Loading shape="grid" />,
failure: (error) => <ErrorState error={error} />,
success: (list) => (
<Stats>
<Stat label="Notes" value={list.length} />
<Stat label="Done" value={list.filter((n) => n.done).length} />
<Stat label="To do" value={list.filter((n) => !n.done).length} />
</Stats>
),
})}
</Section>
</PageContainer>
)
},
})
src/components/counter-card.tsx37 lines
import { useMutation, useQuery } from "canica/client"
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, ErrorState, Loading } from "canica/ui"
import { PlusIcon } from "canica/icons"
/** One shared counter. `counter({ name })` reads one row, so bumping the other counter does not re-run it. */
export function CounterCard({ name }: { readonly name: "red" | "blue" }) {
const value = useQuery("counter", { name })
const bump = useMutation("bump")
return (
<Card>
<CardHeader>
<CardTitle>
<span className="capitalize">{name}</span>
</CardTitle>
<CardDescription>
<span className="font-mono text-xs">counter({`{ name: "${name}" }`})</span>
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
{value.match({
loading: () => <Loading shape="text" />,
failure: (error) => <ErrorState error={error} />,
success: (n) => <span className="font-heading text-4xl font-semibold tabular-nums">{n}</span>,
})}
<Button
variant="outline"
onClick={() => void bump({ name })}
disabled={bump.waiting}
aria-label={`Bump ${name}`}
>
<PlusIcon /> 1
</Button>
</CardContent>
</Card>
)
}
src/components/feed.tsx91 lines
import { useMutation, useQuery } from "canica/client"
import {
Button,
Conversation,
ErrorState,
Loading,
Message,
MessageInput,
ResultBar,
Section,
EmptyBlock,
confirm,
} from "canica/ui"
import { Trash2Icon } from "canica/icons"
import { messageText } from "../../shared/fields.ts"
/** The public feed: `feed` re-runs on every new or deleted message, for everyone watching. */
export function Feed() {
const feed = useQuery("feed")
const remove = useMutation("deleteMessage")
return (
<Section
title="Feed"
description="Everyone sees new messages instantly. Posting re-runs feed and feedStats, nothing else."
>
{feed.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (messages) => (
<Conversation
empty="No messages yet. Say hello."
// Not a form: a composer. Enter sends, Shift+Enter is a new line; it clears on success, keeps the text on failure.
composer={<MessageInput mutation="post" arg="text" field={messageText} label="Message" hideLabel placeholder="Write a message…" />}
>
{messages.map((m, i) => (
<Message
key={m.id}
author={m.author}
at={m.at}
mine={m.mine}
continued={messages[i - 1]?.author === m.author}
actions={
m.mine ? (
<Button
size="icon-sm"
variant="ghost"
aria-label="Delete message"
aria-haspopup="dialog"
onClick={async () => {
const answer = await confirm({ title: "Delete this message?", confirm: "Delete" })
if (answer._tag === "Done") remove({ message: m.id })
}}
>
<Trash2Icon />
</Button>
) : undefined
}
>
{m.text}
</Message>
))}
</Conversation>
),
})}
</Section>
)
}
/** An aggregate over the whole table: one GROUP BY in the database, live like any other query. */
export function FeedStats() {
const stats = useQuery("feedStats")
return (
<Section title="Who talks most" description="feedStats: countBy(authorName) in the database.">
{stats.match({
loading: () => <Loading shape="text" />,
failure: (error) => <ErrorState error={error} />,
success: (s) =>
s.total === 0 ? (
<EmptyBlock title="No messages yet" />
) : (
<div className="flex flex-col gap-3">
{s.byAuthor.map((a, i) => (
<ResultBar key={a.name} label={a.name} value={a.n} total={s.total} highlight={i === 0} />
))}
</div>
),
})}
</Section>
)
}
src/components/notes.tsx111 lines
import { useForm, useMutation, useQuery } from "canica/client"
import {
CheckButton,
Button,
EmptyBlock,
ErrorState,
Item,
ItemActions,
ItemContent,
ItemTitle,
List,
Loading,
Form,
FormField,
Input,
modal,
ModalActions,
ModalTitle,
SubmitButton,
RequireSignIn,
Section,
confirm,
} from "canica/ui"
import { Trash2Icon } from "canica/icons"
import { noteText } from "../../shared/fields.ts"
function NoteList() {
const notes = useQuery("myNotes")
const toggle = useMutation("toggleNote")
const remove = useMutation("deleteNote")
return (
<div className="flex flex-col gap-4">
<div><Button aria-haspopup="dialog" onClick={() => void NewNote.open()}>New note</Button></div>
{notes.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock {...{ title: "No notes yet", description: "They are private to your account." }} />
) : (
<List>
{list.map((n) => (
<Item key={n.id}>
<CheckButton
pressed={n.done}
onClick={() => toggle({ note: n.id })}
label={`Mark "${n.text}" ${n.done ? "not done" : "done"}`}
/>
<ItemContent>
<ItemTitle>
<span className={n.done ? "text-muted-foreground line-through" : undefined}>{n.text}</span>
</ItemTitle>
</ItemContent>
<ItemActions>
<Button
size="icon-sm"
variant="ghost"
aria-label="Delete note"
aria-haspopup="dialog"
onClick={async () => {
const answer = await confirm({ title: "Delete this note?", confirm: "Delete" })
if (answer._tag === "Done") remove({ note: n.id })
}}
>
<Trash2Icon />
</Button>
</ItemActions>
</Item>
))}
</List>
),
})}
</div>
)
}
/** Account-only and private: myNotes uses requireSignIn and reads only this user's rows. */
export function Notes() {
return (
<Section
title="My notes"
description="myNotes: requireSignIn + index by owner. Another user's changes never re-run it."
>
<RequireSignIn
title="Sign in to keep private notes"
description="Guests can use the counters and the feed; notes need an account."
>
<NoteList />
</RequireSignIn>
</Section>
)
}
const NewNote = modal()(() => {
const close = NewNote.useClose()
const add = useMutation("addNote")
const form = useForm("new note", { text: noteText }, (v) => add(v), { onSuccess: () => close() })
return (
<>
<ModalTitle>New note</ModalTitle>
<Form form={form}>
<FormField form={form} name="text" label="Note"><Input name="text" autoFocus autoComplete="off" /></FormField>
<ModalActions>
<Button type="button" variant="outline" onClick={close.cancel}>Cancel</Button>
<SubmitButton form={form}>Add note</SubmitButton>
</ModalActions>
</Form>
</>
)
})
src/components/whoami.tsx33 lines
import { useAuth, useQuery } from "canica/client"
import { Badge, ErrorState, Loading, Section } from "canica/ui"
/** The server's view of this connection. Signing in or out reconnects and every live query re-runs. */
export function WhoAmI() {
const me = useQuery("whoami")
const auth = useAuth()
return (
<Section title="Who am I" description="whoami, from the server. Sign in or out: it updates without reloading.">
{me.match({
loading: () => <Loading shape="text" />,
failure: (error) => <ErrorState error={error} />,
success: (v) => (
<dl className="grid grid-cols-3 gap-x-4 gap-y-2 text-sm">
<dt className="text-muted-foreground">Session</dt>
<dd className="col-span-2">
<Badge variant={v.isSignedIn ? "default" : "secondary"}>{v.isSignedIn ? "Signed in" : "Guest"}</Badge>
</dd>
<dt className="text-muted-foreground">Name</dt>
<dd className="col-span-2">{v.name ?? "—"}</dd>
<dt className="text-muted-foreground">Email</dt>
<dd className="col-span-2 truncate">{v.email ?? "—"}</dd>
<dt className="text-muted-foreground">User id</dt>
<dd className="col-span-2 truncate font-mono text-xs">{v.userId}</dd>
<dt className="text-muted-foreground">Connection</dt>
<dd className="col-span-2">{auth.isLoading ? "reconnecting…" : "live"}</dd>
</dl>
),
})}
</Section>
)
}
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
* App theme: shadcn preset b5ZK2XNe4G (style maia, teal on mauve, font geist, radius none).
* Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b5ZK2XNe4G
* and apply the new code with `canica theme <code>`, or edit these tokens by hand.
*/
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0.008 326);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0.008 326);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0.008 326);
--primary: oklch(0.511 0.096 186.391);
--primary-foreground: oklch(0.984 0.014 180.72);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.96 0.003 325.6);
--muted-foreground: oklch(0.542 0.034 322.5);
--accent: oklch(0.96 0.003 325.6);
--accent-foreground: oklch(0.212 0.019 322.12);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0.005 325.62);
--input: oklch(0.922 0.005 325.62);
--ring: oklch(0.711 0.019 323.02);
--chart-1: oklch(0.855 0.138 181.071);
--chart-2: oklch(0.704 0.14 182.503);
--chart-3: oklch(0.6 0.118 184.704);
--chart-4: oklch(0.511 0.096 186.391);
--chart-5: oklch(0.437 0.078 188.216);
--radius: 0;
--font-body: "Geist", ui-sans-serif, system-ui, sans-serif;
--font-display: "Roboto Slab", ui-serif, Georgia, serif;
}
.dark {
--background: oklch(0.145 0.008 326);
--foreground: oklch(0.985 0 0);
--card: oklch(0.212 0.019 322.12);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.212 0.019 322.12);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.437 0.078 188.216);
--primary-foreground: oklch(0.984 0.014 180.72);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.263 0.024 320.12);
--muted-foreground: oklch(0.711 0.019 323.02);
--accent: oklch(0.263 0.024 320.12);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.542 0.034 322.5);
--chart-1: oklch(0.855 0.138 181.071);
--chart-2: oklch(0.704 0.14 182.503);
--chart-3: oklch(0.6 0.118 184.704);
--chart-4: oklch(0.511 0.096 186.391);
--chart-5: oklch(0.437 0.078 188.216);
}
server/index.test.ts39 lines
import { describe, expect, it } from "vitest"
import { testApp } from "canica/testing"
import app from "./index.ts"
describe("live lab", () => {
it("counters are shared", () => {
const t = testApp(app)
t.as("ana").mutationOk("bump", { name: "red" })
t.as("marc").mutationOk("bump", { name: "red" })
expect(t.as("lucia").queryOk("counter", { name: "red" })).toBe(2)
expect(t.as("lucia").queryOk("counter", { name: "blue" })).toBe(0)
})
it("notes need an account and stay private", () => {
const t = testApp(app)
expect(t.as("guest").mutation("addNote", { text: "x" })).toMatchObject({ _tag: "Failure", error: { _tag: "Unauthenticated" } })
const alice = t.as("alice", { signedIn: true })
const note = alice.mutationOk("addNote", { text: "secret" })
const bob = t.as("bob", { signedIn: true })
expect(bob.queryOk("myNotes")).toEqual([])
expect(bob.mutation("toggleNote", { note })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
})
it("messages carry the signed-in name, guests are 'A guest'", () => {
const t = testApp(app)
t.as("alice", { signedIn: { name: "Alice" } }).mutationOk("post", { text: "hi" })
t.as("g").mutationOk("post", { text: "yo" })
expect(t.as("x").queryOk("feed").map((m) => m.author)).toEqual(["Alice", "A guest"])
})
it("an hourly cron keeps the newest 200 messages", async () => {
const t = testApp(app)
for (let i = 0; i < 205; i++) t.as("ana").mutationOk("post", { text: `m${i}` })
await t.advance(60 * 60_000)
expect(t.as("x").queryOk("feedStats").total).toBe(200)
expect(t.as("x").queryOk("feed").at(-1)?.text).toBe("m204")
})
})
src/app.test.tsx54 lines
import { describe, expect, it } from "vitest"
import { as, click, label, meanwhile, notSee, role, scene, see, testApp, text, type, visit, within } from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"
describe("live lab (scenes)", () => {
it("the feed's composer sends with Enter, clears, and shows other people's messages live", async () => {
const t = testApp(app)
await scene(t, routes,
as("ana"),
visit("/"),
see(text("No messages yet. Say hello.")),
type(role("textbox", { name: "Message" }), "hello everyone{Enter}"),
see(text("hello everyone")),
meanwhile(() => expect(document.querySelector<HTMLTextAreaElement>("[data-slot=message-input] textarea")?.value).toBe("")),
meanwhile(() => t.as("bob").mutationOk("post", { text: "hi ana" })),
see(text("hi ana")),
)
})
it("a message that is too long keeps its text and says why", async () => {
const t = testApp(app)
await scene(t, routes,
as("ana"),
visit("/"),
type(role("textbox", { name: "Message" }), "x".repeat(281)),
see(text("281/280")),
click(role("button", { name: "Send" })),
see(text("At most 280 characters")),
meanwhile(() => expect(document.querySelector<HTMLTextAreaElement>("[data-slot=message-input] textarea")?.value).toHaveLength(281)),
)
expect(t.as("x").queryOk("feed")).toEqual([])
})
it("notes: added from an autofocus modal, private to the account", async () => {
const t = testApp(app)
await scene(t, routes,
as("alice", { signedIn: true }),
visit("/"),
see(text("No notes yet")),
click(role("button", { name: "New note" })),
within(role("dialog"),
meanwhile(() => expect(document.activeElement?.getAttribute("name")).toBe("text")),
type(label("Note"), "Water the plants"),
click(role("button", { name: "Add note" })),
),
notSee(role("dialog")),
see(text("Water the plants")),
as("bob", { signedIn: true }),
notSee(text("Water the plants")),
)
})
})