"use client"; import { ChevronDownIcon, PlusIcon, SettingsIcon } from "lucide-react"; import Link from "next/link"; import { useEffect, useRef, useState } from "react"; import { TagDot } from "@/components/tag-badge"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Input } from "@/components/ui/input"; import type { Tag } from "@/lib/tags"; import { cn } from "@/lib/utils"; /** * "Add tag" dropdown: the first entry creates a new tag (inline name field), below it the existing * tags that aren't picked yet. Calls `onPick` with the tag name. */ export function TagPicker({ exclude, onPick, disabled, className, }: { /** Tag names already applied (case-insensitive), hidden from the list. */ exclude: string[]; /** Picked tag name; `tag` is set when an existing tag was chosen. */ onPick: (name: string, tag?: Tag) => void | Promise; disabled?: boolean; className?: string; }) { const [known, setKnown] = useState([]); const [creating, setCreating] = useState(false); const [name, setName] = useState(""); const inputRef = useRef(null); const cancelled = useRef(false); function load() { fetch("/api/tags") .then((r) => (r.ok ? r.json() : [])) .then((all: Tag[]) => setKnown(all)) .catch(() => {}); } useEffect(load, []); useEffect(() => { if (!creating) return; cancelled.current = false; inputRef.current?.focus(); }, [creating]); function finishCreating() { setCreating(false); setName(""); } async function submit() { const value = name.trim(); const existing = known.find((t) => t.name.toLowerCase() === value.toLowerCase()); if (value) await onPick(existing?.name ?? value, existing); finishCreating(); } if (creating) { return (
{ e.preventDefault(); inputRef.current?.blur(); // blur submits, so Enter and click-away can't add twice }} > setName(e.target.value)} onBlur={() => (name.trim() && !cancelled.current ? void submit() : finishCreating())} onKeyDown={(e) => { if (e.key !== "Escape") return; cancelled.current = true; inputRef.current?.blur(); }} placeholder="New tag name…" disabled={disabled} maxLength={40} className="h-6 w-40 text-xs" aria-label="New tag name" />
); } const hidden = new Set(exclude.map((n) => n.toLowerCase())); const available = known.filter((t) => !hidden.has(t.name.toLowerCase())); return ( open && load()}> Add tag setCreating(true)}> Create new tag… {available.length > 0 && } {available.map((t) => ( void onPick(t.name, t)}> {t.name} ))} } className="text-muted-foreground"> Manage tags… ); }