dsh-plugin-memory 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  所有记录跟随 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/) 风格;版本号与 `package.json` 保持一致。
4
4
 
5
+ ## [0.16.0] - 2026-11-04
6
+
7
+ ### Changed(0.16.0:记忆图谱改为 3D 球面)
8
+
9
+ - **图谱视图从 2D SVG 换成 Canvas 3D**(方案 B):Fibonacci 球面布局(按 type 分色带、确定性)→ 透视投影;拖空白旋转、滚轮缩放、拖节点 3D 整理布局、双击空白重置、自动慢转(尊重 `prefers-reduced-motion`)。
10
+ - **选中/悬停即时高亮邻居**:悬停即点亮邻居(不等点击);点击判定改为「位移 ≤5px 且时长 ≤350ms」双阈值——修复 demo 里轻点一下被判成拖拽、关联点不立即显示的问题。选中节点最后绘制(不被遮挡)、邻居标签显示、卡片内详情行。
11
+ - 新增 `lib/graph-3d.js`(球面分布/旋转/投影/深度排序/命中,纯函数);`client.js` 内联同一套数学并有测试对齐(防止与模块漂移)。2D SVG 渲染撤下,旧的 2D 内联数学保留给测试与静态报告。
12
+
13
+ - **浅色主题配色修正**:设置面板浅色主题下,节点发光把颜色晕成灰白(用户反馈「颜色有点奇怪」);改为按实际渲染背景明暗自适应——浅色:实心节点 + 白描边、深色标签、加深的边色;深色:保留发光与亮标签。主题判断读真实背景色(不猜 CSS 变量名),`isLightColor` 有测试。
14
+
15
+ ### Tests
16
+
17
+ - `graph-3d` 8 条(球面确定性/旋转可逆/投影/深度排序/命中);`graph-card` 新增内联 3D 数学一致性 + 主题判断;全量 **310/310** + self-test PASS。
18
+
5
19
  ## [0.15.2] - 2026-11-04
6
20
 
7
21
  ### Docs
package/README.md CHANGED
@@ -49,7 +49,7 @@ After that the loop is simple: the agent writes memories back as you work, and y
49
49
  - **Automatic index upkeep (declarative compilation)**: index lines are no longer hand-written. A page declares `summary:` in its frontmatter, and `dsh-memory index --write` rewrites the line as a projection of it (tag ≤32 / summary ≤48 / whole line ≤132 characters), **changing only line content while preserving sections and order byte for byte**, and idempotently. `index --check` gives a machine verdict (non-zero exit when there is drift), and `index --sync-frontmatter` backfills summaries already written in the index into the pages (a one-off migration for older stores). The digest reminder appends a note when the index has drifted, so the agent can fix it in passing.
50
50
  - **Cross-linking as a default action**: `index.md` is the directory (who exists); page-to-page links are the **relationships** (who relates to whom). In a real store measured here, 29 pages had only 1 genuine cross-link, yet the graph and all cross-page synthesis rest on that layer. Three places now push it together: the remember flow in `skills/memory.md`, the workflow in the `MEMORY.md` template, and the closing instruction of the digest reminder all require "add 1–3 related-page links for every page you touched this time".
51
51
  - **Link suggestions**: `dsh-memory graph --suggest` lists, for pages that have only their index entry and no content relationship, who they ought to reference — scored by shared topic tags, title words, and same type, with the reason stated (`shared #dsh` / `title word dsh` / `same type`). Report-only: whether and how to link stays the agent's call. Also available as `GET /api/memory/graph?suggest=1`.
52
- - **Memory graph**: a read-only relationship graph in the settings page — not just the `index.md` star (the index is connected to everything), but the relationships pages **already encode and nobody ever drew**: index routing (`index.md` points at every page — the largest edge set in the store, 43 edges; earlier versions skipped meta files, which left the index stranded on the graph), explicit markdown links between pages (with relative path resolution), and shared frontmatter tags (generic container tags like `project`/`skill` are ignored; dense tags go through an anchor chain rather than all-to-all). Coordinates are computed once on the server by `lib/graph-layout.js` (deterministic, no randomness, no dependencies); the client only draws SVG. **Interactive**: wheel zoom (cursor-centred, 0.4×–2.5×, non-passive listener so the settings page does not scroll along), drag empty space to pan, `Reset view` to return to the whole graph; hold a node to drag it, direct neighbours follow slightly by distance, and it eases back to the layout on release — transitions pause during a drag for 1:1 tracking, using an O(neighbours) local relaxation instead of a per-frame full force simulation (which stalls at a few hundred pages). Hover highlights the neighbourhood; the first render blooms out from the centre (respecting `prefers-reduced-motion`). The graph **auto-refreshes every 25 seconds** (changes appear while the panel is open, with "updated at HH:MM:SS" in the subtitle); a failed fetch keeps the previous graph instead of clearing it. The view maths (`zoomAt`/`panBy`/`toGraphPoint`) are pure functions in `lib/graph-view.js` with tests — "the zoom centre must not drift" is pinned down. `GET /api/memory/graph` (read-only, live; `?types=1` adds weak same-type edges). Three edge kinds are distinguishable: page links = solid blue, index routing = grey dashed, shared tags = thin lines.
52
+ - **Memory graph (3D, v0.16.0)**: a read-only relationship graph in the settings page, now an interactive **3D sphere** rendered on Canvas (zero dependency, no WebGL): Fibonacci-sphere placement (same type forms a contiguous colour band; deterministic, no randomness), perspective projection, depth fog and node glow. **Interactive**: drag empty space to rotate, wheel to zoom (0.5×–2.4×), drag a node to arrange it in 3D (positions survive the 25-second live refresh), double-click empty space to reset, auto-spin (disabled when `prefers-reduced-motion`). **Hover or click lights up the neighbourhood immediately**; click detection uses a displacement+duration double threshold (≤5px, ≤350ms), so a light tap is no longer mistaken for a drag — that was the demo bug where neighbours did not light up on click. The selected node is drawn last (never occluded), neighbours keep their labels, and the card shows the selected node's type/degree/neighbour count. The 3D maths lives in `lib/graph-3d.js` (pure functions with tests) and is mirrored inside `client.js` (the client can only require platform seeds) with a consistency test pinning both. Three edge kinds stay distinguishable: page links = solid blue, index routing = grey dashed, shared tags = thin violet. `GET /api/memory/graph` (read-only, live).
53
53
  - **`dsh-memory checkup`**: folds the four readers (lint's integrity, status's counts, the dashboard's size and freshness, graph's relationships) into **one prioritised report** — size, freshness bars, connectivity, consistency checks, ending with "the N things most worth doing". The four numbers are diagnosis; "do these three things" is the product. Exits non-zero when there is work to do, so scripts can consume it. `--boot=N` computes the index share against your boot budget.
54
54
  - **Memory health dashboard**: below the same section is a **read-only** dashboard — memory pages / index routes / word count, an access-freshness bar chart (today / ≤7 / ≤30 / ≤90 / >90 days), four health verdicts (index links, orphan pages, frontmatter, freshness) with a health score, stale-page candidates, and the 5 most recent log entries. Data comes from the new `GET /api/memory/insights` (computed live per request, never cached), and its criteria share a source with `dsh-memory lint`, so the dashboard and the CLI cannot contradict each other.
55
55
  - **Zero build**: plain ESM JavaScript, no compilation step, usable straight after `pnpm add`.
package/README.zh.md CHANGED
@@ -51,7 +51,7 @@ dsh plugin --profile <profile> add dsh-plugin-memory
51
51
  - **index 自动整理(声明式编译)**:索引行不再手写。页面在 frontmatter 里声明 `summary:`,`dsh-memory index --write` 把行重写为它的投影(标签 ≤32 / 摘要 ≤48 / 整行 ≤132 字符),**只改行内容,分节与顺序逐字节保留**,且幂等。`index --check` 给机器判定(有漂移退出码非 0),`index --sync-frontmatter` 把已写在 index 里的摘要回填进页面(老库一次性迁移)。digest 提醒会在索引漂移时附一句提示,agent 顺手就能修。
52
52
  - **互链成为默认动作**:`index.md` 是目录(谁存在),页间互链才是**关系**(谁和谁有关)——实测一个真实记忆库里 29 页只有 1 条真互链,而图谱与跨页综合全都建立在这层关系上。现在三处一起推:`skills/memory.md` 的 remember 流程、`MEMORY.md` 模板的工作流、以及 digest 提醒的收尾指令,都明确要求"给这次碰过的页面各补 1–3 条相关页链接"。
