Canica

Todos

A to-do list per person: the smallest complete app.

queries and mutationsforms in modalsimages (files)an email from an actiontests and scenes

14 files, 834 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in examples/todo.

Files

server/index.ts111 lines
import { boolean, desc, Email, emailId, eq, file, Files, id, mutation, NotFound, query, schema, table, TaggedError, userId, Viewer, type FileId, type FilesShape, type Id } from "canica/server"
import { todoText } from "../shared/fields.ts"
import { emails } from "./emails.tsx"

export const { app, Db, tables } = schema({
  todos: table({
    text: todoText,
    done: boolean().default(false),
    owner: userId(),
    /** An optional picture (uploaded with useUpload / <FileInput>, shown as a thumbnail). */
    image: file().optional(),
  }).index("by_owner", ["owner"]),
})
const { todos } = tables

export class TooManyTodos extends TaggedError("TooManyTodos")<{ readonly max: number }> {}

/** Load a todo the viewer owns. Other people's todos look like they don't exist. */
function* ownTodo(todoId: Id<"todos">) {
  const db = yield* Db
  const viewer = yield* Viewer
  const todo = yield* db.get(todos, todoId)
  if (todo.owner !== viewer.userId) return yield* new NotFound({ table: "todos", id: todoId })
  return todo
}

/**
 * A todo as pages see it: with a link to its image (only its owner reads it, so only they get the link), at most 640
 * px wide ("medium", for the details modal); the list's thumbnails ask a smaller size of the same link.
 */
const withImage = <T extends { readonly image: FileId | null }>(files: FilesShape, todo: T) => ({
  ...todo,
  imageUrl: todo.image ? files.url(todo.image, { size: "medium" }) : null,
})

export default app({
  name: "Todos",
  icon: "list-checks",
  // Each person's own list, after signing in with Google. "signedIn" is the default; written here to show it.
  access: "signedIn",
  emails,
  queries: {
    todos: query(function* () {
      const db = yield* Db
      const viewer = yield* Viewer
      const files = yield* Files
      const list = yield* db.select().from(todos).where(eq(todos.owner, viewer.userId)).orderBy(desc(todos.createdAt)).limit(200)
      return list.map((todo) => withImage(files, todo))
    }),
    todo: query({ id: id("todos") }, function* ({ id }) {
      return withImage(yield* Files, yield* ownTodo(id))
    }),
    /** Where an email to me is (live): queued → sending → sent | failed (with why). */
    emailStatus: query({ id: emailId() }, function* ({ id }) {
      const status = yield* (yield* Email).status(id)
      // Only the recipient sees it: someone else's email looks like it does not exist.
      if (status.to !== (yield* Viewer).userId) return yield* new NotFound({ table: "emails", id })
      return { state: status.state, reason: status.reason, attempts: status.attempts }
    }),
  },
  mutations: {
    addTodo: mutation({ text: todoText }, function* ({ text }) {
      const db = yield* Db
      const viewer = yield* Viewer
      const count = yield* db.count(todos, eq(todos.owner, viewer.userId))
      if (count >= 200) return yield* new TooManyTodos({ max: 200 })
      const [todo] = yield* db.insert(todos).values({ text, owner: viewer.userId }).returning({ id: todos.id })
      return todo!.id
    }),
    setDone: mutation({ id: id("todos"), done: boolean() }, function* ({ id, done }) {
      const db = yield* Db
      yield* ownTodo(id)
      yield* db.update(todos).set({ done }).where(eq(todos.id, id))
    }),
    rename: mutation({ id: id("todos"), text: todoText }, function* ({ id, text }) {
      const db = yield* Db
      yield* ownTodo(id)
      yield* db.update(todos).set({ text }).where(eq(todos.id, id))
    }),
    /** Attach an uploaded image (the previous one is deleted), or remove it (no `image`). */
    setImage: mutation({ id: id("todos"), image: file().optional() }, function* ({ id, image }) {
      const db = yield* Db
      const todo = yield* ownTodo(id)
      yield* db.update(todos).set({ image: image ?? null }).where(eq(todos.id, id))
      if (todo.image && todo.image !== image) yield* (yield* Files).delete(todo.image)
    }),
    remove: mutation({ id: id("todos") }, function* ({ id }) {
      const db = yield* Db
      const todo = yield* ownTodo(id)
      yield* db.delete(todos).where(eq(todos.id, id))
      if (todo.image) yield* (yield* Files).delete(todo.image)
    }),
  },
  actions: (action) => ({
    /**
     * Email me my open todos ("Your todos for today"). Returns how many are open and the email's id (the page follows
     * it with `emailStatus`); with none open, sends nothing.
     */
    remindMe: action(function* (ctx) {
      const open = (yield* ctx.runQuery("todos")).filter((todo) => !todo.done)
      if (open.length === 0) return { open: 0, email: null }
      const shown = open.slice(0, 20)
      const email = yield* (yield* Email).send("todayDigest", {
        to: ctx.viewer.userId,
        props: { name: ctx.viewer.profile?.name ?? "there", todos: shown.map((todo) => todo.text), more: open.length - shown.length },
      })
      return { open: open.length, email }
    }),
  }),
})
server/emails.tsx36 lines
import { email, Heading, Section, Text } from "canica/email"
import { array, number, plural, string } from "canica/server"

