Canica

Kanso

A personal organizer: todos, planner, habits, routines, wishlist. The largest example.

many tables and routesfilesactionscrons

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

Files

server/index.ts1110 lines
import {
  and,
  asc,
  boolean,
  day,
  desc,
  eq,
  file,
  Files,
  gte,
  id,
  inArray,
  isNotNull,
  isNull,
  like,
  lte,
  mutation,
  NotFound,
  number,
  or,
  query,
  schema,
  Scheduler,
  SignedInViewer,
  string,
  table,
  TaggedError,
  userId,
  type ActionCtx,
  type FileId,
  type FilesShape,
  type Id,
} from "canica/server"
import { addDays } from "canica/fields"
import {
  captureText,
  dumpText,
  duration,
  emoji,
  eventTitle,
  habitName,
  itemTitle,
  linkUrl,
  price,
  projectName,
  routineName,
  stepList,
  tagList,
  tagName,
  timeOfDay,
  todoNotes,
  todoTitle,
  trackerKind,
  trackerStatus,
  wishTitle,
  year,
} from "../shared/fields.ts"
import { bestStreak, currentStreak, gridWeeks, isLink, parseCapture, parseTime, siteOf } from "../shared/logic.ts"
import { imdbId, imdbSuggestionUrl, parseImdb, parsePreview, type ImdbSuggestion, type Preview } from "./preview.ts"

export const { app, Db, tables } = schema({
  projects: table({ owner: userId(), name: projectName }).index("by_owner", ["owner"]),
  todos: table({
    owner: userId(),
    title: todoTitle,
    notes: todoNotes.optional(),
    /** No project: the Inbox. */
    project: id("projects").optional(),
    due: day().optional(),
    /** Scheduled at, in minutes since midnight of `due` (the Planner shows it on the timeline). */
    start: number().int().min(0).max(1439).optional(),
    minutes: duration.default(30),
    done: boolean().default(false),
    /** The day it was ticked off: Today keeps showing what was done today. */
    doneOn: day().optional(),
  })
    .index("by_owner_due", ["owner", "due"])
    .index("by_owner_project", ["owner", "project"]),
  // Tags are rows, not an array: lists filter on them.
  todoTags: table({ owner: userId(), todo: id("todos").onDelete("cascade"), tag: tagName })
    .unique("by_todo_tag", ["todo", "tag"])
    .index("by_owner_tag", ["owner", "tag"]),

  habits: table({ owner: userId(), name: habitName, emoji: emoji.optional() }).index("by_owner", ["owner"]),
  habitTicks: table({ owner: userId(), habit: id("habits").onDelete("cascade"), day: day() }).unique("by_habit_day", ["habit", "day"]),

  routines: table({ owner: userId(), name: routineName, emoji: emoji.optional() }).index("by_owner", ["owner"]),
  routineSteps: table({ owner: userId(), routine: id("routines").onDelete("cascade"), text: string().trim().min(1).max(120), position: number().int() }).index(
    "by_routine",
    ["routine"],
  ),
  /** A step ticked on a day: the run of a routine on that day is its ticks. */
  routineTicks: table({
    owner: userId(),
    routine: id("routines").onDelete("cascade"),
    step: id("routineSteps").onDelete("cascade"),
    day: day(),
  })
    .unique("by_step_day", ["step", "day"])
    .index("by_routine_day", ["routine", "day"]),

  events: table({
    owner: userId(),
    title: eventTitle,
    day: day(),
    start: number().int().min(0).max(1439),
    end: number().int().min(1).max(1440),
    notes: todoNotes.optional(),
  }).index("by_owner_day", ["owner", "day"]),

  trackerItems: table({
    owner: userId(),
    url: linkUrl.optional(),
    title: itemTitle,
    kind: trackerKind,
    status: trackerStatus.default("backlog"),
    year: year.optional(),
    description: string().max(500).optional(),
    site: string().max(80).optional(),
    poster: file().optional(),
  }).index("by_owner", ["owner"]),

  wishItems: table({
    owner: userId(),
    title: wishTitle,
    url: linkUrl.optional(),
    price: price.optional(),
    site: string().max(80).optional(),
    image: file().optional(),
    bought: boolean().default(false),
  }).index("by_owner", ["owner"]),

  dumpItems: table({
    owner: userId(),
    kind: string().pattern(/^(note|link|image)$/),
    text: dumpText.optional(),
    url: linkUrl.optional(),
    title: string().max(200).optional(),
    description: string().max(500).optional(),
    site: string().max(80).optional(),
    image: file().optional(),
  }).index("by_owner", ["owner"]),
})
const { projects, todos, todoTags, habits, habitTicks, routines, routineSteps, routineTicks, events, trackerItems, wishItems, dumpItems } = tables

// ---------------------------------------------------------------------------
// Errors

export class EndBeforeStart extends TaggedError("EndBeforeStart")<{}> {
  override get message() {
    return "The event has to end after it starts"
  }
}
export class TooMany extends TaggedError("TooMany")<{ readonly what: string; readonly max: number }> {
  override get message() {
    return `You can have at most ${this.max} ${this.what}`
  }
}
export class NotALink extends TaggedError("NotALink")<{}> {
  override get message() {
    return "This item has no link"
  }
}

// ---------------------------------------------------------------------------
// Helpers

function* viewerId() {
  return (yield* SignedInViewer).userId
}

/** Rows of other people look like they do not exist. */
function* owned<R extends { readonly owner: string }>(row: R, table: string, rowId: string) {
  if (row.owner !== (yield* viewerId())) return yield* new NotFound({ table, id: rowId })
  return row
}

function* ownTodo(todoId: Id<"todos">) {
  return yield* owned(yield* (yield* Db).get(todos, todoId), "todos", todoId)
}
function* ownProject(projectId: Id<"projects">) {
  return yield* owned(yield* (yield* Db).get(projects, projectId), "projects", projectId)
}
function* ownHabit(habitId: Id<"habits">) {
  return yield* owned(yield* (yield* Db).get(habits, habitId), "habits", habitId)
}
function* ownRoutine(routineId: Id<"routines">) {
  return yield* owned(yield* (yield* Db).get(routines, routineId), "routines", routineId)
}
function* ownEvent(eventId: Id<"events">) {
  return yield* owned(yield* (yield* Db).get(events, eventId), "events", eventId)
}
function* ownTracker(itemId: Id<"trackerItems">) {
  return yield* owned(yield* (yield* Db).get(trackerItems, itemId), "trackerItems", itemId)
}
function* ownWish(itemId: Id<"wishItems">) {
  return yield* owned(yield* (yield* Db).get(wishItems, itemId), "wishItems", itemId)
}
function* ownDump(itemId: Id<"dumpItems">) {
  return yield* owned(yield* (yield* Db).get(dumpItems, itemId), "dumpItems", itemId)
}

type TodoRow = typeof todos.$inferSelect

/** Todos as pages see them: with their tags and project name. */
function* withDetails(list: ReadonlyArray<TodoRow>) {
  const db = yield* Db
  const ids = list.map((t) => t.id)
  const tagRows = ids.length ? yield* db.select().from(todoTags).where(inArray(todoTags.todo, ids)) : []
  const projectIds = [...new Set(list.flatMap((t) => (t.project ? [t.project] : [])))]
  const names = projectIds.length ? yield* db.select({ id: projects.id, name: projects.name }).from(projects).where(inArray(projects.id, projectIds)) : []
  return list.map((t) => ({
    ...t,
    tags: tagRows
      .filter((r) => r.todo === t.id)
      .map((r) => r.tag)
      .sort(),
    projectName: names.find((p) => p.id === t.project)?.name ?? null,
  }))
}

/** Open todos first (by due day, undated last), then done ones (latest first). */
const byDue = (a: TodoRow, b: TodoRow): number => {
  if (a.done !== b.done) return a.done ? 1 : -1
  if (a.done) return b.updatedAt - a.updatedAt
  if (a.due !== b.due) return a.due === null ? 1 : b.due === null ? -1 : a.due < b.due ? -1 : 1
  if (a.start !== b.start) return a.start === null ? 1 : b.start === null ? -1 : a.start - b.start
  return a.createdAt - b.createdAt
}

function* setTags(todoId: Id<"todos">, tags: ReadonlyArray<string>) {
  const db = yield* Db
  const owner = yield* viewerId()
  yield* db.delete(todoTags).where(eq(todoTags.todo, todoId))
  const unique = [...new Set(tags.map((t) => t.toLowerCase()))].slice(0, 8)
  if (unique.length) yield* db.insert(todoTags).values(unique.map((tag) => ({ owner, todo: todoId, tag })))
}

const MAX_TODOS = 5000

function* insertTodo(values: {
  readonly title: string
  readonly notes?: string | null
  readonly project?: Id<"projects"> | null
  readonly due?: string | null
  readonly start?: number | null
  readonly minutes?: number
  readonly tags?: ReadonlyArray<string>
}) {
  const db = yield* Db
  const owner = yield* viewerId()
  if ((yield* db.count(todos, eq(todos.owner, owner))) >= MAX_TODOS) return yield* new TooMany({ what: "todos", max: MAX_TODOS })
  if (values.project) yield* ownProject(values.project)
  const [row] = yield* db
    .insert(todos)
    .values({
      owner,
      title: values.title,
      notes: values.notes ?? null,
      project: values.project ?? null,
      due: values.due ?? null,
      start: values.due ? (values.start ?? null) : null,
      minutes: values.minutes ?? 30,
    })
    .returning({ id: todos.id })
  if (values.tags?.length) yield* setTags(row!.id, values.tags)
  return row!.id
}

const withUrl = <T extends Record<K, FileId | null>, K extends string>(files: FilesShape, row: T, key: K) => ({
  ...row,
  [`${key}Url`]: row[key] ? files.url(row[key]) : null,
}) as T & Record<`${K}Url`, string | null>

/** `%` and `_` typed in a search are literal. */
const contains = (q: string) => `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`

// ---------------------------------------------------------------------------
// Link previews (actions)

const BROWSER_HEADERS = {
  "user-agent": "Mozilla/5.0 (compatible; KansoLinkPreview/1.0; +https://kanso.canica.run)",
  accept: "text/html,application/xhtml+xml",
  "accept-language": "en",
}

/** Fetch a link's preview: IMDb titles from IMDb's suggestion JSON, everything else from the page's OpenGraph tags. */
function* readPreview(ctx: ActionCtx, url: string) {
  const imdb = imdbId(url)
  if (imdb) {
    const text = yield* ctx.fetchText(imdbSuggestionUrl(imdb))
    let json: ImdbSuggestion = {}
    try {
      json = JSON.parse(text) as ImdbSuggestion
    } catch {
      json = {}
    }
    const found = parseImdb(json, imdb)
    if (found) return found
  }
  const html = yield* ctx.fetchText(url, { headers: BROWSER_HEADERS })
  return parsePreview(html.slice(0, 2_000_000), url)
}

/** Download a preview image into the app's files. */
function* storeImage(ctx: ActionCtx, src: string, name: string) {
  const res = yield* ctx.fetch(src, { headers: { "user-agent": BROWSER_HEADERS["user-agent"], accept: "image/*" } })
  const type = res.headers.get("content-type") ?? ""
  if (!res.ok || !/^image\/(png|jpe?g|webp|gif|avif)/i.test(type)) return null
  return yield* ctx.files.store(res, { name, type: type.split(";")[0] })
}

const previewFields = (p: Preview) => ({
  title: p.title?.slice(0, 200) ?? null,
  description: p.description?.slice(0, 500) ?? null,
  site: p.site?.slice(0, 80) ?? null,
})

// ---------------------------------------------------------------------------

