Canica

Kanban

Boards with members, columns and cards.

sharing with membersorderingnested routes

15 files, 509 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in apps/kanban.

Files

server/index.ts149 lines
import { and, asc, eq, id, inArray, literal, mutation, NotFound, number, query, schema, table, TaggedError, userId, Viewer, type Id } from "canica/server"
import { title, description } from "../shared/fields.ts"

export const { app, Db, tables } = schema({
  boards: table({ title, owner: userId() }),
  members: table({ board: id("boards").onDelete("cascade"), user: userId() }).unique("board_user", ["board", "user"]).index("by_user", ["user"]),
  columns: table({ board: id("boards").onDelete("cascade"), title, position: number().int().min(0) }).index("by_board", ["board"]),
  cards: table({ board: id("boards").onDelete("cascade"), column: id("columns").onDelete("cascade"), title, description, position: number().int().min(0) }).index("by_board", ["board"]).index("by_column", ["column"]),
})
const { boards, members, columns, cards } = tables
export class NotMember extends TaggedError("NotMember") {}
export class OwnerOnly extends TaggedError("OwnerOnly") {}
export class ColumnNotEmpty extends TaggedError("ColumnNotEmpty") {}
export class WrongBoard extends TaggedError("WrongBoard") {}
export class CannotRemoveOwner extends TaggedError("CannotRemoveOwner") {}
function* member(board: Id<"boards">) {
  const db = yield* Db
  const b = yield* db.get(boards, board)
  const viewer = yield* Viewer
  const [m] = yield* db.select().from(members).where(and(eq(members.board, board), eq(members.user, viewer.userId)))
  if (!m) return yield* new NotMember()
  return b
}
function* columnAccess(column: Id<"columns">) {
  const db = yield* Db
  const c = yield* db.get(columns, column)
  yield* member(c.board)
  return c
}
function* cardAccess(board: Id<"boards">, card: Id<"cards">) {
  const db = yield* Db
  const c = yield* db.get(cards, card)
  if (c.board !== board) return yield* new NotFound({ table: "cards", id: card })
  yield* member(board)
  return c
}
export default app({
  name: "Gather · Kanban",
  queries: {
    boards: query(function* () {
      const db = yield* Db
      const viewer = yield* Viewer
      const mine = yield* db.select().from(members).where(eq(members.user, viewer.userId))
      return yield* db.select().from(boards).where(inArray(boards.id, mine.map(m => m.board))).orderBy(asc(boards.createdAt), asc(boards.id))
    }),
    board: query({ board: id("boards") }, function* ({ board }) {
      const b = yield* member(board)
      const db = yield* Db
      const viewer = yield* Viewer
      return { ...b, isOwner: b.owner === viewer.userId,
        members: yield* db.select().from(members).where(eq(members.board, board)).orderBy(asc(members.createdAt), asc(members.id)),
        columns: yield* db.select().from(columns).where(eq(columns.board, board)).orderBy(asc(columns.position), asc(columns.id)),
        cards: yield* db.select().from(cards).where(eq(cards.board, board)).orderBy(asc(cards.position), asc(cards.id)),
      }
    }),
    card: query({ board: id("boards"), card: id("cards") }, function* ({ board, card }) { return yield* cardAccess(board, card) }),
  },
  mutations: {
    createBoard: mutation({ title }, function* ({ title }) {
      const db = yield* Db
      const viewer = yield* Viewer
      const [b] = yield* db.insert(boards).values({ title, owner: viewer.userId }).returning()
      yield* db.insert(members).values({ board: b!.id, user: viewer.userId })
      return b!.id
    }),
    join: mutation({ board: id("boards") }, function* ({ board }) {
      const db = yield* Db
      yield* db.get(boards, board)
      const viewer = yield* Viewer
      const [m] = yield* db.select().from(members).where(and(eq(members.board, board), eq(members.user, viewer.userId)))
      if (!m) yield* db.insert(members).values({ board, user: viewer.userId })
    }),
    removeMember: mutation({ board: id("boards"), member: id("members") }, function* ({ board, member: mid }) {
      const db = yield* Db
      const b = yield* member(board)
      const viewer = yield* Viewer
      if (viewer.userId !== b.owner) return yield* new OwnerOnly()
      const m = yield* db.get(members, mid)
      if (m.board !== board) return yield* new WrongBoard()
      if (m.user === b.owner) return yield* new CannotRemoveOwner()
      yield* db.delete(members).where(eq(members.id, mid))
    }),
    createColumn: mutation({ board: id("boards"), title }, function* ({ board, title }) {
      yield* member(board)
      const db = yield* Db
      const rows = yield* db.select().from(columns).where(eq(columns.board, board)).orderBy(asc(columns.position))
      const [c] = yield* db.insert(columns).values({ board, title, position: (rows.at(-1)?.position ?? -1) + 1 }).returning()
      return c!.id
    }),
    renameColumn: mutation({ column: id("columns"), title }, function* ({ column, title }) {
      yield* columnAccess(column)
      const db = yield* Db
      yield* db.update(columns).set({ title }).where(eq(columns.id, column))
    }),
    deleteColumn: mutation({ column: id("columns") }, function* ({ column }) {
      yield* columnAccess(column)
      const db = yield* Db
      if (yield* db.count(cards, eq(cards.column, column))) return yield* new ColumnNotEmpty()
      yield* db.delete(columns).where(eq(columns.id, column))
    }),
    moveColumn: mutation({ column: id("columns"), direction: literal("left", "right") }, function* ({ column, direction }) {
      const c = yield* columnAccess(column)
      const db = yield* Db
      const rows = yield* db.select().from(columns).where(eq(columns.board, c.board)).orderBy(asc(columns.position))
      const other = rows[rows.findIndex(r => r.id === column) + (direction === "left" ? -1 : 1)]
      if (other) {
        yield* db.update(columns).set({ position: other.position }).where(eq(columns.id, column))
        yield* db.update(columns).set({ position: c.position }).where(eq(columns.id, other.id))
      }
    }),
    createCard: mutation({ column: id("columns"), title }, function* ({ column, title }) {
      const c = yield* columnAccess(column)
      const db = yield* Db
      const rows = yield* db.select().from(cards).where(eq(cards.column, column)).orderBy(asc(cards.position))
      const [card] = yield* db.insert(cards).values({ board: c.board, column, title, description: "", position: (rows.at(-1)?.position ?? -1) + 1 }).returning()
      return card!.id
    }),
    editCard: mutation({ board: id("boards"), card: id("cards"), title, description }, function* ({ board, card, title, description }) {
      yield* cardAccess(board, card)
      const db = yield* Db
      yield* db.update(cards).set({ title, description }).where(eq(cards.id, card))
    }),
    moveCard: mutation({ board: id("boards"), card: id("cards"), column: id("columns") }, function* ({ board, card, column }) {
      const c = yield* cardAccess(board, card)
      const target = yield* columnAccess(column)
      if (target.board !== board) return yield* new WrongBoard()
      if (c.column === column) return
      const db = yield* Db
      const rows = yield* db.select().from(cards).where(eq(cards.column, column)).orderBy(asc(cards.position))
      yield* db.update(cards).set({ column, position: (rows.at(-1)?.position ?? -1) + 1 }).where(eq(cards.id, card))
    }),
    reorderCard: mutation({ board: id("boards"), card: id("cards"), direction: literal("up", "down") }, function* ({ board, card, direction }) {
      const c = yield* cardAccess(board, card)
      const db = yield* Db
      const rows = yield* db.select().from(cards).where(eq(cards.column, c.column)).orderBy(asc(cards.position))
      const other = rows[rows.findIndex(r => r.id === card) + (direction === "up" ? -1 : 1)]
      if (other) {
        yield* db.update(cards).set({ position: other.position }).where(eq(cards.id, card))
        yield* db.update(cards).set({ position: c.position }).where(eq(cards.id, other.id))
      }
    }),
    deleteCard: mutation({ board: id("boards"), card: id("cards") }, function* ({ board, card }) {
      yield* cardAccess(board, card)
      const db = yield* Db
      yield* db.delete(cards).where(eq(cards.id, card))
    }),
  },
})
server/seed.ts26 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"
export default defineSeed(app, ({ as }) => {
  const me = as("viewer")
  const board = me.mutationOk("createBoard", { title: "Studio website launch" })
  as("Ana").mutationOk("join", { board })
  as("Luca").mutationOk("join", { board })
  const columns = ["To do", "In progress", "Ready to ship"].map(title => me.mutationOk("createColumn", { board, title }))
  const tasks = [
    ["Write the studio story", "Tell visitors who we are, what we care about, and how we work. Include a short introduction from the team.", 0],
    ["Choose project photography", "Select six images for the case study gallery. Check usage permissions before publishing.", 0],
    ["Build the project gallery", "Responsive grid is ready. Review keyboard navigation and image descriptions with Ana.", 1],
    ["Review mobile navigation", "Test the menu on a small screen and make sure every destination is easy to reach.", 1],
    ["Connect the custom domain", "DNS records are verified. Schedule the final switch for launch morning.", 2],
  ] as const
  let card = ""
  for (const [title, description, i] of tasks) {
    const c = me.mutationOk("createCard", { column: columns[i]!, title })
    me.mutationOk("editCard", { board, card: c, title, description })
    if (!card) card = c
  }
  const empty = me.mutationOk("createBoard", { title: "Ideas for next season" })
  const invitation = as("Marta").mutationOk("createBoard", { title: "Community workshop" })
  return { captures: { "/boards/$board": [{ board }, { board: empty }, { board: invitation }], "/boards/$board/cards/$card": [{ board, card }] } }
})
shared/fields.ts4 lines
import { string } from "canica/fields"
export const title = string().trim().min(1).max(100)
export const description = string().trim().max(5000)
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 size="lg" brand={<Link to="/">Gather · Kanban</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. */
export default page({
  title: "Not found",
  view: () => (
    <PageContainer>
      <EmptyBlock
        title="This page does not exist"
        description="The link may be wrong, or what it pointed to was deleted."
        action={
          <Button asChild>
            <Link to="/">Back home</Link>
          </Button>
        }
      />
    </PageContainer>
  ),
})
src/routes/boards/$board.tsx9 lines
import { id, page, useMutation, useQuery } from "canica/client"
import { ActionStatus, Button, ErrorState, Loading } from "canica/ui"
import { Board } from "../../components/board.tsx"
export default page({ params: { board: id("boards") }, title: "Board", view: ({ params }) => {
  const board = useQuery("board", params)
  const join = useMutation("join")
  return board.match({ loading: () => <Loading shape="cards" />, failure: e => <><ErrorState error={e} states={{ NotMember: { title: "You're invited", description: "Join this board to see the work and collaborate.", action: <Button disabled={join.waiting} onClick={() => void join(params)}>Join board</Button> }, NotFound: { title: "Board not found", description: "Check the link with the person who shared it." } }} /><ActionStatus status={join.status} /></>, success: b => <Board board={b} /> })
} })
src/routes/boards/$board/cards/$card.tsx8 lines
import { id, Link, page, useQuery } from "canica/client"
import { Button, ErrorState, Loading } from "canica/ui"
import { CardDetail } from "../../../../components/card-detail.tsx"
export default page({ params: { board: id("boards"), card: id("cards") }, title: "Card", view: ({ params }) => {
  const card = useQuery("card", params)
  return card.match({ loading: () => <Loading shape="text" />, failure: e => <ErrorState error={e} states={{ NotMember: { title: "Join the board first", description: "Open the board link to become a collaborator.", action: <Button asChild><Link to="/boards/$board" params={{ board: params.board }}>Open board</Link></Button> }, NotFound: { title: "Card not found", description: "This card may have been deleted or belong to another board." } }} />, success: c => <CardDetail card={c} /> })
} })
src/routes/index.tsx15 lines
import { formatDate, Link, page, useForm, useMutation, useNavigate, useQuery, type Id } from "canica/client"
import { Button, EmptyBlock, ErrorState, Form, FormField, Input, Item, ItemContent, ItemDescription, ItemTitle, List, Loading, modal, ModalActions, ModalTitle, PageHeader, SubmitButton } from "canica/ui"
import { title } from "../../shared/fields.ts"
const NewBoard = modal<Id<"boards">>()(() => {
  const close = NewBoard.useClose()
  const create = useMutation("createBoard")
  const form = useForm("create board", { title }, v => create(v), { onSuccess: close })
  return <><ModalTitle>Create a board</ModalTitle><Form form={form}><FormField form={form} name="title" label="Board name"><Input name="title" autoFocus placeholder="e.g. Website launch" /></FormField><ModalActions><Button variant="outline" onClick={close.cancel}>Cancel</Button><SubmitButton form={form}>Create board</SubmitButton></ModalActions></Form></>
})
export default page({ title: "Your boards", view: () => {
  const boards = useQuery("boards")
  const open = useNavigate("/boards/$board")
  return <><PageHeader title="Your boards" description="A shared space to move good work forward." actions={<Button aria-haspopup="dialog" onClick={async () => { const r = await NewBoard.open(); if (r._tag === "Done") open({ board: r.value }) }}>New board</Button>} />{boards.match({ loading: () => <Loading shape="cards" />, failure: e => <ErrorState error={e} />, success: list => list.length ? <List>{list.map(b => <Item key={b.id} variant="outline"><ItemContent><ItemTitle><Link to="/boards/$board" params={{ board: b.id }}><span className="break-words">{b.title}</span></Link></ItemTitle><ItemDescription>Created {formatDate(b.createdAt)}</ItemDescription></ItemContent></Item>)}</List> : <EmptyBlock title="Make room for your next project" description="Create a board, add columns, then share its link with your team." /> })}</>
} })
src/components/board.tsx18 lines
import { Link, useMutation, type QueryValue } from "canica/client"
import { ActionStatus, Badge, Button, confirm, CopyButton, EmptyBlock, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, List, PageHeader, prompt, Section } from "canica/ui"
import { title } from "../../shared/fields.ts"
type BoardData = QueryValue<"board">
export function Board({ board: b }: { board: BoardData }) {
  const create = useMutation("createColumn")
  const remove = useMutation("removeMember")
  return <><PageHeader title={<span className="break-words">{b.title}</span>} back={<Link to="/">← Your boards</Link>} description="Plan together. Changes appear live for everyone." actions={<><CopyButton>Copy invite link</CopyButton><Button aria-haspopup="dialog" onClick={async () => { const r = await prompt({ title: "Add a column", label: "Column name", field: title }); if (r._tag === "Done") await create({ board: b.id, title: r.value }) }}>Add column</Button></>} /><ActionStatus status={create.status} success="Column added" />{b.columns.length ? <div className="grid min-w-0 grid-cols-1 items-start gap-6 md:grid-cols-2 lg:grid-cols-3">{b.columns.map((c, i) => <BoardColumn key={c.id} board={b} column={c} index={i} />)}</div> : <EmptyBlock title="Start with a column" description="Add stages such as To do, In progress and Done." />}<Section title="People" description="Anyone with the invite link can join this board."><List>{b.members.map((m, i) => <Item key={m.id}><ItemContent><ItemTitle>{m.user === b.owner ? "Board owner" : `Collaborator ${i + 1}`}</ItemTitle><ItemDescription>{m.user === b.owner ? "Created this workspace" : "Can add, edit and move work"}</ItemDescription></ItemContent>{b.isOwner && m.user !== b.owner && <ItemActions><Button variant="outline" size="sm" aria-haspopup="dialog" onClick={async () => { if ((await confirm({ title: "Remove this collaborator?", description: "They can join again using the board link.", confirm: "Remove member" }))._tag === "Done") await remove({ board: b.id, member: m.id }) }}>Remove member</Button></ItemActions>}</Item>)}</List><ActionStatus status={remove.status} success="Member removed" /></Section></>
}
function BoardColumn({ board: b, column: c, index }: { board: BoardData; column: BoardData["columns"][number]; index: number }) {
  const rename = useMutation("renameColumn")
  const remove = useMutation("deleteColumn")
  const move = useMutation("moveColumn")
  const add = useMutation("createCard")
  const cards = b.cards.filter(card => card.column === c.id)
  return <div className="min-w-0 rounded-lg border border-border bg-muted/30 p-4"><Section title={<span className="break-words">{c.title} <Badge variant="secondary">{cards.length}</Badge></span>}><div className="flex flex-wrap gap-1"><Button variant="ghost" size="sm" disabled={index === 0 || move.waiting} aria-label={`Move ${c.title} left`} onClick={() => void move({ column: c.id, direction: "left" })}>←</Button><Button variant="ghost" size="sm" disabled={index === b.columns.length - 1 || move.waiting} aria-label={`Move ${c.title} right`} onClick={() => void move({ column: c.id, direction: "right" })}>→</Button><Button variant="ghost" size="sm" aria-haspopup="dialog" onClick={async () => { const r = await prompt({ title: "Rename column", label: "Column name", field: title, defaultValue: c.title }); if (r._tag === "Done") await rename({ column: c.id, title: r.value }) }}>Rename</Button><Button variant="ghost" size="sm" disabled={cards.length > 0} aria-haspopup="dialog" onClick={async () => { if ((await confirm({ title: "Delete empty column?", confirm: "Delete column" }))._tag === "Done") await remove({ column: c.id }) }}>Delete</Button></div>{cards.length ? <List>{cards.map(card => <Item key={card.id} variant="outline"><ItemContent><ItemTitle><Link to="/boards/$board/cards/$card" params={{ board: b.id, card: card.id }}><span className="break-words">{card.title}</span></Link></ItemTitle><ItemDescription><span className="line-clamp-2 break-words">{card.description || "Open to add details"}</span></ItemDescription></ItemContent></Item>)}</List> : <EmptyBlock title="No cards yet" description="Add the first next step." />}<Button variant="outline" aria-haspopup="dialog" onClick={async () => { const r = await prompt({ title: "Add a card", label: "Card title", field: title }); if (r._tag === "Done") await add({ column: c.id, title: r.value }) }}>Add card to {c.title}</Button><ActionStatus status={add.status} success="Card added" /><ActionStatus status={rename.status} success="Column renamed" /><ActionStatus status={move.status} success="Column moved" /><ActionStatus status={remove.status} success="Column deleted" /></Section></div>
}
src/components/card-detail.tsx19 lines
import { id, Link, useForm, useMutation, useNavigate, useQuery, type QueryValue } from "canica/client"
import { ActionStatus, Button, confirm, ErrorState, Form, FormField, Input, Loading, NativeSelect, NativeSelectOption, PageHeader, Section, SubmitButton, Textarea } from "canica/ui"
import { description, title } from "../../shared/fields.ts"
export function CardDetail({ card: c }: { card: QueryValue<"card"> }) {
  const edit = useMutation("editCard")
  const remove = useMutation("deleteCard")
  const reorder = useMutation("reorderCard")
  const move = useMutation("moveCard")
  const board = useQuery("board", { board: c.board })
  const back = useNavigate("/boards/$board")
  const form = useForm("edit card", { title, description }, v => edit({ board: c.board, card: c.id, ...v }))
  const moveForm = useForm("move card", { column: id("columns") }, v => move({ board: c.board, card: c.id, ...v }))
  return <><PageHeader title={<span className="break-words">{c.title}</span>} back={<Link to="/boards/$board" params={{ board: c.board }}>← Back to board</Link>} description="Give the next person the context they need." actions={<Button variant="destructive" aria-haspopup="dialog" onClick={async () => { if ((await confirm({ title: "Delete this card?", description: "This cannot be undone.", confirm: "Delete card" }))._tag === "Done" && (await remove({ board: c.board, card: c.id }))._tag === "Success") back({ board: c.board }) }}>Delete card</Button>} /><ActionStatus status={remove.status} /><div className="max-w-2xl"><Form key={`${c.title}:${c.description}`} form={form}><FormField form={form} name="title" label="Card title"><Input name="title" defaultValue={c.title} /></FormField><FormField form={form} name="description" label="Description"><Textarea name="description" defaultValue={c.description} rows={6} placeholder="What needs to happen?" /></FormField><SubmitButton form={form}>Save changes</SubmitButton></Form></div><Section className="max-w-2xl" title="Position" description="Move within this column or send the card to another stage.">{board.match({ loading: () => <Loading shape="text" />, failure: e => <ErrorState error={e} />, success: b => {
    const siblings = b.cards.filter(card => card.column === c.column)
    const index = siblings.findIndex(card => card.id === c.id)
    return <><div className="flex flex-wrap gap-2"><Button variant="outline" disabled={index <= 0 || reorder.waiting} onClick={() => void reorder({ board: c.board, card: c.id, direction: "up" })}>Move up</Button><Button variant="outline" disabled={index === siblings.length - 1 || reorder.waiting} onClick={() => void reorder({ board: c.board, card: c.id, direction: "down" })}>Move down</Button></div><Form key={c.column} form={moveForm}><FormField form={moveForm} name="column" label="Destination column"><NativeSelect name="column" defaultValue={c.column}>{b.columns.map(col => <NativeSelectOption key={col.id} value={col.id}>{col.title}</NativeSelectOption>)}</NativeSelect></FormField><SubmitButton variant="outline" form={moveForm}>Move card</SubmitButton></Form></>
  } })}<ActionStatus status={reorder.status} success="Card reordered" /></Section></>
}
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
 * App theme: shadcn preset b75dVa3Zuc (style rhea, pink on stone, font noto-serif, radius medium).
 * Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b75dVa3Zuc
 * 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.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.525 0.223 3.958);
  --primary-foreground: oklch(0.971 0.014 343.198);
  --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.525 0.223 3.958);
  --accent-foreground: oklch(0.971 0.014 343.198);
  --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.823 0.12 346.018);
  --chart-2: oklch(0.656 0.241 354.308);
  --chart-3: oklch(0.592 0.249 0.584);
  --chart-4: oklch(0.525 0.223 3.958);
  --chart-5: oklch(0.459 0.187 3.815);
  --radius: 0.625rem;
  --font-body: "Noto Serif", ui-sans-serif, system-ui, sans-serif;
  --font-display: "IBM Plex Sans", 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.459 0.187 3.815);
  --primary-foreground: oklch(0.971 0.014 343.198);
  --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.459 0.187 3.815);
  --accent-foreground: oklch(0.971 0.014 343.198);
  --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.823 0.12 346.018);
  --chart-2: oklch(0.656 0.241 354.308);
  --chart-3: oklch(0.592 0.249 0.584);
  --chart-4: oklch(0.525 0.223 3.958);
  --chart-5: oklch(0.459 0.187 3.815);
}
server/index.test.ts105 lines
import { describe, expect, it } from "vitest"
import { missingId, testApp } from "canica/testing"
import app from "./index.ts"
function setup() {
  const t = testApp(app)
  const owner = t.as("owner")
  const bob = t.as("bob")
  const board = owner.mutationOk("createBoard", { title: "Launch" })
  const column = owner.mutationOk("createColumn", { board, title: "To do" })
  const card = owner.mutationOk("createCard", { column, title: "Write copy" })
  return { t, owner, bob, board, column, card }
}
const failure = (tag: string) => ({ _tag: "Failure", error: { _tag: tag } })
describe("board access", () => {
  it("automatically enrolls creator, hides work until joining, and joins idempotently", () => {
    const { owner, bob, board } = setup()
    expect(owner.queryOk("boards")).toHaveLength(1)
    expect(bob.queryOk("boards")).toEqual([])
    expect(bob.query("board", { board })).toMatchObject(failure("NotMember"))
    bob.mutationOk("join", { board }); bob.mutationOk("join", { board })
    expect(bob.queryOk("board", { board }).members).toHaveLength(2)
    expect(bob.queryOk("boards")).toHaveLength(1)
  })
  it("rejects all nonmember editing paths", () => {
    const { bob, board, column, card } = setup()
    for (const result of [
      bob.mutation("createColumn", { board, title: "No" }),
      bob.mutation("renameColumn", { column, title: "No" }),
      bob.mutation("deleteColumn", { column }),
      bob.mutation("moveColumn", { column, direction: "left" }),
      bob.mutation("createCard", { column, title: "No" }),
      bob.mutation("editCard", { board, card, title: "No", description: "" }),
      bob.mutation("moveCard", { board, card, column }),
      bob.mutation("reorderCard", { board, card, direction: "up" }),
      bob.mutation("deleteCard", { board, card }),
      bob.query("card", { board, card }),
    ]) expect(result).toMatchObject(failure("NotMember"))
  })
  it("only owner removes members; removal revokes reads and writes; owner is protected", () => {
    const { owner, bob, board, column } = setup()
    bob.mutationOk("join", { board })
    const data = owner.queryOk("board", { board })
    const own = data.members.find(m => m.user === data.owner)!
    const other = data.members.find(m => m.user !== data.owner)!
    expect(bob.mutation("removeMember", { board, member: own.id })).toMatchObject(failure("OwnerOnly"))
    expect(owner.mutation("removeMember", { board, member: own.id })).toMatchObject(failure("CannotRemoveOwner"))
    owner.mutationOk("removeMember", { board, member: other.id })
    expect(bob.query("board", { board })).toMatchObject(failure("NotMember"))
    expect(bob.mutation("createCard", { column, title: "No" })).toMatchObject(failure("NotMember"))
    expect(bob.queryOk("boards")).toEqual([])
  })
  it("rejects cross-board card URLs, destinations and membership ids", () => {
    const { owner, board, card } = setup()
    const other = owner.mutationOk("createBoard", { title: "Other" })
    const column = owner.mutationOk("createColumn", { board: other, title: "Elsewhere" })
    expect(owner.mutation("moveCard", { board, card, column })).toMatchObject(failure("WrongBoard"))
    expect(owner.query("card", { board: other, card })).toMatchObject(failure("NotFound"))
    const mid = owner.queryOk("board", { board: other }).members[0]!.id
    expect(owner.mutation("removeMember", { board, member: mid })).toMatchObject(failure("WrongBoard"))
    expect(owner.query("board", { board: missingId("boards") })).toMatchObject(failure("NotFound"))
  })
})
describe("ordering and validation", () => {
  it("orders columns, swaps neighbors, handles edges and deletion gaps", () => {
    const { owner, board, column, card } = setup()
    const b = owner.mutationOk("createColumn", { board, title: "Doing" })
    const c = owner.mutationOk("createColumn", { board, title: "Done" })
    owner.mutationOk("moveColumn", { column, direction: "left" })
    owner.mutationOk("moveColumn", { column: c, direction: "left" })
    expect(owner.queryOk("board", { board }).columns.map(c => c.title)).toEqual(["To do", "Done", "Doing"])
    owner.mutationOk("renameColumn", { column: b, title: "In progress" })
    expect(owner.mutation("deleteColumn", { column })).toMatchObject(failure("ColumnNotEmpty"))
    owner.mutationOk("deleteCard", { board, card })
    owner.mutationOk("deleteColumn", { column })
    owner.mutationOk("createColumn", { board, title: "Archive" })
    expect(owner.queryOk("board", { board }).columns.map(c => c.title)).toEqual(["Done", "In progress", "Archive"])
  })
  it("keeps ordered cards through swaps, transfers, deletion and append", () => {
    const { owner, bob, board, column, card } = setup()
    bob.mutationOk("join", { board })
    const b = bob.mutationOk("createCard", { column, title: "Design" })
    const c = owner.mutationOk("createCard", { column, title: "Build" })
    owner.mutationOk("reorderCard", { board, card, direction: "up" })
    bob.mutationOk("reorderCard", { board, card: c, direction: "up" })
    const ordered = () => owner.queryOk("board", { board }).cards.filter(c => c.column === column).map(c => c.title)
    expect(ordered()).toEqual(["Write copy", "Build", "Design"])
    bob.mutationOk("reorderCard", { board, card, direction: "down" })
    expect(ordered()).toEqual(["Build", "Write copy", "Design"])
    const dest = owner.mutationOk("createColumn", { board, title: "Done" })
    bob.mutationOk("moveCard", { board, card, column: dest })
    bob.mutationOk("moveCard", { board, card: b, column: dest })
    owner.mutationOk("moveCard", { board, card, column: dest })
    expect(owner.queryOk("board", { board }).cards.filter(c => c.column === dest).map(c => c.id)).toEqual([card, b])
    bob.mutationOk("editCard", { board, card, title: "  Final copy  ", description: " Ready " })
    expect(owner.queryOk("card", { board, card })).toMatchObject({ title: "Final copy", description: "Ready" })
    owner.mutationOk("deleteCard", { board, card: c })
    owner.mutationOk("createCard", { column, title: "Review" })
    expect(ordered()).toEqual(["Review"])
  })
  it("validates blank, oversized and malformed input", () => {
    const { owner, board, column, card } = setup()
    for (const r of [owner.mutation("createBoard", { title: " " }), owner.mutation("createColumn", { board, title: "x".repeat(101) }), owner.mutation("createCard", { column, title: " " }), owner.mutation("editCard", { board, card, title: "Valid", description: "x".repeat(5001) })]) expect(r).toMatchObject(failure("InvalidArgs"))
  })
})
src/app.test.tsx50 lines
import { describe, it } from "vitest"
import { as, choose, click, label, meanwhile, missingId, 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("collaborative board scenes", () => {
  it("owner creates work; a second guest joins by link and sees live updates", async () => {
    const t = testApp(app)
    let board = missingId("boards")
    let card = missingId("cards")
    await scene(t, routes,
      as("owner"), visit("/"), see(text("Make room for your next project")),
      click(role("button", { name: "New board" })),
      within(role("dialog"), type(label("Board name"), "Launch"), click(role("button", { name: "Create board" }))),
      see(role("heading", { name: "Launch" })),
      meanwhile(() => { board = t.as("owner").queryOk("boards")[0]!.id }),
      click(role("button", { name: "Add column" })),
      within(role("dialog"), type(label("Column name"), "To do"), click(role("button", { name: "OK" }))),
      click(role("button", { name: "Add card to To do" })),
      within(role("dialog"), type(label("Card title"), "Draft announcement"), click(role("button", { name: "OK" }))),
      click(role("link", { name: "Draft announcement" })),
      type(label("Description"), "Explain the release"), click(role("button", { name: "Save changes" })),
      meanwhile(() => { card = t.as("owner").queryOk("board", { board }).cards[0]!.id }),
      as("bob"), visit("/boards/$board", () => ({ board })), see(text("You're invited")),
      notSee(text("Draft announcement")), click(role("button", { name: "Join board" })), see(text("Draft announcement")),
      meanwhile(() => t.as("owner").mutationOk("editCard", { board, card, title: "Announcement ready", description: "Approved by the team" })),
      see(text("Announcement ready")), notSee(text("Draft announcement")),
      click(role("link", { name: "Announcement ready" })), type(label("Card title"), "Ready for review"), click(role("button", { name: "Save changes" })),
      as("owner"), see(role("heading", { name: "Ready for review" })),
      visit("/boards/$board", () => ({ board })), click(role("button", { name: "Remove member" })),
      within(role("alertdialog"), click(role("button", { name: "Remove member" }))),
      as("bob"), see(text("You're invited")), visit("/"), notSee(text("Launch")),
    )
  })
  it("moves, renames and deletes work through real forms and confirmations", async () => {
    const t = testApp(app)
    const owner = t.as("owner")
    const board = owner.mutationOk("createBoard", { title: "Project" })
    const column = owner.mutationOk("createColumn", { board, title: "To do" })
    owner.mutationOk("createColumn", { board, title: "Done" })
    const card = owner.mutationOk("createCard", { column, title: "Task" })
    owner.mutationOk("createCard", { column, title: "Next task" })
    await scene(t, routes, as("owner"), visit("/boards/$board/cards/$card", { board, card }),
      click(role("button", { name: "Move down" })), see(text("Card reordered")),
      choose(label("Destination column"), "Done"), click(role("button", { name: "Move card" })),
      click(role("button", { name: "Delete card" })), within(role("alertdialog"), click(role("button", { name: "Delete card" }))),
      see(role("heading", { name: "Project" })), notSee(role("link", { name: "Task" })),
    )
  })
})