/**
 * Email templates: typed props, a subject from them, sample props (`preview`) for the dev outbox
 * (/_canica/dev/emails), `canica emails` and the storyboard, and the body. Canica adds the app's name and icon above
 * it and the unsubscribe footer below.
 */
export const emails = {
  todayDigest: email(
    {
      props: { name: string(), todos: array(string()), more: number().int().min(0) },
      subject: ({ todos, more }) => `Your todos for today (${todos.length + more})`,
      preview: { name: "Ana", todos: ["Buy oat milk", "Book the dentist", "Reply to Ana about Saturday"], more: 0 },
    },
    ({ name, todos, more }) => (
      <>
        <Heading as="h2" style={{ fontSize: "20px", lineHeight: "28px", margin: "0 0 8px" }}>
          Your todos for today
        </Heading>
        <Text style={{ margin: "0 0 16px", color: "#52525b" }}>
          Hi {name}, you have {plural(todos.length + more, "open todo")}:
        </Text>
        <Section>
          {todos.map((todo, i) => (
            <Text key={i} style={{ margin: 0, padding: "10px 0", borderTop: i === 0 ? "1px solid #e4e4e7" : undefined, borderBottom: "1px solid #e4e4e7", fontSize: "15px", lineHeight: "22px" }}>
              ☐&nbsp;&nbsp;{todo}
            </Text>
          ))}
        </Section>
        {more > 0 && <Text style={{ margin: "12px 0 0", color: "#52525b" }}>…and {more} more.</Text>}
      </>
    ),
  ),
}
server/seed.ts15 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"

export default defineSeed(app, async ({ as, sampleImage }) => {
  const me = as("viewer")
  for (const text of ["Buy oat milk", "Book the dentist", "Water the plants", "Reply to Ana about Saturday"]) {
    me.mutationOk("addTodo", { text })
  }
  const done = me.mutationOk("addTodo", { text: "Renew passport" })
  me.mutationOk("setDone", { id: done, done: true })
  // A todo with a picture, so the thumbnail shows up.
  const image = await me.uploadOk(sampleImage(), "photo.png")
  me.mutationOk("setImage", { id: done, image })
})
shared/fields.ts5 lines
import { string } from "canica/fields"

/** Shared between the server (args/table) and forms. */
export const todoText = string().trim().min(1).max(160)
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"

start(routes)
src/routes/__root.tsx14 lines
import { layout, Link } from "canica/client"
import { AppHeader, PageContainer, UserMenu } from "canica/ui"

export default layout({
  view: ({ children }) => (
    <>
      <AppHeader brand={<Link to="/">Todos</Link>}>
        <UserMenu />
      </AppHeader>
      <PageContainer>{children}</PageContainer>
    </>
  ),
})
src/routes/index.tsx103 lines
import { page, useAction, useMutation, useQuery } from "canica/client"
import {
  ActionStatus,
  Button,
  Checkbox,
  EmptyBlock,
  ErrorState,
  Item,
  ItemActions,
  ItemContent,
  ItemGroup,
  ItemMedia,
  ItemTitle,
  Loading,
  PageHeader,
  Thumbnail,
} from "canica/ui"
import { MailIcon, PlusIcon } from "canica/icons"
import { EmailProgress } from "../components/email-progress.tsx"
import { NewTodo } from "../components/new-todo.tsx"
import { TodoDetails } from "../components/todo-details.tsx"

