graph.js 7.32 KB
// 本体图谱:graphology 建模 + 自研力导向布局 + Sigma 渲染 + 点击查看节点/关系
window.GraphView = (function(){
  let renderer=null, graph=null, dirty=true, activeTypes=null, initialized=false;

  function forceLayout(g, iters){
    const nodes=g.nodes(); const n=nodes.length; if(n<2) return;
    const W=1000,H=1000, area=W*H, k=Math.sqrt(area/n)*0.9;
    const pos={};
    nodes.forEach(id=>pos[id]={x:(Math.random()-0.5)*W, y:(Math.random()-0.5)*H, dx:0, dy:0});
    let temp=W/8;
    for(let it=0; it<iters; it++){
      for(let i=0;i<n;i++){ pos[nodes[i]].dx=0; pos[nodes[i]].dy=0; }
      // 斥力
      for(let i=0;i<n;i++){
        const a=pos[nodes[i]];
        for(let j=i+1;j<n;j++){
          const b=pos[nodes[j]];
          let ddx=a.x-b.x, ddy=a.y-b.y; let dist=Math.hypot(ddx,ddy)||0.01;
          const rep=k*k/dist; const fx=ddx/dist*rep, fy=ddy/dist*rep;
          a.dx+=fx; a.dy+=fy; b.dx-=fx; b.dy-=fy;
        }
      }
      // 引力(沿边)
      g.forEachEdge((e,attr,s,t)=>{
        if(s===t) return;
        const a=pos[s], b=pos[t]; let ddx=a.x-b.x, ddy=a.y-b.y; let dist=Math.hypot(ddx,ddy)||0.01;
        const att=dist*dist/k; const fx=ddx/dist*att, fy=ddy/dist*att;
        a.dx-=fx; a.dy-=fy; b.dx+=fx; b.dy+=fy;
      });
      // 中心引力 + 位移
      for(let i=0;i<n;i++){
        const p=pos[nodes[i]];
        p.dx-=p.x*0.01; p.dy-=p.y*0.01;
        const d=Math.hypot(p.dx,p.dy)||0.01;
        p.x+=p.dx/d*Math.min(d,temp); p.y+=p.dy/d*Math.min(d,temp);
      }
      temp*=0.97;
    }
    nodes.forEach(id=>{ g.setNodeAttribute(id,"x",pos[id].x); g.setNodeAttribute(id,"y",pos[id].y); });
  }

  async function build(){
    const kw=document.getElementById("graph-keyword").value.trim();
    const stats=await OT.api("/api/graph/stats");
    renderTypeFilter(stats.type_dist);
    document.getElementById("graph-stat").textContent=`共 ${stats.entity_count} 实体 · ${stats.relation_count} 关系`;
    const typeParam = activeTypes ? Array.from(activeTypes).join(",") : "";
    const limit=parseInt(document.getElementById("graph-limit").value)||300;
    const data=await OT.api(`/api/graph?limit=${limit}&keyword=${encodeURIComponent(kw)}&type=${encodeURIComponent(typeParam)}`);
    document.getElementById("graph-shown").textContent=`(当前展示按连接度排名的前 ${data.nodes.length} 个节点)`;

    graph=new graphology.MultiDirectedGraph();
    data.nodes.forEach(nd=>{
      const t=nd.attributes.type;
      graph.addNode(nd.key,{label:nd.attributes.label,etype:t,size:nd.attributes.size,
        color:OT.typeColor(t), x:Math.random(), y:Math.random()});
    });
    data.edges.forEach(ed=>{
      if(!graph.hasNode(ed.source)||!graph.hasNode(ed.target)) return;
      try{ graph.addEdgeWithKey(ed.key, ed.source, ed.target,
        {label:ed.attributes.label, relation:ed.attributes.label, type:"arrow", size:1.4, color:"#c3c8d4"}); }catch(e){}
    });
    forceLayout(graph, graph.order>400?70:graph.order>200?120:220);

    if(renderer){ renderer.kill(); renderer=null; }
    renderer=new Sigma(graph, document.getElementById("sigma"), {
      renderEdgeLabels:true, defaultEdgeType:"arrow",
      labelFont:"Segoe UI, PingFang SC, sans-serif", labelColor:{color:"#1f2430"},
      edgeLabelColor:{color:"#8a92a6"}, edgeLabelSize:11, labelRenderedSizeThreshold:1,
      labelDensity:1.2, minCameraRatio:0.05, maxCameraRatio:10
    });
    renderer.on("clickNode",({node})=>showNode(node));
    renderer.on("clickEdge",({edge})=>{
      const s=graph.source(edge), t=graph.target(edge), rel=graph.getEdgeAttribute(edge,"relation");
      showEdge(s,t,rel);
    });
    initialized=true; dirty=false;
  }

  function renderTypeFilter(dist){
    if(activeTypes===null){ activeTypes=new Set(Object.keys(dist)); }
    const box=document.getElementById("type-filter"); box.innerHTML="";
    Object.entries(dist).forEach(([t,c])=>{
      const on=activeTypes.has(t);
      const chip=document.createElement("span");
      chip.className="type-chip"+(on?"":" off");
      chip.innerHTML=`<span class="dot" style="background:${OT.typeColor(t)}"></span>${OT.esc(t)} <span class="muted">${c}</span>`;
      chip.addEventListener("click",()=>{ on?activeTypes.delete(t):activeTypes.add(t); build(); });
      box.appendChild(chip);
    });
  }

  async function showNode(id){
    const panel=document.getElementById("node-detail");
    panel.innerHTML=`<div class="muted">加载中…</div>`;
    try{
      const d=await OT.api("/api/node?id="+encodeURIComponent(id));
      const relHtml=(items,dirLabel)=>items.map(e=>{
        const other=e.target!==undefined?e.target:e.source;
        const otype=e.target_type!==undefined?e.target_type:e.source_type;
        const arrow=e.target!==undefined?`—[${OT.esc(e.relation)}]→`:`←[${OT.esc(e.relation)}]—`;
        const src=(e.sources||[]).slice(0,2).map(s=>`【${OT.esc(s.heading||"正文")}】${OT.esc(s.snippet||"")}`).join("<br>");
        return `<div class="rel-item"><span class="muted">${arrow}</span>
          <a href="#" class="nbr" data-id="${OT.esc(other)}">${OT.esc(other)}</a>
          ${OT.pill(otype,OT.typeColor(otype))}
          ${e.description?`<div class="muted">${OT.esc(e.description)}</div>`:""}
          ${src?`<div class="src">${src}</div>`:""}</div>`;
      }).join("")||`<div class="muted">无</div>`;
      panel.innerHTML=`
        <h4>${OT.esc(d.label)} ${OT.pill(d.type,OT.typeColor(d.type))}</h4>
        <div>${OT.esc(d.description)||'<span class="muted">(无描述)</span>'}</div>
        <h4>出向关系(${d.out_edges.length})</h4>${relHtml(d.out_edges)}
        <h4>入向关系(${d.in_edges.length})</h4>${relHtml(d.in_edges)}`;
      panel.querySelectorAll(".nbr").forEach(a=>a.addEventListener("click",ev=>{ev.preventDefault();
        if(graph.hasNode(a.dataset.id)) renderer.getCamera().animate(nodePos(a.dataset.id),{duration:400});
        showNode(a.dataset.id);}));
    }catch(e){ panel.innerHTML=`<div class="muted">加载失败:${OT.esc(e.message)}</div>`; }
  }

  function nodePos(id){ const d=renderer.getNodeDisplayData(id); return d?{x:d.x,y:d.y,ratio:0.4}:{}; }

  async function showEdge(s,t,rel){
    const panel=document.getElementById("node-detail");
    try{
      const d=await OT.api(`/api/edge?source=${encodeURIComponent(s)}&target=${encodeURIComponent(t)}&relation=${encodeURIComponent(rel)}`);
      const src=(d.sources||[]).map(x=>`<div class="src">【${OT.esc(x.heading||"正文")}】${OT.esc(x.snippet||"")}</div>`).join("");
      panel.innerHTML=`<h4>关系:${OT.esc(d.relation)}</h4>
        <div class="path-chip"><span class="node">${OT.esc(d.source)}</span><span class="arrow">—[${OT.esc(d.relation)}]→</span><span class="node">${OT.esc(d.target)}</span></div>
        <div>${OT.esc(d.description)||'<span class="muted">(无描述)</span>'}</div>
        <h4>原文出处</h4>${src||'<div class="muted">无</div>'}`;
    }catch(e){ panel.innerHTML=`<div class="muted">加载失败</div>`; }
  }

  document.getElementById("btn-graph-refresh").addEventListener("click",()=>{activeTypes=null;build();});
  document.getElementById("btn-graph-fit").addEventListener("click",()=>{ if(renderer) renderer.getCamera().animatedReset(); });
  document.getElementById("graph-keyword").addEventListener("keydown",e=>{ if(e.key==="Enter") build(); });

  return {
    ensure(){ if(!initialized||dirty) build(); },
    markDirty(){ dirty=true; }
  };
})();