droboticflow/src/components/AnnotationLabelsPanel.tsx

586 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { userErrorMessage } from "../lib/user-error-message.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Download, Edit3, Loader2, Plus, Save, Trash2, Upload, X } from "lucide-react";
import { apiRequest } from "../services/api/client";
import { getActionErrorMessage } from "../lib/action-errors.js";
import { projectDictionaryNameKey, reuseOrCreateDictionaryLabel } from "../lib/project-dictionary.js";
import { parseDictionaryImport, planDictionaryImport, serializeDictionaryCSV } from "../lib/dictionary-batch.js";
import { cn } from "../lib/utils";
import type { AnnotationLabelRecord, ProjectAnnotationLabelsRecord } from "../types";
type DictionaryImportResponse = {
created?: number;
reused?: number;
skipped?: Array<{ name: string; reason: string }>;
};
export function AnnotationLabelsPanel({
projectId,
canManage,
kind = "action",
}: {
key?: string;
projectId: string;
canManage: boolean;
kind?: "action" | "slice" | "discard_reason";
}) {
const isSlice = kind === "slice";
const isDiscard = kind === "discard_reason";
const projectScoped = kind !== "action";
const noun = isSlice ? "切片名称" : isDiscard ? "舍弃原因" : "描述";
const title = isSlice ? "项目切片字典" : isDiscard ? "项目舍弃原因字典" : "项目动作描述字典";
const selectionPath = `/api/projects/${projectId}/${isSlice ? "slice-labels" : isDiscard ? "discard-reason-labels" : "annotation-labels"}`;
const importPath = `/api/projects/${projectId}/dictionary-labels/import`;
const [labels, setLabels] = useState<AnnotationLabelRecord[]>([]);
const [enabled, setEnabled] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [saveSuccess, setSaveSuccess] = useState(false);
const [error, setError] = useState("");
const [editingLabelId, setEditingLabelId] = useState("");
const [inputText, setInputText] = useState("");
const [tagText, setTagText] = useState("");
const [checkedIds, setCheckedIds] = useState<string[]>([]);
const [importOpen, setImportOpen] = useState(false);
const [importText, setImportText] = useState("");
const [importNotice, setImportNotice] = useState("");
const scope = useRef(0);
const load = async (generation: number, signal: AbortSignal) => {
setLoading(true);
setError("");
try {
const selectionRequest = apiRequest<ProjectAnnotationLabelsRecord>(selectionPath, { signal });
const [dictionary, selection] = await Promise.all([
projectScoped
? selectionRequest.then((result) => ({ items: result.items || [] }))
: apiRequest<{ items: AnnotationLabelRecord[] }>("/api/annotation-labels", { signal }),
selectionRequest,
]);
if (scope.current !== generation || signal.aborted) return;
setLabels(dictionary.items || []);
setEnabled(
(selection.labelIds || []).filter((id) =>
dictionary.items.some((item) => item.id === id && item.status !== "inactive"),
),
);
} catch (loadError) {
if (scope.current !== generation || signal.aborted) return;
setError(getActionErrorMessage(loadError, "加载标签字典失败"));
} finally {
if (scope.current === generation && !signal.aborted) setLoading(false);
}
};
const reload = () => {
const generation = ++scope.current;
void load(generation, new AbortController().signal);
};
useEffect(() => {
const generation = ++scope.current;
const controller = new AbortController();
setLabels([]);
setEnabled([]);
setEditingLabelId("");
setInputText("");
setTagText("");
setCheckedIds([]);
setImportOpen(false);
setImportText("");
setImportNotice("");
setSaving(false);
setSaveSuccess(false);
void load(generation, controller.signal);
return () => {
controller.abort();
scope.current++;
};
}, [projectId, kind]);
const resetEditing = () => {
setEditingLabelId("");
setInputText("");
setTagText("");
};
const startEdit = (label: AnnotationLabelRecord) => {
setSaveSuccess(false);
setError("");
setEditingLabelId(label.id);
setInputText(label.name || label.description || "");
setTagText((label.tags || []).join(","));
};
const saveLabel = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
if (saving || loading) return;
setSaveSuccess(false);
setError("");
const text = inputText.trim();
if (!text) return;
if (
labels.some(
(label) =>
enabled.includes(label.id) &&
label.status !== "inactive" &&
label.id !== editingLabelId &&
projectDictionaryNameKey(kind, label.name) === projectDictionaryNameKey(kind, text),
)
) {
setError("本项目已存在同名词条,无需重复添加");
return;
}
setSaving(true);
setError("");
const generation = scope.current;
try {
const existing = labels.find((item) => item.id === editingLabelId);
const code = `desc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
const tags = [
...new Set(
tagText
.split(/[,,\n]/)
.map((tag) => tag.trim())
.filter(Boolean),
),
];
const payload = {
tags,
kind,
code,
name: text,
description: text,
category: existing?.category || "",
example: existing?.example || "",
status: existing?.status || ("active" as const),
};
let saved = await reuseOrCreateDictionaryLabel({
kind,
name: text,
preferredId: editingLabelId,
isCurrent: () => scope.current === generation,
list: async () =>
(await apiRequest<{ items: AnnotationLabelRecord[] }>(`/api/annotation-labels?kind=${kind}`)).items,
create: () => apiRequest<AnnotationLabelRecord>("/api/annotation-labels", { method: "POST" }, payload),
});
if (scope.current !== generation) return;
// Explicit tag maintenance versions the shared dictionary word; saved
// selections retain their original tags.
if (
(editingLabelId === saved.id || tags.length > 0) &&
JSON.stringify(saved.tags || []) !== JSON.stringify(tags)
) {
saved = await apiRequest<AnnotationLabelRecord>(
`/api/annotation-labels/${saved.id}`,
{ method: "PATCH" },
{ ...saved, tags },
);
if (scope.current !== generation) return;
}
// Relink only this project; never rename a term shared by other projects.
const selection = await apiRequest<ProjectAnnotationLabelsRecord>(
selectionPath,
{ method: "PUT" },
{
labelIds: editingLabelId
? enabled.map((id) => (id === editingLabelId ? saved.id : id))
: [...enabled, saved.id],
},
);
if (scope.current !== generation) return;
setLabels((items) => [...items.filter((item) => item.id !== saved.id), saved]);
setEnabled(selection.labelIds || []);
setSaveSuccess(true);
resetEditing();
} catch (saveError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(saveError, `${editingLabelId ? "更新" : "添加"}${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
};
const deleteLabel = async (label: AnnotationLabelRecord) => {
if (!window.confirm(`确认从本项目删除此${noun}?已保存的标注和审核记录不会改变。`)) return;
setSaving(true);
setSaveSuccess(false);
setError("");
const generation = scope.current;
try {
const nextEnabled = enabled.filter((id) => id !== label.id);
const selected = await apiRequest<ProjectAnnotationLabelsRecord>(
selectionPath,
{ method: "PUT" },
{ labelIds: nextEnabled },
);
if (scope.current !== generation) return;
setEnabled(selected.labelIds || []);
if (editingLabelId === label.id) resetEditing();
} catch (delError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(delError, `删除${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
};
const deleteChecked = async () => {
if (!checkedIds.length || saving) return;
if (!window.confirm(`确认从本项目移除选中的 ${checkedIds.length} 个${noun}?已保存的标注和审核记录不会改变。`))
return;
setSaving(true);
setSaveSuccess(false);
setError("");
const generation = scope.current;
try {
const nextEnabled = enabled.filter((id) => !checkedIds.includes(id));
const selected = await apiRequest<ProjectAnnotationLabelsRecord>(
selectionPath,
{ method: "PUT" },
{ labelIds: nextEnabled },
);
if (scope.current !== generation) return;
setEnabled(selected.labelIds || []);
setCheckedIds([]);
if (editingLabelId && checkedIds.includes(editingLabelId)) resetEditing();
} catch (delError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(delError, `批量删除${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
};
const toggleChecked = (id: string) => {
setCheckedIds((ids) => (ids.includes(id) ? ids.filter((value) => value !== id) : [...ids, id]));
};
const activeLabels = labels.filter((item) => item.status !== "inactive" && enabled.includes(item.id));
const activeIds = activeLabels.map((item) => item.id);
const allChecked = activeIds.length > 0 && activeIds.every((id) => checkedIds.includes(id));
const exportCSV = () => {
const csv = serializeDictionaryCSV(activeLabels.map((item) => item.name || item.description || ""));
const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");
anchor.href = url;
anchor.download = `${title}-${date}.csv`;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
};
const parsedImport = useMemo(() => parseDictionaryImport(importText), [importText]);
const importPlan = useMemo(
() => planDictionaryImport({ kind, names: parsedImport.names, items: labels, enabledIds: enabled }),
[kind, parsedImport.names, labels, enabled],
);
const readImportFile = (file: File | undefined) => {
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
setImportText(String(reader.result || ""));
setImportNotice("");
setError("");
};
reader.readAsText(file);
};
const runImport = async () => {
if (saving || loading || !parsedImport.names.length) return;
setSaving(true);
setSaveSuccess(false);
setError("");
setImportNotice("");
const generation = scope.current;
try {
const result = await apiRequest<DictionaryImportResponse>(
importPath,
{ method: "POST" },
{
kind,
names: parsedImport.names,
},
);
if (scope.current !== generation) return;
const skipped = result.skipped?.length || 0;
setImportNotice(
`导入完成:新增 ${result.created || 0} 个,复用组织词条 ${result.reused || 0} 个,跳过 ${skipped} 个。`,
);
setImportText("");
reload();
} catch (importError) {
if (scope.current !== generation) return;
setError(getActionErrorMessage(importError, `导入${noun}失败`));
} finally {
if (scope.current === generation) setSaving(false);
}
};
return (
<section className="space-y-4" aria-label={title}>
<p className="text-sm text-slate-500">添加后即可在本项目使用,三个字典独立管理。</p>
{/* Top action and input bar */}
{canManage && (
<form onSubmit={saveLabel} className="flex flex-wrap items-center gap-3">
<input
value={inputText}
onChange={(e) => {
setInputText(e.target.value);
setSaveSuccess(false);
setError("");
}}
disabled={saving || loading}
placeholder={
isSlice
? "输入切片名称,如:商品检查"
: isDiscard
? "输入舍弃原因,如:调整头环"
: "输入描述内容,如:右手自上而下稳定抓取桌面上的水瓶"
}
className="flex-1 min-w-[280px] rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2.5 text-sm text-[color:var(--app-text)] shadow-sm focus:border-blue-500 focus:outline-none"
/>
<input
aria-label="分类标签"
placeholder="分类标签,用逗号分隔"
value={tagText}
onChange={(e) => setTagText(e.target.value)}
disabled={loading || saving}
className="min-w-48 flex-1 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-3 py-2 text-sm"
/>
<button
type="submit"
disabled={loading || saving || !inputText.trim()}
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50 transition-colors"
>
{editingLabelId ? <Save className="h-4 w-4" /> : <Plus className="h-4 w-4" />}
{editingLabelId ? "保存修改" : isSlice ? "添加名称" : isDiscard ? "添加原因" : "添加描述"}
</button>
{editingLabelId && (
<button
type="button"
onClick={resetEditing}
className="inline-flex items-center gap-1.5 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2.5 text-sm font-medium text-slate-600 shadow-sm hover:bg-slate-50 dark:text-gray-300"
>
<X className="h-4 w-4" />
取消
</button>
)}
</form>
)}
{/* Batch toolbar: export, import, batch remove */}
{canManage && (
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={exportCSV}
disabled={loading || !activeLabels.length}
className="inline-flex items-center gap-1.5 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2 text-sm font-medium text-slate-600 shadow-sm hover:bg-slate-50 disabled:opacity-50 dark:text-gray-300"
>
<Download className="h-4 w-4" />
导出 CSV
</button>
<button
type="button"
onClick={() => {
setImportOpen((open) => !open);
setImportNotice("");
}}
disabled={loading}
aria-expanded={importOpen}
className="inline-flex items-center gap-1.5 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2 text-sm font-medium text-slate-600 shadow-sm hover:bg-slate-50 disabled:opacity-50 dark:text-gray-300"
>
<Upload className="h-4 w-4" />
{importOpen ? "收起导入" : "批量导入"}
</button>
{activeLabels.length > 0 && (
<div className="ml-auto flex flex-wrap items-center gap-2">
<label className="inline-flex items-center gap-1.5 text-sm text-slate-600 dark:text-gray-300">
<input
type="checkbox"
checked={allChecked}
onChange={() => setCheckedIds(allChecked ? [] : activeIds)}
className="h-4 w-4 rounded border-[color:var(--app-border)]"
aria-label="全选词条"
/>
全选
</label>
<button
type="button"
onClick={() => void deleteChecked()}
disabled={saving || !checkedIds.length}
className="inline-flex items-center gap-1.5 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm font-medium text-red-600 shadow-sm hover:bg-red-500/20 disabled:opacity-50 dark:text-red-300"
>
<Trash2 className="h-4 w-4" />
删除所选{checkedIds.length ? `(${checkedIds.length})` : ""}
</button>
</div>
)}
</div>
)}
{/* Import dialog: paste or upload one name per line */}
{canManage && importOpen && (
<div className="space-y-3 rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-inset)] p-4 shadow-sm">
<div className="text-sm text-slate-600 dark:text-gray-300">
粘贴或上传名称列表,每行一个{noun};同名词条自动去重,已在本项目的自动跳过。可直接使用「导出 CSV」的文件。
</div>
<input
type="file"
accept=".csv,.txt"
onChange={(e) => readImportFile(e.target.files?.[0])}
className="block w-full text-sm text-slate-600 file:mr-3 file:rounded-lg file:border-0 file:bg-blue-600 file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-white hover:file:bg-blue-700 dark:text-gray-300"
aria-label={`选择要导入的${noun}文件`}
/>
<textarea
value={importText}
onChange={(e) => {
setImportText(e.target.value);
setImportNotice("");
setError("");
}}
rows={6}
placeholder={`每行一个${noun},例如:\n${isSlice ? "商品检查" : isDiscard ? "调整头环" : "右手抓取水瓶"}`}
className="w-full rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2.5 text-sm text-[color:var(--app-text)] shadow-sm focus:border-blue-500 focus:outline-none"
/>
{(parsedImport.names.length > 0 || parsedImport.invalid.length > 0) && (
<div className="text-xs text-slate-500 dark:text-gray-400">
待导入 {importPlan.toImport.length} 个 · 已在本项目 {importPlan.alreadySelected.length} 个 · 输入重复{" "}
{importPlan.duplicates.length} 个
{parsedImport.invalid.length ? ` · 无法识别 ${parsedImport.invalid.length} 行(一行只能有一个名称)` : ""}
</div>
)}
{importNotice && (
<div className="rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-4 py-2.5 text-sm text-emerald-700 dark:text-emerald-300">
✓ {importNotice}
</div>
)}
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={() => void runImport()}
disabled={loading || saving || !importPlan.toImport.length}
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50"
>
<Upload className="h-4 w-4" />
导入 {importPlan.toImport.length} 个名称
</button>
<button
type="button"
onClick={() => {
setImportOpen(false);
setImportText("");
setImportNotice("");
}}
className="inline-flex items-center gap-1.5 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-4 py-2 text-sm font-medium text-slate-600 shadow-sm hover:bg-slate-50 dark:text-gray-300"
>
<X className="h-4 w-4" />
关闭
</button>
</div>
</div>
)}
{error && (
<div className="rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-600 dark:text-red-200">
{userErrorMessage(error)}
</div>
)}
{saveSuccess && (
<div className="rounded-lg border border-emerald-500/20 bg-emerald-500/10 px-4 py-2.5 text-sm text-emerald-700 dark:text-emerald-300">
✓ {title}已成功保存
</div>
)}
{/* Line by line description items */}
<div className="overflow-hidden rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] shadow-sm">
{loading ? (
<div className="flex items-center justify-center gap-2 py-12 text-sm text-slate-500 dark:text-gray-400">
<Loader2 className="h-4 w-4 animate-spin text-blue-500" />
正在加载{noun}列表…
</div>
) : activeLabels.length === 0 ? (
<div className="py-12 text-center text-sm text-slate-500 dark:text-gray-400">暂无{noun},请在上方添加。</div>
) : (
<div className="divide-y divide-slate-100 dark:divide-[#202227]">
{activeLabels.map((item, index) => {
const text = item.name || item.description;
const isEditing = editingLabelId === item.id;
const isChecked = checkedIds.includes(item.id);
return (
<div
key={item.id}
className={cn(
"flex items-center gap-3 px-5 py-3.5 transition-colors hover:bg-slate-50 dark:hover:bg-white/5",
isEditing && "bg-blue-50/50 dark:bg-blue-900/10",
)}
>
{canManage && (
<input
type="checkbox"
checked={isChecked}
onChange={() => toggleChecked(item.id)}
disabled={saving}
className="h-4 w-4 shrink-0 rounded border-[color:var(--app-border)]"
aria-label={`选择${noun} ${text}`}
/>
)}
<span className="text-xs font-mono text-slate-400 select-none w-5 text-right shrink-0">
{index + 1}.
</span>
<span
onClick={() => canManage && startEdit(item)}
className="flex-1 text-sm text-slate-800 dark:text-gray-200 cursor-pointer select-none"
>
{text}
{(item.tags || []).map((tag) => (
<span
key={tag}
className="ml-2 rounded bg-blue-50 px-2 py-0.5 text-xs text-blue-700 dark:bg-blue-900/30 dark:text-blue-200"
>
{tag}
</span>
))}
</span>
{canManage && (
<div className="flex items-center gap-1 shrink-0">
<button
type="button"
onClick={() => startEdit(item)}
disabled={saving}
className="rounded p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-700 dark:text-gray-500 dark:hover:bg-white/5 dark:hover:text-white transition-colors"
title={`编辑${noun}`}
>
<Edit3 className="h-4 w-4" />
</button>
<button
type="button"
onClick={() => void deleteLabel(item)}
disabled={saving}
className="rounded p-1.5 text-slate-400 hover:bg-red-50 hover:text-red-600 dark:text-gray-500 dark:hover:bg-red-500/10 dark:hover:text-red-400 transition-colors"
title={`删除${noun}`}
>
<Trash2 className="h-4 w-4" />
</button>
</div>
)}
</div>
);
})}
</div>
)}
</div>
<p className="text-sm text-slate-500">名称增删只影响本项目;标签随字典词条共享,已保存的分类保持原版本。</p>
</section>
);
}