export default page({
  title: "Todos",
  view: () => {
    const todos = useQuery("todos")
    const setDone = useMutation("setDone")
    const remove = useMutation("remove")
    // Emails me my open todos (server/emails.tsx); in dev it lands in the outbox at /_canica/dev/emails. The action
    // only queues it: <EmailProgress> follows the email live (queued → sending → sent or failed). If I signed in before
    // the app could email me, ActionStatus says so and offers "Sign in again" (canica/ui's EmailNeedsSignIn).
    const remindMe = useAction("remindMe")
    const newTodo = (
      <Button aria-haspopup="dialog" onClick={() => void NewTodo.open()}>
        <PlusIcon />
        New todo
      </Button>
    )

    return (
      <section className="flex flex-col gap-6">
        <PageHeader
          title="Todos"
          actions={
            <>
              <Button variant="outline" disabled={remindMe.waiting} onClick={() => void remindMe()}>
                <MailIcon />
                Email me my list
              </Button>
              {newTodo}
            </>
          }
        />
        <ActionStatus
          status={remindMe.status}
          success={remindMe.status._tag === "Success" && (remindMe.status.value.email ? <EmailProgress id={remindMe.status.value.email} /> : "Nothing open, so no email.")}
        />

        {todos.match({
          loading: () => <Loading shape="cards" />,
          failure: (error) => <ErrorState error={error} />,
          success: (list) =>
            list.length === 0 ? (
              <EmptyBlock title="Nothing to do" description="Add your first todo." action={newTodo} />
            ) : (
              <ItemGroup>
                {list.map((todo) => (
                  <Item key={todo.id} variant="outline">
                    <Checkbox
                      checked={todo.done}
                      onCheckedChange={(checked) => void setDone({ id: todo.id, done: checked === true })}
                    />
                    {todo.imageUrl && (
                      <ItemMedia>
                        <Thumbnail src={todo.imageUrl} alt={`Image of “${todo.text}”`} size="sm" />
                      </ItemMedia>
                    )}
                    <ItemContent>
                      <ItemTitle className={todo.done ? "line-through" : undefined}>{todo.text}</ItemTitle>
                    </ItemContent>
                    <ItemActions>
                      <Button
                        variant="ghost"
                        size="sm"
                        aria-haspopup="dialog"
                        onClick={async () => {
                          const r = await TodoDetails.open({ id: todo.id })
                          if (r._tag === "Done" && r.value === "delete") await remove({ id: todo.id })
                        }}
                      >
                        Open
                      </Button>
                    </ItemActions>
                  </Item>
                ))}
              </ItemGroup>
            ),
        })}
      </section>
    )
  },
})
src/components/email-progress.tsx49 lines
import { useQuery, type EmailFailure, type EmailId } from "canica/client"
import { EmailNeedsSignIn, Spinner } from "canica/ui"

/** Why an email failed, in the person's words. */
const why: Record<EmailFailure, string> = {
  unsubscribed: "you unsubscribed from these emails",
  "not-a-recipient": "this app may not email you any more",
  limit: "today's email limit",
  bounced: "your address bounced",
  complained: "you marked these emails as spam",
  suspended: "this app may not send email",
  off: "email is off on this platform",
  invalid: "the email was not valid",
  template: "the email could not be made",
  relay: "the mail service could not take it",
}

/**
 * Where my email is, live: Queued… → Sending… → Sent | Failed (why). Refused because the platform has no proof that
 * I signed in here: the way to fix it, a "Sign in again" button.
 */
