Agnes 2.0-flash是推理模型,推理token占大量预算。 800仍不够→JSON截断(parse error: unexpected end of JSON input)。 1200确保推理+正文都够用。
382 lines
17 KiB
TypeScript
382 lines
17 KiB
TypeScript
import { ItemView, WorkspaceLeaf } from "obsidian";
|
||
import {
|
||
fetchGraphExport,
|
||
fetchNeighbors,
|
||
fetchByEntity,
|
||
fetchPageRank,
|
||
getRuntimeNamespace,
|
||
type GraphNode,
|
||
type GraphEdge,
|
||
type MemoryRecord,
|
||
} from "./api";
|
||
|
||
// 动态加载 D3.js(从 CDN,不打包)
|
||
async function loadD3(): Promise<typeof import("d3")> {
|
||
if ((window as unknown as Record<string, unknown>)["d3"]) {
|
||
return (window as unknown as Record<string, unknown>)["d3"] as typeof import("d3");
|
||
}
|
||
return new Promise((resolve, reject) => {
|
||
const script = document.createElement("script");
|
||
script.src = "https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js";
|
||
script.onload = () => resolve((window as unknown as Record<string, unknown>)["d3"] as typeof import("d3"));
|
||
script.onerror = reject;
|
||
document.head.appendChild(script);
|
||
});
|
||
}
|
||
|
||
export const GRAPH_VIEW_TYPE = "zhiyi-graph-view";
|
||
|
||
interface SimNode extends d3.SimulationNodeDatum {
|
||
id: string;
|
||
label: string;
|
||
category?: string;
|
||
weight?: number;
|
||
isCentral?: boolean;
|
||
}
|
||
|
||
interface SimLink extends d3.SimulationLinkDatum<SimNode> {
|
||
relation: string;
|
||
weight?: number;
|
||
}
|
||
|
||
export class GraphView extends ItemView {
|
||
private currentEntity = "";
|
||
private d3: typeof import("d3") | null = null;
|
||
private svg: d3.Selection<SVGSVGElement, unknown, null, undefined> | null = null;
|
||
private simulation: d3.Simulation<SimNode, SimLink> | null = null;
|
||
private topEntities: Array<{ entity: string; score: number }> = [];
|
||
|
||
constructor(leaf: WorkspaceLeaf) {
|
||
super(leaf);
|
||
}
|
||
|
||
getViewType() { return GRAPH_VIEW_TYPE; }
|
||
getDisplayText() { return "织忆图谱"; }
|
||
|
||
async onOpen() {
|
||
this.render();
|
||
}
|
||
|
||
async onClose() {
|
||
this.simulation?.stop();
|
||
}
|
||
|
||
async render() {
|
||
this.container.empty();
|
||
this.container.createEl("style", { text: `
|
||
.zhiyi-graph-view { height: 100%; display: flex; flex-direction: column; }
|
||
.zhiyi-graph-toolbar { display: flex; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--background-modifier-border); align-items: center; }
|
||
.zhiyi-graph-toolbar input { flex: 1; padding: 4px 8px; font-size: 12px; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal); }
|
||
.zhiyi-graph-toolbar button { padding: 4px 10px; font-size: 12px; cursor: pointer; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; }
|
||
.zhiyi-graph-toolbar .info { font-size: 11px; color: var(--text-muted); padding: 0 4px; }
|
||
.zhiyi-graph-body { flex: 1; display: flex; overflow: hidden; }
|
||
.zhiyi-graph-entity-list { width: 160px; border-right: 1px solid var(--background-modifier-border); overflow-y: auto; padding: 4px 0; flex-shrink: 0; }
|
||
.zhiyi-graph-entity-list h4 { margin: 0; padding: 4px 8px; font-size: 11px; color: var(--text-muted); font-weight: 600; border-bottom: 1px solid var(--background-modifier-border); }
|
||
.zhiyi-entity-item { padding: 4px 8px; font-size: 11px; cursor: pointer; color: var(--text-normal); display: flex; justify-content: space-between; align-items: center; }
|
||
.zhiyi-entity-item:hover { background: var(--background-modifier-hover); }
|
||
.zhiyi-entity-item.active { color: var(--text-accent); background: var(--background-modifier-hover); }
|
||
.zhiyi-entity-score { font-size: 9px; color: var(--text-faint); }
|
||
.zhiyi-graph-canvas { flex: 1; position: relative; overflow: hidden; }
|
||
.zhiyi-graph-canvas svg { width: 100%; height: 100%; }
|
||
.zhiyi-graph-detail { position: absolute; bottom: 0; left: 0; right: 0; background: var(--background-secondary); border-top: 1px solid var(--background-modifier-border); padding: 8px 12px; font-size: 11px; max-height: 120px; overflow-y: auto; }
|
||
.zhiyi-graph-detail-title { font-weight: 600; margin-bottom: 4px; }
|
||
.zhiyi-graph-node-label { font-size: 10px; fill: var(--text-muted); pointer-events: none; }
|
||
.zhiyi-legend { position: absolute; top: 8px; right: 8px; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; padding: 6px 8px; font-size: 10px; }
|
||
.zhiyi-legend-item { display: flex; align-items: center; gap: 4px; margin: 2px 0; }
|
||
.zhiyi-legend-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
|
||
.zhiyi-tooltip { position: absolute; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; padding: 6px 8px; font-size: 11px; pointer-events: none; opacity: 0; transition: opacity 0.15s; max-width: 200px; z-index: 10; }
|
||
` });
|
||
|
||
const root = this.container.createEl("div", { cls: "zhiyi-graph-view" });
|
||
const toolbar = root.createEl("div", { cls: "zhiyi-graph-toolbar" });
|
||
|
||
const searchInput = toolbar.createEl("input", {
|
||
attr: { placeholder: "输入实体名称,回车查看 ego-network(如: 牧尘)" }
|
||
}) as HTMLInputElement;
|
||
|
||
const loadBtn = toolbar.createEl("button", { text: "加载图谱" });
|
||
toolbar.createEl("span", { cls: "info", text: "点击节点查看详情" });
|
||
const topBtn = toolbar.createEl("button", { text: "Top 节点" });
|
||
const reloadEntitiesBtn = toolbar.createEl("button", { text: "刷新列表" });
|
||
|
||
const body = root.createEl("div", { cls: "zhiyi-graph-body" });
|
||
|
||
// 实体列表侧边栏
|
||
const entityList = body.createEl("div", { cls: "zhiyi-graph-entity-list" });
|
||
entityList.createEl("h4", { text: "📊 Top 实体" });
|
||
const entityListBody = entityList.createEl("div", { cls: "zhiyi-graph-entity-list-body" });
|
||
|
||
const canvas = body.createEl("div", { cls: "zhiyi-graph-canvas" });
|
||
const tooltip = canvas.createEl("div", { cls: "zhiyi-tooltip" });
|
||
const legendEl = canvas.createEl("div", { cls: "zhiyi-legend" });
|
||
legendEl.innerHTML = `
|
||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#4a9eff"></span> 默认</div>
|
||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#f6c945"></span> 人物</div>
|
||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#34c759"></span> 项目</div>
|
||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#ff6b6b"></span> 事件</div>
|
||
`;
|
||
|
||
const detail = root.createEl("div", { cls: "zhiyi-graph-detail", attr: { style: "display:none" } });
|
||
const detailTitle = detail.createEl("div", { cls: "zhiyi-graph-detail-title" });
|
||
const detailContent = detail.createEl("div", { cls: "zhiyi-graph-detail-content" });
|
||
|
||
this.d3 = await loadD3();
|
||
this.svg = this.d3.select(canvas.createEl("svg"));
|
||
await this.renderGlobalGraph();
|
||
await this.loadEntityList(entityListBody);
|
||
|
||
const renderEgo = async (entity: string) => {
|
||
searchInput.value = entity;
|
||
await this.renderEgoGraph(entity, canvas, tooltip, detail, detailTitle, detailContent);
|
||
// 高亮列表中的活动实体
|
||
entityListBody.querySelectorAll(".zhiyi-entity-item").forEach(el => {
|
||
el.classList.toggle("active", (el as HTMLElement).dataset.entity === entity);
|
||
});
|
||
};
|
||
|
||
loadBtn.onclick = async () => {
|
||
if (searchInput.value.trim()) await renderEgo(searchInput.value.trim());
|
||
};
|
||
searchInput.onkeydown = async (e) => {
|
||
if (e.key === "Enter" && searchInput.value.trim()) await renderEgo(searchInput.value.trim());
|
||
};
|
||
topBtn.onclick = async () => {
|
||
try {
|
||
const data = await fetchPageRank(20);
|
||
const topEntity = data.pagerank?.[0]?.entity || "牧尘";
|
||
await renderEgo(topEntity);
|
||
} catch (_) {}
|
||
};
|
||
reloadEntitiesBtn.onclick = async () => {
|
||
await this.loadEntityList(entityListBody);
|
||
};
|
||
}
|
||
|
||
private async loadEntityList(container: HTMLElement) {
|
||
try {
|
||
const data = await fetchPageRank(30);
|
||
this.topEntities = data.pagerank || [];
|
||
container.empty();
|
||
if (this.topEntities.length === 0) {
|
||
container.createEl("div", { text: "暂无数据", attrs: { style: "padding:8px;font-size:11px;color:var(--text-muted)" } });
|
||
return;
|
||
}
|
||
for (const item of this.topEntities) {
|
||
const row = container.createEl("div", { cls: "zhiyi-entity-item", attr: { "data-entity": item.entity } });
|
||
row.createEl("span", { text: item.entity.length > 14 ? item.entity.slice(0, 14) + "…" : item.entity });
|
||
row.createEl("span", { cls: "zhiyi-entity-score", text: item.score.toFixed(2) });
|
||
row.onclick = async () => {
|
||
const toolbar = this.container.querySelector(".zhiyi-graph-toolbar") as HTMLElement;
|
||
const searchInput = toolbar?.querySelector("input") as HTMLInputElement;
|
||
if (searchInput) {
|
||
searchInput.value = item.entity;
|
||
await this.renderEgoGraph(item.entity, null as unknown as HTMLElement, null as unknown as HTMLElement, this.container.querySelector(".zhiyi-graph-detail") as HTMLElement, this.container.querySelector(".zhiyi-graph-detail-title") as HTMLElement, this.container.querySelector(".zhiyi-graph-detail-content") as HTMLElement);
|
||
}
|
||
container.querySelectorAll(".zhiyi-entity-item").forEach(el => el.classList.remove("active"));
|
||
row.classList.add("active");
|
||
};
|
||
}
|
||
} catch {
|
||
container.empty();
|
||
container.createEl("div", { text: "加载失败", attrs: { style: "padding:8px;font-size:11px;color:var(--text-muted)" } });
|
||
}
|
||
}
|
||
|
||
private async renderGlobalGraph() {
|
||
try {
|
||
const ns = getRuntimeNamespace();
|
||
const data = await fetchGraphExport(ns, 80);
|
||
await this.renderD3Graph(data.nodes, data.edges, null);
|
||
} catch (_) {}
|
||
}
|
||
|
||
private async renderEgoGraph(
|
||
entity: string,
|
||
canvas: HTMLElement,
|
||
tooltip: HTMLElement,
|
||
detail: HTMLElement,
|
||
detailTitle: HTMLElement,
|
||
detailContent: HTMLElement
|
||
) {
|
||
this.currentEntity = entity;
|
||
this.simulation?.stop();
|
||
try {
|
||
const [graphData, memData] = await Promise.all([
|
||
fetchNeighbors(entity),
|
||
fetchByEntity(entity),
|
||
]);
|
||
const central: GraphNode = { id: entity, label: entity };
|
||
const nodes = [central, ...graphData.nodes.filter(n => n.id !== entity)];
|
||
await this.renderD3Graph(nodes, graphData.edges, entity);
|
||
|
||
detail.style.display = "block";
|
||
detailTitle.setText(`📌 ${entity}`);
|
||
const mems = (memData.memories || []).slice(0, 5);
|
||
detailContent.innerHTML = mems.length > 0
|
||
? mems.map((m: MemoryRecord) => `<div style="margin:2px 0">• ${this.truncate(m.content, 80)}</div>`).join("")
|
||
: "<div>无关联记忆</div>";
|
||
} catch (e) {
|
||
const errEl = canvas.createEl("div", { text: `加载失败: ${(e as Error).message}`, cls: "zhiyi-empty" });
|
||
setTimeout(() => errEl.remove(), 3000);
|
||
}
|
||
}
|
||
|
||
private async renderD3Graph(
|
||
nodes: GraphNode[],
|
||
edges: GraphEdge[],
|
||
centralId: string | null
|
||
) {
|
||
if (!this.d3 || !this.svg) return;
|
||
const d3 = this.d3;
|
||
const svg = this.svg;
|
||
svg.selectAll("*").remove();
|
||
|
||
const width = svg.node()!.clientWidth || 600;
|
||
const height = svg.node()!.clientHeight || 400;
|
||
|
||
const catColor: Record<string, string> = {
|
||
"人物": "#f6c945", "人物_name": "#f6c945", "project": "#34c759",
|
||
"项目": "#34c759", "event": "#ff6b6b", "事件": "#ff6b6b",
|
||
"concept": "#a855f7", "概念": "#a855f7", "location": "#06b6d4",
|
||
"distilled": "#4a9eff", "default": "#4a9eff"
|
||
};
|
||
|
||
const getColor = (n: GraphNode) => {
|
||
if (n.id === centralId) return "#ff4d4d";
|
||
if (n.category && catColor[n.category]) return catColor[n.category];
|
||
return catColor[n.weight !== undefined && n.weight > 5 ? "distilled" : "default"];
|
||
};
|
||
|
||
const simNodes: SimNode[] = nodes.map(n => ({
|
||
id: n.id, label: n.label || n.id,
|
||
category: n.category, weight: n.weight,
|
||
isCentral: n.id === centralId,
|
||
}));
|
||
|
||
const nodeMap = new Map(simNodes.map(n => [n.id, n]));
|
||
const simLinks: SimLink[] = edges
|
||
.filter(e => nodeMap.has(e.source) && nodeMap.has(e.target))
|
||
.map(e => ({ source: e.source, target: e.target, relation: e.relation, weight: e.weight }));
|
||
|
||
// 缩放
|
||
const zoom = d3.zoom<SVGSVGElement, unknown>()
|
||
.scaleExtent([0.2, 5])
|
||
.on("zoom", (event) => {
|
||
g.attr("transform", event.transform);
|
||
});
|
||
svg.call(zoom as unknown as (s: d3.Selection<SVGSVGElement, unknown, null, undefined>) => void);
|
||
|
||
const g = svg.append("g");
|
||
svg.append("defs").append("marker")
|
||
.attr("id", "arrowhead")
|
||
.attr("viewBox", "-0 -5 10 10")
|
||
.attr("refX", 15).attr("refY", 0)
|
||
.attr("orient", "auto")
|
||
.attr("markerWidth", 6).attr("markerHeight", 6)
|
||
.append("path").attr("d", "M 0,-5 L 10,0 L 0,5")
|
||
.attr("fill", "#666");
|
||
|
||
// 边(带关系标签)
|
||
const link = g.append("g").selectAll("line")
|
||
.data(simLinks)
|
||
.enter().append("line")
|
||
.attr("stroke", "#999").attr("stroke-opacity", 0.6)
|
||
.attr("stroke-width", d => Math.min(2, d.weight || 1))
|
||
.attr("marker-end", "url(#arrowhead)");
|
||
|
||
// 关系标签(居中显示)
|
||
const linkLabel = g.append("g").selectAll("text")
|
||
.data(simLinks)
|
||
.enter().append("text")
|
||
.text(d => d.relation || "")
|
||
.attr("text-anchor", "middle")
|
||
.attr("dy", -3)
|
||
.attr("font-size", "8px")
|
||
.attr("fill", "#999")
|
||
.attr("pointer-events", "none")
|
||
.style("display", d => d.relation ? "block" : "none");
|
||
|
||
const node = g.append("g").selectAll("g")
|
||
.data(simNodes)
|
||
.enter().append("g")
|
||
.style("cursor", "pointer");
|
||
|
||
node.append("circle")
|
||
.attr("r", d => d.isCentral ? 12 : 6 + (d.weight || 1) * 0.5)
|
||
.attr("fill", d => getColor(d as GraphNode))
|
||
.attr("stroke", d => d.isCentral ? "#ff4d4d" : "white")
|
||
.attr("stroke-width", d => d.isCentral ? 2 : 1.5);
|
||
|
||
node.append("text")
|
||
.text(d => d.label.length > 12 ? d.label.slice(0, 12) + "…" : d.label)
|
||
.attr("dy", -8)
|
||
.attr("text-anchor", "middle")
|
||
.attr("class", "zhiyi-graph-node-label")
|
||
.style("font-size", d => d.isCentral ? "11px" : "9px")
|
||
.style("fill", "var(--text-muted)");
|
||
|
||
// 拖拽
|
||
const drag = d3.drag<SVGGElement, SimNode>()
|
||
.on("start", (event, d) => {
|
||
if (!event.active) this.simulation!.alphaTarget(0.3).restart();
|
||
d.fx = d.x; d.fy = d.y;
|
||
})
|
||
.on("drag", (event, d) => { d.fx = event.x; d.fy = event.y; })
|
||
.on("end", (event, d) => {
|
||
if (!event.active) this.simulation!.alphaTarget(0);
|
||
d.fx = null; d.fy = null;
|
||
});
|
||
node.call(drag as unknown as (s: d3.Selection<SVGGElement, SimNode, SVGGElement, unknown>) => void);
|
||
|
||
// 点击节点 → ego 图
|
||
node.on("click", (_event, d) => {
|
||
if (d.id === this.currentEntity) return;
|
||
const toolbar = this.container.querySelector(".zhiyi-graph-toolbar") as HTMLElement;
|
||
const searchInput = toolbar?.querySelector("input") as HTMLInputElement;
|
||
if (searchInput) {
|
||
searchInput.value = d.id;
|
||
this.renderEgoGraph(d.id,
|
||
this.container.querySelector(".zhiyi-graph-canvas") as HTMLElement,
|
||
this.container.querySelector(".zhiyi-tooltip") as HTMLElement,
|
||
this.container.querySelector(".zhiyi-graph-detail") as HTMLElement,
|
||
this.container.querySelector(".zhiyi-graph-detail-title") as HTMLElement,
|
||
this.container.querySelector(".zhiyi-graph-detail-content") as HTMLElement);
|
||
}
|
||
const entityListBody = this.container.querySelector(".zhiyi-graph-entity-list-body") as HTMLElement;
|
||
entityListBody?.querySelectorAll(".zhiyi-entity-item").forEach(el => {
|
||
el.classList.toggle("active", (el as HTMLElement).dataset.entity === d.id);
|
||
});
|
||
});
|
||
|
||
node.on("mouseover", (event, d) => {
|
||
tooltip.style.opacity = "1";
|
||
tooltip.style.left = (event.offsetX + 10) + "px";
|
||
tooltip.style.top = (event.offsetY - 10) + "px";
|
||
tooltip.setText(`${d.label}${d.weight !== undefined ? ` (×${d.weight})` : ""}`);
|
||
});
|
||
|
||
node.on("mouseout", () => { tooltip.style.opacity = "0"; });
|
||
|
||
this.simulation = d3.forceSimulation(simNodes)
|
||
.force("link", d3.forceLink<SimNode, SimLink>(simLinks).id(d => d.id).distance(80))
|
||
.force("charge", d3.forceManyBody().strength(-200))
|
||
.force("center", d3.forceCenter(width / 2, height / 2))
|
||
.force("collision", d3.forceCollide(20))
|
||
.on("tick", () => {
|
||
link
|
||
.attr("x1", d => (d.source as SimNode).x!)
|
||
.attr("y1", d => (d.source as SimNode).y!)
|
||
.attr("x2", d => (d.target as SimNode).x!)
|
||
.attr("y2", d => (d.target as SimNode).y!);
|
||
linkLabel
|
||
.attr("x", d => ((d.source as SimNode).x! + (d.target as SimNode).x!) / 2)
|
||
.attr("y", d => ((d.source as SimNode).y! + (d.target as SimNode).y!) / 2);
|
||
node.attr("transform", d => `translate(${d.x},${d.y})`);
|
||
});
|
||
}
|
||
|
||
private truncate(s: string, max: number) {
|
||
if (!s) return "";
|
||
return s.length > max ? s.slice(0, max) + "…" : s;
|
||
}
|
||
} |