53
53
  - **补链建议**:`dsh-memory graph --suggest` 列出「只有索引入口、没有任何内容关系」的页面该引用谁——按共享主题 tag、标题词、同类型打分,并说明理由(`共享 #dsh` / `标题词 dsh` / `同类型`)。只报告不写入:是否连、怎么连由 agent 决定。`GET /api/memory/graph?suggest=1` 同源。
54
- - **记忆图谱**:设置页里一张只读关系图 —— 不只是 `index.md` 那种"索引连着所有页"的星形,而是把页面**已经编码但没人画出来**的关系画出来:**索引路由**(`index.md` 指向每一页——这是全库最大的边集,43 条;先前版本跳过了元文件,导致 index 在图上孤立无援)、页间显式 markdown 链接(含相对路径解析)、共享 frontmatter tag(通用容器 tag 如 `project`/`skill` 会被忽略,稠密 tag 走锚点链而非全连接)。坐标由服务端 `lib/graph-layout.js` 一次性算好(确定性、无随机、无依赖),客户端只负责画 SVG。**可交互**:滚轮缩放(以光标为中心,缩放范围 0.4×–2.5×,非 passive 监听所以不会连带滚动设置页)、拖空白处平移、`重置视图` 回到全图;按住节点即可拖走,直接邻居按距离轻微跟随,松手后带缓动滑回原布局——拖动期间暂停过渡做到 1:1 跟手,用 O(邻居数) 的局部松弛而不是逐帧全量力导向(后者在几百页时会卡)。悬停高亮邻里,首次渲染从中心绽开(尊重 `prefers-reduced-motion`)。图谱**每 25 秒自动刷新**(面板开着时记忆变更会自己出现,副标题显示「更新于 HH:MM:SS」);取数失败保留上一张图而不是清空。视图数学(`zoomAt`/`panBy`/`toGraphPoint`)在 `lib/graph-view.js` 里是纯函数并有测试——缩放中心不漂移这件事必须被钉住。`GET /api/memory/graph`(只读、实时,`?types=1` 追加同类型弱边)。三类边在图上可区分:页间互链=实线蓝、索引路由=灰色虚线、共享 tag=细线。
54
+ - **记忆图谱(3D,v0.16.0)**:设置页里一张只读关系图,现在升级为可交互的 **3D 球面**,用 Canvas 手绘(零依赖、不用 WebGL):Fibonacci 球面均匀分布(同类型聚成一条色带、确定性无随机)、透视投影、景深雾化、节点发光。**可交互**:拖空白旋转、滚轮缩放(0.5×–2.4×)、**拖节点在 3D 里整理布局**(位置在 25 秒自动刷新后仍保留)、双击空白重置、自动慢转(`prefers-reduced-motion` 时默认关)。**悬停或点击立刻点亮邻居**;点击判定用「位移 + 时长」双阈值(≤5px、≤350ms),轻点一下不会再被误判成拖拽——这正是 demo 里「选中节点不立即显示关联点」的根因。选中节点最后绘制(永远不会被遮住),邻居保留标签,卡片里显示选中节点的类型/度数/邻居数。3D 数学在 `lib/graph-3d.js`(纯函数 + 测试),并在 `client.js` 里内联同一套(客户端只能 require 平台种子),有对齐测试防止漂移。三类边仍可区分:页间互链=实线蓝、索引路由=灰色虚线、共享 tag=细紫线。`GET /api/memory/graph`(只读、实时)。
55
55
  - **`dsh-memory checkup`**:把四个读者(lint 的完整性、status 的计数、看板的体量与新鲜度、graph 的关系)合成**一份带优先级的报告** —— 体量、新鲜度条形图、连接度、一致性检查,最后给出"最该做的 N 件事"。四个数字是诊断,"做这三件事"才是产品。有活干时退出码非 0,可被脚本消费。`--boot=N` 用于按你的 boot 预算计算索引占比。
56
56
  - **记忆健康看板**:同一区块下方是一张**只读**看板——记忆页数 / index 路由数 / 记忆字数、访问新鲜度条形图(今天 / ≤7 / ≤30 / ≤90 / >90 天)、四项体检结论(index 链接、孤儿页、frontmatter、新鲜度)与健康分、陈旧页候选、最近 5 条动态。数据来自新增的 `GET /api/memory/insights`(每次请求实时统计,不缓存),体检口径与 `dsh-memory lint` 同源,所以看板与 CLI 不会互相打脸。
57
57
  - **零构建**:纯 ESM JavaScript,无编译步骤,`pnpm add` 即用。