export default app({
  name: "Kanso",
  icon: "leaf",
  access: "signedIn",
  queries: {
    // -- Today -------------------------------------------------------------
    /** What is due today or overdue and still open, plus what was ticked off today. */
    today: query({ today: day() }, function* ({ today }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const rows = yield* db
        .select()
        .from(todos)
        .where(and(eq(todos.owner, owner), isNotNull(todos.due), lte(todos.due, today)))
        .limit(1000)
      const shown = rows.filter((t) => !t.done || t.doneOn === today).sort(byDue)
      const list = yield* withDetails(shown)
      return {
        overdue: list.filter((t) => t.due! < today && !t.done),
        today: list.filter((t) => t.due === today || t.done),
        left: shown.filter((t) => !t.done).length,
      }
    }),

    // -- Todos -------------------------------------------------------------
    /** The lists for the Todos navigation: Inbox, projects and tags, with open counts. */
    todoLists: query(function* () {
      const db = yield* Db
      const owner = yield* viewerId()
      const open = yield* db
        .select({ id: todos.id, project: todos.project })
        .from(todos)
        .where(and(eq(todos.owner, owner), eq(todos.done, false)))
        .limit(10_000)
      const projectRows = yield* db.select().from(projects).where(eq(projects.owner, owner)).orderBy(asc(projects.name))
      const tagRows = yield* db.select({ todo: todoTags.todo, tag: todoTags.tag }).from(todoTags).where(eq(todoTags.owner, owner)).limit(10_000)
      const openIds = new Set(open.map((t) => t.id))
      const tagCounts = new Map<string, number>()
      for (const r of tagRows) tagCounts.set(r.tag, (tagCounts.get(r.tag) ?? 0) + (openIds.has(r.todo) ? 1 : 0))
      return {
        inbox: open.filter((t) => t.project === null).length,
        all: open.length,
        projects: projectRows.map((p) => ({ id: p.id, name: p.name, open: open.filter((t) => t.project === p.id).length })),
        tags: [...tagCounts].map(([tag, open]) => ({ tag, open })).sort((a, b) => a.tag.localeCompare(b.tag)),
      }
    }),

    /** A list of todos: the Inbox, everything, a project or a tag; `q` filters by title. Done ones last. */
    todoList: query(
      {
        list: string().pattern(/^(inbox|all|project|tag)$/),
        project: id("projects").optional(),
        tag: tagName.optional(),
        q: string().trim().max(100).optional(),
      },
      function* ({ list, project, tag, q }) {
        const db = yield* Db
        const owner = yield* viewerId()
        if (list === "project" && project) yield* ownProject(project)
        const conds = [eq(todos.owner, owner)]
        if (list === "inbox") conds.push(isNull(todos.project))
        if (list === "project" && project) conds.push(eq(todos.project, project))
        if (list === "tag" && tag) {
          const tagged = yield* db
            .select({ todo: todoTags.todo })
            .from(todoTags)
            .where(and(eq(todoTags.owner, owner), eq(todoTags.tag, tag)))
            .limit(10_000)
          conds.push(
            inArray(
              todos.id,
              tagged.map((r) => r.todo),
            ),
          )
        }
        if (q) conds.push(like(todos.title, contains(q)))
        const rows = yield* db.select().from(todos).where(and(...conds)).orderBy(desc(todos.createdAt)).limit(2000)
        const open = rows.filter((t) => !t.done).sort(byDue)
        const done = rows.filter((t) => t.done).sort(byDue).slice(0, 20)
        return { open: yield* withDetails(open), done: yield* withDetails(done) }
      },
    ),

    todo: query({ id: id("todos") }, function* ({ id }) {
      const [t] = yield* withDetails([yield* ownTodo(id)])
      return t!
    }),

    projects: query(function* () {
      const owner = yield* viewerId()
      return yield* (yield* Db).select().from(projects).where(eq(projects.owner, owner)).orderBy(asc(projects.name))
    }),

    project: query({ id: id("projects") }, function* ({ id }) {
      return yield* ownProject(id)
    }),

    /** Every tag the viewer used, for the tag checkboxes. */
    tags: query(function* () {
      const owner = yield* viewerId()
      const rows = yield* (yield* Db).select({ tag: todoTags.tag }).from(todoTags).where(eq(todoTags.owner, owner)).limit(10_000)
      return [...new Set(rows.map((r) => r.tag))].sort()
    }),

    // -- Habits ------------------------------------------------------------
    /** Each habit with today's tick, its current and best streak and the last 4 weeks as a grid. */
    habits: query({ today: day() }, function* ({ today }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const list = yield* db.select().from(habits).where(eq(habits.owner, owner)).orderBy(asc(habits.createdAt))
      const ticks = list.length
        ? yield* db
            .select({ habit: habitTicks.habit, day: habitTicks.day })
            .from(habitTicks)
            .where(and(inArray(habitTicks.habit, list.map((h) => h.id)), gte(habitTicks.day, addDays(today, -400))))
            .limit(10_000)
        : []
      const weeks = gridWeeks(today, 4)
      return list.map((h) => {
        const days = new Set(ticks.filter((t) => t.habit === h.id).map((t) => t.day))
        return {
          ...h,
          doneToday: days.has(today),
          streak: currentStreak(days, today),
          best: bestStreak(days),
          weeks: weeks.map((week) => week.map((d) => ({ day: d, done: days.has(d), future: d > today }))),
          last28: weeks.flat().filter((d) => d <= today && days.has(d)).length,
        }
      })
    }),

    habit: query({ id: id("habits") }, function* ({ id }) {
      return yield* ownHabit(id)
    }),

    // -- Routines ----------------------------------------------------------
    routines: query({ today: day() }, function* ({ today }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const list = yield* db.select().from(routines).where(eq(routines.owner, owner)).orderBy(asc(routines.createdAt))
      const ids = list.map((r) => r.id)
      const steps = ids.length ? yield* db.select({ routine: routineSteps.routine }).from(routineSteps).where(inArray(routineSteps.routine, ids)) : []
      const ticks = ids.length
        ? yield* db
            .select({ routine: routineTicks.routine })
            .from(routineTicks)
            .where(and(inArray(routineTicks.routine, ids), eq(routineTicks.day, today)))
        : []
      return list.map((r) => ({
        ...r,
        steps: steps.filter((s) => s.routine === r.id).length,
        done: ticks.filter((t) => t.routine === r.id).length,
      }))
    }),

    /** A routine and its steps, each ticked or not on `day`: the run of that day. */
    routine: query({ id: id("routines"), day: day() }, function* ({ id, day }) {
      const db = yield* Db
      const routine = yield* ownRoutine(id)
      const steps = yield* db.select().from(routineSteps).where(eq(routineSteps.routine, id)).orderBy(asc(routineSteps.position))
      const ticks = yield* db
        .select({ step: routineTicks.step })
        .from(routineTicks)
        .where(and(eq(routineTicks.routine, id), eq(routineTicks.day, day)))
      const ticked = new Set(ticks.map((t) => t.step))
      return {
        ...routine,
        steps: steps.map((s) => ({ id: s.id, text: s.text, done: ticked.has(s.id) })),
        done: steps.filter((s) => ticked.has(s.id)).length,
      }
    }),

    // -- Planner -----------------------------------------------------------
    /** One day: its events and scheduled todos on the timeline, and the todos due that day without a time. */
    planner: query({ day: day() }, function* ({ day }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const dayEvents = yield* db
        .select()
        .from(events)
        .where(and(eq(events.owner, owner), eq(events.day, day)))
        .orderBy(asc(events.start))
      const due = yield* withDetails(
        yield* db
          .select()
          .from(todos)
          .where(and(eq(todos.owner, owner), eq(todos.due, day)))
          .limit(500),
      )
      const blocks = [
        ...dayEvents.map((e) => ({ kind: "event" as const, id: e.id, title: e.title, start: e.start, end: e.end, done: false, tags: [] as ReadonlyArray<string> })),
        ...due
          .filter((t) => t.start !== null)
          .map((t) => ({ kind: "todo" as const, id: t.id, title: t.title, start: t.start!, end: Math.min(1440, t.start! + t.minutes), done: t.done, tags: t.tags })),
      ].sort((a, b) => a.start - b.start || a.end - b.end)
      return {
        blocks,
        unscheduled: due.filter((t) => t.start === null && !t.done).sort(byDue),
      }
    }),

    event: query({ id: id("events") }, function* ({ id }) {
      return yield* ownEvent(id)
    }),

    // -- Tracker -----------------------------------------------------------
    tracker: query({ status: trackerStatus.optional() }, function* ({ status }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const files = yield* Files
      const rows = yield* db
        .select()
        .from(trackerItems)
        .where(status ? and(eq(trackerItems.owner, owner), eq(trackerItems.status, status)) : eq(trackerItems.owner, owner))
        .orderBy(desc(trackerItems.updatedAt))
        .limit(1000)
      return rows.map((r) => withUrl(files, r, "poster"))
    }),

    trackerItem: query({ id: id("trackerItems") }, function* ({ id }) {
      return withUrl(yield* Files, yield* ownTracker(id), "poster")
    }),

    // -- Wishlist ----------------------------------------------------------
    wishlist: query(function* () {
      const db = yield* Db
      const owner = yield* viewerId()
      const files = yield* Files
      const rows = yield* db.select().from(wishItems).where(eq(wishItems.owner, owner)).orderBy(desc(wishItems.createdAt)).limit(1000)
      const wanted = rows.filter((r) => !r.bought)
      return {
        wanted: wanted.map((r) => withUrl(files, r, "image")),
        bought: rows.filter((r) => r.bought).map((r) => withUrl(files, r, "image")),
        total: wanted.reduce((sum, r) => sum + (r.price ?? 0), 0),
      }
    }),

    wishItem: query({ id: id("wishItems") }, function* ({ id }) {
      return withUrl(yield* Files, yield* ownWish(id), "image")
    }),

    // -- Dump --------------------------------------------------------------
    dump: query({ q: string().trim().max(100).optional() }, function* ({ q }) {
      const db = yield* Db
      const owner = yield* viewerId()
      const files = yield* Files
      const where = q
        ? and(eq(dumpItems.owner, owner), or(like(dumpItems.text, contains(q)), like(dumpItems.title, contains(q)), like(dumpItems.url, contains(q)), like(dumpItems.description, contains(q))))
        : eq(dumpItems.owner, owner)
      const rows = yield* db.select().from(dumpItems).where(where).orderBy(desc(dumpItems.createdAt)).limit(500)
      return rows.map((r) => withUrl(files, r, "image"))
    }),

    // -- Search (the command palette) --------------------------------------
    /** Everything whose name contains `q`, a few of each kind. */
    search: query({ q: string().trim().max(100) }, function* ({ q }) {
      if (q === "") return { todos: [], projects: [], habits: [], routines: [], events: [], tracker: [], wishlist: [], dump: [] }
      const db = yield* Db
      const owner = yield* viewerId()
      const pattern = contains(q)
      const todoHits = yield* db
        .select({ id: todos.id, title: todos.title, due: todos.due, done: todos.done })
        .from(todos)
        .where(and(eq(todos.owner, owner), like(todos.title, pattern)))
        .orderBy(asc(todos.done), desc(todos.createdAt))
        .limit(6)
      const projectHits = yield* db.select({ id: projects.id, name: projects.name }).from(projects).where(and(eq(projects.owner, owner), like(projects.name, pattern))).limit(4)
      const habitHits = yield* db.select({ id: habits.id, name: habits.name }).from(habits).where(and(eq(habits.owner, owner), like(habits.name, pattern))).limit(4)
      const routineHits = yield* db.select({ id: routines.id, name: routines.name }).from(routines).where(and(eq(routines.owner, owner), like(routines.name, pattern))).limit(4)
      const eventHits = yield* db
        .select({ id: events.id, title: events.title, day: events.day })
        .from(events)
        .where(and(eq(events.owner, owner), like(events.title, pattern)))
        .orderBy(desc(events.day))
        .limit(4)
      const trackerHits = yield* db
        .select({ id: trackerItems.id, title: trackerItems.title, kind: trackerItems.kind, status: trackerItems.status })
        .from(trackerItems)
        .where(and(eq(trackerItems.owner, owner), like(trackerItems.title, pattern)))
        .limit(4)
      const wishHits = yield* db.select({ id: wishItems.id, title: wishItems.title }).from(wishItems).where(and(eq(wishItems.owner, owner), like(wishItems.title, pattern))).limit(4)
      const dumpHits = yield* db
        .select({ id: dumpItems.id, text: dumpItems.text, title: dumpItems.title, url: dumpItems.url })
        .from(dumpItems)
        .where(and(eq(dumpItems.owner, owner), or(like(dumpItems.text, pattern), like(dumpItems.title, pattern), like(dumpItems.url, pattern))))
        .limit(4)
      return {
        todos: todoHits,
        projects: projectHits,
        habits: habitHits,
        routines: routineHits,
        events: eventHits,
        tracker: trackerHits,
        wishlist: wishHits,
        dump: dumpHits.map((d) => ({ id: d.id, title: d.title ?? d.text ?? d.url ?? "Image" })),
      }
    }),
  },

  mutations: {
    // -- Todos -------------------------------------------------------------
    createTodo: mutation(
      {
        title: todoTitle,
        notes: todoNotes.optional(),
        project: id("projects").optional(),
        due: day().optional(),
        time: timeOfDay.optional(),
        minutes: duration.optional(),
        tags: tagList.optional(),
        newTags: string().trim().max(200).optional(),
      },
      function* ({ title, notes, project, due, time, minutes, tags, newTags }) {
        return yield* insertTodo({
          title,
          notes,
          project,
          due,
          start: time ? parseTime(time) : null,
          minutes: minutes ?? 30,
          tags: [...(tags ?? []), ...splitTags(newTags)],
        })
      },
    ),

    /** Quick capture: "Pay rent #home tomorrow". `due` is the day it lands on when the text names none (Today passes today). */
    capture: mutation(
      { text: captureText, today: day(), project: id("projects").optional(), due: day().optional() },
      function* ({ text, today, project, due }) {
        const c = parseCapture(text, today)
        return yield* insertTodo({ title: c.title.slice(0, 160), project, due: c.due ?? due, tags: c.tags })
      },
    ),

    updateTodo: mutation(
      {
        id: id("todos"),
        title: todoTitle,
        notes: todoNotes.optional(),
        project: id("projects").optional(),
        due: day().optional(),
        time: timeOfDay.optional(),
        minutes: duration.optional(),
        tags: tagList.optional(),
        newTags: string().trim().max(200).optional(),
      },
      function* ({ id, title, notes, project, due, time, minutes, tags, newTags }) {
        const db = yield* Db
        const todo = yield* ownTodo(id)
        if (project) yield* ownProject(project)
        yield* db
          .update(todos)
          .set({
            title,
            notes: notes ?? null,
            project: project ?? null,
            due: due ?? null,
            start: due && time ? parseTime(time) : null,
            minutes: minutes ?? todo.minutes,
          })
          .where(eq(todos.id, id))
        yield* setTags(id, [...(tags ?? []), ...splitTags(newTags)])
      },
    ),

    /** Tick a todo off (or back on). `today` is the viewer's day: Today keeps showing it until tomorrow. */
    setDone: mutation({ id: id("todos"), done: boolean(), today: day() }, function* ({ id, done, today }) {
      yield* ownTodo(id)
      yield* (yield* Db).update(todos).set({ done, doneOn: done ? today : null }).where(eq(todos.id, id))
    }),

    /** Put a todo on the Planner's timeline: on `day` at `time`, for `minutes`. */
    scheduleTodo: mutation({ id: id("todos"), day: day(), time: timeOfDay, minutes: duration }, function* ({ id, day, time, minutes }) {
      yield* ownTodo(id)
      yield* (yield* Db).update(todos).set({ due: day, start: parseTime(time), minutes }).where(eq(todos.id, id))
    }),

    /** Keep the day, drop the time. */
    unscheduleTodo: mutation({ id: id("todos") }, function* ({ id }) {
      yield* ownTodo(id)
      yield* (yield* Db).update(todos).set({ start: null }).where(eq(todos.id, id))
    }),

    deleteTodo: mutation({ id: id("todos") }, function* ({ id }) {
      yield* ownTodo(id)
      yield* (yield* Db).delete(todos).where(eq(todos.id, id))
    }),

    createProject: mutation({ name: projectName }, function* ({ name }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(projects, eq(projects.owner, owner))) >= 100) return yield* new TooMany({ what: "projects", max: 100 })
      const [row] = yield* db.insert(projects).values({ owner, name }).returning({ id: projects.id })
      return row!.id
    }),

    renameProject: mutation({ id: id("projects"), name: projectName }, function* ({ id, name }) {
      yield* ownProject(id)
      yield* (yield* Db).update(projects).set({ name }).where(eq(projects.id, id))
    }),

    /** Delete a project; its todos move to the Inbox. */
    deleteProject: mutation({ id: id("projects") }, function* ({ id }) {
      const db = yield* Db
      yield* ownProject(id)
      yield* db.update(todos).set({ project: null }).where(eq(todos.project, id))
      yield* db.delete(projects).where(eq(projects.id, id))
    }),

    // -- Habits ------------------------------------------------------------
    createHabit: mutation({ name: habitName, emoji: emoji.optional() }, function* ({ name, emoji }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(habits, eq(habits.owner, owner))) >= 50) return yield* new TooMany({ what: "habits", max: 50 })
      const [row] = yield* db.insert(habits).values({ owner, name, emoji: emoji || null }).returning({ id: habits.id })
      return row!.id
    }),

    updateHabit: mutation({ id: id("habits"), name: habitName, emoji: emoji.optional() }, function* ({ id, name, emoji }) {
      yield* ownHabit(id)
      yield* (yield* Db).update(habits).set({ name, emoji: emoji || null }).where(eq(habits.id, id))
    }),

    deleteHabit: mutation({ id: id("habits") }, function* ({ id }) {
      yield* ownHabit(id)
      yield* (yield* Db).delete(habits).where(eq(habits.id, id))
    }),

    /** Tick a habit on a day, or untick it. */
    setTick: mutation({ habit: id("habits"), day: day(), done: boolean() }, function* ({ habit, day, done }) {
      const db = yield* Db
      yield* ownHabit(habit)
      const where = and(eq(habitTicks.habit, habit), eq(habitTicks.day, day))
      const [tick] = yield* db.select({ id: habitTicks.id }).from(habitTicks).where(where).limit(1)
      if (done && !tick) yield* db.insert(habitTicks).values({ owner: yield* viewerId(), habit, day })
      if (!done && tick) yield* db.delete(habitTicks).where(where)
    }),

    // -- Routines ----------------------------------------------------------
    createRoutine: mutation({ name: routineName, emoji: emoji.optional(), steps: stepList }, function* ({ name, emoji, steps }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(routines, eq(routines.owner, owner))) >= 50) return yield* new TooMany({ what: "routines", max: 50 })
      const [row] = yield* db.insert(routines).values({ owner, name, emoji: emoji || null }).returning({ id: routines.id })
      yield* db.insert(routineSteps).values(steps.map((text, position) => ({ owner, routine: row!.id, text, position })))
      return row!.id
    }),

    /** Rename a routine and rewrite its steps in order. A step keeps today's tick when it stays at its place. */
    updateRoutine: mutation({ id: id("routines"), name: routineName, emoji: emoji.optional(), steps: stepList }, function* ({ id, name, emoji, steps }) {
      const db = yield* Db
      const owner = yield* viewerId()
      yield* ownRoutine(id)
      yield* db.update(routines).set({ name, emoji: emoji || null }).where(eq(routines.id, id))
      const existing = yield* db.select().from(routineSteps).where(eq(routineSteps.routine, id)).orderBy(asc(routineSteps.position))
      for (const [position, text] of steps.entries()) {
        const step = existing[position]
        if (step) {
          if (step.text !== text || step.position !== position) yield* db.update(routineSteps).set({ text, position }).where(eq(routineSteps.id, step.id))
        } else {
          yield* db.insert(routineSteps).values({ owner, routine: id, text, position })
        }
      }
      const extra = existing.slice(steps.length).map((s) => s.id)
      if (extra.length) yield* db.delete(routineSteps).where(inArray(routineSteps.id, extra))
    }),

    deleteRoutine: mutation({ id: id("routines") }, function* ({ id }) {
      yield* ownRoutine(id)
      yield* (yield* Db).delete(routines).where(eq(routines.id, id))
    }),

    /** Tick a step of a routine's run on a day. */
    setStep: mutation({ step: id("routineSteps"), day: day(), done: boolean() }, function* ({ step, day, done }) {
      const db = yield* Db
      const row = yield* owned(yield* db.get(routineSteps, step), "routineSteps", step)
      const where = and(eq(routineTicks.step, step), eq(routineTicks.day, day))
      const [tick] = yield* db.select({ id: routineTicks.id }).from(routineTicks).where(where).limit(1)
      if (done && !tick) yield* db.insert(routineTicks).values({ owner: row.owner, routine: row.routine, step, day })
      if (!done && tick) yield* db.delete(routineTicks).where(where)
    }),

    /** Start the day's run over: untick every step. */
    resetRun: mutation({ routine: id("routines"), day: day() }, function* ({ routine, day }) {
      yield* ownRoutine(routine)
      yield* (yield* Db).delete(routineTicks).where(and(eq(routineTicks.routine, routine), eq(routineTicks.day, day)))
    }),

    // -- Planner -----------------------------------------------------------
    createEvent: mutation(
      { title: eventTitle, day: day(), start: timeOfDay, end: timeOfDay, notes: todoNotes.optional() },
      function* ({ title, day, start, end, notes }) {
        const db = yield* Db
        const owner = yield* viewerId()
        const from = parseTime(start)
        const to = end === "00:00" ? 1440 : parseTime(end)
        if (to <= from) return yield* new EndBeforeStart({})
        const [row] = yield* db.insert(events).values({ owner, title, day, start: from, end: to, notes: notes ?? null }).returning({ id: events.id })
        return row!.id
      },
    ),

    updateEvent: mutation(
      { id: id("events"), title: eventTitle, day: day(), start: timeOfDay, end: timeOfDay, notes: todoNotes.optional() },
      function* ({ id, title, day, start, end, notes }) {
        yield* ownEvent(id)
        const from = parseTime(start)
        const to = end === "00:00" ? 1440 : parseTime(end)
        if (to <= from) return yield* new EndBeforeStart({})
        yield* (yield* Db).update(events).set({ title, day, start: from, end: to, notes: notes ?? null }).where(eq(events.id, id))
      },
    ),

    deleteEvent: mutation({ id: id("events") }, function* ({ id }) {
      yield* ownEvent(id)
      yield* (yield* Db).delete(events).where(eq(events.id, id))
    }),

    // -- Tracker -----------------------------------------------------------
    /** Add an item by hand (or a link whose page could not be read). */
    addTrackerItem: mutation(
      { title: itemTitle, kind: trackerKind, url: linkUrl.optional(), year: year.optional(), status: trackerStatus.optional() },
      function* ({ title, kind, url, year, status }) {
        const db = yield* Db
        const owner = yield* viewerId()
        if ((yield* db.count(trackerItems, eq(trackerItems.owner, owner))) >= 2000) return yield* new TooMany({ what: "tracked items", max: 2000 })
        const [row] = yield* db
          .insert(trackerItems)
          .values({ owner, title, kind, url: url ?? null, year: year ?? null, status: status ?? "backlog", site: url ? siteOf(url) : null })
          .returning({ id: trackerItems.id })
        return row!.id
      },
    ),

    updateTrackerItem: mutation(
      { id: id("trackerItems"), title: itemTitle, kind: trackerKind, year: year.optional(), status: trackerStatus },
      function* ({ id, title, kind, year, status }) {
        yield* ownTracker(id)
        yield* (yield* Db).update(trackerItems).set({ title, kind, year: year ?? null, status }).where(eq(trackerItems.id, id))
      },
    ),

    setTrackerStatus: mutation({ id: id("trackerItems"), status: trackerStatus }, function* ({ id, status }) {
      yield* ownTracker(id)
      yield* (yield* Db).update(trackerItems).set({ status }).where(eq(trackerItems.id, id))
    }),

    /** A poster: downloaded by the Tracker, or uploaded by hand (none removes it). */
    setTrackerPoster: mutation({ id: id("trackerItems"), poster: file().optional() }, function* ({ id, poster }) {
      const item = yield* ownTracker(id)
      yield* (yield* Db).update(trackerItems).set({ poster: poster ?? null }).where(eq(trackerItems.id, id))
      if (item.poster && item.poster !== poster) yield* (yield* Files).delete(item.poster)
    }),

    deleteTrackerItem: mutation({ id: id("trackerItems") }, function* ({ id }) {
      yield* ownTracker(id)
      yield* (yield* Db).delete(trackerItems).where(eq(trackerItems.id, id))
    }),

    // -- Wishlist ----------------------------------------------------------
    /** Add a wish; with a link, its picture is fetched in the background. */
    addWish: mutation({ title: wishTitle, url: linkUrl.optional(), price: price.optional() }, function* ({ title, url, price }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(wishItems, eq(wishItems.owner, owner))) >= 1000) return yield* new TooMany({ what: "wishes", max: 1000 })
      const [row] = yield* db
        .insert(wishItems)
        .values({ owner, title, url: url ?? null, price: price ?? null, site: url ? siteOf(url) : null })
        .returning({ id: wishItems.id })
      if (url) (yield* Scheduler).runAfter(0, "previewWish", { id: row!.id, url })
      return row!.id
    }),

    updateWish: mutation({ id: id("wishItems"), title: wishTitle, url: linkUrl.optional(), price: price.optional() }, function* ({ id, title, url, price }) {
      const wish = yield* ownWish(id)
      yield* (yield* Db).update(wishItems).set({ title, url: url ?? null, price: price ?? null, site: url ? siteOf(url) : null }).where(eq(wishItems.id, id))
      if (url && url !== wish.url && !wish.image) (yield* Scheduler).runAfter(0, "previewWish", { id, url })
    }),

    setWishImage: mutation({ id: id("wishItems"), image: file().optional() }, function* ({ id, image }) {
      const wish = yield* ownWish(id)
      yield* (yield* Db).update(wishItems).set({ image: image ?? null }).where(eq(wishItems.id, id))
      if (wish.image && wish.image !== image) yield* (yield* Files).delete(wish.image)
    }),

    setBought: mutation({ id: id("wishItems"), bought: boolean() }, function* ({ id, bought }) {
      yield* ownWish(id)
      yield* (yield* Db).update(wishItems).set({ bought }).where(eq(wishItems.id, id))
    }),

    deleteWish: mutation({ id: id("wishItems") }, function* ({ id }) {
      yield* ownWish(id)
      yield* (yield* Db).delete(wishItems).where(eq(wishItems.id, id))
    }),

    // -- Dump --------------------------------------------------------------
    /** Throw in a note or a link (a link gets its preview in the background). */
    dumpText: mutation({ text: dumpText }, function* ({ text }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(dumpItems, eq(dumpItems.owner, owner))) >= 2000) return yield* new TooMany({ what: "things in the Dump", max: 2000 })
      const link = isLink(text) && text.length <= 2000
      const [row] = yield* db
        .insert(dumpItems)
        .values(link ? { owner, kind: "link", url: text.trim(), site: siteOf(text.trim()) } : { owner, kind: "note", text })
        .returning({ id: dumpItems.id })
      if (link) (yield* Scheduler).runAfter(0, "previewDump", { id: row!.id, url: text.trim() })
      return row!.id
    }),

    dumpImage: mutation({ image: file() }, function* ({ image }) {
      const db = yield* Db
      const owner = yield* viewerId()
      if ((yield* db.count(dumpItems, eq(dumpItems.owner, owner))) >= 2000) return yield* new TooMany({ what: "things in the Dump", max: 2000 })
      const [row] = yield* db.insert(dumpItems).values({ owner, kind: "image", image }).returning({ id: dumpItems.id })
      return row!.id
    }),

    deleteDump: mutation({ id: id("dumpItems") }, function* ({ id }) {
      yield* ownDump(id)
      yield* (yield* Db).delete(dumpItems).where(eq(dumpItems.id, id))
    }),

    /** Sort a Dump item into the Todo inbox; it leaves the Dump. */
    dumpToTodo: mutation({ id: id("dumpItems") }, function* ({ id }) {
      const item = yield* ownDump(id)
      const title = (item.title ?? item.text ?? item.url ?? "Look at this image").replace(/\s+/g, " ").trim()
      const todo = yield* insertTodo({
        title: title.length > 160 ? `${title.slice(0, 157)}…` : title,
        notes: [item.text && item.text.length > 160 ? item.text : null, item.url].filter(Boolean).join("\n\n").slice(0, 2000) || null,
      })
      yield* (yield* Db).delete(dumpItems).where(eq(dumpItems.id, id))
      return todo
    }),

    /** Sort a Dump link into the Tracker, with what its preview found (the picture moves with it). */
    dumpToTracker: mutation({ id: id("dumpItems") }, function* ({ id }) {
      const db = yield* Db
      const item = yield* ownDump(id)
      if (!item.url) return yield* new NotALink({})
      const [row] = yield* db
        .insert(trackerItems)
        .values({
          owner: item.owner,
          url: item.url,
          title: (item.title ?? siteOf(item.url)).slice(0, 200),
          kind: kindFromSite(item.url),
          description: item.description,
          site: item.site,
          poster: item.image,
        })
        .returning({ id: trackerItems.id })
      yield* db.delete(dumpItems).where(eq(dumpItems.id, id))
      // The Dump only read the page's tags: let the Tracker read it again for the year and the kind.
      const scheduler = yield* Scheduler
      scheduler.runAfter(0, "previewTracker", { id: row!.id, url: item.url })
      return row!.id
    }),

    /** Sort a Dump item into the Wishlist (its link and picture move with it). */
    dumpToWish: mutation({ id: id("dumpItems") }, function* ({ id }) {
      const db = yield* Db
      const item = yield* ownDump(id)
      const title = (item.title ?? item.text ?? (item.url ? siteOf(item.url) : "Something from the Dump")).replace(/\s+/g, " ").trim()
      const [row] = yield* db
        .insert(wishItems)
        .values({ owner: item.owner, title: title.slice(0, 120), url: item.url, site: item.site, image: item.image })
        .returning({ id: wishItems.id })
      yield* db.delete(dumpItems).where(eq(dumpItems.id, id))
      return row!.id
    }),
  },

  internal: {
    saveTrackerPreview: mutation(
      { url: linkUrl, title: itemTitle, kind: trackerKind, year: year.optional(), description: string().max(500).optional(), site: string().max(80).optional() },
      function* (args) {
        const db = yield* Db
        const owner = yield* viewerId()
        if ((yield* db.count(trackerItems, eq(trackerItems.owner, owner))) >= 2000) return yield* new TooMany({ what: "tracked items", max: 2000 })
        const [row] = yield* db
          .insert(trackerItems)
          .values({ owner, ...args, year: args.year ?? null, description: args.description ?? null, site: args.site ?? null })
          .returning({ id: trackerItems.id })
        return row!.id
      },
    ),
    applyTrackerPreview: mutation(
      { id: id("trackerItems"), title: itemTitle.optional(), kind: trackerKind, year: year.optional(), description: string().max(500).optional() },
      function* ({ id, title, kind, year, description }) {
        const db = yield* Db
        const item = yield* db.get(trackerItems, id)
        yield* db
          .update(trackerItems)
          .set({ title: title ?? item.title, kind, year: year ?? item.year, description: description ?? item.description })
          .where(eq(trackerItems.id, id))
      },
    ),
    applyWishPreview: mutation({ id: id("wishItems"), site: string().max(80).optional(), image: file().optional() }, function* ({ id, site, image }) {
      const db = yield* Db
      const wish = yield* db.get(wishItems, id)
      yield* db
        .update(wishItems)
        .set({ site: site ?? wish.site, image: wish.image ?? image ?? null })
        .where(eq(wishItems.id, id))
    }),
    applyDumpPreview: mutation(
      {
        id: id("dumpItems"),
        title: string().max(200).optional(),
        description: string().max(500).optional(),
        site: string().max(80).optional(),
        image: file().optional(),
      },
      function* ({ id, title, description, site, image }) {
        const db = yield* Db
        const item = yield* db.get(dumpItems, id)
        yield* db
          .update(dumpItems)
          .set({ title: title ?? item.title, description: description ?? item.description, site: site ?? item.site, image: item.image ?? image ?? null })
          .where(eq(dumpItems.id, id))
      },
    ),
  },

  actions: (action) => ({
    /**
     * Paste a link into the Tracker: read the page (OpenGraph tags; IMDb from its JSON), save the item with its
     * title, kind, year and description, then download the poster in the background.
     */
    trackLink: action({ url: linkUrl }, function* (ctx, { url }) {
      const p = yield* readPreview(ctx, url)
      const f = previewFields(p)
      const itemId = yield* ctx.runMutation("saveTrackerPreview", {
        url,
        title: f.title ?? siteOf(url),
        kind: p.kind,
        ...dropNulls({ year: p.year, description: f.description, site: f.site }),
      })
      if (p.image) ctx.scheduler.runAfter(0, "fetchPoster", { id: itemId, src: p.image })
      return itemId
    }),

    /** Read a tracked link again (after it moved from the Dump): kind, year, description and poster. */
    previewTracker: action.internal({ id: id("trackerItems"), url: linkUrl }, function* (ctx, { id, url }) {
      const p = yield* readPreview(ctx, url)
      yield* ctx.runMutation("applyTrackerPreview", { id, kind: p.kind, ...dropNulls({ year: p.year, description: p.description?.slice(0, 500) ?? null }) })
      if (p.image) ctx.scheduler.runAfter(0, "fetchPoster", { id, src: p.image })
    }),

    fetchPoster: action.internal({ id: id("trackerItems"), src: linkUrl }, function* (ctx, { id, src }) {
      const poster = yield* storeImage(ctx, src, "poster")
      if (poster) yield* ctx.runMutation("setTrackerPoster", { id, poster })
    }),

    previewWish: action.internal({ id: id("wishItems"), url: linkUrl }, function* (ctx, { id, url }) {
      const p = yield* readPreview(ctx, url)
      const image = p.image ? yield* storeImage(ctx, p.image, "wish") : null
      yield* ctx.runMutation("applyWishPreview", { id, ...dropNulls({ site: p.site?.slice(0, 80) ?? null, image }) })
    }),

    previewDump: action.internal({ id: id("dumpItems"), url: linkUrl }, function* (ctx, { id, url }) {
      const p = yield* readPreview(ctx, url)
      yield* ctx.runMutation("applyDumpPreview", { id, ...dropNulls(previewFields(p)) })
      const image = p.image ? yield* storeImage(ctx, p.image, "preview") : null
      if (image) yield* ctx.runMutation("applyDumpPreview", { id, image })
    }),
  }),
})

// ---------------------------------------------------------------------------

/** "work, Home  errands" → ["work", "home", "errands"] (invalid words are dropped). */
function splitTags(text: string | null | undefined): ReadonlyArray<string> {
  if (!text) return []
  return text
    .split(/[\s,#]+/)
    .map((t) => t.toLowerCase())
    .filter((t) => /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,23}$/u.test(t))
}

function kindFromSite(url: string) {
  return parsePreview("", url).kind
}

/** Optional args are left out, not null. */
function dropNulls<T extends Record<string, unknown>>(o: T): { [K in keyof T]?: Exclude<T[K], null> } {
  return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== null && v !== undefined)) as never
}
server/preview.ts166 lines
import type { TrackerKind } from "../shared/logic.ts"

/** What a page says about itself: OpenGraph and Twitter tags, its <title>, and a year where the site shows one. */
export interface Preview {
  readonly title: string | null
  readonly description: string | null
  /** An absolute URL. */
  readonly image: string | null
  readonly site: string | null
  readonly kind: TrackerKind
  readonly year: number | null
}

const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", bull: "•", lrm: "", rlm: "", mdash: "—", ndash: "–", hellip: "…" }

export const decodeEntities = (s: string): string =>
  s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, e: string) => {
    if (e[0] === "#") {
      const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)
      return Number.isFinite(code) ? String.fromCodePoint(code) : whole
    }
    return ENTITIES[e.toLowerCase()] ?? whole
  })

const attr = (tag: string, name: string): string | undefined => {
  const m = new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag)
  return m ? (m[2] ?? m[3] ?? m[4]) : undefined
}

/** Every <meta property|name=… content=…> in the page, first one wins, keys lowercased. */
export const metaTags = (html: string): ReadonlyMap<string, string> => {
  const out = new Map<string, string>()
  for (const [tag] of html.matchAll(/<meta\b[^>]*>/gi)) {
    const key = attr(tag, "property") ?? attr(tag, "name") ?? attr(tag, "itemprop")
    const content = attr(tag, "content")
    if (!key || content === undefined) continue
    const k = key.toLowerCase()
    if (!out.has(k)) out.set(k, decodeEntities(content).trim())
  }
  return out
}

const clean = (s: string | undefined | null): string | null => {
  const t = s?.replace(/\s+/g, " ").trim()
  return t ? t : null
}

const absolute = (src: string | null, base: string): string | null => {
  if (!src) return null
  try {
    const u = new URL(src, base)
    return u.protocol === "http:" || u.protocol === "https:" ? u.href : null
  } catch {
    return null
  }
}

const host = (url: string): string => {
  try {
    return new URL(url).hostname.replace(/^www\./, "").toLowerCase()
  } catch {
    return ""
  }
}

const plausibleYear = (y: number): number | null => (y >= 1000 && y <= 3000 ? y : null)

/** Guess the kind from the site, then from og:type. */
export const kindOf = (url: string, ogType: string | undefined): TrackerKind => {
  const h = host(url)
  const t = (ogType ?? "").toLowerCase()
  if (/(^|\.)boardgamegeek\.com$/.test(h)) return "boardgame"
  if (/(^|\.)(store\.steampowered\.com|steamcommunity\.com|gog\.com|itch\.io|epicgames\.com)$/.test(h) || h === "store.steampowered.com") return "game"
  if (/(^|\.)(goodreads\.com|openlibrary\.org|storygraph\.com|thestorygraph\.com)$/.test(h)) return "book"
  if (t === "video.tv_show" || t === "video.episode") return "series"
  if (t === "video.movie") return "movie"
  if (t === "books.book" || t === "book") return "book"
  if (/(^|\.)(youtube\.com|youtu\.be|vimeo\.com)$/.test(h) || t.startsWith("video")) return "video"
  if (/(^|\.)(letterboxd\.com)$/.test(h)) return "movie"
  return "other"
}

/** A year the page shows: release-date tags, JSON-LD dates, "First published …" (Goodreads), Steam's release date, "(2021)" in the title. */
const yearOf = (html: string, meta: ReadonlyMap<string, string>, title: string | null): number | null => {
  for (const key of ["video:release_date", "books:release_date", "og:release_date", "music:release_date", "datepublished", "release_date"]) {
    const v = meta.get(key)
    const y = v && /\b(\d{4})\b/.exec(v)
    if (y) return plausibleYear(Number(y[1]))
  }
  const ld = /"(?:datePublished|dateCreated|copyrightYear|startDate|yearpublished)"\s*:\s*"?(\d{4})/i.exec(html)
  if (ld) return plausibleYear(Number(ld[1]))
  const published = /First published[^<]*?\b(\d{4})\b/i.exec(html)
  if (published) return plausibleYear(Number(published[1]))
  const steam = /<div class="date">[^<]*?\b(\d{4})\s*<\/div>/i.exec(html)
  if (steam) return plausibleYear(Number(steam[1]))
  const inTitle = title && /\((?:[^()]*?\s)?(\d{4})(?:[–-]\d{0,4})?\s*\)/.exec(title)
  if (inTitle) return plausibleYear(Number(inTitle[1]))
  return null
}

