World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
The ontology becomes visible as a schema, not only editable as forms (#281)
Angel Suareze7015a83bfef
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 38dfe76d..be1b78e4 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -1028,9 +1028,6 @@ export const en = {description: "Description",descriptionHint:"Guides the extractor: what belongs here, with a couple of examples. Fed straight into the extraction prompt.",- overviewHint:- "The schema your extractor follows. Select a class or property on the left to edit it, or add new ones with the + buttons.",- overviewStats: (c: number, p: number) => `${c} classes · ${p} properties`,attributes: "Attributes",attributesHint:"Literal-valued fields of this class (a person's salary, a contract's amount). Extracted with evidence and history, like any fact.",@@ -1221,6 +1218,41 @@ export const en = {`Some could not be added: ${keys.join(", ")} — the rest went through.`,proposals: "AI proposals",keyHint: "lowercase_snake_case",+ /* ---- Schema diagram ---- */+ schemaDiagram: "Schema diagram",+ schemaSearchPlaceholder: "Search schema…",+ schemaEmpty:+ "No schema to display yet. Add a class on the left, or import an OWL/RDFS/Turtle file to get started.",+ schemaFitView: "Fit view",+ schemaZoomIn: "Zoom in",+ schemaZoomOut: "Zoom out",+ schemaLegendInheritance: "Inheritance",+ schemaLegendRelation: "Relations",+ schemaLegendDisjoint: "Disjoint",+ schemaUnscoped: (n: number) => `Unscoped properties (${n})`,+ schemaUnscopedHint:+ "Not limited to specific classes, so no line on the canvas would be honest. Select one to inspect or edit it.",+ schemaClosePanel: "Close",+ // 面板里的三段:定义(表单)/ 属性(关系 + 字面值字段)/ 实例。+ // 用页面自己的词——左栏就叫 Classes / Properties+ schemaTabDefinition: "Definition",+ schemaTabProperties: "Properties",+ schemaTabInstances: "Instances",+ schemaAddRelationship: "New relationship…",+ schemaCheckDefects: (n: number) =>+ n === 1+ ? "1 new ontology issue from this change"+ : `${n} new ontology issues from this change`,+ schemaCheckReview: "Review",+ schemaRelationships: "Relationships",+ schemaOutgoing: "From this class",+ schemaIncoming: "To this class",+ schemaNoRelationships: "No relationships yet.",+ schemaConnectHint: "Connect using an existing relationship",+ schemaConnectPlaceholder: "Search relationships…",+ schemaConnectAs: "As",+ schemaConnect: "Connect",+ schemaConnected: (label: string) => `Connected via ${label}.`,},mapping: {title: "Data mapping",diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.tsindex b75fed2c..e56e1555 100644--- a/web/src/i18n/zh.ts+++ b/web/src/i18n/zh.ts@@ -932,8 +932,6 @@ export const zh: Strings = {description: "描述",descriptionHint:"指导抽取器:什么属于这里,配上几个例子。它会被原样送进抽取提示词。",- overviewHint: "抽取器遵循的模式。在左侧选一个类或属性来编辑,或用 + 新建。",- overviewStats: (c: number, p: number) => `${c} 个类 · ${p} 个属性`,attributes: "属性",attributesHint:"这个类的字面值字段(一个人的薪资、一份合同的金额)。和任何事实一样带证据与历史。",@@ -1086,6 +1084,35 @@ export const zh: Strings = {`有几个没能加入:${keys.join("、")}——其余的已经成功。`,proposals: "AI 提案",keyHint: "小写下划线命名",+ /* ---- 模式图 ---- */+ schemaDiagram: "模式图",+ schemaSearchPlaceholder: "搜索模式…",+ schemaEmpty: "还没有可显示的模式。在左侧新建一个类,或导入一个 OWL/RDFS/Turtle 文件开始。",+ schemaFitView: "归位",+ schemaZoomIn: "放大",+ schemaZoomOut: "缩小",+ schemaLegendInheritance: "继承",+ schemaLegendRelation: "关系",+ schemaLegendDisjoint: "互斥",+ schemaUnscoped: (n: number) => `未限定的属性(${n})`,+ schemaUnscopedHint: "没有限定在具体的类上,画到画布上的连线会是本体没说过的话。选一个来查看或编辑。",+ schemaClosePanel: "关闭",+ schemaTabDefinition: "定义",+ schemaTabProperties: "属性",+ schemaTabInstances: "实例",+ schemaAddRelationship: "新建关系…",+ schemaCheckDefects: (n) =>+ n === 1 ? "这次改动带来 1 个新的本体问题" : `这次改动带来 ${n} 个新的本体问题`,+ schemaCheckReview: "去审阅",+ schemaRelationships: "关系",+ schemaOutgoing: "从这个类出发",+ schemaIncoming: "指向这个类",+ schemaNoRelationships: "还没有关系。",+ schemaConnectHint: "用一个已有的关系连接",+ schemaConnectPlaceholder: "搜索关系…",+ schemaConnectAs: "作为",+ schemaConnect: "连接",+ schemaConnected: (label) => `已通过 ${label} 连接。`,},mapping: {title: "数据映射",diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsxindex 777c93e7..367c142d 100644--- a/web/src/pages/Graph.tsx+++ b/web/src/pages/Graph.tsx@@ -16,6 +16,23 @@ import Sigma from "sigma";import { createNodeBorderProgram } from "@sigma/node-border";import EdgeCurveProgram from "@sigma/edge-curve";import { NodeSquareShellProgram } from "./squareShellProgram";+import {+ drawHoverCard,+ drawPillLabel,+ drawWorldGrid,+ hexToRgb,+ HOVER_MUTE,+ 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";import { EntityHistory } from "./EntityHistory";import {ArrowLeft,@@ -50,27 +67,6 @@ import { usePopoverFlip } from "../ui/popoverFlip";import { useKb, useKbId } from "../kb";import { toast } from "../toast";-/* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:- Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、- 彩色只属于数据"的既定原则换成同明度纯灰,类型色混入比例不变 */-const NODE_SHELL_BASE = "#121212"; // 节点外壳深底(原 #0B1320 的中性化)-const NODE_CORE_BASE = "#767676"; // 节点核心灰(原 #5A7A9E 的中性化)-const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化)-const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键)-const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例-/* 状态环取**节点自己的类型色**,不是两个写死的色相。-- 换掉的直接原因是一次撞色:原来的选中金环 `#E7C57C` 就是- `rgb(231,197,124)`,与 `EDGE_COLOR_DERIVED` 逐位相同——「这个节点被选中了」- 和「这条边是推出来的」用同一个颜色说话,而这两件事毫无关系。- 金色现在专属于「推出来的」。-- 往白里混而不是直接用原色:环画在节点自己身上,同色同亮度就看不出是个环。- **悬停混得更白、选中混得更少**——悬停时全图不压暗,环要在一片乱线里- 立刻跳出来;选中时其余都压暗了,节点本来就孤立着,这时候环该说的是- 「它是谁」,所以更贴近它自己的颜色。 */-const RING_HOVER_MIX = 0.7; // 悬停:偏白,为的是跳出来-const RING_SELECT_MIX = 0.35; // 选中:偏本色,为的是认得出const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝)// 本体没认下的关系:同色更淡。名字来自原文,不该跟词表里的关系看着一样重const EDGE_COLOR_INFERRED = "rgba(163,163,163,0.1)";@@ -211,34 +207,8 @@ const EDGE_FOCUS = "rgba(255,255,255,0.55)";// 从前一律 EDGE_FOCUS,一选中金线就变白,等于把来历抹掉了。// 比常态的金更亮更实——它同样要表达「被选中了」const EDGE_FOCUS_DERIVED = "rgba(255,214,140,0.95)";-const MUTED_SHELL = "#151515";-/* 悬停时其余的压暗程度。**比选中轻**(选中是压到底):- 悬停是随鼠标走的、每划过一个节点就换一次,压到底会让整张画布不停明灭;- 而且两者压得一样重的话,"我只是路过"和"我选中了它"就成了同一个画面。- 所以留一档差:压得深,但不到底——看得出焦点,也看得出这只是路过。- (试过 0.55,太浅,焦点不够跳)*/-const HOVER_MUTE = 0.78;-const PILL_BG = "rgba(12,12,12,0.9)";-const PILL_BORDER = "rgba(255,255,255,0.14)";-const PILL_TEXT = "#ededed";-const TRANSPARENT = "rgba(0,0,0,0)";const DAY_MS = 24 * 3600 * 1000;-function hexToRgb(hex: string): [number, number, number] {- const m = /^#?([0-9a-f]{6})$/i.exec(hex);- if (!m) return [128, 128, 128];- const v = parseInt(m[1], 16);- return [(v >> 16) & 255, (v >> 8) & 255, v & 255];-}--/** c1 向 c2 按 t 比例混色 */-function mix(c1: string, c2: string, t: number): string {- const [r1, g1, b1] = hexToRgb(c1);- const [r2, g2, b2] = hexToRgb(c2);- const f = (a: number, b: number) => Math.round(a + (b - a) * t);- return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`;-}-/* 播放淡入:解析 hex / rgb / rgba(含 alpha)并线性插值 */function parseRgba(c: string): [number, number, number, number] {if (c.startsWith("#")) {@@ -260,168 +230,6 @@ function lerpColor(from: string, to: string, t: number): string {/** 播放中新元素的淡入时长 */const FADE_MS = 320;-/* 世界坐标网格:随相机平移/缩放(Figma/tldraw 式无限画布惯例)。- 4 倍细分 LOD:每层 alpha 随其屏幕间距连续淡入(13px 进场 → 52px 满亮 5.5%),- 粗层与细层线重合处自然叠亮,形成"大小格"层次;无任何跳变。 */-const GRID_BASE_WORLD = 24; // 基准世界格距(匹配 ~300 尺度的布局)-const GRID_FADE_IN_PX = 13;-const GRID_FULL_PX = 52;-const GRID_MAX_LEVEL_PX = 480;-const GRID_MAX_ALPHA = 0.055;--function drawWorldGrid(canvas: HTMLCanvasElement, sigma: Sigma): void {- const ctx = canvas.getContext("2d");- if (!ctx) return;- const { width, height } = sigma.getDimensions();- const dpr = window.devicePixelRatio || 1;- const pw = Math.round(width * dpr);- const ph = Math.round(height * dpr);- if (canvas.width !== pw || canvas.height !== ph) {- canvas.width = pw;- canvas.height = ph;- }- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- ctx.clearRect(0, 0, width, height);- if (width <= 0 || height <= 0) return;-- // 世界→屏幕:两个探针点求每世界单位像素数与原点位置(无相机旋转场景)- const p0 = sigma.graphToViewport({ x: 0, y: 0 });- const p1 = sigma.graphToViewport({ x: 1, y: 0 });- const ppw = p1.x - p0.x;- if (!Number.isFinite(ppw) || ppw <= 0) return;-- // 最细可见层级:屏幕间距 ≥ 淡入阈值的最小 4 幂格距- let spacing = GRID_BASE_WORLD;- while (spacing * ppw < GRID_FADE_IN_PX) spacing *= 4;- while (spacing * ppw >= GRID_FADE_IN_PX * 4) spacing /= 4;-- for (let sp = spacing; sp * ppw < GRID_MAX_LEVEL_PX; sp *= 4) {- const ss = sp * ppw;- const t = Math.min(- 1,- (ss - GRID_FADE_IN_PX) / (GRID_FULL_PX - GRID_FADE_IN_PX),- );- if (t <= 0) continue;- ctx.strokeStyle = `rgba(255,255,255,${(GRID_MAX_ALPHA * t).toFixed(4)})`;- ctx.lineWidth = 1;- ctx.beginPath();- const startX = ((p0.x % ss) + ss) % ss;- for (let x = startX; x <= width; x += ss) {- const px = Math.round(x) + 0.5;- ctx.moveTo(px, 0);- ctx.lineTo(px, height);- }- const startY = ((p0.y % ss) + ss) % ss;- for (let y = startY; y <= height; y += ss) {- const py = Math.round(y) + 0.5;- ctx.moveTo(0, py);- ctx.lineTo(width, py);- }- ctx.stroke();- }-}--/* 胶囊标签:深色圆角底 + 柔和文字(学 Semantica 的浮签风格) */-// eslint-disable-next-line @typescript-eslint/no-explicit-any-function drawPillLabel(- ctx: CanvasRenderingContext2D,- data: any,- settings: any,-): void {- if (!data.label) return;- // hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签- if (data.hideBaseLabel) return;- // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12- const size = Math.max(10, Math.min(11, data.size * 0.25));- ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`;- ctx.textBaseline = "middle";- const padX = 6;- const padY = 3;- const w = ctx.measureText(data.label).width + padX * 2;- const h = size + padY * 2;- const x = data.x + Math.max(data.size * 0.7, 12);- const y = data.y - Math.max(data.size * 0.9, 10) - h;- ctx.save();- ctx.shadowColor = "rgba(0,0,0,0.6)";- ctx.shadowBlur = 12;- ctx.beginPath();- ctx.roundRect(x, y, w, h, 6);- ctx.fillStyle = PILL_BG;- ctx.fill();- ctx.shadowBlur = 0;- ctx.strokeStyle = PILL_BORDER;- ctx.lineWidth = 1;- ctx.stroke();- ctx.fillStyle = PILL_TEXT;- ctx.fillText(data.label, x + padX, y + h / 2);- ctx.restore();-}--/* Hover 悬浮卡(Semantica hoverCard 规格):径向柔光 + 名称 + 类型行 */-// eslint-disable-next-line @typescript-eslint/no-explicit-any-function drawHoverCard(- ctx: CanvasRenderingContext2D,- data: any,- _settings: any,-): void {- if (!data.label) return;- ctx.save();-- // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0- const glowR = Math.max(data.size * 4.8, 16);- const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888");- const grad = ctx.createRadialGradient(- data.x,- data.y,- 0,- data.x,- data.y,- glowR,- );- grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`);- grad.addColorStop(1, `rgba(${r},${g},${b},0)`);- ctx.fillStyle = grad;- ctx.beginPath();- ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);- ctx.fill();-- // 卡片: 标题 700/13 + 类型行 500/10 大写- const titleSize = 13;- const metaSize = 10;- const padX = 10;- const padY = 7;- const metaGap = 5;- const meta = String(data.typeLabel ?? "NODE").toUpperCase();- ctx.textBaseline = "top";- ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;- const titleW = ctx.measureText(data.label).width;- ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;- const metaW = ctx.measureText(meta).width;- const w = Math.max(titleW, metaW) + padX * 2;- const h = padY * 2 + titleSize + metaGap + metaSize;- const x = data.x + Math.max(data.size * 0.9, 16);- const y = data.y - Math.max(data.size * 1.1, 16) - h;-- ctx.shadowColor = "rgba(0,0,0,0.62)";- ctx.shadowBlur = 15;- ctx.beginPath();- ctx.roundRect(x, y, w, h, 8);- ctx.fillStyle = "rgba(12,12,12,0.94)";- ctx.fill();- ctx.shadowBlur = 0;- ctx.strokeStyle = "rgba(255,255,255,0.16)";- ctx.lineWidth = 1;- ctx.stroke();-- ctx.fillStyle = "#f5f5f5";- ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;- ctx.fillText(data.label, x + padX, y + padY);- ctx.fillStyle = "rgba(255,255,255,0.5)";- ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;- ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);- ctx.restore();-}-export function Graph() {const kbId = useKbId();const { kb } = useKb();diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex fe0484ac..9558c41f 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -1,16 +1,20 @@// 本体编辑器:master-detail 双栏(与 Library 的 SourcesRail 同构)。// 左栏 = filter + Classes/Properties 两小节 + 底部 Unmatched 入口;// 右侧 = 选中项的表单 / 未匹配信号面板 / 概览。-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Link } from "@tanstack/react-router";+import { Link, useNavigate } from "@tanstack/react-router";import {+ ArrowLeft,+ ArrowRight,ChevronRight,Inbox,+ Network,Plus,Search,Upload,Wand2,+ X,} from "lucide-react";import {api,@@ -26,6 +30,7 @@ import {import { S } from "../i18n";import { useKb } from "../kb";import { toast } from "../toast";+import { OntologySchemaGraph, type SchemaSelection } from "./OntologySchemaGraph";import {Button,Chip,@@ -37,7 +42,6 @@ import {Loading,MultiSearchSelect,Pager,- PageTitle,RAIL_CLS,SearchSelect,cn,@@ -52,23 +56,63 @@ const RAIL_PAGE = 14;/** 过滤模式两节混排时每节的行数 */const RAIL_PAGE_MIXED = 6;-/** 右侧详情区当前展示什么 */+/** 右侧详情区当前展示什么。+ *+ * class / relation / new-class / new-relation / schema / null 这一组共享+ * 同一块工作区:模式图常驻做背景,表单(如果有)停靠在右侧——左栏点一个+ * 类名、画布上点一个节点、模式图自己的搜索框选中一个关系,三条路径落到+ * 的是同一个 `sel`,因此也落到同一份表单,不必再各画一遍。+ * import / refine / misses 仍是独立的整页视图:那三个不是「关于某个类+ * 或关系」的事,跟模式图没有共同的背景可言。 */type Sel =| { kind: "class"; id: string }| { kind: "relation"; id: string }| { kind: "new-class"; parentId: string | null }- | { kind: "new-relation" }+ // 从模式图上一个类发起「新建关系」时带上它的 id,表单里 domain 预填成它+ | { kind: "new-relation"; initialDomain?: string | null }| { kind: "misses" }// 类型消解:把「大致对」的类换成更具体的那个| { kind: "refine" }| { kind: "import" }+ // 模式图无选中:看整张图,不停靠表单+ | { kind: "schema" }| null;+/** 这次选中会不会在模式图右侧停靠一张表单 */+const onPanel = (s: Sel) =>+ s?.kind === "class" ||+ s?.kind === "relation" ||+ s?.kind === "new-class" ||+ s?.kind === "new-relation";+export function Ontology() {const { kb } = useKb();const queryClient = useQueryClient();+ const navigate = useNavigate();const [sel, setSel] = useState<Sel>(null);const [railTab, setRailTab] = useState<"classes" | "properties">("classes");+ // 模式图详情面板停在哪一段。**跨选中保留**:在实例上挨个类看下去,+ // 是一种真实的读法,每换一个类就被弹回定义页会打断它+ const [panelTab, setPanelTab] = useState<+ "definition" | "properties" | "instances"+ >("definition");+ /** 正在退场的那次选择:面板演完 `u-dock-out` 再卸载,而不是一下子消失 */+ const [exitingSel, setExitingSel] = useState<Sel>(null);+ // **当前选中从 ref 里取,不从闭包里取。** 模式图注册 sigma 事件的 effect+ // 只依赖 [schema],`clickStage` 抓住的是那一次渲染的 onSelect;读闭包里的+ // sel 会把早就过期的那次选中当成"正在退场的东西",于是点空白处时面板先+ // 冒出来再消失。图谱页的 `selectedRef` 是同一个理由+ const selRef = useRef<Sel>(null);+ useEffect(() => {+ selRef.current = sel;+ }, [sel]);+ const closePanel = useCallback(() => {+ const cur = selRef.current;+ if (!onPanel(cur)) return;+ setExitingSel(cur);+ setSel({ kind: "schema" });+ window.setTimeout(() => setExitingSel(null), 170);+ }, []);const [filter, setFilter] = useState("");const [collapsed, setCollapsed] = useState<Set<string>>(new Set());// 每页行数按列表区实际高度动态算:窗口多高铺多满,不滚动也不留大空@@ -97,6 +141,29 @@ export function Ontology() {// 错误统一走全局 toast,不再用页面内嵌错误行const onError = (e: unknown) => toast.error((e as Error).message);+ // 本体自洽检查是同步的纯计算(Review 页的「Run check」用的是同一个接口),+ // 不排队、不需要确认——每次本体改动后顺手跑一遍,把新增的矛盾在它们+ // 发生的当下就说出来,而不是等人某天想起去 Review 才看见。+ // 干净就不出声:**只在有新东西时才说话**,否则每次保存都弹一条「没事」+ // 比不弹还烦+ const runCheck = useMutation({+ mutationFn: () => api.runConsistencyCheck(kb!.id),+ onSuccess: (r) => {+ if (r.defects_new > 0) {+ toast.info(S.ontology.schemaCheckDefects(r.defects_new), {+ label: S.ontology.schemaCheckReview,+ onClick: () =>+ navigate({ to: "/kb/$kbId/review", params: { kbId: kb!.id } }),+ });+ }+ },+ // 检查本身失败不该盖过「保存成功」——本体的写已经落了盘,静默重试留给下次改动+ });+ const afterOntologyChange = () => {+ refresh();+ runCheck.mutate();+ };+if (!kb) return <Loading>{S.nav.loading}</Loading>;if (data.isPending) return <Loading>{S.nav.loading}</Loading>;if (data.isError) return <Loading>{(data.error as Error).message}</Loading>;@@ -104,14 +171,33 @@ export function Ontology() {const { entity_types, relation_types, misses, dismissed_misses } = data.data;// 属性不进 Properties 列表:它们挂在类下,在类详情区编辑const relations = relation_types.filter((r) => r.kind !== "attribute");+ // 面板要演完退场再卸载:一取消选中就 unmount 是瞬间消失(图谱页同一个做法)。+ // 在两个类之间切换不走这条路——面板留在原地换内容,每点一个节点抖一下反而吵+ const panelSel = onPanel(sel) ? sel : exitingSel;+const selectedClass =- sel?.kind === "class"- ? (entity_types.find((t) => t.id === sel.id) ?? null)+ panelSel?.kind === "class"+ ? (entity_types.find((t) => t.id === panelSel.id) ?? null): null;const selectedProp =- sel?.kind === "relation"- ? (relation_types.find((r) => r.id === sel.id) ?? null)+ panelSel?.kind === "relation"+ ? (relation_types.find((r) => r.id === panelSel.id) ?? null): null;+ // 选中类身上挂着的东西,面板分段的计数和内容都用它+ const classRelations = selectedClass+ ? relations.filter(+ (r) =>+ r.domains.includes(selectedClass.id) ||+ r.ranges.includes(selectedClass.id),+ )+ : [];+ const classAttributes = selectedClass+ ? relation_types.filter(+ (r) => r.kind === "attribute" && r.domains.includes(selectedClass.id),+ )+ : [];+ // 新建的类还没有关系也没有实例,只剩定义这一段+ const classTab = selectedClass ? panelTab : "definition";return (<div className="h-full flex">@@ -124,13 +210,30 @@ export function Ontology() {className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-600"/><input- className="input-dark w-full pl-7 pr-2 py-1.5 text-xs"+ className="input-dark w-full pl-7 pr-2 py-[7px] text-xs"placeholder={S.ontology.filter}value={filter}onChange={(e) => setFilter(e.target.value)}/></div></div>+ {/* 模式图:本体结构的主视图,不是 Import/Refine/Unmatched 那种管理性操作——+ 放在筛选框正下方、列表上方,与那三个钉在底部的按钮拉开位置,+ 视觉上就说明了「这是浏览本体的另一种方式」而不是「这是一项维护动作」 */}+ <div className="px-3 pb-2">+ <button+ onClick={() => setSel({ kind: "schema" })}+ className={cn(+ "w-full flex items-center gap-2 rounded-lg px-2.5 py-2 text-[13px] font-medium transition-colors",+ sel?.kind === "schema"+ ? "u-nav-active"+ : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",+ )}+ >+ <Network size={14} className="text-neutral-500" />+ {S.ontology.schemaDiagram}+ </button>+ </div>{/* 分段切换:与登录页模式切换/日程选择器同一语汇(bg-white/5 容器 + 激活反白);过滤时列表例外:两节混排同时给出命中 */}<div className="mx-3 mb-1 flex gap-1 rounded-lg bg-white/5 p-1">@@ -272,45 +375,107 @@ export function Ontology() {</button></aside>- {/* 右侧:详情。选中类时表单 + 实例列表双栏铺开,提高宽屏利用率 */}- <div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">- {/* 放宽到 6xl 供三列铺开;misses/关系/概览各自带 max-w-xl 内衬不受影响 */}- <div className="max-w-6xl">- {sel?.kind === "import" ? (- <div className="max-w-xl">- <ImportPanel kbId={kb.id} onChanged={refresh} onError={onError} />- </div>- ) : sel?.kind === "refine" ? (- <div className="max-w-2xl">- <RefinePanel kbId={kb.id} onChanged={refresh} onError={onError} />- </div>- ) : sel?.kind === "misses" ? (- <div className="max-w-xl">- <MissesPanel- kbId={kb.id}- misses={misses}- dismissedMisses={dismissed_misses ?? []}- onChanged={refresh}- onError={onError}- />- </div>- ) : sel?.kind === "new-class" || selectedClass ? (- /* lg 两列(表单 | 属性+实例堆叠);xl 三列并排(包装器 xl:contents 解散入栅格) */- <div className="grid gap-4 items-start lg:grid-cols-[minmax(0,24rem)_minmax(0,1fr)] xl:grid-cols-[minmax(0,22rem)_minmax(0,1fr)_minmax(0,1fr)]">- <div className="glass rounded-xl p-4">+ {/* 右侧:详情。class/relation/new-class/new-relation/schema/概览共享+ 同一块工作区——模式图常驻做背景,表单(有的话)停靠右侧,近实底+ (u-modal-panel),不是浮层玻璃:画布是动的,透出来的内容会跟+ 正在读的表单字段打架。左栏点类名、画布点节点、模式图自带的搜索框+ 选中关系,三条路径落到同一个 sel,也就落到同一份表单——+ 不再各画一遍。import/refine/misses 仍是独立整页视图,那三个+ 不是「关于某个类或关系」的事,没有跟模式图共享背景的道理 */}+ {sel?.kind === "import" || sel?.kind === "refine" || sel?.kind === "misses" ? (+ <div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">+ <div className="max-w-6xl">+ {sel.kind === "import" ? (+ <div className="max-w-xl">+ <ImportPanel kbId={kb.id} onChanged={refresh} onError={onError} />+ </div>+ ) : sel.kind === "refine" ? (+ <div className="max-w-2xl">+ <RefinePanel kbId={kb.id} onChanged={refresh} onError={onError} />+ </div>+ ) : (+ <div className="max-w-xl">+ <MissesPanel+ kbId={kb.id}+ misses={misses}+ dismissedMisses={dismissed_misses ?? []}+ onChanged={refresh}+ onError={onError}+ />+ </div>+ )}+ </div>+ </div>+ ) : (+ <div className="flex-1 min-w-0 relative">+ <OntologySchemaGraph+ entityTypes={entity_types}+ relationTypes={relation_types}+ selected={+ sel?.kind === "class" || sel?.kind === "relation"+ ? ({ kind: sel.kind, id: sel.id } as SchemaSelection)+ : null+ }+ // 点空白处取消选中走的也是 closePanel:不然点画布关掉的面板没有+ // 退场动画,而点画布正是最常用的那种关法+ onSelect={(next) => (next ? setSel(next) : closePanel())}+ />+ {(panelSel?.kind === "new-class" || selectedClass) && (+ <DockedPanel+ onClose={closePanel}+ exiting={!onPanel(sel)}+ header={+ <PanelHeader+ color={selectedClass?.color}+ square={selectedClass?.shape === "square"}+ title={selectedClass?.label ?? S.ontology.newClass}+ builtin={selectedClass?.builtin}+ />+ }+ tabs={+ selectedClass && (+ <>+ <PanelTab+ active={classTab === "definition"}+ onClick={() => setPanelTab("definition")}+ >+ {S.ontology.schemaTabDefinition}+ </PanelTab>+ <PanelTab+ active={classTab === "properties"}+ count={classRelations.length + classAttributes.length}+ onClick={() => setPanelTab("properties")}+ >+ {S.ontology.schemaTabProperties}+ </PanelTab>+ <PanelTab+ active={classTab === "instances"}+ count={selectedClass.usage}+ onClick={() => setPanelTab("instances")}+ >+ {S.ontology.schemaTabInstances}+ </PanelTab>+ </>+ )+ }+ >+ {/* 三段用 hidden 藏,不卸载:表单里改了一半的字段、实例列表翻到的+ 第几页,都该在切回来的时候还在 */}+ <div className={classTab === "definition" ? "" : "hidden"}><ClassFormkey={selectedClass?.id ??- `new-${sel?.kind === "new-class" ? sel.parentId : "root"}`+ `new-${panelSel?.kind === "new-class" ? panelSel.parentId : "root"}`}kbId={kb.id}existing={selectedClass}parentId={- sel?.kind === "new-class"- ? sel.parentId+ panelSel?.kind === "new-class"+ ? panelSel.parentId: (selectedClass?.primary_parent ?? null)}allTypes={entity_types}+ headlessonNewSub={selectedClass? () =>@@ -324,70 +489,220 @@ export function Ontology() {// 新建成功即选中它:立刻能看到、能继续编辑if (sel?.kind === "new-class")setSel(- createdId ? { kind: "class", id: createdId } : null,+ createdId+ ? { kind: "class", id: createdId }+ : { kind: "schema" },);- refresh();+ afterOntologyChange();}}onError={onError}/></div>- {/* lg 右列堆叠属性+实例;xl 解散为两个独立栅格列 */}{selectedClass && (- <div className="grid gap-4 items-start xl:contents">- <AttributesCard- kbId={kb.id}- type={selectedClass}- attributes={relation_types.filter(- (r) =>- r.kind === "attribute" &&- r.domains.includes(selectedClass.id),- )}- onChanged={refresh}- onError={onError}- />- <InstancesCard kbId={kb.id} type={selectedClass} />- </div>+ <>+ <div+ className={+ classTab === "properties" ? "flex flex-col gap-3" : "hidden"+ }+ >+ <RelationshipsCard+ kbId={kb.id}+ cls={selectedClass}+ relations={relations}+ allTypes={entity_types}+ onChanged={afterOntologyChange}+ onError={onError}+ onSelect={(id) => setSel({ kind: "relation", id })}+ onAddNew={() =>+ setSel({+ kind: "new-relation",+ initialDomain: selectedClass.id,+ })+ }+ />+ <AttributesCard+ kbId={kb.id}+ type={selectedClass}+ attributes={classAttributes}+ onChanged={afterOntologyChange}+ onError={onError}+ />+ </div>+ <div className={classTab === "instances" ? "" : "hidden"}>+ <InstancesCard kbId={kb.id} type={selectedClass} />+ </div>+ </>)}- </div>- ) : sel?.kind === "new-relation" || selectedProp ? (- <div className="glass rounded-xl p-4 max-w-xl">- <PropertyForm- key={selectedProp?.id ?? "new"}- kbId={kb.id}- existing={selectedProp}- allTypes={entity_types}- allRelations={relations}- onDone={(createdId) => {- if (sel?.kind === "new-relation")- setSel(- createdId ? { kind: "relation", id: createdId } : null,- );- refresh();- }}- onError={onError}- />- </div>- ) : (- /* 概览:未选中任何条目 */- <div className="glass rounded-xl p-6 max-w-xl">- <PageTitle className="mb-1">{S.ontology.title}</PageTitle>- <p className="text-xs text-neutral-500 u-num">- {S.ontology.overviewStats(- entity_types.length,- relations.length,- )}- </p>- <p className="mt-3 text-sm text-neutral-400">- {S.ontology.overviewHint}- </p>- </div>+ </DockedPanel>+ )}+ {(panelSel?.kind === "new-relation" || selectedProp) && (+ <DockedPanel+ onClose={closePanel}+ exiting={!onPanel(sel)}+ header={+ <PanelHeader+ title={selectedProp?.label ?? S.ontology.newProperty}+ sub={+ selectedProp+ ? S.ontology.usage(selectedProp.usage)+ : undefined+ }+ builtin={selectedProp?.builtin}+ />+ }+ >+ <div>+ <PropertyForm+ key={selectedProp?.id ?? "new"}+ kbId={kb.id}+ existing={selectedProp}+ allTypes={entity_types}+ allRelations={relations}+ initialDomain={+ panelSel?.kind === "new-relation" ? panelSel.initialDomain : null+ }+ headless+ onDone={(createdId) => {+ if (sel?.kind === "new-relation")+ setSel(+ createdId+ ? { kind: "relation", id: createdId }+ : { kind: "schema" },+ );+ afterOntologyChange();+ }}+ onError={onError}+ />+ </div>+ </DockedPanel>)}</div>+ )}+ </div>+ );+}++/* ---------- 停靠面板:模式图右侧的详情外壳 ----------+ 与图谱页的实体面板同一个结构:**标题行固定,只有下面的内容滚**。整列一起滚+ 的话,正在编辑的那个类叫什么、用了多少次、以及关闭键,都会滚出视野。+ 关闭键跟着标题走,不再单开一行——那一行既占掉顶上的高度,又让按钮看着不+ 属于任何一张卡片。++ 面也跟图谱页一样是 `glass-strong`:**指针一放上去就压实**(120ms 进、260ms+ 出,见 styles.css)。作者原本用近实底,理由是画布在动、透上来的动静会跟正在+ 读的字段打架——那个顾虑成立,而玻璃的 hover 压实正是对它的回答:人在用这块+ 面的时候它就是实的,手移开才透回去,画布的上下文也就没被一块死板挡住。++ 退场也照图谱页:`u-dock-out` 演完再卸载,而不是一下子消失 */++function DockedPanel({+ header,+ tabs,+ exiting,+ onClose,+ children,+}: {+ header: React.ReactNode;+ /** 分段控件,跟着标题一起固定在顶上——它要能一直点得到 */+ tabs?: React.ReactNode;+ /** 正在退场:演动画,期间不再接受点击(u-dock-out 里带了 pointer-events) */+ exiting?: boolean;+ onClose: () => void;+ children: React.ReactNode;+}) {+ return (+ <div+ className={`${exiting ? "u-dock-out" : "u-dock-in"} glass-strong absolute top-3 right-3 bottom-3 w-[26rem] z-10 rounded-xl shadow-2xl flex flex-col`}+ >+ <div className="shrink-0 flex items-start justify-between gap-2 px-4 py-3.5 border-b border-white/10">+ <div className="min-w-0">{header}</div>+ <button+ onClick={onClose}+ title={S.ontology.schemaClosePanel}+ className="mt-0.5 shrink-0 text-neutral-500 hover:text-neutral-200 transition-colors"+ >+ <X size={15} />+ </button>+ </div>+ {tabs && (+ <div className="shrink-0 px-4 pt-3 pb-1">+ <div className="flex rounded-lg overflow-hidden border border-white/10">+ {tabs}+ </div>+ </div>+ )}+ <div className="u-scroll flex-1 min-h-0 overflow-y-auto flex flex-col gap-3 px-4 py-3">+ {children}</div></div>);}+/** 分段控件里的一格。与 Library / 图谱页那个是同一个写法 */+function PanelTab({+ active,+ count,+ onClick,+ children,+}: {+ active: boolean;+ count?: number;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ onClick={onClick}+ className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-[11px] transition-colors ${+ active+ ? "bg-white/10 text-neutral-100"+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"+ }`}+ >+ {children}+ {count !== undefined && count > 0 && (+ <span className="u-num text-neutral-500">{count}</span>+ )}+ </button>+ );+}++/* 面板标题:色点 + 名字 + 第二行的小字。与图谱页实体面板的头一个写法 */+function PanelHeader({+ color,+ square,+ title,+ sub,+ builtin,+}: {+ color?: string;+ square?: boolean;+ title: string;+ sub?: string;+ builtin?: boolean;+}) {+ return (+ <>+ <div className="flex items-center gap-2">+ {color && (+ <span+ className={`h-2.5 w-2.5 shrink-0 ${square ? "" : "rounded-full"}`}+ style={{ background: color, boxShadow: `0 0 8px ${color}55` }}+ />+ )}+ <span+ className="truncate text-[15px] font-semibold tracking-tight text-white"+ style={{ fontFamily: "var(--font-display)" }}+ >+ {title}+ </span>+ {builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}+ </div>+ {sub && <div className="mt-1 text-xs text-neutral-500">{sub}</div>}+ </>+ );+}+/* ---------- 实例列表:选中类的实体(服务端分页,点击进图谱) ---------- */function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {@@ -417,14 +732,14 @@ function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {to="/kb/$kbId/graph"params={{ kbId }}search={{ entity: e.id }}- className="flex items-center gap-2 py-1.5 text-sm text-neutral-300 hover:text-white"+ className="group flex items-center gap-2 -mx-2 px-2 py-1.5 rounded-lg text-sm text-neutral-300 transition-colors hover:bg-white/[0.05] hover:text-white"><spanclassName={`h-2 w-2 shrink-0 ${type.shape === "square" ? "" : "rounded-full"}`}style={{ background: type.color }}/><span className="truncate">{e.name}</span>- <span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600">+ <span className="ml-auto shrink-0 u-num text-[10.5px] text-neutral-600 transition-colors group-hover:text-neutral-400">{S.ontology.instanceFacts(e.fact_count)}</span></Link>@@ -435,9 +750,221 @@ function InstancesCard({ kbId, type }: { kbId: string; type: EntityTypeView }) {);}+/* ---------- 关系卡片:这个类作为主语/宾语连着哪些关系 + 用已有关系接一条新的 ---------- */++/** 「新建关系」(PropertyForm)解决的是本体里还没有这条关系的情况;这张卡片+ * 解决另一半——**这个类身上已经挂着哪些关系**(从它出发的、指向它的),+ * 以及更常见的那种需求:不是每次都要一条新关系,而是把这个类接到一条+ * 已经存在的关系上(`works_at` 已经连着 Person→Organization,+ * 再建一个 Contractor 时多半是把 Contractor 也加进 works_at 的 domain,+ * 不是另建一条 works_at_2)。后一半直接改写已有关系的 domains/ranges,+ * 走的是 PropertyForm 保存时同一个 updateRelationType,只是把「打开表单、+ * 找到多选框、加一个类」压缩成一步。 */+function RelationshipsCard({+ kbId,+ cls,+ relations,+ allTypes,+ onChanged,+ onError,+ onSelect,+ onAddNew,+}: {+ kbId: string;+ cls: EntityTypeView;+ /** kind === "relation" 的那些——attribute 的宾语是字面值,谈不上「连着」 */+ relations: RelationTypeView[];+ allTypes: EntityTypeView[];+ onChanged: () => void;+ onError: (e: unknown) => void;+ onSelect: (relationId: string) => void;+ onAddNew: () => void;+}) {+ const labelOf = (id: string) =>+ allTypes.find((t) => t.id === id)?.label ?? id;+ // 自环关系(domain 和 range 都是这个类)两边都算——它确实两个方向都成立+ const outgoing = relations.filter((r) => r.domains.includes(cls.id));+ const incoming = relations.filter((r) => r.ranges.includes(cls.id));++ const [connectId, setConnectId] = useState("");+ const [connectSide, setConnectSide] = useState<"domain" | "range">("domain");+ useEffect(() => {+ setConnectId("");+ }, [cls.id]);++ const connect = useMutation({+ mutationFn: () => {+ const rel = relations.find((r) => r.id === connectId);+ if (!rel) return Promise.reject(new Error("relation not found"));+ // 只加不减:已经连着的那一侧原样保留,另一侧才可能被追加。+ // Set 去重——挑到已经连过的关系时这是个无害的空操作,不必先禁用按钮+ const domains =+ connectSide === "domain"+ ? [...new Set([...rel.domains, cls.id])]+ : rel.domains;+ const ranges =+ connectSide === "range"+ ? [...new Set([...rel.ranges, cls.id])]+ : rel.ranges;+ return api.updateRelationType(kbId, rel.id, {+ label: rel.label,+ temporal: rel.temporal,+ functional: rel.functional,+ inverse_functional: rel.inverse_functional,+ is_transitive: rel.is_transitive,+ is_symmetric: rel.is_symmetric,+ is_asymmetric: rel.is_asymmetric,+ is_irreflexive: rel.is_irreflexive,+ inverse_of: rel.inverse_of,+ sub_property_of: rel.sub_property_of,+ description: rel.description,+ domains,+ ranges,+ });+ },+ onSuccess: () => {+ const rel = relations.find((r) => r.id === connectId);+ toast.success(S.ontology.schemaConnected(rel?.label ?? ""));+ const id = connectId;+ setConnectId("");+ onChanged();+ // 连完直接跳到那条关系:域/值域改没改、改对了没有,一眼可见+ onSelect(id);+ },+ onError,+ });++ const RelationRow = ({ r, dir }: { r: RelationTypeView; dir: "out" | "in" }) => (+ // 悬停要有底色:这一行整条可点,只把文字提亮半级在深底上几乎看不出来。+ // 底色用左栏那一档(white/[0.05]),右端的类型小字跟着一起提亮+ <button+ onClick={() => onSelect(r.id)}+ className="group w-full flex items-center gap-1.5 -mx-2 px-2 py-1.5 rounded-lg text-sm text-left text-neutral-300 transition-colors hover:bg-white/[0.05] hover:text-white"+ >+ {dir === "out" ? (+ <ArrowRight size={12} className="shrink-0 text-[#c4a5ff]" />+ ) : (+ <ArrowLeft size={12} className="shrink-0 text-[#c4a5ff]" />+ )}+ <span className="truncate">{r.label}</span>+ <span className="ml-auto shrink-0 text-xs text-neutral-500 truncate max-w-[8rem] transition-colors group-hover:text-neutral-300">+ {(dir === "out" ? r.ranges : r.domains).map(labelOf).join(", ") ||+ S.ontology.anyType}+ </span>+ </button>+ );++ return (+ // 卡片在面板里边,底交给面板;这里与属性卡、实例卡同一个写法+ <div className="glass rounded-xl p-4">+ <div className="mb-1 flex items-baseline gap-2">+ <h3 className="text-sm font-bold text-neutral-200">+ {S.ontology.schemaRelationships}+ </h3>+ {outgoing.length + incoming.length > 0 && (+ <span className="u-num text-xs text-neutral-500">+ {outgoing.length + incoming.length}+ </span>+ )}+ </div>+ {outgoing.length === 0 && incoming.length === 0 ? (+ <p className="text-xs text-neutral-500 mb-2">+ {S.ontology.schemaNoRelationships}+ </p>+ ) : (+ <div className="mb-2">+ {outgoing.length > 0 && (+ <>+ <div className="text-[10px] uppercase tracking-[0.08em] text-neutral-600 mb-0.5">+ {S.ontology.schemaOutgoing}+ </div>+ <div className="divide-y divide-white/[0.06] mb-1.5">+ {outgoing.map((r) => (+ <RelationRow key={`out:${r.id}`} r={r} dir="out" />+ ))}+ </div>+ </>+ )}+ {incoming.length > 0 && (+ <>+ <div className="text-[10px] uppercase tracking-[0.08em] text-neutral-600 mb-0.5">+ {S.ontology.schemaIncoming}+ </div>+ <div className="divide-y divide-white/[0.06]">+ {incoming.map((r) => (+ <RelationRow key={`in:${r.id}`} r={r} dir="in" />+ ))}+ </div>+ </>+ )}+ </div>+ )}+ <div className="pt-2 border-t border-white/5">+ <p className="text-[11px] text-neutral-500 mb-1.5">+ {S.ontology.schemaConnectHint}+ </p>+ <div className="flex gap-1.5 mb-1.5">+ <SearchSelect+ value={connectId}+ onChange={setConnectId}+ options={relations.map((r) => ({+ value: r.id,+ label: r.label,+ hint: r.key,+ }))}+ size="sm"+ className="flex-1 min-w-0"+ placeholder={S.ontology.schemaConnectPlaceholder}+ />+ </div>+ <div className="flex items-center gap-1.5 mb-2">+ <span className="text-[11px] text-neutral-500">+ {S.ontology.schemaConnectAs}+ </span>+ <div className="flex rounded-lg overflow-hidden border border-white/10">+ {(["domain", "range"] as const).map((side) => (+ <button+ key={side}+ onClick={() => setConnectSide(side)}+ className={cn(+ "px-2 py-1 text-[11px] transition-colors",+ connectSide === side+ ? "bg-white/[0.12] text-white"+ : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300",+ )}+ >+ {side === "domain" ? S.ontology.domainLabel : S.ontology.rangeLabel}+ </button>+ ))}+ </div>+ </div>+ <Button+ size="sm"+ variant="ghost"+ disabled={!connectId || connect.isPending}+ onClick={() => connect.mutate()}+ >+ {S.ontology.schemaConnect}+ </Button>+ </div>+ <div className="mt-2 pt-2 border-t border-white/5">+ <button+ onClick={onAddNew}+ className="flex items-center gap-1.5 text-[13px] text-neutral-500 hover:text-neutral-200 transition-colors"+ >+ <Plus size={13} />+ {S.ontology.schemaAddRelationship}+ </button>+ </div>+ </div>+ );+}+/* ---------- 属性卡片:选中类的字面值字段(行内增改删) ---------- */-function AttributesCard({+/** 导出给模式图复用:选中一个类时,检查器里嵌的就是这一张卡片本身,+ * 不是另一份只读摘要——编辑发生在同一处,不必跳回本体主视图 */+export function AttributesCard({kbId,type,attributes,@@ -488,7 +1015,7 @@ function AttributesCard({<buttonkey={a.id}onClick={() => setEditing(a.id)}- className="w-full flex items-center gap-2 py-1.5 text-sm text-left text-neutral-300 hover:text-white"+ className="w-full flex items-center gap-2 -mx-2 px-2 py-1.5 rounded-lg text-sm text-left text-neutral-300 transition-colors hover:bg-white/[0.05] hover:text-white"><span className="truncate">{a.label}</span><Chip tone="neutral">@@ -909,12 +1436,14 @@ function parentOptions(return out;}-function ClassForm({+/** 导出给模式图复用(见 AttributesCard 上的注释) */+export function ClassForm({kbId,existing,parentId,allTypes,onNewSub,+ headless,onDone,onError,}: {@@ -924,6 +1453,8 @@ function ClassForm({allTypes: EntityTypeView[];/** 编辑已有类时提供:以当前类为父级新建子类 */onNewSub?: () => void;+ /** 停靠面板把标题画在自己的固定头里,表单就不再画第二遍 */+ headless?: boolean;/** 创建成功时携带新 id,编辑成功时为 undefined */onDone: (createdId?: string) => void;onError: (e: unknown) => void;@@ -988,22 +1519,24 @@ function ClassForm({const lbl = "block text-xs font-medium text-neutral-500 mb-1";return (<div className="space-y-3">- <div className="flex items-center gap-2">- <span- className={`h-3 w-3 ${shape === "square" ? "" : "rounded-full"}`}- style={{ background: color }}- />- <span className="font-bold text-neutral-100">- {existing?.label ?? S.ontology.newClass}- </span>- {/* key 是纯技术标识:已存在时干脆不展示,只在创建时输入 */}- {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}- {existing && (- <span className="ml-auto text-xs text-neutral-500">- {S.ontology.usage(existing.usage)}+ {!headless && (+ <div className="flex items-center gap-2">+ <span+ className={`h-3 w-3 ${shape === "square" ? "" : "rounded-full"}`}+ style={{ background: color }}+ />+ <span className="font-bold text-neutral-100">+ {existing?.label ?? S.ontology.newClass}</span>- )}- </div>+ {/* key 是纯技术标识:已存在时干脆不展示,只在创建时输入 */}+ {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}+ {existing && (+ <span className="ml-auto text-xs text-neutral-500">+ {S.ontology.usage(existing.usage)}+ </span>+ )}+ </div>+ )}{!existing && (<div><label className={lbl}>@@ -1148,11 +1681,14 @@ function ClassForm({/* ---------- 关系表单 ---------- */-function PropertyForm({+/** 导出给模式图复用(见 AttributesCard 上的注释) */+export function PropertyForm({kbId,existing,allTypes,allRelations,+ initialDomain,+ headless,onDone,onError,}: {@@ -1162,6 +1698,11 @@ function PropertyForm({/** 本库的关系(不含属性)。逆与子属性的下拉从这里取——**属性不在其中**,* 它的宾语是字面值,反过来无从谈起 */allRelations: RelationTypeView[];+ /** 从模式图上一个类出发新建关系时,domain 预填成那个类——**只影响初始值**,+ * 不是约束:下面照旧是个可编辑的 MultiSearchSelect,填错了随手改 */+ initialDomain?: string | null;+ /** 见 `ClassForm.headless` */+ headless?: boolean;onDone: (createdId?: string) => void;onError: (e: unknown) => void;}) {@@ -1186,7 +1727,9 @@ function PropertyForm({existing?.sub_property_of ?? "",);const [description, setDescription] = useState(existing?.description ?? "");- const [domains, setDomains] = useState<string[]>(existing?.domains ?? []);+ const [domains, setDomains] = useState<string[]>(+ existing?.domains ?? (initialDomain ? [initialDomain] : []),+ );const [ranges, setRanges] = useState<string[]>(existing?.ranges ?? []);// 显示标签,不显示 key。**进提示词的 key 由服务端从库里取**,与界面显示什么无关;// 而类树、属性列表也都显示标签,这里没有理由例外——中文库里用户该看到@@ -1278,17 +1821,19 @@ function PropertyForm({const lbl = "block text-xs font-medium text-neutral-500 mb-1";return (<div className="space-y-3">- <div className="flex items-center gap-2">- <span className="font-bold text-neutral-100">- {existing?.label ?? S.ontology.newProperty}- </span>- {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}- {existing && (- <span className="ml-auto text-xs text-neutral-500">- {S.ontology.usage(existing.usage)}+ {!headless && (+ <div className="flex items-center gap-2">+ <span className="font-bold text-neutral-100">+ {existing?.label ?? S.ontology.newProperty}</span>- )}- </div>+ {existing?.builtin && <Chip tone="neutral">{S.ontology.builtin}</Chip>}+ {existing && (+ <span className="ml-auto text-xs text-neutral-500">+ {S.ontology.usage(existing.usage)}+ </span>+ )}+ </div>+ )}{!existing && (<div><label className={lbl}>diff --git a/web/src/pages/OntologySchemaGraph.tsx b/web/src/pages/OntologySchemaGraph.tsxnew file mode 100644index 00000000..81fae10a--- /dev/null+++ b/web/src/pages/OntologySchemaGraph.tsx@@ -0,0 +1,817 @@+// 本体的模式图:类是节点,subClassOf / 关系 / 互斥是三种边。+// 画的是 TBox(本体本身的结构),不是 /graph 画的那张 ABox(实例与事实)——+// 两者共用 graphology/sigma 这套工具链与视觉语汇(见 graphVisuals.ts),+// 但语义不共享,也不共用查询:本体数据只有一份,由 Ontology.tsx 的 useQuery+// 取,这里只接数据 + 回调。+//+// **选中态是受控的**:这个组件只管画布本身(节点/边/搜索/图例/缩放),+// 不知道编辑表单长什么样——选中一个类或关系之后,实际的 ClassForm /+// PropertyForm 由 Ontology.tsx 在画布右侧停靠渲染。早先这里自己内嵌过一份+// (selected 是内部 state,检查器也在这个文件里),代价是本体页原有的那套+// 「点左栏类名 → 出表单」路径和这里各画一遍,长得还不一样。现在两条路径+// 落到同一个 sel 状态、同一份表单组件,这个文件只剩「画」和「选中了什么」。+import { useEffect, useMemo, useRef, useState } from "react";+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 { EdgeCurvedArrowProgram } from "@sigma/edge-curve";+import { NodeSquareShellProgram } from "./squareShellProgram";+import {+ drawHoverCard,+ drawPillLabel,+ 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";+import { Maximize2, Network, Search, X, ZoomIn, ZoomOut } from "lucide-react";+import type { EntityTypeView, RelationTypeView } from "../api";+import { S } from "../i18n";+import { cn } from "../ui";+import { usePopoverFlip } from "../ui/popoverFlip";++/* ============ 边的三种语义,与三种视觉语汇的映射 ============+ 紫色留给「关系」——本体页 AI 提案面板里,Property 提案的徽标(P)已经是紫的,+ 这里延续同一个语义,不是另起一套颜色。粉色是 --u-danger,ClassForm 里+ 互斥与父类冲突的提示文字用的就是它。灰色留给纯结构性的 subClassOf,+ 让「谁是谁的对象属性」在余光里就比「谁是谁的子类」更显眼——+ 语义关系是这张图要回答的主要问题,继承是骨架,互斥是附注。++ 暗态的 RGB 得自己压向背景色,不能只调低 alpha:sigma 的边着色器在+ 预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB,alpha 单独降不会让边+ 看起来变暗(Graph.tsx 的 EDGE_DIM 处有同一条注释)。这里的边不需要+ 动画淡入淡出,所以不必再搬一套 lerp/parseRgba,几个状态各写一个+ 现成的颜色字面量就够了。 */+const EDGE_SUBCLASS = "rgba(195,195,195,0.4)";+const EDGE_SUBCLASS_FOCUS = "rgba(235,235,235,0.95)";+const EDGE_RELATION = "rgba(196,165,255,0.55)"; // --u-violet+const EDGE_RELATION_FOCUS = "rgba(214,193,255,0.95)";+const EDGE_DISJOINT = "rgba(255,157,175,0.45)"; // --u-danger+const EDGE_DISJOINT_FOCUS = "rgba(255,157,175,0.9)";+const EDGE_DIM = "rgba(48,48,48,0.4)";++/** 三种边各自的语义——驱动颜色/暗淡/可点选,与「用哪个 sigma 程序画」分开管 */+const SUBCLASS_KIND = "subclass";+const RELATION_KIND = "relation";+const DISJOINT_KIND = "disjoint";++/** sigma 的渲染派发键。**故意与上面的语义分开**:关系边有直的也有弯的+ * (只有一条就是直的,平行才弯),但两种都是「relation 语义」;早先把+ * 这两件事焊成一个字段,直的关系边全都退回默认类型、边看不见——+ * 这正是本体模式图第一版里"有些线不可见"的根因 */+const EDGE_TYPE_ARROW = "arrow"; // 直线 + 箭头(EdgeArrowProgram)+const EDGE_TYPE_CURVED_ARROW = "curvedArrow"; // 弧线 + 箭头(EdgeCurvedArrowProgram)+const EDGE_TYPE_LINE = "line"; // 直线,无箭头(EdgeLineProgram)——互斥专用++/** 结构边细、关系边粗一档——「语义关系比结构性信息更显眼」不能只靠颜色说,+ * 粗细上也要有一档差。这个粗细同时也是点选判定的命中带宽——sigma 的边拾取+ * 用的就是渲染出来的这条几何体(WebGL 拾取缓冲,不是另一套「点击容差」),+ * 细到 minEdgeThickness 的默认 1.7px 时,关系边在真实鼠标操作下几乎点不中。+ * 调粗关系边,视觉突出与「点得中」是同一个改动 */+const SUBCLASS_EDGE_SIZE = 0.9;+const DISJOINT_EDGE_SIZE = 0.8;+const RELATION_EDGE_SIZE = 2;+/** sigma 边渲染的最小厚度(像素),默认 1.7——同一个理由,全局兜底,+ * 免得缩小到某个层级时任何边都变得难点 */+const MIN_EDGE_THICKNESS = 3;+/** 节点基准大小;连接越多(继承 + 关系 + 互斥合计)越大 */+const BASE_NODE_SIZE = 9;++/** 并排偏移的步长;同一对类之间的关系边超过一条时用它扇开 */+const RELATION_CURVATURE_STEP = 0.22;+/** 自环(domain === range,如 married_to: Person→Person)没有「偏移」可言——+ * 给一个固定起始弯曲,否则退化成一个看不见的点 */+const SELF_LOOP_BASE_CURVATURE = 1;++export interface SchemaGraphResult {+ graph: Graphology;+ /** domains 或 ranges 留空的关系——本体没把它限定在哪个类上,画不出边,+ * 但不能装作它不存在 */+ unscoped: RelationTypeView[];+}++/** 本体 → 模式图的纯函数投影。不碰 React/Sigma,方便单独验证语义是否正确:+ * 多重继承是不是都进了图、互斥有没有被对称声明重复、平行关系有没有叠成一条、+ * 未限定的关系有没有被错误地画成全连接、坏引用(父类/域/值域指向不存在的+ * id)会不会让它崩溃。 */+export function buildSchemaGraph(+ entityTypes: EntityTypeView[],+ relationTypes: RelationTypeView[],+): SchemaGraphResult {+ const graph = new Graphology({ multi: true });+ const byId = new Map(entityTypes.map((t) => [t.id, t]));++ for (const t of entityTypes) {+ graph.addNode(t.id, {+ label: t.label,+ // 与 /graph 同一套四层壳配方(深壳 + 14% 类型 tint,核心 50% tint,+ // 钢灰描边微 tint)——模式图与实例图看着是同一个引擎画的+ color: mix(NODE_CORE_BASE, t.color, NODE_CORE_MIX),+ shellColor: mix(NODE_SHELL_BASE, t.color, NODE_TINT_MIX),+ borderColor: mix(NODE_BORDER_BASE, t.color, 0.3),+ ringColor: TRANSPARENT,+ typeColor: t.color,+ typeLabel: t.key,+ type: t.shape === "square" ? "square" : "circle",+ key: t.key,+ });+ }++ // subClassOf:子 → 父。方向不因为「父类画在上面看着顺眼」而倒转——+ // 那是布局要解决的事,不是边该说谎的理由。全部 parents,不是只有+ // primary_parent:多重继承必须在图上看得见,primary_parent 只管左栏那棵树+ for (const t of entityTypes) {+ for (const parentId of t.parents) {+ if (parentId === t.id || !byId.has(parentId)) continue;+ graph.addEdgeWithKey(`sub:${t.id}:${parentId}`, t.id, parentId, {+ kind: SUBCLASS_KIND,+ type: EDGE_TYPE_ARROW,+ size: SUBCLASS_EDGE_SIZE,+ });+ }+ }++ // 互斥:无向声明,两边经常互相写一遍——按排序后的 id 对去重,只画一条+ const disjointSeen = new Set<string>();+ for (const t of entityTypes) {+ for (const otherId of t.disjoint) {+ if (otherId === t.id || !byId.has(otherId)) continue;+ const pairKey = [t.id, otherId].sort().join("|");+ if (disjointSeen.has(pairKey)) continue;+ disjointSeen.add(pairKey);+ graph.addEdgeWithKey(`dis:${pairKey}`, t.id, otherId, {+ kind: DISJOINT_KIND,+ type: EDGE_TYPE_LINE,+ size: DISJOINT_EDGE_SIZE,+ });+ }+ }++ // 关系:attribute 的宾语是字面值,不是类,这里只处理 kind === "relation"+ const unscoped: RelationTypeView[] = [];+ for (const r of relationTypes) {+ if (r.kind !== "relation") continue;+ const domains = [...new Set(r.domains)].filter((id) => byId.has(id));+ const ranges = [...new Set(r.ranges)].filter((id) => byId.has(id));+ // domains/ranges 留空 = 本体没把这条关系限定在某个类上,不是「对所有类+ // 都成立」——画成全连接等于替本体断言了一句它没说过的话。引用的类全部+ // 失效(坏数据)时退化成同一种「画不出来」,同样进这个篮子,不吞掉它+ if (+ r.domains.length === 0 ||+ r.ranges.length === 0 ||+ domains.length === 0 ||+ ranges.length === 0+ ) {+ unscoped.push(r);+ continue;+ }+ for (const d of domains) {+ for (const rg of ranges) {+ graph.addEdgeWithKey(`rel:${r.id}:${d}:${rg}`, d, rg, {+ kind: RELATION_KIND,+ // type 由 layOutParallelRelations 按最终弯曲度决定(直线还是弧线)+ relationId: r.id,+ label: r.label,+ size: RELATION_EDGE_SIZE,+ });+ }+ }+ }++ // 大小按连接数走——继承、关系、互斥合起来算,连得越多的类看着越「重要」。+ // 必须等边全部建完才能算度数,所以放在这两段循环之后+ for (const t of entityTypes) {+ const degree = graph.degree(t.id);+ graph.setNodeAttribute(+ t.id,+ "size",+ BASE_NODE_SIZE + Math.min(7, Math.sqrt(degree) * 2.1),+ );+ }++ layOutParallelRelations(graph);+ return { graph, unscoped };+}++/** 同一对类之间的多条关系边(works_at / founded / owns 都连着 Person↔Organization)+ * 各自扇到一条独立的弧上,不叠成一条谁也点不中的线。算法与 Graph.tsx 的+ * layOutParallelEdges 同一个思路(按无向对分组,围绕直线对称铺开),+ * 但这里的边不需要先合并逆关系——本体里 inverse_of 只在关系检查器里说明,+ * 不折进画布,所以少了那一整步。+ *+ * 顺带决定每条关系边的渲染类型:**独苗走直线**(EDGE_TYPE_ARROW),+ * 只有真的平行/自环时才切到弧线程序——弧线程序在零弯曲度下也能画,+ * 但没必要为大多数只有一条的关系边多背一层曲线计算 */+function layOutParallelRelations(graph: Graphology): void {+ const groups = new Map<string, string[]>();+ graph.forEachEdge((edge, attrs, source, target) => {+ if (attrs.kind !== RELATION_KIND) return;+ const key =+ source === target ? `loop:${source}` : [source, target].sort().join("|");+ const list = groups.get(key);+ if (list) list.push(edge);+ else groups.set(key, [edge]);+ });+ for (const edges of groups.values()) {+ const n = edges.length;+ edges.forEach((edge, i) => {+ const [source, target] = graph.extremities(edge);+ if (source === target) {+ graph.mergeEdgeAttributes(edge, {+ curvature: SELF_LOOP_BASE_CURVATURE + i * RELATION_CURVATURE_STEP,+ type: EDGE_TYPE_CURVED_ARROW,+ });+ return;+ }+ const offset = n === 1 ? 0 : i - (n - 1) / 2;+ // sigma 的弯曲度相对这条边自己的 source→target 而言,符号得按谁小谁大+ // 归一化,否则方向相反的两条边会各自以为自己是独苗,扇到同一侧叠回去+ const sign = source < target ? 1 : -1;+ const curvature = offset === 0 ? 0 : sign * offset * RELATION_CURVATURE_STEP;+ graph.mergeEdgeAttributes(edge, {+ curvature,+ type: curvature === 0 ? EDGE_TYPE_ARROW : EDGE_TYPE_CURVED_ARROW,+ });+ });+ }+}++/** 确定性初始布局 + 一次性同步收敛的 ForceAtlas2。**不起动画 worker**——+ * 本体的类数量级比实例图小得多(几十到大几百,不是几千),一次性跑够步数+ * 比维护一个 worker 的生命周期简单,也不会在用户只是点了一下选中时被+ * 误重启(依赖数组只挂 entityTypes/relationTypes,选中状态在别处)。+ * circular 的起始顺序取自节点插入顺序(即 entityTypes 数组顺序),+ * 本体不变时顺序不变,因此这套布局是可重复的——不是精确到像素的稳定,+ * 但同一份本体两次渲染出来的样子不会天差地别。 */+function layoutSchemaGraph(graph: Graphology): void {+ if (graph.order === 0) return;+ circular.assign(graph, { scale: 260 });+ if (graph.size === 0) return; // 只有孤立节点:圆形摆好就是终局,没有力可跑+ const settings = {+ ...forceAtlas2.inferSettings(graph),+ gravity: 0.55,+ scalingRatio: 28,+ outboundAttractionDistribution: true,+ };+ forceAtlas2.assign(graph, { iterations: 200, settings });+}++export type SchemaSelection =+ | { kind: "class"; id: string }+ | { kind: "relation"; id: string }+ | null;++interface SearchHit {+ kind: "class" | "relation";+ id: string;+ label: string;+ sub: string | null; // 类的 key,或关系的 domain → range 摘要+}++export function OntologySchemaGraph({+ entityTypes,+ relationTypes,+ selected,+ onSelect,+}: {+ entityTypes: EntityTypeView[];+ /** 全量关系(含 attribute):图只画 kind === "relation",attribute 在这里+ * 单纯被忽略——它们的宾语是字面值,不是类,不进类图,也不用在这个文件里+ * 另外筛出来,展示 attribute 是 Ontology.tsx 停靠面板的事 */+ relationTypes: RelationTypeView[];+ /** 受控选中态:与 Ontology.tsx 左栏共用同一个 `sel`,点画布上的节点/边+ * 和点左栏的类名走的是同一条状态,右侧停靠的表单也就自然是同一份 */+ selected: SchemaSelection;+ onSelect: (sel: SchemaSelection) => void;+}) {+ const entityById = useMemo(+ () => new Map(entityTypes.map((t) => [t.id, t])),+ [entityTypes],+ );+ const relationById = useMemo(+ () => new Map(relationTypes.map((r) => [r.id, r])),+ [relationTypes],+ );+ const objectRelations = useMemo(+ () => relationTypes.filter((r) => r.kind === "relation"),+ [relationTypes],+ );++ // 本体没变就不重建图——依赖数组只看 entityTypes/relationTypes 的引用,+ // 选中/悬停都是别的状态,不会触发这里+ const schema = useMemo(+ () => buildSchemaGraph(entityTypes, objectRelations),+ [entityTypes, objectRelations],+ );++ const selectedRef = useRef<SchemaSelection>(null);+ const hoverRef = useRef<string | null>(null);+ const hoverEdgeRef = useRef<string | null>(null);+ useEffect(() => {+ selectedRef.current = selected;+ sigmaRef.current?.refresh();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selected]);++ const containerRef = useRef<HTMLDivElement>(null);+ const gridRef = useRef<HTMLCanvasElement>(null);+ const sigmaRef = useRef<Sigma | null>(null);+ const graphRef = useRef<Graphology | null>(null);+ // 手动拖过的节点位置,按 id 存——**跨重建存活**:这个 ref 不在 [schema]+ // 依赖里,本体一编辑(新建/改一个类或关系都会让 entityTypes/relationTypes+ // 换引用,图整个重建)也不会清空。没有这个,摆好的布局会在下一次保存后+ // 被自动布局悄悄冲掉,「挪节点求清楚」就成了白费。只留在这次会话里,+ // 不写回后端——这是渲染层的手感,不是本体数据,同一个道理 /graph 的拖拽+ // 也没有持久化+ const draggedPositionsRef = useRef<Map<string, { x: number; y: number }>>(+ new Map(),+ );++ useEffect(() => {+ if (!containerRef.current) return;+ const g = schema.graph;+ layoutSchemaGraph(g);+ // 拖过的节点摆回去——自动布局不知道用户已经动过手,重新算一遍位置+ // 之后,把记下来的坐标原样盖回去+ for (const [id, pos] of draggedPositionsRef.current) {+ if (!g.hasNode(id)) continue;+ g.setNodeAttribute(id, "x", pos.x);+ g.setNodeAttribute(id, "y", pos.y);+ }+ graphRef.current = g;+ // 选中的东西可能在新图里已经不存在了(比如删除了当前选中的类)——+ // 交给渲染时的存在性检查处理,这里不主动清空:多数情况下(编辑保存后+ // 刷新)选中的东西还在,清空只会让面板无缘无故地闪一下关掉再开++ 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,+ },+ enableEdgeEvents: true,+ minEdgeThickness: MIN_EDGE_THICKNESS,+ labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',+ labelSize: 11,+ labelColor: { color: "#e5e5e5" },+ labelRenderedSizeThreshold: 6,+ labelDensity: 0.7,+ labelGridCellSize: 140,+ minCameraRatio: 0.05,+ maxCameraRatio: 6,+ edgeLabelSize: 10,+ // 关系边的同一个紫——看到画布上有字,就知道这是一条关系边而不是继承/互斥+ edgeLabelColor: { color: "#c4a5ff" },+ edgeLabelFont: '"Geist", "Inter", sans-serif',+ defaultDrawNodeLabel: drawPillLabel,+ defaultDrawNodeHover: drawHoverCard,+ 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 (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;+ res.zIndex = 3;+ return res;+ }+ if (g.areNeighbors(sel.id, node)) {+ res.zIndex = 2;+ return res;+ }+ muteNode();+ return res;+ }+ if (sel?.kind === "relation") {+ const rel = relationById.get(sel.id);+ if (rel) {+ 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;+ }+ muteNode();+ return res;+ }+ }+ return res;+ },+ edgeReducer: (edge, attrs) => {+ const res = { ...attrs };+ const kind = attrs.kind as string;+ const relId = attrs.relationId as string | undefined;+ const base =+ kind === SUBCLASS_KIND+ ? EDGE_SUBCLASS+ : kind === DISJOINT_KIND+ ? EDGE_DISJOINT+ : EDGE_RELATION;+ const focus =+ kind === SUBCLASS_KIND+ ? EDGE_SUBCLASS_FOCUS+ : kind === DISJOINT_KIND+ ? EDGE_DISJOINT_FOCUS+ : EDGE_RELATION_FOCUS;+ res.color = base;+ // 结构性的边(继承/互斥)不挂标签;关系边挂——但一大张图上,全部常显+ // 会变成一堵读不动的字墙,交给 renderEdgeLabels 按缩放开关(见下方+ // updateEdgeLabels),选中的那条在检查器里说得明明白白,不用画布保证+ if (kind !== RELATION_KIND) res.label = "";++ const [s, t] = g.extremities(edge);+ const hov = hoverRef.current;+ const hoverHit = hov !== null && (hov === s || hov === t);+ const hoverEdgeHit = hoverEdgeRef.current === edge;+ const sel = selectedRef.current;+ const selHit =+ sel?.kind === "class"+ ? sel.id === s || sel.id === t+ : sel?.kind === "relation"+ ? sel.id === relId+ : false;++ if (selHit || hoverHit || hoverEdgeHit) {+ res.color = focus;+ res.size = Math.max((attrs.size as number) ?? 1, 1) * 1.5;+ res.zIndex = 3;+ return res;+ }+ if (sel) {+ // 选中了什么但这条边跟它无关:压到背景色附近去+ res.color = EDGE_DIM;+ res.label = "";+ return res;+ }+ return res;+ },+ });++ sigma.on("clickNode", ({ node }) => onSelect({ kind: "class", id: node }));+ sigma.on("clickEdge", ({ edge }) => {+ const relId = g.getEdgeAttribute(edge, "relationId") as string | undefined;+ if (relId) onSelect({ kind: "relation", id: relId });+ });+ sigma.on("clickStage", () => onSelect(null));+ sigma.on("enterNode", ({ node }) => {+ hoverRef.current = node;+ sigma.refresh();+ });+ sigma.on("leaveNode", () => {+ hoverRef.current = null;+ sigma.refresh();+ });+ sigma.on("enterEdge", ({ edge }) => {+ hoverEdgeRef.current = edge;+ sigma.refresh();+ });+ sigma.on("leaveEdge", () => {+ hoverEdgeRef.current = null;+ sigma.refresh();+ });++ // 拖节点。**没有活的力模拟要喂**——与 /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);+ // 边拖边记:万一中途出岔子(组件卸载、切换本体)也不丢这一手+ draggedPositionsRef.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 = "";+ });++ // 关系标签只在放大后出现——本体大起来(导入包常有几十上百个类)时,+ // 全部常显就是第 11 条要治的那堵字墙+ const updateEdgeLabels = () =>+ sigma.setSetting("renderEdgeLabels", sigma.getCamera().ratio < 1.1);+ sigma.getCamera().on("updated", updateEdgeLabels);+ updateEdgeLabels();++ // 世界坐标网格:随相机变动/容器尺寸变动重绘,与 /graph 同一张背景+ const renderGrid = () => {+ if (gridRef.current) drawWorldGrid(gridRef.current, sigma);+ };+ sigma.getCamera().on("updated", renderGrid);+ sigma.on("resize", renderGrid);+ renderGrid();++ sigmaRef.current = sigma;+ if (import.meta.env.DEV) {+ // 调试句柄(仅 dev),与 Graph.tsx 同一个约定+ (window as unknown as Record<string, unknown>).__schemaGraph = g;+ (window as unknown as Record<string, unknown>).__schemaSigma = sigma;+ }+ return () => {+ sigma.kill();+ sigmaRef.current = null;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [schema]);++ const [searchQ, setSearchQ] = useState("");+ const searchHits = useMemo<SearchHit[]>(() => {+ const q = searchQ.trim().toLowerCase();+ if (!q) return [];+ const hits: SearchHit[] = [];+ for (const t of entityTypes) {+ if (t.label.toLowerCase().includes(q) || t.key.toLowerCase().includes(q))+ hits.push({ kind: "class", id: t.id, label: t.label, sub: t.key });+ }+ for (const r of objectRelations) {+ if (!r.label.toLowerCase().includes(q) && !r.key.toLowerCase().includes(q))+ continue;+ const d = r.domains.map((id) => entityById.get(id)?.label ?? "?").join(", ");+ const rg = r.ranges.map((id) => entityById.get(id)?.label ?? "?").join(", ");+ hits.push({+ kind: "relation",+ id: r.id,+ label: r.label,+ sub: d && rg ? `${d} → ${rg}` : null,+ });+ }+ return hits.slice(0, 12);+ }, [searchQ, entityTypes, objectRelations, entityById]);++ const focusClass = (id: string) => {+ const g = graphRef.current;+ const sigma = sigmaRef.current;+ if (!g || !sigma || !g.hasNode(id)) return;+ sigma.getCamera().animate(+ { x: g.getNodeAttribute(id, "x"), y: g.getNodeAttribute(id, "y"), ratio: 0.35 },+ { duration: 300 },+ );+ };+ const pickHit = (hit: SearchHit) => {+ if (hit.kind === "class") {+ onSelect({ kind: "class", id: hit.id });+ focusClass(hit.id);+ } else {+ onSelect({ kind: "relation", id: hit.id });+ const rel = relationById.get(hit.id);+ if (rel?.domains[0]) focusClass(rel.domains[0]);+ }+ setSearchQ("");+ };++ const unscopedPop = usePopoverFlip<HTMLButtonElement, HTMLDivElement>("top left");+ const empty = entityTypes.length === 0;++ return (+ <div className="h-full relative">+ {/* 顶部悬浮条:搜索 + 图例 + 未限定关系入口 */}+ <div className="absolute top-3 left-3 right-3 z-10 flex items-start gap-2 pointer-events-none">+ <div className="relative pointer-events-auto">+ <Search+ size={12}+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-neutral-600"+ />+ <input+ className="input-dark w-60 pl-7 pr-2 py-[5px] text-sm shadow-lg"+ placeholder={S.ontology.schemaSearchPlaceholder}+ value={searchQ}+ onChange={(e) => setSearchQ(e.target.value)}+ />+ {searchQ && (+ <div className="glass-strong absolute mt-1 w-72 rounded-lg shadow-xl overflow-hidden">+ {searchHits.length === 0 && (+ <p className="px-3 py-2 text-xs text-neutral-600">{S.ui.noMatches}</p>+ )}+ {searchHits.map((hit) => (+ <button+ key={`${hit.kind}:${hit.id}`}+ onClick={() => pickHit(hit)}+ className="w-full px-3 py-1.5 text-left text-sm text-neutral-200 hover:bg-white/5 flex items-center gap-2"+ >+ {hit.kind === "class" ? (+ <span+ className={cn(+ "h-2.5 w-2.5 shrink-0",+ entityById.get(hit.id)?.shape !== "square" && "rounded-full",+ )}+ style={{ background: entityById.get(hit.id)?.color }}+ />+ ) : (+ <Network size={11} className="shrink-0 text-[#c4a5ff]" />+ )}+ <span className="truncate">{hit.label}</span>+ {hit.sub && (+ <span className="ml-auto shrink-0 text-xs text-neutral-500 truncate max-w-[9rem]">+ {hit.sub}+ </span>+ )}+ </button>+ ))}+ </div>+ )}+ </div>++ <div className="pointer-events-auto flex flex-wrap gap-1.5 pt-0.5">+ {/* 静态图例:三种边各自的说法,不是可切换的过滤器——本体的边远比+ 实例图少,藏一种边省下的空间不值得多一层交互 */}+ {(+ [+ [S.ontology.schemaLegendInheritance, EDGE_SUBCLASS_FOCUS],+ [S.ontology.schemaLegendRelation, EDGE_RELATION_FOCUS],+ [S.ontology.schemaLegendDisjoint, EDGE_DISJOINT_FOCUS],+ ] as const+ ).map(([label, color]) => (+ <span+ key={label}+ className="glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 text-neutral-300"+ >+ <span className="h-0.5 w-3 rounded-full" style={{ background: color }} />+ {label}+ </span>+ ))}++ {schema.unscoped.length > 0 && (+ <div className="relative" ref={unscopedPop.rootRef}>+ <button+ ref={unscopedPop.anchorRef}+ onClick={() =>+ unscopedPop.open ? unscopedPop.close() : unscopedPop.setOpen(true)+ }+ aria-expanded={unscopedPop.open}+ className={cn(+ "glass rounded-full px-2.5 py-1 text-[11px] transition-colors",+ unscopedPop.open ? "text-neutral-100" : "text-neutral-400",+ "hover:text-neutral-100",+ )}+ >+ {S.ontology.schemaUnscoped(schema.unscoped.length)}+ </button>+ {unscopedPop.open && (+ <div+ ref={unscopedPop.panelRef}+ className="u-menu-glass absolute left-0 top-0 z-50 w-64 overflow-hidden rounded-xl p-2 shadow-2xl"+ >+ <button+ onClick={() => unscopedPop.close()}+ className="mb-1.5 flex w-full items-center gap-1.5 rounded-full px-1.5 py-0.5 text-[11px] text-neutral-300 hover:text-neutral-100"+ >+ {S.ontology.schemaUnscoped(schema.unscoped.length)}+ <X size={11} className="ml-auto text-neutral-500" />+ </button>+ <p className="px-1.5 pb-1.5 text-[11px] leading-relaxed text-neutral-500">+ {S.ontology.schemaUnscopedHint}+ </p>+ <div className="flex max-h-64 flex-col overflow-y-auto">+ {schema.unscoped.map((r) => (+ <button+ key={r.id}+ onClick={() => {+ onSelect({ kind: "relation", id: r.id });+ unscopedPop.close();+ }}+ className="w-full truncate rounded px-1.5 py-1 text-left text-[12px] text-neutral-300 hover:bg-white/5 hover:text-white"+ >+ {r.label}+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ </div>++ {/* 画布:世界坐标网格层(随相机动)垫在 sigma WebGL 层下,与 /graph 同款 */}+ <div className="absolute inset-0">+ <canvas ref={gridRef} className="absolute inset-0 h-full w-full" />+ <div ref={containerRef} className="absolute inset-0" />+ </div>++ {/* 左下:缩放 + 归位。不给布局切换——模式图只有一套确定性布局,+ 不像实例图那样需要按类型聚簇或摊成环 */}+ <div className="absolute bottom-4 left-3 z-10 flex flex-col items-start gap-2">+ <div className="u-tower group glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">+ <button+ title={S.ontology.schemaZoomIn}+ onClick={() => sigmaRef.current?.getCamera().animatedZoom({ duration: 220 })}+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"+ >+ <ZoomIn size={15} />+ <span className="u-tower-label">{S.ontology.schemaZoomIn}</span>+ </button>+ <button+ title={S.ontology.schemaZoomOut}+ onClick={() => sigmaRef.current?.getCamera().animatedUnzoom({ duration: 220 })}+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"+ >+ <ZoomOut size={15} />+ <span className="u-tower-label">{S.ontology.schemaZoomOut}</span>+ </button>+ <div className="h-px bg-white/10 mx-1.5" />+ <button+ title={S.ontology.schemaFitView}+ onClick={() => sigmaRef.current?.getCamera().animatedReset({ duration: 300 })}+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"+ >+ <Maximize2 size={15} />+ <span className="u-tower-label">{S.ontology.schemaFitView}</span>+ </button>+ </div>+ </div>++ {empty && (+ <div className="absolute inset-0 grid place-items-center pointer-events-none">+ <div className="text-center text-sm text-neutral-500 max-w-xs">+ {S.ontology.schemaEmpty}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/pages/graphVisuals.ts b/web/src/pages/graphVisuals.tsnew file mode 100644index 00000000..10d091d7--- /dev/null+++ b/web/src/pages/graphVisuals.ts@@ -0,0 +1,210 @@+// 节点视觉:色彩数学 + 四层壳配色 + 胶囊标签/悬浮卡 + 世界坐标网格。+// 从 Graph.tsx 抽出——这几样是「怎么画一个带类型色的节点」,不含任何实例图+// 语义(没有 derived/contested/temporal 这些概念),本体模式图原样复用,+// 图谱与模式图因此长得像同一个引擎画的,而不是各自一套视觉识别。+//+// **边的画法没有抽到这里**:/graph 的边携带派生/争议/时态这些实例图独有的+// 状态,模式图的边是 subClassOf/relation/disjoint 三种本体语义,两者的+// 「边意味着什么」根本不是同一件事,抽成共用只会把两套语义焊在一起。+import type Sigma from "sigma";++/* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:+ Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、+ 彩色只属于数据"的既定原则换成同明度纯灰,类型色混入比例不变 */+export const NODE_SHELL_BASE = "#121212"; // 节点外壳深底(原 #0B1320 的中性化)+export const NODE_CORE_BASE = "#767676"; // 节点核心灰(原 #5A7A9E 的中性化)+export const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化)+export const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键)+export const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例+/* 状态环取**节点自己的类型色**,不是写死的色相。往白里混而不是直接用原色:+ 环画在节点自己身上,同色同亮度就看不出是个环。**悬停混得更白、选中混得+ 更少**——悬停时全图不压暗,环要在一片乱线里立刻跳出来;选中时其余都+ 压暗了,节点本来就孤立着,这时候环该说的是「它是谁」,所以更贴近它自己+ 的颜色。 */+export const RING_HOVER_MIX = 0.7; // 悬停:偏白,为的是跳出来+export const RING_SELECT_MIX = 0.35; // 选中:偏本色,为的是认得出+export const TRANSPARENT = "rgba(0,0,0,0)";+export const MUTED_SHELL = "#151515";+/* 悬停时其余的压暗程度。**比选中轻**(选中是压到底):悬停是随鼠标走的、+ 每划过一个节点就换一次,压到底会让整张画布不停明灭 */+export const HOVER_MUTE = 0.78;+export const PILL_BG = "rgba(12,12,12,0.9)";+export const PILL_BORDER = "rgba(255,255,255,0.14)";+export const PILL_TEXT = "#ededed";++export function hexToRgb(hex: string): [number, number, number] {+ const m = /^#?([0-9a-f]{6})$/i.exec(hex);+ if (!m) return [128, 128, 128];+ const v = parseInt(m[1], 16);+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];+}++/** c1 向 c2 按 t 比例混色 */+export function mix(c1: string, c2: string, t: number): string {+ const [r1, g1, b1] = hexToRgb(c1);+ const [r2, g2, b2] = hexToRgb(c2);+ const f = (a: number, b: number) => Math.round(a + (b - a) * t);+ return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`;+}++/* 胶囊标签:深色圆角底 + 柔和文字(学 Semantica 的浮签风格) */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function drawPillLabel(+ ctx: CanvasRenderingContext2D,+ data: any,+ _settings: any,+): void {+ if (!data.label) return;+ // hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签+ if (data.hideBaseLabel) return;+ // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12+ const size = Math.max(10, Math.min(11, data.size * 0.25));+ ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`;+ ctx.textBaseline = "middle";+ const padX = 6;+ const padY = 3;+ const w = ctx.measureText(data.label).width + padX * 2;+ const h = size + padY * 2;+ const x = data.x + Math.max(data.size * 0.7, 12);+ const y = data.y - Math.max(data.size * 0.9, 10) - h;+ ctx.save();+ ctx.shadowColor = "rgba(0,0,0,0.6)";+ ctx.shadowBlur = 12;+ ctx.beginPath();+ ctx.roundRect(x, y, w, h, 6);+ ctx.fillStyle = PILL_BG;+ ctx.fill();+ ctx.shadowBlur = 0;+ ctx.strokeStyle = PILL_BORDER;+ ctx.lineWidth = 1;+ ctx.stroke();+ ctx.fillStyle = PILL_TEXT;+ ctx.fillText(data.label, x + padX, y + h / 2);+ ctx.restore();+}++/* Hover 悬浮卡(Semantica hoverCard 规格):径向柔光 + 名称 + 类型行 */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export function drawHoverCard(+ ctx: CanvasRenderingContext2D,+ data: any,+ _settings: any,+): void {+ if (!data.label) return;+ ctx.save();++ // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0+ const glowR = Math.max(data.size * 4.8, 16);+ const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888");+ const grad = ctx.createRadialGradient(+ data.x,+ data.y,+ 0,+ data.x,+ data.y,+ glowR,+ );+ grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`);+ grad.addColorStop(1, `rgba(${r},${g},${b},0)`);+ ctx.fillStyle = grad;+ ctx.beginPath();+ ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);+ ctx.fill();++ // 卡片: 标题 700/13 + 类型行 500/10 大写+ const titleSize = 13;+ const metaSize = 10;+ const padX = 10;+ const padY = 7;+ const metaGap = 5;+ const meta = String(data.typeLabel ?? "NODE").toUpperCase();+ ctx.textBaseline = "top";+ ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;+ const titleW = ctx.measureText(data.label).width;+ ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;+ const metaW = ctx.measureText(meta).width;+ const w = Math.max(titleW, metaW) + padX * 2;+ const h = padY * 2 + titleSize + metaGap + metaSize;+ const x = data.x + Math.max(data.size * 0.9, 16);+ const y = data.y - Math.max(data.size * 1.1, 16) - h;++ ctx.shadowColor = "rgba(0,0,0,0.62)";+ ctx.shadowBlur = 15;+ ctx.beginPath();+ ctx.roundRect(x, y, w, h, 8);+ ctx.fillStyle = "rgba(12,12,12,0.94)";+ ctx.fill();+ ctx.shadowBlur = 0;+ ctx.strokeStyle = "rgba(255,255,255,0.16)";+ ctx.lineWidth = 1;+ ctx.stroke();++ ctx.fillStyle = "#f5f5f5";+ ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;+ ctx.fillText(data.label, x + padX, y + padY);+ ctx.fillStyle = "rgba(255,255,255,0.5)";+ ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;+ ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);+ ctx.restore();+}++/* 世界坐标网格:随相机平移/缩放(Figma/tldraw 式无限画布惯例)。+ 4 倍细分 LOD:每层 alpha 随其屏幕间距连续淡入(13px 进场 → 52px 满亮 5.5%),+ 粗层与细层线重合处自然叠亮,形成"大小格"层次;无任何跳变。 */+const GRID_BASE_WORLD = 24; // 基准世界格距(匹配 ~300 尺度的布局)+const GRID_FADE_IN_PX = 13;+const GRID_FULL_PX = 52;+const GRID_MAX_LEVEL_PX = 480;+const GRID_MAX_ALPHA = 0.055;++export function drawWorldGrid(canvas: HTMLCanvasElement, sigma: Sigma): void {+ const ctx = canvas.getContext("2d");+ if (!ctx) return;+ const { width, height } = sigma.getDimensions();+ const dpr = window.devicePixelRatio || 1;+ const pw = Math.round(width * dpr);+ const ph = Math.round(height * dpr);+ if (canvas.width !== pw || canvas.height !== ph) {+ canvas.width = pw;+ canvas.height = ph;+ }+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, width, height);+ if (width <= 0 || height <= 0) return;++ // 世界→屏幕:两个探针点求每世界单位像素数与原点位置(无相机旋转场景)+ const p0 = sigma.graphToViewport({ x: 0, y: 0 });+ const p1 = sigma.graphToViewport({ x: 1, y: 0 });+ const ppw = p1.x - p0.x;+ if (!Number.isFinite(ppw) || ppw <= 0) return;++ // 最细可见层级:屏幕间距 ≥ 淡入阈值的最小 4 幂格距+ let spacing = GRID_BASE_WORLD;+ while (spacing * ppw < GRID_FADE_IN_PX) spacing *= 4;+ while (spacing * ppw >= GRID_FADE_IN_PX * 4) spacing /= 4;++ for (let sp = spacing; sp * ppw < GRID_MAX_LEVEL_PX; sp *= 4) {+ const ss = sp * ppw;+ const t = Math.min(+ 1,+ (ss - GRID_FADE_IN_PX) / (GRID_FULL_PX - GRID_FADE_IN_PX),+ );+ if (t <= 0) continue;+ ctx.strokeStyle = `rgba(255,255,255,${(GRID_MAX_ALPHA * t).toFixed(4)})`;+ ctx.lineWidth = 1;+ ctx.beginPath();+ const startX = ((p0.x % ss) + ss) % ss;+ for (let x = startX; x <= width; x += ss) {+ const px = Math.round(x) + 0.5;+ ctx.moveTo(px, 0);+ ctx.lineTo(px, height);+ }+ const startY = ((p0.y % ss) + ss) % ss;+ for (let y = startY; y <= height; y += ss) {+ const py = Math.round(y) + 0.5;+ ctx.moveTo(0, py);+ ctx.lineTo(width, py);+ }+ ctx.stroke();+ }+}