feat(web): show, add and remove task tags and filter by tag in the companion

- web/src/lib/taskQueries.ts: list task query (existing filters + tags),
  subtasks, loadTaskTags (one query, live tags of the account only) and the
  account tags, shared by the list page and GET /api/lists/[id]/tasks.
- ?tags= validated by zod (at most 20 UUIDs, count checked first); the tag
  filter joins sl_tags on the account and deleted_at IS NULL; 400 on a
  malformed value.
- TaskItem: tag pills on tasks and subtasks; the detail view adds an
  existing tag and removes one through the task-tag API.
- Sidebar: a click on a tag filters the current view by ?tags=<id>, a second
  click removes it; FilterBar shows the active tag filter.
- FR/EN strings.

Refs #179
Refs #168

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-02 21:16:47 -05:00
commit 99cc2fc1c4
13 changed files with 648 additions and 144 deletions

View file

@ -3,11 +3,17 @@ export const dynamic = "force-dynamic";
import { notFound, redirect } from "next/navigation";
import { getAuthenticatedUser } from "@/lib/auth";
import { db } from "@/db/client";
import { slLists, slTasks } from "@/db/schema";
import { eq, and, isNull, asc, desc } from "drizzle-orm";
import { slLists } from "@/db/schema";
import { eq, and, isNull } from "drizzle-orm";
import { TaskList } from "@/components/TaskList";
import type { Task } from "@/lib/types";
import type { SQL } from "drizzle-orm";
import { parseTagFilter } from "@/lib/validators";
import {
queryListTasks,
loadSubtasks,
loadTaskTags,
loadAccountTags,
} from "@/lib/taskQueries";
export default async function ListPage({
params,
@ -37,70 +43,31 @@ export default async function ListPage({
if (!list) notFound();
// Build conditions
const conditions: SQL[] = [
eq(slTasks.listId, listId),
eq(slTasks.userId, userId),
isNull(slTasks.deletedAt),
isNull(slTasks.parentId),
];
const completed = typeof search.completed === "string" ? search.completed : undefined;
if (completed === "true" || completed === "false") {
conditions.push(eq(slTasks.completed, completed === "true"));
}
// A malformed ?tags= in the address bar shows the list unfiltered (the API
// answers 400 to the same value).
const tagFilter = parseTagFilter(typeof search.tags === "string" ? search.tags : undefined);
const sortBy = (typeof search.sortBy === "string" ? search.sortBy : "position") as string;
const sortOrder = (typeof search.sortOrder === "string" ? search.sortOrder : "asc") as string;
const tasks = await queryListTasks(userId, listId, {
completed: completed === "true" || completed === "false" ? completed === "true" : undefined,
tagIds: tagFilter.ok ? tagFilter.tagIds : null,
sortBy: typeof search.sortBy === "string" ? search.sortBy : "position",
sortOrder: typeof search.sortOrder === "string" ? search.sortOrder : "asc",
});
const sortColumn =
sortBy === "priority"
? slTasks.priority
: sortBy === "dueDate"
? slTasks.dueDate
: sortBy === "createdAt"
? slTasks.createdAt
: sortBy === "title"
? slTasks.title
: slTasks.position;
const orderFn = sortOrder === "desc" ? desc : asc;
const tasks = await db
.select()
.from(slTasks)
.where(and(...conditions))
.orderBy(orderFn(sortColumn));
// Fetch subtasks for all parent tasks
const parentIds = tasks.map((t) => t.id);
const subtasksMap: Record<string, Task[]> = {};
if (parentIds.length > 0) {
const allSubtasks = await db
.select()
.from(slTasks)
.where(
and(
eq(slTasks.userId, userId),
isNull(slTasks.deletedAt)
)
)
.orderBy(asc(slTasks.position));
const parentIdSet = new Set(parentIds);
for (const sub of allSubtasks) {
if (sub.parentId && parentIdSet.has(sub.parentId)) {
if (!subtasksMap[sub.parentId]) subtasksMap[sub.parentId] = [];
subtasksMap[sub.parentId].push(sub as Task);
}
}
}
const subtasksMap = await loadSubtasks(userId, tasks.map((t) => t.id));
const subtaskIds = Object.values(subtasksMap).flat().map((s) => s.id);
const [tagsMap, accountTags] = await Promise.all([
loadTaskTags(userId, [...tasks.map((t) => t.id), ...subtaskIds]),
loadAccountTags(userId),
]);
return (
<TaskList
tasks={tasks as Task[]}
subtasksMap={subtasksMap}
subtasksMap={subtasksMap as Record<string, Task[]>}
tagsMap={tagsMap}
accountTags={accountTags}
listId={listId}
listName={list.name}
/>

View file

@ -1,9 +1,11 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slLists, slTaskTags } from '@/db/schema';
import { eq, and, isNull, asc, desc, inArray, SQL } from 'drizzle-orm';
import { slLists } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
import { rateLimit } from '@/lib/rateLimit';
import { parseTagFilter } from '@/lib/validators';
import { queryListTasks } from '@/lib/taskQueries';
export async function GET(
request: NextRequest,
@ -16,6 +18,15 @@ export async function GET(
const { id: listId } = await params;
const url = request.nextUrl;
const completed = url.searchParams.get('completed');
const priority = url.searchParams.get('priority');
const dueDate = url.searchParams.get('dueDate');
const tagFilter = parseTagFilter(url.searchParams.get('tags'));
if (!tagFilter.ok) {
return NextResponse.json({ error: 'Invalid tags' }, { status: 400 });
}
// Verify list belongs to user
const [list] = await db
.select({ id: slLists.id })
@ -26,63 +37,14 @@ export async function GET(
return NextResponse.json({ error: 'List not found' }, { status: 404 });
}
const url = request.nextUrl;
const completed = url.searchParams.get('completed');
const priority = url.searchParams.get('priority');
const dueDate = url.searchParams.get('dueDate');
const tags = url.searchParams.get('tags');
const sortBy = url.searchParams.get('sortBy') || 'position';
const sortOrder = url.searchParams.get('sortOrder') || 'asc';
const conditions: SQL[] = [
eq(slTasks.listId, listId),
eq(slTasks.userId, auth.userId),
isNull(slTasks.deletedAt),
isNull(slTasks.parentId),
];
if (completed !== null) {
conditions.push(eq(slTasks.completed, completed === 'true'));
}
if (priority !== null) {
conditions.push(eq(slTasks.priority, parseInt(priority, 10)));
}
// Build query
const query = db
.select()
.from(slTasks)
.where(and(...conditions));
// Sort
const sortColumn = sortBy === 'priority' ? slTasks.priority
: sortBy === 'dueDate' ? slTasks.dueDate
: sortBy === 'createdAt' ? slTasks.createdAt
: sortBy === 'title' ? slTasks.title
: slTasks.position;
const orderFn = sortOrder === 'desc' ? desc : asc;
const tasks = await query.orderBy(orderFn(sortColumn));
// Filter by tags if specified (post-query since it's a join table)
if (tags) {
const tagIds = tags.split(',');
const taskTagRows = await db
.select({ taskId: slTaskTags.taskId })
.from(slTaskTags)
.where(inArray(slTaskTags.tagId, tagIds));
const taskIdsWithTags = new Set(taskTagRows.map((r) => r.taskId));
return NextResponse.json(tasks.filter((t) => taskIdsWithTags.has(t.id)));
}
// Filter by dueDate if specified (before/on that date)
if (dueDate) {
const cutoff = new Date(dueDate);
return NextResponse.json(
tasks.filter((t) => t.dueDate && t.dueDate <= cutoff)
);
}
const tasks = await queryListTasks(auth.userId, listId, {
completed: completed !== null ? completed === 'true' : undefined,
priority: priority !== null ? parseInt(priority, 10) : undefined,
dueBefore: dueDate ? new Date(dueDate) : undefined,
tagIds: tagFilter.tagIds,
sortBy: url.searchParams.get('sortBy') || 'position',
sortOrder: url.searchParams.get('sortOrder') || 'asc',
});
return NextResponse.json(tasks);
}

View file

@ -1,10 +1,15 @@
"use client";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { Filter, ArrowUpDown } from "lucide-react";
import { Filter, ArrowUpDown, Tag, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { TagPill } from "@/lib/types";
export function FilterBar() {
interface FilterBarProps {
accountTags?: TagPill[];
}
export function FilterBar({ accountTags = [] }: FilterBarProps) {
const { t } = useTranslation();
const router = useRouter();
const pathname = usePathname();
@ -27,6 +32,11 @@ export function FilterBar() {
const completed = searchParams.get("completed") ?? "";
const sortBy = searchParams.get("sortBy") ?? "position";
const sortOrder = searchParams.get("sortOrder") ?? "asc";
// Tag filter set from the sidebar (one tag at a time, as on mobile).
const tagFilterId = searchParams.get("tags") ?? "";
const tagFilter = accountTags.find((tag) => tag.id === tagFilterId);
// A filter on a tag that no longer exists still shows, so it can be removed.
const tagFilterName = tagFilter?.name ?? t("filter.unknownTag");
const updateParam = (key: string, value: string) => {
const params = new URLSearchParams(searchParams.toString());
@ -80,6 +90,20 @@ export function FilterBar() {
{sortOrder === "asc" ? "↑" : "↓"}
</button>
</div>
{/* Active tag filter */}
{tagFilterId && (
<button
onClick={() => updateParam("tags", "")}
className="flex items-center gap-1.5 px-2 py-1 rounded-full text-xs bg-bleu/10 text-bleu hover:bg-bleu/20"
title={t("filter.clearTag", { name: tagFilterName })}
aria-label={t("filter.clearTag", { name: tagFilterName })}
>
<Tag size={12} style={tagFilter ? { color: tagFilter.color } : undefined} />
{t("filter.tag", { name: tagFilterName })}
<X size={12} />
</button>
)}
</div>
);
}

View file

@ -1,8 +1,8 @@
"use client";
import { useState } from "react";
import { Suspense, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
Inbox,
Plus,
@ -16,6 +16,56 @@ import {
import { useTranslation } from "react-i18next";
import type { List as ListType, Tag as TagType } from "@/lib/types";
// Sidebar tags: a click filters the current view by `?tags=<id>` (one tag at
// a time, as in src/components/FilterMenu.tsx of the app); a second click on
// the active tag removes the filter.
function SidebarTags({ tags, onNavigate }: { tags: TagType[]; onNavigate: () => void }) {
const { t } = useTranslation();
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
const activeTagId = searchParams.get("tags");
const toggleTag = (tagId: string) => {
const params = new URLSearchParams(searchParams.toString());
if (activeTagId === tagId) {
params.delete("tags");
} else {
params.set("tags", tagId);
}
const query = params.toString();
router.push(query ? `${pathname}?${query}` : pathname);
onNavigate();
};
return (
<>
{tags.map((tag) => {
const isActive = activeTagId === tag.id;
const label = isActive
? t("filter.clearTag", { name: tag.name })
: t("sidebar.filterByTag", { name: tag.name });
return (
<button
key={tag.id}
onClick={() => toggleTag(tag.id)}
aria-pressed={isActive}
title={label}
className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg w-full text-left transition-colors ${
isActive
? "bg-bleu/10 text-bleu font-medium"
: "hover:bg-black/5 dark:hover:bg-white/5"
}`}
>
<Tag size={14} style={{ color: tag.color }} className="shrink-0" />
<span className="truncate">{tag.name}</span>
</button>
);
})}
</>
);
}
interface SidebarProps {
lists: ListType[];
tags: TagType[];
@ -122,16 +172,11 @@ export function Sidebar({ lists, tags }: SidebarProps) {
)}
{t("sidebar.tags")}
</button>
{tagsExpanded &&
tags.map((tag) => (
<div
key={tag.id}
className="flex items-center gap-2 px-3 py-1.5 text-sm"
>
<Tag size={14} style={{ color: tag.color }} />
<span>{tag.name}</span>
</div>
))}
{tagsExpanded && (
<Suspense fallback={null}>
<SidebarTags tags={tags} onNavigate={() => setMobileOpen(false)} />
</Suspense>
)}
</div>
</nav>

View file

@ -10,9 +10,10 @@ import {
Repeat,
Check,
Search,
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { Task } from "@/lib/types";
import type { Task, TagPill } from "@/lib/types";
import { TaskForm } from "./TaskForm";
const PRIORITY_COLORS: Record<number, string> = {
@ -31,13 +32,40 @@ function formatDate(dateStr: string | Date | null): string {
});
}
// Tag pill: the tag name on its color, for tasks and subtasks alike.
function TagChip({ tag, onRemove, removeLabel }: { tag: TagPill; onRemove?: () => void; removeLabel?: string }) {
return (
<span
className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[11px] leading-none text-white max-w-[10rem]"
style={{ backgroundColor: tag.color }}
>
<span className="truncate">{tag.name}</span>
{onRemove && (
<button
type="button"
onClick={onRemove}
className="shrink-0 hover:opacity-70"
title={removeLabel}
aria-label={removeLabel}
>
<X size={10} />
</button>
)}
</span>
);
}
interface TaskItemProps {
task: Task;
subtasks?: Task[];
depth?: number;
// Tags of this task and of its subtasks, by task id.
tagsMap?: Record<string, TagPill[]>;
// Live tags of the account, offered in the detail view.
accountTags?: TagPill[];
}
export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
export function TaskItem({ task, subtasks = [], depth = 0, tagsMap = {}, accountTags = [] }: TaskItemProps) {
const { t } = useTranslation();
const router = useRouter();
const [expanded, setExpanded] = useState(false);
@ -52,6 +80,11 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
const [recurrence, setRecurrence] = useState(task.recurrence || "");
const [showSubtaskForm, setShowSubtaskForm] = useState(false);
const [saving, setSaving] = useState(false);
const [tagBusy, setTagBusy] = useState(false);
const taskTags = tagsMap[task.id] ?? [];
const assignedIds = new Set(taskTags.map((tag) => tag.id));
const availableTags = accountTags.filter((tag) => !assignedIds.has(tag.id));
const PRIORITY_LABELS: Record<number, string> = {
0: t("priority.none"),
@ -113,6 +146,33 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
}
};
// Add or remove an existing tag through the task-tag API, then reload.
const addTag = async (tagId: string) => {
if (!tagId || tagBusy) return;
setTagBusy(true);
try {
await fetch(`/api/tasks/${task.id}/tags`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tagIds: [tagId] }),
});
router.refresh();
} finally {
setTagBusy(false);
}
};
const removeTag = async (tagId: string) => {
if (tagBusy) return;
setTagBusy(true);
try {
await fetch(`/api/tasks/${task.id}/tags/${tagId}`, { method: "DELETE" });
router.refresh();
} finally {
setTagBusy(false);
}
};
const deleteTask = async () => {
await fetch(`/api/tasks/${task.id}`, { method: "DELETE" });
router.refresh();
@ -168,6 +228,13 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
</span>
{/* Badges */}
{taskTags.length > 0 && (
<span className="flex flex-wrap gap-1 justify-end max-w-[45%]">
{taskTags.map((tag) => (
<TagChip key={tag.id} tag={tag} />
))}
</span>
)}
{task.dueDate && (
<span className="flex items-center gap-1 text-xs text-foreground/50">
<Calendar size={12} />
@ -274,6 +341,37 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
<span>{t("task.recurrenceLabel", { value: RECURRENCE_LABELS[task.recurrence] || task.recurrence })}</span>
)}
</div>
{/* Tags: remove an assigned tag, add an existing one */}
<div className="flex flex-wrap items-center gap-1.5 text-xs">
<span className="text-foreground/50">{t("tag.label")}</span>
{taskTags.length === 0 && (
<span className="text-foreground/40">{t("tag.none")}</span>
)}
{taskTags.map((tag) => (
<TagChip
key={tag.id}
tag={tag}
onRemove={() => removeTag(tag.id)}
removeLabel={t("tag.remove", { name: tag.name })}
/>
))}
{availableTags.length > 0 && (
<select
value=""
disabled={tagBusy}
onChange={(e) => addTag(e.target.value)}
aria-label={t("tag.add")}
className="bg-transparent border border-border-light dark:border-border-dark rounded px-1.5 py-0.5 text-xs focus:outline-none focus:border-bleu disabled:opacity-50"
>
<option value="">{t("tag.add")}</option>
{availableTags.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
)}
</div>
<div className="flex gap-2 pt-1">
<button
onClick={() => setEditing(true)}
@ -316,7 +414,13 @@ export function TaskItem({ task, subtasks = [], depth = 0 }: TaskItemProps) {
{/* Subtasks — toggled by chevron */}
{expanded && subtasks.map((sub) => (
<TaskItem key={sub.id} task={sub} depth={depth + 1} />
<TaskItem
key={sub.id}
task={sub}
depth={depth + 1}
tagsMap={tagsMap}
accountTags={accountTags}
/>
))}
</div>
);

View file

@ -1,6 +1,6 @@
"use client";
import type { Task } from "@/lib/types";
import type { Task, TagPill } from "@/lib/types";
import { TaskItem } from "./TaskItem";
import { TaskForm } from "./TaskForm";
import { FilterBar } from "./FilterBar";
@ -12,11 +12,15 @@ import { useTranslation } from "react-i18next";
interface TaskListProps {
tasks: Task[];
subtasksMap: Record<string, Task[]>;
// Tags of every task and subtask shown, by task id.
tagsMap: Record<string, TagPill[]>;
// Live tags of the account, for the tag picker and the active filter.
accountTags: TagPill[];
listId: string;
listName: string;
}
export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps) {
export function TaskList({ tasks, subtasksMap, tagsMap, accountTags, listId, listName }: TaskListProps) {
const { t } = useTranslation();
const router = useRouter();
const [refreshing, setRefreshing] = useState(false);
@ -44,7 +48,7 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps
</button>
</div>
<Suspense fallback={null}>
<FilterBar />
<FilterBar accountTags={accountTags} />
</Suspense>
</div>
@ -66,6 +70,8 @@ export function TaskList({ tasks, subtasksMap, listId, listName }: TaskListProps
key={task.id}
task={task}
subtasks={subtasksMap[task.id] || []}
tagsMap={tagsMap}
accountTags={accountTags}
/>
))}
</div>

View file

@ -12,7 +12,8 @@
"lists": "Lists",
"tags": "Tags",
"newList": "New list",
"newListPlaceholder": "List name..."
"newListPlaceholder": "List name...",
"filterByTag": "Filter by {{name}}"
},
"task": {
"add": "Add a task",
@ -32,6 +33,12 @@
"dueDate": "Due: {{value}}",
"recurrenceLabel": "Recurrence: {{value}}"
},
"tag": {
"label": "Tags:",
"none": "None",
"add": "+ Tag",
"remove": "Remove tag {{name}}"
},
"priority": {
"none": "None",
"noneExplicit": "No priority",
@ -49,7 +56,10 @@
"filter": {
"all": "All",
"active": "Active",
"completed": "Completed"
"completed": "Completed",
"tag": "Tag: {{name}}",
"clearTag": "Remove filter {{name}}",
"unknownTag": "not found"
},
"sort": {
"position": "Position",

View file

@ -12,7 +12,8 @@
"lists": "Listes",
"tags": "Étiquettes",
"newList": "Nouvelle liste",
"newListPlaceholder": "Nom de la liste..."
"newListPlaceholder": "Nom de la liste...",
"filterByTag": "Filtrer par {{name}}"
},
"task": {
"add": "Ajouter une tâche",
@ -32,6 +33,12 @@
"dueDate": "Échéance : {{value}}",
"recurrenceLabel": "Récurrence : {{value}}"
},
"tag": {
"label": "Étiquettes :",
"none": "Aucune",
"add": "+ Étiquette",
"remove": "Retirer l'étiquette {{name}}"
},
"priority": {
"none": "Aucune",
"noneExplicit": "Aucune priorité",
@ -49,7 +56,10 @@
"filter": {
"all": "Toutes",
"active": "Actives",
"completed": "Complétées"
"completed": "Complétées",
"tag": "Étiquette : {{name}}",
"clearTag": "Retirer le filtre {{name}}",
"unknownTag": "introuvable"
},
"sort": {
"position": "Position",

View file

@ -0,0 +1,188 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// Task reads of the list page and of GET /api/lists/[id]/tasks (#179), against
// an in-memory Postgres (PGlite) with the companion migrations, as in
// web/src/app/api/sync/route.test.ts. Auth and rate limiting are stubbed.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return { pg: new PGlite() as PGlite, userId: '' };
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => null }));
vi.mock('@/lib/api', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/api')>()),
requireAuth: async () => ({ userId: h.userId }),
}));
vi.mock('@/lib/rateLimit', () => ({ rateLimit: () => null }));
const { loadTaskTags, queryListTasks, loadSubtasks } = await import('./taskQueries');
const { GET } = await import('@/app/api/lists/[id]/tasks/route');
const { NextRequest } = await import('next/server');
beforeAll(async () => {
const dir = path.join(__dirname, '../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
async function exec(sql: string, params: unknown[]) {
await h.pg.query(sql, params);
}
// One account: a list, three tasks (one with a subtask), and tags.
async function seedAccount() {
const a = {
userId: `user-${u()}`, list: u(),
t1: u(), t2: u(), t3: u(), sub: u(),
red: u(), blue: u(), gone: u(),
};
await exec('INSERT INTO sl_lists (id, user_id, name) VALUES ($1, $2, $3)', [a.list, a.userId, 'L']);
for (const [id, title, pos] of [[a.t1, 't1', 0], [a.t2, 't2', 1], [a.t3, 't3', 2]] as const) {
await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, position) VALUES ($1, $2, $3, $4, $5)', [id, a.userId, title, a.list, pos]);
}
await exec('INSERT INTO sl_tasks (id, user_id, title, list_id, parent_id) VALUES ($1, $2, $3, $4, $5)', [a.sub, a.userId, 'sub', a.list, a.t1]);
await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.red, a.userId, 'red', '#E57373']);
await exec('INSERT INTO sl_tags (id, user_id, name, color) VALUES ($1, $2, $3, $4)', [a.blue, a.userId, 'blue', '#4A90A4']);
await exec('INSERT INTO sl_tags (id, user_id, name, deleted_at) VALUES ($1, $2, $3, now())', [a.gone, a.userId, 'gone']);
const links: [string, string][] = [[a.t1, a.red], [a.t1, a.blue], [a.t2, a.blue], [a.t3, a.gone], [a.sub, a.red]];
for (const [taskId, tagId] of links) {
await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, tagId]);
}
return a;
}
// A tag of another account linked to a task of `a`: rows the sync can never
// produce (it checks the tag owner), but the reads must not trust that.
async function foreignTagOn(taskId: string) {
const other = { userId: `user-${u()}`, tag: u() };
await exec('INSERT INTO sl_tags (id, user_id, name) VALUES ($1, $2, $3)', [other.tag, other.userId, 'foreign']);
await exec('INSERT INTO sl_task_tags (task_id, tag_id) VALUES ($1, $2)', [taskId, other.tag]);
return other;
}
async function getTasks(userId: string, listId: string, query: string) {
h.userId = userId;
const req = new NextRequest(`http://localhost/api/lists/${listId}/tasks${query}`);
return GET(req, { params: Promise.resolve({ id: listId }) });
}
describe('loadTaskTags', () => {
it('loads the tags of N tasks in a single query', async () => {
const a = await seedAccount();
const spy = vi.spyOn(h.pg, 'query');
const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3, a.sub]);
expect(spy).toHaveBeenCalledTimes(1);
spy.mockRestore();
expect(map[a.t1].map((t) => t.name)).toEqual(['blue', 'red']);
expect(map[a.t2]).toEqual([{ id: a.blue, name: 'blue', color: '#4A90A4' }]);
expect(map[a.sub].map((t) => t.id)).toEqual([a.red]);
});
it('runs no query for no task', async () => {
const spy = vi.spyOn(h.pg, 'query');
expect(await loadTaskTags('user-x', [])).toEqual({});
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('never returns a deleted tag', async () => {
const a = await seedAccount();
const map = await loadTaskTags(a.userId, [a.t1, a.t2, a.t3]);
expect(map[a.t3]).toBeUndefined();
expect(Object.values(map).flat().some((t) => t.id === a.gone)).toBe(false);
});
it('never returns a tag of another account', async () => {
const a = await seedAccount();
const other = await foreignTagOn(a.t2);
const map = await loadTaskTags(a.userId, [a.t1, a.t2]);
expect(map[a.t2].map((t) => t.id)).toEqual([a.blue]);
// Nor are the tags of `a` returned to the other account.
expect(await loadTaskTags(other.userId, [a.t1, a.t2])).toEqual({ [a.t2]: [{ id: other.tag, name: 'foreign', color: '#4A90A4' }] });
});
});
describe('queryListTasks', () => {
it('filters by a live tag of the account', async () => {
const a = await seedAccount();
expect((await queryListTasks(a.userId, a.list, { tagIds: [a.red] })).map((t) => t.id)).toEqual([a.t1]);
expect((await queryListTasks(a.userId, a.list, { tagIds: [a.blue] })).map((t) => t.id)).toEqual([a.t1, a.t2]);
});
it('matches nothing on a deleted tag', async () => {
const a = await seedAccount();
expect(await queryListTasks(a.userId, a.list, { tagIds: [a.gone] })).toEqual([]);
});
it('returns every top-level task without a tag filter', async () => {
const a = await seedAccount();
expect((await queryListTasks(a.userId, a.list, { tagIds: null })).map((t) => t.id)).toEqual([a.t1, a.t2, a.t3]);
});
});
describe('loadSubtasks', () => {
it('groups the live subtasks of the account by parent', async () => {
const a = await seedAccount();
const map = await loadSubtasks(a.userId, [a.t1, a.t2]);
expect(Object.keys(map)).toEqual([a.t1]);
expect(map[a.t1].map((t) => t.id)).toEqual([a.sub]);
expect(await loadSubtasks(`user-${u()}`, [a.t1])).toEqual({});
});
});
describe('GET /api/lists/[id]/tasks?tags=', () => {
it('filters by a tag of the account', async () => {
const a = await seedAccount();
const res = await getTasks(a.userId, a.list, `?tags=${a.red}`);
expect(res.status).toBe(200);
expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t1]);
});
it('returns an empty list for a tag of another account', async () => {
const a = await seedAccount();
const other = await foreignTagOn(a.t2);
const res = await getTasks(a.userId, a.list, `?tags=${other.tag}`);
expect(res.status).toBe(200);
expect(await res.json()).toEqual([]);
});
it('answers 400 to a malformed id', async () => {
const a = await seedAccount();
const res = await getTasks(a.userId, a.list, '?tags=pas-un-uuid');
expect(res.status).toBe(400);
});
it('answers 400 to 21 ids and 200 to 20', async () => {
const a = await seedAccount();
const ids = (n: number) => Array.from({ length: n }, () => u()).join(',');
expect((await getTasks(a.userId, a.list, `?tags=${ids(21)}`)).status).toBe(400);
expect((await getTasks(a.userId, a.list, `?tags=${ids(20)}`)).status).toBe(200);
});
it('keeps the other filters with a tag filter', async () => {
const a = await seedAccount();
await exec('UPDATE sl_tasks SET completed = true WHERE id = $1', [a.t1]);
const res = await getTasks(a.userId, a.list, `?tags=${a.blue}&completed=false`);
expect((await res.json() as { id: string }[]).map((t) => t.id)).toEqual([a.t2]);
});
it('still answers 404 for a list of another account', async () => {
const a = await seedAccount();
const res = await getTasks(`user-${u()}`, a.list, '');
expect(res.status).toBe(404);
});
});

123
web/src/lib/taskQueries.ts Normal file
View file

@ -0,0 +1,123 @@
// Task reads shared by the list page (web/src/app/(app)/lists/[id]/page.tsx)
// and GET /api/lists/[id]/tasks (#179). Every query is scoped to the account:
// tasks by sl_tasks.user_id, tags by sl_tags.user_id and deleted_at IS NULL.
import { db } from '@/db/client';
import { slTasks, slTags, slTaskTags } from '@/db/schema';
import { eq, and, isNull, asc, desc, inArray, lte, type SQL } from 'drizzle-orm';
import type { TagPill } from './types';
export interface ListTaskFilters {
completed?: boolean;
priority?: number;
// Tasks due on or before this date.
dueBefore?: Date;
// Tasks carrying at least one of these tags (ids already validated).
tagIds?: string[] | null;
sortBy?: string;
sortOrder?: string;
}
export type TaskTagPill = TagPill;
function sortColumn(sortBy: string | undefined) {
switch (sortBy) {
case 'priority': return slTasks.priority;
case 'dueDate': return slTasks.dueDate;
case 'createdAt': return slTasks.createdAt;
case 'title': return slTasks.title;
default: return slTasks.position;
}
}
// Top-level tasks of a list, filtered and sorted. The caller has checked that
// the list belongs to the account.
export async function queryListTasks(userId: string, listId: string, filters: ListTaskFilters = {}) {
const conditions: SQL[] = [
eq(slTasks.listId, listId),
eq(slTasks.userId, userId),
isNull(slTasks.deletedAt),
isNull(slTasks.parentId),
];
if (filters.completed !== undefined) {
conditions.push(eq(slTasks.completed, filters.completed));
}
if (filters.priority !== undefined && Number.isInteger(filters.priority)) {
conditions.push(eq(slTasks.priority, filters.priority));
}
if (filters.dueBefore && !Number.isNaN(filters.dueBefore.getTime())) {
conditions.push(lte(slTasks.dueDate, filters.dueBefore));
}
if (filters.tagIds && filters.tagIds.length > 0) {
// Only a live tag of this account can select a task: an id from another
// account, or a deleted tag, matches nothing.
const tagged = db
.select({ taskId: slTaskTags.taskId })
.from(slTaskTags)
.innerJoin(slTags, eq(slTags.id, slTaskTags.tagId))
.where(and(
inArray(slTaskTags.tagId, filters.tagIds),
eq(slTags.userId, userId),
isNull(slTags.deletedAt),
));
conditions.push(inArray(slTasks.id, tagged));
}
const orderFn = filters.sortOrder === 'desc' ? desc : asc;
return db
.select()
.from(slTasks)
.where(and(...conditions))
.orderBy(orderFn(sortColumn(filters.sortBy)));
}
// Live subtasks of the given parents, grouped by parent id.
export async function loadSubtasks(userId: string, parentIds: string[]) {
const map: Record<string, (typeof slTasks.$inferSelect)[]> = {};
if (parentIds.length === 0) return map;
const rows = await db
.select()
.from(slTasks)
.where(and(
eq(slTasks.userId, userId),
isNull(slTasks.deletedAt),
inArray(slTasks.parentId, parentIds),
))
.orderBy(asc(slTasks.position));
for (const row of rows) {
if (!row.parentId) continue;
(map[row.parentId] ??= []).push(row);
}
return map;
}
// Tags of the given tasks, grouped by task id, in one query. Deleted tags and
// tags of another account never appear.
export async function loadTaskTags(userId: string, taskIds: string[]) {
const map: Record<string, TaskTagPill[]> = {};
if (taskIds.length === 0) return map;
const rows = await db
.select({ taskId: slTaskTags.taskId, id: slTags.id, name: slTags.name, color: slTags.color })
.from(slTaskTags)
.innerJoin(slTags, eq(slTags.id, slTaskTags.tagId))
.where(and(
inArray(slTaskTags.taskId, taskIds),
eq(slTags.userId, userId),
isNull(slTags.deletedAt),
))
.orderBy(asc(slTags.name));
for (const { taskId, ...tag } of rows) {
(map[taskId] ??= []).push(tag);
}
return map;
}
// Live tags of the account, by name (tag picker of a task).
export async function loadAccountTags(userId: string): Promise<TaskTagPill[]> {
return db
.select({ id: slTags.id, name: slTags.name, color: slTags.color })
.from(slTags)
.where(and(eq(slTags.userId, userId), isNull(slTags.deletedAt)))
.orderBy(asc(slTags.name));
}

View file

@ -39,3 +39,10 @@ export interface Tag {
createdAt: Date | string;
deletedAt: Date | string | null;
}
// A tag as shown on a task (pill) and in the tag picker.
export interface TagPill {
id: string;
name: string;
color: string;
}

View file

@ -1,6 +1,6 @@
import { randomUUID as u } from 'node:crypto';
import { describe, it, expect } from 'vitest';
import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS } from './validators';
import { syncPushSchema, reorderSchema, assignTagsSchema, SYNC_MAX_OPERATIONS, tagFilterSchema, parseTagFilter, TAG_FILTER_MAX } from './validators';
// Length bounds checked before the elements (#147).
@ -81,3 +81,41 @@ describe('assignTagsSchema', () => {
expect(assignTagsSchema.safeParse({ tagIds: Array.from({ length: 100 }, () => u()) }).success).toBe(true);
});
});
describe('tagFilterSchema / parseTagFilter (#179)', () => {
it('bounds the filter at 20 tags', () => {
expect(TAG_FILTER_MAX).toBe(20);
});
it('accepts 20 ids and refuses 21 with a single issue', () => {
expect(tagFilterSchema.safeParse(Array.from({ length: 20 }, () => u())).success).toBe(true);
const r = tagFilterSchema.safeParse(Array.from({ length: 21 }, () => u()));
expect(r.success).toBe(false);
expect(r.error!.issues).toHaveLength(1);
expect(r.error!.issues[0].code).toBe('too_big');
});
it('checks the count before the ids: 10000 invalid ids give one issue', () => {
const r = tagFilterSchema.safeParse(Array.from({ length: 10_000 }, () => 'x'));
expect(r.success).toBe(false);
expect(r.error!.issues).toHaveLength(1);
});
it('treats an absent or empty value as no filter', () => {
expect(parseTagFilter(null)).toEqual({ ok: true, tagIds: null });
expect(parseTagFilter(undefined)).toEqual({ ok: true, tagIds: null });
expect(parseTagFilter('')).toEqual({ ok: true, tagIds: null });
});
it('splits comma-separated ids', () => {
const a = u();
const b = u();
expect(parseTagFilter(`${a},${b}`)).toEqual({ ok: true, tagIds: [a, b] });
});
it('refuses a malformed id, an empty element and 21 ids', () => {
expect(parseTagFilter('pas-un-uuid').ok).toBe(false);
expect(parseTagFilter(`${u()},`).ok).toBe(false);
expect(parseTagFilter(Array.from({ length: 21 }, () => u()).join(',')).ok).toBe(false);
});
});

View file

@ -60,6 +60,26 @@ export const assignTagsSchema = z.object({
tagIds: z.array(z.unknown()).min(1).max(100).pipe(z.array(z.string().uuid())),
}).strict();
// Tag filter of GET /api/lists/[id]/tasks and of the list page (`?tags=a,b`).
// Same bound-first pattern: the count is checked before each id is parsed.
export const TAG_FILTER_MAX = 20;
export const tagFilterSchema = z
.array(z.unknown())
.min(1)
.max(TAG_FILTER_MAX)
.pipe(z.array(z.string().uuid()));
// `?tags=` absent or empty: no filter (null). Otherwise the comma-separated
// ids, validated by tagFilterSchema.
export function parseTagFilter(
raw: string | null | undefined,
): { ok: true; tagIds: string[] | null } | { ok: false } {
if (raw === null || raw === undefined || raw === '') return { ok: true, tagIds: null };
const r = tagFilterSchema.safeParse(raw.split(','));
return r.success ? { ok: true, tagIds: r.data } : { ok: false };
}
// Sync
// Maximum operations in one POST /api/sync. The app sends batches of 50