/** Strip what sites add around a name: "(2021)", "on Steam", "| Goodreads", "- YouTube", "Save 50% on". */
const tidyTitle = (title: string, kind: TrackerKind): string => {
  let t = title
  t = t.replace(/^Save \d+% on /i, "").replace(/ on Steam$/i, "")
  t = t.replace(/\s+[|•·-]\s+(YouTube|Goodreads|Letterboxd|BoardGameGeek|IMDb)\s*$/i, "")
  t = t.replace(/\s*⭐.*$/, "")
  if (kind === "movie" || kind === "series") t = t.replace(/\s*\((?:[^()]*?\s)?\d{4}(?:[–-]\d{0,4})?\s*\)\s*$/, "")
  if (kind === "book") t = t.replace(/\s+by\s+[^|]+$/i, "")
  return t.trim() || title.trim()
}

/** Read a page's preview from its HTML. Pure: tested with fixtures in server/fixtures/. */
export const parsePreview = (html: string, url: string): Preview => {
  const meta = metaTags(html)
  const titleTag = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)
  const rawTitle = clean(meta.get("og:title") ?? meta.get("twitter:title") ?? (titleTag ? decodeEntities(titleTag[1]!) : undefined))
  const kind = kindOf(url, meta.get("og:type"))
  const year = yearOf(html, meta, rawTitle)
  return {
    title: rawTitle ? tidyTitle(rawTitle, kind) : null,
    description: clean(meta.get("og:description") ?? meta.get("twitter:description") ?? meta.get("description"))?.slice(0, 500) ?? null,
    image: absolute(meta.get("og:image:secure_url") ?? meta.get("og:image") ?? meta.get("twitter:image") ?? meta.get("twitter:image:src") ?? null, url),
    site: clean(meta.get("og:site_name") ?? meta.get("og:site")) ?? (host(url) || null),
    kind,
    year,
  }
}

// ---------------------------------------------------------------------------
// IMDb: its pages answer bots with an empty "202" challenge, so titles are read from IMDb's public suggestion JSON
// (https://v3.sg.media-imdb.com/suggestion/x/<id>.json), which carries the title, year, poster and type.

/** "tt1160419" from an IMDb title link. */
export const imdbId = (url: string): string | null => {
  if (!/(^|\.)imdb\.com$/.test(host(url))) return null
  return /\/title\/(tt\d+)/.exec(url)?.[1] ?? null
}

export interface ImdbSuggestion {
  readonly d?: ReadonlyArray<{
    readonly id: string
    readonly l?: string
    readonly qid?: string
    readonly y?: number
    readonly s?: string
    readonly i?: { readonly imageUrl?: string }
  }>
}

export const imdbSuggestionUrl = (id: string): string => `https://v3.sg.media-imdb.com/suggestion/x/${id}.json`

/** The preview of an IMDb title from its suggestion JSON, or null when the id is not in it. */
export const parseImdb = (json: ImdbSuggestion, id: string): Preview | null => {
  const hit = json.d?.find((d) => d.id === id)
  if (!hit?.l) return null
  const series = /^(tvSeries|tvMiniSeries|tvEpisode|tvSpecial)$/.test(hit.qid ?? "")
  return {
    title: hit.l,
    description: hit.s ? `With ${hit.s}` : null,
    image: hit.i?.imageUrl ?? null,
    site: "IMDb",
    kind: series ? "series" : hit.qid === "videoGame" ? "game" : "movie",
    year: typeof hit.y === "number" ? plausibleYear(hit.y) : null,
  }
}
server/seed.ts90 lines
import { defineSeed } from "canica/testing"
import app from "./index.ts"

/** A lived-in week: the storyboard's "today" is Thursday 2026-01-15, 12:00 UTC. */
export default defineSeed(app, async ({ as, day, sampleImage }) => {
  const me = as("viewer")
  const today = day(0)

  // Todos ------------------------------------------------------------------
  const work = me.mutationOk("createProject", { name: "Work" })
  const home = me.mutationOk("createProject", { name: "Home" })
  const side = me.mutationOk("createProject", { name: "Side project" })

  const run = me.mutationOk("createTodo", { title: "Morning run", due: today, time: "07:30", minutes: 30, tags: ["health"] })
  me.mutationOk("setDone", { id: run, done: true, today })
  me.mutationOk("createTodo", { title: "Send the invoice to Marko", project: work, due: today, time: "10:00", minutes: 30, tags: ["work"] })
  me.mutationOk("createTodo", { title: "Fix the leaking kitchen tap", project: home, due: today, tags: ["home"] })
  me.mutationOk("createTodo", { title: "Buy a birthday gift for mom", due: today, tags: ["errands"] })
  me.mutationOk("createTodo", { title: "Review the Q4 roadmap", project: work, due: today, time: "14:00", minutes: 90, tags: ["work"], notes: "Focus on the onboarding goals; send comments to Ana by Friday." })
  me.mutationOk("createTodo", { title: "Renew the passport", due: day(-2), tags: ["errands"] })
  me.mutationOk("createTodo", { title: "Write the release notes", project: side, due: day(1), tags: ["writing"] })
  me.mutationOk("createTodo", { title: "Answer Ana about the offsite", project: work, due: day(1) })
  me.mutationOk("capture", { text: "Clean up the backlog #work", today })
  me.mutationOk("capture", { text: "Call the plumber about the boiler #home", today })
  me.mutationOk("capture", { text: "Try the new ramen place", today })
  const old = me.mutationOk("createTodo", { title: "Book the dentist", project: home, tags: ["health"] })
  me.mutationOk("setDone", { id: old, done: true, today: day(-1) })

  // Planner ----------------------------------------------------------------
  me.mutationOk("createEvent", { title: "Standup", day: today, start: "09:00", end: "09:15" })
  me.mutationOk("createEvent", { title: "Lunch with Iva", day: today, start: "12:30", end: "13:30" })
  me.mutationOk("createEvent", { title: "Dentist", day: today, start: "17:00", end: "17:45", notes: "Dr. Horvat, 2nd floor" })
  me.mutationOk("createEvent", { title: "Climbing", day: day(1), start: "19:00", end: "21:00" })
  me.mutationOk("createEvent", { title: "Design review", day: day(1), start: "11:00", end: "12:00" })

  // Habits -----------------------------------------------------------------
  const tick = (habit: ReturnType<typeof me.mutationOk<"createHabit">>, offsets: ReadonlyArray<number>) => {
    for (const o of offsets) me.mutationOk("setTick", { habit, day: day(o), done: true })
  }
  const read = me.mutationOk("createHabit", { name: "Read", emoji: "📚" })
  tick(read, [-1, -2, -3, -5, -6, -9, -10, -11, -12, -16, -17, -20])
  const stretch = me.mutationOk("createHabit", { name: "Stretch", emoji: "🧘" })
  tick(stretch, [0, -1, -2, -3, -6, -7, -8, -13, -14, -15, -21, -22])
  const phone = me.mutationOk("createHabit", { name: "No phone in bed", emoji: "🌙" })
  tick(phone, [0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -13, -14, -15, -16, -17, -18, -19])

  // Routines ---------------------------------------------------------------
  const morning = me.mutationOk("createRoutine", { name: "Morning", emoji: "☀️", steps: ["Glass of water", "Make the bed", "10 minutes outside", "Plan the day", "Stretch"] })
  const steps = me.queryOk("routine", { id: morning, day: today }).steps
  for (const s of steps.slice(0, 3)) me.mutationOk("setStep", { step: s.id, day: today, done: true })
  me.mutationOk("createRoutine", { name: "Gym day", emoji: "🏋️", steps: ["Pack shoes and towel", "Water bottle", "Warm up 10 minutes", "Main lifts", "Stretch", "Protein"] })
  me.mutationOk("createRoutine", {
    name: "Packing for a trip",
    emoji: "🧳",
    steps: ["Passport and wallet", "Chargers", "Toothbrush", "Two days of clothes", "Book", "Headphones", "Water the plants", "Take out the trash"],
  })

  // Tracker ----------------------------------------------------------------
  const poster = await me.uploadOk(sampleImage(), "poster.png")
  const pastLives = me.mutationOk("addTrackerItem", { title: "Past Lives", kind: "movie", year: 2023, url: "https://letterboxd.com/film/past-lives/", status: "done" })
  me.mutationOk("setTrackerPoster", { id: pastLives, poster })
  me.mutationOk("addTrackerItem", { title: "The Bear", kind: "series", year: 2022, url: "https://www.imdb.com/title/tt14452776/", status: "active" })
  me.mutationOk("addTrackerItem", { title: "Project Hail Mary", kind: "book", year: 2021, url: "https://www.goodreads.com/book/show/54493401-project-hail-mary", status: "active" })
  me.mutationOk("addTrackerItem", { title: "Hades", kind: "game", year: 2020, url: "https://store.steampowered.com/app/1145360/Hades/" })
  me.mutationOk("addTrackerItem", { title: "Wingspan", kind: "boardgame", year: 2019, url: "https://boardgamegeek.com/boardgame/266192/wingspan", status: "done" })

  // Wishlist ---------------------------------------------------------------
  const keyboard = me.mutationOk("addWish", { title: "Mechanical keyboard", url: "https://keychron.com/products/keychron-q1", price: 14900 })
  me.mutationOk("setWishImage", { id: keyboard, image: await me.uploadOk(sampleImage(), "keyboard.png") })
  me.mutationOk("addWish", { title: "Rain jacket", price: 9000 })
  me.mutationOk("addWish", { title: "Espresso grinder", price: 22000 })
  const shoes = me.mutationOk("addWish", { title: "Climbing shoes", price: 11000 })
  me.mutationOk("setBought", { id: shoes, bought: true })

  // Dump -------------------------------------------------------------------
  me.mutationOk("dumpText", { text: "A long read about sleep, from the New Yorker" })
  me.mutationOk("dumpImage", { image: await me.uploadOk(sampleImage(), "shelf.png") })
  me.mutationOk("dumpText", { text: "Gift idea for Luka: that board game from the party" })

  return {
    captures: {
      "/routines/$routine": [{ routine: morning }],
      "/todos/projects/$project": [{ project: work }],
      "/todos/tags/$tag": [{ tag: "work" }],
      "/planner/$day": [{ day: day(1) }],
      "/tracker/$status": [{ status: "active" }],
    },
  }
})
shared/fields.ts51 lines
import { array, cents, literal, number, string } from "canica/fields"

/** Field schemas shared by the server (args, tables) and the UI (forms). */

// Todos
export const todoTitle = string().trim().min(1, "Write what needs doing").max(160)
export const todoNotes = string().trim().max(2000)
export const projectName = string().trim().min(1, "Give it a name").max(40)
export const tagName = string()
  .trim()
  .lower()
  .min(1)
  .max(24)
  .pattern(/^[\p{L}\p{N}][\p{L}\p{N}_-]*$/u, "Tags are one word: letters, numbers, - and _")
export const tagList = array(tagName).max(8)
/** Quick capture: one line, with optional #tags and a trailing "today"/"tomorrow". */
export const captureText = string().trim().min(1).max(200)

/** A time of day typed in an <Input type="time">: "09:30". */
export const timeOfDay = string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/, "Use a time like 09:30")
export const duration = number().int().min(5, "At least 5 minutes").max(720, "At most 12 hours")

// Habits and routines
export const habitName = string().trim().min(1, "Name the habit").max(60)
export const emoji = string().trim().max(8)
export const routineName = string().trim().min(1, "Name the routine").max(60)
export const stepText = string().trim().min(1).max(120)
export const stepList = array(stepText).min(1, "Add at least one step").max(30)

// Planner
export const eventTitle = string().trim().min(1, "Name the event").max(120)

