Rooms (chat)
Realtime chat rooms with display names.
14 files, 915 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in apps/chat.
Files
server/index.ts127server/seed.ts45shared/fields.ts13src/main.tsx6src/routes/__root.tsx15src/routes/404.tsx21src/routes/index.tsx84src/routes/rooms/$room.tsx146src/components/display-name.tsx35src/components/new-room.tsx45src/styles.css4src/theme.css60server/index.test.ts160src/app.test.tsx154
server/index.ts127 lines
import {
asc,
count,
desc,
eq,
id,
mutation,
NotFound,
query,
schema,
sql,
table,
TaggedError,
userId,
Viewer,
type Id,
} from "canica/server"
import { displayName, messageBody, roomName } from "../shared/fields.ts"
export const { app, Db, tables } = schema({
/** One row per user: the name they chat under. No row means "Anonymous". */
profiles: table({ user: userId(), name: displayName }).unique("by_user", ["user"]),
rooms: table({ name: roomName }).unique("by_name", ["name"], { caseInsensitive: true }),
messages: table({
room: id("rooms").onDelete("cascade"),
author: userId(),
body: messageBody,
}).index("by_room", ["room"]),
})
const { profiles, rooms, messages } = tables
export class RoomNameTaken extends TaggedError("RoomNameTaken")<{ readonly name: string }> {}
/** A message the viewer wrote. Someone else's message looks like it does not exist. */
function* ownMessage(message: Id<"messages">) {
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 })
return row
}
export default app({
name: "Rooms",
queries: {
/** Every room, with how many messages it holds. */
rooms: query(function* () {
const db = yield* Db
return yield* db
.select({ id: rooms.id, name: rooms.name, messages: count(messages.id) })
.from(rooms)
.leftJoin(messages, eq(messages.room, rooms.id))
.groupBy(rooms.id)
.orderBy(asc(rooms.createdAt))
}),
/** One room, with its message count. A missing room is a NotFound the page words. */
room: query({ room: id("rooms") }, function* ({ room }) {
const db = yield* Db
const row = yield* db.get(rooms, room)
const total = yield* db.count(messages, eq(messages.room, room))
return { id: row.id, name: row.name, messages: total }
}),
/** The last 100 messages of a room, oldest first, each with its author's display name. */
messages: query({ room: id("rooms") }, function* ({ room }) {
const db = yield* Db
yield* db.get(rooms, room)
const newest = yield* db
.select({
id: messages.id,
body: messages.body,
author: messages.author,
authorName: profiles.name,
createdAt: messages.createdAt,
})
.from(messages)
.leftJoin(profiles, eq(profiles.user, messages.author))
.where(eq(messages.room, room))
.orderBy(desc(messages.createdAt))
.limit(100)
return newest.reverse()
}),
/** The viewer's own profile row, or null while they are anonymous. */
profile: query(function* () {
const db = yield* Db
const viewer = yield* Viewer
const [row] = yield* db.select().from(profiles).where(eq(profiles.user, viewer.userId)).limit(1)
return row ?? null
}),
},
mutations: {
createRoom: mutation({ name: roomName }, function* ({ name }) {
const db = yield* Db
// Uniqueness is case-insensitive: check first, fail with our own error (a violation would be a bug).
const [taken] = yield* db
.select({ id: rooms.id })
.from(rooms)
.where(eq(sql`lower(${rooms.name})`, name.toLowerCase()))
.limit(1)
if (taken) return yield* new RoomNameTaken({ name })
const [row] = yield* db.insert(rooms).values({ name }).returning({ id: rooms.id })
return row!.id
}),
send: mutation({ room: id("rooms"), body: messageBody }, function* ({ room, body }) {
const db = yield* Db
const viewer = yield* Viewer
yield* db.get(rooms, room) // a room deleted meanwhile: NotFound
const [row] = yield* db.insert(messages).values({ room, author: viewer.userId, body }).returning({ id: messages.id })
return row!.id
}),
deleteMessage: mutation({ message: id("messages") }, function* ({ message }) {
yield* ownMessage(message)
const db = yield* Db
yield* db.delete(messages).where(eq(messages.id, message))
}),
/** Set (or change) the viewer's display name. One profile row per user. */
setName: mutation({ name: displayName }, function* ({ name }) {
const db = yield* Db
const viewer = yield* Viewer
yield* db
.insert(profiles)
.values({ user: viewer.userId, name })
.onConflictDoUpdate({ target: profiles.user, set: { name } })
return name
}),
},
})
server/seed.ts45 lines
import { defineSeed, MINUTE } from "canica/testing"
import app from "./index.ts"
// Sample data for `pnpm storyboard`, created through the mutations (so every invariant holds).
// "viewer" is the user the storyboard browses as; other names are other people.
// Everything sits in yesterday evening, so the sample never depends on the hour the storyboard runs.
export default defineSeed(app, ({ as, advance, at }) => {
const me = as("viewer")
me.mutationOk("setName", { name: "Vera" })
at(-1, "18:40")
const general = me.mutationOk("createRoom", { name: "General" })
const weekend = me.mutationOk("createRoom", { name: "Weekend plans" })
// Left empty on purpose: the room page's empty state.
const support = me.mutationOk("createRoom", { name: "Support" })
at(-1, "19:02")
as("Ana").mutationOk("setName", { name: "Ana" })
as("Ana").mutationOk("send", { room: general, body: "Who is around this evening?" })
advance(3 * MINUTE)
// A guest who never set a name: shows as Anonymous.
as("lurker").mutationOk("send", { room: general, body: "just reading 👀" })
advance(4 * MINUTE)
me.mutationOk("send", { room: general, body: "Here! Working late, but around." })
at(-1, "20:15")
as("Ana").mutationOk("send", { room: general, body: "Did anyone try the new café on Gran Via?" })
advance(MINUTE)
as("Ana").mutationOk("send", { room: general, body: "The cinnamon rolls are worth the queue." })
advance(6 * MINUTE)
me.mutationOk("send", { room: general, body: "Adding it to the list. Anyone up for Saturday?" })
advance(2 * MINUTE)
as("Marc").mutationOk("setName", { name: "Marc" })
as("Marc").mutationOk("send", { room: general, body: "Saturday works. 10:00?" })
advance(9 * MINUTE)
as("Ana").mutationOk("send", { room: general, body: "10:00 is perfect. I'll book a table for four." })
at(-1, "21:00")
as("Marc").mutationOk("send", { room: weekend, body: "Rain forecast on Sunday — indoor plan?" })
advance(4 * MINUTE)
me.mutationOk("send", { room: weekend, body: "Board games at mine, then. Bring the good ones." })
return { captures: { "/rooms/$room": [{ room: general }, { room: weekend }, { room: support }] } }
})
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"
start(routes)
src/routes/__root.tsx15 lines
import { layout, Link } from "canica/client"
import { AppHeader, PageContainer, UserMenu } from "canica/ui"
export default layout({
view: ({ children }) => (
<div className="min-h-screen">
<AppHeader brand={<Link to="/">Chat</Link>}>
<UserMenu />
</AppHeader>
{/* Frames every page, loading and error states included. */}
<PageContainer>{children}</PageContainer>
</div>
),
})
src/routes/404.tsx21 lines
import { Link, page } from "canica/client"
import { Button, EmptyBlock, PageContainer } from "canica/ui"
/** Shown for a URL that matches no route, or whose params are invalid (e.g. /rooms/not-an-id). */
export default page({
title: "Not found",
view: () => (
<PageContainer>
<EmptyBlock
title="This page does not exist"
description="The link may be wrong. Rooms live at /rooms/<id>."
action={
<Button asChild>
<Link to="/">All rooms</Link>
</Button>
}
/>
</PageContainer>
),
})
src/routes/index.tsx84 lines
import { Link, page, plural, useNavigate, useQuery } from "canica/client"
import {
Button,
EmptyBlock,
ErrorState,
Item,
ItemContent,
ItemDescription,
ItemTitle,
List,
Loading,
PageContainer,
PageHeader,
Section,
} from "canica/ui"
import { DisplayNameForm } from "../components/display-name.tsx"
import { NewRoom } from "../components/new-room.tsx"
export default page({
title: "Rooms",
view: () => {
const rooms = useQuery("rooms")
const profile = useQuery("profile")
const goToRoom = useNavigate("/rooms/$room")
const newRoom = async () => {
const created = await NewRoom.open()
created.match({ done: (room) => goToRoom({ room }), cancelled: () => {} })
}
return (
<PageContainer>
<PageHeader
title="Rooms"
description="Everyone here is a guest — pick a room, or start one."
actions={
<Button aria-haspopup="dialog" onClick={() => void newRoom()}>
New room
</Button>
}
/>
{profile.match({
loading: () => <Loading shape="text" />,
failure: (error) => <ErrorState error={error} />,
success: (row) => <DisplayNameForm current={row?.name ?? null} />,
})}
<Section title="Rooms">
{rooms.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock
title="No rooms yet"
description="Start the first one; the others will see it appear."
action={
<Button aria-haspopup="dialog" onClick={() => void newRoom()}>
Create the first room
</Button>
}
/>
) : (
<List>
{list.map((room) => (
<Item key={room.id} asChild>
<Link to="/rooms/$room" params={{ room: room.id }}>
<ItemContent>
<ItemTitle>{room.name}</ItemTitle>
<ItemDescription>{plural(room.messages, "message")}</ItemDescription>
</ItemContent>
</Link>
</Item>
))}
</List>
),
})}
</Section>
</PageContainer>
)
},
})
src/routes/rooms/$room.tsx146 lines
import {
id,
Link,
page,
plural,
useAuth,
useForm,
useMutation,
useQuery,
type Id,
type QueryValue,
} from "canica/client"
import {
Button,
confirm,
Conversation,
ErrorState,
Form,
FormField,
Input,
Loading,
Message,
PageContainer,
PageHeader,
SubmitButton,
} from "canica/ui"
import { Trash2Icon } from "canica/icons"
import { messageBody } from "../../../shared/fields.ts"
/** One message's delete control: only ever rendered on the viewer's own messages. */
function DeleteMessage({ message }: { readonly message: Id<"messages"> }) {
const remove = useMutation("deleteMessage")
return (
<Button
size="icon-sm"
variant="ghost"
aria-label="Delete message"
aria-haspopup="dialog"
onClick={async () => {
const answer = await confirm({
title: "Delete this message?",
description: "It disappears for everyone in the room.",
confirm: "Delete",
})
if (answer._tag === "Done") await remove({ message })
}}
>
<Trash2Icon />
</Button>
)
}
/** The live message list and the composer, for one room that exists. */
function RoomView({ room }: { readonly room: QueryValue<"room"> }) {
const messages = useQuery("messages", { room: room.id })
const profile = useQuery("profile")
const send = useMutation("send")
const auth = useAuth()
const me = profile._tag === "Success" ? profile.value?.name : undefined
const form = useForm("send message", { body: messageBody }, (values) => send({ room: room.id, ...values }))
return (
<PageContainer>
<PageHeader
title={room.name}
description={plural(room.messages, "message")}
back={<Link to="/">← All rooms</Link>}
/>
{messages.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) => (
<Conversation
empty="No messages yet. Say hello."
composer={
<Form form={form}>
<FormField form={form} name="body" label="Message">
<div className="flex items-start gap-2">
<Input
name="body"
placeholder={me ? `Message as ${me}…` : "Message as Anonymous…"}
autoComplete="off"
className="flex-1"
/>
<SubmitButton form={form}>Send</SubmitButton>
</div>
</FormField>
</Form>
}
>
{list.map((message, i) => {
const mine = message.author === auth.userId
const previous = list[i - 1]
return (
<Message
key={message.id}
author={message.authorName ?? "Anonymous"}
at={message.createdAt}
mine={mine}
continued={previous?.author === message.author}
actions={mine ? <DeleteMessage message={message.id} /> : undefined}
>
{message.body}
</Message>
)
})}
</Conversation>
),
})}
</PageContainer>
)
}
export default page({
params: { room: id("rooms") },
title: "Room",
view: ({ params }) => {
const room = useQuery("room", { room: params.room })
return room.match({
loading: () => (
<PageContainer>
<Loading shape="text" />
<Loading shape="list" />
</PageContainer>
),
failure: (error) => (
<ErrorState
error={error}
states={{
NotFound: {
title: "This room does not exist",
description: "It may have been deleted, or the link is wrong.",
action: (
<Button asChild variant="outline">
<Link to="/">All rooms</Link>
</Button>
),
},
}}
/>
),
success: (value) => <RoomView room={value} />,
})
},
})
src/components/display-name.tsx35 lines
import { useForm, useMutation } from "canica/client"
import { Badge, Form, FormField, Input, SubmitButton } from "canica/ui"
import { displayName } from "../../shared/fields.ts"
/**
* The viewer's display name: what their messages are signed with.
* Rendered once the `profile` query has loaded; `current` is null while anonymous.
* The `key` remounts the controls when the saved name changes, so the input shows the stored value.
*/
export function DisplayNameForm({ current }: { readonly current: string | null }) {
const setName = useMutation("setName")
const form = useForm("set display name", { name: displayName }, (values) => setName(values))
return (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
You chat as <Badge variant={current ? "default" : "secondary"}>{current ?? "Anonymous"}</Badge>
</p>
<Form form={form} className="max-w-md" key={current ?? "anonymous"}>
<FormField
form={form}
name="name"
label="Display name"
description="1–40 characters; you can change it any time."
>
<div className="flex items-start gap-2">
<Input name="name" defaultValue={current ?? ""} placeholder="Anonymous" autoComplete="off" className="flex-1" />
<SubmitButton form={form}>Save name</SubmitButton>
</div>
</FormField>
</Form>
</div>
)
}
src/components/new-room.tsx45 lines
import { useForm, useMutation, type Id } from "canica/client"
import { Button, Form, FormField, Input, modal, ModalActions, ModalText, ModalTitle, SubmitButton } from "canica/ui"
import { roomName } from "../../shared/fields.ts"
/**
* The "New room" dialog. Awaited from the home page; closes with the new room's id.
*
* ```tsx
* const created = await NewRoom.open()
* created.match({ done: (room) => goToRoom({ room }), cancelled: () => {} })
* ```
*/
export const NewRoom = modal<Id<"rooms">>()(() => {
const close = NewRoom.useClose()
const createRoom = useMutation("createRoom")
const form = useForm(
"create room",
{ name: roomName },
(values) => createRoom(values),
{ onSuccess: (room) => close(room) },
)
return (
<>
<ModalTitle>New room</ModalTitle>
<ModalText>Everyone can see and join it from the home page.</ModalText>
<Form
form={form}
describeError={(error) =>
error._tag === "RoomNameTaken" ? `There is already a room called “${error.name}”.` : undefined
}
>
<FormField form={form} name="name" label="Name" description="Rooms are unique; names up to 60 characters.">
<Input name="name" placeholder="General" autoComplete="off" autoFocus />
</FormField>
<ModalActions>
<Button type="button" variant="outline" onClick={close.cancel}>
Cancel
</Button>
<SubmitButton form={form}>Create room</SubmitButton>
</ModalActions>
</Form>
</>
)
})
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
* App theme: shadcn preset b87K9rR0ax (style sera, blue on olive, font outfit, radius medium).
* Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b87K9rR0ax
* and apply the new code with `pnpm exec canica theme <code>`, or edit these tokens by hand.
*/
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.153 0.006 107.1);
--card: oklch(1 0 0);
--card-foreground: oklch(0.153 0.006 107.1);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.153 0.006 107.1);
--primary: oklch(0.488 0.243 264.376);
--primary-foreground: oklch(0.97 0.014 254.604);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.966 0.005 106.5);
--muted-foreground: oklch(0.58 0.031 107.3);
--accent: oklch(0.488 0.243 264.376);
--accent-foreground: oklch(0.97 0.014 254.604);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.93 0.007 106.5);
--input: oklch(0.93 0.007 106.5);
--ring: oklch(0.737 0.021 106.9);
--chart-1: oklch(0.837 0.128 66.29);
--chart-2: oklch(0.705 0.213 47.604);
--chart-3: oklch(0.646 0.222 41.116);
--chart-4: oklch(0.553 0.195 38.402);
--chart-5: oklch(0.47 0.157 37.304);
--radius: 0.625rem;
--font-body: "Outfit", ui-sans-serif, system-ui, sans-serif;
--font-display: "EB Garamond", ui-serif, Georgia, serif;
}
.dark {
--background: oklch(0.153 0.006 107.1);
--foreground: oklch(0.988 0.003 106.5);
--card: oklch(0.228 0.013 107.4);
--card-foreground: oklch(0.988 0.003 106.5);
--popover: oklch(0.228 0.013 107.4);
--popover-foreground: oklch(0.988 0.003 106.5);
--primary: oklch(0.424 0.199 265.638);
--primary-foreground: oklch(0.97 0.014 254.604);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.286 0.016 107.4);
--muted-foreground: oklch(0.737 0.021 106.9);
--accent: oklch(0.424 0.199 265.638);
--accent-foreground: oklch(0.97 0.014 254.604);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.58 0.031 107.3);
--chart-1: oklch(0.837 0.128 66.29);
--chart-2: oklch(0.705 0.213 47.604);
--chart-3: oklch(0.646 0.222 41.116);
--chart-4: oklch(0.553 0.195 38.402);
--chart-5: oklch(0.47 0.157 37.304);
}
server/index.test.ts160 lines
import { describe, expect, it } from "vitest"
import { missingId, testApp } from "canica/testing"
import app from "./index.ts"
describe("rooms", () => {
it("lists every room with its message count, for anyone", () => {
const t = testApp(app)
const general = t.as("ana").mutationOk("createRoom", { name: "General" })
t.as("bob").mutationOk("createRoom", { name: "Weekend plans" })
t.as("ana").mutationOk("send", { room: general, body: "hello" })
expect(t.as("carol").query("rooms")).toMatchObject({
_tag: "Success",
value: [
{ name: "General", messages: 1 },
{ name: "Weekend plans", messages: 0 },
],
})
expect(t.as("carol").queryOk("room", { room: general })).toMatchObject({ name: "General", messages: 1 })
})
it("trims names and rejects duplicates, ignoring case", () => {
const t = testApp(app)
expect(t.as("ana").mutationOk("createRoom", { name: " General " })).toBeTruthy()
expect(t.as("bob").mutation("createRoom", { name: "general" })).toMatchObject({
_tag: "Failure",
error: { _tag: "RoomNameTaken", name: "general" },
})
expect(t.as("bob").mutation("createRoom", { name: "GENERAL" })).toMatchObject({ _tag: "Failure", error: { _tag: "RoomNameTaken" } })
expect(t.as("bob").queryOk("rooms")).toMatchObject([{ name: "General" }])
})
it("validates the room name (1–60 characters)", () => {
const t = testApp(app)
expect(t.as("ana").mutation("createRoom", { name: " " })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["name"], message: "Give the room a name" }] },
})
expect(t.as("ana").mutation("createRoom", { name: "x".repeat(61) })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["name"] }] },
})
expect(t.as("ana").mutationOk("createRoom", { name: "x".repeat(60) })).toBeTruthy()
})
it("a room that does not exist is NotFound", () => {
const t = testApp(app)
expect(t.as("ana").query("room", { room: missingId("rooms") })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
expect(t.as("ana").query("messages", { room: missingId("rooms") })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
expect(t.as("ana").mutation("send", { room: missingId("rooms"), body: "hi" })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
})
})
describe("messages", () => {
it("keeps each room's messages separate, oldest first", () => {
const t = testApp(app)
const general = t.as("ana").mutationOk("createRoom", { name: "General" })
const other = t.as("ana").mutationOk("createRoom", { name: "Other" })
t.as("ana").mutationOk("send", { room: general, body: "first" })
t.advance(60_000)
t.as("bob").mutationOk("send", { room: general, body: "second" })
t.as("bob").mutationOk("send", { room: other, body: "elsewhere" })
expect(t.as("ana").queryOk("messages", { room: general }).map((m) => m.body)).toEqual(["first", "second"])
expect(t.as("ana").queryOk("messages", { room: other }).map((m) => m.body)).toEqual(["elsewhere"])
expect(t.as("ana").queryOk("room", { room: general })).toMatchObject({ messages: 2 })
})
it("signs messages with the author's display name, and Anonymous until one is set", () => {
const t = testApp(app)
const room = t.as("ana").mutationOk("createRoom", { name: "General" })
t.as("ana").mutationOk("setName", { name: "Ana" })
t.as("ana").mutationOk("send", { room, body: "hi, I am Ana" })
t.as("bob").mutationOk("send", { room, body: "and I am nobody yet" })
expect(t.as("ana").queryOk("messages", { room })).toMatchObject([
{ body: "hi, I am Ana", authorName: "Ana" },
{ body: "and I am nobody yet", authorName: null },
])
})
it("shows only the last 100 messages of a room", () => {
const t = testApp(app)
const room = t.as("ana").mutationOk("createRoom", { name: "Busy" })
for (let i = 1; i <= 105; i++) t.as("ana").mutationOk("send", { room, body: `message ${i}` })
const list = t.as("ana").queryOk("messages", { room })
expect(list).toHaveLength(100)
expect(list[0]!.body).toBe("message 6")
expect(list.at(-1)!.body).toBe("message 105")
expect(t.as("ana").queryOk("room", { room })).toMatchObject({ messages: 105 })
})
it("validates the body (1–2000 characters)", () => {
const t = testApp(app)
const room = t.as("ana").mutationOk("createRoom", { name: "General" })
expect(t.as("ana").mutation("send", { room, body: " " })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["body"], message: "Write something first" }] },
})
expect(t.as("ana").mutation("send", { room, body: "x".repeat(2001) })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
})
it("you can only delete your own message", () => {
const t = testApp(app)
const room = t.as("ana").mutationOk("createRoom", { name: "General" })
const hers = t.as("ana").mutationOk("send", { room, body: "mine" })
const his = t.as("bob").mutationOk("send", { room, body: "his" })
expect(t.as("bob").mutation("deleteMessage", { message: hers })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
expect(t.as("bob").queryOk("messages", { room })).toHaveLength(2)
expect(t.as("bob").mutation("deleteMessage", { message: his })._tag).toBe("Success")
expect(t.as("ana").queryOk("messages", { room })).toMatchObject([{ body: "mine" }])
})
})
describe("display names", () => {
it("one profile row per user: it starts empty, is created, then updated", () => {
const t = testApp(app)
expect(t.as("ana").queryOk("profile")).toBeNull()
t.as("ana").mutationOk("setName", { name: " Ana " })
expect(t.as("ana").queryOk("profile")).toMatchObject({ name: "Ana" })
t.as("ana").mutationOk("setName", { name: "Ana María" })
expect(t.as("ana").queryOk("profile")).toMatchObject({ name: "Ana María" })
expect(t.as("bob").queryOk("profile")).toBeNull()
})
it("validates the name (1–40 characters)", () => {
const t = testApp(app)
expect(t.as("ana").mutation("setName", { name: "" })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["name"], message: "Enter a name" }] },
})
expect(t.as("ana").mutation("setName", { name: "x".repeat(41) })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
})
it("renaming updates the name shown on messages already sent", () => {
const t = testApp(app)
const room = t.as("ana").mutationOk("createRoom", { name: "General" })
t.as("ana").mutationOk("setName", { name: "Ana" })
t.as("ana").mutationOk("send", { room, body: "hello" })
t.as("ana").mutationOk("setName", { name: "Ana María" })
expect(t.as("ana").queryOk("messages", { room })).toMatchObject([{ authorName: "Ana María" }])
})
})
src/app.test.tsx154 lines
import { describe, expect, it } from "vitest"
import {
as,
click,
label,
meanwhile,
missingId,
notSee,
role,
scene,
see,
testApp,
text,
type,
visit,
within,
type Id,
} from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"
describe("chat (scenes)", () => {
it("sets a name, creates a room and sends the first message", async () => {
const t = testApp(app)
await scene(
t,
routes,
as("ana"),
visit("/"),
see(text("No rooms yet")),
see(text("Anonymous")),
type(label("Display name"), "Ana"),
click(role("button", { name: "Save name" })),
see(text("Ana")),
click(role("button", { name: "New room" })),
within(role("dialog"), type(label("Name"), "General"), click(role("button", { name: "Create room" }))),
// Creating a room takes you to it.
see(role("heading", { name: "General" })),
see(text("0 messages")),
see(text("No messages yet. Say hello.")),
// Sending nothing is refused with the field's own message.
click(role("button", { name: "Send" })),
see(text("Write something first")),
type(label("Message"), "Hello everyone"),
click(role("button", { name: "Send" })),
see(text("Hello everyone")),
see(text("1 message")),
see(text("Ana")),
)
})
it("one person sends and the other sees it live, both ways", async () => {
const t = testApp(app)
let room: Id<"rooms"> = missingId("rooms")
await scene(
t,
routes,
as("ana"),
meanwhile(() => {
room = t.as("ana").mutationOk("createRoom", { name: "General" })
t.as("ana").mutationOk("setName", { name: "Ana" })
}),
visit("/rooms/$room", () => ({ room })),
see(text("No messages yet. Say hello.")),
type(label("Message"), "Anyone around?"),
click(role("button", { name: "Send" })),
see(text("Anyone around?")),
// Another window, another person: it appears here without a reload.
meanwhile(() => t.as("bob").mutationOk("send", { room, body: "Right here" })),
see(text("Right here")),
see(text("2 messages")),
// And the same room from the other person's window.
as("bob"),
see(text("Anyone around?")),
see(text("Ana")),
see(text("Anonymous")),
type(label("Message"), "Bob here, still nameless"),
click(role("button", { name: "Send" })),
see(text("3 messages")),
)
})
it("deletes your own message after a confirmation, and only your own", async () => {
const t = testApp(app)
let room: Id<"rooms"> = missingId("rooms")
await scene(
t,
routes,
as("bob"),
meanwhile(() => {
room = t.as("ana").mutationOk("createRoom", { name: "General" })
t.as("ana").mutationOk("setName", { name: "Ana" })
t.as("ana").mutationOk("send", { room, body: "Ana's message" })
t.as("bob").mutationOk("send", { room, body: "Bob's message" })
}),
visit("/rooms/$room", () => ({ room })),
see(text("Ana's message")),
see(text("Bob's message")),
// Only Bob's own message offers a Delete.
see(role("button", { name: "Delete message" }), 1),
click(role("button", { name: "Delete message" })),
within(role("alertdialog"), click(role("button", { name: "Delete" }))),
notSee(text("Bob's message")),
see(text("Ana's message")),
see(text("1 message")),
)
expect(t.as("ana").queryOk("messages", { room })).toMatchObject([{ body: "Ana's message" }])
})
it("room names are unique (ignoring case) and the list is live", async () => {
const t = testApp(app)
let weekend: Id<"rooms"> = missingId("rooms")
await scene(
t,
routes,
as("ana"),
visit("/"),
click(role("button", { name: "New room" })),
within(role("dialog"), type(label("Name"), "General"), click(role("button", { name: "Create room" }))),
see(role("heading", { name: "General" })),
visit("/"),
see(text("General")),
// Only the case differs: the name is taken, and the dialog says so.
click(role("button", { name: "New room" })),
within(role("dialog"), type(label("Name"), "general"), click(role("button", { name: "Create room" }))),
within(role("dialog"), see(text(/already a room called/))),
click(role("button", { name: "Cancel" })),
notSee(role("dialog")),
// Another window creates a room and talks in it: the list follows.
meanwhile(() => {
weekend = t.as("bob").mutationOk("createRoom", { name: "Weekend plans" })
}),
see(text("Weekend plans")),
meanwhile(() => t.as("bob").mutationOk("send", { room: weekend, body: "hi" })),
see(text("1 message")),
)
})
it("shows the not-found page for a bad id and a worded state for a missing room", async () => {
const t = testApp(app)
await scene(
t,
routes,
as("ana"),
visit("/rooms/not-an-id"),
see(text("This page does not exist")),
visit("/rooms/$room", { room: missingId("rooms") }),
see(text("This room does not exist")),
click(role("link", { name: "All rooms" })),
see(role("heading", { name: "Rooms" })),
)
})
})