Canica

Live polls

Polls with single or multiple choice and live results.

typed errorscascadesresult bars

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

Files

server/index.ts88 lines
import { and, asc, boolean, desc, eq, id, inArray, mutation, number, query, schema, table, TaggedError, userId, Viewer, type Id } from "canica/server"
import { optionText, pollMode, pollOptions, pollQuestion, resultsPrivate, selectedOptions } from "../shared/fields.ts"

export const { app, Db, tables } = schema({
  polls: table({ question: pollQuestion, mode: pollMode, resultsPrivate, open: boolean().default(true), owner: userId() }).index("by_owner", ["owner"]),
  options: table({ poll: id("polls").onDelete("cascade"), label: optionText, position: number().int() }).index("by_poll", ["poll"]),
  votes: table({ poll: id("polls").onDelete("cascade"), option: id("options").onDelete("cascade"), user: userId() }).index("by_poll", ["poll"]).index("by_option", ["option"]).index("by_user", ["user"]),
})
const { polls, options, votes } = tables

export class NotOwner extends TaggedError("NotOwner") {}
export class PollClosed extends TaggedError("PollClosed") {}
export class InvalidVote extends TaggedError("InvalidVote")<{ readonly reason: string }> {}

function* loadPoll(poll: Id<"polls">) {
  const db = yield* Db
  return yield* db.get(polls, poll)
}

function* requireOwner(poll: Id<"polls">) {
  const row = yield* loadPoll(poll)
  const viewer = yield* Viewer
  if (row.owner !== viewer.userId) return yield* new NotOwner()
  return row
}

function* pollSnapshot(poll: Id<"polls">) {
  const db = yield* Db
  const viewer = yield* Viewer
  const row = yield* loadPoll(poll)
  const choices = yield* db.select().from(options).where(eq(options.poll, poll)).orderBy(asc(options.position))
  const allVotes = yield* db.select().from(votes).where(eq(votes.poll, poll))
  const own = allVotes.filter((v) => v.user === viewer.userId).map((v) => v.option)
  const canSeeResults = !row.resultsPrivate || own.length > 0 || row.owner === viewer.userId || !row.open
  return { ...row, options: choices.map((o) => ({ id: o.id, label: o.label, votes: canSeeResults ? allVotes.filter((v) => v.option === o.id).length : 0, selected: own.includes(o.id) })), voterCount: new Set(allVotes.map((v) => v.user)).size, canSeeResults, hasVoted: own.length > 0 }
}

export default app({
  name: "Live polls",
  queries: {
    home: query(function* () {
      const db = yield* Db
      const viewer = yield* Viewer
      const mine = yield* db.select().from(polls).where(eq(polls.owner, viewer.userId)).orderBy(desc(polls.createdAt)).limit(20)
      const myVoteRows = yield* db.select().from(votes).where(eq(votes.user, viewer.userId)).limit(200)
      const votedIds = [...new Set(myVoteRows.map((v) => v.poll))]
      const voted = votedIds.length ? yield* db.select().from(polls).where(inArray(polls.id, votedIds)).orderBy(desc(polls.createdAt)).limit(20) : []
      const recent = yield* db.select().from(polls).where(eq(polls.resultsPrivate, false)).orderBy(desc(polls.createdAt)).limit(20)
      return { mine, voted, recent }
    }),
    poll: query({ poll: id("polls") }, function* ({ poll }) {
      return yield* pollSnapshot(poll)
    }),
  },
  mutations: {
    createPoll: mutation({ question: pollQuestion, options: pollOptions, mode: pollMode, resultsPrivate }, function* ({ question, options: labels, mode, resultsPrivate }) {
      const db = yield* Db
      const viewer = yield* Viewer
      const [poll] = yield* db.insert(polls).values({ question, mode, resultsPrivate, owner: viewer.userId }).returning({ id: polls.id })
      for (const [position, label] of labels.entries()) yield* db.insert(options).values({ poll: poll!.id, label, position }).returning()
      return poll!.id
    }),
    vote: mutation({ poll: id("polls"), options: selectedOptions }, function* ({ poll, options: selected }) {
      const db = yield* Db
      const viewer = yield* Viewer
      const row = yield* loadPoll(poll)
      if (!row.open) return yield* new PollClosed()
      if (row.mode === "single" && selected.length !== 1) return yield* new InvalidVote({ reason: "Choose exactly one option." })
      if (new Set(selected).size !== selected.length) return yield* new InvalidVote({ reason: "Choose each option only once." })
      const choices = yield* db.select({ id: options.id }).from(options).where(eq(options.poll, poll))
      const valid = new Set(choices.map((o) => o.id))
      if (selected.some((option) => !valid.has(option as Id<"options">))) return yield* new InvalidVote({ reason: "That option is not part of this poll." })
      yield* db.delete(votes).where(and(eq(votes.poll, poll), eq(votes.user, viewer.userId)))
      for (const option of selected) yield* db.insert(votes).values({ poll, option: option as Id<"options">, user: viewer.userId }).returning()
    }),
    setPollOpen: mutation({ poll: id("polls"), open: boolean() }, function* ({ poll, open }) {
      yield* requireOwner(poll)
      const db = yield* Db
      yield* db.update(polls).set({ open }).where(eq(polls.id, poll))
    }),
    deletePoll: mutation({ poll: id("polls") }, function* ({ poll }) {
      yield* requireOwner(poll)
      const db = yield* Db
      yield* db.delete(polls).where(eq(polls.id, poll))
    }),
  },
})
server/seed.ts14 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"

