PropertyPanel.tsx 12.2 KB
import { BadgeCheck, Check, FileText, Maximize2, Pencil, X } from "lucide-react";
import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { typeColor } from "@/lib/colors";
import { shortHeading, truncate } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Badge, Empty, ErrorNote, Pill, Skeleton } from "@/components/ui";
import type { EdgeBrief, EdgeDetail, NodeDetail } from "@/lib/types";

export type Selection =
  | { kind: "node"; id: string }
  | { kind: "edge"; source: string; target: string; relation: string }
  | null;

/**
 * 属性面板:实体/关系的全部属性、出入边、原文出处,并且**可编辑**。
 * 编辑后标记 verified —— 人工校订过的内容在图上有区分,这是交付客户时的刚需。
 */
export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onChanged }: {
  selection: Selection;
  entityTypes: string[];
  onSelect: (s: Selection) => void;
  onExpand: (id: string) => void;
  onChanged?: () => void;
}) {
  const [node, setNode] = useState<NodeDetail | null>(null);
  const [edge, setEdge] = useState<EdgeDetail | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState({ type: "", description: "" });

  useEffect(() => {
    setEditing(false);
    setError(null);
    if (!selection) { setNode(null); setEdge(null); return; }
    let cancelled = false;
    setLoading(true);
    (async () => {
      try {
        if (selection.kind === "node") {
          const d = await api.node(selection.id);
          if (!cancelled) { setNode(d); setEdge(null); setDraft({ type: d.type, description: d.description }); }
        } else {
          const d = await api.edge(selection.source, selection.target, selection.relation);
          if (!cancelled) { setEdge(d); setNode(null); setDraft({ type: "", description: d.description }); }
        }
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : "加载失败");
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [selection]);

  const save = async () => {
    try {
      if (node) {
        const r = await api.updateNode({ id: node.id, type: draft.type, description: draft.description, verified: true });
        setNode(r.node);
      } else if (edge) {
        await api.updateEdge({ source: edge.source, target: edge.target, relation: edge.relation,
                               description: draft.description, verified: true });
        setEdge({ ...edge, description: draft.description, verified: true });
      }
      setEditing(false);
      toast("ok", "已保存并标记为人工校订");
      onChanged?.();
    } catch (e) {
      toast("error", "保存失败", e instanceof Error ? e.message : undefined);
    }
  };

  if (!selection) {
    return (
      <Empty
        icon={<Maximize2 className="h-8 w-8" />}
        title="点击节点或关系查看详情"
        desc="悬停会高亮它的邻居;双击节点可以展开它的邻域;拖拽可以调整位置。按 / 打开搜索。"
      />
    );
  }
  if (loading) {
    return (
      <div className="space-y-2.5 p-3">
        <Skeleton className="h-5 w-2/3" />
        <Skeleton className="h-3 w-full" />
        <Skeleton className="h-3 w-4/5" />
        <Skeleton className="h-20 w-full" />
      </div>
    );
  }
  if (error) return <div className="p-3"><ErrorNote>{error}</ErrorNote></div>;

  if (node) {
    return (
      <div className="flex h-full flex-col overflow-auto">
        <div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur">
          <div className="flex items-start gap-2">
            <h3 className="min-w-0 flex-1 break-words text-[15px] font-semibold leading-snug">{node.label}</h3>
            <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)}
                    title={editing ? "取消编辑" : "编辑"}>
              {editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />}
            </button>
          </div>
          <div className="mt-1.5 flex flex-wrap items-center gap-1.5">
            <Pill color={typeColor(node.type)}>{node.type}</Pill>
            <Badge>{node.degree} 度</Badge>
            <Badge>{node.occurrence} 处提及</Badge>
            {node.community != null && <Badge>社区 {node.community}</Badge>}
            {node.verified && (
              <Badge tone="bg-ok/10 text-ok"><BadgeCheck className="h-3 w-3" />已校订</Badge>
            )}
          </div>
        </div>

        <div className="space-y-4 p-3">
          {editing ? (
            <div className="space-y-2">
              <div>
                <label className="label">实体类型</label>
                <select className="input" value={draft.type}
                        onChange={(e) => setDraft({ ...draft, type: e.target.value })}>
                  {entityTypes.map((t) => <option key={t} value={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <label className="label">描述</label>
                <textarea className="input min-h-24 resize-y" value={draft.description}
                          onChange={(e) => setDraft({ ...draft, description: e.target.value })} />
              </div>
              <div className="flex gap-2">
                <button className="btn btn-primary btn-sm" onClick={save}>
                  <Check className="h-3.5 w-3.5" />保存
                </button>
                <button className="btn btn-sm" onClick={() => setEditing(false)}>取消</button>
              </div>
            </div>
          ) : (
            <p className="text-[13px] leading-relaxed">
              {node.description || <span className="text-muted">(无描述)</span>}
            </p>
          )}

          {node.aliases.length > 0 && (
            <Field label={`别名(消歧合并 ${node.aliases.length} 个)`}>
              <div className="flex flex-wrap gap-1.5">
                {node.aliases.map((a) => <Badge key={a}>{a}</Badge>)}
              </div>
            </Field>
          )}

          <button className="btn w-full" onClick={() => onExpand(node.id)}>
            <Maximize2 className="h-3.5 w-3.5" />以该节点为中心展开邻域
          </button>

          <EdgeList title={`出向关系(${node.out_edges.length})`} items={node.out_edges} dir="out"
                    onPick={(other, rel) => onSelect({ kind: "edge", source: node.id, target: other, relation: rel })}
                    onNode={(id) => onSelect({ kind: "node", id })} />
          <EdgeList title={`入向关系(${node.in_edges.length})`} items={node.in_edges} dir="in"
                    onPick={(other, rel) => onSelect({ kind: "edge", source: other, target: node.id, relation: rel })}
                    onNode={(id) => onSelect({ kind: "node", id })} />

          {node.sources.length > 0 && (
            <Field label={`原文出处(${node.sources.length})`}>
              <div className="space-y-1.5">
                {node.sources.map((s) => <SourceCard key={s.chunk_id} s={s} />)}
              </div>
            </Field>
          )}
        </div>
      </div>
    );
  }

  if (edge) {
    return (
      <div className="flex h-full flex-col overflow-auto">
        <div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur">
          <div className="flex items-start gap-2">
            <h3 className="min-w-0 flex-1 text-[15px] font-semibold">关系:{edge.relation}</h3>
            <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)}>
              {editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />}
            </button>
          </div>
          <div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-[13px]">
            <button className="rounded-md bg-brand/10 px-2 py-0.5 font-medium text-brand hover:bg-brand/20"
                    onClick={() => onSelect({ kind: "node", id: edge.source })}>{edge.source}</button>
            <span className="text-warn">→</span>
            <button className="rounded-md bg-brand/10 px-2 py-0.5 font-medium text-brand hover:bg-brand/20"
                    onClick={() => onSelect({ kind: "node", id: edge.target })}>{edge.target}</button>
            <Badge>{edge.occurrence} 处佐证</Badge>
            {edge.verified && <Badge tone="bg-ok/10 text-ok"><BadgeCheck className="h-3 w-3" />已校订</Badge>}
          </div>
        </div>
        <div className="space-y-4 p-3">
          {editing ? (
            <div className="space-y-2">
              <textarea className="input min-h-24 resize-y" value={draft.description}
                        onChange={(e) => setDraft({ ...draft, description: e.target.value })} />
              <div className="flex gap-2">
                <button className="btn btn-primary btn-sm" onClick={save}><Check className="h-3.5 w-3.5" />保存</button>
                <button className="btn btn-sm" onClick={() => setEditing(false)}>取消</button>
              </div>
            </div>
          ) : (
            <p className="text-[13px] leading-relaxed">
              {edge.description || <span className="text-muted">(无描述)</span>}
            </p>
          )}
          {edge.sources.length > 0 && (
            <Field label={`原文出处(${edge.sources.length})`}>
              <div className="space-y-1.5">{edge.sources.map((s) => <SourceCard key={s.chunk_id} s={s} />)}</div>
            </Field>
          )}
        </div>
      </div>
    );
  }
  return null;
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <div><p className="label">{label}</p>{children}</div>;
}

function EdgeList({ title, items, dir, onPick, onNode }: {
  title: string; items: EdgeBrief[]; dir: "in" | "out";
  onPick: (other: string, rel: string) => void; onNode: (id: string) => void;
}) {
  const [expanded, setExpanded] = useState(false);
  if (!items.length) return null;
  const shown = expanded ? items : items.slice(0, 8);
  return (
    <Field label={title}>
      <div className="space-y-1">
        {shown.map((e, i) => {
          const other = (dir === "out" ? e.target : e.source) ?? "";
          const otype = (dir === "out" ? e.target_type : e.source_type) ?? "";
          return (
            <div key={`${other}-${e.relation}-${i}`}
                 className="rounded-lg border border-line bg-elevated px-2 py-1.5">
              <div className="flex flex-wrap items-center gap-1.5 text-[12.5px]">
                <button className="text-muted hover:text-brand"
                        onClick={() => onPick(other, e.relation)}>
                  {dir === "out" ? `—[${e.relation}]→` : `←[${e.relation}]—`}
                </button>
                <button className="min-w-0 truncate font-medium hover:text-brand" onClick={() => onNode(other)}>
                  {other}
                </button>
                <Pill color={typeColor(otype)}>{otype || "其他"}</Pill>
                {e.occurrence > 1 && <Badge>{e.occurrence}×</Badge>}
              </div>
              {e.description && (
                <p className="mt-0.5 text-[11.5px] leading-relaxed text-muted">{truncate(e.description, 120)}</p>
              )}
            </div>
          );
        })}
        {items.length > 8 && (
          <button className="btn btn-ghost btn-sm w-full" onClick={() => setExpanded(!expanded)}>
            {expanded ? "收起" : `展开其余 ${items.length - 8} 条`}
          </button>
        )}
      </div>
    </Field>
  );
}

function SourceCard({ s }: { s: { chunk_id: string; heading: string; snippet: string } }) {
  return (
    <div className="rounded-lg border border-line bg-elevated p-2">
      <p className="flex items-center gap-1 text-[11px] font-medium text-brand2">
        <FileText className="h-3 w-3 shrink-0" />
        <span className="truncate">{shortHeading(s.heading)}</span>
        <code className="ml-auto shrink-0 rounded bg-ink/5 px-1 font-mono text-[10px] text-muted">{s.chunk_id}</code>
      </p>
      <p className="mt-1 text-[11.5px] leading-relaxed text-muted">{s.snippet}</p>
    </div>
  );
}