Skip to content

World's first open-source enterprise world model.

One canvas, drawn once (#499)

WaylandYang360108979152
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index c01b8d6f..b294a290 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -14,19 +14,11 @@ import { circular, circlepack } from "graphology-layout";
import forceAtlas2 from "graphology-layout-forceatlas2";
import FA2Layout from "graphology-layout-forceatlas2/worker";
import Sigma from "sigma";
-import { createNodeBorderProgram } from "@sigma/node-border";
import EdgeCurveProgram from "@sigma/edge-curve";
-import { NodeSquareShellProgram } from "./squareShellProgram";
import {
- drawHoverCard,
- CANVAS_FONT,
- CANVAS_LABEL_SIZE,
- CANVAS_TEXT,
- CANVAS_TEXT_2,
- drawNodeLabel,
drawWorldGrid,
- hexToRgb,
HOVER_MUTE,
+ lerpColor,
mix,
MUTED_SHELL,
NODE_BORDER_BASE,
@@ -34,10 +26,21 @@ import {
NODE_CORE_MIX,
NODE_SHELL_BASE,
NODE_TINT_MIX,
- RING_HOVER_MIX,
- RING_SELECT_MIX,
TRANSPARENT,
} from "./graphVisuals";
+// 画布那台机器是两页共用的(#496):构造选项、状态表、相机、拖拽都在那边,
+// 这个文件只管把实例与事实投影成一张图、说清楚每个节点是什么颜色
+import {
+ attachDrag,
+ hoveredNode,
+ mutedNode,
+ neighborNode,
+ NODE_TYPE_SHELL,
+ NODE_TYPE_SQUARE,
+ selectedNode,
+ sigmaOptions,
+ softMutedNode,
+} from "./graphCanvas";
import { EntityHistory } from "./EntityHistory";
import { EntityDialog, FactTimeDialog } from "./graphDialogs";
import { fmtTime } from "../time";
@@ -237,23 +240,6 @@ const EDGE_FOCUS_DERIVED = "rgba(255,214,140,0.95)";
const DAY_MS = 24 * 3600 * 1000;
/* 播放淡入:解析 hex / rgb / rgba(含 alpha)并线性插值 */
-function parseRgba(c: string): [number, number, number, number] {
- if (c.startsWith("#")) {
- const [r, g, b] = hexToRgb(c);
- return [r, g, b, 1];
- }
- const m = c.match(
- /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/,
- );
- if (!m) return [128, 128, 128, 1];
- return [+m[1], +m[2], +m[3], m[4] !== undefined ? +m[4] : 1];
-}
-function lerpColor(from: string, to: string, t: number): string {
- const a = parseRgba(from);
- const b = parseRgba(to);
- const f = (i: number) => a[i] + (b[i] - a[i]) * t;
- return `rgba(${Math.round(f(0))},${Math.round(f(1))},${Math.round(f(2))},${f(3).toFixed(3)})`;
-}
/** 播放中新元素的淡入时长 */
const FADE_MS = 320;
@@ -701,7 +687,7 @@ export function Graph() {
typeColor: n.color,
typeLabel: n.type_label ?? S.graph.untyped,
typeKey: n.type_key ?? "",
- type: n.shape === "square" ? "square" : "shell",
+ type: n.shape === "square" ? NODE_TYPE_SQUARE : NODE_TYPE_SHELL,
size: 5 + Math.min(8, Math.sqrt(Number(n.degree)) * 1.6),
});
}
@@ -837,98 +823,27 @@ export function Graph() {
sigmaRef.current?.kill();
const sigma = new Sigma(g, containerRef.current, {
- allowInvalidContainer: true,
- defaultNodeType: "shell",
- nodeProgramClasses: {
- // Semantica 节点解剖:状态环 → 描边 → 深色壳 → 微彩核心
- shell: createNodeBorderProgram({
- borders: [
- { size: { value: 0.1 }, color: { attribute: "ringColor" } },
- { size: { value: 0.07 }, color: { attribute: "borderColor" } },
- { size: { value: 0.3 }, color: { attribute: "shellColor" } },
- { size: { fill: true }, color: { attribute: "color" } },
- ],
- }),
- square: NodeSquareShellProgram,
- },
- renderEdgeLabels: true,
- defaultEdgeType: "line",
- /* 平行边扇成弧(见 `layOutParallelEdges`)。直线那一版把同一对节点之间
- 的每条边画在同一条线段上,于是几个标签逐字符叠成乱码——实测一对节点
- 之间最多压着六条 */
- edgeProgramClasses: { curved: EdgeCurveProgram },
- // 边的悬停事件默认是关的。开它是为了 `enterEdge`:并进去的那些说法
- // 要有地方看得见(见 edgeReducer)
- enableEdgeEvents: true,
- labelFont: CANVAS_FONT,
- labelSize: CANVAS_LABEL_SIZE,
- labelColor: { color: CANVAS_TEXT },
- /* 标签按距离出没——离得远只看形状,走近了才认名字。**试过不按距离**
- (阈值归零、只按拥挤程度筛):缩远之后一百多个名字铺开互相压字,
- 读不出也点不准。
- 阈值 5、每 130px 见方留 0.8 个:只比原先松半档。**放宽到 3 / 1.2 试过
- 一轮,一屏上百个名字铺开,太吵**——这里要的是「远处认得出几个地标」,
- 不是「每个点都报名字」。放大时 sigma 自己按 1/ratio² 放开这个上限
- (见 `getLabelsToDisplay`),越走近露得越全,不封顶 */
- labelRenderedSizeThreshold: 5,
- labelDensity: 0.8,
- labelGridCellSize: 130,
- minCameraRatio: 0.04,
- maxCameraRatio: 8,
- /* 边的字与节点同一档(fine)、同一个次要色。从前是 9px/#a1a1a1——
- 9 比界面里最小的字还小一半,而 #a1a1a1 是上一版的 ink-2 */
- edgeLabelSize: CANVAS_LABEL_SIZE,
- edgeLabelColor: { color: CANVAS_TEXT_2 },
- edgeLabelFont: CANVAS_FONT,
- defaultDrawNodeLabel: drawNodeLabel,
- defaultDrawNodeHover: drawHoverCard,
+ ...sigmaOptions({
+ defaultEdgeType: "line",
+ /* 平行边扇成弧(见 `layOutParallelEdges`)。直线那一版把同一对节点
+ 之间的每条边画在同一条线段上,于是几个标签逐字符叠成乱码——实测
+ 一对节点之间最多压着六条 */
+ edgeProgramClasses: { curved: EdgeCurveProgram },
+ // 边上写的是谓词,近距离下每条画得出来的边都写(见 updateEdgeLabels)
+ renderEdgeLabels: true,
+ // 上千个节点,得缩得比本体页更远才看得见全貌
+ minCameraRatio: 0.04,
+ maxCameraRatio: 8,
+ }),
nodeReducer: (node, attrs) => {
const f = filterRef.current;
const res = { ...attrs };
const base = attrs.size as number;
- // 状态环取节点自己的类型色(见 RING_*_MIX 处的理由)
- const ownColor = (attrs.typeColor as string) ?? NODE_CORE_BASE;
if (f.hiddenTypes.has(attrs.typeKey as string)) {
res.hidden = true;
return res;
}
- // Semantica 状态表: muted { ×0.52, 全层压暗 }
- const muteNode = () => {
- res.size = base * 0.52;
- res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3);
- res.shellColor = MUTED_SHELL;
- res.borderColor = TRANSPARENT;
- res.ringColor = TRANSPARENT;
- res.label = "";
- res.zIndex = 0;
- };
- /* 悬停时其余的按 HOVER_MUTE 压一档(选中是压到底)。
- 邻居不压——悬停要回答的是"它连着谁",把邻居也压掉就等于没回答 */
- const softMute = () => {
- res.size = base * (1 - 0.48 * HOVER_MUTE);
- res.color = lerpColor(
- String(attrs.color ?? NODE_CORE_BASE),
- mix(MUTED_SHELL, NODE_CORE_BASE, 0.3),
- HOVER_MUTE,
- );
- res.shellColor = lerpColor(
- String(attrs.shellColor ?? NODE_SHELL_BASE),
- MUTED_SHELL,
- HOVER_MUTE,
- );
- res.borderColor = TRANSPARENT;
- res.ringColor = TRANSPARENT;
- res.label = "";
- res.zIndex = 0;
- };
- if (hoverRef.current === node) {
- res.size = Math.max(base * 1.08, 10.4);
- res.ringColor = mix(ownColor, "#ffffff", RING_HOVER_MIX);
- // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题)
- res.hideBaseLabel = true;
- res.zIndex = 4;
- return res;
- }
+ if (hoverRef.current === node) return hoveredNode(res, attrs, base);
const hov = hoverRef.current;
// 选中实体可能不在当前画布(侧栏跳转/邻域重载间隙)——不在则跳过聚焦压暗逻辑
const sel =
@@ -936,39 +851,24 @@ export function Graph() {
? selectedRef.current
: null;
if (sel) {
- if (node === sel) {
- res.size = Math.max(base * 1.02, 9.2);
- res.ringColor = mix(ownColor, "#ffffff", RING_SELECT_MIX);
- res.forceLabel = true;
- // 选中的那一个补一块底:其余都压暗了,它得读得最清楚
- res.labelSlab = true;
- res.zIndex = 3;
- return res;
- }
- if (g.areNeighbors(sel, node)) {
- // neighbor {×0.76, min 4, zIndex 2}
- res.size = Math.max(base * 0.76, 4);
- res.zIndex = 2;
- } else {
- muteNode();
- return res;
- }
+ if (node === sel) return selectedNode(res, attrs, base);
+ // 邻居收到 0.76:上千个节点,得给选中的那一条路让地方
+ if (g.areNeighbors(sel, node)) neighborNode(res, base, 0.76);
+ else return mutedNode(res, base);
} else if (hov && hov !== node && !g.areNeighbors(hov, node)) {
// **悬停也压暗其余**,只是比选中轻一档(见 HOVER_MUTE)。
// 邻居留着:悬停要回答的正是"它连着谁"。
// **此刻还不存在的节点直接压到底**:这个分支会提前 return,
// 绕过下面那道时间过滤,只压一半的话它反而比不 hover 时更亮
- if (f.activeNodes && !f.activeNodes.has(node)) muteNode();
- else softMute();
- return res;
+ if (f.activeNodes && !f.activeNodes.has(node))
+ return mutedNode(res, base);
+ return softMutedNode(res, attrs, base);
} else {
// default {×0.7}
res.size = base * 0.7;
}
- if (f.activeNodes && !f.activeNodes.has(node)) {
- muteNode();
- return res;
- }
+ if (f.activeNodes && !f.activeNodes.has(node))
+ return mutedNode(res, base);
// 播放淡入:从 muted 形态渐变到本帧算出的正常形态
const fs = fadeRef.current.get(node);
if (fs !== undefined) {
@@ -1212,44 +1112,26 @@ export function Graph() {
//(否则纯点选也会误启 FA2);被拖节点由 fa2 的 outputReducer 钉在光标上(见上),
// 松手后稳定 ~1.2s 停机
let settleTimer: ReturnType<typeof setTimeout> | null = null;
- let dragCandidate: string | null = null;
- let downPoint: { x: number; y: number } | null = null;
- sigma.on("downNode", (e) => {
- dragCandidate = e.node;
- downPoint = { x: e.event.x, y: e.event.y };
- });
- sigma.getMouseCaptor().on("mousemovebody", (e) => {
- if (!dragCandidate) return;
- if (!dragged) {
- if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4)
- return;
- // 升格为拖拽
- dragged = dragCandidate;
+ // 阈值、包围盒冻结那一套在 attachDrag 里;这里只接三个当口。
+ // `dragged` 仍留在这个闭包里——FA2 的 outputReducer 每帧读它,
+ // 把被拖的那个钉回光标(见上面 fa2 的构造)
+ attachDrag(sigma, {
+ onStart: (node) => {
+ dragged = node;
if (settleTimer) clearTimeout(settleTimer);
// 静态布局(circular/pack)下拖拽不唤醒力模拟——否则一碰就散架
if (layoutModeRef.current === "force" && fa2 && !fa2.isRunning())
fa2.start();
- // 固定当前包围盒,避免拖拽时相机自动跟随缩放
- if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
- }
- const pos = sigma.viewportToGraph(e);
- dragPos = pos;
- g.setNodeAttribute(dragged, "x", pos.x);
- g.setNodeAttribute(dragged, "y", pos.y);
- // 阻止相机平移
- e.preventSigmaDefault();
- e.original.preventDefault();
- e.original.stopPropagation();
+ },
+ onMove: (_node, pos) => {
+ dragPos = pos;
+ },
+ onEnd: () => {
+ dragged = null;
+ dragPos = null;
+ settleTimer = setTimeout(() => fa2?.stop(), 1200);
+ },
});
- const endDrag = () => {
- dragCandidate = null;
- downPoint = null;
- if (!dragged) return;
- dragged = null;
- dragPos = null;
- settleTimer = setTimeout(() => fa2?.stop(), 1200);
- };
- sigma.getMouseCaptor().on("mouseup", endDrag);
sigmaRef.current = sigma;
if (import.meta.env.DEV) {
// 调试句柄(仅 dev):无头环境下检查 reducer 输出
diff --git a/web/src/pages/OntologySchemaGraph.tsx b/web/src/pages/OntologySchemaGraph.tsx
index 2862ddaa..c82a875a 100644
--- a/web/src/pages/OntologySchemaGraph.tsx
+++ b/web/src/pages/OntologySchemaGraph.tsx
@@ -24,29 +24,34 @@ import Graphology from "graphology";
import { circular } from "graphology-layout";
import forceAtlas2 from "graphology-layout-forceatlas2";
import Sigma from "sigma";
-import { createNodeBorderProgram } from "@sigma/node-border";
import { EdgeArrowProgram, EdgeLineProgram } from "sigma/rendering";
import EdgeCurveProgram, { EdgeCurvedArrowProgram } from "@sigma/edge-curve";
-import { NodeSquareShellProgram } from "./squareShellProgram";
import {
- drawHoverCard,
- CANVAS_FONT,
- CANVAS_LABEL_SIZE,
- CANVAS_TEXT,
- CANVAS_TEXT_2,
- drawNodeLabel,
drawWorldGrid,
mix,
- MUTED_SHELL,
NODE_BORDER_BASE,
NODE_CORE_BASE,
NODE_CORE_MIX,
NODE_SHELL_BASE,
NODE_TINT_MIX,
- RING_HOVER_MIX,
RING_SELECT_MIX,
TRANSPARENT,
} from "./graphVisuals";
+// 画布那台机器是两页共用的(#496):构造选项、状态表、相机、拖拽都在那边,
+// 这个文件只管把本体投影成一张图、说清楚每个节点是什么颜色
+import {
+ attachDrag,
+ focusNode,
+ hoveredNode,
+ mutedNode,
+ neighborNode,
+ nodeInView,
+ NODE_TYPE_SHELL,
+ NODE_TYPE_SQUARE,
+ ownColorOf,
+ selectedNode,
+ sigmaOptions,
+} from "./graphCanvas";
import { Maximize2, X, ZoomIn, ZoomOut } from "lucide-react";
import type { BusinessRule, EntityTypeView, RelationTypeView } from "../api";
import { S } from "../i18n";
@@ -256,7 +261,7 @@ export function buildSchemaGraph(
ringColor: TRANSPARENT,
typeColor: t.color,
typeLabel: t.key,
- type: t.shape === "square" ? "square" : "circle",
+ type: t.shape === "square" ? NODE_TYPE_SQUARE : NODE_TYPE_SHELL,
key: t.key,
});
}
@@ -517,47 +522,6 @@ function seedFreshNodes(
return total;
}
-/** 相机推过去时最多放大到这个比例;已经比它更近就保持——从左栏挨个点类
- * 看下去时,画面不该每点一下就重新缩放 */
-const FOCUS_MAX_RATIO = 0.5;
-/** 视口四边留的边距:贴着边的节点也算看不见(右侧还有停靠的面板压着) */
-const IN_VIEW_MARGIN = 48;
-
-function nodePosition(sigma: Sigma, id: string): Point {
- const graph = sigma.getGraph();
- return {
- x: graph.getNodeAttribute(id, "x") as number,
- y: graph.getNodeAttribute(id, "y") as number,
- };
-}
-
-/** 节点此刻是否在视口里(按上一次渲染的相机算) */
-function nodeInView(sigma: Sigma, id: string): boolean {
- const { x, y } = sigma.graphToViewport(nodePosition(sigma, id));
- const { width, height } = sigma.getDimensions();
- return (
- x >= IN_VIEW_MARGIN &&
- x <= width - IN_VIEW_MARGIN &&
- y >= IN_VIEW_MARGIN &&
- y <= height - IN_VIEW_MARGIN
- );
-}
-
-/** 相机推到一个节点上。sigma 的相机坐标是归一化到 [0,1] 的「框内」坐标,
- * 不是图坐标——直接喂图坐标(x 动辄几百)相机会飞出画面几万像素,画布
- * 一片空白。sigma 没有公开的图→框内换算,绕一趟视口:graphToViewport 用的
- * 是上一次渲染的矩阵,与 viewportToFramedGraph 用同一台相机,一来一回把
- * 相机抵消掉,剩下的就是框内坐标 */
-function focusNode(sigma: Sigma, id: string): void {
- if (!sigma.getGraph().hasNode(id)) return;
- const framed = sigma.viewportToFramedGraph(
- sigma.graphToViewport(nodePosition(sigma, id)),
- );
- const ratio = Math.min(sigma.getCamera().ratio, FOCUS_MAX_RATIO);
- sigma
- .getCamera()
- .animate({ x: framed.x, y: framed.y, ratio }, { duration: 300 });
-}
export type SchemaSelection =
| { kind: "class"; id: string }
@@ -703,103 +667,42 @@ export function OntologySchemaGraph({
sigmaRef.current?.kill();
const sigma = new Sigma(g, containerRef.current, {
- allowInvalidContainer: true,
- defaultNodeType: "circle",
- nodeProgramClasses: {
- // 与 /graph 同一套「状态环 → 描边 → 深色壳 → 微彩核心」四层解剖
- circle: createNodeBorderProgram({
- borders: [
- { size: { value: 0.1 }, color: { attribute: "ringColor" } },
- { size: { value: 0.07 }, color: { attribute: "borderColor" } },
- { size: { value: 0.3 }, color: { attribute: "shellColor" } },
- { size: { fill: true }, color: { attribute: "color" } },
- ],
- }),
- square: NodeSquareShellProgram,
- },
- defaultEdgeType: EDGE_TYPE_ARROW,
- edgeProgramClasses: {
- [EDGE_TYPE_ARROW]: EdgeArrowProgram,
- [EDGE_TYPE_LINE]: EdgeLineProgram,
- [EDGE_TYPE_CURVED_ARROW]: EdgeCurvedArrowProgram,
- [EDGE_TYPE_CURVED_LINE]: EdgeCurveProgram,
- },
- enableEdgeEvents: true,
- minEdgeThickness: MIN_EDGE_THICKNESS,
- labelFont: CANVAS_FONT,
- labelSize: CANVAS_LABEL_SIZE,
- labelColor: { color: CANVAS_TEXT },
- /* 标签按距离出没——离得远只看形状,走近了才认名字。**试过不按距离**
- (阈值归零、只按拥挤程度筛):缩远之后一百多个名字铺开互相压字,
- 读不出也点不准。
- 阈值 5、每 130px 见方留 0.8 个:只比原先松半档。**放宽到 3 / 1.2 试过
- 一轮,一屏上百个名字铺开,太吵**——这里要的是「远处认得出几个地标」,
- 不是「每个点都报名字」。放大时 sigma 自己按 1/ratio² 放开这个上限
- (见 `getLabelsToDisplay`),越走近露得越全,不封顶 */
- labelRenderedSizeThreshold: 5,
- labelDensity: 0.8,
- labelGridCellSize: 130,
- minCameraRatio: 0.05,
- maxCameraRatio: 6,
- edgeLabelSize: CANVAS_LABEL_SIZE,
- // 与 /graph 的边标签同一个灰;只有关系边挂标签,有字的就是关系边
- edgeLabelColor: { color: CANVAS_TEXT_2 },
- edgeLabelFont: CANVAS_FONT,
- defaultDrawNodeLabel: drawNodeLabel,
- defaultDrawNodeHover: drawHoverCard,
+ ...sigmaOptions({
+ defaultEdgeType: EDGE_TYPE_ARROW,
+ edgeProgramClasses: {
+ [EDGE_TYPE_ARROW]: EdgeArrowProgram,
+ [EDGE_TYPE_LINE]: EdgeLineProgram,
+ [EDGE_TYPE_CURVED_ARROW]: EdgeCurvedArrowProgram,
+ [EDGE_TYPE_CURVED_LINE]: EdgeCurveProgram,
+ },
+ minEdgeThickness: MIN_EDGE_THICKNESS,
+ // 几十上百个类,缩到 0.05 就看得见全貌;实例图动辄上千,那边缩得更远
+ minCameraRatio: 0.05,
+ maxCameraRatio: 6,
+ }),
nodeReducer: (node, attrs) => {
const res = { ...attrs };
const base = attrs.size as number;
const sel = selectedRef.current;
const hov = hoverRef.current;
- // 环取节点自己的类型色,不取已经混过壳色的 color——见 graphVisuals
- // 里 RING_*_MIX 的说明
- const ownColor = (attrs.typeColor as string) ?? NODE_CORE_BASE;
- const muteNode = () => {
- res.size = base * 0.55;
- res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3);
- res.shellColor = MUTED_SHELL;
- res.borderColor = TRANSPARENT;
- res.ringColor = TRANSPARENT;
- res.label = "";
- res.zIndex = 0;
- };
- if (hov === node) {
- res.size = Math.max(base * 1.08, 10.4);
- res.ringColor = mix(ownColor, "#ffffff", RING_HOVER_MIX);
- // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题)
- res.hideBaseLabel = true;
- res.zIndex = 4;
- return res;
- }
+ if (hov === node) return hoveredNode(res, attrs, base);
if (sel?.kind === "class" && g.hasNode(sel.id)) {
- if (node === sel.id) {
- res.size = Math.max(base * 1.02, 9.2);
- res.ringColor = mix(ownColor, "#ffffff", RING_SELECT_MIX);
- res.forceLabel = true;
- // 选中的那一个补一块底(同 /graph)
- res.labelSlab = true;
- res.zIndex = 3;
- return res;
- }
- if (g.areNeighbors(sel.id, node)) {
- res.zIndex = 2;
- return res;
- }
- muteNode();
- return res;
+ if (node === sel.id) return selectedNode(res, attrs, base);
+ // 邻居不收小:几十个类的图,收了显得瘫(实例图那边收到 0.76)
+ if (g.areNeighbors(sel.id, node)) return neighborNode(res, base);
+ return mutedNode(res, base);
}
if (sel?.kind === "relation") {
const rel = relationById.get(sel.id);
if (rel) {
+ // 选中一条关系,亮的是它的两端——类之间没有「邻居」可言,
+ // 这条关系的 domain 与 range 就是它连着的
const endpoints = new Set([...rel.domains, ...rel.ranges]);
if (endpoints.has(node)) {
- res.ringColor = mix(ownColor, "#ffffff", RING_SELECT_MIX);
- res.zIndex = 2;
- return res;
+ res.ringColor = mix(ownColorOf(attrs), "#ffffff", RING_SELECT_MIX);
+ return neighborNode(res, base);
}
- muteNode();
- return res;
+ return mutedNode(res, base);
}
}
return res;
@@ -897,55 +800,15 @@ export function OntologySchemaGraph({
// 拖节点。**没有活的力模拟要喂**——与 /graph 不同,这里的布局是一次性
// 算完就定住的,拖完往哪放就在哪,不会被力模拟拽回去,这正是「手动摆
- // 布局求清楚」要的效果。按下只记候选:位移超过阈值才升格成拖拽,
- // 否则一次纯点击也会被当成拖了 0 像素的拖拽,鼠标松手时机跟点选打架
- let dragCandidate: string | null = null;
- let downPoint: { x: number; y: number } | null = null;
- let dragged: string | null = null;
- sigma.on("downNode", (e) => {
- dragCandidate = e.node;
- downPoint = { x: e.event.x, y: e.event.y };
- });
- sigma.getMouseCaptor().on("mousemovebody", (e) => {
- if (!dragCandidate) return;
- if (!dragged) {
- if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4)
- return;
- dragged = dragCandidate;
- if (containerRef.current) containerRef.current.style.cursor = "grabbing";
- // 冻住此刻的包围盒:拖着拖着节点飞出画面边缘时,相机不该跟着自动
- // 缩放去「适应」新的包围盒——那样一拖节点全图就跟着抖
- if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
- }
- const pos = sigma.viewportToGraph(e);
- g.setNodeAttribute(dragged, "x", pos.x);
- g.setNodeAttribute(dragged, "y", pos.y);
+ // 布局求清楚」要的效果。阈值、包围盒冻结、光标那一套在 attachDrag 里
+ attachDrag(sigma, {
+ container: () => containerRef.current,
+ hovering: () => !!hoverRef.current,
// 边拖边记:万一中途出岔子(组件卸载、切换本体)也不丢这一手
- draggedPositionsRef.current.set(dragged, pos);
- positionsRef.current.set(dragged, pos);
- e.preventSigmaDefault();
- e.original.preventDefault();
- e.original.stopPropagation();
- });
- const endDrag = () => {
- dragCandidate = null;
- downPoint = null;
- if (!dragged) return;
- dragged = null;
- if (containerRef.current)
- containerRef.current.style.cursor = hoverRef.current ? "grab" : "";
- // 拖完把冻结的包围盒解开——「归位」要看得见刚挪过去的新位置,
- // 不能还按拖拽开始前的旧范围来适应
- sigma.setCustomBBox(null);
- };
- sigma.getMouseCaptor().on("mouseup", endDrag);
- // 悬停在节点上方给个「可以抓」的提示——发现得靠猜的交互等于没有
- sigma.on("enterNode", () => {
- if (containerRef.current && !dragged)
- containerRef.current.style.cursor = "grab";
- });
- sigma.on("leaveNode", () => {
- if (containerRef.current && !dragged) containerRef.current.style.cursor = "";
+ onMove: (node, pos) => {
+ draggedPositionsRef.current.set(node, pos);
+ positionsRef.current.set(node, pos);
+ },
});
// 关系标签只在放大后出现——本体大起来(导入包常有几十上百个类)时,
diff --git a/web/src/pages/graphCanvas.ts b/web/src/pages/graphCanvas.ts
new file mode 100644
index 00000000..30f78fa4
--- /dev/null
+++ b/web/src/pages/graphCanvas.ts
@@ -0,0 +1,335 @@
+// 两块画布共用的那台机器(#496)。
+//
+// `/graph` 画实例与事实,本体页画类与关系。它们的**数据**不共享,语义也不共享,
+// 但把数据变成一块能看能点的画布的那套东西是同一份:节点程序的四层解剖、标签
+// 何时出没、悬停卡、状态表、相机、拖拽。从前这些在两个文件里各写一遍,字面
+// 相同——连解释标签阈值为什么是 5 和 0.8 的那段注释都是逐字两份。代价不是行数,
+// 是**会走样**:压暗系数一边 0.52 一边 0.55,谁也不知道哪个是对的。
+//
+// 分界线:这个文件管「怎么画、怎么动」,页面管「画什么」。页面把自己的数据投影
+// 成一张 graphology 图,给每个节点一个类型色,再说清楚哪些该藏;其余的在这里。
+//
+// `graphVisuals.ts` 是上一轮抽出来的常量与绘制函数,这个文件建在它上面。
+
+import Sigma from "sigma";
+import type { Settings } from "sigma/settings";
+import { createNodeBorderProgram } from "@sigma/node-border";
+
+import { NodeSquareShellProgram } from "./squareShellProgram";
+import {
+ CANVAS_FONT,
+ CANVAS_LABEL_SIZE,
+ CANVAS_TEXT,
+ CANVAS_TEXT_2,
+ drawHoverCard,
+ drawNodeLabel,
+ HOVER_MUTE,
+ lerpColor,
+ mix,
+ MUTED_SHELL,
+ NODE_CORE_BASE,
+ NODE_SHELL_BASE,
+ RING_HOVER_MIX,
+ RING_SELECT_MIX,
+ TRANSPARENT,
+} from "./graphVisuals";
+
+/* ============ 节点程序 ============ */
+
+/** Semantica 节点解剖:状态环 → 描边 → 深色壳 → 微彩核心。
+ *
+ * 两页同一份。从前默认那一种在 `/graph` 叫 `shell`、在本体页叫 `circle`,
+ * 而它们是同一个 `createNodeBorderProgram`——两个名字说的是同一件事 */
+export const NODE_TYPE_SHELL = "shell";
+export const NODE_TYPE_SQUARE = "square";
+
+export const NODE_PROGRAMS = {
+ [NODE_TYPE_SHELL]: createNodeBorderProgram({
+ borders: [
+ { size: { value: 0.1 }, color: { attribute: "ringColor" } },
+ { size: { value: 0.07 }, color: { attribute: "borderColor" } },
+ { size: { value: 0.3 }, color: { attribute: "shellColor" } },
+ { size: { fill: true }, color: { attribute: "color" } },
+ ],
+ }),
+ [NODE_TYPE_SQUARE]: NodeSquareShellProgram,
+};
+
+/* ============ 构造选项 ============ */
+
+/** 两页真正不同的那几项。其余一律在 `sigmaOptions` 里定死——它们决定画布
+ * 长什么样、怎么响应,两页长得不一样就是 bug 而不是特性 */
+export interface CanvasOptions {
+ /** 边的类型名到程序的映射。`/graph` 只有直线与弧,本体页还要箭头 */
+ edgeProgramClasses: Settings["edgeProgramClasses"];
+ defaultEdgeType: string;
+ /** 相机能缩到多远、放到多近。两页的图规模差几个量级,取景范围本就不同 */
+ minCameraRatio: number;
+ maxCameraRatio: number;
+ /** 边上写不写字。`/graph` 的边是谓词,要写;本体页只有关系边写 */
+ renderEdgeLabels?: boolean;
+ minEdgeThickness?: number;
+}
+
+/** `new Sigma(g, el, { ...sigmaOptions(...), nodeReducer, edgeReducer })`。
+ *
+ * **两个 reducer 不从这里过。** sigma 的 reducer 类型跟着它自己的泛型参数走,
+ * 中转一手就把推断掐断了;而 reducer 的**内容**本就是两页各自的事,共用的是
+ * 它们调用的那张状态表(下一节),不是函数本身。
+ *
+ * 标签按距离出没——离得远只看形状,走近了才认名字。**试过不按距离**
+ * (阈值归零、只按拥挤程度筛):缩远之后一百多个名字铺开互相压字,读不出也
+ * 点不准。阈值 5、每 130px 见方留 0.8 个:只比原先松半档。**放宽到 3 / 1.2
+ * 试过一轮,一屏上百个名字铺开,太吵**——这里要的是「远处认得出几个地标」,
+ * 不是「每个点都报名字」。放大时 sigma 自己按 1/ratio² 放开这个上限
+ * (见 `getLabelsToDisplay`),越走近露得越全,不封顶。
+ *
+ * 边的字与节点同一档(fine)、同一个次要色。从前是 9px/#a1a1a1——9 比界面里
+ * 最小的字还小一半,而 #a1a1a1 是上一版的 ink-2。
+ *
+ * 边的悬停事件默认是关的,这里一律开:两页都靠 `enterEdge` 让边说话。 */
+export function sigmaOptions(o: CanvasOptions) {
+ return {
+ allowInvalidContainer: true,
+ defaultNodeType: NODE_TYPE_SHELL,
+ nodeProgramClasses: NODE_PROGRAMS,
+ edgeProgramClasses: o.edgeProgramClasses,
+ defaultEdgeType: o.defaultEdgeType,
+ enableEdgeEvents: true,
+ renderEdgeLabels: o.renderEdgeLabels ?? false,
+ ...(o.minEdgeThickness === undefined
+ ? {}
+ : { minEdgeThickness: o.minEdgeThickness }),
+ labelFont: CANVAS_FONT,
+ labelSize: CANVAS_LABEL_SIZE,
+ labelColor: { color: CANVAS_TEXT },
+ labelRenderedSizeThreshold: 5,
+ labelDensity: 0.8,
+ labelGridCellSize: 130,
+ minCameraRatio: o.minCameraRatio,
+ maxCameraRatio: o.maxCameraRatio,
+ edgeLabelSize: CANVAS_LABEL_SIZE,
+ edgeLabelColor: { color: CANVAS_TEXT_2 },
+ edgeLabelFont: CANVAS_FONT,
+ defaultDrawNodeLabel: drawNodeLabel,
+ defaultDrawNodeHover: drawHoverCard,
+ };
+}
+
+/* ============ 状态表 ============ */
+
+/** reducer 收到的属性袋与它要交回去的那一份。sigma 的类型在这一层是 `any`,
+ * 两页各自的属性键也不一样,所以这里只认「一袋东西」 */
+export type NodeAttrs = Record<string, unknown>;
+
+/** 状态环取节点**自己的类型色**,不取已经混过壳色的 `color`——见 graphVisuals
+ * 里 RING_*_MIX 的说明 */
+export function ownColorOf(attrs: NodeAttrs): string {
+ return (attrs.typeColor as string) ?? NODE_CORE_BASE;
+}
+
+/** 压到底:其余都退场,只留形状。
+ *
+ * 系数从前两页不一样,0.52 与 0.55,没有一处说明为什么。设计表里写的是 0.52,
+ * 这里按它统一——那个 0.55 是抄的时候走的样,不是谁定的 */
+export const MUTE_SCALE = 0.52;
+
+export function mutedNode(res: NodeAttrs, base: number): NodeAttrs {
+ res.size = base * MUTE_SCALE;
+ res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3);
+ res.shellColor = MUTED_SHELL;
+ res.borderColor = TRANSPARENT;
+ res.ringColor = TRANSPARENT;
+ res.label = "";
+ res.zIndex = 0;
+ return res;
+}
+
+/** 悬停时其余的按 `HOVER_MUTE` 压一档(选中是压到底)。
+ * 邻居不压——悬停要回答的是「它连着谁」,把邻居也压掉就等于没回答 */
+export function softMutedNode(
+ res: NodeAttrs,
+ attrs: NodeAttrs,
+ base: number,
+): NodeAttrs {
+ res.size = base * (1 - (1 - MUTE_SCALE) * HOVER_MUTE);
+ res.color = lerpColor(
+ String(attrs.color ?? NODE_CORE_BASE),
+ mix(MUTED_SHELL, NODE_CORE_BASE, 0.3),
+ HOVER_MUTE,
+ );
+ res.shellColor = lerpColor(
+ String(attrs.shellColor ?? NODE_SHELL_BASE),
+ MUTED_SHELL,
+ HOVER_MUTE,
+ );
+ res.borderColor = TRANSPARENT;
+ res.ringColor = TRANSPARENT;
+ res.label = "";
+ res.zIndex = 0;
+ return res;
+}
+
+/** 指着的那一个:×1.08,最小 10.4,偏白的环——为的是跳出来。
+ * 悬浮卡接管标签展示;`label` 本身保留,悬浮卡靠它渲染标题 */
+export function hoveredNode(
+ res: NodeAttrs,
+ attrs: NodeAttrs,
+ base: number,
+): NodeAttrs {
+ res.size = Math.max(base * 1.08, 10.4);
+ res.ringColor = mix(ownColorOf(attrs), "#ffffff", RING_HOVER_MIX);
+ res.hideBaseLabel = true;
+ res.zIndex = 4;
+ return res;
+}
+
+/** 选中的那一个:×1.02,最小 9.2,偏本色的环——为的是认得出。
+ * 再补一块底:其余都压暗了,它得读得最清楚 */
+export function selectedNode(
+ res: NodeAttrs,
+ attrs: NodeAttrs,
+ base: number,
+): NodeAttrs {
+ res.size = Math.max(base * 1.02, 9.2);
+ res.ringColor = mix(ownColorOf(attrs), "#ffffff", RING_SELECT_MIX);
+ res.forceLabel = true;
+ res.labelSlab = true;
+ res.zIndex = 3;
+ return res;
+}
+
+/** 选中的那一个的邻居。
+ *
+ * `scale` 两页不同,这一处是真的设计差别不是走样:`/graph` 上千个节点,
+ * 收到 0.76 是为了给选中的那一条路让地方;本体页几十个类,收了反而显得瘫 */
+export function neighborNode(
+ res: NodeAttrs,
+ base: number,
+ scale = 1,
+): NodeAttrs {
+ if (scale !== 1) res.size = Math.max(base * scale, 4);
+ res.zIndex = 2;
+ return res;
+}
+
+/* ============ 相机 ============ */
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+export function nodePosition(sigma: Sigma, id: string): Point {
+ const graph = sigma.getGraph();
+ return {
+ x: graph.getNodeAttribute(id, "x") as number,
+ y: graph.getNodeAttribute(id, "y") as number,
+ };
+}
+
+/** 节点此刻是否在视口里(按上一次渲染的相机算) */
+export function nodeInView(sigma: Sigma, id: string, margin = 48): boolean {
+ const { x, y } = sigma.graphToViewport(nodePosition(sigma, id));
+ const { width, height } = sigma.getDimensions();
+ return (
+ x >= margin && x <= width - margin && y >= margin && y <= height - margin
+ );
+}
+
+/** 相机推到一个节点上。sigma 的相机坐标是归一化到 [0,1] 的「框内」坐标,
+ * 不是图坐标——直接喂图坐标(x 动辄几百)相机会飞出画面几万像素,画布
+ * 一片空白。sigma 没有公开的图→框内换算,绕一趟视口:`graphToViewport` 用的
+ * 是上一次渲染的矩阵,与 `viewportToFramedGraph` 用同一台相机,一来一回把
+ * 相机抵消掉,剩下的就是框内坐标 */
+export function focusNode(sigma: Sigma, id: string, maxRatio = 0.5): void {
+ if (!sigma.getGraph().hasNode(id)) return;
+ const framed = sigma.viewportToFramedGraph(
+ sigma.graphToViewport(nodePosition(sigma, id)),
+ );
+ const ratio = Math.min(sigma.getCamera().ratio, maxRatio);
+ sigma
+ .getCamera()
+ .animate({ x: framed.x, y: framed.y, ratio }, { duration: 300 });
+}
+
+/* ============ 拖拽 ============ */
+
+/** 拖一个节点。**按下只记候选,位移超过阈值才升格成拖拽**——否则一次纯点击
+ * 也会被当成拖了 0 像素的拖拽,鼠标松手的时机跟点选打架。
+ *
+ * 升格的那一刻冻住包围盒:拖着拖着节点飞出画面边缘时,相机不该跟着自动缩放去
+ * 「适应」新的包围盒,那样一拖全图就跟着抖。松手再解开——「归位」要看得见刚
+ * 挪过去的新位置,不能还按拖拽开始前的旧范围来算。
+ *
+ * 两页对「拖动过程中还要做什么」的回答不同:`/graph` 要把光标位置喂进力模拟,
+ * 本体页要把位置记进它自己的坐标表。所以那两件事是回调,不在这里。 */
+export function attachDrag(
+ sigma: Sigma,
+ o: {
+ /** 升格成拖拽的那一刻。`/graph` 在这里唤醒力模拟 */
+ onStart?: (node: string) => void;
+ /** 每一帧的新位置。写进图的那两笔已经做过了 */
+ onMove?: (node: string, pos: Point) => void;
+ /** 松手。`/graph` 在这里安排力模拟停下 */
+ onEnd?: (node: string) => void;
+ /** 光标形状归谁管;不给就不动光标 */
+ container?: () => HTMLElement | null;
+ /** 悬停在节点上是不是「可以抓」的样子。本体页给,`/graph` 不给 */
+ hovering?: () => boolean;
+ } = {},
+): void {
+ const graph = sigma.getGraph();
+ let dragCandidate: string | null = null;
+ let downPoint: Point | null = null;
+ let dragged: string | null = null;
+ const cursor = (v: string) => {
+ const el = o.container?.();
+ if (el) el.style.cursor = v;
+ };
+
+ sigma.on("downNode", (e) => {
+ dragCandidate = e.node;
+ downPoint = { x: e.event.x, y: e.event.y };
+ });
+ sigma.getMouseCaptor().on("mousemovebody", (e) => {
+ if (!dragCandidate) return;
+ if (!dragged) {
+ if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4)
+ return;
+ dragged = dragCandidate;
+ cursor("grabbing");
+ if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
+ o.onStart?.(dragged);
+ }
+ const pos = sigma.viewportToGraph(e);
+ graph.setNodeAttribute(dragged, "x", pos.x);
+ graph.setNodeAttribute(dragged, "y", pos.y);
+ o.onMove?.(dragged, pos);
+ // 阻止相机跟着平移
+ e.preventSigmaDefault();
+ e.original.preventDefault();
+ e.original.stopPropagation();
+ });
+ const endDrag = () => {
+ dragCandidate = null;
+ downPoint = null;
+ if (!dragged) return;
+ const node = dragged;
+ dragged = null;
+ cursor(o.hovering?.() ? "grab" : "");
+ sigma.setCustomBBox(null);
+ o.onEnd?.(node);
+ };
+ sigma.getMouseCaptor().on("mouseup", endDrag);
+
+ // 悬停在节点上方给个「可以抓」的提示——发现得靠猜的交互等于没有
+ if (o.hovering) {
+ sigma.on("enterNode", () => {
+ if (!dragged) cursor("grab");
+ });
+ sigma.on("leaveNode", () => {
+ if (!dragged) cursor("");
+ });
+ }
+}
diff --git a/web/src/pages/graphVisuals.ts b/web/src/pages/graphVisuals.ts
index fb4390da..285935a4 100644
--- a/web/src/pages/graphVisuals.ts
+++ b/web/src/pages/graphVisuals.ts
@@ -68,6 +68,29 @@ export function mix(c1: string, c2: string, t: number): string {
return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`;
}
+/** rgb / rgba / #hex 都收,按 t 从 from 渐到 to,**alpha 也一起渐**。
+ *
+ * 与 `mix` 分工:那个只吃 hex、只管把类型色按比例调进壳色(节点的配方);
+ * 这个要处理边的 `rgba(...)` 与淡入淡出,两边都得能解析、alpha 不能丢 */
+function parseRgba(c: string): [number, number, number, number] {
+ if (c.startsWith("#")) {
+ const [r, g, b] = hexToRgb(c);
+ return [r, g, b, 1];
+ }
+ const m = c.match(
+ /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/,
+ );
+ if (!m) return [128, 128, 128, 1];
+ return [+m[1], +m[2], +m[3], m[4] !== undefined ? +m[4] : 1];
+}
+
+export function lerpColor(from: string, to: string, t: number): string {
+ const a = parseRgba(from);
+ const b = parseRgba(to);
+ const f = (i: number) => a[i] + (b[i] - a[i]) * t;
+ return `rgba(${Math.round(f(0))},${Math.round(f(1))},${Math.round(f(2))},${f(3).toFixed(3)})`;
+}
+
/* 节点标签:**平时是一行裸字,指到或选中的那一个才补一块底**。
从前它一直是个胶囊(深底 + 一圈 14% 的白描边),而在界面的语汇里那副样子
说的是「状态」——Ready、3 dropped、System admin。节点的名字不是状态,它就是