export default defineSeed(app, ({ as }) => {
  const ana = as("Ana")
  const lunch = ana.mutationOk("createPoll", { question: "Where should we go for lunch?", options: ["Tacos", "Ramen", "Salads"], mode: "single", resultsPrivate: false })
  const lunchOptions = ana.queryOk("poll", { poll: lunch }).options
  as("Ben").mutationOk("vote", { poll: lunch, options: [lunchOptions[0]!.id] })
  const weekend = as("viewer").mutationOk("createPoll", { question: "Pick our weekend project", options: ["Ship the update", "Write docs", "Polish onboarding"], mode: "multiple", resultsPrivate: true })
  const weekendOptions = as("viewer").queryOk("poll", { poll: weekend }).options
  as("viewer").mutationOk("vote", { poll: weekend, options: [weekendOptions[0]!.id, weekendOptions[1]!.id] })
  return { captures: { "/polls/$poll": [{ poll: lunch }, { poll: weekend }] } }
})
shared/fields.ts10 lines
import { array, boolean, literal, number, string } from "canica/fields"

export const pollQuestion = string().trim().min(1).max(200)
export const optionText = string().trim().min(1).max(100)
export const pollOptions = array(optionText).min(2).max(8)
export const pollMode = literal("single", "multiple")
export const resultsPrivate = boolean().default(false)
export const selectedOptions = array(string()).min(1).max(8)
export const pollLimit = number().int().min(1).max(20)
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="/">Live polls</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/index.tsx26 lines
import { Link, page, useForm, useMutation, useNavigate, useQuery, type Id } from "canica/client"
import { Button, Checkbox, ChoiceRow, EmptyBlock, ErrorState, Form, FormField, Input, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, List, Loading, PageHeader, RadioGroup, RadioGroupItem, RepeatInput, Section, SubmitButton } from "canica/ui"
import { pollMode, pollOptions, pollQuestion, resultsPrivate } from "../../shared/fields.ts"

function PollList({ title, polls }: { readonly title: string; readonly polls: ReadonlyArray<{ id: Id<"polls">; question: string; open: boolean; createdAt: number }> }) {
  return <Section title={title}>{polls.length === 0 ? <EmptyBlock title="Nothing here yet" description="Create a poll or vote in a public poll to see it here." /> : <List>{polls.map((poll) => <Item key={poll.id}><ItemContent><ItemTitle><Link to="/polls/$poll" params={{ poll: poll.id }}>{poll.question}</Link></ItemTitle><ItemDescription>{poll.open ? "Open" : "Closed"} · {new Date(poll.createdAt).toLocaleDateString()}</ItemDescription></ItemContent><ItemActions><Button asChild variant="ghost" size="sm"><Link to="/polls/$poll" params={{ poll: poll.id }}>Open</Link></Button></ItemActions></Item>)}</List>}</Section>
}