// Tracker
export const trackerKinds = ["movie", "series", "book", "game", "boardgame", "video", "other"] as const
export const trackerKind = literal(...trackerKinds)
export const trackerStatuses = ["backlog", "active", "done"] as const
export const trackerStatus = literal(...trackerStatuses)
export const linkUrl = string()
  .trim()
  .max(2000)
  .pattern(/^https?:\/\/[^\s/$.?#].[^\s]*$/i, "Paste a full link, starting with https://")
export const itemTitle = string().trim().min(1, "Give it a title").max(200)
export const year = number().int().min(1000).max(3000)

// Wishlist
export const wishTitle = string().trim().min(1, "What is it?").max(120)
export const price = cents()

// Dump
export const dumpText = string().trim().min(1).max(4000)
shared/logic.ts135 lines
import { addDays } from "canica/fields"

// ---------------------------------------------------------------------------
// Streaks

/**
 * Consecutive ticked days ending today. Today not ticked yet does not break it: the streak then ends yesterday
 * (the day is not over). A missed day before that resets it to 0.
 */
export const currentStreak = (ticked: ReadonlySet<string>, today: string): number => {
  let day = ticked.has(today) ? today : addDays(today, -1)
  let n = 0
  while (ticked.has(day)) {
    n++
    day = addDays(day, -1)
  }
  return n
}

/** The longest run of consecutive ticked days. */
export const bestStreak = (days: Iterable<string>): number => {
  const sorted = [...new Set(days)].sort()
  let best = 0
  let run = 0
  let prev: string | undefined
  for (const d of sorted) {
    run = prev !== undefined && addDays(prev, 1) === d ? run + 1 : 1
    best = Math.max(best, run)
    prev = d
  }
  return best
}

/** The last `weeks` whole weeks, Monday first, as rows of 7 days, the current week last (its future days included). */
export const gridWeeks = (today: string, weeks: number): ReadonlyArray<ReadonlyArray<string>> => {
  const weekday = (new Date(`${today}T00:00:00Z`).getUTCDay() + 6) % 7
  const monday = addDays(today, -weekday)
  return Array.from({ length: weeks }, (_, w) => {
    const start = addDays(monday, -7 * (weeks - 1 - w))
    return Array.from({ length: 7 }, (_, i) => addDays(start, i))
  })
}

// ---------------------------------------------------------------------------
// Time of day (minutes since midnight)

/** "09:30" → 570. */
export const parseTime = (hhmm: string): number => {
  const [h, m] = hhmm.split(":").map(Number)
  return (h ?? 0) * 60 + (m ?? 0)
}

/** 570 → "09:30". */
export const formatMinutes = (minutes: number): string => {
  const m = Math.max(0, Math.min(24 * 60, Math.round(minutes)))
  return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`
}

/** "09:30–10:15" */
export const formatRange = (start: number, end: number): string => `${formatMinutes(start)}–${formatMinutes(end)}`

// ---------------------------------------------------------------------------
// Quick capture: "Call the plumber #home tomorrow"

export interface Capture {
  readonly title: string
  readonly tags: ReadonlyArray<string>
  /** "today" or "tomorrow" as a day, when the text ends with one of them. */
  readonly due: string | undefined
}

/**
 * Read a quick-capture line: `#tags` anywhere become tags (lowercased, at most 8), a trailing "today",
 * "tomorrow" or "tmr" sets the due day. What is left is the title; when nothing is left, the text is kept as is.
 */
export const parseCapture = (text: string, today: string): Capture => {
  const tags: Array<string> = []
  let rest = text.replace(/(^|\s)#([\p{L}\p{N}][\p{L}\p{N}_-]{0,23})(?=\s|$)/gu, (_, space: string, tag: string) => {
    const t = tag.toLowerCase()
    if (!tags.includes(t) && tags.length < 8) tags.push(t)
    return space
  })
  let due: string | undefined
  const when = /\s+(today|tod|tomorrow|tmr)\s*$/i.exec(` ${rest.trim()}`)
  if (when) {
    const word = when[1]!.toLowerCase()
    due = word === "today" || word === "tod" ? today : addDays(today, 1)
    rest = ` ${rest.trim()}`.slice(0, when.index)
  }
  const title = rest.replace(/\s+/g, " ").trim()
  return title === "" ? { title: text.trim(), tags: [], due: undefined } : { title, tags, due }
}

// ---------------------------------------------------------------------------
// Tracker: what each status is called for each kind

export type TrackerKind = "movie" | "series" | "book" | "game" | "boardgame" | "video" | "other"
export type TrackerStatus = "backlog" | "active" | "done"

const ACTIVE: Record<TrackerKind, [string, string]> = {
  movie: ["Watching", "Watched"],
  series: ["Watching", "Watched"],
  video: ["Watching", "Watched"],
  book: ["Reading", "Read"],
  game: ["Playing", "Played"],
  boardgame: ["Playing", "Played"],
  other: ["In progress", "Done"],
}

/** "Watched" for a finished movie, "Reading" for a book in progress, "Backlog" for anything not started. */
export const statusLabel = (kind: TrackerKind, status: TrackerStatus): string =>
  status === "backlog" ? "Backlog" : ACTIVE[kind][status === "active" ? 0 : 1]

export const KIND_LABEL: Record<TrackerKind, string> = {
  movie: "Movie",
  series: "Series",
  book: "Book",
  game: "Game",
  boardgame: "Board game",
  video: "Video",
  other: "Link",
}

/** The host of a link without "www.": "imdb.com". */
export const siteOf = (url: string): string => {
  try {
    return new URL(url).hostname.replace(/^www\./, "")
  } catch {
    return url
  }
}

/** Does this text look like a single link (the Dump turns it into a link card)? */
export const isLink = (text: string): boolean => /^https?:\/\/[^\s/$.?#][^\s]*$/i.test(text.trim())
src/main.tsx20 lines
import { start } from "canica/client"
import { openPalette } from "./components/palette.tsx"
import { routes } from "./routes.gen.ts"
import "./styles.css"

start(routes)

// ⌘K / Ctrl+K opens the command palette from anywhere. Canica has no API for app-wide shortcuts and app code has
// no effects, so the listener lives here, next to start().
let paletteOpen = false
document.addEventListener("keydown", (e) => {
  if (e.key.toLowerCase() !== "k" || !(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return
  e.preventDefault()
  if (paletteOpen) return
  paletteOpen = true
  void openPalette().finally(() => {
    paletteOpen = false
  })
})
src/routes/__root.tsx19 lines
import { layout } from "canica/client"
import { PageContainer } from "canica/ui"
import { MobileBars, Sidebar } from "../components/nav.tsx"

export default layout({
  view: ({ children }) => (
    <div className="min-h-screen">
      <Sidebar />
      <div className="md:pl-56">
        <MobileBars />
        {/* Room for the phone's bottom bar. */}
        <div className="mx-auto w-full max-w-4xl pb-20 md:pb-0">
          <PageContainer>{children}</PageContainer>
        </div>
      </div>
    </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/dump.tsx38 lines
import { page, string, useMutation, useQuery } from "canica/client"
import { Button, EmptyBlock, ErrorState, FileInput, Loading, PageHeader, SearchInput } from "canica/ui"
import { DumpCard, NewDump } from "../components/dump.tsx"

/** Dump: throw in links, notes and images without deciding where they belong; sort them later. */
export default page({
  title: "Dump",
  search: { q: string().trim().optional() },
  view: ({ search }) => {
    const items = useQuery("dump", { q: search.q })
    const dumpImage = useMutation("dumpImage")
    const newItem = <Button aria-haspopup="dialog" onClick={() => void NewDump.open()}>New note or link</Button>
    return (
      <>
        <PageHeader title="Dump" description="Throw in links, notes and images without deciding where they belong. Search finds them later." actions={newItem} />
        <div className="flex flex-col gap-3">
          <FileInput label="Dump an image" accept="image/png,image/jpeg,image/webp,image/gif" onUpload={(image) => void dumpImage({ image })} />
        </div>
        <SearchInput param="q" label="Search the Dump" />
        {items.match({
          loading: () => <Loading shape="grid" />,
          failure: (e) => <ErrorState error={e} />,
          success: (list) =>
            list.length === 0 ? (
              <EmptyBlock title={search.q ? `Nothing matches “${search.q}”` : "The Dump is empty"} description={search.q ? "Try another word." : "Use New note or link to save something."} action={search.q ? undefined : newItem} />
            ) : (
              <div className="columns-1 gap-3 sm:columns-2 lg:columns-3">
                {list.map((item) => (
                  <DumpCard key={item.id} item={item} />
                ))}
              </div>
            ),
        })}
      </>
    )
  },
})
src/routes/habits.tsx45 lines
import { page, plural, useQuery, useToday } from "canica/client"
import { Button, EmptyBlock, ErrorState, Loading, PageHeader, Stat, Stats } from "canica/ui"
import { PlusIcon } from "canica/icons"
import { HabitRow, NewHabit } from "../components/habits.tsx"

/** Habits: tick today, watch the streak grow; the grid shows the last 4 weeks. */
export default page({
  title: "Habits",
  view: () => {
    const today = useToday()
    const habits = useQuery("habits", { today })
    const newHabit = (
      <Button aria-haspopup="dialog" onClick={() => void NewHabit.open()}>
        <PlusIcon />
        New habit
      </Button>
    )
    return (
      <>
        <PageHeader title="Habits" description="Tick off what you want to do every day. Skip a day and the grid will notice." actions={newHabit} />
        {habits.match({
          loading: () => <Loading shape="cards" />,
          failure: (e) => <ErrorState error={e} />,
          success: (list) =>
            list.length === 0 ? (
              <EmptyBlock title="No habits yet" description="Start with one small thing: read 10 pages, stretch, no phone in bed." action={newHabit} />
            ) : (
              <>
                <Stats>
                  <Stat label="Done today" value={`${list.filter((h) => h.doneToday).length} of ${list.length}`} />
                  <Stat label="Longest streak now" value={plural(Math.max(...list.map((h) => h.streak)), "day")} />
                </Stats>
                <div className="flex flex-col gap-3">
                  {list.map((h) => (
                    <HabitRow key={h.id} habit={h} today={today} />
                  ))}
                </div>
              </>
            ),
        })}
      </>
    )
  },
})
src/routes/index.tsx126 lines
import { Link, page, plural, useNow, useQuery, useToday } from "canica/client"
import { Button, EmptyBlock, ErrorState, List, Loading, PageHeader, Section } from "canica/ui"
import { PlusIcon } from "canica/icons"
import { formatRange } from "../../shared/logic.ts"
import { HabitChip } from "../components/habits.tsx"
import { NewTodo, TodoRow } from "../components/todos.tsx"

const longDate = (day: string) => new Date(`${day}T12:00:00Z`).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", timeZone: "UTC" })

/** Today: what is due today and overdue, the day's schedule and habits. */
export default page({
  title: "Today",
  view: () => {
    const today = useToday()
    const todos = useQuery("today", { today })
    const plan = useQuery("planner", { day: today })
    const habits = useQuery("habits", { today })
    const now = useNow("minute")
    const minutesNow = new Date(now).getHours() * 60 + new Date(now).getMinutes()
    const newTodo = (
      <Button aria-haspopup="dialog" onClick={() => void NewTodo.open({ due: today })}>
        <PlusIcon />
        New todo
      </Button>
    )
    return (
      <>
        <PageHeader
          title="Today"
          description={
            <>
              {longDate(today)}
              {todos._tag === "Success" && <span className="tabular-nums"> · {todos.value.left === 0 ? "nothing left" : `${todos.value.left} left`}</span>}
            </>
          }
          actions={newTodo}
        />
        {todos.match({
          loading: () => <Loading shape="list" />,
          failure: (e) => <ErrorState error={e} />,
          success: (t) =>
            t.overdue.length === 0 && t.today.length === 0 ? (
              <EmptyBlock title="A clear day" description="Nothing is due today. Use New todo, or plan the week in Todos." action={newTodo} />
            ) : (
              <div className="flex flex-col gap-6">
                {t.overdue.length > 0 && (
                  <Section title="Overdue" description={plural(t.overdue.length, "todo")}>
                    <List>
                      {t.overdue.map((todo) => (
                        <TodoRow key={todo.id} todo={todo} today={today} showProject />
                      ))}
                    </List>
                  </Section>
                )}
                {t.today.length > 0 && (
                  <Section title={t.overdue.length > 0 ? "Due today" : undefined}>
                    <List>
                      {t.today.map((todo) => (
                        <TodoRow key={todo.id} todo={todo} today={today} showProject />
                      ))}
                    </List>
                  </Section>
                )}
              </div>
            ),
        })}

        <div className="grid gap-6 lg:grid-cols-2">
          <Section
            title="Schedule"
            actions={
              <Button variant="ghost" size="sm" asChild>
                <Link to="/planner">Planner</Link>
              </Button>
            }
          >
            {plan.match({
              loading: () => <Loading shape="text" />,
              failure: (e) => <ErrorState error={e} />,
              success: (p) =>
                p.blocks.length === 0 ? (
                  <p className="text-sm text-muted-foreground">No events or scheduled todos today.</p>
                ) : (
                  <List>
                    {p.blocks.map((b) => (
                      <div key={`${b.kind}-${b.id}`} role="listitem" className={b.end <= minutesNow ? "flex items-center gap-3 px-4 py-2.5 text-sm text-muted-foreground" : "flex items-center gap-3 px-4 py-2.5 text-sm"}>
                        <span className="w-24 shrink-0 text-xs text-muted-foreground tabular-nums">{formatRange(b.start, b.end)}</span>
                        <span className={b.kind === "todo" && b.done ? "truncate line-through" : "truncate"}>{b.title}</span>
                        {b.kind === "todo" && <span className="ml-auto text-xs text-muted-foreground">todo</span>}
                      </div>
                    ))}
                  </List>
                ),
            })}
          </Section>
          <Section
            title="Habits"
            actions={
              <Button variant="ghost" size="sm" asChild>
                <Link to="/habits">All habits</Link>
              </Button>
            }
          >
            {habits.match({
              loading: () => <Loading shape="text" />,
              failure: (e) => <ErrorState error={e} />,
              success: (list) =>
                list.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    No habits yet. <Link to="/habits">Start one</Link>.
                  </p>
                ) : (
                  <div className="flex flex-col gap-2">
                    {list.map((h) => (
                      <HabitChip key={h.id} habit={h} today={today} />
                    ))}
                  </div>
                ),
            })}
          </Section>
        </div>
      </>
    )
  },
})
src/routes/planner/$day.tsx10 lines
import { day, page } from "canica/client"
import { PlannerView } from "../../components/planner-view.tsx"

/** The Planner on any day (`/planner/2026-01-16`). */
export default page({
  title: "Planner",
  params: { day: day() },
  view: ({ params }) => <PlannerView day={params.day} />,
})
src/routes/planner/index.tsx9 lines
import { page, useToday } from "canica/client"
import { PlannerView } from "../../components/planner-view.tsx"

/** The Planner, on today. */
export default page({
  title: "Planner",
  view: () => <PlannerView day={useToday()} />,
})
src/routes/routines/$routine.tsx63 lines
import { id, Link, page, useMutation, useNavigate, useQuery, useToday } from "canica/client"
import { ActionStatus, Button, Checkbox, ErrorState, Label, List, Loading, PageHeader, Progress } from "canica/ui"
import { PencilIcon, RotateCcwIcon } from "canica/icons"
import { EditRoutine } from "../../components/routines.tsx"

/** Run a routine: today's checklist, "3 of 5". */
export default page({
  title: "Routine",
  params: { routine: id("routines") },
  view: ({ params }) => {
    const today = useToday()
    const routine = useQuery("routine", { id: params.routine, day: today })
    const setStep = useMutation("setStep")
    const reset = useMutation("resetRun")
    const goRoutines = useNavigate("/routines")
    return routine.match({
      loading: () => <Loading shape="list" />,
      failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This routine does not exist", action: <Link to="/routines">All routines</Link> } }} />,
      success: (r) => (
        <>
          <PageHeader
            back={<Link to="/routines">← Routines</Link>}
            title={`${r.emoji ? `${r.emoji} ` : ""}${r.name}`}
            description={<span className="tabular-nums">{r.done === r.steps.length ? `All ${r.steps.length} done today` : `${r.done} of ${r.steps.length} today`}</span>}
            actions={
              <>
                <Button variant="outline" disabled={r.done === 0} onClick={() => void reset({ routine: r.id, day: today })}>
                  <RotateCcwIcon />
                  Start over
                </Button>
                <Button
                  variant="outline"
                  aria-haspopup="dialog"
                  onClick={async () => {
                    const x = await EditRoutine.open({ id: r.id, day: today })
                    if (x._tag === "Done") goRoutines()
                  }}
                >
                  <PencilIcon />
                  Edit
                </Button>
              </>
            }
          />
          <Progress value={r.steps.length === 0 ? 0 : (r.done / r.steps.length) * 100} aria-label={`${r.done} of ${r.steps.length} steps done`} />
          <List>
            {r.steps.map((s, i) => (
              <div key={s.id} role="listitem" className="px-4 py-3.5">
                <Label className="text-base">
                  <Checkbox checked={s.done} onCheckedChange={(c) => void setStep({ step: s.id, day: today, done: c === true })} />
                  <span className="w-5 text-sm font-normal text-muted-foreground tabular-nums">{i + 1}</span>
                  <span className={s.done ? "font-normal text-muted-foreground line-through" : "font-normal"}>{s.text}</span>
                </Label>
              </div>
            ))}
          </List>
          <ActionStatus status={setStep.status} />
        </>
      ),
    })
  },
})
src/routes/routines/index.tsx69 lines
import { Link, page, plural, useNavigate, useQuery, useToday } from "canica/client"
import { Button, EmptyBlock, ErrorState, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, List, Loading, PageHeader, Progress } from "canica/ui"
import { PlayIcon, PlusIcon } from "canica/icons"
import { NewRoutine } from "../../components/routines.tsx"

/** Routines: checklists you run, each with today's progress. */
export default page({
  title: "Routines",
  view: () => {
    const today = useToday()
    const routines = useQuery("routines", { today })
    const goRoutine = useNavigate("/routines/$routine")
    const newRoutine = (
      <Button
        aria-haspopup="dialog"
        onClick={async () => {
          const r = await NewRoutine.open()
          if (r._tag === "Done") goRoutine({ routine: r.value })
        }}
      >
        <PlusIcon />
        New routine
      </Button>
    )
    return (
      <>
        <PageHeader title="Routines" description="Morning, evening, gym day, packing for a trip. Write the steps once and run them as a checklist." actions={newRoutine} />
        {routines.match({
          loading: () => <Loading shape="list" />,
          failure: (e) => <ErrorState error={e} />,
          success: (list) =>
            list.length === 0 ? (
              <EmptyBlock title="No routines yet" description="A routine is a checklist you run again and again." action={newRoutine} />
            ) : (
              <List>
                {list.map((r) => (
                  <Item key={r.id}>
                    <ItemContent className="min-w-0">
                      <ItemTitle>
                        <Link to="/routines/$routine" params={{ routine: r.id }}>
                          {r.emoji ? `${r.emoji} ` : ""}
                          {r.name}
                        </Link>
                      </ItemTitle>
                      <ItemDescription>
                        <span className="tabular-nums">
                          {r.done === 0 ? plural(r.steps, "step") : r.done === r.steps ? "Done today" : `${r.done} of ${r.steps} today`}
                        </span>
                      </ItemDescription>
                      <Progress value={r.steps === 0 ? 0 : (r.done / r.steps) * 100} aria-label={`${r.name}: ${r.done} of ${r.steps}`} className="mt-1 h-1.5 max-w-60" />
                    </ItemContent>
                    <ItemActions>
                      <Button variant="outline" size="sm" asChild>
                        <Link to="/routines/$routine" params={{ routine: r.id }}>
                          <PlayIcon />
                          {r.done > 0 && r.done < r.steps ? "Continue" : "Run"}
                        </Link>
                      </Button>
                    </ItemActions>
                  </Item>
                ))}
              </List>
            ),
        })}
      </>
    )
  },
})
src/routes/todos/all.tsx10 lines
import { page, string } from "canica/client"
import { TodosView } from "../../components/todo-lists.tsx"

/** Every open todo, from every list. */
export default page({
  title: "All todos",
  search: { q: string().trim().optional() },
  view: ({ search }) => <TodosView list="all" title="All todos" q={search.q} />,
})
src/routes/todos/index.tsx10 lines
import { page, string } from "canica/client"
import { TodosView } from "../../components/todo-lists.tsx"

/** Todos: the Inbox (todos without a project). */
export default page({
  title: "Inbox",
  search: { q: string().trim().optional() },
  view: ({ search }) => <TodosView list="inbox" title="Inbox" q={search.q} />,
})
src/routes/todos/projects/$project.tsx23 lines
import { id, Link, page, string, useQuery } from "canica/client"
import { ErrorState, PageHeader } from "canica/ui"
import { TodosView } from "../../../components/todo-lists.tsx"

/** A project's todos; the page's title is the project's name. A deleted project: only "not found", no actions. */
export default page({
  title: "Project",
  params: { project: id("projects") },
  search: { q: string().trim().optional() },
  view: ({ params, search }) => {
    const project = useQuery("project", { id: params.project })
    if (project._tag === "Failure" && (project.error as { _tag?: string })._tag === "NotFound")
      return (
        <>
          <PageHeader title="Project not found" />
          <ErrorState error={project.error} states={{ NotFound: { title: "This project was deleted", action: <Link to="/todos">Back to the Inbox</Link> } }} />
        </>
      )
    const name = project._tag === "Success" ? project.value.name : "Project"
    return <TodosView key={params.project} list="project" project={params.project} title={name} q={search.q} />
  },
})
src/routes/todos/tags/$tag.tsx12 lines
import { page, string } from "canica/client"
import { tagName } from "../../../../shared/fields.ts"
import { TodosView } from "../../../components/todo-lists.tsx"

/** Every todo with a tag. */
export default page({
  title: (params) => `#${params.tag}`,
  params: { tag: tagName },
  search: { q: string().trim().optional() },
  view: ({ params, search }) => <TodosView key={params.tag} list="tag" tag={params.tag} title={`#${params.tag}`} q={search.q} />,
})
src/routes/tracker/$status.tsx11 lines
import { page } from "canica/client"
import { trackerStatus } from "../../../shared/fields.ts"
import { TrackerView } from "../../components/tracker-view.tsx"

/** The Tracker, one status: backlog, in progress, finished. */
export default page({
  title: "Tracker",
  params: { status: trackerStatus },
  view: ({ params }) => <TrackerView status={params.status} />,
})
src/routes/tracker/index.tsx9 lines
import { page } from "canica/client"
import { TrackerView } from "../../components/tracker-view.tsx"

/** The Tracker: everything. */
export default page({
  title: "Tracker",
  view: () => <TrackerView />,
})
src/routes/wishlist.tsx53 lines
import { page, plural, useQuery } from "canica/client"
import { Button, EmptyBlock, ErrorState, Loading, PageHeader, Section, Stat, Stats } from "canica/ui"
import { PlusIcon } from "canica/icons"
import { money, NewWish, WishCard } from "../components/wishlist.tsx"

/** Wishlist: a board of things to buy, with links and prices, and what they add up to. */
export default page({
  title: "Wishlist",
  view: () => {
    const wishes = useQuery("wishlist")
    const add = (
      <Button aria-haspopup="dialog" onClick={() => void NewWish.open()}>
        <PlusIcon />
        Add a wish
      </Button>
    )
    return (
      <>
        <PageHeader title="Wishlist" description="Things you want to buy. Good for gift ideas, and for letting an impulse buy cool off." actions={add} />
        {wishes.match({
          loading: () => <Loading shape="grid" />,
          failure: (e) => <ErrorState error={e} />,
          success: (w) =>
            w.wanted.length === 0 && w.bought.length === 0 ? (
              <EmptyBlock title="Nothing on the board" description="Add something you have your eye on, with its link and price." action={add} />
            ) : (
              <>
                <Stats>
                  <Stat label="Wanted" value={plural(w.wanted.length, "thing")} />
                  <Stat label="Total" value={money(w.total)} />
                </Stats>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
                  {w.wanted.map((wish) => (
                    <WishCard key={wish.id} wish={wish} />
                  ))}
                </div>
                {w.bought.length > 0 && (
                  <Section title="Bought">
                    <div className="grid grid-cols-2 gap-3 opacity-70 sm:grid-cols-3 lg:grid-cols-4">
                      {w.bought.map((wish) => (
                        <WishCard key={wish.id} wish={wish} />
                      ))}
                    </div>
                  </Section>
                )}
              </>
            ),
        })}
      </>
    )
  },
})
src/components/create.ts36 lines
import { NewHabit } from "./habits.tsx"
import { NewEvent } from "./planner.tsx"
import { NewRoutine } from "./routines.tsx"
import { NewProject, NewTodo } from "./todos.tsx"
import { TrackLink } from "./tracker.tsx"
import { NewWish } from "./wishlist.tsx"

export { openTodo } from "./todos.tsx"

/** Open the creation modal a palette command names. */
export const create = async (what: "todo" | "event" | "habit" | "routine" | "track" | "wish" | "project", today: string): Promise<void> => {
  switch (what) {
    case "todo":
      await NewTodo.open({})
      return
    case "event":
      await NewEvent.open({ day: today })
      return
    case "habit":
      await NewHabit.open()
      return
    case "routine":
      await NewRoutine.open()
      return
    case "track":
      await TrackLink.open()
      return
    case "wish":
      await NewWish.open()
      return
    case "project":
      await NewProject.open()
      return
  }
}
src/components/dump.tsx132 lines
import { useForm, useMutation, useRelativeFormatter, type QueryValue } from "canica/client"
import {
  Button,
  Card,
  Form,
  FormField,
  modal,
  ModalActions,
  ModalTitle,
  SubmitButton,
  Textarea,
  confirm,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "canica/ui"
import { ClapperboardIcon, EllipsisIcon, ExternalLinkIcon, GiftIcon, ListTodoIcon, Trash2Icon } from "canica/icons"
import { dumpText } from "../../shared/fields.ts"
import { siteOf } from "../../shared/logic.ts"
import { TodoDetails } from "./todos.tsx"
import { TrackerDetails } from "./tracker.tsx"
import { WishDetails } from "./wishlist.tsx"

type DumpItem = QueryValue<"dump">[number]

/** One thing in the Dump: a note, a link card (picture, title, site) or an image; its menu sorts it elsewhere. */
export function DumpCard({ item }: { readonly item: DumpItem }) {
  const relative = useRelativeFormatter()
  const toTodo = useMutation("dumpToTodo")
  const toTracker = useMutation("dumpToTracker")
  const toWish = useMutation("dumpToWish")
  const remove = useMutation("deleteDump")
  const name = item.title ?? item.text ?? (item.url ? siteOf(item.url) : "Image")
  return (
    <Card className="mb-3 break-inside-avoid gap-0 overflow-hidden py-0">
      {item.imageUrl && <img src={item.imageUrl} alt={item.kind === "image" ? "Dumped image" : ""} className="max-h-72 w-full bg-muted object-cover" />}
      <div className="flex flex-col gap-1.5 p-3">
        {item.kind === "note" && <p className="text-sm whitespace-pre-wrap">{item.text}</p>}
        {item.kind === "link" && (
          <>
            <a href={item.url!} rel="noreferrer" className={item.title ? "text-sm font-medium underline-offset-4 hover:underline" : "text-sm font-medium break-all underline-offset-4 hover:underline"}>
              {item.title ?? item.url}
            </a>
            {item.description && <p className="line-clamp-2 text-xs text-muted-foreground">{item.description}</p>}
          </>
        )}
        <div className="flex items-center justify-between gap-2">
          <span className="truncate text-xs text-muted-foreground">
            {[item.kind === "link" ? (item.site ?? siteOf(item.url!)) : item.kind === "image" ? "Image" : "Note", relative(item.createdAt)].join(" · ")}
          </span>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon-xs" aria-label={`Sort “${name}”`}>
                <EllipsisIcon />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Move to</DropdownMenuLabel>
              <DropdownMenuItem
                onSelect={async () => {
                  const r = await toTodo({ id: item.id })
                  if (r._tag === "Success") await TodoDetails.open({ id: r.value })
                }}
              >
                <ListTodoIcon aria-hidden /> Todos
              </DropdownMenuItem>
              {item.url && (
                <DropdownMenuItem
                  onSelect={async () => {
                    const r = await toTracker({ id: item.id })
                    if (r._tag === "Success") await TrackerDetails.open({ id: r.value })
                  }}
                >
                  <ClapperboardIcon aria-hidden /> Tracker
                </DropdownMenuItem>
              )}
              <DropdownMenuItem
                onSelect={async () => {
                  const r = await toWish({ id: item.id })
                  if (r._tag === "Success") await WishDetails.open({ id: r.value })
                }}
              >
                <GiftIcon aria-hidden /> Wishlist
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              {item.url && (
                <DropdownMenuItem asChild>
                  <a href={item.url} rel="noreferrer">
                    <ExternalLinkIcon aria-hidden /> Open link
                  </a>
                </DropdownMenuItem>
              )}
              <DropdownMenuItem
                variant="destructive"
                onSelect={async () => {
                  if ((await confirm({ title: "Delete this from the Dump?", confirm: "Delete" }))._tag === "Done") await remove({ id: item.id })
                }}
              >
                <Trash2Icon aria-hidden /> Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
    </Card>
  )
}

/** Notes and links are entities: compose them in a modal, not a page input. */
export const NewDump = modal()(() => {
  const close = NewDump.useClose()
  const add = useMutation("dumpText")
  const form = useForm("new note or link", { text: dumpText }, (v) => add(v), { onSuccess: () => close() })
  return (
    <>
      <ModalTitle>New note or link</ModalTitle>
      <Form form={form}>
        <FormField form={form} name="text" label="Note or link">
          <Textarea name="text" placeholder="A thought, or paste a link…" rows={4} autoFocus />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>Cancel</Button>
          <SubmitButton form={form}>Add</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})
src/components/grid.ts17 lines
/**
 * Grid placement classes for the Planner's timeline, written out in full: Tailwind only generates classes it finds
 * in the source, and lint forbids inline styles and arbitrary values, so `row-start-${n}` cannot be computed.
 */
const ROW_START = ["row-start-1", "row-start-2", "row-start-3", "row-start-4", "row-start-5", "row-start-6", "row-start-7", "row-start-8", "row-start-9", "row-start-10", "row-start-11", "row-start-12", "row-start-13", "row-start-14", "row-start-15", "row-start-16", "row-start-17", "row-start-18", "row-start-19", "row-start-20", "row-start-21", "row-start-22", "row-start-23", "row-start-24", "row-start-25", "row-start-26", "row-start-27", "row-start-28", "row-start-29", "row-start-30", "row-start-31", "row-start-32", "row-start-33", "row-start-34", "row-start-35", "row-start-36", "row-start-37", "row-start-38", "row-start-39", "row-start-40", "row-start-41", "row-start-42", "row-start-43", "row-start-44", "row-start-45", "row-start-46", "row-start-47", "row-start-48", "row-start-49"] as const
const ROW_SPAN = ["row-span-1", "row-span-2", "row-span-3", "row-span-4", "row-span-5", "row-span-6", "row-span-7", "row-span-8", "row-span-9", "row-span-10", "row-span-11", "row-span-12", "row-span-13", "row-span-14", "row-span-15", "row-span-16", "row-span-17", "row-span-18", "row-span-19", "row-span-20", "row-span-21", "row-span-22", "row-span-23", "row-span-24", "row-span-25", "row-span-26", "row-span-27", "row-span-28", "row-span-29", "row-span-30", "row-span-31", "row-span-32", "row-span-33", "row-span-34", "row-span-35", "row-span-36", "row-span-37", "row-span-38", "row-span-39", "row-span-40", "row-span-41", "row-span-42", "row-span-43", "row-span-44", "row-span-45", "row-span-46", "row-span-47", "row-span-48"] as const
const COL_START = ["col-start-1", "col-start-2", "col-start-3", "col-start-4"] as const

const clamp = (n: number, max: number) => Math.max(1, Math.min(max, Math.round(n)))

/** `row-start-<n>` for n in 1…49. */
export const rowStart = (n: number): string => ROW_START[clamp(n, 49) - 1]!
/** `row-span-<n>` for n in 1…48. */
export const rowSpan = (n: number): string => ROW_SPAN[clamp(n, 48) - 1]!
/** `col-start-<n>` for n in 1…4. */
export const colStart = (n: number): string => COL_START[clamp(n, 4) - 1]!
src/components/habits.tsx190 lines
import { addDays, plural, useForm, useMutation, useQuery, useToday, type Id, type QueryValue } from "canica/client"
import { Button, CheckButton, confirm, ErrorState, Form, FormField, Input, Item, ItemActions, ItemContent, ItemDescription, ItemTitle, Label, Checkbox, Loading, modal, ModalActions, ModalTitle, SubmitButton } from "canica/ui"
import { FlameIcon, SettingsIcon } from "canica/icons"
import { emoji, habitName } from "../../shared/fields.ts"

type Habit = QueryValue<"habits">[number]

const WEEKDAYS = ["M", "T", "W", "T", "F", "S", "S"]

/** The last 4 weeks, Monday first, one square a day: filled when ticked, outlined today, faint in the future. */
export function HabitGrid({ habit, today }: { readonly habit: Habit; readonly today: string }) {
  return (
    <div className="flex flex-col gap-1" role="img" aria-label={`${habit.name}: ${habit.last28} of the last 4 weeks' days ticked`}>
      <div className="grid grid-cols-7 gap-1 text-center text-xs leading-none text-muted-foreground" aria-hidden>
        {WEEKDAYS.map((d, i) => (
          <span key={i}>{d}</span>
        ))}
      </div>
      {habit.weeks.map((week) => (
        <div key={week[0]!.day} className="grid grid-cols-7 gap-1" aria-hidden>
          {week.map((d) => (
            <span
              key={d.day}
              title={d.day}
              className={
                d.future
                  ? "size-4 rounded-sm border border-dashed border-border"
                  : d.done
                    ? d.day === today
                      ? "size-4 rounded-sm bg-chart-1 ring-2 ring-chart-1/30"
                      : "size-4 rounded-sm bg-chart-1"
                    : d.day === today
                      ? "size-4 rounded-sm bg-muted ring-2 ring-border"
                      : "size-4 rounded-sm bg-muted"
              }
            />
          ))}
        </div>
      ))}
    </div>
  )
}

/** A habit: today's tick, its streak and its 4-week grid. */
export function HabitRow({ habit, today }: { readonly habit: Habit; readonly today: string }) {
  const setTick = useMutation("setTick")
  return (
    <Item variant="outline" className="items-start">
      <CheckButton pressed={habit.doneToday} label={`Done today: ${habit.name}`} onClick={() => setTick({ habit: habit.id, day: today, done: !habit.doneToday })} />
      <ItemContent className="min-w-0">
        <ItemTitle>
          <span className="truncate">
            {habit.emoji ? `${habit.emoji} ` : ""}
            {habit.name}
          </span>
        </ItemTitle>
        <ItemDescription>
          <span className="flex items-center gap-1 tabular-nums">
            <FlameIcon className={habit.streak > 0 ? "size-3.5 text-chart-4" : "size-3.5"} aria-hidden />
            {habit.streak > 0 ? `${habit.streak}-day streak` : "No streak yet"}
            {habit.best > habit.streak && <span> · best {habit.best}</span>}
          </span>
        </ItemDescription>
      </ItemContent>
      <div className="order-last w-full pl-14 sm:order-none sm:w-auto sm:pl-0">
        <HabitGrid habit={habit} today={today} />
      </div>
      <ItemActions>
        <Button variant="ghost" size="icon-sm" aria-haspopup="dialog" aria-label={`Edit ${habit.name}`} onClick={() => void HabitDetails.open({ id: habit.id })}>
          <SettingsIcon />
        </Button>
      </ItemActions>
    </Item>
  )
}

/** A compact habit tick for Today. */
export function HabitChip({ habit, today }: { readonly habit: Habit; readonly today: string }) {
  const setTick = useMutation("setTick")
  return (
    <Item variant="outline" size="sm">
      <CheckButton pressed={habit.doneToday} label={`Done today: ${habit.name}`} onClick={() => setTick({ habit: habit.id, day: today, done: !habit.doneToday })} />
      <ItemContent className="min-w-0">
        <ItemTitle>
          <span className="truncate">
            {habit.emoji ? `${habit.emoji} ` : ""}
            {habit.name}
          </span>
        </ItemTitle>
        <ItemDescription>
          <span className="tabular-nums">{habit.streak > 0 ? `${habit.streak}-day streak` : "Start a streak"}</span>
        </ItemDescription>
      </ItemContent>
    </Item>
  )
}

export const NewHabit = modal<Id<"habits">>()(() => {
  const close = NewHabit.useClose()
  const create = useMutation("createHabit")
  const form = useForm("new habit", { name: habitName, emoji: emoji.optional() }, (v) => create(v), { onSuccess: close })
  return (
    <>
      <ModalTitle>New habit</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "TooMany" ? `You can have at most ${e.max} habits.` : undefined)}>
        <div className="grid grid-cols-4 gap-3">
          <FormField form={form} name="emoji" label="Emoji">
            <Input name="emoji" placeholder="📚" autoComplete="off" />
          </FormField>
          <FormField form={form} name="name" label="Habit" className="col-span-3">
            <Input name="name" placeholder="Read 10 pages" autoComplete="off" autoFocus />
          </FormField>
        </div>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Add habit</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

/** Rename a habit, fix yesterday's tick, or delete it. */
export const HabitDetails = modal()(({ id }: { id: Id<"habits"> }) => {
  const close = HabitDetails.useClose()
  const today = useToday()
  const habit = useQuery("habit", { id })
  const all = useQuery("habits", { today })
  const update = useMutation("updateHabit")
  const setTick = useMutation("setTick")
  const remove = useMutation("deleteHabit")
  const form = useForm("edit habit", { name: habitName, emoji: emoji.optional() }, (v) => update({ id, ...v }), { onSuccess: () => close(), resetOnSuccess: false })
  const yesterday = addDays(today, -1)
  const stats = all._tag === "Success" ? all.value.find((h) => h.id === id) : undefined
  const tickedYesterday = stats?.weeks.flat().find((d) => d.day === yesterday)?.done ?? false
  return (
    <>
      <ModalTitle>Habit</ModalTitle>
      {habit.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This habit was deleted" } }} />,
        success: (h) => (
          <Form form={form} key={h.updatedAt}>
            <div className="grid grid-cols-4 gap-3">
              <FormField form={form} name="emoji" label="Emoji">
                <Input name="emoji" defaultValue={h.emoji ?? ""} autoComplete="off" />
              </FormField>
              <FormField form={form} name="name" label="Habit" className="col-span-3">
                <Input name="name" defaultValue={h.name} autoComplete="off" />
              </FormField>
            </div>
            {stats && (
              <div className="flex items-center justify-between gap-4 rounded-lg border border-border p-3">
                <HabitGrid habit={stats} today={today} />
                <div className="flex flex-col items-end gap-1 text-sm">
                  <span className="tabular-nums">{plural(stats.streak, "day")} now</span>
                  <span className="text-muted-foreground tabular-nums">best {stats.best}</span>
                </div>
              </div>
            )}
            <Label>
              <Checkbox checked={tickedYesterday} onCheckedChange={(c) => void setTick({ habit: id, day: yesterday, done: c === true })} />
              <span>Done yesterday</span>
            </Label>
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${h.name}”?`, description: "Its streak and history go too.", confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close()
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})
src/components/nav.tsx121 lines
import { Link } from "canica/client"
import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, UserMenu } from "canica/ui"
import {
  CalendarClockIcon,
  CalendarDaysIcon,
  ClapperboardIcon,
  EllipsisIcon,
  GiftIcon,
  InboxIcon,
  LeafIcon,
  ListChecksIcon,
  ListTodoIcon,
  RepeatIcon,
  SearchIcon,
  SunIcon,
} from "canica/icons"
import { openPalette } from "./palette.tsx"

/** The tools, in Kanso's order. */
export const TOOLS = [
  { to: "/", label: "Today", icon: SunIcon },
  { to: "/todos", label: "Todos", icon: ListTodoIcon },
  { to: "/planner", label: "Planner", icon: CalendarClockIcon },
  { to: "/habits", label: "Habits", icon: CalendarDaysIcon },
  { to: "/routines", label: "Routines", icon: ListChecksIcon },
  { to: "/tracker", label: "Tracker", icon: ClapperboardIcon },
  { to: "/wishlist", label: "Wishlist", icon: GiftIcon },
  { to: "/dump", label: "Dump", icon: InboxIcon },
] as const

function Brand() {
  return (
    <Link to="/" className="flex items-center gap-2 font-heading text-base font-semibold tracking-tight">
      <span className="flex size-7 items-center justify-center rounded-lg bg-primary text-primary-foreground">
        <LeafIcon className="size-4" aria-hidden />
      </span>
      Kanso
    </Link>
  )
}

/** Desktop: a fixed sidebar with every tool, search (⌘K) and the account. */
export function Sidebar() {
  return (
    <aside className="fixed inset-y-0 left-0 z-20 hidden w-56 flex-col gap-6 border-r border-border bg-muted/40 px-3 py-4 md:flex">
      <div className="px-2">
        <Brand />
      </div>
      <Button variant="outline" className="justify-between" aria-label="Search and commands" aria-haspopup="dialog" onClick={() => void openPalette()}>
        <span className="flex items-center gap-2 font-normal text-muted-foreground">
          <SearchIcon aria-hidden />
          Search
        </span>
        <kbd className="rounded border border-border bg-background px-1.5 font-mono text-xs">⌘K</kbd>
      </Button>
      <nav aria-label="Tools" data-nav className="flex flex-col gap-0.5">
        {TOOLS.map(({ to, label, icon: Icon }) => (
          <Link key={to} to={to} className="flex items-center gap-3 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground hover:bg-accent hover:text-foreground">
            <Icon className="size-4" aria-hidden />
            {label}
          </Link>
        ))}
      </nav>
      <div className="mt-auto">
        <UserMenu />
      </div>
    </aside>
  )
}

/** Phones: a top bar (brand, search, account) and a bottom bar with the main tools and the rest in a menu. */
export function MobileBars() {
  const main = TOOLS.slice(0, 4)
  const more = TOOLS.slice(4)
  return (
    <>
      <header className="sticky top-0 z-20 flex h-14 items-center justify-between gap-2 border-b border-border bg-background/90 px-4 backdrop-blur md:hidden">
        <Brand />
        <div className="flex items-center gap-1">
          <Button variant="ghost" size="icon" aria-label="Search and commands" aria-haspopup="dialog" onClick={() => void openPalette()}>
            <SearchIcon />
          </Button>
          <UserMenu />
        </div>
      </header>
      <nav aria-label="Tools" data-nav className="fixed inset-x-0 bottom-0 z-20 grid grid-cols-5 border-t border-border bg-background/95 backdrop-blur md:hidden">
        {main.map(({ to, label, icon: Icon }) => (
          <Link key={to} to={to} className="flex flex-col items-center gap-0.5 py-2 text-xs text-muted-foreground">
            <Icon className="size-5" aria-hidden />
            {label}
          </Link>
        ))}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-auto">
              <span className="flex flex-col items-center gap-0.5 text-xs font-normal text-muted-foreground">
                <EllipsisIcon className="size-5" aria-hidden />
                More
              </span>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" side="top">
            {more.map(({ to, label, icon: Icon }) => (
              <DropdownMenuItem key={to} asChild>
                <Link to={to}>
                  <Icon aria-hidden />
                  {label}
                </Link>
              </DropdownMenuItem>
            ))}
            <DropdownMenuItem onSelect={() => void openPalette()}>
              <RepeatIcon aria-hidden />
              Search and commands
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </nav>
    </>
  )
}
src/components/palette.tsx210 lines
import { string, useForm, useNavigate, useQuery, useToday, type Id, type ModalResult, type ReactNode } from "canica/client"
import { Button, Form, Input, modal, ModalTitle } from "canica/ui"
import {
  CalendarClockIcon,
  CalendarDaysIcon,
  CalendarPlusIcon,
  ClapperboardIcon,
  FolderIcon,
  GiftIcon,
  InboxIcon,
  ListChecksIcon,
  ListTodoIcon,
  PlusIcon,
  SunIcon,
  type LucideIcon,
} from "canica/icons"
import { KIND_LABEL, statusLabel } from "../../shared/logic.ts"
import { create } from "./create.ts"
import { dueLabel, openTodo } from "./todos.tsx"

/** What the palette asks its opener to do once it closed: open a creation modal, or a todo's details. */
export type PaletteResult =
  | { readonly create: "todo" | "event" | "habit" | "routine" | "track" | "wish" | "project"; readonly today: string }
  | { readonly todo: Id<"todos"> }

const CREATE: ReadonlyArray<{ readonly label: string; readonly create: Extract<PaletteResult, { create: unknown }>["create"]; readonly icon: LucideIcon; readonly words: string }> = [
  { label: "New todo", create: "todo", icon: PlusIcon, words: "add task todo capture" },
  { label: "New event", create: "event", icon: CalendarPlusIcon, words: "calendar meeting planner schedule" },
  { label: "Track a link", create: "track", icon: ClapperboardIcon, words: "movie book game series imdb goodreads steam tracker" },
  { label: "Add a wish", create: "wish", icon: GiftIcon, words: "wishlist buy gift" },
  { label: "New habit", create: "habit", icon: CalendarDaysIcon, words: "streak daily" },
  { label: "New routine", create: "routine", icon: ListChecksIcon, words: "checklist morning gym packing" },
  { label: "New project", create: "project", icon: FolderIcon, words: "list todos" },
]

/**
 * ⌘K: search everything and run commands. Typing filters live: the field submits its form on every change (forms
 * are the only input a modal has), and the latest text drives the search query.
 */
export const CommandPalette = modal<PaletteResult>()(() => {
  const close = CommandPalette.useClose()
  const today = useToday()
  const form = useForm("search", { q: string().trim().max(100).optional() }, (v) => v.q ?? "", { resetOnSuccess: false })
  const q = form.status._tag === "Success" ? form.status.value : ""
  const results = useQuery("search", { q })
  const go = {
    "/": useNavigate("/"),
    "/todos": useNavigate("/todos"),
    "/planner": useNavigate("/planner"),
    "/habits": useNavigate("/habits"),
    "/routines": useNavigate("/routines"),
    "/tracker": useNavigate("/tracker"),
    "/wishlist": useNavigate("/wishlist"),
    "/dump": useNavigate("/dump"),
  }
  const goPlannerDay = useNavigate("/planner/$day")
  const goRoutine = useNavigate("/routines/$routine")
  const goProject = useNavigate("/todos/projects/$project")
  /** Close, then go: navigating waits for the modal's history entry to be gone. */
  const leave = (then: () => void) => {
    close.cancel()
    then()
  }
  const needle = q.toLowerCase()
  const matches = (text: string) => needle === "" || text.toLowerCase().includes(needle)
  const pages = [
    { label: "Today", to: "/", icon: SunIcon },
    { label: "Todos", to: "/todos", icon: ListTodoIcon },
    { label: "Planner", to: "/planner", icon: CalendarClockIcon },
    { label: "Habits", to: "/habits", icon: CalendarDaysIcon },
    { label: "Routines", to: "/routines", icon: ListChecksIcon },
    { label: "Tracker", to: "/tracker", icon: ClapperboardIcon },
    { label: "Wishlist", to: "/wishlist", icon: GiftIcon },
    { label: "Dump", to: "/dump", icon: InboxIcon },
  ] as const
  const commands = CREATE.filter((c) => matches(`${c.label} ${c.words}`))
  const places = pages.filter((p) => matches(`go to ${p.label}`))

  return (
    <>
      <ModalTitle>Search and commands</ModalTitle>
      <Form form={form}>
        <div>
          <Input
            name="q"
            aria-label="Search or type a command"
            placeholder="Search or type a command…"
            autoComplete="off"
            autoFocus
            onChange={(e) => e.currentTarget.form?.requestSubmit()}
          />
        </div>
      </Form>
      <div className="-mx-1 flex max-h-96 flex-col gap-3 overflow-y-auto px-1">
        {commands.length > 0 && (
          <Group title="Create">
            {commands.map((c) => (
              <Row key={c.create} icon={c.icon} label={c.label} onClick={() => close({ create: c.create, today })} />
            ))}
          </Group>
        )}
        {places.length > 0 && (
          <Group title="Go to">
            {places.map((p) => (
              <Row key={p.to} icon={p.icon} label={p.label} onClick={() => leave(() => go[p.to]())} />
            ))}
          </Group>
        )}
        {q !== "" &&
          results.match({
            loading: () => <p className="px-2 text-sm text-muted-foreground">Searching…</p>,
            failure: () => <p className="px-2 text-sm text-destructive">Search failed. Try again.</p>,
            success: (r) => {
              const total = r.todos.length + r.projects.length + r.habits.length + r.routines.length + r.events.length + r.tracker.length + r.wishlist.length + r.dump.length
              if (total === 0 && commands.length === 0 && places.length === 0) return <p className="px-2 py-6 text-center text-sm text-muted-foreground">Nothing matches “{q}”.</p>
              return (
                <>
                  {r.todos.length > 0 && (
                    <Group title="Todos">
                      {r.todos.map((t) => (
                        <Row key={t.id} icon={ListTodoIcon} label={t.title} detail={t.done ? "Done" : t.due ? dueLabel(t.due, today) : "No date"} onClick={() => close({ todo: t.id })} />
                      ))}
                    </Group>
                  )}
                  {r.projects.length > 0 && (
                    <Group title="Projects">
                      {r.projects.map((p) => (
                        <Row key={p.id} icon={FolderIcon} label={p.name} onClick={() => leave(() => goProject({ project: p.id }))} />
                      ))}
                    </Group>
                  )}
                  {r.events.length > 0 && (
                    <Group title="Planner">
                      {r.events.map((e) => (
                        <Row key={e.id} icon={CalendarClockIcon} label={e.title} detail={dueLabel(e.day, today).replace("Overdue · ", "")} onClick={() => leave(() => goPlannerDay({ day: e.day }))} />
                      ))}
                    </Group>
                  )}
                  {r.habits.length > 0 && (
                    <Group title="Habits">
                      {r.habits.map((h) => (
                        <Row key={h.id} icon={CalendarDaysIcon} label={h.name} onClick={() => leave(() => go["/habits"]())} />
                      ))}
                    </Group>
                  )}
                  {r.routines.length > 0 && (
                    <Group title="Routines">
                      {r.routines.map((x) => (
                        <Row key={x.id} icon={ListChecksIcon} label={x.name} detail="Run" onClick={() => leave(() => goRoutine({ routine: x.id }))} />
                      ))}
                    </Group>
                  )}
                  {r.tracker.length > 0 && (
                    <Group title="Tracker">
                      {r.tracker.map((x) => (
                        <Row key={x.id} icon={ClapperboardIcon} label={x.title} detail={`${KIND_LABEL[x.kind]} · ${statusLabel(x.kind, x.status)}`} onClick={() => leave(() => go["/tracker"]())} />
                      ))}
                    </Group>
                  )}
                  {r.wishlist.length > 0 && (
                    <Group title="Wishlist">
                      {r.wishlist.map((x) => (
                        <Row key={x.id} icon={GiftIcon} label={x.title} onClick={() => leave(() => go["/wishlist"]())} />
                      ))}
                    </Group>
                  )}
                  {r.dump.length > 0 && (
                    <Group title="Dump">
                      {r.dump.map((x) => (
                        <Row key={x.id} icon={InboxIcon} label={x.title} onClick={() => leave(() => go["/dump"]())} />
                      ))}
                    </Group>
                  )}
                </>
              )
            },
          })}
      </div>
    </>
  )
})

function Group({ title, children }: { readonly title: string; readonly children: ReactNode }) {
  return (
    <div role="group" aria-label={title} className="flex flex-col">
      <span className="px-2 pb-1 text-xs font-medium text-muted-foreground">{title}</span>
      {children}
    </div>
  )
}

function Row({ icon: Icon, label, detail, onClick }: { readonly icon: LucideIcon; readonly label: string; readonly detail?: string; readonly onClick: () => void }) {
  return (
    <Button variant="ghost" className="justify-start" onClick={onClick}>
      <Icon className="text-muted-foreground" aria-hidden />
      <span className="truncate">{label}</span>
      {detail && <span className="ml-auto pl-3 text-xs text-muted-foreground">{detail}</span>}
    </Button>
  )
}

/** Open the palette, then do what was picked (create modals open from here, not from inside the palette). */
export const openPalette = async (): Promise<void> => {
  const r: ModalResult<PaletteResult> = await CommandPalette.open()
  if (r._tag !== "Done") return
  const v = r.value
  if ("todo" in v) return openTodo(v.todo)
  await create(v.create, v.today)
}
src/components/planner-view.tsx83 lines
import { addDays, Link, useNow, useQuery, useToday } from "canica/client"
import { Button, ErrorState, Item, ItemActions, ItemContent, ItemTitle, List, Loading, PageHeader, Section } from "canica/ui"
import { CalendarPlusIcon, ChevronLeftIcon, ChevronRightIcon } from "canica/icons"
import { NewEvent, Timeline } from "./planner.tsx"
import { ScheduleTodo, TagChips } from "./todos.tsx"

const title = (day: string, today: string) => {
  const text = new Date(`${day}T12:00:00Z`).toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", timeZone: "UTC" })
  return day === today ? `Today, ${text.split(", ").slice(1).join(", ")}` : text
}

/** One day of the Planner: the timeline, and the day's todos that have no time yet. */
export function PlannerView({ day }: { readonly day: string }) {
  const today = useToday()
  const now = useNow("minute")
  const plan = useQuery("planner", { day })
  const d = new Date(now)
  const minutesNow = day === today ? d.getHours() * 60 + d.getMinutes() : null
  return (
    <>
      <PageHeader
        title={title(day, today)}
        description="Your calendar and your todos on the same timeline."
        actions={
          <>
            <Button variant="outline" size="icon" asChild>
              <Link to="/planner/$day" params={{ day: addDays(day, -1) }} aria-label="Previous day">
                <ChevronLeftIcon />
              </Link>
            </Button>
            {day !== today && (
              <Button variant="outline" asChild>
                <Link to="/planner">Today</Link>
              </Button>
            )}
            <Button variant="outline" size="icon" asChild>
              <Link to="/planner/$day" params={{ day: addDays(day, 1) }} aria-label="Next day">
                <ChevronRightIcon />
              </Link>
            </Button>
            <Button aria-haspopup="dialog" onClick={() => void NewEvent.open({ day })}>
              <CalendarPlusIcon />
              New event
            </Button>
          </>
        }
      />
      {plan.match({
        loading: () => <Loading shape="list" />,
        failure: (e) => <ErrorState error={e} />,
        success: (p) => (
          <div className="flex flex-col gap-8 lg:flex-row lg:items-start">
            <div className="min-w-0 flex-1">
              <Timeline blocks={p.blocks} now={minutesNow} />
            </div>
            <Section title="To schedule" description={p.unscheduled.length === 0 ? "Every todo of the day has a time." : "Due this day, without a time"} className="lg:w-72 lg:shrink-0">
              {p.unscheduled.length > 0 && (
                <List>
                  {p.unscheduled.map((t) => (
                    <Item key={t.id} size="sm">
                      <ItemContent className="min-w-0">
                        <ItemTitle className="w-full">
                          <span className="truncate">{t.title}</span>
                        </ItemTitle>
                        <TagChips tags={t.tags} />
                      </ItemContent>
                      <ItemActions>
                        <Button variant="outline" size="sm" aria-haspopup="dialog" onClick={() => void ScheduleTodo.open({ id: t.id, day })}>
                          Schedule
                        </Button>
                      </ItemActions>
                    </Item>
                  ))}
                </List>
              )}
            </Section>
          </div>
        ),
      })}
    </>
  )
}
src/components/planner.tsx178 lines
import { day, useForm, useMutation, useQuery, type Id, type QueryValue } from "canica/client"
import { Button, confirm, ErrorState, Form, FormField, Input, Loading, modal, ModalActions, ModalTitle, SubmitButton, Textarea } from "canica/ui"
import { CheckIcon } from "canica/icons"
import { eventTitle, timeOfDay, todoNotes } from "../../shared/fields.ts"
import { formatMinutes, formatRange } from "../../shared/logic.ts"
import { colStart, rowSpan, rowStart } from "./grid.ts"
import { openTodo } from "./todos.tsx"

type Block = QueryValue<"planner">["blocks"][number]

const SLOT = 30 // minutes per grid row

/** Which column each block goes in so that overlapping ones sit side by side (at most 3). */
const lanes = (blocks: ReadonlyArray<Block>): ReadonlyArray<number> => {
  const ends: Array<number> = []
  return blocks.map((b) => {
    let lane = ends.findIndex((end) => end <= b.start)
    if (lane === -1) lane = ends.length < 3 ? ends.length : ends.indexOf(Math.min(...ends))
    ends[lane] = b.end
    return lane
  })
}

/**
 * The day as a timeline: an hour per two rows, events and scheduled todos placed by their time. The hours shown are
 * 7:00–22:00, stretched to fit anything earlier or later.
 */
export function Timeline({ blocks, now }: { readonly blocks: ReadonlyArray<Block>; readonly now: number | null }) {
  const first = Math.min(7, ...blocks.map((b) => Math.floor(b.start / 60)))
  const last = Math.max(22, ...blocks.map((b) => Math.ceil(b.end / 60)))
  const hours = Array.from({ length: last - first }, (_, i) => first + i)
  const row = (minutes: number) => Math.floor((minutes - first * 60) / SLOT) + 1
  const placed = lanes(blocks)
  const width = Math.max(1, ...placed.map((l) => l + 1))
  const cols = width === 1 ? "grid-cols-1" : width === 2 ? "grid-cols-2" : "grid-cols-3"
  return (
    <div className="flex gap-2">
      <div className="grid w-11 shrink-0" aria-hidden>
        {hours.map((h, i) => (
          <span key={h} className={`${rowStart(i * 2 + 1)} row-span-2 h-14 -translate-y-2 text-right text-xs text-muted-foreground tabular-nums`}>
            {formatMinutes(h * 60)}
          </span>
        ))}
      </div>
      <div className={`grid flex-1 gap-x-1 ${cols}`}>
        {/* One line per hour; each sizes its two half-hour rows. */}
        {hours.map((h, i) => (
          <div key={h} aria-hidden className={`${rowStart(i * 2 + 1)} col-span-full col-start-1 row-span-2 h-14 border-t border-border`} />
        ))}
        {now !== null && now >= first * 60 && now < last * 60 && (
          <div aria-hidden className={`${rowStart(row(now))} col-span-full col-start-1 h-0 border-t-2 border-chart-5`} />
        )}
        {blocks.map((b, i) => (
          <TimelineBlock key={`${b.kind}-${b.id}`} block={b} className={`${rowStart(row(b.start))} ${rowSpan(Math.max(1, Math.ceil((b.end - b.start) / SLOT)))} ${colStart(placed[i]! + 1)}`} />
        ))}
      </div>
    </div>
  )
}

function TimelineBlock({ block, className }: { readonly block: Block; readonly className: string }) {
  const label = `${block.title}, ${formatRange(block.start, block.end)}`
  const short = block.end - block.start <= SLOT
  return (
    <Button
      variant={block.kind === "event" ? "secondary" : "outline"}
      size="xs"
      aria-haspopup="dialog"
      aria-label={label}
      className={`${className} z-10 my-px h-auto min-h-0 items-start justify-start overflow-hidden`}
      onClick={() => void (block.kind === "event" ? EventDetails.open({ id: block.id as Id<"events"> }) : openTodo(block.id as Id<"todos">))}
    >
      <span className={short ? "flex min-w-0 items-baseline gap-2 py-0.5" : "flex min-w-0 flex-col items-start py-1"}>
      <span className="flex min-w-0 items-center gap-1 text-xs font-medium">
        {block.kind === "todo" && block.done && <CheckIcon className="size-3" aria-hidden />}
        <span className={block.kind === "todo" && block.done ? "truncate line-through" : "truncate"}>{block.title}</span>
      </span>
      <span className="text-xs font-normal text-muted-foreground tabular-nums">{formatRange(block.start, block.end)}</span>
      </span>
    </Button>
  )
}

const eventFields = { title: eventTitle, day: day(), start: timeOfDay, end: timeOfDay, notes: todoNotes.optional() }

/** A calendar event on a day. `start` preselects the hour it was opened for. */
export const NewEvent = modal<Id<"events">>()(({ day: initialDay, start = "09:00" }: { day: string; start?: string }) => {
  const close = NewEvent.useClose()
  const create = useMutation("createEvent")
  const form = useForm("new event", eventFields, (v) => create(v), { onSuccess: close })
  const end = formatMinutes(Math.min(1439, (Number(start.slice(0, 2)) + 1) * 60 + Number(start.slice(3))))
  return (
    <>
      <ModalTitle>New event</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "EndBeforeStart" ? "The event has to end after it starts." : undefined)}>
        <FormField form={form} name="title" label="What">
          <Input name="title" placeholder="Lunch with Iva" autoComplete="off" autoFocus />
        </FormField>
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
          <FormField form={form} name="day" label="Day">
            <Input name="day" type="date" defaultValue={initialDay} />
          </FormField>
          <FormField form={form} name="start" label="From">
            <Input name="start" type="time" defaultValue={start} />
          </FormField>
          <FormField form={form} name="end" label="To">
            <Input name="end" type="time" defaultValue={end} />
          </FormField>
        </div>
        <FormField form={form} name="notes" label="Notes">
          <Textarea name="notes" rows={2} />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Add event</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

export const EventDetails = modal()(({ id }: { id: Id<"events"> }) => {
  const close = EventDetails.useClose()
  const event = useQuery("event", { id })
  const update = useMutation("updateEvent")
  const remove = useMutation("deleteEvent")
  const form = useForm("edit event", eventFields, (v) => update({ id, ...v }), { onSuccess: () => close(), resetOnSuccess: false })
  return (
    <>
      <ModalTitle>Event</ModalTitle>
      {event.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This event was deleted" } }} />,
        success: (ev) => (
          <Form form={form} key={ev.updatedAt} describeError={(e) => (e._tag === "EndBeforeStart" ? "The event has to end after it starts." : undefined)}>
            <FormField form={form} name="title" label="What">
              <Input name="title" defaultValue={ev.title} autoComplete="off" />
            </FormField>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
              <FormField form={form} name="day" label="Day">
                <Input name="day" type="date" defaultValue={ev.day} />
              </FormField>
              <FormField form={form} name="start" label="From">
                <Input name="start" type="time" defaultValue={formatMinutes(ev.start)} />
              </FormField>
              <FormField form={form} name="end" label="To">
                <Input name="end" type="time" defaultValue={formatMinutes(ev.end % 1440)} />
              </FormField>
            </div>
            <FormField form={form} name="notes" label="Notes">
              <Textarea name="notes" rows={2} defaultValue={ev.notes ?? ""} />
            </FormField>
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${ev.title}”?`, confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close()
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})
src/components/routines.tsx87 lines
import { useForm, useMutation, useQuery, type Id } from "canica/client"
import { Button, confirm, ErrorState, Form, FormField, Input, Loading, modal, ModalActions, ModalTitle, RepeatInput, SubmitButton } from "canica/ui"
import { emoji, routineName, stepList } from "../../shared/fields.ts"

const fields = { name: routineName, emoji: emoji.optional(), steps: stepList }

/** Write a routine's steps once; run them as a checklist every time. Ends with its id. */
export const NewRoutine = modal<Id<"routines">>()(() => {
  const close = NewRoutine.useClose()
  const create = useMutation("createRoutine")
  const form = useForm("new routine", fields, (v) => create(v), { onSuccess: close })
  return (
    <>
      <ModalTitle>New routine</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "TooMany" ? `You can have at most ${e.max} routines.` : undefined)}>
        <div className="grid grid-cols-4 gap-3">
          <FormField form={form} name="emoji" label="Emoji">
            <Input name="emoji" placeholder="☀️" autoComplete="off" />
          </FormField>
          <FormField form={form} name="name" label="Name" className="col-span-3">
            <Input name="name" placeholder="Morning" autoComplete="off" autoFocus />
          </FormField>
        </div>
        <FormField form={form} name="steps" label="Steps, in order">
          <RepeatInput name="steps" label="Step" min={1} max={30} defaultValue={["", "", ""]} placeholder="Glass of water" />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Create routine</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

/** Rename a routine, rewrite its steps or delete it. Ends with "deleted" when deleted. */
export const EditRoutine = modal<"deleted">()(({ id, day }: { id: Id<"routines">; day: string }) => {
  const close = EditRoutine.useClose()
  const routine = useQuery("routine", { id, day })
  const update = useMutation("updateRoutine")
  const remove = useMutation("deleteRoutine")
  const form = useForm("edit routine", fields, (v) => update({ id, ...v }), { onSuccess: () => close.cancel(), resetOnSuccess: false })
  return (
    <>
      <ModalTitle>Edit routine</ModalTitle>
      {routine.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} />,
        success: (r) => (
          <Form form={form} key={r.updatedAt}>
            <div className="grid grid-cols-4 gap-3">
              <FormField form={form} name="emoji" label="Emoji">
                <Input name="emoji" defaultValue={r.emoji ?? ""} autoComplete="off" />
              </FormField>
              <FormField form={form} name="name" label="Name" className="col-span-3">
                <Input name="name" defaultValue={r.name} autoComplete="off" />
              </FormField>
            </div>
            <FormField form={form} name="steps" label="Steps, in order">
              <RepeatInput name="steps" label="Step" min={1} max={30} defaultValue={r.steps.map((s) => s.text)} />
            </FormField>
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${r.name}”?`, confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close("deleted")
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})
src/components/todo-lists.tsx143 lines
import { Link, plural, useNavigate, useQuery, useToday, type Id, type ReactNode } from "canica/client"
import { Button, EmptyBlock, ErrorState, List, Loading, PageHeader, SearchInput, Section } from "canica/ui"
import { FolderIcon, FolderPlusIcon, HashIcon, InboxIcon, LayersIcon, PlusIcon, SettingsIcon } from "canica/icons"
import { NewProject, NewTodo, ProjectSettings, TodoRow } from "./todos.tsx"

/** The lists of the Todos tool: Inbox, everything, projects and tags, each with its open count. */
function ListNav() {
  const lists = useQuery("todoLists")
  const goProject = useNavigate("/todos/projects/$project")
  return lists.match({
    loading: () => <div className="h-8" />,
    failure: (e) => <ErrorState error={e} />,
    success: (l) => (
      <nav aria-label="Lists" data-nav className="-mx-4 flex gap-1 overflow-x-auto px-4 pb-1 sm:mx-0 sm:flex-wrap sm:px-0">
        <Chip to="/todos" icon={<InboxIcon />} label="Inbox" count={l.inbox} />
        <Chip to="/todos/all" icon={<LayersIcon />} label="All" count={l.all} />
        {l.projects.map((p) => (
          <Link key={p.id} to="/todos/projects/$project" params={{ project: p.id }} className={CHIP}>
            <FolderIcon className="size-3.5" aria-hidden />
            {p.name}
            <span className="text-muted-foreground tabular-nums">{p.open}</span>
          </Link>
        ))}
        {l.tags.map((t) => (
          <Link key={t.tag} to="/todos/tags/$tag" params={{ tag: t.tag }} className={CHIP}>
            <HashIcon className="size-3.5" aria-hidden />
            {t.tag}
            <span className="text-muted-foreground tabular-nums">{t.open}</span>
          </Link>
        ))}
        <Button
          variant="ghost"
          size="sm"
          aria-haspopup="dialog"
          onClick={async () => {
            const r = await NewProject.open()
            if (r._tag === "Done") goProject({ project: r.value })
          }}
        >
          <FolderPlusIcon />
          Project
        </Button>
      </nav>
    ),
  })
}

const CHIP = "flex shrink-0 items-center gap-1.5 rounded-full border border-border px-3 py-1 text-sm whitespace-nowrap hover:bg-accent"

function Chip({ to, icon, label, count }: { readonly to: "/todos" | "/todos/all"; readonly icon: ReactNode; readonly label: string; readonly count: number }) {
  return (
    <Link to={to} className={`${CHIP} [&_svg]:size-3.5`}>
      {icon}
      {label}
      <span className="text-muted-foreground tabular-nums">{count}</span>
    </Link>
  )
}

/** One list of todos: its header, a New todo modal, a filter, the open todos and the latest done ones. */
export function TodosView({
  list,
  project,
  tag,
  title,
  q,
}: {
  readonly list: "inbox" | "all" | "project" | "tag"
  readonly project?: Id<"projects">
  readonly tag?: string
  readonly title: string
  readonly q: string | null | undefined
}) {
  const today = useToday()
  const todos = useQuery("todoList", { list, project, tag, q: q ?? undefined })
  const goInbox = useNavigate("/todos")
  const newTodo = (
    <Button aria-haspopup="dialog" onClick={() => void NewTodo.open({ project, tag })}>
      <PlusIcon />
      New todo
    </Button>
  )
  return (
    <>
      <PageHeader
        title={title}
        description={todos._tag === "Success" ? plural(todos.value.open.length, "open todo") : undefined}
        actions={
          <>
            {project && (
              <Button
                variant="outline"
                size="icon"
                aria-haspopup="dialog"
                aria-label="Project settings"
                onClick={async () => {
                  const r = await ProjectSettings.open({ id: project })
                  if (r._tag === "Done") goInbox()
                }}
              >
                <SettingsIcon />
              </Button>
            )}
            {newTodo}
          </>
        }
      />
      <ListNav />
      <SearchInput param="q" label={`Search ${title}`} />
      {todos.match({
        loading: () => <Loading shape="list" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This project was deleted", action: <Link to="/todos">Back to the Inbox</Link> } }} />,
        success: (t) => (
          <div className="flex flex-col gap-6">
            {t.open.length === 0 ? (
              <EmptyBlock
                title={q ? `Nothing matches “${q}”` : list === "inbox" ? "Inbox zero" : "Nothing open here"}
                description={q ? "Try another word." : "Use New todo to add something to this list."}
                action={q ? undefined : newTodo}
              />
            ) : (
              <List>
                {t.open.map((todo) => (
                  <TodoRow key={todo.id} todo={todo} today={today} showProject={list === "all" || list === "tag"} />
                ))}
              </List>
            )}
            {t.done.length > 0 && (
              <Section title="Completed" description="The latest 20">
                <List>
                  {t.done.map((todo) => (
                    <TodoRow key={todo.id} todo={todo} today={today} />
                  ))}
                </List>
              </Section>
            )}
          </div>
        ),
      })}
    </>
  )
}
src/components/todos.tsx391 lines
import { addDays, day, formatDate, id, string, useForm, useMutation, useQuery, useToday, type Id, type QueryValue } from "canica/client"
import {
  Badge,
  Button,
  Checkbox,
  confirm,
  ErrorState,
  Form,
  FormField,
  Input,
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemTitle,
  Label,
  Loading,
  modal,
  ModalActions,
  ModalText,
  ModalTitle,
  NativeSelect,
  NativeSelectOption,
  SubmitButton,
  Textarea,
} from "canica/ui"
import { CalendarClockIcon, ChevronRightIcon } from "canica/icons"
import { duration, projectName, tagList, timeOfDay, todoNotes, todoTitle } from "../../shared/fields.ts"
import { formatMinutes, formatRange, parseCapture } from "../../shared/logic.ts"

export type TodoView = QueryValue<"todo">

const SUGGESTED_TAGS = ["work", "home", "errands", "health"]

/** "Today", "Tomorrow", "Yesterday", "Overdue · Jan 13" or "Fri, Jan 16". */
export function dueLabel(due: string, today: string): string {
  if (due === today) return "Today"
  if (due === addDays(today, 1)) return "Tomorrow"
  if (due === addDays(today, -1)) return "Yesterday"
  const d = new Date(`${due}T12:00:00Z`)
  const text = d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" })
  return due < today ? `Overdue · ${text}` : text
}

/** Small chips for a todo's tags. */
export function TagChips({ tags }: { readonly tags: ReadonlyArray<string> }) {
  if (tags.length === 0) return null
  return (
    <span className="flex flex-wrap gap-1">
      {tags.map((t) => (
        <Badge key={t} variant="secondary">
          {t}
        </Badge>
      ))}
    </span>
  )
}

/** A todo in a list: the done box, its title, tags and when; the arrow opens its details. */
export function TodoRow({ todo, today, showProject = false }: { readonly todo: Omit<TodoView, "notes"> & { readonly notes: string | null }; readonly today: string; readonly showProject?: boolean }) {
  const setDone = useMutation("setDone")
  const facts = [
    todo.due && !todo.done ? dueLabel(todo.due, today) : null,
    todo.start !== null ? formatRange(todo.start, todo.start + todo.minutes) : null,
    showProject ? (todo.projectName ?? "Inbox") : null,
  ].filter(Boolean)
  return (
    <Item size="sm">
      <Checkbox
        checked={todo.done}
        aria-label={`Done: ${todo.title}`}
        onCheckedChange={(checked) => void setDone({ id: todo.id, done: checked === true, today })}
      />
      <ItemContent className="min-w-0">
        <ItemTitle className="w-full">
          <span className={todo.done ? "truncate text-muted-foreground line-through" : "truncate"}>{todo.title}</span>
        </ItemTitle>
        {(facts.length > 0 || todo.tags.length > 0) && (
          <ItemDescription>
            {facts.length > 0 && <span className={todo.due && todo.due < today && !todo.done ? "text-destructive" : undefined}>{facts.join(" · ")}</span>}
          </ItemDescription>
        )}
      </ItemContent>
      <TagChips tags={todo.tags} />
      <ItemActions>
        <Button variant="ghost" size="icon-sm" aria-haspopup="dialog" aria-label={`Open “${todo.title}”`} onClick={() => void openTodo(todo.id)}>
          <ChevronRightIcon />
        </Button>
      </ItemActions>
    </Item>
  )
}

/** Open a todo's details; it deletes itself from there. */
export const openTodo = async (id: Id<"todos">) => {
  await TodoDetails.open({ id })
}

// ---------------------------------------------------------------------------
// New todo

const todoFields = {
  title: todoTitle,
  notes: todoNotes.optional(),
  project: id("projects").optional(),
  due: day().optional(),
  time: timeOfDay.optional(),
  minutes: duration.optional(),
  tags: tagList.optional(),
  newTags: string().trim().max(200).optional(),
}

/** The tag checkboxes: the usual four, every tag used before, and the todo's own. */
function TagBoxes({ known, checked }: { readonly known: ReadonlyArray<string>; readonly checked: ReadonlyArray<string> }) {
  const all = [...new Set([...SUGGESTED_TAGS, ...known, ...checked])].sort()
  return (
    <div className="flex flex-wrap gap-x-4 gap-y-2">
      {all.map((t) => (
        <Label key={t}>
          <Checkbox name="tags" value={t} defaultChecked={checked.includes(t)} />
          <span>{t}</span>
        </Label>
      ))}
    </div>
  )
}

/**
 * Create a todo with everything: list, day, time, tags. `project`/`due` preselect (the list or day it was opened
 * from). Ends with the new todo's id.
 */
export const NewTodo = modal<Id<"todos">>()(({ project, due, tag }: { project?: Id<"projects">; due?: string; tag?: string }) => {
  const close = NewTodo.useClose()
  const create = useMutation("createTodo")
  const projects = useQuery("projects")
  const tags = useQuery("tags")
  const today = useToday()
  const form = useForm("new todo", todoFields, (v) => {
    const parsed = parseCapture(v.title, today)
    return create({ ...v, title: parsed.title, due: parsed.due ?? v.due, tags: [...new Set([...(v.tags ?? []), ...parsed.tags])] })
  }, { onSuccess: close })
  // Mount the uncontrolled select after its options arrive, so the current list stays selected.
  if (projects._tag !== "Success" || tags._tag !== "Success") return (
    <>
      <ModalTitle>New todo</ModalTitle>
      {projects._tag === "Failure" ? <ErrorState error={projects.error} /> : tags._tag === "Failure" ? <ErrorState error={tags.error} /> : <Loading shape="text" />}
    </>
  )
  const projectList = projects.value
  return (
    <>
      <ModalTitle>New todo</ModalTitle>
      <Form form={form}>
        <FormField form={form} name="title" label="What needs doing?" description="Use #tags and a trailing today or tomorrow; a day in the title overrides Day.">
          <Input name="title" placeholder="Send the invoice to Marko" autoComplete="off" autoFocus />
        </FormField>
        <div className="grid grid-cols-2 gap-3">
          <FormField form={form} name="project" label="List">
            <NativeSelect name="project" defaultValue={project ?? ""}>
              <NativeSelectOption value="">Inbox</NativeSelectOption>
              {projectList.map((p) => (
                <NativeSelectOption key={p.id} value={p.id}>
                  {p.name}
                </NativeSelectOption>
              ))}
            </NativeSelect>
          </FormField>
          <FormField form={form} name="due" label="Day">
            <Input name="due" type="date" defaultValue={due ?? ""} />
          </FormField>
        </div>
        <FormField form={form} name="tags" label="Tags">
          <TagBoxes known={tags._tag === "Success" ? tags.value : []} checked={tag ? [tag] : []} />
        </FormField>
        <FormField form={form} name="newTags" label="Other tags" description="Words separated by commas">
          <Input name="newTags" placeholder="side-project, reading" autoComplete="off" />
        </FormField>
        <FormField form={form} name="notes" label="Notes">
          <Textarea name="notes" rows={2} />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Add todo</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

// ---------------------------------------------------------------------------
// Details

/** A todo's details: edit everything, tick it off, schedule it, delete it. */
export const TodoDetails = modal()(({ id }: { id: Id<"todos"> }) => {
  const close = TodoDetails.useClose()
  const today = useToday()
  const todo = useQuery("todo", { id })
  const projects = useQuery("projects")
  const tags = useQuery("tags")
  const update = useMutation("updateTodo")
  const setDone = useMutation("setDone")
  const remove = useMutation("deleteTodo")
  const form = useForm("edit todo", todoFields, (v) => update({ id, ...v }), { onSuccess: () => close(), resetOnSuccess: false })
  const projectList = projects._tag === "Success" ? projects.value : []
  return (
    <>
      <ModalTitle>Todo</ModalTitle>
      {todo.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This todo was deleted" } }} />,
        success: (t) => (
          <Form form={form} key={t.updatedAt}>
            <div className="flex items-center justify-between gap-3">
              <Label>
                <Checkbox checked={t.done} onCheckedChange={(c) => void setDone({ id, done: c === true, today })} />
                <span>{t.done ? `Done${t.doneOn ? ` ${dueLabel(t.doneOn, today).toLowerCase()}` : ""}` : "Not done yet"}</span>
              </Label>
              <span className="text-xs text-muted-foreground">Added {formatDate(t.createdAt)}</span>
            </div>
            <FormField form={form} name="title" label="Title">
              <Input name="title" defaultValue={t.title} autoComplete="off" />
            </FormField>
            <div className="grid grid-cols-2 gap-3">
              <FormField form={form} name="project" label="List">
                <NativeSelect name="project" defaultValue={t.project ?? ""}>
                  <NativeSelectOption value="">Inbox</NativeSelectOption>
                  {projectList.map((p) => (
                    <NativeSelectOption key={p.id} value={p.id}>
                      {p.name}
                    </NativeSelectOption>
                  ))}
                </NativeSelect>
              </FormField>
              <FormField form={form} name="due" label="Day">
                <Input name="due" type="date" defaultValue={t.due ?? ""} />
              </FormField>
              <FormField form={form} name="time" label="Time" description="On the Planner">
                <Input name="time" type="time" defaultValue={t.start !== null ? formatMinutes(t.start) : ""} />
              </FormField>
              <FormField form={form} name="minutes" label="Minutes">
                <Input name="minutes" type="number" min={5} max={720} step={5} defaultValue={t.minutes} />
              </FormField>
            </div>
            <FormField form={form} name="tags" label="Tags">
              <TagBoxes known={tags._tag === "Success" ? tags.value : []} checked={t.tags} />
            </FormField>
            <FormField form={form} name="newTags" label="Other tags" description="Words separated by commas">
              <Input name="newTags" autoComplete="off" />
            </FormField>
            <FormField form={form} name="notes" label="Notes">
              <Textarea name="notes" rows={3} defaultValue={t.notes ?? ""} />
            </FormField>
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  if ((await confirm({ title: `Delete “${t.title}”?`, confirm: "Delete" }))._tag !== "Done") return
                  if ((await remove({ id }))._tag === "Success") close()
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})

// ---------------------------------------------------------------------------
// Schedule

/** Put a todo on the timeline: a day, a start time and how long. */
export const ScheduleTodo = modal()(({ id, day: initialDay, time }: { id: Id<"todos">; day: string; time?: string }) => {
  const close = ScheduleTodo.useClose()
  const todo = useQuery("todo", { id })
  const schedule = useMutation("scheduleTodo")
  const form = useForm("schedule todo", { day: day(), time: timeOfDay, minutes: duration }, (v) => schedule({ id, ...v }), { onSuccess: () => close() })
  return (
    <>
      <ModalTitle>Schedule</ModalTitle>
      {todo.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} />,
        success: (t) => (
          <Form form={form}>
            <ModalText>
              <span className="flex items-center gap-2">
                <CalendarClockIcon className="size-4" aria-hidden /> {t.title}
              </span>
            </ModalText>
            <div className="grid grid-cols-3 gap-3">
              <FormField form={form} name="day" label="Day">
                <Input name="day" type="date" defaultValue={t.due ?? initialDay} />
              </FormField>
              <FormField form={form} name="time" label="At">
                <Input name="time" type="time" defaultValue={t.start !== null ? formatMinutes(t.start) : (time ?? "09:00")} autoFocus />
              </FormField>
              <FormField form={form} name="minutes" label="Minutes">
                <Input name="minutes" type="number" min={5} max={720} step={5} defaultValue={t.minutes} />
              </FormField>
            </div>
            <ModalActions>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Schedule</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})

// ---------------------------------------------------------------------------
// Projects

export const NewProject = modal<Id<"projects">>()(() => {
  const close = NewProject.useClose()
  const create = useMutation("createProject")
  const form = useForm("new project", { name: projectName }, (v) => create(v), { onSuccess: close })
  return (
    <>
      <ModalTitle>New project</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "TooMany" ? `You can have at most ${e.max} projects.` : undefined)}>
        <FormField form={form} name="name" label="Name">
          <Input name="name" placeholder="Side project" autoComplete="off" autoFocus />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Create</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

/** Rename or delete a project. Ends with "deleted" when it was deleted (its page then goes to the Inbox). */
export const ProjectSettings = modal<"deleted">()(({ id }: { id: Id<"projects"> }) => {
  const close = ProjectSettings.useClose()
  const project = useQuery("project", { id })
  const rename = useMutation("renameProject")
  const remove = useMutation("deleteProject")
  const form = useForm("rename project", { name: projectName }, (v) => rename({ id, ...v }), { onSuccess: () => close.cancel() })
  return (
    <>
      <ModalTitle>Project</ModalTitle>
      {project.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} />,
        success: (p) => (
          <Form form={form} key={p.updatedAt}>
            <FormField form={form} name="name" label="Name">
              <Input name="name" defaultValue={p.name} autoComplete="off" />
            </FormField>
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${p.name}”?`, description: "Its todos move to the Inbox.", confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close("deleted")
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})
src/components/tracker-view.tsx61 lines
import { Link } from "canica/client"
import { useQuery } from "canica/client"
import { Button, EmptyBlock, ErrorState, Loading, PageHeader } from "canica/ui"
import { LinkIcon } from "canica/icons"
import type { TrackerStatus } from "../../shared/logic.ts"
import { TrackLink, TrackerCard } from "./tracker.tsx"

const FILTERS = [
  { label: "All", status: undefined },
  { label: "Backlog", status: "backlog" },
  { label: "In progress", status: "active" },
  { label: "Finished", status: "done" },
] as const

/** Movies, shows, books and games as a poster grid, filtered by status. */
export function TrackerView({ status }: { readonly status?: TrackerStatus }) {
  const items = useQuery("tracker", { status })
  const add = (
    <Button aria-haspopup="dialog" onClick={() => void TrackLink.open()}>
      <LinkIcon />
      Track a link
    </Button>
  )
  return (
    <>
      <PageHeader title="Tracker" description="Paste a link to a movie, show, book or game. The poster, year and details fill in." actions={add} />
      <nav aria-label="Status" data-nav className="flex gap-1 overflow-x-auto">
        {FILTERS.map((f) =>
          f.status ? (
            <Link key={f.label} to="/tracker/$status" params={{ status: f.status }} className="shrink-0 rounded-full border border-border px-3 py-1 text-sm hover:bg-accent">
              {f.label}
            </Link>
          ) : (
            <Link key={f.label} to="/tracker" className="shrink-0 rounded-full border border-border px-3 py-1 text-sm hover:bg-accent">
              {f.label}
            </Link>
          ),
        )}
      </nav>
      {items.match({
        loading: () => <Loading shape="grid" />,
        failure: (e) => <ErrorState error={e} />,
        success: (list) =>
          list.length === 0 ? (
            <EmptyBlock
              title={status ? "Nothing here" : "Nothing tracked yet"}
              description="Paste a link from IMDb, Letterboxd, Goodreads, Steam or BoardGameGeek."
              action={add}
            />
          ) : (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
              {list.map((item) => (
                <TrackerCard key={item.id} item={item} />
              ))}
            </div>
          ),
      })}
    </>
  )
}
src/components/tracker.tsx256 lines
import { useAction, useForm, useMutation, useQuery, type Id, type QueryValue } from "canica/client"
import {
  Badge,
  Button,
  Card,
  confirm,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
  ErrorState,
  FileInput,
  Form,
  FormField,
  Input,
  Loading,
  modal,
  ModalActions,
  ModalText,
  ModalTitle,
  NativeSelect,
  NativeSelectOption,
  SubmitButton,
  Thumbnail,
} from "canica/ui"
import { ChevronDownIcon, ClapperboardIcon, ExternalLinkIcon } from "canica/icons"
import { itemTitle, linkUrl, trackerKind, trackerKinds, trackerStatus, trackerStatuses, year } from "../../shared/fields.ts"
import { KIND_LABEL, statusLabel, type TrackerKind, type TrackerStatus } from "../../shared/logic.ts"

type TrackerItem = QueryValue<"tracker">[number]

/** The status as a menu: picking one saves it at once. */
export function StatusMenu({ item }: { readonly item: Pick<TrackerItem, "id" | "kind" | "status" | "title"> }) {
  const setStatus = useMutation("setTrackerStatus")
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant={item.status === "done" ? "secondary" : "outline"} size="xs" aria-label={`Status of ${item.title}: ${statusLabel(item.kind, item.status)}`}>
          {statusLabel(item.kind, item.status)}
          <ChevronDownIcon aria-hidden />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start">
        <DropdownMenuLabel>Status</DropdownMenuLabel>
        <DropdownMenuRadioGroup value={item.status} onValueChange={(v) => void setStatus({ id: item.id, status: v as TrackerStatus })}>
          {trackerStatuses.map((s) => (
            <DropdownMenuRadioItem key={s} value={s}>
              {statusLabel(item.kind, s)}
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

/** A poster card: the picture, title, year and kind, and the status menu. */
export function TrackerCard({ item }: { readonly item: TrackerItem }) {
  return (
    <Card className="gap-0 overflow-hidden py-0">
      {item.posterUrl ? (
        <img src={item.posterUrl} alt="" className="aspect-2/3 w-full bg-muted object-cover" />
      ) : (
        <div className="flex aspect-2/3 w-full items-center justify-center bg-muted text-muted-foreground" aria-hidden>
          <ClapperboardIcon className="size-8" />
        </div>
      )}
      <div className="flex flex-col gap-2 p-3">
        <Button variant="link" size="xs" className="-mx-2 h-auto shrink justify-start" aria-haspopup="dialog" onClick={() => void TrackerDetails.open({ id: item.id })}>
          <span className="truncate">{item.title}</span>
        </Button>
        <span className="text-xs text-muted-foreground tabular-nums">{[item.year, KIND_LABEL[item.kind]].filter(Boolean).join(" · ")}</span>
        <StatusMenu item={item} />
      </div>
    </Card>
  )
}

const manualFields = { title: itemTitle, kind: trackerKind, url: linkUrl.optional(), year: year.optional() }

/**
 * Paste a link: the page is read (title, poster, year, kind) and the item is saved. When the page cannot be read,
 * the second step adds it by hand with the link kept.
 */
export const TrackLink = modal<Id<"trackerItems">>()(() => {
  const close = TrackLink.useClose()
  const track = useAction("trackLink")
  const add = useMutation("addTrackerItem")
  const paste = useForm(
    "track link",
    { url: linkUrl },
    async ({ url }) => {
      const r = await track({ url })
      if (r._tag === "Success") return { added: r.value, manual: null, reason: "" }
      return { added: null, manual: url, reason: r.error._tag === "FetchFailed" && r.error.status ? `The page answered ${r.error.status}.` : "The page could not be read." }
    },
    {
      resetOnSuccess: false,
      onSuccess: (v) => {
        if (v.added) close(v.added)
      },
    },
  )
  const manual = paste.status._tag === "Success" && paste.status.value.manual !== null ? { url: paste.status.value.manual, reason: paste.status.value.reason } : undefined
  const byHand = useForm("track by hand", manualFields, (v) => add(v), { onSuccess: close })

  if (manual) {
    return (
      <>
        <ModalTitle>Add it by hand</ModalTitle>
        <ModalText>{manual.reason} Fill in the details and the link is kept.</ModalText>
        <Form form={byHand}>
          <FormField form={byHand} name="title" label="Title">
            <Input name="title" autoComplete="off" autoFocus />
          </FormField>
          <div className="grid grid-cols-2 gap-3">
            <FormField form={byHand} name="kind" label="Kind">
              <NativeSelect name="kind" defaultValue="movie">
                {trackerKinds.map((k) => (
                  <NativeSelectOption key={k} value={k}>
                    {KIND_LABEL[k]}
                  </NativeSelectOption>
                ))}
              </NativeSelect>
            </FormField>
            <FormField form={byHand} name="year" label="Year">
              <Input name="year" inputMode="numeric" autoComplete="off" />
            </FormField>
          </div>
          <FormField form={byHand} name="url" label="Link">
            <Input name="url" defaultValue={manual.url} autoComplete="off" />
          </FormField>
          <ModalActions>
            <Button type="button" variant="outline" onClick={close.cancel}>
              Cancel
            </Button>
            <SubmitButton form={byHand}>Add</SubmitButton>
          </ModalActions>
        </Form>
      </>
    )
  }
  return (
    <>
      <ModalTitle>Track a link</ModalTitle>
      <ModalText>Paste a link to a movie, show, book, game or board game: IMDb, Letterboxd, Goodreads, Steam, BoardGameGeek, YouTube…</ModalText>
      <Form form={paste}>
        <FormField form={paste} name="url" label="Link">
          <Input name="url" type="url" placeholder="https://www.imdb.com/title/tt1160419/" autoComplete="off" autoFocus />
        </FormField>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={paste}>Add</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

/** An item's details: poster, link, edit, delete. */
export const TrackerDetails = modal()(({ id }: { id: Id<"trackerItems"> }) => {
  const close = TrackerDetails.useClose()
  const item = useQuery("trackerItem", { id })
  const update = useMutation("updateTrackerItem")
  const remove = useMutation("deleteTrackerItem")
  const setPoster = useMutation("setTrackerPoster")
  const form = useForm("edit tracked item", { title: itemTitle, kind: trackerKind, year: year.optional(), status: trackerStatus }, (v) => update({ id, ...v }), {
    onSuccess: () => close(),
    resetOnSuccess: false,
  })
  return (
    <>
      <ModalTitle>Tracker</ModalTitle>
      {item.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This item was deleted" } }} />,
        success: (t) => (
          <Form form={form} key={t.updatedAt}>
            <div className="flex gap-4">
              {t.posterUrl && <Thumbnail src={t.posterUrl} alt={`Poster of ${t.title}`} size="lg" />}
              <div className="flex min-w-0 flex-col gap-2">
                <span className="flex flex-wrap gap-1">
                  <Badge variant="secondary">{KIND_LABEL[t.kind]}</Badge>
                  {t.year && <Badge variant="outline">{t.year}</Badge>}
                </span>
                {t.description && <p className="line-clamp-5 text-sm text-muted-foreground">{t.description}</p>}
                {t.url && (
                  <a href={t.url} rel="noreferrer" className="flex items-center gap-1 text-sm underline-offset-4 hover:underline">
                    <ExternalLinkIcon className="size-3.5" aria-hidden />
                    <span className="truncate">{t.site ?? t.url}</span>
                  </a>
                )}
              </div>
            </div>
            <FormField form={form} name="title" label="Title">
              <Input name="title" defaultValue={t.title} autoComplete="off" />
            </FormField>
            <div className="grid grid-cols-3 gap-3">
              <FormField form={form} name="kind" label="Kind">
                <NativeSelect name="kind" defaultValue={t.kind}>
                  {trackerKinds.map((k) => (
                    <NativeSelectOption key={k} value={k}>
                      {KIND_LABEL[k]}
                    </NativeSelectOption>
                  ))}
                </NativeSelect>
              </FormField>
              <FormField form={form} name="status" label="Status">
                <NativeSelect name="status" defaultValue={t.status}>
                  {trackerStatuses.map((s) => (
                    <NativeSelectOption key={s} value={s}>
                      {statusLabel(t.kind as TrackerKind, s)}
                    </NativeSelectOption>
                  ))}
                </NativeSelect>
              </FormField>
              <FormField form={form} name="year" label="Year">
                <Input name="year" inputMode="numeric" defaultValue={t.year ?? ""} autoComplete="off" />
              </FormField>
            </div>
            {t.posterUrl ? (
              <Button type="button" variant="outline" size="sm" className="self-start" onClick={() => void setPoster({ id })}>
                Remove poster
              </Button>
            ) : (
              <FileInput label="Poster" accept="image/png,image/jpeg,image/webp,image/gif" description="Upload one when the link had none" onUpload={(poster) => void setPoster({ id, poster })} />
            )}
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${t.title}”?`, confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close()
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})

src/components/wishlist.tsx153 lines
import { formatCents, useForm, useMutation, useQuery, type Id, type QueryValue } from "canica/client"
import {
  Button,
  Card,
  Checkbox,
  confirm,
  ErrorState,
  FileInput,
  Form,
  FormField,
  Input,
  Label,
  Loading,
  modal,
  ModalActions,
  ModalTitle,
  SubmitButton,
  Thumbnail,
} from "canica/ui"
import { ExternalLinkIcon, GiftIcon } from "canica/icons"
import { linkUrl, price, wishTitle } from "../../shared/fields.ts"

type Wish = QueryValue<"wishlist">["wanted"][number]

export const money = (cents: number) => formatCents(cents, "EUR")

/** A card on the board: picture, name, price, where to buy it, and a "bought" tick. */
export function WishCard({ wish }: { readonly wish: Wish }) {
  const setBought = useMutation("setBought")
  return (
    <Card className="gap-0 overflow-hidden py-0">
      {wish.imageUrl ? (
        <img src={wish.imageUrl} alt="" className="aspect-4/3 w-full bg-muted object-cover" />
      ) : (
        <div className="flex aspect-4/3 w-full items-center justify-center bg-muted text-muted-foreground" aria-hidden>
          <GiftIcon className="size-8" />
        </div>
      )}
      <div className="flex flex-col gap-1 p-3">
        <Button variant="link" size="xs" className="-mx-2 h-auto min-w-0 shrink justify-start" aria-haspopup="dialog" onClick={() => void WishDetails.open({ id: wish.id })}>
          <span className="truncate">{wish.title}</span>
        </Button>
        <div className="flex items-center gap-2 text-xs text-muted-foreground">
          {wish.price !== null && <span className="text-sm font-medium text-foreground tabular-nums">{money(wish.price)}</span>}
          {wish.url && (
            <a href={wish.url} rel="noreferrer" className="flex min-w-0 items-center gap-1 underline-offset-4 hover:underline">
              <ExternalLinkIcon className="size-3 shrink-0" aria-hidden />
              <span className="truncate">{wish.site ?? "Link"}</span>
            </a>
          )}
        </div>
        <Label className="mt-1 text-xs">
          <Checkbox checked={wish.bought} onCheckedChange={(c) => void setBought({ id: wish.id, bought: c === true })} />
          <span>Bought</span>
        </Label>
      </div>
    </Card>
  )
}

const fields = { title: wishTitle, url: linkUrl.optional(), price: price.optional() }

export const NewWish = modal<Id<"wishItems">>()(() => {
  const close = NewWish.useClose()
  const add = useMutation("addWish")
  const form = useForm("new wish", fields, (v) => add(v), { onSuccess: close })
  return (
    <>
      <ModalTitle>Add a wish</ModalTitle>
      <Form form={form} describeError={(e) => (e._tag === "TooMany" ? `You can have at most ${e.max} wishes.` : undefined)}>
        <FormField form={form} name="title" label="What">
          <Input name="title" placeholder="Espresso grinder" autoComplete="off" autoFocus />
        </FormField>
        <div className="grid grid-cols-3 gap-3">
          <FormField form={form} name="url" label="Link" description="Its picture is fetched for you" className="col-span-2">
            <Input name="url" type="url" placeholder="https://…" autoComplete="off" />
          </FormField>
          <FormField form={form} name="price" label="Price (€)">
            <Input name="price" inputMode="decimal" placeholder="149" autoComplete="off" />
          </FormField>
        </div>
        <ModalActions>
          <Button type="button" variant="outline" onClick={close.cancel}>
            Cancel
          </Button>
          <SubmitButton form={form}>Add</SubmitButton>
        </ModalActions>
      </Form>
    </>
  )
})

/** Edit a wish, change its picture, or delete it. */
export const WishDetails = modal()(({ id }: { id: Id<"wishItems"> }) => {
  const close = WishDetails.useClose()
  const wish = useQuery("wishItem", { id })
  const update = useMutation("updateWish")
  const setImage = useMutation("setWishImage")
  const remove = useMutation("deleteWish")
  const form = useForm("edit wish", fields, (v) => update({ id, ...v }), { onSuccess: () => close(), resetOnSuccess: false })
  return (
    <>
      <ModalTitle>Wish</ModalTitle>
      {wish.match({
        loading: () => <Loading shape="text" />,
        failure: (e) => <ErrorState error={e} states={{ NotFound: { title: "This wish was deleted" } }} />,
        success: (w) => (
          <Form form={form} key={w.updatedAt}>
            <FormField form={form} name="title" label="What">
              <Input name="title" defaultValue={w.title} autoComplete="off" />
            </FormField>
            <div className="grid grid-cols-3 gap-3">
              <FormField form={form} name="url" label="Link" className="col-span-2">
                <Input name="url" type="url" defaultValue={w.url ?? ""} autoComplete="off" />
              </FormField>
              <FormField form={form} name="price" label="Price (€)">
                <Input name="price" inputMode="decimal" defaultValue={w.price !== null ? (w.price / 100).toFixed(2) : ""} autoComplete="off" />
              </FormField>
            </div>
            {w.imageUrl ? (
              <div className="flex items-end gap-3">
                <Thumbnail src={w.imageUrl} alt={`Picture of ${w.title}`} size="lg" />
                <Button type="button" variant="outline" size="sm" onClick={() => void setImage({ id })}>
                  Remove picture
                </Button>
              </div>
            ) : (
              <FileInput label="Picture" accept="image/png,image/jpeg,image/webp,image/gif" description="PNG, JPEG, WebP or GIF" onUpload={(image) => void setImage({ id, image })} />
            )}
            <ModalActions>
              <Button
                type="button"
                variant="ghost"
                aria-haspopup="dialog"
                onClick={async () => {
                  const ok = await confirm({ title: `Delete “${w.title}”?`, confirm: "Delete" })
                  if (ok._tag === "Done" && (await remove({ id }))._tag === "Success") close()
                }}
              >
                Delete
              </Button>
              <Button type="button" variant="outline" onClick={close.cancel}>
                Cancel
              </Button>
              <SubmitButton form={form}>Save</SubmitButton>
            </ModalActions>
          </Form>
        ),
      })}
    </>
  )
})
src/styles.css14 lines
@import "tailwindcss";
@import "canica/ui/theme.css";
@import "./theme.css";

/* The tool you are on, in the sidebar and the bottom bar (Link marks it with aria-current="page"). */
[data-nav] a[aria-current="page"] {
  background-color: var(--accent);
  color: var(--foreground);
  font-weight: 500;
}
nav[data-nav].fixed {
  padding-bottom: env(safe-area-inset-bottom);
}
src/theme.css62 lines
/*
 * Kanso's look: quiet neutrals with a near-black primary (like kanso.so), Geist, soft radius,
 * and a sage green for progress (habit grid, routine progress) through the chart tokens.
 * Hand-written tokens (started from `canica theme`); edit them here.
 */
:root {
  --background: oklch(0.992 0.002 106);
  --foreground: oklch(0.2 0.006 106);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.2 0.006 106);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.2 0.006 106);
  --primary: oklch(0.24 0.008 150);
  --primary-foreground: oklch(0.985 0.004 150);
  --secondary: oklch(0.945 0.025 150);
  --secondary-foreground: oklch(0.3 0.04 150);
  --muted: oklch(0.962 0.004 106);
  --muted-foreground: oklch(0.54 0.01 106);
  --accent: oklch(0.955 0.006 140);
  --accent-foreground: oklch(0.24 0.008 150);
  --destructive: oklch(0.577 0.2 27);
  --success: oklch(0.58 0.09 150);
  --border: oklch(0.915 0.004 106);
  --input: oklch(0.905 0.004 106);
  --ring: oklch(0.62 0.07 150);
  --chart-1: oklch(0.62 0.09 150);
  --chart-2: oklch(0.84 0.06 150);
  --chart-3: oklch(0.6 0.12 250);
  --chart-4: oklch(0.72 0.12 70);
  --chart-5: oklch(0.62 0.13 20);
  --radius: 0.625rem;
  --font-body: "Geist", ui-sans-serif, system-ui, sans-serif;
  --font-display: "Geist", ui-sans-serif, system-ui, sans-serif;
}

.dark {
  --background: oklch(0.165 0.004 150);
  --foreground: oklch(0.96 0.002 106);
  --card: oklch(0.195 0.004 150);
  --card-foreground: oklch(0.96 0.002 106);
  --popover: oklch(0.21 0.005 150);
  --popover-foreground: oklch(0.96 0.002 106);
  --primary: oklch(0.93 0.01 150);
  --primary-foreground: oklch(0.2 0.006 150);
  --secondary: oklch(0.28 0.03 150);
  --secondary-foreground: oklch(0.93 0.02 150);
  --muted: oklch(0.235 0.005 150);
  --muted-foreground: oklch(0.68 0.01 150);
  --accent: oklch(0.26 0.008 150);
  --accent-foreground: oklch(0.96 0.002 106);
  --destructive: oklch(0.65 0.2 25);
  --success: oklch(0.7 0.11 150);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 14%);
  --ring: oklch(0.62 0.07 150);
  --chart-1: oklch(0.72 0.1 150);
  --chart-2: oklch(0.42 0.06 150);
  --chart-3: oklch(0.68 0.13 250);
  --chart-4: oklch(0.77 0.13 70);
  --chart-5: oklch(0.68 0.15 20);
}
server/index.test.ts268 lines
import { readFileSync } from "node:fs"
import { join } from "node:path"
import { describe, expect, it } from "vitest"
import { missingId, testApp } from "canica/testing"
import app from "./index.ts"

const fixture = (name: string) => readFileSync(join(process.cwd(), "server/fixtures", name), "utf8") // vitest runs in the app's directory
const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])

/** A fake web: pages from the fixtures, images as PNG bytes; anything else is a 404. */
const web = (url: string) => {
  if (/\.(png|jpg)(\?|$)/.test(url) || url.includes("media-amazon.com") || url.includes("steamstatic.com")) return new Response(PNG, { headers: { "content-type": "image/png" } })
  if (url.includes("goodreads.com/book")) return new Response(fixture("goodreads.html"), { headers: { "content-type": "text/html" } })
  if (url.includes("store.steampowered.com")) return new Response(fixture("steam.html"), { headers: { "content-type": "text/html" } })
  if (url.includes("v3.sg.media-imdb.com/suggestion/x/tt1160419")) return new Response(fixture("imdb-movie.json"))
  if (url === "https://example.shop/grinder") return new Response(`<meta property="og:image" content="https://example.shop/grinder.png"><meta property="og:site_name" content="Example Shop">`)
  return new Response("Not found", { status: 404 })
}

describe("today", () => {
  it("shows what is due today and overdue, counts what is left, and keeps today's done ones", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const today = t.today()
    ana.mutationOk("capture", { text: "Morning run #health", today, due: today })
    const late = ana.mutationOk("createTodo", { title: "Send the invoice", due: "2026-01-13", tags: ["work"] })
    const done = ana.mutationOk("capture", { text: "Fix the tap #home today", today })
    ana.mutationOk("createTodo", { title: "Someday", due: "2026-01-20" })
    ana.mutationOk("createTodo", { title: "No date" })
    ana.mutationOk("setDone", { id: done, done: true, today })

    const view = ana.queryOk("today", { today })
    expect(view.left).toBe(2)
    expect(view.overdue.map((x) => x.title)).toEqual(["Send the invoice"])
    expect(view.overdue[0]!.tags).toEqual(["work"])
    expect(view.today.map((x) => [x.title, x.done, x.tags])).toEqual([
      ["Morning run", false, ["health"]],
      ["Fix the tap", true, ["home"]],
    ])
    // Tomorrow the done one is gone and the open ones are overdue.
    const tomorrow = ana.queryOk("today", { today: "2026-01-16" })
    expect(tomorrow.today).toEqual([])
    expect(tomorrow.overdue.map((x) => x.title)).toEqual(["Send the invoice", "Morning run"])
    expect(tomorrow.overdue[0]!.id).toBe(late)
  })

  it("is private: other people see nothing and cannot touch it", () => {
    const t = testApp(app)
    const id = t.as("ana").mutationOk("createTodo", { title: "Mine", due: t.today() })
    expect(t.as("bob").queryOk("today", { today: t.today() }).left).toBe(0)
    expect(t.as("bob").mutation("setDone", { id, done: true, today: t.today() })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
    expect(t.as("visitor", { signedIn: false }).query("today", { today: t.today() })._tag).toBe("Failure")
  })
})

describe("todos", () => {
  it("lists the Inbox, a project and a tag, with counts", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const home = ana.mutationOk("createProject", { name: "Home" })
    ana.mutationOk("capture", { text: "Inbox thing #errands", today: t.today() })
    ana.mutationOk("capture", { text: "Paint the hall #weekend", today: t.today(), project: home })
    ana.mutationOk("createTodo", { title: "Buy paint", project: home, tags: ["errands"], newTags: "weekend, Urgent" })

    expect(ana.queryOk("todoList", { list: "inbox" }).open.map((x) => x.title)).toEqual(["Inbox thing"])
    expect(ana.queryOk("todoList", { list: "project", project: home }).open.map((x) => x.title)).toEqual(["Paint the hall", "Buy paint"])
    expect(ana.queryOk("todoList", { list: "tag", tag: "errands" }).open.map((x) => x.title).sort()).toEqual(["Buy paint", "Inbox thing"])
    expect(ana.queryOk("todoList", { list: "all", q: "paint" }).open).toHaveLength(2)
    const lists = ana.queryOk("todoLists")
    expect(lists).toMatchObject({ inbox: 1, all: 3, projects: [{ name: "Home", open: 2 }] })
    expect(lists.tags).toEqual([
      { tag: "errands", open: 2 },
      { tag: "urgent", open: 1 },
      { tag: "weekend", open: 2 },
    ])
  })

  it("edits a todo in place, and deleting a project moves its todos to the Inbox", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const p = ana.mutationOk("createProject", { name: "Side project" })
    const id = ana.mutationOk("createTodo", { title: "Write notes", project: p, tags: ["work"] })
    ana.mutationOk("updateTodo", { id, title: "Write the release notes", project: p, due: "2026-01-16", time: "10:00", minutes: 45, tags: ["writing"] })
    expect(ana.queryOk("todo", { id })).toMatchObject({ title: "Write the release notes", due: "2026-01-16", start: 600, minutes: 45, tags: ["writing"], projectName: "Side project" })
    ana.mutationOk("deleteProject", { id: p })
    expect(ana.queryOk("todo", { id })).toMatchObject({ project: null, projectName: null })
    expect(ana.mutation("createTodo", { title: "x", project: missingId("projects") })).toMatchObject({ _tag: "Failure", error: { _tag: "NotFound" } })
  })
})

describe("planner", () => {
  it("puts events and scheduled todos on one timeline, and keeps unscheduled ones aside", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const day = "2026-01-16"
    ana.mutationOk("createEvent", { title: "Standup", day, start: "09:00", end: "09:15" })
    ana.mutationOk("createEvent", { title: "Lunch with Iva", day, start: "12:30", end: "13:30" })
    const invoice = ana.mutationOk("createTodo", { title: "Send the invoice", due: day })
    const roadmap = ana.mutationOk("createTodo", { title: "Review the roadmap", due: "2026-01-20" })

    let plan = ana.queryOk("planner", { day })
    expect(plan.blocks.map((b) => b.title)).toEqual(["Standup", "Lunch with Iva"])
    expect(plan.unscheduled.map((x) => x.title)).toEqual(["Send the invoice"])

    ana.mutationOk("scheduleTodo", { id: invoice, day, time: "10:00", minutes: 30 })
    ana.mutationOk("scheduleTodo", { id: roadmap, day, time: "14:00", minutes: 90 })
    plan = ana.queryOk("planner", { day })
    expect(plan.blocks.map((b) => [b.kind, b.title, b.start, b.end])).toEqual([
      ["event", "Standup", 540, 555],
      ["todo", "Send the invoice", 600, 630],
      ["event", "Lunch with Iva", 750, 810],
      ["todo", "Review the roadmap", 840, 930],
    ])
    expect(plan.unscheduled).toEqual([])
    // Scheduling moved the roadmap to that day; unscheduling keeps the day.
    ana.mutationOk("unscheduleTodo", { id: roadmap })
    expect(ana.queryOk("planner", { day }).unscheduled.map((x) => x.title)).toEqual(["Review the roadmap"])
  })

  it("refuses an event that ends before it starts; midnight is the end of the day", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    expect(ana.mutation("createEvent", { title: "Oops", day: "2026-01-16", start: "10:00", end: "09:00" })).toMatchObject({ _tag: "Failure", error: { _tag: "EndBeforeStart" } })
    const late = ana.mutationOk("createEvent", { title: "Late show", day: "2026-01-16", start: "22:00", end: "00:00" })
    expect(ana.queryOk("event", { id: late }).end).toBe(1440)
    expect(ana.mutation("createEvent", { title: "Bad", day: "2026-01-16", start: "9am", end: "10:00" })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
  })
})

describe("habits", () => {
  it("ticks today, counts the streak and fills the 4-week grid", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const today = t.today() // Thursday 2026-01-15
    const read = ana.mutationOk("createHabit", { name: "Read", emoji: "📚" })
    for (const day of ["2026-01-10", "2026-01-12", "2026-01-13", "2026-01-14"]) ana.mutationOk("setTick", { habit: read, day, done: true })

    let [h] = ana.queryOk("habits", { today })
    expect(h).toMatchObject({ doneToday: false, streak: 3, best: 3, last28: 4 })
    ana.mutationOk("setTick", { habit: read, day: today, done: true })
    ana.mutationOk("setTick", { habit: read, day: today, done: true }) // twice is once
    ;[h] = ana.queryOk("habits", { today })
    expect(h).toMatchObject({ doneToday: true, streak: 4, best: 4, last28: 5 })
    expect(h!.weeks).toHaveLength(4)
    expect(h!.weeks[3]!.map((d) => (d.future ? "·" : d.done ? "x" : "_")).join("")).toBe("xxxx···")
    ana.mutationOk("setTick", { habit: read, day: "2026-01-13", done: false })
    ;[h] = ana.queryOk("habits", { today })
    expect(h).toMatchObject({ streak: 2, best: 2 })
  })
})

describe("routines", () => {
  it("runs as a checklist for the day: 3 of 5, reset, and edits keep ticks in place", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    const today = t.today()
    const id = ana.mutationOk("createRoutine", { name: "Morning", steps: ["Glass of water", "Make the bed", "10 minutes outside", "Plan the day", "Stretch"] })
    const run = ana.queryOk("routine", { id, day: today })
    for (const s of run.steps.slice(0, 3)) ana.mutationOk("setStep", { step: s.id, day: today, done: true })
    expect(ana.queryOk("routine", { id, day: today })).toMatchObject({ done: 3, steps: [{ done: true }, { done: true }, { done: true }, { done: false }, { done: false }] })
    expect(ana.queryOk("routines", { today })).toMatchObject([{ name: "Morning", steps: 5, done: 3 }])
    // Another day starts empty.
    expect(ana.queryOk("routine", { id, day: "2026-01-16" }).done).toBe(0)

    ana.mutationOk("updateRoutine", { id, name: "Morning", steps: ["Glass of water", "Make the bed", "Coffee"] })
    expect(ana.queryOk("routine", { id, day: today })).toMatchObject({ done: 3, steps: [{ text: "Glass of water" }, { text: "Make the bed" }, { text: "Coffee", done: true }] })
    ana.mutationOk("resetRun", { routine: id, day: today })
    expect(ana.queryOk("routine", { id, day: today }).done).toBe(0)
    expect(ana.mutation("createRoutine", { name: "Empty", steps: [] })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
  })
})

describe("tracker", () => {
  it("paste a link: the page's title, kind and year fill in, and the poster is downloaded into the app's files", async () => {
    const t = testApp(app, { fetch: web })
    const ana = t.as("ana")
    const id = await ana.actionOk("trackLink", { url: "https://www.goodreads.com/book/show/44767458-dune" })
    expect(ana.queryOk("trackerItem", { id })).toMatchObject({ title: "Dune (Dune, #1)", kind: "book", year: 1965, status: "backlog", posterUrl: null })
    await t.advance(1000) // the poster download runs in the background
    const item = ana.queryOk("trackerItem", { id })
    expect(item.posterUrl).toMatch(/^\/_canica\/files\//)
    expect((await t.fetch(item.posterUrl!)).status).toBe(200)
    ana.mutationOk("setTrackerStatus", { id, status: "active" })
    expect(ana.queryOk("tracker", { status: "active" }).map((x) => x.title)).toEqual(["Dune (Dune, #1)"])
  })

  it("IMDb links are read from IMDb's JSON", async () => {
    const t = testApp(app, { fetch: web })
    const id = await t.as("ana").actionOk("trackLink", { url: "https://www.imdb.com/title/tt1160419/" })
    expect(t.as("ana").queryOk("trackerItem", { id })).toMatchObject({ title: "Dune", kind: "movie", year: 2021, site: "IMDb" })
  })

  it("a page that cannot be read fails in words, and the link can be saved by hand", async () => {
    const t = testApp(app, { fetch: web })
    const r = await t.as("ana").action("trackLink", { url: "https://nowhere.example/film" })
    expect(r).toMatchObject({ _tag: "Failure", error: { _tag: "FetchFailed", status: 404 } })
    const id = t.as("ana").mutationOk("addTrackerItem", { title: "Some film", kind: "movie", url: "https://nowhere.example/film" })
    expect(t.as("ana").queryOk("trackerItem", { id })).toMatchObject({ site: "nowhere.example", status: "backlog" })
  })
})

describe("wishlist", () => {
  it("adds wishes with prices, totals what is still wanted, and fetches the picture of a link", async () => {
    const t = testApp(app, { fetch: web })
    const ana = t.as("ana")
    const grinder = ana.mutationOk("addWish", { title: "Espresso grinder", url: "https://example.shop/grinder", price: 22000 })
    const jacket = ana.mutationOk("addWish", { title: "Rain jacket", price: 9000 })
    ana.mutationOk("addWish", { title: "Climbing shoes" })
    expect(ana.queryOk("wishlist").total).toBe(31000)
    await t.advance(1000)
    expect(ana.queryOk("wishItem", { id: grinder })).toMatchObject({ site: "Example Shop", imageUrl: expect.stringMatching(/^\/_canica\/files\//) })
    ana.mutationOk("setBought", { id: jacket, bought: true })
    const list = ana.queryOk("wishlist")
    expect(list.total).toBe(22000)
    expect(list.bought.map((x) => x.title)).toEqual(["Rain jacket"])
    expect(ana.mutation("addWish", { title: "Free", price: 0 })).toMatchObject({ _tag: "Failure", error: { _tag: "InvalidArgs" } })
  })
})

describe("dump", () => {
  it("notes, links with a preview and images; search; sorting into the other tools", async () => {
    const t = testApp(app, { fetch: web })
    const ana = t.as("ana")
    const note = ana.mutationOk("dumpText", { text: "Gift idea for Luka: that board game from the party" })
    const link = ana.mutationOk("dumpText", { text: "https://store.steampowered.com/app/1245620/ELDEN_RING/" })
    const image = await ana.uploadOk(PNG, "shelf.png", "image/png")
    const pic = ana.mutationOk("dumpImage", { image })
    await t.advance(1000)
    const items = ana.queryOk("dump", {})
    expect(items.map((i) => i.kind)).toEqual(["image", "link", "note"])
    expect(items[1]).toMatchObject({ title: "ELDEN RING", site: "Steam", imageUrl: expect.stringMatching(/^\/_canica\/files\//) })
    expect(ana.queryOk("dump", { q: "luka" }).map((i) => i.id)).toEqual([note])

    const todo = ana.mutationOk("dumpToTodo", { id: note })
    expect(ana.queryOk("todo", { id: todo })).toMatchObject({ title: "Gift idea for Luka: that board game from the party", project: null })
    const tracked = ana.mutationOk("dumpToTracker", { id: link })
    await t.advance(1000)
    expect(ana.queryOk("trackerItem", { id: tracked })).toMatchObject({ title: "ELDEN RING", kind: "game", year: 2022, posterUrl: expect.any(String) })
    const wish = ana.mutationOk("dumpToWish", { id: pic })
    expect(ana.queryOk("wishItem", { id: wish })).toMatchObject({ imageUrl: expect.any(String) })
    expect(ana.queryOk("dump", {})).toEqual([])
  })

  it("only links go to the Tracker", () => {
    const t = testApp(app)
    const note = t.as("ana").mutationOk("dumpText", { text: "just a thought" })
    expect(t.as("ana").mutation("dumpToTracker", { id: note })).toMatchObject({ _tag: "Failure", error: { _tag: "NotALink" } })
  })
})

describe("search", () => {
  it("finds things across the tools, only the viewer's", () => {
    const t = testApp(app)
    const ana = t.as("ana")
    ana.mutationOk("createTodo", { title: "Review the Q4 roadmap" })
    ana.mutationOk("createEvent", { title: "Roadmap meeting", day: "2026-01-16", start: "10:00", end: "11:00" })
    ana.mutationOk("addWish", { title: "Road bike" })
    ana.mutationOk("createHabit", { name: "Stretch" })
    t.as("bob").mutationOk("createTodo", { title: "Bob's roadmap" })
    const r = ana.queryOk("search", { q: "road" })
    expect(r.todos.map((x) => x.title)).toEqual(["Review the Q4 roadmap"])
    expect(r.events.map((x) => x.title)).toEqual(["Roadmap meeting"])
    expect(r.wishlist.map((x) => x.title)).toEqual(["Road bike"])
    expect(r.habits).toEqual([])
    expect(ana.queryOk("search", { q: "100%" }).todos).toEqual([])
  })
})
server/logic.test.ts149 lines
import { readFileSync } from "node:fs"
import { join } from "node:path"
import { describe, expect, it } from "vitest"
import { bestStreak, currentStreak, formatMinutes, gridWeeks, isLink, parseCapture, parseTime, statusLabel } from "../shared/logic.ts"
import { decodeEntities, imdbId, kindOf, metaTags, parseImdb, parsePreview } from "./preview.ts"

const fixture = (name: string) => readFileSync(join(process.cwd(), "server/fixtures", name), "utf8") // vitest runs in the app's directory

describe("streaks", () => {
  const days = (...d: Array<string>) => new Set(d)

  it("counts consecutive days ending today", () => {
    expect(currentStreak(days("2026-01-13", "2026-01-14", "2026-01-15"), "2026-01-15")).toBe(3)
  })

  it("an unticked today does not break it yet: the streak ends yesterday", () => {
    expect(currentStreak(days("2026-01-13", "2026-01-14"), "2026-01-15")).toBe(2)
  })

  it("a missed day resets it", () => {
    expect(currentStreak(days("2026-01-12", "2026-01-13"), "2026-01-15")).toBe(0)
    expect(currentStreak(days("2026-01-10", "2026-01-11", "2026-01-13", "2026-01-14", "2026-01-15"), "2026-01-15")).toBe(3)
  })

  it("crosses months and years", () => {
    expect(currentStreak(days("2025-12-30", "2025-12-31", "2026-01-01"), "2026-01-01")).toBe(3)
  })

  it("best streak is the longest run anywhere", () => {
    expect(bestStreak(["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-05", "2026-01-06"])).toBe(3)
    expect(bestStreak([])).toBe(0)
    expect(bestStreak(["2026-01-02", "2026-01-01", "2026-01-02"])).toBe(2)
  })

  it("the grid is whole weeks from Monday, the current week last", () => {
    const weeks = gridWeeks("2026-01-15", 4) // a Thursday
    expect(weeks).toHaveLength(4)
    expect(weeks[3]![0]).toBe("2026-01-12")
    expect(weeks[3]![6]).toBe("2026-01-18")
    expect(weeks[0]![0]).toBe("2025-12-22")
  })
})

describe("time of day", () => {
  it("reads and writes HH:MM", () => {
    expect(parseTime("09:30")).toBe(570)
    expect(parseTime("00:00")).toBe(0)
    expect(formatMinutes(570)).toBe("09:30")
    expect(formatMinutes(1440)).toBe("24:00")
  })
})

describe("quick capture", () => {
  const today = "2026-01-15"

  it("takes #tags out of the title", () => {
    expect(parseCapture("Fix the kitchen tap #home #Errands", today)).toEqual({ title: "Fix the kitchen tap", tags: ["home", "errands"], due: undefined })
  })

  it("a trailing today/tomorrow sets the day", () => {
    expect(parseCapture("Send the invoice #work tomorrow", today)).toEqual({ title: "Send the invoice", tags: ["work"], due: "2026-01-16" })
    expect(parseCapture("Call mom today", today).due).toBe(today)
    expect(parseCapture("Plan tomorrow's talk", today)).toMatchObject({ title: "Plan tomorrow's talk", due: undefined })
  })

  it("keeps the text when only tags were typed", () => {
    expect(parseCapture("#work", today)).toEqual({ title: "#work", tags: [], due: undefined })
  })

  it("a # inside a word is not a tag", () => {
    expect(parseCapture("Learn C# basics", today).tags).toEqual([])
  })
})

describe("tracker labels", () => {
  it("names the status after the kind", () => {
    expect(statusLabel("movie", "done")).toBe("Watched")
    expect(statusLabel("book", "active")).toBe("Reading")
    expect(statusLabel("game", "done")).toBe("Played")
    expect(statusLabel("series", "backlog")).toBe("Backlog")
  })

  it("recognizes links", () => {
    expect(isLink("https://example.com/a?b=1")).toBe(true)
    expect(isLink("see https://example.com")).toBe(false)
    expect(isLink("buy milk")).toBe(false)
  })
})

describe("link previews", () => {
  it("Goodreads: a book, its cover and the year it was first published", () => {
    const p = parsePreview(fixture("goodreads.html"), "https://www.goodreads.com/book/show/44767458-dune")
    expect(p).toMatchObject({ title: "Dune (Dune, #1)", kind: "book", year: 1965, site: "Goodreads" })
    expect(p.image).toMatch(/^https:\/\/m\.media-amazon\.com\/.+\.jpg$/)
    expect(p.description).toMatch(/^Set on the desert planet Arrakis/)
  })

  it("Steam: a game without “on Steam”, the release year from the store page", () => {
    const p = parsePreview(fixture("steam.html"), "https://store.steampowered.com/app/1245620/ELDEN_RING/")
    expect(p).toMatchObject({ title: "ELDEN RING", kind: "game", year: 2022 })
    expect(p.image).toContain("capsule_616x353.jpg")
  })

  it("Letterboxd: a movie, the year taken out of the title", () => {
    const p = parsePreview(fixture("letterboxd.html"), "https://letterboxd.com/film/dune-2021/")
    expect(p).toMatchObject({ title: "Dune", kind: "movie", year: 2021 })
  })

  it("YouTube: a video", () => {
    const p = parsePreview(fixture("youtube.html"), "https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    expect(p).toMatchObject({ kind: "video", site: "YouTube", image: "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" })
    expect(p.title).toContain("Never Gonna Give You Up")
  })

  it("IMDb: titles from the suggestion JSON, movies and series", () => {
    expect(imdbId("https://www.imdb.com/title/tt1160419/?ref_=nv_sr_srsg_0")).toBe("tt1160419")
    expect(imdbId("https://example.com/title/tt1160419/")).toBeNull()
    const movie = parseImdb(JSON.parse(fixture("imdb-movie.json")), "tt1160419")
    expect(movie).toMatchObject({ title: "Dune", kind: "movie", year: 2021, site: "IMDb" })
    expect(movie?.image).toMatch(/^https:\/\/m\.media-amazon\.com\//)
    expect(parseImdb(JSON.parse(fixture("imdb-series.json")), "tt11280740")).toMatchObject({ title: "Severance", kind: "series", year: 2022 })
    expect(parseImdb({ d: [] }, "tt1")).toBeNull()
  })

  it("falls back to <title> and makes images absolute", () => {
    const html = `<html><head><title>My &amp; page</title><meta content="/img/a.png" property="og:image"></head></html>`
    expect(parsePreview(html, "https://blog.example.com/post/1")).toMatchObject({
      title: "My & page",
      image: "https://blog.example.com/img/a.png",
      site: "blog.example.com",
      kind: "other",
      year: null,
    })
  })

  it("reads meta tags in any attribute order and quoting", () => {
    const m = metaTags(`<meta content='A' name="description"><meta property=og:type content=video.tv_show>`)
    expect(m.get("description")).toBe("A")
    expect(m.get("og:type")).toBe("video.tv_show")
    expect(kindOf("https://www.imdb.com/title/tt1/", "video.tv_show")).toBe("series")
    expect(kindOf("https://boardgamegeek.com/boardgame/266192/wingspan", undefined)).toBe("boardgame")
    expect(decodeEntities("&#8220;Hi&#x201D; &lrm;&bull;")).toBe("“Hi” •")
  })

  it("a page without anything still gives a usable preview", () => {
    expect(parsePreview("", "https://example.com/x")).toEqual({ title: null, description: null, image: null, site: "example.com", kind: "other", year: null })
  })
})
src/app.test.tsx326 lines
import { readFileSync } from "node:fs"
import { join } from "node:path"
import { describe, expect, it } from "vitest"
import { as, choose, click, label, meanwhile, notSee, role, scene, see, testApp, text, type, visit, within } from "canica/testing"
import app from "../server/index.ts"
import { routes } from "./routes.gen.ts"

const goodreads = readFileSync(join(process.cwd(), "server/fixtures/goodreads.html"), "utf8")

describe("today", () => {
  it("New todo adds a todo for today with its tag; ticking it off leaves nothing", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/"),
      see(text("A clear day")),
      click(role("button", { name: "New todo" })),
      within(role("dialog"),
        meanwhile(() => expect(document.activeElement?.getAttribute("name")).toBe("title")),
        type(label("What needs doing?"), "Call mom #home"),
        click(role("button", { name: "Add todo" })),
      ),
      notSee(role("dialog")),
      see(text("Call mom")),
      see(text("home")),
      see(text(/1 left/)),
      click(role("checkbox", { name: "Done: Call mom" })),
      see(text(/nothing left/)),
    )
  })

  it("shows overdue todos apart, and today's schedule and habits", async () => {
    const t = testApp(app)
    const today = t.today()
    t.as("ana").mutationOk("createTodo", { title: "Renew the passport", due: "2026-01-13", tags: ["errands"] })
    t.as("ana").mutationOk("createEvent", { title: "Lunch with Iva", day: today, start: "12:30", end: "13:30" })
    t.as("ana").mutationOk("createHabit", { name: "Stretch" })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      see(role("heading", { name: "Overdue" })),
      see(text("Renew the passport")),
      see(text(/Overdue · Tue, Jan 13/)),
      see(text("Lunch with Iva")),
      see(text("12:30–13:30")),
      click(role("button", { name: "Done today: Stretch" })),
      see(text("1-day streak")),
    )
  })

  it("visitors who have not signed in get the sign-in screen", async () => {
    const t = testApp(app)
    await scene(t, routes, as("visitor", { signedIn: false }), visit("/"), see(text(/Sign in with Google/)))
  })
})

describe("todos", () => {
  it("a new todo goes through its modal; details edit it; delete asks first", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/todos"),
      see(text("Inbox zero")),
      click(role("button", { name: "New todo" })),
      within(role("dialog"),
        type(label("What needs doing?"), "Write the release notes"),
        click(role("checkbox", { name: "work" })),
        type(label("Other tags"), "writing"),
        click(role("button", { name: "Add todo" })),
      ),
      notSee(role("dialog")),
      see(text("Write the release notes")),
      see(text("writing")),
      click(role("button", { name: "Open “Write the release notes”" })),
      within(role("dialog"), type(label("Title"), "Write the 2.0 release notes"), click(role("button", { name: "Save" }))),
      notSee(role("dialog")),
      see(text("Write the 2.0 release notes")),
      click(role("button", { name: "Open “Write the 2.0 release notes”" })),
      within(role("dialog"), click(role("button", { name: "Delete" }))),
      within(role("alertdialog"), click(role("button", { name: "Delete" }))),
      notSee(role("dialog")),
      see(text("Inbox zero")),
    )
  })

  it("projects: create one, add a todo in its modal, and its todos show under its name", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/todos"),
      click(role("button", { name: "Project" })),
      within(role("dialog"), type(label("Name"), "Side project"), click(role("button", { name: "Create" }))),
      see(role("heading", { name: "Side project" })),
      click(role("button", { name: "New todo" })),
      within(role("dialog"), type(label("What needs doing?"), "Ship the beta #launch tomorrow"), click(role("button", { name: "Add todo" }))),
      notSee(role("dialog")),
      see(text("Ship the beta")),
      see(text(/Tomorrow/)),
      see(text("launch")),
    )
  })

  it("New todo in a tag list keeps that tag and accepts more tags and a day in its title", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("createTodo", { title: "Existing task", tags: ["work"] })
    await scene(t, routes,
      as("ana"), visit("/todos/tags/$tag", { tag: "work" }),
      click(role("button", { name: "New todo" })),
      within(role("dialog"),
        type(label("What needs doing?"), "Send invoice #billing tomorrow"),
        click(role("button", { name: "Add todo" })),
      ),
      notSee(role("dialog")), see(text("Send invoice")), see(text(/Tomorrow/)), see(text("billing")),
    )
    const created = t.as("ana").queryOk("todoList", { list: "tag", tag: "work" }).open.find((todo) => todo.title === "Send invoice")
    expect(created?.tags).toEqual(["billing", "work"])
  })

  it("the search box filters the list through the URL", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("createTodo", { title: "Buy oat milk" })
    t.as("ana").mutationOk("createTodo", { title: "Book the dentist" })
    await scene(t, routes, as("ana"), visit("/todos?q=milk"), see(text("Buy oat milk")), notSee(text("Book the dentist")))
  })
})

describe("habits and routines", () => {
  it("a new habit is ticked for today and starts a streak", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/habits"),
      see(text("No habits yet")),
      click(role("button", { name: "New habit" })),
      within(role("dialog"), type(label("Habit"), "Read"), click(role("button", { name: "Add habit" }))),
      see(text("No streak yet")),
      click(role("button", { name: "Done today: Read" })),
      see(text("1-day streak")),
      see(text("1 of 1")),
    )
  })

  it("a routine is written once, then run as a checklist: 2 of 3", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/routines"),
      click(role("button", { name: "New routine" })),
      within(role("dialog"),
        type(label("Name"), "Morning"),
        type(label("Step 1"), "Glass of water"),
        type(label("Step 2"), "Make the bed"),
        type(label("Step 3"), "Plan the day"),
        click(role("button", { name: "Create routine" })),
      ),
      see(role("heading", { name: "Morning" })),
      see(text("0 of 3 today")),
      click(role("checkbox", { name: /Glass of water/ })),
      click(role("checkbox", { name: /Make the bed/ })),
      see(text("2 of 3 today")),
      click(role("button", { name: "Start over" })),
      see(text("0 of 3 today")),
    )
  })
})

describe("planner", () => {
  it("an event made in its modal sits on the timeline; a todo of the day gets a time", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("createTodo", { title: "Send the invoice", due: t.today() })
    await scene(t, routes,
      as("ana"),
      visit("/planner"),
      see(role("heading", { name: "To schedule" })),
      see(text("Send the invoice")),
      click(role("button", { name: "New event" })),
      within(role("dialog"), type(label("What"), "Standup"), type(label("From"), "09:00"), type(label("To"), "09:15"), click(role("button", { name: "Add event" }))),
      see(role("button", { name: "Standup, 09:00–09:15" })),
      click(role("button", { name: "Schedule" })),
      within(role("dialog"), type(label("At"), "10:00"), type(label("Minutes"), "45"), click(role("button", { name: "Schedule" }))),
      see(role("button", { name: "Send the invoice, 10:00–10:45" })),
      see(text("Every todo of the day has a time.")),
    )
  })

  it("an event that ends before it starts is refused in words", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/planner"),
      click(role("button", { name: "New event" })),
      within(role("dialog"), type(label("What"), "Oops"), type(label("From"), "10:00"), type(label("To"), "09:00"), click(role("button", { name: "Add event" })), see(text("The event has to end after it starts."))),
    )
  })
})

describe("tracker, wishlist and dump", () => {
  it("pasting a Goodreads link fills in the title, year and kind", async () => {
    const t = testApp(app, { fetch: (url) => (url.includes("goodreads.com/book") ? new Response(goodreads) : new Response("no", { status: 404 })) })
    await scene(t, routes,
      as("ana"),
      visit("/tracker"),
      see(text("Nothing tracked yet")),
      click(role("button", { name: "Track a link" })),
      within(role("dialog"), type(label("Link"), "https://www.goodreads.com/book/show/44767458-dune"), click(role("button", { name: "Add" }))),
      notSee(role("dialog")),
      see(text("Dune (Dune, #1)")),
      see(text("1965 · Book")),
      see(role("button", { name: /Status of Dune \(Dune, #1\): Backlog/ })),
    )
  })

  it("a page that cannot be read is added by hand, the link kept", async () => {
    const t = testApp(app, { fetch: () => new Response("Forbidden", { status: 403 }) })
    await scene(t, routes,
      as("ana"),
      visit("/tracker"),
      click(role("button", { name: "Track a link" })),
      within(role("dialog"), type(label("Link"), "https://www.imdb.com/title/tt0000001/"), click(role("button", { name: "Add" }))),
      within(role("dialog"), see(text(/The page answered 403/)), type(label("Title"), "Some old film"), choose(label("Kind"), "Movie"), type(label("Year"), "1999"), click(role("button", { name: "Add" }))),
      notSee(role("dialog")),
      see(text("Some old film")),
      see(text("1999 · Movie")),
    )
  })

  it("wishes with prices add up", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/wishlist"),
      click(role("button", { name: "Add a wish" })),
      within(role("dialog"), type(label("What"), "Rain jacket"), type(label("Price (€)"), "90"), click(role("button", { name: "Add" }))),
      click(role("button", { name: "Add a wish" })),
      within(role("dialog"), type(label("What"), "Espresso grinder"), type(label("Price (€)"), "219.50"), click(role("button", { name: "Add" }))),
      see(text("€309.50")),
      click(role("checkbox", { name: /Bought/ })),
      see(text("€90.00")),
    )
  })

  it("Dump's modal validates empty text and recognizes a link", async () => {
    const t = testApp(app, { fetch: () => new Response("Not found", { status: 404 }) })
    await scene(t, routes,
      as("ana"), visit("/dump"),
      click(role("button", { name: "New note or link" })),
      within(role("dialog"),
        click(role("button", { name: "Add" })),
        see(role("textbox", { name: "Note or link" })),
        type(label("Note or link"), "https://example.com/article"),
        click(role("button", { name: "Add" })),
      ),
      notSee(role("dialog")), see(role("link", { name: "https://example.com/article" })),
    )
    expect(t.as("ana").queryOk("dump", {})[0]).toMatchObject({ kind: "link", url: "https://example.com/article" })
  })

  it("a dumped note is sorted into Todos, where its details open", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/dump"),
      see(text("The Dump is empty")),
      click(role("button", { name: "New note or link" })),
      within(role("dialog"),
        meanwhile(() => expect(document.activeElement?.getAttribute("name")).toBe("text")),
        type(label("Note or link"), "Gift idea for Luka: that board game"),
        click(role("button", { name: "Add" })),
      ),
      notSee(role("dialog")),
      see(text("Gift idea for Luka: that board game")),
      click(role("button", { name: "Sort “Gift idea for Luka: that board game”" })),
      click(role("menuitem", { name: "Todos" })),
      within(role("dialog"), see(role("textbox", { name: "Title" }))),
      within(role("dialog"), click(role("button", { name: "Cancel" }))),
      see(text("The Dump is empty")),
    )
  })
})

describe("phone bar", () => {
  // Its items are links rendered as menu items (`<DropdownMenuItem asChild><Link>`), and one opens the palette.
  for (const [item, heading] of [["Routines", "Routines"], ["Tracker", "Tracker"], ["Wishlist", "Wishlist"], ["Dump", "Dump"]] as const) {
    it(`More → ${item} goes there`, async () => {
      const t = testApp(app)
      await scene(t, routes,
        as("ana"),
        visit("/"),
        click(role("button", { name: "More" })),
        click(role("menuitem", { name: item })),
        see(role("heading", { name: heading, level: 1 })),
        notSee(role("heading", { name: "Today", level: 1 })),
      )
    })
  }

  it("More → Search and commands opens the palette", async () => {
    const t = testApp(app)
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "More" })),
      click(role("menuitem", { name: "Search and commands" })),
      within(role("dialog"), see(role("textbox", { name: "Search or type a command" }))),
    )
  })
})

describe("command palette", () => {
  it("search finds a todo across the app and opens it; commands go to a tool", async () => {
    const t = testApp(app)
    t.as("ana").mutationOk("createTodo", { title: "Send the invoice to Marko" })
    await scene(t, routes,
      as("ana"),
      visit("/"),
      click(role("button", { name: "Search and commands" })),
      within(role("dialog"), type(role("textbox", { name: "Search or type a command" }), "invoice"), click(role("button", { name: /Send the invoice to Marko/ }))),
      within(role("dialog"), see(role("heading", { name: "Todo" }))),
      within(role("dialog"), click(role("button", { name: "Cancel" }))),
      click(role("button", { name: "Search and commands" })),
      within(role("dialog"), type(role("textbox", { name: "Search or type a command" }), "habits"), click(role("button", { name: "Habits" }))),
      see(role("heading", { name: "Habits" })),
    )
  })
})