package/lib/client.js CHANGED
@@ -164,17 +164,18 @@ window.__ModuleLoader__.load({
164
164
  graphLoading: '正在构建记忆图谱…',
165
165
  graphTitle: '记忆图谱',
166
166
  graphResetView: '重置视图',
167
+ graph3dSpin: '自动旋转',
168
+ graph3dHint: '拖空白旋转 · 滚轮缩放 · 拖节点整理布局 · 悬停/点击节点高亮邻居 · 双击空白重置;只读、实时。',
169
+ graph3dNeighbours: '邻居 {count} 个',
167
170
  graphStats: '{pages} 页 · {links} 条页间互链 · {tagEdges} 条共享 tag',
168
171
  graphIndexRoutes: '{count} 条索引路由(虚线)',
169
172
  graphIsolated: '{count} 页暂时孤立',
170
173
  graphUpdatedAt: '更新于 {time}',
171
- graphRelations: '{count} 条关系',
172
174
  graphNoLinks: '页面之间还没有互相引用——图谱目前只靠共享 tag 连接。写下「见 [某页](path)」会让关系变实。',
173
175
  graphIsolatedHint: '这 {count} 页还没和别的记忆连上:{list}{more}',
174
176
  graphMore: ' 等',
175
177
  legendLinks: '━ 页间互链',
176
178
  legendIndexRoutes: '┄ 索引路由',
177
- graphHint: '细线=共享 tag。滚轮缩放 · 拖空白处平移 · 拖节点整理视图 · 悬停高亮关系;只读、实时。',
178
179
  typeIdentity: '自我',
179
180
  typeUser: '关于你',
180
181
  typeUserPreference: '偏好',
@@ -310,17 +311,18 @@ window.__ModuleLoader__.load({
310
311
  graphLoading: 'Building the memory graph…',
311
312
  graphTitle: 'Memory graph',
312
313
  graphResetView: 'Reset view',
314
+ graph3dSpin: 'Auto-spin',
315
+ graph3dHint: 'Drag empty space to rotate · wheel to zoom · drag nodes to tidy the layout · hover or click a node to light up its neighbours · double-click empty space to reset; read-only, live.',
316
+ graph3dNeighbours: 'Neighbours: {count}',
313
317
  graphStats: '{pages} pages · {links} page links · {tagEdges} shared tags',
314
318
  graphIndexRoutes: '{count} index routes (dashed)',
315
319
  graphIsolated: '{count} pages isolated',
316
320
  graphUpdatedAt: 'updated {time}',
317
- graphRelations: '{count} relations',
318
321
  graphNoLinks: 'Pages do not reference each other yet — the graph currently connects them only through shared tags. Writing "see [some page](path)" makes the relation real.',
319
322
  graphIsolatedHint: 'These {count} pages are not connected to any other memory yet: {list}{more}',
320
323
  graphMore: ' and more',
321
324
  legendLinks: '━ page links',
322
325
  legendIndexRoutes: '┄ index routes',
323
- graphHint: 'Thin line = shared tag. Wheel to zoom · drag empty space to pan · drag a node to tidy the view · hover to highlight relations; read-only, live.',
324
326
  typeIdentity: 'identity',
325
327
  typeUser: 'about you',
326
328
  typeUserPreference: 'preference',
@@ -1583,257 +1585,486 @@ window.__ModuleLoader__.load({
1583
1585
  * 图谱视图:拿到 nodes/edges 就画(纯渲染,无副作用)。拖动与悬停是它
1584
1586
  * 自己维护的临时状态;`memo` 隔断父级重渲染带来的 hooks 调用。
1585
1587
  */
1586
- const GraphView = React.memo(function GraphView(props) {
1587
- const { graph, fetchedAt } = props
1588
- const t = useT(props)
1589
- const [hover, setHover] = React.useState(undefined)
1590
- const [dragPositions, setDragPositions] = React.useState(undefined)
1591
- const [dragging, setDragging] = React.useState(false)
1592
- const [dropAnim, setDropAnim] = React.useState(false)
1593
- const svgRef = React.useRef(null)
1594
- const dragRef = React.useRef(undefined)
1595
- const [view, setView] = React.useState({ x: 0, y: 0, w: GRAPH_W, h: GRAPH_H })
1596
- const [zoomed, setZoomed] = React.useState(false)
1597
- const panRef = React.useRef(undefined)
1598
- const viewRef = React.useRef({ x: 0, y: 0, w: GRAPH_W, h: GRAPH_H })
1599
- const firstPaint = React.useRef(true)
1600
- React.useEffect(() => { viewRef.current = view }, [view])
1601
- const basePositions = React.useMemo(() => {
1602
- const map = new Map()
1603
- for (const node of graph.nodes ?? []) map.set(node.id, { x: node.x, y: node.y })
1604
- return map
1605
- }, [graph])
1588
+ // ---------------- 记忆图谱(3D canvas,方案 B) ----------------
1589
+ //
1590
+ // 球面布局 + 透视投影,Canvas 绘制。交互:拖空白旋转、滚轮缩放、拖节点
1591
+ // 整理布局、悬停/点击高亮邻居、双击空白重置。
1592
+ //
1593
+ // 点击 vs 拖拽用「位移 + 时长」双阈值:demo 里只靠 3px 位移判定太急,
1594
+ // 轻点一下手指抖两像素就变成拖拽、选中不生效——也就是用户反馈的
1595
+ // 「选择节点不能及时显示出关联的点」。悬停也即时高亮,不等点击。
1596
+ const GRAPH3D = {
1597
+ width: 560,
1598
+ height: 400,
1599
+ radius: 250,
1600
+ focal: 900,
1601
+ camera: 340,
1602
+ zoomMin: 0.5,
1603
+ zoomMax: 2.4,
1604
+ clickSlop: 5,
1605
+ clickMs: 350,
1606
+ }
1606
1607
 
1607
- // Bloom in from the centre, once, unless reduced motion is asked. Graph
1608
- // refreshes must not replay it (memory edits can arrive every few seconds).
1609
- React.useEffect(() => {
1610
- const el = svgRef.current
1611
- if (el === null) return undefined
1612
- if (!firstPaint.current) return undefined
1613
- firstPaint.current = false
1614
- const reduced = typeof window !== 'undefined'
1615
- && typeof window.matchMedia === 'function'
1616
- && window.matchMedia('(prefers-reduced-motion: reduce)').matches
1617
- if (reduced) {
1618
- el.classList.remove('anim-off')
1619
- return undefined
1608
+ // 以下数学内联自 lib/graph-3d.js(客户端只能 require 平台种子)。
1609
+ const GRAPH3D_GOLDEN = Math.PI * (3 - Math.sqrt(5))
1610
+
1611
+ function graph3dSphere(nodes, radius) {
1612
+ const sorted = [...nodes].sort((a, b) => {
1613
+ const byType = String(a.type ?? '').localeCompare(String(b.type ?? ''))
1614
+ return byType !== 0 ? byType : String(a.id).localeCompare(String(b.id))
1615
+ })
1616
+ const count = sorted.length
1617
+ return sorted.map((node, index) => {
1618
+ const y = 1 - ((index + 0.5) * 2) / count
1619
+ const ring = Math.sqrt(Math.max(0, 1 - y * y))
1620
+ const angle = index * GRAPH3D_GOLDEN
1621
+ return {
1622
+ id: node.id,
1623
+ x: Math.cos(angle) * ring * radius,
1624
+ y: y * radius,
1625
+ z: Math.sin(angle) * ring * radius,
1620
1626
  }
1621
- el.classList.add('anim-off')
1622
- el.classList.add('entering')
1623
- const raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
1624
- raf(() => {
1625
- el.classList.remove('anim-off')
1626
- el.classList.remove('entering')
1627
- })
1628
- return () => { el.classList.remove('anim-off', 'entering') }
1629
- }, [graph])
1627
+ })
1628
+ }
1630
1629
 
1631
- const nodes = graph.nodes ?? []
1632
- const edges = graph.edges ?? []
1633
- const stats = graph.stats ?? {}
1634
- if (nodes.length === 0) return null
1630
+ function graph3dRotate(point, yaw, pitch) {
1631
+ const cy = Math.cos(yaw)
1632
+ const sy = Math.sin(yaw)
1633
+ const cp = Math.cos(pitch)
1634
+ const sp = Math.sin(pitch)
1635
+ const x1 = point.x * cy - point.z * sy
1636
+ const z1 = point.x * sy + point.z * cy
1637
+ return { id: point.id, x: x1, y: point.y * cp - z1 * sp, z: point.y * sp + z1 * cp }
1638
+ }
1639
+
1640
+ function graph3dUnrotate(point, yaw, pitch) {
1641
+ const cy = Math.cos(-yaw)
1642
+ const sy = Math.sin(-yaw)
1643
+ const cp = Math.cos(-pitch)
1644
+ const sp = Math.sin(-pitch)
1645
+ const y1 = point.y * cp - point.z * sp
1646
+ const z1 = point.y * sp + point.z * cp
1647
+ return { id: point.id, x: point.x * cy - z1 * sy, y: y1, z: point.x * sy + z1 * cy }
1648
+ }
1635
1649
 
1636
- const byId = new Map(nodes.map((node) => [node.id, node]))
1637
- const neighbours = new Map()
1638
- for (const e of edges) {
1639
- if (!neighbours.has(e.source)) neighbours.set(e.source, new Set())
1640
- if (!neighbours.has(e.target)) neighbours.set(e.target, new Set())
1641
- neighbours.get(e.source).add(e.target)
1642
- neighbours.get(e.target).add(e.source)
1650
+ function graph3dProject(node, view) {
1651
+ const rotated = graph3dRotate(node, view.yaw, view.pitch)
1652
+ const scale = (GRAPH3D.focal / Math.max(60, GRAPH3D.focal + rotated.z + GRAPH3D.camera)) * view.zoom
1653
+ // 1 = nearest the camera, 0 = far pole.
1654
+ const depth = Math.max(0, Math.min(1, (GRAPH3D.radius - rotated.z) / (2 * GRAPH3D.radius)))
1655
+ return {
1656
+ id: node.id,
1657
+ x: GRAPH3D.width / 2 + rotated.x * scale,
1658
+ y: GRAPH3D.height / 2 + rotated.y * scale,
1659
+ z: rotated.z,
1660
+ scale,
1661
+ depth,
1643
1662
  }
1644
- const lit = (id) => hover === undefined || hover === id || (neighbours.get(hover)?.has(id) ?? false)
1645
- const litEdge = (e) => hover === undefined || e.source === hover || e.target === hover
1646
- const posOf = (node) => dragPositions?.get(node.id) ?? node
1647
-
1648
- /** Pointer position in graph coordinates, honouring the current zoom. */
1649
- const toGraphPoint = (event) => {
1650
- const el = svgRef.current
1651
- const rect = el?.getBoundingClientRect?.()
1652
- if (rect === undefined || rect.width === 0 || rect.height === 0) {
1653
- return { x: event.clientX, y: event.clientY }
1663
+ }
1664
+
1665
+ function graph3dHit(points, x, y, radiusOf) {
1666
+ let best = null
1667
+ let bestDistance = Infinity
1668
+ for (const point of points) {
1669
+ const distance = Math.hypot(point.x - x, point.y - y)
1670
+ if (distance <= radiusOf(point) && distance < bestDistance) {
1671
+ best = point
1672
+ bestDistance = distance
1654
1673
  }
1655
- return toGraphPointIn(viewRef.current, rect, event.clientX, event.clientY)
1656
1674
  }
1675
+ return best
1676
+ }
1657
1677
 
1658
- /** Zoom about a graph point so it stays under the cursor. */
1659
- const applyView = (next) => {
1660
- viewRef.current = next
1661
- setView(next)
1662
- setZoomed(isZoomedView(next))
1663
- }
1664
- const zoomBy = (fx, fy, factor) => applyView(zoomAt(viewRef.current, fx, fy, factor))
1665
- const resetView = () => applyView(resetViewState())
1678
+ function graph3dHexToRgba(hex, alpha) {
1679
+ const value = String(hex ?? '#8b8f96').replace('#', '')
1680
+ const full = value.length === 3 ? value.split('').map((c) => c + c).join('') : value
1681
+ const num = Number.parseInt(full, 16)
1682
+ if (!Number.isFinite(num)) return `rgba(139,143,150,${alpha})`
1683
+ return `rgba(${(num >> 16) & 255},${(num >> 8) & 255},${num & 255},${alpha})`
1684
+ }
1666
1685
 
1667
- // Wheel zoom is registered by hand instead of via onWheel so it can be
1668
- // non-passive: otherwise preventDefault is ignored and the settings page
1669
- // scrolls while the user is trying to zoom.
1670
- React.useEffect(() => {
1671
- const el = svgRef.current
1672
- if (el === null || typeof el.addEventListener !== 'function') return undefined
1673
- const onWheel = (event) => {
1674
- event.preventDefault()
1675
- const p = toGraphPointIn(viewRef.current, el.getBoundingClientRect(), event.clientX, event.clientY)
1676
- zoomBy(p.x, p.y, event.deltaY < 0 ? 1 / 1.15 : 1.15)
1686
+ /** 一帧 3D 场景:边按深度淡出、节点发光、选中置顶、标签按 LOD 显示。
1687
+ * 浅色主题不画发光——浅底上发光会把节点晕成一片灰白,看着「颜色奇怪」。 */
1688
+ function drawGraph3D(ctx, model, state, dpr, theme) {
1689
+ const view = state.view
1690
+ const selected = state.selected
1691
+ const hovered = state.hovered
1692
+ const projected = model.nodes.map((node) => graph3dProject(node, view))
1693
+ const byIdProj = new Map(projected.map((p) => [p.id, p]))
1694
+ projected.sort((a, b) => a.z - b.z) // far first
1695
+ const isNeighbour = (id) => selected !== undefined && (model.adjacency.get(selected)?.has(id) ?? false)
1696
+ const lit = (id) => selected === undefined || id === selected || isNeighbour(id)
1697
+ const selectedPoint = selected !== undefined ? byIdProj.get(selected) : undefined
1698
+ const light = theme.light
1699
+
1700
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
1701
+ ctx.clearRect(0, 0, GRAPH3D.width, GRAPH3D.height)
1702
+
1703
+ for (const edge of model.edges) {
1704
+ const a = byIdProj.get(edge.source)
1705
+ const b = byIdProj.get(edge.target)
1706
+ if (a === undefined || b === undefined) continue
1707
+ const on = selected !== undefined && (edge.source === selected || edge.target === selected)
1708
+ const hot = hovered !== undefined && (edge.source === hovered || edge.target === hovered)
1709
+ // 浅色背景上边要更实一点;深色背景可以淡,靠发光补层次。
1710
+ const base = light
1711
+ ? (edge.kind === 'index' ? 0.32 : edge.kind === 'tag' ? 0.36 : 0.68)
1712
+ : (edge.kind === 'index' ? 0.16 : edge.kind === 'tag' ? 0.2 : 0.45)
1713
+ const depthFactor = light
1714
+ ? 0.75 + 0.25 * ((a.depth + b.depth) / 2)
1715
+ : 0.4 + 0.6 * ((a.depth + b.depth) / 2)
1716
+ const alpha = (on || hot ? 0.9 : lit(edge.source) && lit(edge.target) ? base : 0.05) * depthFactor
1717
+ ctx.strokeStyle = theme.edges[edge.kind] ?? theme.edges.link
1718
+ ctx.globalAlpha = Math.max(0.02, Math.min(1, alpha))
1719
+ ctx.lineWidth = edge.kind === 'link' ? 1.2 : 0.8
1720
+ ctx.setLineDash(edge.kind === 'index' ? [3, 4] : [])
1721
+ ctx.beginPath()
1722
+ ctx.moveTo(a.x, a.y)
1723
+ ctx.lineTo(b.x, b.y)
1724
+ ctx.stroke()
1725
+ }
1726
+ ctx.setLineDash([])
1727
+
1728
+ // 选中节点最后画:它永远不该被别的节点盖住。
1729
+ const order = projected.filter((p) => p.id !== selected)
1730
+ if (selectedPoint !== undefined) order.push(selectedPoint)
1731
+ for (const p of order) {
1732
+ const node = model.byId.get(p.id)
1733
+ if (node === undefined) continue
1734
+ const r = Math.max(1.5, node.baseR * p.scale)
1735
+ const alpha = lit(p.id)
1736
+ ? (light ? 0.9 + 0.1 * p.depth : 0.3 + 0.7 * p.depth)
1737
+ : (light ? 0.28 : 0.16)
1738
+ const isSelected = p.id === selected
1739
+ const isHovered = p.id === hovered
1740
+ const color = node.color ?? '#8b8f96'
1741
+ ctx.globalAlpha = Math.max(0.12, Math.min(1, alpha))
1742
+ if (light) {
1743
+ // 浅色主题:实心圆 + 白描边,绝不发光(发光在浅底上变成脏灰白)。
1744
+ ctx.fillStyle = color
1745
+ ctx.beginPath()
1746
+ ctx.arc(p.x, p.y, r, 0, Math.PI * 2)
1747
+ ctx.fill()
1748
+ ctx.strokeStyle = 'rgba(255,255,255,0.95)'
1749
+ ctx.lineWidth = 1.2
1750
+ ctx.stroke()
1751
+ } else {
1752
+ const glow = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, r * 2.6)
1753
+ glow.addColorStop(0, graph3dHexToRgba(color, 0.9))
1754
+ glow.addColorStop(0.5, graph3dHexToRgba(color, 0.3))
1755
+ glow.addColorStop(1, graph3dHexToRgba(color, 0))
1756
+ ctx.fillStyle = glow
1757
+ ctx.beginPath()
1758
+ ctx.arc(p.x, p.y, r * 2.6, 0, Math.PI * 2)
1759
+ ctx.fill()
1760
+ ctx.globalAlpha = Math.min(1, (isSelected ? 1 : alpha) + 0.1)
1761
+ ctx.fillStyle = color
1762
+ ctx.beginPath()
1763
+ ctx.arc(p.x, p.y, r, 0, Math.PI * 2)
1764
+ ctx.fill()
1677
1765
  }
1678
- el.addEventListener('wheel', onWheel, { passive: false })
1679
- return () => el.removeEventListener('wheel', onWheel)
1680
- }, [])
1766
+ if (isSelected || isHovered) {
1767
+ ctx.globalAlpha = 1
1768
+ ctx.strokeStyle = isSelected
1769
+ ? (light ? '#1f2328' : '#ffffff')
1770
+ : (light ? 'rgba(31,35,40,0.65)' : 'rgba(255,255,255,0.7)')
1771
+ ctx.lineWidth = 1.6
1772
+ ctx.beginPath()
1773
+ ctx.arc(p.x, p.y, r + 4, 0, Math.PI * 2)
1774
+ ctx.stroke()
1775
+ }
1776
+ const showLabel = isSelected || isHovered || isNeighbour(p.id) || (p.depth > 0.72 && p.scale > 0.9)
1777
+ if (showLabel) {
1778
+ const label = String(node.label).length > 18 ? `${String(node.label).slice(0, 17)}…` : String(node.label)
1779
+ ctx.globalAlpha = isSelected || isHovered ? 1 : 0.88
1780
+ ctx.font = '11px -apple-system, "PingFang SC", sans-serif'
1781
+ ctx.textAlign = 'center'
1782
+ ctx.textBaseline = 'bottom'
1783
+ ctx.lineWidth = 3
1784
+ ctx.strokeStyle = light ? 'rgba(255,255,255,0.9)' : 'rgba(0,0,0,0.35)'
1785
+ ctx.strokeText(label, p.x, p.y - r - 4)
1786
+ ctx.fillStyle = isSelected || isHovered ? theme.labelStrong : theme.label
1787
+ ctx.fillText(label, p.x, p.y - r - 4)
1788
+ }
1789
+ }
1790
+ ctx.globalAlpha = 1
1791
+ }
1681
1792
 
1682
- /** Drag empty canvas to pan. */
1683
- const panStart = (event) => {
1684
- if (dragRef.current !== undefined) return
1685
- if (event.button !== undefined && event.button !== 0) return
1686
- const v = viewRef.current
1687
- const rect = event.currentTarget?.getBoundingClientRect?.()
1688
- if (rect === undefined) return
1689
- event.preventDefault?.()
1690
- panRef.current = {
1691
- clientX: event.clientX,
1692
- clientY: event.clientY,
1693
- view: v,
1694
- scaleX: v.w / rect.width,
1695
- scaleY: v.h / rect.height,
1793
+ /** 从真实渲染背景判断明暗主题;CSS 变量读不到时一路向上找实际背景色。 */
1794
+ function graphCanvasTheme(canvas) {
1795
+ const style = typeof getComputedStyle === 'function' ? getComputedStyle(canvas) : undefined
1796
+ const cssVar = (name) => (style?.getPropertyValue?.(name) || '').trim()
1797
+ let background = ''
1798
+ if (typeof getComputedStyle === 'function' && typeof document !== 'undefined') {
1799
+ let node = canvas
1800
+ while (node && node !== document.documentElement) {
1801
+ const bg = getComputedStyle(node).backgroundColor
1802
+ if (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') {
1803
+ background = bg
1804
+ break
1805
+ }
1806
+ node = node.parentElement
1696
1807
  }
1808
+ if (background === '' && document.body) background = getComputedStyle(document.body).backgroundColor
1809
+ }
1810
+ const light = isLightColor(background)
1811
+ return {
1812
+ light,
1813
+ label: light ? '#3d4451' : '#e8ecf7',
1814
+ labelStrong: light ? '#1f2328' : '#ffffff',
1815
+ edges: light
1816
+ ? { link: '#2563eb', index: '#6b7280', tag: '#7c3aed' }
1817
+ : {
1818
+ link: cssVar('--dsw-alias-brand-primary') || '#4c8bf5',
1819
+ index: cssVar('--dsw-alias-label-secondary') || '#8b8f96',
1820
+ tag: '#8b7bf5',
1821
+ },
1697
1822
  }
1698
- const panMove = (event) => {
1699
- const pan = panRef.current
1700
- if (pan === undefined) return
1701
- event.preventDefault?.()
1702
- applyView(panBy(pan.view, event.clientX - pan.clientX, event.clientY - pan.clientY,
1703
- { scaleX: pan.scaleX, scaleY: pan.scaleY }))
1823
+ }
1824
+
1825
+ function isLightColor(value) {
1826
+ if (typeof value !== 'string' || value.length === 0) return false
1827
+ const text = value.trim().toLowerCase()
1828
+ const rgb = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(text)
1829
+ if (rgb !== null) {
1830
+ const lum = (0.299 * Number(rgb[1]) + 0.587 * Number(rgb[2]) + 0.114 * Number(rgb[3])) / 255
1831
+ return lum > 0.55
1704
1832
  }
1705
- const panEnd = () => { panRef.current = undefined }
1706
-
1707
- const endDrag = () => {
1708
- if (dragRef.current === undefined) return
1709
- dragRef.current = undefined
1710
- setDragging(false)
1711
- setDragPositions(undefined) // CSS transition glides everything back
1712
- setDropAnim(false)
1833
+ const hex = /^#([0-9a-f]{3,8})$/.exec(text)
1834
+ if (hex !== null) {
1835
+ const digits = hex[1].length === 3 ? hex[1].split('').map((c) => c + c).join('') : hex[1].slice(0, 6)
1836
+ const num = Number.parseInt(digits, 16)
1837
+ return (0.299 * ((num >> 16) & 255) + 0.587 * ((num >> 8) & 255) + 0.114 * (num & 255)) / 255 > 0.55
1713
1838
  }
1839
+ return false
1840
+ }
1714
1841
 
1715
- const handlePointerDown = (event, node) => {
1716
- if (event.button !== undefined && event.button !== 0) return
1717
- event.preventDefault?.()
1718
- dragRef.current = { id: node.id, pointerId: event.pointerId }
1719
- try {
1720
- event.currentTarget?.setPointerCapture?.(event.pointerId)
1721
- } catch {
1722
- // Capture is an optimisation; without it the element's own
1723
- // pointermove events still drive the drag.
1842
+ const GraphView = React.memo(function GraphView(props) {
1843
+ const { graph, fetchedAt } = props
1844
+ const t = useT(props)
1845
+ const nodes = graph.nodes ?? []
1846
+ const edges = graph.edges ?? []
1847
+ const stats = graph.stats ?? {}
1848
+ const canvasRef = React.useRef(null)
1849
+ // 尊重系统的「减少动态效果」:默认不自动转,但仍可手动旋转。
1850
+ const reducedMotion = typeof window !== 'undefined'
1851
+ && typeof window.matchMedia === 'function'
1852
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches
1853
+ const stateRef = React.useRef({
1854
+ view: { yaw: 0.55, pitch: -0.2, zoom: 1 },
1855
+ selected: undefined,
1856
+ hovered: undefined,
1857
+ drag: undefined,
1858
+ spin: !reducedMotion,
1859
+ })
1860
+ const [selected, setSelected] = React.useState(undefined)
1861
+ const [spin, setSpin] = React.useState(!reducedMotion)
1862
+ // 用户拖过的节点位置:轮询刷新时保留,别把布局打回原形。
1863
+ const draggedRef = React.useRef(new Map())
1864
+
1865
+ const model = React.useMemo(() => {
1866
+ const list = nodes.map((n) => ({
1867
+ id: n.id,
1868
+ label: n.label,
1869
+ type: n.type,
1870
+ color: n.color,
1871
+ degree: n.degree ?? 0,
1872
+ hub: n.hub === true,
1873
+ x: 0,
1874
+ y: 0,
1875
+ z: 0,
1876
+ baseR: 4.5 + Math.min(9, (n.degree ?? 0) * 0.6),
1877
+ }))
1878
+ const positions = graph3dSphere(list, GRAPH3D.radius)
1879
+ const byPos = new Map(positions.map((p) => [p.id, p]))
1880
+ for (const node of list) {
1881
+ const pos = byPos.get(node.id)
1882
+ node.x = pos.x
1883
+ node.y = pos.y
1884
+ node.z = pos.z
1724
1885
  }
1725
- setDragging(true)
1726
- setDragPositions(applyDrag(basePositions, node.id, toGraphPoint(event), edges,
1727
- { width: GRAPH_W, height: GRAPH_H }))
1728
- }
1886
+ for (const [id, pos] of draggedRef.current) {
1887
+ const node = list.find((n) => n.id === id)
1888
+ if (node !== undefined) {
1889
+ node.x = pos.x
1890
+ node.y = pos.y
1891
+ node.z = pos.z
1892
+ }
1893
+ }
1894
+ const byId = new Map(list.map((n) => [n.id, n]))
1895
+ const adjacency = new Map(list.map((n) => [n.id, new Set()]))
1896
+ const edgeList = edges.filter((e) => byId.has(e.source) && byId.has(e.target))
1897
+ for (const edge of edgeList) {
1898
+ adjacency.get(edge.source).add(edge.target)
1899
+ adjacency.get(edge.target).add(edge.source)
1900
+ }
1901
+ return { nodes: list, byId, edges: edgeList, adjacency }
1902
+ }, [graph])
1729
1903
 
1730
- const handlePointerMove = (event) => {
1731
- const drag = dragRef.current
1732
- if (drag === undefined) return
1733
- event.preventDefault?.()
1734
- setDragPositions(applyDrag(basePositions, drag.id, toGraphPoint(event), edges,
1735
- { width: GRAPH_W, height: GRAPH_H }))
1736
- }
1904
+ React.useEffect(() => { stateRef.current.selected = selected }, [selected])
1905
+ React.useEffect(() => { stateRef.current.spin = spin }, [spin])
1737
1906
 
1738
- const handlePointerUp = (event) => {
1739
- const drag = dragRef.current
1740
- if (drag === undefined) return
1741
- try {
1742
- event.currentTarget?.releasePointerCapture?.(drag.pointerId)
1743
- } catch {
1744
- // Already released, or never captured.
1907
+ // 渲染循环:空闲时球体慢转;画布颜色每年主题切换一次即可。
1908
+ React.useEffect(() => {
1909
+ const canvas = canvasRef.current
1910
+ if (canvas === null || typeof canvas.getContext !== 'function') return undefined
1911
+ const ctx = canvas.getContext('2d')
1912
+ if (ctx === null) return undefined
1913
+ const dpr = Math.min(2, (typeof window !== 'undefined' && window.devicePixelRatio) || 1)
1914
+ canvas.width = Math.floor(GRAPH3D.width * dpr)
1915
+ canvas.height = Math.floor(GRAPH3D.height * dpr)
1916
+ const theme = graphCanvasTheme(canvas)
1917
+ let raf = 0
1918
+ const render = () => {
1919
+ const state = stateRef.current
1920
+ if (state.spin && state.drag === undefined) state.view.yaw += 0.0028
1921
+ drawGraph3D(ctx, model, state, dpr, theme)
1922
+ raf = requestAnimationFrame(render)
1745
1923
  }
1746
- setDropAnim(true)
1747
- setTimeout(endDrag, 60)
1748
- }
1924
+ raf = requestAnimationFrame(render)
1925
+ return () => { if (raf !== 0) cancelAnimationFrame(raf) }
1926
+ }, [model])
1749
1927
 
1750
- /** One node = one <g>, so a drag transform moves dot and label together. */
1751
- const renderNode = (node) => {
1752
- const p = posOf(node)
1753
- const dx = p.x - node.x
1754
- const dy = p.y - node.y
1755
- const tip = `${node.label}\n${typeLabel(node.type, t)}`
1756
- + `${node.salience ? ` · salience:${node.salience}` : ''}`
1757
- + `${node.tags && node.tags.length > 0 ? `\n#${node.tags.join(' #')}` : ''}`
1758
- + `\n${fill(t('graphRelations'), { count: node.degree ?? 0 })}`
1759
- const showLabel = node.hub || (node.degree ?? 0) >= 2
1760
- const label = String(node.label).length > 16 ? `${String(node.label).slice(0, 15)}…` : String(node.label)
1761
- return React.createElement('g', {
1762
- key: node.id,
1763
- transform: `translate(${dx.toFixed(2)} ${dy.toFixed(2)})`,
1764
- className: lit(node.id) ? 'lit' : undefined,
1765
- style: { cursor: 'grab' },
1766
- onPointerDown: (event) => { event.stopPropagation?.(); handlePointerDown(event, node) },
1767
- onPointerMove: handlePointerMove,
1768
- onPointerUp: handlePointerUp,
1769
- onPointerCancel: handlePointerUp,
1770
- onMouseEnter: () => setHover(node.id),
1771
- onMouseLeave: () => setHover(undefined),
1772
- },
1773
- React.createElement('circle', {
1774
- cx: node.x, cy: node.y, r: node.r,
1775
- fill: node.color,
1776
- fillOpacity: lit(node.id) ? 0.95 : 0.2,
1777
- stroke: 'var(--dsw-alias-bg-layer-2, #22252a)',
1778
- strokeWidth: node.hub ? 2 : 1,
1779
- }, React.createElement('title', null, tip)),
1780
- showLabel
1781
- ? React.createElement('text', {
1782
- x: node.x + node.r + 4,
1783
- y: node.y + 3.5,
1784
- fontSize: node.hub ? 11 : 10,
1785
- fontWeight: node.hub ? 600 : 400,
1786
- fill: 'var(--dsw-alias-label-secondary, #999)',
1787
- fillOpacity: lit(node.id) ? 1 : 0.25,
1788
- style: { userSelect: 'none' },
1789
- }, label)
1790
- : null,
1791
- )
1792
- }
1928
+ // 交互:hover 即时高亮;点击用「位移 + 时长」双阈值判定(demo 的单阈值
1929
+ // 会让轻点变成拖拽,选中不生效)。
1930
+ React.useEffect(() => {
1931
+ const canvas = canvasRef.current
1932
+ if (canvas === null || typeof canvas.addEventListener !== 'function') return undefined
1933
+ const localPoint = (event) => {
1934
+ const rect = canvas.getBoundingClientRect()
1935
+ if (rect.width === 0 || rect.height === 0) return { x: event.clientX, y: event.clientY }
1936
+ return {
1937
+ x: ((event.clientX - rect.left) / rect.width) * GRAPH3D.width,
1938
+ y: ((event.clientY - rect.top) / rect.height) * GRAPH3D.height,
1939
+ }
1940
+ }
1941
+ const projectedNow = () => model.nodes.map((node) => graph3dProject(node, stateRef.current.view))
1942
+ const radiusOf = (point) => {
1943
+ const node = model.byId.get(point.id)
1944
+ return Math.max(6, (node?.baseR ?? 6) * point.scale + 5)
1945
+ }
1946
+ const hoverAt = (point) => {
1947
+ const hit = graph3dHit(projectedNow(), point.x, point.y, radiusOf)
1948
+ stateRef.current.hovered = hit?.id ?? undefined
1949
+ }
1950
+ const onDown = (event) => {
1951
+ if (event.button !== undefined && event.button !== 0) return
1952
+ const point = localPoint(event)
1953
+ const hit = graph3dHit(projectedNow(), point.x, point.y, radiusOf)
1954
+ stateRef.current.drag = {
1955
+ kind: hit !== null ? 'node' : 'rotate',
1956
+ id: hit?.id,
1957
+ pointerId: event.pointerId,
1958
+ startClientX: event.clientX,
1959
+ startClientY: event.clientY,
1960
+ lastX: point.x,
1961
+ lastY: point.y,
1962
+ startAt: Date.now(),
1963
+ moved: false,
1964
+ }
1965
+ try { canvas.setPointerCapture?.(event.pointerId) } catch { /* synthetic events have no capture */ }
1966
+ }
1967
+ const onMove = (event) => {
1968
+ const point = localPoint(event)
1969
+ const drag = stateRef.current.drag
1970
+ if (drag === undefined) {
1971
+ hoverAt(point)
1972
+ return
1973
+ }
1974
+ if (drag.pointerId !== undefined && event.pointerId !== drag.pointerId) return
1975
+ if (drag.kind === 'node') {
1976
+ const node = model.byId.get(drag.id)
1977
+ if (node === undefined) return
1978
+ const view = stateRef.current.view
1979
+ const projection = graph3dProject(node, view)
1980
+ const dx = (point.x - drag.lastX) / Math.max(0.05, projection.scale)
1981
+ const dy = (point.y - drag.lastY) / Math.max(0.05, projection.scale)
1982
+ const rotated = graph3dRotate(node, view.yaw, view.pitch)
1983
+ const world = graph3dUnrotate(
1984
+ { x: rotated.x + dx, y: rotated.y + dy, z: rotated.z },
1985
+ view.yaw,
1986
+ view.pitch,
1987
+ )
1988
+ node.x = world.x
1989
+ node.y = world.y
1990
+ node.z = world.z
1991
+ draggedRef.current.set(node.id, { x: node.x, y: node.y, z: node.z })
1992
+ drag.lastX = point.x
1993
+ drag.lastY = point.y
1994
+ drag.moved = true
1995
+ } else {
1996
+ const moved = Math.hypot(event.clientX - drag.startClientX, event.clientY - drag.startClientY)
1997
+ if (moved > 2) drag.moved = true
1998
+ if (drag.moved) {
1999
+ stateRef.current.view.yaw += (event.clientX - drag.startClientX) * 0.006
2000
+ stateRef.current.view.pitch = Math.max(
2001
+ -1.2,
2002
+ Math.min(1.2, stateRef.current.view.pitch - (event.clientY - drag.startClientY) * 0.006),
2003
+ )
2004
+ drag.startClientX = event.clientX
2005
+ drag.startClientY = event.clientY
2006
+ }
2007
+ }
2008
+ hoverAt(point)
2009
+ }
2010
+ const onUp = (event) => {
2011
+ const drag = stateRef.current.drag
2012
+ stateRef.current.drag = undefined
2013
+ if (drag === undefined) return
2014
+ const duration = Date.now() - drag.startAt
2015
+ const moved = Math.hypot(event.clientX - drag.startClientX, event.clientY - drag.startClientY)
2016
+ const isClick = !drag.moved && duration <= GRAPH3D.clickMs && moved <= GRAPH3D.clickSlop
2017
+ if (!isClick) return
2018
+ if (drag.kind === 'node') {
2019
+ const next = stateRef.current.selected === drag.id ? undefined : drag.id
2020
+ stateRef.current.selected = next
2021
+ setSelected(next)
2022
+ } else {
2023
+ stateRef.current.selected = undefined
2024
+ setSelected(undefined)
2025
+ }
2026
+ }
2027
+ const onWheel = (event) => {
2028
+ event.preventDefault()
2029
+ const factor = event.deltaY < 0 ? 1.08 : 0.92
2030
+ stateRef.current.view.zoom = Math.max(
2031
+ GRAPH3D.zoomMin,
2032
+ Math.min(GRAPH3D.zoomMax, stateRef.current.view.zoom * factor),
2033
+ )
2034
+ }
2035
+ const onDouble = (event) => {
2036
+ const point = localPoint(event)
2037
+ const hit = graph3dHit(projectedNow(), point.x, point.y, radiusOf)
2038
+ if (hit !== null) return
2039
+ stateRef.current.view = { yaw: 0.55, pitch: -0.2, zoom: 1 }
2040
+ stateRef.current.selected = undefined
2041
+ setSelected(undefined)
2042
+ }
2043
+ const onLeave = () => {
2044
+ stateRef.current.hovered = undefined
2045
+ stateRef.current.drag = undefined
2046
+ }
2047
+ canvas.addEventListener('pointerdown', onDown)
2048
+ canvas.addEventListener('pointermove', onMove)
2049
+ canvas.addEventListener('pointerup', onUp)
2050
+ canvas.addEventListener('pointercancel', onUp)
2051
+ canvas.addEventListener('pointerleave', onLeave)
2052
+ canvas.addEventListener('wheel', onWheel, { passive: false })
2053
+ canvas.addEventListener('dblclick', onDouble)
2054
+ return () => {
2055
+ canvas.removeEventListener('pointerdown', onDown)
2056
+ canvas.removeEventListener('pointermove', onMove)
2057
+ canvas.removeEventListener('pointerup', onUp)
2058
+ canvas.removeEventListener('pointercancel', onUp)
2059
+ canvas.removeEventListener('pointerleave', onLeave)
2060
+ canvas.removeEventListener('wheel', onWheel)
2061
+ canvas.removeEventListener('dblclick', onDouble)
2062
+ }
2063
+ }, [model])
1793
2064
 
1794
- const svgClass = ['dsh-memory-graph-svg', dragging ? 'dragging' : '', dropAnim ? 'graph-drop' : '']
1795
- .filter(Boolean).join(' ')
1796
- const svg = React.createElement('svg', {
1797
- ref: svgRef,
1798
- viewBox: `${view.x} ${view.y} ${view.w} ${view.h}`,
1799
- width: '100%',
1800
- className: svgClass,
1801
- style: {
1802
- display: 'block',
1803
- borderRadius: '8px',
1804
- background: 'var(--dsw-alias-bg-layer-1, transparent)',
1805
- touchAction: 'none',
1806
- cursor: zoomed ? 'grab' : 'default',
1807
- },
1808
- role: 'img',
1809
- 'aria-label': t('graphTitle'),
1810
- onPointerDown: panStart,
1811
- onPointerMove: panMove,
1812
- onPointerUp: panEnd,
1813
- onPointerLeave: panEnd,
1814
- },
1815
- edges.map((e, index) => {
1816
- const a = byId.get(e.source)
1817
- const b = byId.get(e.target)
1818
- if (a === undefined || b === undefined) return null
1819
- const pa = posOf(a)
1820
- const pb = posOf(b)
1821
- return React.createElement('line', {
1822
- key: `e${index}`,
1823
- x1: pa.x, y1: pa.y, x2: pb.x, y2: pb.y,
1824
- stroke: e.kind === 'link'
1825
- ? 'var(--dsw-alias-brand-primary, #4c8bf5)'
1826
- : e.kind === 'index'
1827
- ? 'var(--dsw-alias-label-secondary, #8b8f96)'
1828
- : 'var(--dsw-alias-border-l2, rgba(128,128,128,0.45))',
1829
- strokeWidth: e.kind === 'link' ? 1.4 : 0.7,
1830
- strokeDasharray: e.kind === 'index' ? '2 3' : undefined,
1831
- strokeOpacity: litEdge(e) ? (e.kind === 'index' ? 0.5 : 0.9) : (e.kind === 'index' ? 0.08 : 0.12),
1832
- })
1833
- }),
1834
- nodes.map(renderNode),
1835
- )
2065
+ if (nodes.length === 0) return null
1836
2066
 
2067
+ const byId = model.byId
1837
2068
  const colourOf = (type) => (nodes.find((n) => n.type === type)?.color) ?? '#8b8f96'
1838
2069
  const chips = [...new Set(nodes.map((n) => n.type))]
1839
2070
  .filter((type) => type !== 'unknown')
@@ -1844,26 +2075,38 @@ window.__ModuleLoader__.load({
1844
2075
  React.createElement('span', { style: { width: '7px', height: '7px', borderRadius: '4px', background: colourOf(type), display: 'inline-block' } }),
1845
2076
  typeLabel(type, t),
1846
2077
  ))
1847
-
1848
2078
  const isolated = stats.isolated ?? []
2079
+ const selectedNode = selected !== undefined ? byId.get(selected) : undefined
2080
+ const selectedNeighbours = selected !== undefined ? (model.adjacency.get(selected)?.size ?? 0) : 0
2081
+ const smallButtonStyle = {
2082
+ fontSize: '11px',
2083
+ padding: '2px 8px',
2084
+ borderRadius: '6px',
2085
+ cursor: 'pointer',
2086
+ border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))',
2087
+ background: 'transparent',
2088
+ color: 'var(--dsw-alias-label-secondary, #999)',
2089
+ }
2090
+
1849
2091
  return React.createElement('div', { style: cardStyle },
1850
2092
  React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: '8px' } },
1851
2093
  React.createElement('div', { style: cardTitleStyle }, t('graphTitle')),
1852
- zoomed
1853
- ? React.createElement('button', {
2094
+ React.createElement('div', { style: { display: 'flex', gap: '6px' } },
2095
+ React.createElement('button', {
1854
2096
  type: 'button',
1855
- onClick: resetView,
1856
- style: {
1857
- fontSize: '11px',
1858
- padding: '2px 8px',
1859
- borderRadius: '6px',
1860
- cursor: 'pointer',
1861
- border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))',
1862
- background: 'transparent',
1863
- color: 'var(--dsw-alias-label-secondary, #999)',
2097
+ onClick: () => setSpin((value) => !value),
2098
+ style: smallButtonStyle,
2099
+ }, `${t('graph3dSpin')}${spin ? ' ✓' : ''}`),
2100
+ React.createElement('button', {
2101
+ type: 'button',
2102
+ onClick: () => {
2103
+ stateRef.current.view = { yaw: 0.55, pitch: -0.2, zoom: 1 }
2104
+ stateRef.current.selected = undefined
2105
+ setSelected(undefined)
1864
2106
  },
1865
- }, t('graphResetView'))
1866
- : null,
2107
+ style: smallButtonStyle,
2108
+ }, t('graphResetView')),
2109
+ ),
1867
2110
  ),
1868
2111
  React.createElement('div', { style: cardSubStyle },
1869
2112
  fill(t('graphStats'), { pages: stats.pages ?? nodes.length, links: stats.links ?? 0, tagEdges: stats.tagEdges ?? 0 })
@@ -1871,7 +2114,41 @@ window.__ModuleLoader__.load({
1871
2114
  + (isolated.length > 0 ? ` · ${fill(t('graphIsolated'), { count: isolated.length })}` : '')
1872
2115
  + (fetchedAt instanceof Date ? ` · ${fill(t('graphUpdatedAt'), { time: fetchedAt.toLocaleTimeString() })}` : ''),
1873
2116
  ),
1874
- svg,
2117
+ React.createElement('canvas', {
2118
+ ref: canvasRef,
2119
+ 'aria-label': t('graphTitle'),
2120
+ role: 'img',
2121
+ style: {
2122
+ display: 'block',
2123
+ width: '100%',
2124
+ height: 'auto',
2125
+ aspectRatio: `${GRAPH3D.width} / ${GRAPH3D.height}`,
2126
+ borderRadius: '8px',
2127
+ touchAction: 'none',
2128
+ cursor: 'grab',
2129
+ },
2130
+ }),
2131
+ React.createElement('div', { style: { marginTop: '8px', fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary, #888)' } },
2132
+ t('graph3dHint'),
2133
+ ),
2134
+ selectedNode !== undefined
2135
+ ? React.createElement('div', {
2136
+ role: 'status',
2137
+ style: {
2138
+ marginTop: '6px',
2139
+ padding: '6px 8px',
2140
+ borderRadius: '6px',
2141
+ background: 'var(--dsw-alias-bg-layer-2, rgba(128,128,128,0.12))',
2142
+ fontSize: '11px',
2143
+ lineHeight: '17px',
2144
+ },
2145
+ },
2146
+ React.createElement('b', null, selectedNode.label),
2147
+ ` · ${typeLabel(selectedNode.type, t)} · degree ${selectedNode.degree} · `,
2148
+ fill(t('graph3dNeighbours'), { count: selectedNeighbours }),
2149
+ React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary, #888)' } }, selectedNode.id),
2150
+ )
2151
+ : null,
1875
2152
  React.createElement('div', { style: { marginTop: '8px' } }, ...chips),
1876
2153
  ((stats.links ?? 0) === 0 || isolated.length > 0)
1877
2154
  ? React.createElement('div', { style: { fontSize: '11px', lineHeight: '17px', color: 'var(--dsw-alias-label-secondary, #888)', marginTop: '6px' } },
@@ -1888,8 +2165,6 @@ window.__ModuleLoader__.load({
1888
2165
  React.createElement('span', { style: { color: 'var(--dsw-alias-brand-primary, #4c8bf5)' } }, t('legendLinks')),
1889
2166
  ' · ',
1890
2167
  React.createElement('span', { style: { color: '#8b8f96' } }, t('legendIndexRoutes')),
1891
- ' · ',
1892
- t('graphHint'),
1893
2168
  ),
1894
2169
  )
1895
2170
  })
@@ -2100,6 +2375,13 @@ window.__ModuleLoader__.load({
2100
2375
  MAX_VIEW_SCALE,
2101
2376
  GRAPH_W,
2102
2377
  GRAPH_H,
2378
+ GRAPH3D,
2379
+ graph3dSphere,
2380
+ graph3dRotate,
2381
+ graph3dUnrotate,
2382
+ graph3dProject,
2383
+ graph3dHit,
2384
+ isLightColor,
2103
2385
  }
2104
2386
  return module.exports
2105
2387
  },
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Deterministic 3D sphere placement + perspective projection for the memory
3
+ * graph.
4
+ *
5
+ * The client half cannot import local modules (it only gets the platform's
6
+ * `react` seat at runtime), so the same maths is **inlined** in `client.js` —
7
+ * exactly like `graph-drag`/`graph-view`. Keeping the pure implementation here
8
+ * lets Node tests pin the behaviour.
9
+ *
10
+ * No randomness: the same nodes always land on the same slots, and the same
11
+ * view always projects to the same screen coordinates. That matters because the
12
+ * panel re-renders every frame while the user rotates.
13
+ *
14
+ * @module dsh-plugin-memory/graph-3d
15
+ */
16
+
17
+ /** Defaults shared by the panel and the tests. */
18
+ export const GRAPH3D_DEFAULTS = Object.freeze({
19
+ width: 560,
20
+ height: 400,
21
+ radius: 250,
22
+ focal: 900,
23
+ camera: 340,
24
+ zoom: 1,
25
+ yaw: 0,
26
+ pitch: 0,
27
+ })
28
+
29
+ const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5))
30
+
31
+ /**
32
+ * Distribute nodes evenly over a sphere (Fibonacci sphere).
33
+ *
34
+ * Nodes are sorted by `type` then `id` first, so a given type forms a
35
+ * contiguous band on the sphere instead of being scattered — that is what makes
36
+ * the colours readable when the sphere rotates.
37
+ *
38
+ * @param {Array<{ id: string, type?: string }>} nodes
39
+ * @param {{ radius?: number }} [options]
40
+ * @returns {Array<{ id: string, x: number, y: number, z: number }>}
41
+ */
42
+ export function spherePositions(nodes, options = {}) {
43
+ const radius = options.radius ?? GRAPH3D_DEFAULTS.radius
44
+ const sorted = [...nodes].sort((a, b) => {
45
+ const byType = String(a.type ?? '').localeCompare(String(b.type ?? ''))
46
+ if (byType !== 0) return byType
47
+ return String(a.id).localeCompare(String(b.id))
48
+ })
49
+ const count = sorted.length
50
+ return sorted.map((node, index) => {
51
+ // y walks from +1 to -1; the ring radius shrinks toward the poles.
52
+ const y = 1 - ((index + 0.5) * 2) / count
53
+ const ring = Math.sqrt(Math.max(0, 1 - y * y))
54
+ const angle = index * GOLDEN_ANGLE
55
+ return {
56
+ id: node.id,
57
+ x: Math.cos(angle) * ring * radius,
58
+ y: y * radius,
59
+ z: Math.sin(angle) * ring * radius,
60
+ }
61
+ })
62
+ }
63
+
64
+ /** Rotate a world point by yaw (around Y) then pitch (around X). */
65
+ export function rotatePoint(point, yaw, pitch) {
66
+ const cy = Math.cos(yaw)
67
+ const sy = Math.sin(yaw)
68
+ const cp = Math.cos(pitch)
69
+ const sp = Math.sin(pitch)
70
+ // yaw around Y
71
+ const x1 = point.x * cy - point.z * sy
72
+ const z1 = point.x * sy + point.z * cy
73
+ // pitch around X
74
+ return {
75
+ id: point.id,
76
+ x: x1,
77
+ y: point.y * cp - z1 * sp,
78
+ z: point.y * sp + z1 * cp,
79
+ }
80
+ }
81
+
82
+ /** Inverse of {@link rotatePoint}. */
83
+ export function unrotatePoint(point, yaw, pitch) {
84
+ const cy = Math.cos(-yaw)
85
+ const sy = Math.sin(-yaw)
86
+ const cp = Math.cos(-pitch)
87
+ const sp = Math.sin(-pitch)
88
+ // undo pitch
89
+ const y1 = point.y * cp - point.z * sp
90
+ const z1 = point.y * sp + point.z * cp
91
+ // undo yaw
92
+ return {
93
+ id: point.id,
94
+ x: point.x * cy - z1 * sy,
95
+ y: y1,
96
+ z: point.x * sy + z1 * cy,
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Project one world point to screen space.
102
+ *
103
+ * @param {{ id: string, x: number, y: number, z: number }} point
104
+ * @param {object} [view] overrides: width/height/radius/focal/camera/zoom/yaw/pitch
105
+ * @returns {{ id: string, x: number, y: number, z: number, scale: number, depth: number }}
106
+ */
107
+ export function projectPoint(point, view = {}) {
108
+ const width = view.width ?? GRAPH3D_DEFAULTS.width
109
+ const height = view.height ?? GRAPH3D_DEFAULTS.height
110
+ const radius = view.radius ?? GRAPH3D_DEFAULTS.radius
111
+ const focal = view.focal ?? GRAPH3D_DEFAULTS.focal
112
+ const camera = view.camera ?? GRAPH3D_DEFAULTS.camera
113
+ const zoom = view.zoom ?? GRAPH3D_DEFAULTS.zoom
114
+ const rotated = rotatePoint(point, view.yaw ?? 0, view.pitch ?? 0)
115
+ // Perspective: nearer (smaller z) means a larger scale.
116
+ const scale = (focal / Math.max(60, focal + rotated.z + camera)) * zoom
117
+ // Depth is 1 when nearest the camera (z = -radius) and 0 at the far pole.
118
+ const depth = Math.max(0, Math.min(1, (radius - rotated.z) / (2 * radius)))
119
+ return {
120
+ id: point.id,
121
+ x: width / 2 + rotated.x * scale,
122
+ y: height / 2 + rotated.y * scale,
123
+ z: rotated.z,
124
+ scale,
125
+ depth,
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Sort projected points for painter's algorithm (farthest first by default).
131
+ * @param {Array<{ z: number }>} points
132
+ * @param {'far-first' | 'near-first'} [direction]
133
+ */
134
+ export function depthSorted(points, direction = 'far-first') {
135
+ const sorted = [...points].sort((a, b) => a.z - b.z)
136
+ return direction === 'near-first' ? sorted.reverse() : sorted
137
+ }
138
+
139
+ /**
140
+ * Return the closest projected node within its hit radius.
141
+ *
142
+ * @param {Array<{ id: string, x: number, y: number }>} points
143
+ * @param {number} x
144
+ * @param {number} y
145
+ * @param {(point: { id: string }) => number} [radiusOf]
146
+ * @returns {{ id: string, x: number, y: number } | null}
147
+ */
148
+ export function hitTest3D(points, x, y, radiusOf = () => 8) {
149
+ let best = null
150
+ let bestDistance = Infinity
151
+ for (const point of points) {
152
+ const distance = Math.hypot(point.x - x, point.y - y)
153
+ if (distance <= radiusOf(point) && distance < bestDistance) {
154
+ best = point
155
+ bestDistance = distance
156
+ }
157
+ }
158
+ return best
159
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-memory",
3
3
  "description": "Long-term memory plugin for DeepSeek Harness: persistent cross-session markdown memory with a soul/persona file, auto-injected at every session start, plus remember/recall/consolidate/forget workflows and portable migration tooling.",
4
- "version": "0.15.2",
4
+ "version": "0.16.0",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",