export default page({ title: "Live polls", view: () => {
  const home = useQuery("home")
  const create = useMutation("createPoll")
  const open = useNavigate("/polls/$poll")
  const form = useForm("create poll", { question: pollQuestion, options: pollOptions, mode: pollMode, resultsPrivate }, (values) => create(values), { onSuccess: (id) => open({ poll: id }) })
  return <>
    <PageHeader title="Live polls" description="Ask a question, share the link, and watch the room decide." />
    <Form form={form} className="mb-8 max-w-2xl">
      <FormField form={form} name="question" label="Question"><Input name="question" placeholder="What should we do next?" autoComplete="off" /></FormField>
      <FormField form={form} name="options" label="Options"><RepeatInput name="options" label="Option" min={2} max={8} placeholder="A choice" /></FormField>
      <FormField form={form} name="mode" label="Voting"><RadioGroup name="mode" defaultValue="single"><ChoiceRow control={<RadioGroupItem value="single" />}>Choose one</ChoiceRow><ChoiceRow control={<RadioGroupItem value="multiple" />}>Choose multiple</ChoiceRow></RadioGroup></FormField>
      <ChoiceRow control={<Checkbox name="resultsPrivate" />}>Hide results until someone votes</ChoiceRow>
      <SubmitButton form={form}>Create poll</SubmitButton>
    </Form>
    {home.match({ loading: () => <Loading shape="list" />, failure: (error) => <ErrorState error={error} />, success: (data) => <div className="flex flex-col gap-8"><PollList title="Polls I created" polls={data.mine} /><PollList title="Polls I voted in" polls={data.voted} /><Section title="Recent public polls" description="The latest public questions from everyone."><List>{data.recent.map((poll) => <Item key={poll.id}><ItemContent><ItemTitle><Link to="/polls/$poll" params={{ poll: poll.id }}>{poll.question}</Link></ItemTitle><ItemDescription>{poll.open ? "Open for votes" : "Final results"}</ItemDescription></ItemContent></Item>)}</List></Section></div> })}
  </>
}})
src/routes/polls/$poll.tsx36 lines
import { id, Link, page, useAuth, useForm, useMutation, useNavigate, useQuery, type Id } from "canica/client"
import { ActionStatus, Button, Checkbox, ChoiceRow, CopyButton, EmptyBlock, ErrorState, Form, FormField, Loading, PageHeader, RadioGroup, RadioGroupItem, ResultBar, Section, Stat, Stats, confirm } from "canica/ui"
import { selectedOptions } from "../../../shared/fields.ts"

