feat(web): create, rename, recolor and delete tags in the companion

The sidebar's Tags section gets a "Manage tags" mode, on par with the
app's Settings: create a tag (name + color from the app palette),
rename it, change its color, delete it after a confirmation. A deleted
tag leaves the sidebar at once; when it was the active filter, ?tags=
leaves the URL. router.refresh() reloads the server data so the task
detail view offers new tags without a reload.

The logic (palette, name check, list after deletion, URL after the
active filter's tag is deleted) lives in the pure helper
web/src/lib/tagEditing.ts, covered by vitest; the JSX is not tested.
No API route and no dependency change.

Refs #182
Refs #168

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-02 21:43:49 -05:00
commit 83cf32a561
6 changed files with 468 additions and 3 deletions

View file

@ -12,9 +12,12 @@ import {
ChevronDown,
ChevronRight,
LogOut,
Settings2,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { List as ListType, Tag as TagType } from "@/lib/types";
import { removeTagFromList } from "@/lib/tagEditing";
import { TagManager } from "./TagManager";
// 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
@ -79,6 +82,15 @@ export function Sidebar({ lists, tags }: SidebarProps) {
const [showNewList, setShowNewList] = useState(false);
const [newListName, setNewListName] = useState("");
const [tagsExpanded, setTagsExpanded] = useState(false);
const [managingTags, setManagingTags] = useState(false);
// Tags shown in the sidebar: the server's, minus a tag just deleted until
// router.refresh() brings the new list (#182). Reset when the props change.
const [serverTags, setServerTags] = useState(tags);
const [shownTags, setShownTags] = useState(tags);
if (tags !== serverTags) {
setServerTags(tags);
setShownTags(tags);
}
const handleCreateList = async () => {
const name = newListName.trim();
@ -174,7 +186,24 @@ export function Sidebar({ lists, tags }: SidebarProps) {
</button>
{tagsExpanded && (
<Suspense fallback={null}>
<SidebarTags tags={tags} onNavigate={() => setMobileOpen(false)} />
{managingTags ? (
<TagManager
tags={shownTags}
onDeleted={(id) => setShownTags((cur) => removeTagFromList(cur, id))}
onClose={() => setManagingTags(false)}
/>
) : (
<>
<SidebarTags tags={shownTags} onNavigate={() => setMobileOpen(false)} />
<button
onClick={() => setManagingTags(true)}
className="flex items-center gap-2 px-3 py-1.5 text-sm text-foreground/60 hover:text-foreground transition-colors w-full"
>
<Settings2 size={14} />
{t("tag.manage")}
</button>
</>
)}
</Suspense>
)}
</div>

View file

@ -0,0 +1,259 @@
"use client";
import { useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Check, Pencil, Plus, Trash2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { Tag as TagType } from "@/lib/types";
import {
TAG_COLORS,
DEFAULT_TAG_COLOR,
validateTagName,
urlAfterTagDelete,
} from "@/lib/tagEditing";
// Tag management of the companion (#182), as in the app's Settings
// (app/(tabs)/settings.tsx): create, rename, recolor, delete with a
// confirmation. Logic lives in web/src/lib/tagEditing.ts (tested); this JSX
// is not covered by tests.
type Editing = { mode: "new" } | { mode: "edit"; id: string } | null;
function TagForm({
initialName,
initialColor,
onSubmit,
onCancel,
}: {
initialName: string;
initialColor: string;
onSubmit: (name: string, color: string) => Promise<boolean>;
onCancel: () => void;
}) {
const { t } = useTranslation();
const [name, setName] = useState(initialName);
const [color, setColor] = useState(initialColor);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async () => {
if (busy) return;
const check = validateTagName(name);
if (!check.ok) {
setError(t(check.reason === "empty" ? "tag.nameRequired" : "tag.nameTooLong"));
return;
}
setBusy(true);
setError(null);
let ok = false;
try {
ok = await onSubmit(check.name, color);
} catch {
ok = false;
}
setBusy(false);
if (!ok) setError(t("tag.saveError"));
};
return (
<div className="px-3 py-2 space-y-2">
<input
autoFocus
value={name}
onChange={(e) => {
setName(e.target.value);
setError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter") submit();
if (e.key === "Escape") onCancel();
}}
placeholder={t("tag.namePlaceholder")}
aria-label={t("tag.name")}
aria-invalid={error ? true : undefined}
className="w-full px-2 py-1 text-sm border border-border-light dark:border-border-dark rounded bg-transparent focus:outline-none focus:border-bleu"
/>
<div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={t("tag.color")}>
{TAG_COLORS.map((c) => (
<button
key={c}
type="button"
role="radio"
aria-checked={color === c}
aria-label={t("tag.colorOption", { color: c })}
title={c}
onClick={() => setColor(c)}
className={`w-6 h-6 rounded-full flex items-center justify-center ${
color === c ? "ring-2 ring-offset-1 ring-foreground/60" : ""
}`}
style={{ backgroundColor: c }}
>
{color === c && <Check size={12} className="text-white" />}
</button>
))}
</div>
{error && (
<p role="alert" className="text-xs text-rouge">
{error}
</p>
)}
<div className="flex gap-2">
<button
type="button"
onClick={submit}
disabled={busy}
className="px-2 py-1 text-xs rounded bg-bleu text-white disabled:opacity-50"
>
{t("tag.save")}
</button>
<button
type="button"
onClick={onCancel}
className="px-2 py-1 text-xs rounded text-foreground/60 hover:text-foreground"
>
{t("tag.cancel")}
</button>
</div>
</div>
);
}
export function TagManager({
tags,
onDeleted,
onClose,
}: {
tags: TagType[];
// Called once the API has deleted the tag, so the sidebar drops it at once.
onDeleted: (tagId: string) => void;
onClose: () => void;
}) {
const { t } = useTranslation();
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const [editing, setEditing] = useState<Editing>(null);
const [deleteError, setDeleteError] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const createTag = async (name: string, color: string) => {
const res = await fetch("/api/tags", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, color }),
});
if (!res.ok) return false;
setEditing(null);
// Reloads the server data: the task detail view offers the new tag.
router.refresh();
return true;
};
const updateTag = async (id: string, name: string, color: string) => {
const res = await fetch(`/api/tags/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, color }),
});
if (!res.ok) return false;
setEditing(null);
router.refresh();
return true;
};
const deleteTag = async (tag: TagType) => {
if (busyId) return;
if (!window.confirm(t("tag.deleteConfirm", { name: tag.name }))) return;
setBusyId(tag.id);
setDeleteError(null);
try {
const res = await fetch(`/api/tags/${tag.id}`, { method: "DELETE" });
if (!res.ok) {
setDeleteError(t("tag.deleteError"));
return;
}
onDeleted(tag.id);
if (editing?.mode === "edit" && editing.id === tag.id) setEditing(null);
const next = urlAfterTagDelete(pathname, searchParams.toString(), tag.id);
if (next !== null) router.replace(next);
router.refresh();
} catch {
setDeleteError(t("tag.deleteError"));
} finally {
setBusyId(null);
}
};
return (
<div className="space-y-1">
{tags.length === 0 && editing?.mode !== "new" && (
<p className="px-3 py-1 text-sm text-foreground/40">{t("tag.noTags")}</p>
)}
{tags.map((tag) =>
editing?.mode === "edit" && editing.id === tag.id ? (
<TagForm
key={tag.id}
initialName={tag.name}
initialColor={tag.color}
onSubmit={(name, color) => updateTag(tag.id, name, color)}
onCancel={() => setEditing(null)}
/>
) : (
<div key={tag.id} className="flex items-center gap-2 px-3 py-1.5 text-sm">
<span className="w-3 h-3 rounded-full shrink-0" style={{ backgroundColor: tag.color }} />
<span className="truncate flex-1">{tag.name}</span>
<button
type="button"
onClick={() => setEditing({ mode: "edit", id: tag.id })}
aria-label={t("tag.edit", { name: tag.name })}
title={t("tag.edit", { name: tag.name })}
className="p-1 text-foreground/50 hover:text-foreground"
>
<Pencil size={14} />
</button>
<button
type="button"
onClick={() => deleteTag(tag)}
disabled={busyId !== null}
aria-label={t("tag.delete", { name: tag.name })}
title={t("tag.delete", { name: tag.name })}
className="p-1 text-foreground/50 hover:text-rouge disabled:opacity-50"
>
<Trash2 size={14} />
</button>
</div>
),
)}
{deleteError && (
<p role="alert" className="px-3 text-xs text-rouge">
{deleteError}
</p>
)}
{editing?.mode === "new" ? (
<TagForm
initialName=""
initialColor={DEFAULT_TAG_COLOR}
onSubmit={createTag}
onCancel={() => setEditing(null)}
/>
) : (
<button
type="button"
onClick={() => setEditing({ mode: "new" })}
className="flex items-center gap-2 px-3 py-1.5 text-sm text-foreground/60 hover:text-foreground transition-colors w-full"
>
<Plus size={14} />
{t("tag.newTag")}
</button>
)}
<button
type="button"
onClick={onClose}
className="flex items-center gap-2 px-3 py-1.5 text-xs text-foreground/60 hover:text-foreground transition-colors w-full"
>
<X size={12} />
{t("tag.doneManaging")}
</button>
</div>
);
}

View file

@ -37,7 +37,24 @@
"label": "Tags:",
"none": "None",
"add": "+ Tag",
"remove": "Remove tag {{name}}"
"remove": "Remove tag {{name}}",
"manage": "Manage tags",
"doneManaging": "Done",
"newTag": "New tag",
"noTags": "No tags",
"name": "Tag name",
"namePlaceholder": "Tag name...",
"nameRequired": "The name cannot be empty.",
"nameTooLong": "The name cannot exceed 100 characters.",
"color": "Tag color",
"colorOption": "Color {{color}}",
"save": "Save",
"cancel": "Cancel",
"edit": "Edit tag {{name}}",
"delete": "Delete tag {{name}}",
"deleteConfirm": "Are you sure you want to delete the tag \"{{name}}\"? It will be removed from all your tasks.",
"saveError": "The tag could not be saved.",
"deleteError": "The tag could not be deleted."
},
"priority": {
"none": "None",

View file

@ -37,7 +37,24 @@
"label": "Étiquettes :",
"none": "Aucune",
"add": "+ Étiquette",
"remove": "Retirer l'étiquette {{name}}"
"remove": "Retirer l'étiquette {{name}}",
"manage": "Gérer les étiquettes",
"doneManaging": "Terminer",
"newTag": "Nouvelle étiquette",
"noTags": "Aucune étiquette",
"name": "Nom de l'étiquette",
"namePlaceholder": "Nom de l'étiquette...",
"nameRequired": "Le nom ne peut pas être vide.",
"nameTooLong": "Le nom ne peut pas dépasser 100 caractères.",
"color": "Couleur de l'étiquette",
"colorOption": "Couleur {{color}}",
"save": "Enregistrer",
"cancel": "Annuler",
"edit": "Modifier l'étiquette {{name}}",
"delete": "Supprimer l'étiquette {{name}}",
"deleteConfirm": "Voulez-vous vraiment supprimer l'étiquette « {{name}} » ? Elle sera retirée de toutes vos tâches.",
"saveError": "L'étiquette n'a pas pu être enregistrée.",
"deleteError": "L'étiquette n'a pas pu être supprimée."
},
"priority": {
"none": "Aucune",

View file

@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import {
TAG_COLORS,
DEFAULT_TAG_COLOR,
TAG_NAME_MAX,
validateTagName,
removeTagFromList,
urlAfterTagDelete,
} from './tagEditing';
const A = '11111111-1111-4111-8111-111111111111';
const B = '22222222-2222-4222-8222-222222222222';
describe('TAG_COLORS', () => {
it('is the app palette, the first color by default', () => {
expect([...TAG_COLORS]).toEqual(['#4A90A4', '#C17767', '#8BA889', '#D4A574', '#7B68EE', '#E57373', '#4DB6AC']);
expect(DEFAULT_TAG_COLOR).toBe('#4A90A4');
});
});
describe('validateTagName', () => {
it('refuses an empty name', () => {
expect(validateTagName('')).toEqual({ ok: false, reason: 'empty' });
});
it('refuses a name made of spaces', () => {
expect(validateTagName(' ')).toEqual({ ok: false, reason: 'empty' });
expect(validateTagName('\t \n')).toEqual({ ok: false, reason: 'empty' });
});
it('accepts and trims a real name', () => {
expect(validateTagName(' Courses ')).toEqual({ ok: true, name: 'Courses' });
expect(validateTagName('x')).toEqual({ ok: true, name: 'x' });
});
it('accepts the API bound and refuses one character more', () => {
expect(validateTagName('a'.repeat(TAG_NAME_MAX))).toEqual({ ok: true, name: 'a'.repeat(TAG_NAME_MAX) });
expect(validateTagName('a'.repeat(TAG_NAME_MAX + 1))).toEqual({ ok: false, reason: 'tooLong' });
// Surrounding spaces do not count against the bound.
expect(validateTagName(` ${'a'.repeat(TAG_NAME_MAX)} `).ok).toBe(true);
});
});
describe('removeTagFromList', () => {
const tags = [
{ id: A, name: 'Alpha', color: '#4A90A4' },
{ id: B, name: 'Beta', color: '#C17767' },
];
it('removes the deleted tag and keeps the order of the others', () => {
expect(removeTagFromList(tags, A)).toEqual([tags[1]]);
expect(removeTagFromList(tags, B)).toEqual([tags[0]]);
});
it('leaves the list as it was for an unknown id, without mutating it', () => {
expect(removeTagFromList(tags, 'other')).toEqual(tags);
removeTagFromList(tags, A);
expect(tags).toHaveLength(2);
});
});
describe('urlAfterTagDelete', () => {
it('drops ?tags= when the deleted tag is the active filter', () => {
expect(urlAfterTagDelete('/lists/x', `?tags=${A}`, A)).toBe('/lists/x');
expect(urlAfterTagDelete('/lists/x', `tags=${A}`, A)).toBe('/lists/x');
});
it('keeps the other parameters', () => {
expect(urlAfterTagDelete('/lists/x', `?completed=false&tags=${A}&sortBy=title`, A)).toBe(
'/lists/x?completed=false&sortBy=title',
);
});
it('keeps the other tags of a multi-tag filter', () => {
expect(urlAfterTagDelete('/lists/x', `?tags=${A},${B}`, A)).toBe(`/lists/x?tags=${encodeURIComponent(B)}`);
});
it('leaves the URL unchanged when another tag is the filter', () => {
expect(urlAfterTagDelete('/lists/x', `?tags=${B}`, A)).toBeNull();
});
it('leaves the URL unchanged without a tag filter', () => {
expect(urlAfterTagDelete('/lists/x', '', A)).toBeNull();
expect(urlAfterTagDelete('/lists/x', '?completed=true', A)).toBeNull();
});
});

57
web/src/lib/tagEditing.ts Normal file
View file

@ -0,0 +1,57 @@
// Pure helpers of the companion tag manager (#182), kept out of the JSX so
// vitest covers them without a DOM: the palette, the name check, the list
// after a deletion and the URL after the active filter's tag is deleted.
// Same palette as the app's tag modal (app/(tabs)/settings.tsx, TAG_COLORS).
export const TAG_COLORS = [
'#4A90A4',
'#C17767',
'#8BA889',
'#D4A574',
'#7B68EE',
'#E57373',
'#4DB6AC',
] as const;
export const DEFAULT_TAG_COLOR = TAG_COLORS[0];
// Same bound as createTagSchema / updateTagSchema in validators.ts.
export const TAG_NAME_MAX = 100;
export type TagNameCheck =
| { ok: true; name: string }
| { ok: false; reason: 'empty' | 'tooLong' };
// The name sent to the API: trimmed, neither empty nor made of spaces, at
// most TAG_NAME_MAX characters once trimmed.
export function validateTagName(raw: string): TagNameCheck {
const name = raw.trim();
if (name.length === 0) return { ok: false, reason: 'empty' };
if (name.length > TAG_NAME_MAX) return { ok: false, reason: 'tooLong' };
return { ok: true, name };
}
// The tag list once `tagId` is deleted; the other tags keep their order.
export function removeTagFromList<T extends { id: string }>(tags: readonly T[], tagId: string): T[] {
return tags.filter((tag) => tag.id !== tagId);
}
// The URL to show once `tagId` is deleted. `search` is the current query
// string, with or without its leading `?`. When the deleted tag is in the
// `?tags=` filter, it leaves it, and `tags` goes away once empty; the other
// parameters stay. Returns null when the URL does not change.
export function urlAfterTagDelete(pathname: string, search: string, tagId: string): string | null {
const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
const raw = params.get('tags');
if (raw === null) return null;
const ids = raw.split(',');
if (!ids.includes(tagId)) return null;
const rest = ids.filter((id) => id !== tagId && id !== '');
if (rest.length > 0) {
params.set('tags', rest.join(','));
} else {
params.delete('tags');
}
const query = params.toString();
return query ? `${pathname}?${query}` : pathname;
}