export function EmailProgress({ id }: { readonly id: EmailId }) {
  const status = useQuery("emailStatus", { id })
  if (status.match({ loading: () => false, failure: () => false, success: (s) => s.state === "failed" && s.reason === "not-a-recipient" })) {
    return <EmailNeedsSignIn />
  }
  const text = status.match({
    loading: () => "Queued…",
    failure: () => "We can't tell where this email is.",
    success: (s) =>
      s.state === "queued"
        ? s.attempts > 0
          ? "Queued… (trying again soon)"
          : "Queued…"
        : s.state === "sending"
          ? "Sending…"
          : s.state === "sent"
            ? "Sent: check your inbox."
            : `Failed (${why[s.reason ?? "relay"]})`,
  })
  const busy = text.startsWith("Queued") || text === "Sending…"
  return (
    <span className="inline-flex items-center gap-2">
      {busy && <Spinner role="presentation" aria-hidden />}
      {text}
    </span>
  )
}
src/components/new-todo.tsx28 lines
import { useForm, useMutation, type Id } from "canica/client"
import { Button, Form, FormField, Input, modal, ModalActions, ModalTitle, SubmitButton } from "canica/ui"
import { todoText } from "../../shared/fields.ts"

/** Create a todo. Ends with the new todo's id: `const r = await NewTodo.open()`. */
export const NewTodo = modal<Id<"todos">>()(() => {
  const close = NewTodo.useClose()
  const addTodo = useMutation("addTodo")
  const form = useForm("add todo", { text: todoText }, (values) => addTodo(values), { onSuccess: close })

  return (
    <>
      <ModalTitle>New todo</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "TooManyTodos" ? `You can have at most ${e.max} todos. Delete some first.` : undefined)}>
        <FormField form={form} name="text" label="What needs doing?">
          <Input name="text" placeholder="Buy milk" autoComplete="off" autoFocus />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Add todo</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})
src/components/todo-details.tsx95 lines
import { formatDate, useForm, useMutation, useQuery, type Id } from "canica/client"
import {
  ActionStatus,
  Button,
  Checkbox,
  confirm,
  ErrorState,
  FileInput,
  Form,
  FormField,
  Input,
  Label,
  Loading,
  modal,
  ModalActions,
  ModalTitle,
  SubmitButton,
  Thumbnail,
} from "canica/ui"
import { todoText } from "../../shared/fields.ts"

/**
 * A todo's details: rename it, mark it done, attach an image. Asking to delete it ends the modal with "delete"; the caller deletes:
 * `if ((await TodoDetails.open({ id })).value === "delete") …`.
 */
export const TodoDetails = modal<"delete">()(({ id }: { id: Id<"todos"> }) => {
  const close = TodoDetails.useClose()
  // Live: a change from another tab shows up here while it is open.
  const todo = useQuery("todo", { id })
  const rename = useMutation("rename")
  const setDone = useMutation("setDone")
  const setImage = useMutation("setImage")
  const form = useForm("rename todo", { text: todoText }, (values) => rename({ id, ...values }))

  return (
    <>
      <ModalTitle>Todo</ModalTitle>
      {todo.match({
        loading: () => <Loading shape="text" />,
        failure: (error) => <ErrorState error={error} states={{ NotFound: { title: "This todo was deleted" } }} />,
        success: (t) => (
          <div className="flex flex-col gap-5">
            <Form form={form} key={t.updatedAt}>
              <FormField form={form} name="text" label="Name">
                <div className="flex gap-2">
                  <Input name="text" defaultValue={t.text} />
                  <SubmitButton form={form} variant="outline">
                    Save
                  </SubmitButton>
                </div>
              </FormField>
            </Form>

            <div className="flex items-center justify-between gap-3">
              <Label>
                <Checkbox checked={t.done} onCheckedChange={(checked) => void setDone({ id, done: checked === true })} />
                <span>Done</span>
              </Label>
              <ActionStatus status={setDone.status} success="Saved" />
            </div>

            {t.imageUrl ? (
              <div className="flex flex-col items-start gap-3">
                <Thumbnail src={t.imageUrl} alt={`Image of “${t.text}”`} size="xl" />
                <Button variant="outline" size="sm" onClick={() => void setImage({ id })}>
                  Remove image
                </Button>
              </div>
            ) : (
              <FileInput label="Image" accept="image/png,image/jpeg,image/webp,image/gif" description="PNG, JPEG, WebP or GIF, up to 25 MB" onUpload={(image) => void setImage({ id, image })} />
            )}
            <ActionStatus status={setImage.status} />

            <p className="text-sm text-muted-foreground">Created {formatDate(t.createdAt)}</p>
          </div>
        ),
      })}
      <ModalActions>
        <Button
          variant="destructive"
          aria-haspopup="dialog"
          onClick={async () => {
            if ((await confirm({ title: "Delete this todo?", confirm: "Delete" }))._tag === "Done") close("delete")
          }}
        >
          Delete
        </Button>
        <Button variant="outline" onClick={close.cancel}>
          Close
        </Button>
      </ModalActions>
    </>
  )
})
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
 * App theme: shadcn preset b2vjanf10s (style luma, fuchsia on stone, font eb-garamond, radius none).
 * Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b2vjanf10s
 * and apply the new code with `canica theme <code>`, or edit these tokens by hand.
 */
:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.147 0.004 49.25);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.147 0.004 49.25);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.147 0.004 49.25);
  --primary: oklch(0.518 0.253 323.949);
  --primary-foreground: oklch(0.977 0.017 320.058);
  --secondary: oklch(0.967 0.001 286.375);
  --secondary-foreground: oklch(0.21 0.006 285.885);
  --muted: oklch(0.97 0.001 106.424);
  --muted-foreground: oklch(0.553 0.013 58.071);
  --accent: oklch(0.97 0.001 106.424);
  --accent-foreground: oklch(0.216 0.006 56.043);
  --destructive: oklch(0.577 0.245 27.325);
  --border: oklch(0.923 0.003 48.717);
  --input: oklch(0.923 0.003 48.717);
  --ring: oklch(0.709 0.01 56.259);
  --chart-1: oklch(0.865 0.127 207.078);
  --chart-2: oklch(0.715 0.143 215.221);
  --chart-3: oklch(0.609 0.126 221.723);
  --chart-4: oklch(0.52 0.105 223.128);
  --chart-5: oklch(0.45 0.085 224.283);
  --radius: 0;
  --font-body: "EB Garamond", ui-sans-serif, system-ui, sans-serif;
  --font-display: "Outfit", ui-serif, Georgia, serif;
}

.dark {
  --background: oklch(0.147 0.004 49.25);
  --foreground: oklch(0.985 0.001 106.423);
  --card: oklch(0.216 0.006 56.043);
  --card-foreground: oklch(0.985 0.001 106.423);
  --popover: oklch(0.216 0.006 56.043);
  --popover-foreground: oklch(0.985 0.001 106.423);
  --primary: oklch(0.452 0.211 324.591);
  --primary-foreground: oklch(0.977 0.017 320.058);
  --secondary: oklch(0.274 0.006 286.033);
  --secondary-foreground: oklch(0.985 0 0);
  --muted: oklch(0.268 0.007 34.298);
  --muted-foreground: oklch(0.709 0.01 56.259);
  --accent: oklch(0.268 0.007 34.298);
  --accent-foreground: oklch(0.985 0.001 106.423);
  --destructive: oklch(0.704 0.191 22.216);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 15%);
  --ring: oklch(0.553 0.013 58.071);
  --chart-1: oklch(0.865 0.127 207.078);
  --chart-2: oklch(0.715 0.143 215.221);
  --chart-3: oklch(0.609 0.126 221.723);
  --chart-4: oklch(0.52 0.105 223.128);
  --chart-5: oklch(0.45 0.085 224.283);
}
server/index.test.ts112 lines
import { describe, expect, it } from "vitest"
import { testApp } from "canica/testing"
import app from "./index.ts"
import { emails } from "./emails.tsx"

