components/linyi/tag-input.tsx
class-variance-authoritylucide-react
"use client"; import * as React from "react";import { cva, type VariantProps } from "class-variance-authority";import { X } from "lucide-react";import { cn } from "@/lib/cn"; export const tagInputVariants = cva( [ "flex w-full flex-wrap items-center gap-1.5 rounded-control border text-fg transition-[border-color,background-color,box-shadow] duration-150", "focus-within:border-accent focus-within:ring-2 focus-within:ring-accent/20", ].join(" "), { variants: { variant: { surface: "border-line-strong bg-surface hover:border-fg/30", well: "border-line-well bg-well hover:border-line-strong focus-within:bg-surface", }, size: { sm: "min-h-control-sm px-2 py-1 text-xs", md: "min-h-control-md px-2.5 py-1.5 text-xs", lg: "min-h-control-lg px-3 py-2 text-sm", }, invalid: { true: "border-danger focus-within:border-danger focus-within:ring-danger/20", false: "", }, disabled: { true: "opacity-45 pointer-events-none", false: "", }, }, defaultVariants: { variant: "surface", size: "md", invalid: false, disabled: false, }, }); export const tagChipVariants = cva( "inline-flex max-w-full items-center gap-1 rounded-badge border px-2 py-0.5 text-[11px] font-medium transition-colors select-none outline-none", { variants: { state: { default: "border-line bg-surface-2 text-fg", active: "border-accent bg-accent-soft text-accent ring-1 ring-accent/25", duplicate: "border-warning-border bg-warning-soft text-warning", }, }, defaultVariants: { state: "default", }, }); export interface TagInputProps extends Omit< React.ComponentPropsWithRef<"input">, "value" | "defaultValue" | "onChange" | "size" >, Omit<VariantProps<typeof tagInputVariants>, "disabled"> { value?: string[]; defaultValue?: string[]; onValueChange?: (tags: string[]) => void; maxTags?: number; allowDuplicates?: boolean; caseSensitive?: boolean; delimiters?: string[]; validateTag?: (tag: string) => boolean; addOnBlur?: boolean; showCount?: boolean; clearable?: boolean; containerClassName?: string;} const DEFAULT_DELIMITERS = [",", ","]; export function TagInput({ value, defaultValue = [], onValueChange, maxTags, allowDuplicates = false, caseSensitive = false, delimiters = DEFAULT_DELIMITERS, validateTag, addOnBlur = false, showCount = false, clearable = true, variant = "surface", size = "md", invalid = false, disabled = false, placeholder = "输入后按回车或逗号添加...", className, containerClassName, ref, onBlur, onKeyDown, onPaste, onCompositionStart, onCompositionEnd, ...props}: TagInputProps) { const isControlled = value !== undefined; const [internalTags, setInternalTags] = React.useState<string[]>(defaultValue); const tags = isControlled ? value : internalTags; const [inputValue, setInputValue] = React.useState(""); const [activeIndex, setActiveIndex] = React.useState<number | null>(null); const [duplicateTag, setDuplicateTag] = React.useState<string | null>(null); const [liveMessage, setLiveMessage] = React.useState(""); const composingRef = React.useRef(false); const inputRef = React.useRef<HTMLInputElement | null>(null); const duplicateTimerRef = React.useRef<number | null>(null); React.useEffect(() => { return () => { if (duplicateTimerRef.current !== null) { window.clearTimeout(duplicateTimerRef.current); } }; }, []); const setMergedRef = React.useCallback( (node: HTMLInputElement | null) => { inputRef.current = node; if (typeof ref === "function") { ref(node); } else if (ref && "current" in ref) { (ref as React.MutableRefObject<HTMLInputElement | null>).current = node; } }, [ref] ); const commitTags = React.useCallback( (next: string[]) => { if (!isControlled) { setInternalTags(next); } onValueChange?.(next); }, [isControlled, onValueChange] ); const flashDuplicate = React.useCallback((tag: string) => { setDuplicateTag(tag); setLiveMessage(`标签“${tag}”已存在`); if (duplicateTimerRef.current !== null) { window.clearTimeout(duplicateTimerRef.current); } duplicateTimerRef.current = window.setTimeout(() => { setDuplicateTag(null); }, 900); }, []); const addCandidates = React.useCallback( (rawItems: string[]) => { const next = [...tags]; let addedCount = 0; for (const raw of rawItems) { const cleaned = raw.trim(); if (!cleaned) continue; if (maxTags !== undefined && next.length >= maxTags) { setLiveMessage(`已达到最大标签数量 ${maxTags}`); break; } if (validateTag && !validateTag(cleaned)) { continue; } const exists = next.some((existing) => caseSensitive ? existing === cleaned : existing.toLowerCase() === cleaned.toLowerCase() ); if (exists && !allowDuplicates) { flashDuplicate(cleaned); continue; } next.push(cleaned); addedCount += 1; } if (addedCount > 0) { commitTags(next); setLiveMessage(`已添加 ${addedCount} 个标签,当前共 ${next.length} 个`); } setActiveIndex(null); }, [ tags, maxTags, validateTag, caseSensitive, allowDuplicates, flashDuplicate, commitTags, ] ); const removeAt = React.useCallback( (index: number) => { if (disabled) return; const target = tags[index]; if (target === undefined) return; const next = tags.filter((_, i) => i !== index); commitTags(next); setLiveMessage(`已移除标签“${target}”`); if (activeIndex !== null) { if (next.length === 0) { setActiveIndex(null); } else { setActiveIndex(Math.min(index, next.length - 1)); } } inputRef.current?.focus(); }, [disabled, tags, commitTags, activeIndex] ); const splitByDelimiters = React.useCallback( (text: string): string[] => { if (delimiters.length === 0) return [text]; const escaped = delimiters .map((d) => d.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) .join("|"); return text.split(new RegExp(escaped, "g")); }, [delimiters] ); const atLimit = maxTags !== undefined && tags.length >= maxTags; const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) => { const val = e.target.value; setActiveIndex(null); if ( !composingRef.current && delimiters.some((d) => d.length > 0 && val.includes(d)) ) { const parts = splitByDelimiters(val); const tail = parts.pop() ?? ""; addCandidates(parts); setInputValue(tail); return; } setInputValue(val); }; const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => { onKeyDown?.(e); if (e.defaultPrevented) return; const native = e.nativeEvent as KeyboardEvent; const isIme = composingRef.current || native.isComposing || e.keyCode === 229; // 中文输入法组合输入态按回车或逗号时不误提交 if (isIme) return; if (e.key === "Enter" || delimiters.includes(e.key)) { if (inputValue.trim()) { e.preventDefault(); addCandidates(splitByDelimiters(inputValue)); setInputValue(""); } else if (e.key === "Enter") { e.preventDefault(); } return; } if (e.key === "Backspace" && inputValue === "") { if (tags.length === 0) return; e.preventDefault(); if (activeIndex !== null) { removeAt(activeIndex); } else { removeAt(tags.length - 1); } return; } if (e.key === "Delete" && activeIndex !== null) { e.preventDefault(); removeAt(activeIndex); return; } if (e.key === "ArrowLeft" && inputValue === "" && tags.length > 0) { e.preventDefault(); setActiveIndex((prev) => prev === null ? tags.length - 1 : Math.max(0, prev - 1) ); return; } if (e.key === "ArrowRight" && activeIndex !== null) { e.preventDefault(); setActiveIndex((prev) => { if (prev === null) return null; return prev >= tags.length - 1 ? null : prev + 1; }); return; } if (e.key === "Escape" && activeIndex !== null) { setActiveIndex(null); } }; const handlePaste: React.ClipboardEventHandler<HTMLInputElement> = (e) => { onPaste?.(e); if (e.defaultPrevented) return; const pasted = e.clipboardData.getData("text"); if ( pasted && (delimiters.some((d) => pasted.includes(d)) || pasted.includes("\n")) ) { e.preventDefault(); const normalized = pasted.replace(/\r?\n/g, delimiters[0] ?? ","); addCandidates(splitByDelimiters(normalized)); } }; const handleBlur: React.FocusEventHandler<HTMLInputElement> = (e) => { setActiveIndex(null); if (addOnBlur && inputValue.trim()) { addCandidates(splitByDelimiters(inputValue)); setInputValue(""); } onBlur?.(e); }; const activeDescendantId = activeIndex !== null ? `tag-item-${activeIndex}` : undefined; return ( <div className={cn("w-full", containerClassName)}> <div role="group" aria-label="标签列表输入区" onClick={() => inputRef.current?.focus()} className={cn( tagInputVariants({ variant, size, invalid, disabled }), "cursor-text" )} > {tags.map((tag, idx) => { const isDup = duplicateTag !== null && (caseSensitive ? tag === duplicateTag : tag.toLowerCase() === duplicateTag.toLowerCase()); const state = isDup ? "duplicate" : activeIndex === idx ? "active" : "default"; return ( <span key={`${tag}-${idx}`} id={`tag-item-${idx}`} className={cn(tagChipVariants({ state }))} > <span className="truncate max-w-[160px]">{tag}</span> <button type="button" tabIndex={-1} disabled={disabled} onClick={(ev) => { ev.stopPropagation(); removeAt(idx); }} aria-label={`移除标签 ${tag}`} className="inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded-full text-fg-muted transition-colors cursor-pointer hover:bg-well hover:text-fg" > <X className="h-2.5 w-2.5" aria-hidden="true" /> </button> </span> ); })} <input ref={setMergedRef} type="text" value={inputValue} disabled={disabled || atLimit} placeholder={ atLimit ? `已达上限(${maxTags} 项)` : tags.length === 0 ? placeholder : "继续输入..." } aria-invalid={invalid || undefined} aria-activedescendant={activeDescendantId} onChange={handleInputChange} onKeyDown={handleKeyDown} onPaste={handlePaste} onBlur={handleBlur} onCompositionStart={(e) => { composingRef.current = true; onCompositionStart?.(e); }} onCompositionEnd={(e) => { composingRef.current = false; onCompositionEnd?.(e); }} className={cn( "min-w-[84px] flex-1 bg-transparent py-0.5 text-inherit text-fg placeholder:text-fg-muted outline-none disabled:cursor-not-allowed", className )} {...props} /> {clearable && tags.length > 0 && !disabled && ( <button type="button" onClick={(ev) => { ev.stopPropagation(); commitTags([]); setInputValue(""); setActiveIndex(null); setLiveMessage("已清空全部标签"); inputRef.current?.focus(); }} aria-label="清空全部标签" className="ml-auto inline-flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-[5px] text-fg-muted transition-colors cursor-pointer hover:bg-well hover:text-fg" > <X className="h-3 w-3" aria-hidden="true" /> </button> )} </div> {(showCount || maxTags !== undefined) && ( <div className="mt-1.5 flex items-center justify-between gap-2 text-[11px] text-fg-muted"> <span>按回车或逗号分词,退格键删除末项</span> <span className="font-mono-num"> {tags.length} {maxTags !== undefined ? ` / ${maxTags}` : ""} </span> </div> )} <span className="sr-only" aria-live="polite"> {liveMessage} </span> </div> );}