feat: implement TagSelector component for improved tag management across dashboard features

- Added TagSelector component to streamline tag selection in various components.
- Refactored existing tag handling in DashboardConversationsPage, ConversationTagPicker, EditDialog, and TicketsPage to utilize the new TagSelector.
- Removed redundant tag handling functions and optimized state management for tags.
- Updated tests to ensure proper functionality of the new tag handling logic.
This commit is contained in:
mlogclub
2026-05-30 11:23:05 +08:00
parent d2da9de641
commit 8398cd6f91
9 changed files with 653 additions and 354 deletions
@@ -23,6 +23,7 @@ import {
OptionCombobox,
type ComboboxOption,
} from "@/components/option-combobox"
import { TagSelector } from "@/components/tag-selector"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
@@ -112,24 +113,6 @@ function getStatusOptions(
]
}
function buildTagOptions(
nodes: TagTree[],
parentPath = ""
): ComboboxOption[] {
const result: ComboboxOption[] = []
nodes.forEach((item) => {
const currentPath = parentPath ? `${parentPath}/${item.name}` : item.name
result.push({
value: String(item.id),
label: currentPath,
})
if (item.children.length > 0) {
result.push(...buildTagOptions(item.children, currentPath))
}
})
return result
}
export default function DashboardConversationsPage() {
const t = useI18n()
const statusOptions = useMemo(() => getStatusOptions(t), [t])
@@ -145,9 +128,7 @@ export default function DashboardConversationsPage() {
const [agentTeamFilter, setAgentTeamFilter] = useState("0")
const [page, setPage] = useState(1)
const [limit, setLimit] = useState(20)
const [tagOptions, setTagOptions] = useState<ComboboxOption[]>([
{ value: "0", label: t("conversationMonitor.allTags") },
])
const [tags, setTags] = useState<TagTree[]>([])
const [assigneeOptions, setAssigneeOptions] = useState<ComboboxOption[]>([
{ value: "0", label: t("conversationMonitor.allAssignees") },
])
@@ -213,10 +194,7 @@ export default function DashboardConversationsPage() {
fetchAgentTeamsAll(),
])
if (!cancelled) {
setTagOptions([
{ value: "0", label: t("conversationMonitor.allTags") },
...buildTagOptions(tagData),
])
setTags(Array.isArray(tagData) ? tagData : [])
setAssigneeOptions([
{ value: "0", label: t("conversationMonitor.allAssignees") },
...assigneeData.map((item: AdminAgentProfile) => ({
@@ -675,13 +653,15 @@ export default function DashboardConversationsPage() {
/>
</div>
<div className="w-full sm:w-64">
<OptionCombobox
value={tagFilterInput}
options={tagOptions}
<TagSelector
mode="single"
value={Number(tagFilterInput)}
onChange={(value) => setTagFilterInput(String(value))}
tags={tags}
placeholder={t("conversationMonitor.selectTag")}
searchPlaceholder={t("conversationMonitor.searchTagPath")}
emptyText={t("conversationMonitor.emptyTags")}
onChange={setTagFilterInput}
rootOption={{ value: 0, label: t("conversationMonitor.allTags") }}
/>
</div>
<div className="w-full sm:w-56">
@@ -1,24 +1,9 @@
"use client"
import { CheckIcon, Loader2Icon, TagIcon } from "lucide-react"
import { useMemo, useState } from "react"
import { toast } from "sonner"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { TagBadges, TagSelector } from "@/components/tag-selector"
import {
addConversationTag,
removeConversationTag,
@@ -27,39 +12,6 @@ import {
} from "@/lib/api/agent"
import { type TagTree } from "@/lib/api/admin"
import { useI18n } from "@/i18n/provider"
import { cn } from "@/lib/utils"
type TagNode = TagTree & {
depth: number
}
function flattenTagTree(nodes: TagTree[], depth = 0): TagNode[] {
const result: TagNode[] = []
nodes.forEach((item) => {
result.push({ ...item, depth })
if (item.children.length > 0) {
result.push(...flattenTagTree(item.children, depth + 1))
}
})
return result
}
function buildTagPathMap(
nodes: TagTree[],
parentPath = ""
): Map<number, string> {
const result = new Map<number, string>()
nodes.forEach((item) => {
const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name
result.set(item.id, currentPath)
if (item.children.length > 0) {
buildTagPathMap(item.children, currentPath).forEach((value, key) => {
result.set(key, value)
})
}
})
return result
}
type ConversationTagPickerProps = {
conversation: AgentConversation
@@ -77,34 +29,45 @@ export function ConversationTagPicker({
const t = useI18n()
const [pendingTagId, setPendingTagId] = useState<number | null>(null)
const flattenedTags = useMemo(() => flattenTagTree(availableTags), [availableTags])
const selectedTagIds = useMemo(
() => new Set((conversation.tags ?? []).map((item) => item.id)),
const selectedValues = useMemo(
() => (conversation.tags ?? []).map((item) => item.id),
[conversation.tags]
)
const selectedTagIds = useMemo(
() => new Set(selectedValues),
[selectedValues]
)
async function handleToggle(tag: TagNode) {
async function handleChange(nextTagIds: number[]) {
if (pendingTagId !== null) {
return
}
const exists = selectedTagIds.has(tag.id)
const tagId =
nextTagIds.find((id) => !selectedTagIds.has(id)) ??
selectedValues.find((id) => !nextTagIds.includes(id))
if (!tagId) {
return
}
const exists = selectedTagIds.has(tagId)
const currentTags = conversation.tags ?? []
const nextTags = exists
? currentTags.filter((item) => item.id !== tag.id)
: [...currentTags, { id: tag.id, name: tag.name }]
? currentTags.filter((item) => item.id !== tagId)
: [...currentTags, { id: tagId, name: "" }]
setPendingTagId(tag.id)
setPendingTagId(tagId)
try {
if (exists) {
await removeConversationTag({
conversationId: conversation.id,
tagId: tag.id,
tagId,
})
} else {
await addConversationTag({
conversationId: conversation.id,
tagId: tag.id,
tagId,
})
}
onTagsChange(nextTags)
@@ -117,70 +80,25 @@ export function ConversationTagPicker({
}
return (
<Popover>
<PopoverTrigger
render={
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 shrink-0 gap-1 px-2 text-xs"
aria-label={t("conversation.editTags")}
/>
}
>
<TagIcon className="size-3.5 text-muted-foreground" />
{t("conversation.edit")}
</PopoverTrigger>
<PopoverContent
align="end"
className="w-72 p-0"
onClick={(event) => event.stopPropagation()}
>
<Command>
<CommandInput placeholder={t("conversation.searchTags")} />
<CommandList>
{loading ? <CommandEmpty>{t("conversation.loadingTags")}</CommandEmpty> : null}
{!loading && flattenedTags.length === 0 ? (
<CommandEmpty>{t("conversation.emptyTags")}</CommandEmpty>
) : null}
{!loading ? (
<CommandGroup heading={t("conversation.tagGroup")}>
{flattenedTags.map((tag) => {
const checked = selectedTagIds.has(tag.id)
const pending = pendingTagId === tag.id
return (
<CommandItem
key={tag.id}
value={`${tag.id} ${tag.name} ${tag.remark}`}
disabled={pendingTagId !== null}
onSelect={() => void handleToggle(tag)}
>
{pending ? (
<Loader2Icon className="mr-2 size-4 animate-spin" />
) : (
<CheckIcon
className={cn(
"mr-2 size-4",
checked ? "opacity-100" : "opacity-0"
)}
/>
)}
<span
className="truncate"
style={{ paddingLeft: `${tag.depth * 12}px` }}
>
{tag.name}
</span>
</CommandItem>
)
})}
</CommandGroup>
) : null}
</CommandList>
</Command>
</PopoverContent>
</Popover>
<TagSelector
mode="multiple"
value={selectedValues}
onChange={(value) => void handleChange(value)}
tags={availableTags}
loading={loading}
pendingTagId={pendingTagId}
placeholder={t("conversation.edit")}
triggerText={t("conversation.edit")}
searchPlaceholder={t("conversation.searchTags")}
loadingText={t("conversation.loadingTags")}
emptyText={t("conversation.emptyTags")}
align="end"
showSelectedBadges={false}
triggerVariant="ghost"
triggerSize="sm"
triggerClassName="h-7 w-auto shrink-0 justify-start gap-1 px-2 text-xs"
contentClassName="w-72"
/>
)
}
@@ -197,21 +115,11 @@ export function ConversationTagBadges({
return null
}
const tagPathMap = buildTagPathMap(availableTags)
return (
<div className="flex flex-wrap items-center gap-1.5">
{tags.map((tag) => (
<Badge
key={tag.id}
variant="outline"
className="max-w-full px-2 text-[12px] font-normal"
>
<span className="break-all">
{tagPathMap.get(tag.id) ?? tag.name}
</span>
</Badge>
))}
</div>
<TagBadges
ids={tags.map((tag) => tag.id)}
tags={availableTags}
fallbackTags={tags}
/>
)
}
+10 -55
View File
@@ -5,8 +5,8 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, Resolver, useForm } from "react-hook-form";
import { z } from "zod/v4";
import { OptionCombobox } from "@/components/option-combobox";
import { ProjectDialog } from "@/components/project-dialog";
import { TagSelector } from "@/components/tag-selector";
import { Button } from "@/components/ui/button";
import {
Field,
@@ -66,39 +66,6 @@ function buildPayload(form: EditForm): CreateTagPayload {
};
}
type TagTreeNode = TagTree & {
children: TagTreeNode[];
depth: number;
};
function withDepth(
nodes: TagTree[] | null | undefined,
depth = 0,
): TagTreeNode[] {
const safeNodes = Array.isArray(nodes) ? nodes : [];
return safeNodes.map((node) => ({
...node,
depth,
children: withDepth(node.children, depth + 1),
}));
}
function flattenTreeForSelect(
nodes: TagTreeNode[],
excludeId?: number,
): { id: number; name: string; depth: number }[] {
const result: { id: number; name: string; depth: number }[] = [];
function traverse(node: TagTreeNode) {
if (node.id !== excludeId) {
result.push({ id: node.id, name: node.name, depth: node.depth });
node.children.forEach(traverse);
}
}
nodes.forEach(traverse);
return result;
}
export function EditDialog({
open,
saving,
@@ -140,9 +107,7 @@ function TagFormDialogBody({
const t = useI18n();
const formId = "tag-edit-form";
const [loading, setLoading] = useState(false);
const [parentTags, setParentTags] = useState<
{ id: number; name: string; depth: number }[]
>([]);
const [parentTags, setParentTags] = useState<TagTree[]>([]);
const tagFormSchema = useMemo(
() =>
@@ -157,17 +122,6 @@ function TagFormDialogBody({
() => zodResolver(tagFormSchema as never) as Resolver<EditForm>,
[tagFormSchema],
);
const parentOptions = useMemo(
() => [
{ value: "0", label: t("tag.rootParent") },
...parentTags.map((tag) => ({
value: String(tag.id),
label: `${" ".repeat(tag.depth)}${tag.name}`,
})),
],
[parentTags, t],
);
const form = useForm<EditForm>({
resolver: editFormResolver,
defaultValues: emptyForm,
@@ -184,9 +138,7 @@ function TagFormDialogBody({
async function loadParentTags() {
try {
const data = await fetchTagsAll();
const tree = withDepth(data);
const flatList = flattenTreeForSelect(tree, itemId ?? undefined);
setParentTags(flatList);
setParentTags(Array.isArray(data) ? data : []);
} catch (error) {
console.error("Failed to load parent tags:", error);
}
@@ -258,14 +210,17 @@ function TagFormDialogBody({
control={control}
name="parentId"
render={({ field }) => (
<OptionCombobox
value={field.value}
options={parentOptions}
<TagSelector
mode="single"
value={Number(field.value)}
onChange={(value) => field.onChange(String(value))}
tags={parentTags}
placeholder={t("tag.rootParent")}
searchPlaceholder={t("tag.searchParent")}
emptyText={t("tag.emptyParent")}
disabled={saving}
onChange={field.onChange}
rootOption={{ value: 0, label: t("tag.rootParent") }}
excludeIds={itemId ? [itemId] : undefined}
/>
)}
/>
+8 -105
View File
@@ -1,6 +1,5 @@
"use client"
import { CheckIcon, TagIcon } from "lucide-react"
import { useEffect, useMemo, useState } from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import type { Resolver } from "react-hook-form"
@@ -11,16 +10,8 @@ import { ContentEditor } from "@/components/content-editor"
import { OptionCombobox } from "@/components/option-combobox"
import { ProjectDialog } from "@/components/project-dialog"
import { isRichTextEmpty } from "@/components/safe-rich-html"
import { Badge } from "@/components/ui/badge"
import { TagSelector } from "@/components/tag-selector"
import { Button } from "@/components/ui/button"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import {
Field,
FieldContent,
@@ -29,7 +20,6 @@ import {
FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import {
fetchAgentProfilesAll,
fetchTagsAll,
@@ -113,97 +103,6 @@ function buildPayload(form: EditForm): CreateTicketPayload {
}
}
type FlatTagNode = TagTree & {
depth: number
path: string
}
function flattenTagTree(nodes: TagTree[], depth = 0, parentPath = ""): FlatTagNode[] {
const result: FlatTagNode[] = []
nodes.forEach((item) => {
const path = parentPath ? `${parentPath} / ${item.name}` : item.name
result.push({ ...item, depth, path })
if (item.children.length > 0) {
result.push(...flattenTagTree(item.children, depth + 1, path))
}
})
return result
}
type TicketTagSelectorProps = {
value?: number[]
onChange: (value: number[]) => void
availableTags: TagTree[]
t: TFunction
}
function TicketTagSelector({ value, onChange, availableTags, t }: TicketTagSelectorProps) {
const selectedValues = useMemo(() => value ?? [], [value])
const flatTags = useMemo(() => flattenTagTree(availableTags), [availableTags])
const selectedTagIDs = useMemo(() => new Set(selectedValues), [selectedValues])
const selectedTags = useMemo(
() => flatTags.filter((tag) => selectedTagIDs.has(tag.id)),
[flatTags, selectedTagIDs],
)
function handleToggle(tagID: number) {
if (selectedTagIDs.has(tagID)) {
onChange(selectedValues.filter((item) => item !== tagID))
return
}
onChange(selectedValues.concat(tagID))
}
return (
<div className="space-y-2">
<Popover>
<PopoverTrigger
render={
<Button type="button" variant="outline" className="w-full justify-start" />
}
>
<TagIcon className="size-4" />
{selectedTags.length > 0 ? t("ticket.selectedTags", { count: selectedTags.length }) : t("ticket.selectTags")}
</PopoverTrigger>
<PopoverContent align="start" className="w-[320px] p-0">
<Command>
<CommandInput placeholder={t("ticket.searchTags")} />
<CommandList>
<CommandEmpty>{t("ticket.emptyTags")}</CommandEmpty>
<CommandGroup heading={t("ticket.tags")}>
{flatTags.map((tag) => {
const checked = selectedTagIDs.has(tag.id)
return (
<CommandItem
key={tag.id}
value={`${tag.id} ${tag.path} ${tag.remark}`}
onSelect={() => handleToggle(tag.id)}
>
<CheckIcon className={`mr-2 size-4 ${checked ? "opacity-100" : "opacity-0"}`} />
<span className="truncate" style={{ paddingLeft: `${tag.depth * 12}px` }}>
{tag.name}
</span>
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
{selectedTags.length > 0 ? (
<div className="flex flex-wrap gap-1">
{selectedTags.map((tag) => (
<Badge key={tag.id} variant="outline">
{tag.path}
</Badge>
))}
</div>
) : null}
</div>
)
}
export function EditDialog({
open,
saving,
@@ -421,11 +320,15 @@ function TicketEditDialogBody({
control={control}
name="tagIds"
render={({ field }) => (
<TicketTagSelector
<TagSelector
mode="multiple"
value={field.value}
onChange={field.onChange}
availableTags={tags}
t={t}
tags={tags}
placeholder={t("ticket.selectTags")}
selectedCountText={(count) => t("ticket.selectedTags", { count })}
searchPlaceholder={t("ticket.searchTags")}
emptyText={t("ticket.emptyTags")}
/>
)}
/>
+8 -26
View File
@@ -60,10 +60,6 @@ function getAssigneeAllOption(t: TFunction): ComboboxOption {
return { value: "0", label: t("ticket.allAssignees") }
}
function getTagAllOption(t: TFunction): ComboboxOption {
return { value: "0", label: t("ticket.allTags") }
}
function getStaleHourOptions(t: TFunction): ComboboxOption[] {
return [
{ value: "24", label: t("ticket.hours", { hours: 24 }) },
@@ -72,21 +68,6 @@ function getStaleHourOptions(t: TFunction): ComboboxOption[] {
]
}
function buildTagOptions(nodes: TagTree[], parentPath = ""): ComboboxOption[] {
const result: ComboboxOption[] = []
nodes.forEach((item) => {
const currentPath = parentPath ? `${parentPath}/${item.name}` : item.name
result.push({
value: String(item.id),
label: currentPath,
})
if (item.children.length > 0) {
result.push(...buildTagOptions(item.children, currentPath))
}
})
return result
}
function sourceLabel(source: string, t: TFunction) {
switch (source) {
case "manual":
@@ -117,7 +98,7 @@ export default function TicketsPage() {
const searchParams = useSearchParams()
const [summary, setSummary] = useState<TicketSummary>(emptySummary)
const [assigneeOptions, setAssigneeOptions] = useState<ComboboxOption[]>([])
const [tagOptions, setTagOptions] = useState<ComboboxOption[]>([])
const [tags, setTags] = useState<TagTree[]>([])
const [selectedTicketId, setSelectedTicketId] = useState<number | null>(null)
const [detailOpen, setDetailOpen] = useState(false)
const [createOpen, setCreateOpen] = useState(false)
@@ -125,7 +106,6 @@ export default function TicketsPage() {
const listReloadRef = useRef<() => Promise<void>>(async () => undefined)
const assigneeAllOption = useMemo(() => getAssigneeAllOption(t), [t])
const tagAllOption = useMemo(() => getTagAllOption(t), [t])
const staleHourOptions = useMemo(() => getStaleHourOptions(t), [t])
const quickViews = useMemo(
@@ -201,11 +181,13 @@ export default function TicketsPage() {
{
name: "tagId",
label: t("ticket.allTags"),
type: "select",
type: "tag",
defaultValue: "0",
allValue: "0",
valueType: "number",
options: tagOptions,
tags,
searchPlaceholder: t("ticket.searchTags"),
emptyText: t("ticket.emptyTags"),
className: "w-full sm:w-44",
},
{
@@ -217,7 +199,7 @@ export default function TicketsPage() {
className: "w-full sm:w-40",
},
],
[assigneeOptions, quickViews, staleHourOptions, tagOptions, t],
[assigneeOptions, quickViews, staleHourOptions, tags, t],
)
const fetchList = useCallback(
@@ -365,7 +347,7 @@ export default function TicketsPage() {
t("ticket.agentFallback", { id: agent.userId }),
})),
])
setTagOptions([tagAllOption, ...buildTagOptions(Array.isArray(tags) ? tags : [])])
setTags(Array.isArray(tags) ? tags : [])
})
.catch((error) => {
toast.error(error instanceof Error ? error.message : t("ticket.loadFiltersFailed"))
@@ -373,7 +355,7 @@ export default function TicketsPage() {
return () => {
active = false
}
}, [assigneeAllOption, tagAllOption, t])
}, [assigneeAllOption, t])
async function handleCreateTicket(payload: CreateTicketPayload) {
setSavingCreate(true)