GraphEditor.tsx 7 KB
import { Check, X } from "lucide-react";
import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { typeColor } from "@/lib/colors";
import { toast } from "@/store/useAppStore";
import { Modal, Pill, Spinner } from "@/components/ui";
import type { OntologyResponse } from "@/lib/types";

export type EditorKind = "node" | "edge";

function EntityTypeOptions({ types }: { types: string[] }) {
  const options = [...new Set([...(types ?? []), "其他"])];
  return (
    <>
      {options.map((t) => <option key={t} value={t}>{t}</option>)}
    </>
  );
}

function RelationTypeOptions({ types }: { types: string[] }) {
  const options = [...new Set([...(types ?? []), "关联"])];
  return (
    <>
      {options.map((t) => <option key={t} value={t}>{t}</option>)}
    </>
  );
}

function EndpointField({ label, value, onChange }: {
  label: string; value: string; onChange: (v: string) => void;
}) {
  const [hits, setHits] = useState<{ id: string; label: string; type: string; degree: number }[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!value.trim()) { setHits([]); return; }
    let cancelled = false;
    setLoading(true);
    const t = setTimeout(async () => {
      try {
        const r = await api.searchNodes(value.trim(), 8);
        if (!cancelled) { setHits(r); setOpen(true); }
      } catch { if (!cancelled) setHits([]); }
      finally { if (!cancelled) setLoading(false); }
    }, 220);
    return () => { cancelled = true; clearTimeout(t); };
  }, [value]);

  return (
    <div className="relative">
      <p className="label">{label}</p>
      <input className="input w-full" value={value} placeholder="输入节点名,可从下方选择"
             onChange={(e) => { onChange(e.target.value); setOpen(true); }}
             onFocus={() => hits.length && setOpen(true)} />
      {loading && <Spinner className="absolute right-2.5 top-8 h-3.5 w-3.5 text-muted" />}
      {open && hits.length > 0 && (
        <div className="card absolute left-0 right-0 top-full z-30 mt-1.5 max-h-64 overflow-auto p-1">
          {hits.map((h) => (
            <button key={h.id} type="button"
                    className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-ink/5"
                    onClick={() => { onChange(h.id); setOpen(false); }}>
              <span className="h-2 w-2 shrink-0 rounded-full" style={{ background: typeColor(h.type) }} />
              <span className="min-w-0 flex-1 truncate text-[13px]">{h.label}</span>
              <Pill color={typeColor(h.type)}>{h.type}</Pill>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/** 新增人工节点/关系。人工内容参与检索,但没有原文证据。 */
export function GraphEditor({ open, kind, onto, onClose, onSaved }: {
  open: boolean; kind: EditorKind; onto: OntologyResponse | null;
  onClose: () => void; onSaved: () => void;
}) {
  const [name, setName] = useState("");
  const [label, setLabel] = useState("");
  const [etype, setEtype] = useState("其他");
  const [source, setSource] = useState("");
  const [target, setTarget] = useState("");
  const [relation, setRelation] = useState("关联");
  const [description, setDescription] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    setName(""); setLabel(""); setEtype("其他");
    setSource(""); setTarget(""); setRelation("关联"); setDescription("");
  }, [open, kind]);

  const submit = async () => {
    if (kind === "node") {
      if (!name.trim()) { toast("warn", "请填写节点名称"); return; }
    } else {
      if (!source.trim() || !target.trim()) { toast("warn", "请填写源节点和目标节点"); return; }
      if (!relation.trim()) { toast("warn", "请填写关系类型"); return; }
    }
    setSaving(true);
    try {
      if (kind === "node") {
        await api.createNode({ id: name.trim(), type: etype, label: label.trim(), description });
        toast("ok", "节点已新增");
      } else {
        await api.createEdge({ source: source.trim(), target: target.trim(),
                               relation: relation.trim(), description });
        toast("ok", "关系已新增");
      }
      onSaved();
      onClose();
    } catch (e) {
      toast("error", kind === "node" ? "新增节点失败" : "新增关系失败",
            e instanceof Error ? e.message : undefined);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose}
           title={kind === "node" ? "新增节点" : "新增关系"}
           desc="人工内容会用「人工」徽标区分,参与深挖检索但不会产生原文引用"
           footer={
             <>
               <button className="btn" onClick={onClose}><X className="h-3.5 w-3.5" />取消</button>
               <button className="btn btn-primary" onClick={submit} disabled={saving}>
                 {saving ? <Spinner className="h-3.5 w-3.5" /> : <Check className="h-3.5 w-3.5" />}
                 保存
               </button>
             </>
           }>
      {kind === "node" ? (
        <div className="space-y-3">
          <div>
            <p className="label">节点名称 *</p>
            <input className="input w-full" value={name} placeholder="例如:安心包专岗"
                   onChange={(e) => setName(e.target.value)} />
          </div>
          <div>
            <p className="label">显示名(可选)</p>
            <input className="input w-full" value={label} placeholder="与节点名不同时填写"
                   onChange={(e) => setLabel(e.target.value)} />
          </div>
          <div>
            <p className="label">类型</p>
            <select className="input w-full" value={etype} onChange={(e) => setEtype(e.target.value)}>
              <EntityTypeOptions types={onto?.entity_types ?? []} />
            </select>
          </div>
          <div>
            <p className="label">描述</p>
            <textarea className="input min-h-24 w-full resize-y" value={description}
                      placeholder="这个实体在业务中的含义" onChange={(e) => setDescription(e.target.value)} />
          </div>
        </div>
      ) : (
        <div className="space-y-3">
          <EndpointField label="源节点 *" value={source} onChange={setSource} />
          <EndpointField label="目标节点 *" value={target} onChange={setTarget} />
          <div>
            <p className="label">关系类型</p>
            <select className="input w-full" value={relation} onChange={(e) => setRelation(e.target.value)}>
              <RelationTypeOptions types={onto?.relation_types ?? []} />
            </select>
          </div>
          <div>
            <p className="label">描述</p>
            <textarea className="input min-h-24 w-full resize-y" value={description}
                      placeholder="这条关系的业务含义" onChange={(e) => setDescription(e.target.value)} />
          </div>
        </div>
      )}
    </Modal>
  );
}