function PollView({ poll }: { readonly poll: { readonly id: Id<"polls">; readonly question: string; readonly mode: "single" | "multiple"; readonly resultsPrivate: boolean; readonly open: boolean; readonly owner: string; readonly options: ReadonlyArray<{ readonly id: Id<"options">; readonly label: string; readonly votes: number; readonly selected: boolean }>; readonly voterCount: number; readonly canSeeResults: boolean; readonly hasVoted: boolean } }) {
  const auth = useAuth()
  const vote = useMutation("vote")
  const close = useMutation("setPollOpen")
  const remove = useMutation("deletePoll")
  const goHome = useNavigate("/")
  const form = useForm("vote", { options: selectedOptions }, (values) => vote({ poll: poll.id, options: values.options }))
  const owner = poll.owner === auth.userId
  const total = poll.options.reduce((sum, option) => sum + option.votes, 0)
  const deletePoll = async () => {
    const answer = await confirm({ title: "Delete this poll?", description: "This removes the poll and its votes permanently.", confirm: "Delete" })
    answer.match({ done: () => void remove({ poll: poll.id }).then(() => goHome({})), cancelled: () => undefined })
  }
  return <>
    <PageHeader title={poll.question} description={`${poll.open ? "Open" : "Closed"} · ${poll.voterCount} voter${poll.voterCount === 1 ? "" : "s"}`} actions={<><CopyButton>Share link</CopyButton>{owner && <Button variant="outline" onClick={() => void close({ poll: poll.id, open: !poll.open })}>{poll.open ? "Close poll" : "Reopen poll"}</Button>}{owner && <Button variant="destructive" onClick={() => void deletePoll()}>Delete</Button>}</>} />
    <div className="grid gap-8 lg:grid-cols-3">
      <Section title={poll.open ? (poll.hasVoted ? "Your vote" : "Cast your vote") : "Final results"} description={poll.mode === "multiple" ? "Choose one or more options." : "Choose one option."}>
        {poll.open ? <Form form={form}><FormField form={form} name="options" label="Options"><div className="flex flex-col gap-2">{poll.mode === "single" ? <RadioGroup name="options" defaultValue={poll.options.find((o) => o.selected)?.id}><>{poll.options.map((option) => <ChoiceRow key={option.id} control={<RadioGroupItem value={option.id} />} share={poll.canSeeResults ? option.votes / Math.max(1, total) : undefined} highlight={option.selected} trailing={poll.canSeeResults ? `${option.votes}` : undefined}>{option.label}</ChoiceRow>)}</></RadioGroup> : <>{poll.options.map((option) => <ChoiceRow key={option.id} control={<Checkbox name="options" value={option.id} defaultChecked={option.selected} />} share={poll.canSeeResults ? option.votes / Math.max(1, total) : undefined} highlight={option.selected} trailing={poll.canSeeResults ? `${option.votes}` : undefined}>{option.label}</ChoiceRow>)}</>}</div></FormField><div className="flex items-center gap-3"><Button type="submit">Submit vote</Button><ActionStatus status={vote.status} success="Vote saved" /></div></Form> : <EmptyBlock title="Voting is closed" description="The creator closed this poll. These are the final results." />}
        {poll.resultsPrivate && !poll.canSeeResults && <p className="text-sm text-muted-foreground">Results are hidden until you vote.</p>}
      </Section>
      {poll.canSeeResults && <Section title="Results"><div className="flex flex-col gap-5">{poll.options.map((option) => <ResultBar key={option.id} label={option.label} value={option.votes} total={Math.max(1, total)} highlight={option.selected} />)}</div></Section>}
    </div>
    <Stats><Stat label="Voters" value={poll.voterCount} /><Stat label="Choices" value={poll.options.length} /><Stat label="Status" value={poll.open ? "Open" : "Closed"} /></Stats>
    <p className="text-sm"><Link to="/">← Back to polls</Link></p>
  </>
}

export default page({ title: "Poll", params: { poll: id("polls") }, view: ({ params }) => {
  const poll = useQuery("poll", { poll: params.poll })
  return poll.match({ loading: () => <Loading shape="cards" />, failure: (error) => <ErrorState error={error} states={{ NotFound: { title: "Poll not found", description: "This poll may have been deleted.", action: <Button asChild><Link to="/">Back home</Link></Button> } }}/> , success: (data) => <PollView poll={data} /> })
}})
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
 * App theme: shadcn preset b2HRadm12R (style maia, mist on mist, font raleway, radius none).
 * Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b2HRadm12R
 * 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.148 0.004 228.8);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.148 0.004 228.8);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.148 0.004 228.8);
  --primary: oklch(0.218 0.008 223.9);
  --primary-foreground: oklch(0.987 0.002 197.1);
  --secondary: oklch(0.963 0.002 197.1);
  --secondary-foreground: oklch(0.218 0.008 223.9);
  --muted: oklch(0.963 0.002 197.1);
  --muted-foreground: oklch(0.56 0.021 213.5);
  --accent: oklch(0.218 0.008 223.9);
  --accent-foreground: oklch(0.987 0.002 197.1);
  --destructive: oklch(0.577 0.245 27.325);
  --border: oklch(0.925 0.005 214.3);
  --input: oklch(0.925 0.005 214.3);
  --ring: oklch(0.723 0.014 214.4);
  --chart-1: oklch(0.809 0.105 251.813);
  --chart-2: oklch(0.623 0.214 259.815);
  --chart-3: oklch(0.546 0.245 262.881);
  --chart-4: oklch(0.488 0.243 264.376);
  --chart-5: oklch(0.424 0.199 265.638);
  --radius: 0;
  --font-body: "Raleway", ui-sans-serif, system-ui, sans-serif;
  --font-display: "DM Sans", ui-serif, Georgia, serif;
}