describe("todos", () => {
  it("each user only sees and changes their own todos", () => {
    const t = testApp(app)
    const alice = t.as("alice")
    const bob = t.as("bob")
    const added = alice.mutation("addTodo", { text: "  buy milk " })
    expect(added._tag).toBe("Success")
    expect(alice.query("todos")).toMatchObject({ _tag: "Success", value: [{ text: "buy milk", done: false }] })
    expect(bob.query("todos")).toEqual({ _tag: "Success", value: [] })
    if (added._tag !== "Success") return
    expect(bob.mutation("setDone", { id: added.value, done: true })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
    expect(alice.mutation("setDone", { id: added.value, done: true })._tag).toBe("Success")
  })

  it("needs signing in: a visitor without an account gets nothing and can change nothing", () => {
    const t = testApp(app)
    const visitor = t.as("visitor", { signedIn: false })
    expect(visitor.query("todos")).toMatchObject({ _tag: "Failure", error: { _tag: "Unauthenticated" } })
    expect(visitor.mutation("addTodo", { text: "x" })).toMatchObject({ _tag: "Failure", error: { _tag: "Unauthenticated" } })
  })

  it("rejects empty text with a field error", () => {
    const t = testApp(app)
    expect(t.as("alice").mutation("addTodo", { text: "   " })).toMatchObject({
      _tag: "Failure",
      error: { _tag: "InvalidArgs", issues: [{ path: ["text"] }] },
    })
  })

  it("a todo's image: only the owner's upload, a private link, deleted when replaced or with the todo", async () => {
    const t = testApp(app)
    const alice = t.as("alice")
    const todo = alice.mutationOk("addTodo", { text: "Paint the fence" })
    const png = new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3])], { type: "image/png" })
    const first = await alice.uploadOk(png, "fence.png")
    alice.mutationOk("setImage", { id: todo, image: first })
    const [shown] = alice.queryOk("todos")
    expect(shown).toMatchObject({ image: first, imageUrl: expect.stringMatching(/^\/_canica\/files\/_files_\w+\?m=640&/) })
    // At most 640 px wide (resized once, as WebP); the list's thumbnails ask 160 of the same link, not more.
    const res = await t.fetch(shown!.imageUrl!)
    expect([res.status, res.headers.get("content-type")]).toEqual([200, "image/webp"])
    expect((await t.fetch(`${shown!.imageUrl!}&w=160`)).status).toBe(200)
    expect((await t.fetch(`${shown!.imageUrl!}&w=1280`)).status).toBe(403)
    // Bob cannot attach Alice's image to his own todo, nor touch hers.
    const bobs = t.as("bob").mutationOk("addTodo", { text: "Mine" })
    expect(t.as("bob").mutation("setImage", { id: bobs, image: await alice.uploadOk(png, "x.png") })).toMatchObject({ _tag: "Failure", error: { _tag: "FileNotFound" } })
    expect(t.as("bob").mutation("setImage", { id: todo })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
    // Replacing deletes the old file; deleting the todo deletes the new one.
    const second = await alice.uploadOk(png, "fence2.png")
    alice.mutationOk("setImage", { id: todo, image: second })
    expect((await t.fetch(shown!.imageUrl!)).status).toBe(404)
    alice.mutationOk("remove", { id: todo })
    await t.advance(1)
    expect(t.engine.files.meta(second)).toBeUndefined()
  })

  it("remindMe emails me my open todos (only mine, only open ones); nothing open sends nothing", async () => {
    const t = testApp(app)
    const alice = t.as("alice")
    expect(await alice.actionOk("remindMe")).toEqual({ open: 0, email: null })
    expect(t.emails()).toEqual([])
    alice.mutationOk("addTodo", { text: "Buy milk" })
    const done = alice.mutationOk("addTodo", { text: "Call mum" })
    alice.mutationOk("setDone", { id: done, done: true })
    t.as("bob").mutationOk("addTodo", { text: "Bob's secret" })
    const sent = await alice.actionOk("remindMe")
    expect(sent).toEqual({ open: 1, email: t.emails()[0]!.id })
    expect(t.emails()).toMatchObject([
      { template: "todayDigest", to: alice.viewer.userId, email: "alice@example.com", props: { name: "alice", todos: ["Buy milk"], more: 0 }, subject: "Your todos for today (1)" },
    ])
    const { html, text } = t.emails()[0]!.render()
    expect(text).toContain("Hi alice, you have 1 open todo:")
    expect(text).toContain("Buy milk")
    expect(text).not.toContain("Bob's secret")
    expect(text).toMatch(/You're getting this because you use Todos/)
    expect(html).toContain("Unsubscribe")
  })

  it("remindMe after unsubscribing fails with Unsubscribed; ten a day at most", async () => {
    const t = testApp(app)
    const alice = t.as("alice")
    alice.mutationOk("addTodo", { text: "Buy milk" })
    for (let i = 0; i < 10; i++) await alice.actionOk("remindMe")
    expect(await alice.action("remindMe")).toMatchObject({ _tag: "Failure", error: { _tag: "EmailLimitReached", per: "recipient" } })
    alice.unsubscribeFromEmails()
    await t.advance(24 * 3600_000)
    expect(await alice.action("remindMe")).toMatchObject({ _tag: "Failure", error: { _tag: "Unsubscribed" } })
  })

  it("emailStatus follows my email: queued, then sent; only I can see it", async () => {
    const t = testApp(app)
    const alice = t.as("alice")
    alice.mutationOk("addTodo", { text: "Buy milk" })
    const { email } = await alice.actionOk("remindMe")
    expect(alice.queryOk("emailStatus", { id: email! })).toEqual({ state: "queued", reason: null, attempts: 0 })
    await t.advance(0)
    expect(alice.queryOk("emailStatus", { id: email! })).toEqual({ state: "sent", reason: null, attempts: 1 })
    expect(t.as("bob").query("emailStatus", { id: email! })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
  })

  it("the digest template renders its preview", () => {
    const { html, text } = emails.todayDigest["~render"](emails.todayDigest.preview)
    expect(html).toContain("Your todos for today")
    expect(text).toContain("Book the dentist")
  })
})
src/app.test.tsx196 lines
import { describe, expect, it } from "vitest"
import { as, click, label, meanwhile, notSee, role, scene, see, testApp, text, type, upload, visit, within } from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"

