From 83cf32a5618bfe76917f4b199aa2639e1feb0c33 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:43:49 -0500 Subject: [PATCH] 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 --- web/src/components/Sidebar.tsx | 31 +++- web/src/components/TagManager.tsx | 259 ++++++++++++++++++++++++++++++ web/src/i18n/en.json | 19 ++- web/src/i18n/fr.json | 19 ++- web/src/lib/tagEditing.test.ts | 86 ++++++++++ web/src/lib/tagEditing.ts | 57 +++++++ 6 files changed, 468 insertions(+), 3 deletions(-) create mode 100644 web/src/components/TagManager.tsx create mode 100644 web/src/lib/tagEditing.test.ts create mode 100644 web/src/lib/tagEditing.ts diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsx index fbf1aa8..c31f649 100644 --- a/web/src/components/Sidebar.tsx +++ b/web/src/components/Sidebar.tsx @@ -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=` (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) { {tagsExpanded && ( - setMobileOpen(false)} /> + {managingTags ? ( + setShownTags((cur) => removeTagFromList(cur, id))} + onClose={() => setManagingTags(false)} + /> + ) : ( + <> + setMobileOpen(false)} /> + + + )} )} diff --git a/web/src/components/TagManager.tsx b/web/src/components/TagManager.tsx new file mode 100644 index 0000000..e66faad --- /dev/null +++ b/web/src/components/TagManager.tsx @@ -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; + onCancel: () => void; +}) { + const { t } = useTranslation(); + const [name, setName] = useState(initialName); + const [color, setColor] = useState(initialColor); + const [error, setError] = useState(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 ( +
+ { + 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" + /> +
+ {TAG_COLORS.map((c) => ( + + ))} +
+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+ ); +} + +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(null); + const [deleteError, setDeleteError] = useState(null); + const [busyId, setBusyId] = useState(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 ( +
+ {tags.length === 0 && editing?.mode !== "new" && ( +

{t("tag.noTags")}

+ )} + {tags.map((tag) => + editing?.mode === "edit" && editing.id === tag.id ? ( + updateTag(tag.id, name, color)} + onCancel={() => setEditing(null)} + /> + ) : ( +
+ + {tag.name} + + +
+ ), + )} + {deleteError && ( +

+ {deleteError} +

+ )} + {editing?.mode === "new" ? ( + setEditing(null)} + /> + ) : ( + + )} + +
+ ); +} diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index 2fb5887..3ae55e7 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -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", diff --git a/web/src/i18n/fr.json b/web/src/i18n/fr.json index 6cfebff..d3adf1a 100644 --- a/web/src/i18n/fr.json +++ b/web/src/i18n/fr.json @@ -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", diff --git a/web/src/lib/tagEditing.test.ts b/web/src/lib/tagEditing.test.ts new file mode 100644 index 0000000..6272afa --- /dev/null +++ b/web/src/lib/tagEditing.test.ts @@ -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(); + }); +}); diff --git a/web/src/lib/tagEditing.ts b/web/src/lib/tagEditing.ts new file mode 100644 index 0000000..92943bd --- /dev/null +++ b/web/src/lib/tagEditing.ts @@ -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(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; +}