.dark {
  --background: oklch(0.148 0.004 228.8);
  --foreground: oklch(0.987 0.002 197.1);
  --card: oklch(0.218 0.008 223.9);
  --card-foreground: oklch(0.987 0.002 197.1);
  --popover: oklch(0.218 0.008 223.9);
  --popover-foreground: oklch(0.987 0.002 197.1);
  --primary: oklch(0.925 0.005 214.3);
  --primary-foreground: oklch(0.218 0.008 223.9);
  --secondary: oklch(0.275 0.011 216.9);
  --secondary-foreground: oklch(0.987 0.002 197.1);
  --muted: oklch(0.275 0.011 216.9);
  --muted-foreground: oklch(0.723 0.014 214.4);
  --accent: oklch(0.925 0.005 214.3);
  --accent-foreground: oklch(0.218 0.008 223.9);
  --destructive: oklch(0.704 0.191 22.216);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 15%);
  --ring: oklch(0.56 0.021 213.5);
  --chart-1: oklch(0.809 0.105 251.813);
  --chart-2: oklch(0.623 0.214 259.815);
  --chart-3: oklch(0.546 0.245 262.881);
  --chart-4: oklch(0.488 0.243 264.376);
  --chart-5: oklch(0.424 0.199 265.638);
}
server/index.test.ts33 lines
import { describe, expect, it } from "vitest"
import { testApp } from "canica/testing"
import app from "./index.ts"

describe("poll rules", () => {
  it("allows one vote per user and changing a vote", () => {
    const t = testApp(app)
    const alice = t.as("alice")
    const poll = alice.mutationOk("createPoll", { question: "Best color?", options: ["Blue", "Green"], mode: "single", resultsPrivate: false })
    const choices = alice.queryOk("poll", { poll }).options
    alice.mutationOk("vote", { poll, options: [choices[0]!.id] })
    alice.mutationOk("vote", { poll, options: [choices[1]!.id] })
    expect(alice.queryOk("poll", { poll }).options.map((o) => o.votes)).toEqual([0, 1])
  })

  it("rejects malformed votes and blocks voting when closed", () => {
    const t = testApp(app)
    const alice = t.as("alice")
    const bob = t.as("bob")
    const poll = alice.mutationOk("createPoll", { question: "Pick two", options: ["A", "B"], mode: "multiple", resultsPrivate: false })
    const choices = alice.queryOk("poll", { poll }).options
    expect(bob.mutation("vote", { poll, options: [] })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
    alice.mutationOk("setPollOpen", { poll, open: false })
    expect(bob.mutation("vote", { poll, options: [choices[0]!.id] })).toMatchObject({ _tag: "Failure", error: { _tag: "PollClosed" } })
    expect(bob.mutation("deletePoll", { poll })).toMatchObject({ _tag: "Failure", error: { _tag: "NotOwner" } })
  })

  it("validates poll fields", () => {
    const t = testApp(app)
    expect(t.as("alice").mutation("createPoll", { question: "", options: ["Only"], mode: "single", resultsPrivate: false })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
  })
})
src/app.test.tsx26 lines
import { describe, it } from "vitest"
import { as, click, label, meanwhile, role, scene, see, testApp, text, type, visit } from "canica/testing"
import type { Id } from "canica/client"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"

describe("poll scenes", () => {
  it("creates, votes live, and closes a poll", async () => {
    const t = testApp(app)
    let poll = "" as Id<"polls">
    await scene(t, routes,
      as("alice"), visit("/"),
      type(label("Question"), "Where should we eat?"), type(label("Option 1"), "Tacos"), type(label("Option 2"), "Ramen"),
      click(role("button", { name: "Create poll" })),
      meanwhile(() => { poll = t.as("alice").queryOk("home").mine[0]!.id }),
      see(text("Where should we eat?")),
      meanwhile(() => { const choice = t.as("bob").queryOk("poll", { poll }).options[0]!.id; t.as("bob").mutationOk("vote", { poll, options: [choice] }) }),
      see(text(/1 voter/)), see(text(/Tacos/)),
      click(role("button", { name: "Close poll" })),
      see(text("Final results")),
      as("bob"), visit("/polls/$poll", () => ({ poll })),
      see(text("Voting is closed")),
    )
  })
})