describe("todos (scenes)", () => {
  it("a visitor who has not signed in sees the sign-in screen on every route", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Buy milk" })
    await scene(t, routes,
      as("visitor", { signedIn: false }),
      visit("/"),
      see(role("heading", { name: "Todos", level: 1 })),
      see(text(/Anyone with a Google account can use it/)),
      see(role("button", { name: "Sign in with Google" })),
      notSee(role("button", { name: /Sign in as/ })),
      notSee(text("Buy milk")),
      notSee(role("button", { name: "New todo" })),
    )
  })

  it("adds a todo from the New todo modal and checks it off", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/"),
      see(text("Nothing to do")),
      click(role("button", { name: "New todo" })),
      within(role("dialog", { name: "New todo" }), type(label("What needs doing?"), "Buy milk"), click(role("button", { name: "Add todo" }))),
      notSee(role("dialog")), // it closes on success
      see(text("Buy milk")),
      click(role("checkbox")),
      see(role("checkbox", { checked: true })),
    )
  })

  it("the create modal words its errors and stays open; Cancel adds nothing", async () => {
    const t = testApp(app)
    for (let i = 0; i < 200; i++) t.as("ana").mutationOk("addTodo", { text: `Todo ${i}` })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "New todo" })),
      within(role("dialog"), click(role("button", { name: "Add todo" })), see(text("Required"))),
      within(role("dialog"), type(label("What needs doing?"), "One too many"), click(role("button", { name: "Add todo" }))),
      within(role("dialog"), see(text("You can have at most 200 todos. Delete some first."))),
      within(role("dialog"), click(role("button", { name: "Cancel" }))),
      notSee(role("dialog")),
      notSee(text("One too many")),
    )
  })

  it("the details modal renames, checks off and deletes a todo", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Buy milk" })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Open" })),
      within(role("dialog"), type(label("Name"), "Buy oat milk"), click(role("button", { name: "Save" }))),
      see(text("Buy oat milk")), // the list behind the modal is live
      within(role("dialog"),
        click(role("checkbox", { name: "Done" })),
        see(role("checkbox", { name: "Done", checked: true })),
        type(label("Name"), "Unsaved draft"),
        click(role("button", { name: "Delete" })),
      ),
      // One modal at a time: the confirmation hides the details; cancelling brings them back as they were.
      notSee(role("dialog")),
      within(role("alertdialog"), click(role("button", { name: "Cancel" }))),
      within(role("dialog"), see(role("textbox", { name: "Name" }))),
      meanwhile(() => expect(document.querySelector<HTMLInputElement>("[role=dialog] input[name=text]")?.value).toBe("Unsaved draft")),
      within(role("dialog"), click(role("button", { name: "Delete" }))),
      within(role("alertdialog"), click(role("button", { name: "Delete" }))),
      notSee(role("dialog")),
      see(text("Nothing to do")),
    )
  })

  it("todos are private and live", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/"),
      meanwhile(() => t.as("ana").mutationOk("addTodo", { text: "From another tab" })),
      see(text("From another tab")),
      as("bob"),
      notSee(text("From another tab")),
    )
  })

  it("a modal left open does not leak into the next scene; values from earlier steps", async () => {
    const t = testApp(app)
    let todo = ""
    await scene(t, routes,
      as("ana"),
      meanwhile(() => {
        todo = t.as("ana").mutationOk("addTodo", { text: "Water plants" }) ? "Water plants" : ""
      }),
      visit("/"),
      click(role("button", { name: "Open" })),
      within(role("dialog"), see(label("Name"))),
    )
    await scene(t, routes,
      as("ana"),
      visit("/"),
      notSee(role("dialog")),
      see(text(() => todo)),
    )
  })

  it("attaches an image from the details modal and shows it as a thumbnail", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Paint the fence" })
    const png = new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3])], "fence.png", { type: "image/png" })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Open" })),
      within(role("dialog"), upload(label("Image"), png), see(role("img", { name: "Image of “Paint the fence”" }))),
      within(role("dialog"), click(role("button", { name: "Close" }))),
      see(role("img", { name: "Image of “Paint the fence”" })), // in the list
      click(role("button", { name: "Open" })),
      within(role("dialog"), click(role("button", { name: "Remove image" })), see(label("Image"))),
      within(role("dialog"), click(role("button", { name: "Close" }))),
      notSee(role("img")),
    )
  })

  it("Email me my list shows where the email is, live: Queued…, then Sent", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Buy milk" })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Email me my list" })),
      see(text("Queued…")),
      notSee(text(/Sent/)),
      meanwhile(() => t.advance(0)), // the job delivers it (tests never send; the app sees it as sent)
      see(text("Sent: check your inbox.")),
    )
    expect(t.emails()).toMatchObject([{ template: "todayDigest", subject: "Your todos for today (1)", props: { todos: ["Buy milk"] }, status: "sent" }])
  })

  it("Email me my list: Sent once the relay sends it; Failed (why) when it refuses", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Buy milk" })
    ;(t.engine as any).mailTransport = { deliver: async () => ({ status: "sent", messageId: "m-1" }) }
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Email me my list" })),
      see(text("Queued…")),
      meanwhile(() => t.advance(0)),
      see(text("Sent: check your inbox.")),
    )
    ;(t.engine as any).mailTransport = { deliver: async () => ({ status: "refused", reason: "limit", message: "This app sent its 100 emails for today." }) }
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Email me my list" })),
      meanwhile(() => t.advance(0)),
      see(text("Failed (today's email limit)")),
    )
  })

  it("Email me my list, signed in from before the app could email me: says so to me, and Sign in again fixes it", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("addTodo", { text: "Buy milk" })
    // Deployed: the relay needs the sign-in service's proof, which ana's account (an older session) does not have.
    ;(t.engine as any).mailTransport = { requireProof: true, deliver: async () => ({ status: "sent", messageId: "m-1" }) }
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Email me my list" })),
      see(text("To get emails from Todos, confirm your email by signing in again.")),
      notSee(text(/This person/)),
      notSee(role("alert")),
      click(role("button", { name: "Sign in again" })), // the usual sign-in, back to this page
      notSee(role("button", { name: "Sign in again" })),
      click(role("button", { name: "Email me my list" })),
      see(text("Queued…")),
      meanwhile(() => t.advance(0)),
      see(text("Sent: check your inbox.")),
    )
    expect(t.engine.sql.exec(`SELECT proof FROM _canica_accounts WHERE user_id = ?`, t.as("ana").viewer.userId)).toEqual([{ proof: "test-proof" }])
    expect(t.emails()).toMatchObject([{ template: "todayDigest", status: "sent" }])
  })

  it("Email me my list with nothing open sends nothing", async () => {
    const t = testApp(app)
    await scene(t, routes, as("ana"), visit("/"), click(role("button", { name: "Email me my list" })), see(text("Nothing open, so no email.")))
    expect(t.emails()).toEqual([])
  })
})