Habits
Daily habits with streaks and an archive.
20 files, 1107 lines. Source on GitHub. To run it, from a clone of the repository: pnpm install, then pnpm dev in apps/habits.
Files
server/index.ts201server/seed.ts42shared/fields.ts26shared/streak.ts34src/main.tsx6src/routes/__root.tsx16src/routes/404.tsx21src/routes/archived.tsx43src/routes/habits/$habit.tsx73src/routes/index.tsx40src/components/archived-row.tsx31src/components/day-grid.tsx48src/components/edit-habit.tsx25src/components/habit-fields.tsx44src/components/habit-row.tsx36src/components/new-habit.tsx40src/styles.css4src/theme.css60server/index.test.ts208src/app.test.tsx109
server/index.ts201 lines
import {
and,
asc,
boolean,
count,
day,
eq,
gte,
id,
inArray,
max,
mutation,
NotFound,
query,
schema,
table,
TaggedError,
userId,
Viewer,
type Id,
} from "canica/server"
import { addDays, startOfWeek } from "canica/fields"
import { habitEmoji, habitName, habitTarget } from "../shared/fields.ts"
import { bestStreak, currentStreak } from "../shared/streak.ts"
export const { app, Db, tables } = schema({
habits: table({
name: habitName,
emoji: habitEmoji,
target: habitTarget,
archived: boolean().default(false),
owner: userId(),
}).index("by_owner", ["owner"]),
// One check-in per habit per calendar day; deleting a habit deletes its history.
checkins: table({
habit: id("habits").onDelete("cascade"),
day: day(),
}).unique("by_habit_day", ["habit", "day"]),
})
const { habits, checkins } = tables
export class TooManyHabits extends TaggedError("TooManyHabits")<{ readonly max: number }> {}
/** Load a habit the viewer owns. Other people's habits look like they don't exist. */
function* ownHabit(habitId: Id<"habits">) {
const db = yield* Db
const viewer = yield* Viewer
const habit = yield* db.get(habits, habitId)
if (habit.owner !== viewer.userId) return yield* new NotFound({ table: "habits", id: habitId })
return habit
}
/**
* Days of check-ins to read for streaks: a trailing year. Streaks longer than
* 367 days are reported as 367 on the home page (the habit page reads every
* check-in and is exact); this keeps the read small for many habits.
*/
const STREAK_WINDOW = 366
export default app({
name: "Habits",
queries: {
/** Today's board: the viewer's active habits with today's check-in, streak and week progress. */
today: query({ today: day() }, function* ({ today }) {
const db = yield* Db
const viewer = yield* Viewer
const mine = yield* db
.select()
.from(habits)
.where(and(eq(habits.owner, viewer.userId), eq(habits.archived, false)))
.orderBy(asc(habits.createdAt))
const ids = mine.map((h) => h.id)
const rows =
ids.length === 0
? []
: yield* db
.select({ habit: checkins.habit, day: checkins.day })
.from(checkins)
.where(and(inArray(checkins.habit, ids), gte(checkins.day, addDays(today, -STREAK_WINDOW))))
.orderBy(asc(checkins.day))
const days = new Map<string, Array<string>>()
for (const row of rows) {
const list = days.get(row.habit) ?? []
list.push(row.day)
days.set(row.habit, list)
}
const weekStart = startOfWeek(today)
return mine.map((h) => {
const checked = days.get(h.id) ?? []
return {
id: h.id,
name: h.name,
emoji: h.emoji,
target: h.target,
doneToday: checked.includes(today),
streak: currentStreak(checked, today),
weekDone: checked.filter((d) => d >= weekStart).length,
}
})
}),
/** One habit: its fields, every check-in day (for the grid) and its stats. */
habit: query({ habit: id("habits"), today: day() }, function* ({ habit: habitId, today }) {
const habit = yield* ownHabit(habitId)
const db = yield* Db
const days = (
yield* db.select({ day: checkins.day }).from(checkins).where(eq(checkins.habit, habitId)).orderBy(asc(checkins.day))
).map((r) => r.day)
const weekStart = startOfWeek(today)
return {
id: habit.id,
name: habit.name,
emoji: habit.emoji,
target: habit.target,
archived: habit.archived,
createdAt: habit.createdAt,
updatedAt: habit.updatedAt,
days,
total: days.length,
best: bestStreak(days),
streak: currentStreak(days, today),
weekDone: days.filter((d) => d >= weekStart).length,
}
}),
/** The viewer's archived habits, with their totals and last check-in. */
archived: query(function* () {
const db = yield* Db
const viewer = yield* Viewer
const mine = yield* db
.select()
.from(habits)
.where(and(eq(habits.owner, viewer.userId), eq(habits.archived, true)))
.orderBy(asc(habits.createdAt))
const ids = mine.map((h) => h.id)
const stats =
ids.length === 0
? []
: yield* db
.select({ habit: checkins.habit, total: count(), last: max(checkins.day) })
.from(checkins)
.where(inArray(checkins.habit, ids))
.groupBy(checkins.habit)
const byHabit = new Map(stats.map((s) => [s.habit, s]))
return mine.map((h) => {
const s = byHabit.get(h.id)
return { id: h.id, name: h.name, emoji: h.emoji, target: h.target, total: s?.total ?? 0, last: s?.last ?? null }
})
}),
},
mutations: {
createHabit: mutation({ name: habitName, emoji: habitEmoji, target: habitTarget }, function* ({ name, emoji, target }) {
const db = yield* Db
const viewer = yield* Viewer
const active = yield* db.count(habits, and(eq(habits.owner, viewer.userId), eq(habits.archived, false)))
if (active >= 20) return yield* new TooManyHabits({ max: 20 })
const [habit] = yield* db.insert(habits).values({ name, emoji, target, owner: viewer.userId }).returning({ id: habits.id })
return habit!.id
}),
updateHabit: mutation(
{ habit: id("habits"), name: habitName, emoji: habitEmoji, target: habitTarget },
function* ({ habit: habitId, name, emoji, target }) {
const db = yield* Db
yield* ownHabit(habitId)
yield* db.update(habits).set({ name, emoji, target }).where(eq(habits.id, habitId))
},
),
setArchived: mutation({ habit: id("habits"), archived: boolean() }, function* ({ habit: habitId, archived }) {
const db = yield* Db
yield* ownHabit(habitId)
yield* db.update(habits).set({ archived }).where(eq(habits.id, habitId))
}),
deleteHabit: mutation({ habit: id("habits") }, function* ({ habit: habitId }) {
const db = yield* Db
yield* ownHabit(habitId)
yield* db.delete(habits).where(eq(habits.id, habitId))
}),
/**
* Set whether a habit is done on a calendar day. Idempotent: setting the
* same state twice is fine, and there is at most one check-in per habit
* per day (the `by_habit_day` unique index backs that up).
*/
setCheckin: mutation({ habit: id("habits"), day: day(), done: boolean() }, function* ({ habit: habitId, day, done }) {
const db = yield* Db
yield* ownHabit(habitId)
const [existing] = yield* db
.select({ id: checkins.id })
.from(checkins)
.where(and(eq(checkins.habit, habitId), eq(checkins.day, day)))
.limit(1)
if (done && !existing) yield* db.insert(checkins).values({ habit: habitId, day })
else if (!done && existing) yield* db.delete(checkins).where(eq(checkins.id, existing.id))
return done
}),
},
})
server/seed.ts42 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"
/**
* Sample data for `pnpm storyboard`, created through the mutations (so every
* invariant the handlers enforce holds). `day(n)` is n days before real today.
*/
export default defineSeed(app, ({ as, day }) => {
const me = as("viewer")
// A 4-day streak that ended yesterday, on 3 of 4 days this week,
// with a better week three weeks back (best streak: 5).
const run = me.mutationOk("createHabit", { name: "Morning run", emoji: "๐", target: 4 })
for (const offset of [-11, -10, -9, -8, -7, -5, -4, -3, -2]) {
me.mutationOk("setCheckin", { habit: run, day: day(offset), done: true })
}
// Twelve days in a row, today included: 5 of 7 this week.
const water = me.mutationOk("createHabit", { name: "Drink water", emoji: "๐ง", target: 7 })
for (let offset = -11; offset <= 0; offset++) {
me.mutationOk("setCheckin", { habit: water, day: day(offset), done: true })
}
// Two evenings this week and an older pair: best 2, current 1.
const read = me.mutationOk("createHabit", { name: "Read before bed", emoji: "๐", target: 3 })
for (const offset of [-15, -14, -2, 0]) {
me.mutationOk("setCheckin", { habit: read, day: day(offset), done: true })
}
// Started yesterday, nothing checked in yet.
me.mutationOk("createHabit", { name: "Meditate", emoji: "๐ง", target: 5 })
// Given up for now, history kept.
const piano = me.mutationOk("createHabit", { name: "Learn piano", emoji: "๐ธ", target: 2 })
for (const offset of [-32, -31, -30, -29, -28]) {
me.mutationOk("setCheckin", { habit: piano, day: day(offset), done: true })
}
me.mutationOk("setArchived", { habit: piano, archived: true })
return { captures: { "/habits/$habit": [{ habit: run }, { habit: water }, { habit: piano }] } }
})
src/main.tsx6 lines
import { start } from "canica/client"
import { routes } from "./routes.gen.ts"
import "./styles.css"
start(routes)
src/routes/__root.tsx16 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="/">Habits</Link>}>
<Link to="/archived">Archived</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/archived.tsx43 lines
import { Link, page, useQuery } from "canica/client"
import { Button, EmptyBlock, ErrorState, List, Loading, PageContainer, PageHeader } from "canica/ui"
import { ArchivedRow } from "../components/archived-row.tsx"
/** Habits the user put aside, with their facts, ready to come back. */
export default page({
title: "Archived habits",
view: () => {
const archived = useQuery("archived")
return (
<PageContainer>
<PageHeader
title="Archived habits"
description="Out of your day, history kept."
back={<Link to="/">โ Back to today</Link>}
/>
{archived.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock
title="Nothing archived"
description="Habits you archive collect here, history intact."
action={
<Button asChild variant="outline">
<Link to="/">Back to today</Link>
</Button>
}
/>
) : (
<List>
{list.map((habit) => (
<ArchivedRow key={habit.id} habit={habit} />
))}
</List>
),
})}
</PageContainer>
)
},
})
src/routes/habits/$habit.tsx73 lines
import { Badge, Button, confirm, ErrorState, Loading, PageContainer, PageHeader, Section, Stat, Stats } from "canica/ui"
import { id, Link, page, plural, useMutation, useNavigate, useQuery, useToday } from "canica/client"
import { DayGrid } from "../../components/day-grid.tsx"
import { EditHabit } from "../../components/edit-habit.tsx"
export default page({
params: { habit: id("habits") },
title: "Habit",
view: ({ params }) => {
const today = useToday()
const habit = useQuery("habit", { habit: params.habit, today })
const setArchived = useMutation("setArchived")
const remove = useMutation("deleteHabit")
const goHome = useNavigate("/")
return habit.match({
loading: () => <Loading shape="text" />,
failure: (error) => (
<ErrorState
error={error}
states={{
NotFound: {
title: "This habit does not exist",
description: "It may have been deleted, or the link is wrong.",
action: (
<Button asChild variant="outline">
<Link to="/">Back to today</Link>
</Button>
),
},
}}
/>
),
success: (h) => (
<PageContainer>
<PageHeader
title={`${h.emoji} ${h.name}`}
description={h.archived ? <Badge variant="secondary">Archived</Badge> : undefined}
back={<Link to="/">โ Back to today</Link>}
actions={
<>
<Button variant="outline" onClick={() => void setArchived({ habit: h.id, archived: !h.archived })}>
{h.archived ? "Unarchive" : "Archive"}
</Button>
<Button
variant="destructive"
aria-haspopup="dialog"
onClick={async () => {
if ((await confirm({ title: `Delete ${h.name}?`, description: "Its whole check-in history goes too.", confirm: "Delete" }))._tag !== "Done") return
if ((await remove({ habit: h.id }))._tag === "Success") goHome()
}}
>
Delete
</Button>
</>
}
/>
<Stats>
<Stat label="Current streak" value={plural(h.streak, "day")} tone={h.streak > 0 ? "positive" : undefined} />
<Stat label="Best streak" value={plural(h.best, "day")} />
<Stat label="Total check-ins" value={String(h.total)} />
<Stat label="This week" value={`${h.weekDone} of ${h.target}`} hint="days this week" />
</Stats>
<Section title="Last 8 weeks" description="Tap a day to toggle its check-in.">
<DayGrid habit={h.id} days={h.days} today={today} />
</Section>
<EditHabit habit={h} />
</PageContainer>
),
})
},
})
src/routes/index.tsx40 lines
import { formatDate, page, useNow, useQuery, useToday } from "canica/client"
import { EmptyBlock, ErrorState, List, Loading, PageContainer, PageHeader } from "canica/ui"
import { HabitRow } from "../components/habit-row.tsx"
import { NewHabitButton } from "../components/new-habit.tsx"
/** Today's board: every active habit with a big toggle, its streak and week progress. */
export default page({
title: "Today",
view: () => {
// The page decides what "today" is (the user's calendar day) and passes it
// to the query; the server has no clock of its own for this.
const today = useToday()
const now = useNow("day")
const habits = useQuery("today", { today })
return (
<PageContainer>
<PageHeader title="Today" description={formatDate(now)} actions={<NewHabitButton />} />
{habits.match({
loading: () => <Loading shape="list" />,
failure: (error) => <ErrorState error={error} />,
success: (list) =>
list.length === 0 ? (
<EmptyBlock
title="No habits yet"
description="Start with something small, like a ten-minute walk."
action={<NewHabitButton />}
/>
) : (
<List>
{list.map((habit) => (
<HabitRow key={habit.id} habit={habit} today={today} />
))}
</List>
),
})}
</PageContainer>
)
},
})
src/components/archived-row.tsx31 lines
import { formatDate, Link, plural, useMutation, type QueryValue } from "canica/client"
import { Button, Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "canica/ui"
/** One archived habit: its facts, a link to its history, and a way back. */
export function ArchivedRow({ habit }: { readonly habit: QueryValue<"archived">[number] }) {
const unarchive = useMutation("setArchived")
return (
<Item>
<ItemContent>
<ItemTitle>
<Link to="/habits/$habit" params={{ habit: habit.id }}>
{habit.emoji} {habit.name}
</Link>
</ItemTitle>
<ItemDescription>
<span className="tabular-nums">
{habit.total > 0
? `${plural(habit.total, "check-in")} ยท last ${formatDate(Date.parse(`${habit.last}T00:00:00`))}`
: "No check-ins yet"}
</span>
</ItemDescription>
</ItemContent>
<ItemActions>
<Button variant="outline" size="sm" onClick={() => void unarchive({ habit: habit.id, archived: false })}>
Unarchive
</Button>
</ItemActions>
</Item>
)
}
src/components/day-grid.tsx48 lines
import { addDays, startOfWeek, useMutation, type Id } from "canica/client"
import { CheckButton } from "canica/ui"
/**
* The last 8 weeks of a habit as a grid of toggle buttons, oldest week on top.
* Days after today (the tail of the current week) are placeholders, not buttons.
*/
export function DayGrid({
habit,
days,
today,
}: {
readonly habit: Id<"habits">
readonly days: ReadonlyArray<string>
readonly today: string
}) {
const setCheckin = useMutation("setCheckin")
const checked = new Set(days)
const mondays = Array.from({ length: 8 }, (_, i) => addDays(startOfWeek(today), -7 * (7 - i)))
return (
<div className="flex flex-col gap-1.5">
<div className="grid grid-cols-7 gap-1.5 text-center text-xs text-muted-foreground">
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((d) => (
<span key={d} aria-hidden>
{d}
</span>
))}
</div>
{mondays.map((monday) => (
<div key={monday} className="grid grid-cols-7 gap-1.5">
{Array.from({ length: 7 }, (_, i) => addDays(monday, i)).map((day) =>
day > today ? (
<span key={day} aria-hidden className="size-10 rounded-full border border-dashed border-border/60" />
) : (
<CheckButton
key={day}
pressed={checked.has(day)}
label={`Toggle ${day}`}
onClick={() => void setCheckin({ habit, day, done: !checked.has(day) })}
/>
),
)}
</div>
))}
</div>
)
}
src/components/edit-habit.tsx25 lines
import { useForm, useMutation, type QueryValue } from "canica/client"
import { ActionStatus, Form, Section, SubmitButton } from "canica/ui"
import { habitFields } from "../../shared/fields.ts"
import { HabitFields } from "./habit-fields.tsx"
/**
* The edit form on a habit's page. The `Form` is keyed by `updatedAt`, so it
* always shows the saved values; feedback survives the re-render.
*/
export function EditHabit({ habit }: { readonly habit: QueryValue<"habit"> }) {
const update = useMutation("updateHabit")
const form = useForm("edit habit", habitFields, (values) => update({ habit: habit.id, ...values }))
return (
<Section title="Edit habit">
<Form form={form} key={habit.updatedAt} className="max-w-md">
<HabitFields form={form} defaults={habit} />
<div className="flex items-center gap-3">
<SubmitButton form={form}>Save changes</SubmitButton>
<ActionStatus status={form.status} success="Saved" />
</div>
</Form>
</Section>
)
}
src/components/habit-fields.tsx44 lines
import type { AnyForm } from "canica/client"
import { FormField, Input, NativeSelect, NativeSelectOption } from "canica/ui"
import { emojiChoices } from "../../shared/fields.ts"
/**
* The three fields of a habit form (create and edit). The values come back
* validated by `habitFields` in shared/fields.ts; selects read strings and the
* `number()` field parses the target back.
*/
export function HabitFields({
form,
defaults,
}: {
readonly form: AnyForm
/** Existing values (the edit form); the create form starts fresh. */
readonly defaults?: { readonly name?: string; readonly emoji?: string; readonly target?: number }
}) {
return (
<>
<FormField form={form} name="name" label="Name">
<Input name="name" defaultValue={defaults?.name} placeholder="Morning run" autoComplete="off" />
</FormField>
<FormField form={form} name="emoji" label="Emoji">
<NativeSelect name="emoji" defaultValue={defaults?.emoji ?? "โญ"}>
{emojiChoices.map((c) => (
<NativeSelectOption key={c.value} value={c.value}>
{c.label}
</NativeSelectOption>
))}
</NativeSelect>
</FormField>
<FormField form={form} name="target" label="Target" description="How many days a week you aim for.">
<NativeSelect name="target" defaultValue={String(defaults?.target ?? 3)}>
{[1, 2, 3, 4, 5, 6, 7].map((n) => (
<NativeSelectOption key={n} value={String(n)}>
{n === 1 ? "1 day a week" : `${n} days a week`}
</NativeSelectOption>
))}
</NativeSelect>
</FormField>
</>
)
}
src/components/habit-row.tsx36 lines
import { Link, useMutation, type QueryValue } from "canica/client"
import { CheckButton, Item, ItemContent, ItemDescription, ItemTitle } from "canica/ui"
/** One of today's habits: a big toggle, the streak and this week's progress. */
export function HabitRow({
habit,
today,
}: {
readonly habit: QueryValue<"today">[number]
readonly today: string
}) {
const setCheckin = useMutation("setCheckin")
return (
<Item>
<CheckButton
pressed={habit.doneToday}
onClick={() => void setCheckin({ habit: habit.id, day: today, done: !habit.doneToday })}
label={`Toggle ${habit.name} for today`}
/>
<ItemContent>
<ItemTitle>
<Link to="/habits/$habit" params={{ habit: habit.id }}>
{habit.emoji} {habit.name}
</Link>
</ItemTitle>
<ItemDescription>
<span className="tabular-nums">
{habit.streak > 0 ? `${habit.streak}-day streak` : "No streak yet"} ยท {habit.weekDone} of {habit.target}{" "}
{habit.target === 1 ? "day" : "days"} this week
</span>
</ItemDescription>
</ItemContent>
</Item>
)
}
src/components/new-habit.tsx40 lines
import { useForm, useMutation } from "canica/client"
import { Button, Form, modal, ModalActions, ModalText, ModalTitle, SubmitButton } from "canica/ui"
import { habitFields } from "../../shared/fields.ts"
import { HabitFields } from "./habit-fields.tsx"
const NewHabitModal = modal()(() => {
const close = NewHabitModal.useClose()
const create = useMutation("createHabit")
const form = useForm("new habit", habitFields, (values) => create(values), { onSuccess: () => close() })
return (
<>
<ModalTitle>New habit</ModalTitle>
<ModalText>Something small you want to do often.</ModalText>
<Form
form={form}
describeError={(e) =>
e._tag === "TooManyHabits" ? `You can keep at most ${e.max} active habits. Archive one first.` : undefined
}
>
<HabitFields form={form} />
<ModalActions>
<Button type="button" variant="outline" onClick={close.cancel}>
Cancel
</Button>
<SubmitButton form={form}>Create habit</SubmitButton>
</ModalActions>
</Form>
</>
)
})
/** Opens the new-habit modal from the page header or the empty state. */
export function NewHabitButton() {
return (
<Button aria-haspopup="dialog" onClick={() => void NewHabitModal.open()}>
New habit
</Button>
)
}
src/styles.css4 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";
src/theme.css60 lines
/*
* App theme: shadcn preset b21qK4knlB (style mira, lime on taupe, font eb-garamond, radius default).
* Generated by `canica theme`. Tweak it visually at https://ui.shadcn.com/create?preset=b21qK4knlB
* 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.3);
--card: oklch(1 0 0);
--card-foreground: oklch(0.147 0.004 49.3);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.147 0.004 49.3);
--primary: oklch(0.841 0.238 128.85);
--primary-foreground: oklch(0.405 0.101 131.063);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.96 0.002 17.2);
--muted-foreground: oklch(0.547 0.021 43.1);
--accent: oklch(0.96 0.002 17.2);
--accent-foreground: oklch(0.214 0.009 43.1);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0.005 34.3);
--input: oklch(0.922 0.005 34.3);
--ring: oklch(0.714 0.014 41.2);
--chart-1: oklch(0.811 0.111 293.571);
--chart-2: oklch(0.606 0.25 292.717);
--chart-3: oklch(0.541 0.281 293.009);
--chart-4: oklch(0.491 0.27 292.581);
--chart-5: oklch(0.432 0.232 292.759);
--radius: 0.625rem;
--font-body: "EB Garamond", ui-sans-serif, system-ui, sans-serif;
--font-display: "Raleway", ui-serif, Georgia, serif;
}
.dark {
--background: oklch(0.147 0.004 49.3);
--foreground: oklch(0.986 0.002 67.8);
--card: oklch(0.214 0.009 43.1);
--card-foreground: oklch(0.986 0.002 67.8);
--popover: oklch(0.214 0.009 43.1);
--popover-foreground: oklch(0.986 0.002 67.8);
--primary: oklch(0.768 0.233 130.85);
--primary-foreground: oklch(0.405 0.101 131.063);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.268 0.011 36.5);
--muted-foreground: oklch(0.714 0.014 41.2);
--accent: oklch(0.268 0.011 36.5);
--accent-foreground: oklch(0.986 0.002 67.8);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.547 0.021 43.1);
--chart-1: oklch(0.811 0.111 293.571);
--chart-2: oklch(0.606 0.25 292.717);
--chart-3: oklch(0.541 0.281 293.009);
--chart-4: oklch(0.491 0.27 292.581);
--chart-5: oklch(0.432 0.232 292.759);
}
server/index.test.ts208 lines
import { describe, expect, it } from "vitest"
import { testApp } from "canica/testing"
import { addDays, startOfWeek } from "canica/fields"
import app from "./index.ts"
import { bestStreak, currentStreak } from "../shared/streak.ts"
/** A habit with some check-ins on day offsets relative to `today` (0 = today). */
const habitWith = (
user: ReturnType<ReturnType<typeof testApp<typeof app>>["as"]>,
offsets: ReadonlyArray<number>,
today: string,
) => {
const habit = user.mutationOk("createHabit", { name: "Read", emoji: "๐", target: 4 })
for (const offset of offsets) user.mutationOk("setCheckin", { habit, day: addDays(today, offset), done: true })
return habit
}
describe("habits: privacy", () => {
it("each user only sees their own habits and history", () => {
const t = testApp(app)
const alice = t.as("alice")
const bob = t.as("bob")
const today = t.today()
const run = alice.mutationOk("createHabit", { name: "Morning run", emoji: "๐", target: 4 })
alice.mutationOk("setCheckin", { habit: run, day: today, done: true })
bob.mutationOk("createHabit", { name: "Read", emoji: "๐", target: 3 })
expect(alice.queryOk("today", { today }).map((h) => h.name)).toEqual(["Morning run"])
expect(bob.queryOk("today", { today }).map((h) => h.name)).toEqual(["Read"])
expect(bob.queryOk("archived")).toEqual([])
})
it("other people's habits look like they do not exist", () => {
const t = testApp(app)
const alice = t.as("alice")
const bob = t.as("bob")
const today = t.today()
const run = alice.mutationOk("createHabit", { name: "Morning run", emoji: "๐", target: 4 })
expect(bob.query("habit", { habit: run, today })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
expect(bob.mutation("setCheckin", { habit: run, day: today, done: true })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
expect(bob.mutation("updateHabit", { habit: run, name: "Hacked", emoji: "โญ", target: 1 })).toMatchObject({
_tag: "Failure",
error: { _tag: "NotFound" },
})
expect(bob.mutation("setArchived", { habit: run, archived: true })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
expect(bob.mutation("deleteHabit", { habit: run })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
// Alice's habit is untouched.
expect(alice.queryOk("habit", { habit: run, today })).toMatchObject({ name: "Morning run", days: [] })
})
it("archiving hides a habit from today's board and lists it with its facts", () => {
const t = testApp(app)
const alice = t.as("alice")
const bob = t.as("bob")
const today = t.today()
const run = alice.mutationOk("createHabit", { name: "Morning run", emoji: "๐", target: 4 })
alice.mutationOk("setCheckin", { habit: run, day: addDays(today, -2), done: true })
alice.mutationOk("setArchived", { habit: run, archived: true })
expect(alice.queryOk("today", { today })).toEqual([])
expect(alice.queryOk("archived")).toMatchObject([
{ name: "Morning run", emoji: "๐", target: 4, total: 1, last: addDays(today, -2) },
])
expect(bob.queryOk("archived")).toEqual([])
// Unarchiving brings it back.
alice.mutationOk("setArchived", { habit: run, archived: false })
expect(alice.queryOk("today", { today }).map((h) => h.name)).toEqual(["Morning run"])
expect(alice.queryOk("archived")).toEqual([])
})
it("deleting a habit makes it (and its page) gone", () => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const run = habitWith(alice, [0], today)
alice.mutationOk("deleteHabit", { habit: run })
expect(alice.query("habit", { habit: run, today })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
expect(alice.queryOk("today", { today })).toEqual([])
})
it("caps the number of active habits", () => {
const t = testApp(app)
const alice = t.as("alice")
for (let i = 0; i < 20; i++) alice.mutationOk("createHabit", { name: `Habit ${i + 1}`, emoji: "โญ", target: 3 })
expect(alice.mutation("createHabit", { name: "One too many", emoji: "โญ", target: 3 })).toMatchObject({
_tag: "Failure",
error: { _tag: "TooManyHabits", max: 20 },
})
// Archiving one frees a slot.
const [first] = alice.queryOk("today", { today: t.today() })
alice.mutationOk("setArchived", { habit: first!.id, archived: true })
expect(alice.mutation("createHabit", { name: "Fits now", emoji: "โญ", target: 3 })._tag).toBe("Success")
})
})
describe("habits: check-ins", () => {
it("keeps at most one check-in per habit per day", () => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const habit = alice.mutationOk("createHabit", { name: "Drink water", emoji: "๐ง", target: 7 })
// Setting the same state repeatedly never adds a second row.
alice.mutationOk("setCheckin", { habit, day: today, done: true })
alice.mutationOk("setCheckin", { habit, day: today, done: true })
expect(alice.queryOk("habit", { habit, today }).days).toEqual([today])
// Turning it off twice is equally fine.
alice.mutationOk("setCheckin", { habit, day: today, done: false })
alice.mutationOk("setCheckin", { habit, day: today, done: false })
expect(alice.queryOk("habit", { habit, today }).days).toEqual([])
})
it("toggles one day without touching the others", () => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const habit = habitWith(alice, [0, -1, -2], today)
expect(alice.mutationOk("setCheckin", { habit, day: addDays(today, -1), done: false })).toBe(false)
expect(alice.queryOk("habit", { habit, today }).days).toEqual([addDays(today, -2), today])
})
it("rejects values the fields do not allow", () => {
const t = testApp(app)
const alice = t.as("alice")
expect(alice.mutation("createHabit", { name: " ", emoji: "โญ", target: 3 })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["name"] }] },
})
expect(alice.mutation("createHabit", { name: "Run", emoji: "๐ฅ", target: 3 })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["emoji"] }] },
})
expect(alice.mutation("createHabit", { name: "Run", emoji: "โญ", target: 8 })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["target"] }] },
})
const habit = alice.mutationOk("createHabit", { name: "Run", emoji: "โญ", target: 3 })
expect(alice.mutation("setCheckin", { habit, day: "2026-02-30", done: true })).toMatchObject({
_tag: "Failure",
error: { _tag: "InvalidArgs", issues: [{ path: ["day"] }] },
})
})
})
describe("habits: streak math", () => {
it.each([
["no check-ins yet", [], 0],
["only today", [0], 1],
["only yesterday", [-1], 1],
["the last three days", [0, -1, -2], 3],
["a run that ended two days ago", [-2, -3], 0],
["a run ending yesterday", [-1, -2], 2],
["an older gap before yesterday", [-1, -2, -4], 2],
["a long run with one hole", [0, -1, -2, -4, -5, -6], 3],
] as const)("counts %s", (_, offsets, expected) => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const habit = habitWith(alice, offsets, today)
const [row] = alice.queryOk("today", { today })
expect(row!.id).toBe(habit)
expect(row!.streak).toBe(expected)
expect(alice.queryOk("habit", { habit, today }).streak).toBe(expected)
})
it("counts the week's progress from Monday, not from the first check-in", () => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const weekStart = startOfWeek(today)
const habit = alice.mutationOk("createHabit", { name: "Read", emoji: "๐", target: 4 })
// Sunday of last week: history, but not this week's progress (nor a live streak: the run ends Monday).
alice.mutationOk("setCheckin", { habit, day: addDays(weekStart, -1), done: true })
expect(alice.queryOk("today", { today })[0]!.weekDone).toBe(0)
expect(alice.queryOk("today", { today })[0]!.streak).toBe(0)
// Monday counts towards this week.
alice.mutationOk("setCheckin", { habit, day: weekStart, done: true })
expect(alice.queryOk("today", { today })[0]!.weekDone).toBe(1)
expect(alice.queryOk("today", { today })[0]!.streak).toBe(0)
})
it("totals and best streaks come from the whole history", () => {
const t = testApp(app)
const alice = t.as("alice")
const today = t.today()
const habit = habitWith(alice, [-10, -9, -8, -5, -4, -3], today)
expect(alice.queryOk("habit", { habit, today })).toMatchObject({ total: 6, best: 3, streak: 0 })
// Checking in today starts a fresh run without touching the old best.
alice.mutationOk("setCheckin", { habit, day: today, done: true })
expect(alice.queryOk("habit", { habit, today })).toMatchObject({ total: 7, best: 3, streak: 1 })
})
it("the helpers handle month, week and leap-year boundaries", () => {
expect(currentStreak(["2026-01-31", "2026-02-01"], "2026-02-01")).toBe(2)
expect(currentStreak(["2026-01-11", "2026-01-12"], "2026-01-12")).toBe(2) // Sunday into Monday
expect(bestStreak(["2028-02-27", "2028-02-28", "2028-02-29", "2028-03-01", "2028-03-03"])).toBe(4)
expect(bestStreak([])).toBe(0)
})
})
src/app.test.tsx109 lines
import { describe, it } from "vitest"
import { addDays } from "canica/fields"
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("habits (scenes)", () => {
it("creates a habit from the modal, checks in, and the streak shows", async () => {
const t = testApp(app)
await scene(t, routes,
as("ana"),
visit("/"),
see(text("No habits yet")),
click(role("button", { name: "New habit" })),
within(role("dialog"),
type(label("Name"), "Morning run"),
choose(label("Emoji"), "๐ Run"),
choose(label("Target"), "3 days a week"),
click(role("button", { name: "Create habit" })),
),
notSee(role("dialog")),
see(text(/Morning run/)),
click(role("button", { name: "Toggle Morning run for today" })),
see(text(/1-day streak/)),
see(text(/1 of 3 days this week/)),
)
})
it("a second user sees nothing of the first", async () => {
const t = testApp(app)
let habit = missingId("habits")
await scene(t, routes,
as("ana"),
visit("/"),
meanwhile(() => {
habit = t.as("ana").mutationOk("createHabit", { name: "Morning run", emoji: "๐", target: 4 })
}),
see(text(/Morning run/)),
as("bob"),
visit("/"),
see(text("No habits yet")),
notSee(text(/Morning run/)),
visit("/habits/$habit", () => ({ habit })),
see(text("This habit does not exist")),
visit("/archived"),
see(text("Nothing archived")),
)
})
it("the habit page shows stats, toggles any day in the grid, and saves edits", async () => {
const t = testApp(app)
const today = t.today()
const read = t.as("ana").mutationOk("createHabit", { name: "Read", emoji: "๐", target: 4 })
for (const offset of [-3, -2, -1]) {
t.as("ana").mutationOk("setCheckin", { habit: read, day: addDays(today, offset), done: true })
}
await scene(t, routes,
as("ana"),
visit("/habits/$habit", { habit: read }),
see(role("heading", { name: /Read/ })),
see(text("3 days")),
click(role("button", { name: `Toggle ${today}` })),
see(text("4 days")),
see(text("4 of 4")),
type(label("Name"), "Read fiction"),
click(role("button", { name: "Save changes" })),
see(role("heading", { name: /Read fiction/ })),
see(text("Saved")),
)
})
it("archiving moves a habit out of today and into the archived page, and back", async () => {
const t = testApp(app)
const meditate = t.as("ana").mutationOk("createHabit", { name: "Meditate", emoji: "๐ง", target: 7 })
t.as("ana").mutationOk("setCheckin", { habit: meditate, day: t.today(), done: true })
await scene(t, routes,
as("ana"),
visit("/"),
see(text(/Meditate/)),
visit("/habits/$habit", { habit: meditate }),
click(role("button", { name: "Archive" })),
see(role("button", { name: "Unarchive" })),
visit("/archived"),
see(text(/Meditate/)),
see(text(/1 check-in/)),
click(role("button", { name: "Unarchive" })),
notSee(text(/Meditate/)),
visit("/"),
see(text(/Meditate/)),
)
})
})