Skip to content

World's first open-source enterprise world model.

Parallel edges must not share one line (#174)

WaylandYange1a37af7d179
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 6e1b8bb4..025b9a00 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -490,6 +490,19 @@ pub struct GraphEdge {
/// **与 `inferred` 不是一回事**,尽管两个词很近:那一位说的是「名字来自原文
/// 而不是本体」,这一位说的是「这条边根本不是谁说的,是引擎推的」
pub derived: bool,
+ /// 推它出来的那条规则(`transitive` / `symmetric` / `inverse` / `sub_property`);
+ /// 断言的边为 None。
+ ///
+ /// **界面需要分辨 `inverse`**:`A works_at B` 与它推出的 `B employs A` 是
+ /// 同一件事的两种说法,画成两条边只是把冗余画了两遍;而 `sub_property`
+ /// 推出的是另一条粒度不同的事实,该各画各的
+ pub rule: Option<String>,
+ /// 推它出来用到的前提事实(按证明顺序)。断言的边为空。
+ ///
+ /// **界面并边要靠它认准来源。** 只按「同一对节点」找,会把 `contains`
+ /// 挂到恰好也连着那两点的 `allied_with` 上——那条说法属于 `part_of`,
+ /// 挂错的结果看着完全正常,正是最难发现的那种
+ pub premises: Vec<Uuid>,
pub valid_from: Option<DateTime<Utc>>,
pub valid_to: Option<DateTime<Utc>>,
pub confidence: f32,
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 8cd1f096..41652dba 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -447,7 +447,8 @@ async fn edges_among(
"SELECT f.id, f.subject_id AS source, f.object_id AS target,
COALESCE(r.key, fact_surface_predicate(f.id)) AS predicate,
COALESCE(r.label, fact_surface_predicate(f.id)) AS label,
- r.id IS NULL AS inferred, FALSE AS derived,
+ r.id IS NULL AS inferred, FALSE AS derived, NULL::text AS rule,
+ ARRAY[]::uuid[] AS premises,
f.valid_from, f.valid_to, f.confidence
FROM facts f LEFT JOIN relation_types r ON r.id = f.predicate_id
WHERE f.kb_id = $1 AND f.invalidated_at IS NULL AND f.object_id IS NOT NULL
@@ -458,9 +459,12 @@ async fn edges_among(
UNION ALL
SELECT d.id, d.subject_id AS source, d.object_id AS target,
r.key AS predicate, r.label AS label,
- FALSE AS inferred, TRUE AS derived,
+ FALSE AS inferred, TRUE AS derived, ru.kind AS rule,
+ ARRAY(SELECT fd.premise_fact_id FROM fact_derivations fd
+ WHERE fd.derived_fact_id = d.id ORDER BY fd.seq) AS premises,
d.valid_from, d.valid_to, d.confidence
FROM derived_facts d JOIN relation_types r ON r.id = d.predicate_id
+ JOIN rules ru ON ru.id = d.rule_id
WHERE d.kb_id = $1 AND d.invalidated_at IS NULL
AND d.subject_id = ANY($2) AND d.object_id = ANY($2)
AND ($3::timestamptz IS NULL
diff --git a/web/package.json b/web/package.json
index 879d5af1..9a7d6361 100644
--- a/web/package.json
+++ b/web/package.json
@@ -11,6 +11,7 @@
"preview": "vite preview"
},
"dependencies": {
+ "@sigma/edge-curve": "3.1.0",
"@sigma/node-border": "^3.0.0",
"@sigma/node-square": "^3.0.0",
"@tanstack/react-query": "^5.62.0",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
index 23a34ad8..e3a5b294 100644
--- a/web/pnpm-lock.yaml
+++ b/web/pnpm-lock.yaml
@@ -8,6 +8,9 @@ importers:
.:
dependencies:
+ '@sigma/edge-curve':
+ specifier: 3.1.0
'@sigma/node-border':
specifier: ^3.0.0
@@ -476,6 +479,11 @@ packages:
cpu: [x64]
os: [win32]
+ '@sigma/[email protected]':
+ resolution: {integrity: sha512-OFWkfAXEsm+X8l1K4K49cC0psB0gQ+gqxKA08HG5piNPdzrDZ5gG9Gza6htZ5AirOVwd/4/uq/gPpD5En+H+3Q==}
+ peerDependencies:
+ sigma: '>=3.0.0-beta.10'
+
resolution: {integrity: sha512-mE3zUfjvJVuAMhSjiP/zdlkqe0OVTETxd04XHUwof01YqdzTk0OB4ACJIhWrwgsBXl7tTd9lPuKoroafLh8MtQ==}
peerDependencies:
@@ -1627,6 +1635,10 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ dependencies:
+ sigma: 3.0.3([email protected])
+
dependencies:
sigma: 3.0.3([email protected])
diff --git a/web/src/api.ts b/web/src/api.ts
index 3dd9c9e7..f6d92f50 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -515,6 +515,13 @@ export interface GraphEdge {
/** true = 这条边是**推出来的**,不是任何人断言的(R1)。
* 与 `inferred` 不是一回事:那个说「名字来自原文」,这个说「不是谁说的」 */
derived: boolean;
+ /** 推它出来的那条规则;断言的边为 null。
+ * 界面靠它认出 `inverse`——那种边与来源边是同一件事的两种说法,
+ * 画两条只是把冗余画了两遍(见 Graph 的 `layOutParallelEdges`) */
+ rule: string | null;
+ /** 推它出来用到的前提事实 id(按证明顺序);断言的边为空。
+ * 并边要靠它认准来源——只按节点对匹配会把说法挂到错的边上 */
+ premises: string[];
valid_from: string | null;
valid_to: string | null;
confidence: number;
diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsx
index ba75c565..915a0605 100644
--- a/web/src/pages/Graph.tsx
+++ b/web/src/pages/Graph.tsx
@@ -7,6 +7,7 @@ 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 { EntityHistory } from "./EntityHistory";
import {
@@ -68,6 +69,95 @@ const EDGE_COLOR_INFERRED = "rgba(163,163,163,0.1)";
// 用户要在余光里就分得出「文档里写的」和「推出来的」
const EDGE_COLOR_DERIVED = "rgba(231,197,124,0.42)";
const EDGE_COLOR_DERIVED_DIM = "rgba(231,197,124,0.14)";
+
+/** 相邻两条弧之间的曲率差。太小仍然糊,太大在长边上会甩得离节点很远 */
+const EDGE_CURVATURE_STEP = 0.18;
+
+/** 一条边画在哪条弧上;`curvature === 0` = 直线。 */
+interface PlacedEdge {
+ edge: GraphEdge;
+ curvature: number;
+ /** 并进这条边的别的说法(逆关系),悬停时一并显示 */
+ alsoLabels: string[];
+}
+
+/** 同一对节点之间的边,画在各自的弧上;逆关系推出来的那些先并掉。
+ *
+ * **两件事,顺序有讲究:先减后分。**
+ *
+ * 一、`A works_at B` 与它推出的 `B employs A` 是**同一件事的两种说法**,
+ * 不是两条知识。画成两条弧只是把冗余画得好看一点。所以逆关系推出来的边
+ * 并进它的来源边,说法挂在那条边上。`sub_property`(`ceo_of ⊑ works_at`)
+ * 不并——那是两条粒度不同的事实,各自成立。
+ *
+ * 二、剩下的按**无向对**分组扇开。无向是要点:一条边和它的反向边起终点相反,
+ * 按有向对分组会各自成组、各自以为自己是独苗,于是又叠回同一条直线上。
+ * 分组用 min/max,而落到弧上时按边自己的方向翻符号——sigma 的曲率是相对
+ * source→target 的,不翻的话反向的弧会绕到同一侧。 */
+function layOutParallelEdges(edges: GraphEdge[]): {
+ edges: PlacedEdge[];
+ folded: number;
+} {
+ const pairKey = (a: string, b: string) => (a < b ? `${a} ${b}` : `${b} ${a}`);
+ const push = (m: Map<string, GraphEdge[]>, k: string, e: GraphEdge) => {
+ const list = m.get(k);
+ if (list) list.push(e);
+ else m.set(k, [e]);
+ };
+
+ // ---- 一、并掉逆关系推出来的边
+ const survivors: GraphEdge[] = [];
+ const inverses: GraphEdge[] = [];
+ for (const e of edges) {
+ if (e.derived && e.rule === "inverse") inverses.push(e);
+ else survivors.push(e);
+ }
+ /* **按前提找来源边,不是按节点对。**
+ 一度写成「取那一对节点上的第一条边」,于是 `contains` 挂到了恰好也连着
+ 那两点的 `allied_with` 上——而 `contains` 属于 `part_of`。挂错之后
+ 界面上看着完全正常,是最难发现的那一种。前提是服务端算出来的,用它。 */
+ const onScreen = new Map<string, GraphEdge>();
+ for (const e of survivors) onScreen.set(e.id, e);
+
+ const also = new Map<string, string[]>();
+ let folded = 0;
+ for (const e of inverses) {
+ const host = (e.premises ?? []).map((p) => onScreen.get(p)).find(Boolean);
+ if (!host) {
+ // 来源边不在这一屏(时间轴筛掉了,或它自己也是推出来的而被过滤了)。
+ // **那就留着它**——并进一条不存在的边等于把这条知识删了
+ survivors.push(e);
+ continue;
+ }
+ const list = also.get(host.id) ?? [];
+ // 去重:传递推出来的几条 `part_of` 各有各的逆,而前提链都回到同一条边上,
+ // 于是同一个说法会被挂三遍。**说法是名字,不是计数**
+ const name = e.label ?? e.predicate ?? "";
+ if (!list.includes(name)) list.push(name);
+ also.set(host.id, list);
+ folded++;
+ }
+
+ // ---- 二、剩下的按无向对扇开
+ const groups = new Map<string, GraphEdge[]>();
+ for (const e of survivors) push(groups, pairKey(e.source, e.target), e);
+
+ const placed: PlacedEdge[] = [];
+ for (const group of groups.values()) {
+ const n = group.length;
+ group.forEach((e, i) => {
+ // 围绕直线对称铺开:n=1 → [0];n=2 → [-0.5, 0.5];n=3 → [-1, 0, 1]
+ const offset = n === 1 ? 0 : i - (n - 1) / 2;
+ const sign = e.source < e.target ? 1 : -1;
+ placed.push({
+ edge: e,
+ curvature: offset === 0 ? 0 : sign * offset * EDGE_CURVATURE_STEP,
+ alsoLabels: also.get(e.id) ?? [],
+ });
+ });
+ }
+ return { edges: placed, folded };
+}
// 呼吸周期。动画不是为了好看,是因为静态的一个色差在几百条边里根本注意不到
const DERIVED_PULSE_MS = 2200;
// 超过这个数就只上色不动画。**写出来而不是悄悄降级**:每帧重算几千条边的颜色,
@@ -479,6 +569,8 @@ export function Graph() {
/* 焦点 = hover 优先于选中;样式在 reducer 里统一处理 */
const selectedRef = useRef<string | null>(null);
const hoverRef = useRef<string | null>(null);
+ /** 鼠标停在哪条边上。用来把并进它的逆关系说法亮出来 */
+ const hoverEdgeRef = useRef<string | null>(null);
const filterRef = useRef<{
hiddenTypes: Set<string>;
activeNodes: Set<string> | null;
@@ -746,21 +838,26 @@ export function Graph() {
});
}
}
- for (const e of data.data.edges) {
- if (g.hasNode(e.source) && g.hasNode(e.target)) {
- g.addEdgeWithKey(e.id, e.source, e.target, {
- label: e.label?.toUpperCase() ?? "",
- size: 1,
- color: e.derived
- ? EDGE_COLOR_DERIVED
- : e.inferred
- ? EDGE_COLOR_INFERRED
- : EDGE_COLOR,
- type: "line",
- // reducer 每帧读它:决定要不要藏、要不要呼吸
- derived: e.derived,
- });
- }
+ const placed = layOutParallelEdges(
+ data.data.edges.filter((e) => g.hasNode(e.source) && g.hasNode(e.target)),
+ );
+ for (const { edge: e, curvature, alsoLabels } of placed.edges) {
+ g.addEdgeWithKey(e.id, e.source, e.target, {
+ label: e.label?.toUpperCase() ?? "",
+ size: 1,
+ color: e.derived
+ ? EDGE_COLOR_DERIVED
+ : e.inferred
+ ? EDGE_COLOR_INFERRED
+ : EDGE_COLOR,
+ // 独一条就走直线:曲线是为了把重叠分开,没有重叠就不必弯
+ type: curvature === 0 ? "line" : "curved",
+ curvature,
+ // 并进来的逆关系说法,悬停时连着本名一起显示
+ alsoLabels,
+ // reducer 每帧读它:决定要不要藏、要不要呼吸
+ derived: e.derived,
+ });
}
// 布局:先静态铺开,再用 worker 动画稳定 ~2.5s(Semantica 式 stabilizing)
let fa2: InstanceType<typeof FA2Layout> | null = null;
@@ -879,6 +976,13 @@ export function Graph() {
},
renderEdgeLabels: true,
defaultEdgeType: "line",
+ /* 平行边扇成弧(见 `layOutParallelEdges`)。直线那一版把同一对节点之间
+ 的每条边画在同一条线段上,于是几个标签逐字符叠成乱码——实测一对节点
+ 之间最多压着六条 */
+ edgeProgramClasses: { curved: EdgeCurveProgram },
+ // 边的悬停事件默认是关的。开它是为了 `enterEdge`:并进去的那些说法
+ // 要有地方看得见(见 edgeReducer)
+ enableEdgeEvents: true,
labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',
labelSize: 11,
labelColor: { color: "#e5e5e5" },
@@ -1005,6 +1109,27 @@ export function Graph() {
const f = filterRef.current;
const res = { ...attrs };
const [s, t] = g.extremities(edge);
+ /* 并进这条边的逆关系说法,接在本名后面:`PART OF ⁻¹ CONTAINS`。
+ **只在关注它的时候显示**——常驻会把标签拉长一倍,而标签太长
+ 正是这次要治的毛病。
+ 两个触发点,因为**边只有一像素宽,精确悬停对人也很难命中**:
+ 鼠标压在这条边上,或者压在它两端任一个节点上。后者才是实际
+ 用得上的那个,前者留着是因为有时人就是要指那一条。
+ 放在隐藏/压暗逻辑之前:说法是显示的事,不是可见性的事 */
+ const also = attrs.alsoLabels as string[] | undefined;
+ if (also && also.length > 0) {
+ const focused =
+ edge === hoverEdgeRef.current ||
+ hoverRef.current === s ||
+ hoverRef.current === t ||
+ selectedRef.current === s ||
+ selectedRef.current === t;
+ if (focused) {
+ res.label = `${attrs.label} ⁻¹ ${also
+ .map((l) => l.toUpperCase())
+ .join(" / ")}`;
+ }
+ }
const sk = g.getNodeAttribute(s, "typeKey") as string;
const tk = g.getNodeAttribute(t, "typeKey") as string;
if (f.hiddenTypes.has(sk) || f.hiddenTypes.has(tk)) {
@@ -1134,6 +1259,19 @@ export function Graph() {
hoverRef.current = null;
sigma.refresh();
});
+ /* 悬停一条边,把并进来的说法亮出来。
+ 逆关系的边被并掉了(见 `layOutParallelEdges`),少画一条是对的,
+ 但那个名字不该就此消失:`part_of` 反过来叫 `contains` 是本体里
+ 写着的东西,人有权看见。**只在悬停时显示**——常驻会把标签拉长一倍,
+ 而拉长标签正是这次要治的毛病 */
+ sigma.on("enterEdge", ({ edge }) => {
+ hoverEdgeRef.current = edge;
+ sigma.refresh();
+ });
+ sigma.on("leaveEdge", () => {
+ hoverEdgeRef.current = null;
+ sigma.refresh();
+ });
// 边标签只在放大后出现(默认视距下太密,Semantica 同样克制)
const updateEdgeLabels = () =>
sigma.setSetting("renderEdgeLabels", sigma.getCamera().ratio < 0.7);