dsh-plugin-memory 0.5.2 → 0.7.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 +47 -0
- package/README.md +51 -12
- package/cordis.patch.yml +3 -2
- package/lib/activity-tracker.js +115 -0
- package/lib/boot.js +101 -7
- package/lib/client.js +665 -2
- package/lib/config-store.js +7 -1
- package/lib/digest-guard.js +44 -4
- package/lib/graph-drag.js +100 -0
- package/lib/graph-layout.js +137 -0
- package/lib/graph-view.js +98 -0
- package/lib/graph.js +249 -0
- package/lib/index-page.js +399 -0
- package/lib/index.js +171 -7
- package/lib/insights.js +263 -0
- package/lib/pages.js +197 -0
- package/lib/recall-nudge.js +14 -1
- package/lib/scaffold.js +11 -5
- package/lib/schema.js +4 -0
- package/lib/types/index.d.ts +121 -5
- package/package.json +1 -1
- package/scripts/memory.mjs +123 -7
- package/skills/memory.md +4 -4
package/lib/config-store.js
CHANGED
|
@@ -23,7 +23,7 @@ export function defaultConfigPath() {
|
|
|
23
23
|
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), MEMORY_CONFIG_FILENAME)
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
|
|
26
|
+
const FIELDS = ['enabled', 'memoryDir', 'autoInject', 'registerSkill', 'deferUntilUserSpeaks', 'activeSessionOnly', 'recallEnabled', 'recallIntervalMinMinutes', 'recallIntervalMaxMinutes', 'recallMaxPerSession']
|
|
27
27
|
|
|
28
28
|
function pickFields(input) {
|
|
29
29
|
const picked = {}
|
|
@@ -57,6 +57,8 @@ export class MemoryConfigStore {
|
|
|
57
57
|
: '~/.memory',
|
|
58
58
|
autoInject: options.base?.autoInject !== false,
|
|
59
59
|
registerSkill: options.base?.registerSkill !== false,
|
|
60
|
+
deferUntilUserSpeaks: options.base?.deferUntilUserSpeaks !== false,
|
|
61
|
+
activeSessionOnly: options.base?.activeSessionOnly !== false,
|
|
60
62
|
recallEnabled: options.base?.recallEnabled !== false,
|
|
61
63
|
recallIntervalMinMinutes: options.base?.recallIntervalMinMinutes ?? 30,
|
|
62
64
|
recallIntervalMaxMinutes: options.base?.recallIntervalMaxMinutes ?? 240,
|
|
@@ -86,6 +88,8 @@ export class MemoryConfigStore {
|
|
|
86
88
|
memoryDir: resolved.memoryDir,
|
|
87
89
|
autoInject: resolved.autoInject,
|
|
88
90
|
registerSkill: resolved.registerSkill,
|
|
91
|
+
deferUntilUserSpeaks: resolved.deferUntilUserSpeaks,
|
|
92
|
+
activeSessionOnly: resolved.activeSessionOnly,
|
|
89
93
|
recallEnabled: resolved.recallEnabled,
|
|
90
94
|
recallIntervalMinMinutes: resolved.recallIntervalMinMinutes,
|
|
91
95
|
recallIntervalMaxMinutes: resolved.recallIntervalMaxMinutes,
|
|
@@ -123,6 +127,8 @@ export class MemoryConfigStore {
|
|
|
123
127
|
memoryDir: next.memoryDir,
|
|
124
128
|
autoInject: next.autoInject,
|
|
125
129
|
registerSkill: next.registerSkill,
|
|
130
|
+
deferUntilUserSpeaks: next.deferUntilUserSpeaks,
|
|
131
|
+
activeSessionOnly: next.activeSessionOnly,
|
|
126
132
|
recallEnabled: next.recallEnabled,
|
|
127
133
|
recallIntervalMinMinutes: next.recallIntervalMinMinutes,
|
|
128
134
|
recallIntervalMaxMinutes: next.recallIntervalMaxMinutes,
|
package/lib/digest-guard.js
CHANGED
|
@@ -22,10 +22,37 @@
|
|
|
22
22
|
import { randomUUID } from 'node:crypto'
|
|
23
23
|
import { existsSync, statSync } from 'node:fs'
|
|
24
24
|
import { join } from 'node:path'
|
|
25
|
+
import { planIndex } from './index-page.js'
|
|
25
26
|
|
|
26
27
|
/** A digest must touch these files; their mtime is the freshness signal. */
|
|
27
28
|
export const DIGEST_MARKER_FILES = ['log.md', 'index.md']
|
|
28
29
|
|
|
30
|
+
/**
|
|
31
|
+
* One line telling the agent how far the routing table has drifted, or '' when
|
|
32
|
+
* it is in sync. Runs the same planner as `dsh-memory index --check`, so the
|
|
33
|
+
* reminder and the CLI can never disagree about what "drifted" means.
|
|
34
|
+
*
|
|
35
|
+
* Never throws: a broken or unreadable store degrades to "no hint", because a
|
|
36
|
+
* reminder must still be delivered.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} memoryDir absolute path of the memory store
|
|
39
|
+
* @returns {string} hint sentence, or ''
|
|
40
|
+
*/
|
|
41
|
+
export function buildIndexDriftHint(memoryDir) {
|
|
42
|
+
try {
|
|
43
|
+
const plan = planIndex(memoryDir)
|
|
44
|
+
const stale = plan.lines.filter((line) => line.changed).length
|
|
45
|
+
const parts = []
|
|
46
|
+
if (stale > 0) parts.push(`${stale} 行与页面不一致(\`dsh-memory index --write\` 可修)`)
|
|
47
|
+
if (plan.missing.length > 0) parts.push(`${plan.missing.length} 个新页面未收录(分节与顺序需你自己决定)`)
|
|
48
|
+
if (plan.removed.length > 0) parts.push(`${plan.removed.length} 个索引链接已失效(决定是否删行)`)
|
|
49
|
+
if (parts.length === 0) return ''
|
|
50
|
+
return `另外,记忆 index 有漂移:${parts.join(';')}。`
|
|
51
|
+
} catch {
|
|
52
|
+
return ''
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
29
56
|
/**
|
|
30
57
|
* Latest mtime (ms epoch) across the digest marker files.
|
|
31
58
|
* @param {string} memoryDir
|
|
@@ -49,9 +76,12 @@ export function lastStoreWriteMs(memoryDir) {
|
|
|
49
76
|
* Build the nudge message in the exact shape `dsh-agent-loop` expects for
|
|
50
77
|
* `followup()` (role 'user', content array, plugin source).
|
|
51
78
|
* @param {number} staleMinutes how long the store has been unwritten
|
|
79
|
+
* @param {{ indexHint?: string }} [options] optional routing-table drift line,
|
|
80
|
+
* rendered on its own so the message stays a checklist, not a paragraph
|
|
52
81
|
* @returns {{ id: string, role: 'user', content: [{type:'text', text:string}], source: {kind:'plugin', plugin:string} }}
|
|
53
82
|
*/
|
|
54
|
-
export function buildDigestNudgeMessage(staleMinutes) {
|
|
83
|
+
export function buildDigestNudgeMessage(staleMinutes, options = {}) {
|
|
84
|
+
const indexHint = typeof options.indexHint === 'string' ? options.indexHint.trim() : ''
|
|
55
85
|
return {
|
|
56
86
|
id: `memory-digest-${randomUUID()}`,
|
|
57
87
|
role: 'user',
|
|
@@ -61,6 +91,7 @@ export function buildDigestNudgeMessage(staleMinutes) {
|
|
|
61
91
|
`【记忆 digest 提醒】距上次记忆写入已超过 ${staleMinutes} 分钟。`,
|
|
62
92
|
'请现在执行 remember 沉淀:把本次会话值得持久化的关键事实、偏好、决策写回记忆库(更新对应页面与 index.md,并追加 log.md 条目)。',
|
|
63
93
|
'若本会话确实没有值得持久化的内容,也在 log.md 记一条「## [日期] digest | 无新增」并说明原因——这同样会解除提醒。',
|
|
94
|
+
...(indexHint.length > 0 ? [indexHint] : []),
|
|
64
95
|
'完成后继续手头的事即可,不要开启新任务。',
|
|
65
96
|
].join('\n'),
|
|
66
97
|
}],
|
|
@@ -70,9 +101,10 @@ export function buildDigestNudgeMessage(staleMinutes) {
|
|
|
70
101
|
|
|
71
102
|
/**
|
|
72
103
|
* @typedef {object} DigestGuardOptions
|
|
73
|
-
* @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number }} readConfig
|
|
104
|
+
* @property {() => { enabled: boolean, afterMinutes: number, cooldownMinutes: number, maxPerSession: number, deferUntilUserSpeaks?: boolean, activeSessionOnly?: boolean }} readConfig
|
|
74
105
|
* @property {() => string} getMemoryDir resolve the current store dir on every check
|
|
75
106
|
* @property {unknown} [agents] optional live-agent registry for liveness checks
|
|
107
|
+
* @property {import('./activity-tracker.js').ActivityTracker} [tracker] gate source: has-user-spoken + active-session
|
|
76
108
|
* @property {{ info?: Function, warn?: Function }} [logger]
|
|
77
109
|
*/
|
|
78
110
|
|
|
@@ -89,6 +121,7 @@ export class DigestGuard {
|
|
|
89
121
|
this.readConfig = options.readConfig
|
|
90
122
|
this.getMemoryDir = options.getMemoryDir
|
|
91
123
|
this.agents = options.agents
|
|
124
|
+
this.tracker = options.tracker
|
|
92
125
|
this.logger = options.logger
|
|
93
126
|
this.disposed = false
|
|
94
127
|
this.stopTurnStopping = undefined
|
|
@@ -124,6 +157,9 @@ export class DigestGuard {
|
|
|
124
157
|
}
|
|
125
158
|
const config = this.readConfig()
|
|
126
159
|
if (!config.enabled) return
|
|
160
|
+
// Both gates: don't remind before the user has spoken, and only for the
|
|
161
|
+
// currently active session (most recent user message).
|
|
162
|
+
if (this.tracker && !this.tracker.shouldInject(this.agent.id, config)) return
|
|
127
163
|
if (this.nudges >= Math.max(1, Number(config.maxPerSession ?? 2))) return
|
|
128
164
|
if (this.agent.status !== 'idle') return
|
|
129
165
|
const inbox = this.agent.inbox
|
|
@@ -138,9 +174,13 @@ export class DigestGuard {
|
|
|
138
174
|
if (now - lastWrite < afterMs) return
|
|
139
175
|
|
|
140
176
|
const staleMinutes = Math.max(1, Math.round((now - lastWrite) / 60000))
|
|
141
|
-
|
|
177
|
+
// Only computed once a reminder is actually being delivered: scanning the
|
|
178
|
+
// store on every idle turn would be pure overhead.
|
|
179
|
+
const indexHint = buildIndexDriftHint(this.getMemoryDir())
|
|
180
|
+
this.agent.followup(buildDigestNudgeMessage(staleMinutes, { indexHint }))
|
|
142
181
|
this.lastNudgeAt = now
|
|
143
182
|
this.nudges += 1
|
|
144
|
-
this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}"
|
|
183
|
+
this.logger?.info?.(`memory: digest nudge #${this.nudges} for agent "${this.agent.id}" `
|
|
184
|
+
+ `(store idle ${staleMinutes}min${indexHint.length > 0 ? ', index drift reported' : ''})`)
|
|
145
185
|
}
|
|
146
186
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drag maths for the memory graph.
|
|
3
|
+
*
|
|
4
|
+
* Kept pure and dependency-free so it can be unit-tested in Node: the browser
|
|
5
|
+
* half cannot import local modules, and the drag behaviour is exactly the part
|
|
6
|
+
* that is impossible to verify by reading it.
|
|
7
|
+
*
|
|
8
|
+
* The model is deliberately simple — the dragged node follows the pointer, its
|
|
9
|
+
* direct neighbours lean toward it a little, everything else stays put. A full
|
|
10
|
+
* force simulation per frame would be O(n²) and stutter on large stores; this
|
|
11
|
+
* reads as "alive" while staying O(degree).
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-plugin-memory/graph-drag
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Clamp into `[min, max]`. `NaN` means "no usable input" and falls back to
|
|
18
|
+
* `min`; the infinities are real directions, so they clamp to the edge.
|
|
19
|
+
* @param {number} value @param {number} min @param {number} max
|
|
20
|
+
*/
|
|
21
|
+
export function clampToBox(value, min, max) {
|
|
22
|
+
if (Number.isNaN(value)) return min
|
|
23
|
+
return Math.min(Math.max(value, min), max)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* How far a neighbour leans toward the dragged node.
|
|
28
|
+
* @param {number} distance current distance between the two nodes
|
|
29
|
+
* @param {number} pull 0..1 strength (scaled down as the drag gets far away)
|
|
30
|
+
* @param {number} [strength] global multiplier
|
|
31
|
+
* @returns {number} offset in px, along the drag direction
|
|
32
|
+
*/
|
|
33
|
+
export function neighbourLean(distance, pull, strength = 6) {
|
|
34
|
+
const d = Number.isFinite(distance) ? Math.max(1, distance) : 1
|
|
35
|
+
const p = Number.isFinite(pull) ? Math.min(Math.max(pull, 0), 1) : 0
|
|
36
|
+
return (p * strength * 12) / (12 + d)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Positions for one drag frame.
|
|
41
|
+
*
|
|
42
|
+
* @param {Map<string, {x: number, y: number}> | Record<string, {x: number, y: number}>} positions base layout
|
|
43
|
+
* @param {string} draggedId node under the pointer
|
|
44
|
+
* @param {{x: number, y: number}} target pointer position
|
|
45
|
+
* @param {Array<{source: string, target: string}>} edges
|
|
46
|
+
* @param {{width?: number, height?: number, minPull?: number, strength?: number}} [options]
|
|
47
|
+
* @returns {Map<string, {x: number, y: number}>} new positions (input untouched)
|
|
48
|
+
*/
|
|
49
|
+
export function applyDrag(positions, draggedId, target, edges, options = {}) {
|
|
50
|
+
const width = options.width ?? 560
|
|
51
|
+
const height = options.height ?? 340
|
|
52
|
+
const minPull = options.minPull ?? 0.3
|
|
53
|
+
const strength = options.strength ?? 6
|
|
54
|
+
const current = positions instanceof Map ? positions : new Map(Object.entries(positions ?? {}))
|
|
55
|
+
const at = (id) => current.get(id)
|
|
56
|
+
const start = at(draggedId)
|
|
57
|
+
const next = new Map(current)
|
|
58
|
+
|
|
59
|
+
if (start === undefined) return next
|
|
60
|
+
|
|
61
|
+
const x = clampToBox(target?.x, 0, width)
|
|
62
|
+
const y = clampToBox(target?.y, 0, height)
|
|
63
|
+
next.set(draggedId, { x, y })
|
|
64
|
+
|
|
65
|
+
// Neighbour set in one pass over the edges.
|
|
66
|
+
const neighbours = new Set()
|
|
67
|
+
for (const edge of edges ?? []) {
|
|
68
|
+
if (edge?.source === draggedId) neighbours.add(edge.target)
|
|
69
|
+
else if (edge?.target === draggedId) neighbours.add(edge.source)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const dx = x - start.x
|
|
73
|
+
const dy = y - start.y
|
|
74
|
+
const distance = Math.max(1, Math.hypot(dx, dy))
|
|
75
|
+
const ux = dx / distance
|
|
76
|
+
const uy = dy / distance
|
|
77
|
+
const pull = Math.max(minPull, Math.min(1, 1 / (1 + distance / 80)))
|
|
78
|
+
|
|
79
|
+
for (const id of neighbours) {
|
|
80
|
+
const base = at(id)
|
|
81
|
+
if (base === undefined) continue
|
|
82
|
+
const lean = neighbourLean(distance, pull, strength)
|
|
83
|
+
next.set(id, {
|
|
84
|
+
x: clampToBox(base.x + ux * lean, 0, width),
|
|
85
|
+
y: clampToBox(base.y + uy * lean, 0, height),
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
return next
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Positions after releasing, i.e. the untouched base layout — the client pairs
|
|
93
|
+
* this with a CSS transition so nodes glide back instead of snapping.
|
|
94
|
+
*
|
|
95
|
+
* @param {Map<string, {x: number, y: number}> | Record<string, {x: number, y: number}>} base
|
|
96
|
+
* @returns {Map<string, {x: number, y: number}>}
|
|
97
|
+
*/
|
|
98
|
+
export function releasePositions(base) {
|
|
99
|
+
return base instanceof Map ? new Map(base) : new Map(Object.entries(base ?? {}))
|
|
100
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic force-directed layout for the memory graph.
|
|
3
|
+
*
|
|
4
|
+
* Split out of the browser half so the maths can be unit-tested in Node and
|
|
5
|
+
* reused by the standalone report/preview without duplicating it. No
|
|
6
|
+
* randomness, no dependency: same input, same coordinates, every time.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-plugin-memory/graph-layout
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Canvas the renderer draws into. Shared so the panel and any static report
|
|
12
|
+
* (or preview) agree on the picture's proportions. */
|
|
13
|
+
export const GRAPH_CANVAS = { width: 560, height: 340 }
|
|
14
|
+
|
|
15
|
+
/** Colour per memory type, shared by the SVG renderer and any static report. */
|
|
16
|
+
export const TYPE_COLORS = {
|
|
17
|
+
project: '#4c8bf5',
|
|
18
|
+
skill: '#8b7bf5',
|
|
19
|
+
decision: '#f5a623',
|
|
20
|
+
concept: '#30a46c',
|
|
21
|
+
user: '#e5484d',
|
|
22
|
+
'user-preference': '#e5484d',
|
|
23
|
+
identity: '#e0712f',
|
|
24
|
+
fact: '#8b8f96',
|
|
25
|
+
meta: '#5b6068',
|
|
26
|
+
unknown: '#8b8f96',
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {string} type */
|
|
30
|
+
export function typeColor(type) {
|
|
31
|
+
return TYPE_COLORS[type] ?? TYPE_COLORS.unknown
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Place nodes inside a width x height box.
|
|
36
|
+
*
|
|
37
|
+
* @param {Array<{ id: string, degree?: number, hub?: boolean }>} nodes
|
|
38
|
+
* @param {Array<{ source: string, target: string, kind?: string }>} edges
|
|
39
|
+
* @param {{ width?: number, height?: number, iterations?: number }} [options]
|
|
40
|
+
* @returns {{ positions: Map<string, {x: number, y: number}>, radius: (id: string) => number }}
|
|
41
|
+
*/
|
|
42
|
+
export function layoutGraph(nodes, edges, options = {}) {
|
|
43
|
+
const width = options.width ?? 560
|
|
44
|
+
const height = options.height ?? 340
|
|
45
|
+
const iterations = options.iterations ?? 220
|
|
46
|
+
const positions = new Map()
|
|
47
|
+
if (nodes.length === 0) {
|
|
48
|
+
return { positions, radius: () => 5 }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const cx = width / 2
|
|
52
|
+
const cy = height / 2
|
|
53
|
+
nodes.forEach((node, index) => {
|
|
54
|
+
const angle = (index / nodes.length) * Math.PI * 2
|
|
55
|
+
positions.set(node.id, { x: cx + Math.cos(angle) * 110, y: cy + Math.sin(angle) * 80 })
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const degrees = new Map(nodes.map((node) => [node.id, node.degree ?? 0]))
|
|
59
|
+
const radius = (id) => 4.5 + Math.min(7.5, Math.sqrt(degrees.get(id) ?? 0) * 2.4)
|
|
60
|
+
const springs = []
|
|
61
|
+
for (const edge of edges) {
|
|
62
|
+
if (!positions.has(edge.source) || !positions.has(edge.target)) continue
|
|
63
|
+
springs.push({ a: edge.source, b: edge.target, w: edge.kind === 'link' ? 1.6 : 0.5 })
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
for (let iter = 0; iter < iterations; iter += 1) {
|
|
67
|
+
const cool = 1 - iter / (iterations * 1.18)
|
|
68
|
+
|
|
69
|
+
// pairwise repulsion
|
|
70
|
+
for (let i = 0; i < nodes.length; i += 1) {
|
|
71
|
+
const pi = positions.get(nodes[i].id)
|
|
72
|
+
for (let j = i + 1; j < nodes.length; j += 1) {
|
|
73
|
+
const pj = positions.get(nodes[j].id)
|
|
74
|
+
let dx = pi.x - pj.x
|
|
75
|
+
let dy = pi.y - pj.y
|
|
76
|
+
let d2 = dx * dx + dy * dy
|
|
77
|
+
if (d2 < 1) {
|
|
78
|
+
// Coincident nodes: nudge them apart deterministically.
|
|
79
|
+
dx = (i - j) * 0.7 + 0.3
|
|
80
|
+
dy = 0.4 * (j - i) + 0.2
|
|
81
|
+
d2 = dx * dx + dy * dy
|
|
82
|
+
}
|
|
83
|
+
const d = Math.sqrt(d2)
|
|
84
|
+
const push = (46 * cool) / d2
|
|
85
|
+
const ux = (dx / d) * push
|
|
86
|
+
const uy = (dy / d) * push
|
|
87
|
+
pi.x += ux
|
|
88
|
+
pi.y += uy
|
|
89
|
+
pj.x -= ux
|
|
90
|
+
pj.y -= uy
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// spring attraction along edges
|
|
95
|
+
for (const spring of springs) {
|
|
96
|
+
const pa = positions.get(spring.a)
|
|
97
|
+
const pb = positions.get(spring.b)
|
|
98
|
+
const dx = pb.x - pa.x
|
|
99
|
+
const dy = pb.y - pa.y
|
|
100
|
+
const d = Math.max(1, Math.sqrt(dx * dx + dy * dy))
|
|
101
|
+
const pull = (d - 78) * 0.016 * spring.w * cool
|
|
102
|
+
const ux = (dx / d) * pull
|
|
103
|
+
const uy = (dy / d) * pull
|
|
104
|
+
pa.x += ux
|
|
105
|
+
pa.y += uy
|
|
106
|
+
pb.x -= ux
|
|
107
|
+
pb.y -= uy
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// centring, with hubs pulled a little harder so they read as hubs
|
|
111
|
+
for (const node of nodes) {
|
|
112
|
+
const p = positions.get(node.id)
|
|
113
|
+
const strength = node.hub ? 0.022 : 0.0035
|
|
114
|
+
p.x += (cx - p.x) * strength * cool
|
|
115
|
+
p.y += (cy - p.y) * strength * cool
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// normalise into the box, preserving aspect ratio
|
|
120
|
+
const pad = 30
|
|
121
|
+
const xs = [...positions.values()].map((p) => p.x)
|
|
122
|
+
const ys = [...positions.values()].map((p) => p.y)
|
|
123
|
+
const minX = Math.min(...xs)
|
|
124
|
+
const maxX = Math.max(...xs)
|
|
125
|
+
const minY = Math.min(...ys)
|
|
126
|
+
const maxY = Math.max(...ys)
|
|
127
|
+
const scale = Math.min(
|
|
128
|
+
(width - pad * 2) / Math.max(1, maxX - minX),
|
|
129
|
+
(height - pad * 2) / Math.max(1, maxY - minY),
|
|
130
|
+
)
|
|
131
|
+
for (const p of positions.values()) {
|
|
132
|
+
p.x = pad + (p.x - minX) * scale
|
|
133
|
+
p.y = pad + (p.y - minY) * scale
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { positions, radius }
|
|
137
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* View maths for the memory graph: wheel zoom and canvas panning.
|
|
3
|
+
*
|
|
4
|
+
* Pure and dependency-free, for the same reason as `graph-drag`: the browser
|
|
5
|
+
* half cannot import local modules, so the maths is mirrored there and a test
|
|
6
|
+
* asserts the two agree. Zoom-about-a-point is exactly the kind of arithmetic
|
|
7
|
+
* that looks right and drifts under the cursor.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-plugin-memory/graph-view
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** @type {{x: number, y: number, w: number, h: number}} */
|
|
13
|
+
export const DEFAULT_VIEW = { x: 0, y: 0, w: 560, h: 340 }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Viewport width is expressed as a fraction of the base width:
|
|
17
|
+
* `minScale` = tightest zoom (2.5x in), `maxScale` = widest (0.4x out).
|
|
18
|
+
*/
|
|
19
|
+
export const MIN_VIEW_SCALE = 0.4
|
|
20
|
+
export const MAX_VIEW_SCALE = 2.5
|
|
21
|
+
|
|
22
|
+
/** @param {{x: number, y: number, w: number, h: number}} view */
|
|
23
|
+
export function isZoomed(view, base = DEFAULT_VIEW) {
|
|
24
|
+
return view.w < base.w - 1 || Math.abs(view.x - base.x) > 1 || Math.abs(view.y - base.y) > 1
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Zoom about a graph-space point, keeping that point under the cursor.
|
|
29
|
+
*
|
|
30
|
+
* @param {{x: number, y: number, w: number, h: number}} view current view
|
|
31
|
+
* @param {number} fx focus x in graph coordinates
|
|
32
|
+
* @param {number} fy focus y in graph coordinates
|
|
33
|
+
* @param {number} factor >1 zooms out, <1 zooms in
|
|
34
|
+
* @param {{width?: number, height?: number, minScale?: number, maxScale?: number}} [options]
|
|
35
|
+
* @returns {{x: number, y: number, w: number, h: number}} next view
|
|
36
|
+
*/
|
|
37
|
+
export function zoomAt(view, fx, fy, factor, options = {}) {
|
|
38
|
+
const width = options.width ?? DEFAULT_VIEW.w
|
|
39
|
+
const height = options.height ?? DEFAULT_VIEW.h
|
|
40
|
+
const minScale = options.minScale ?? MIN_VIEW_SCALE
|
|
41
|
+
const maxScale = options.maxScale ?? MAX_VIEW_SCALE
|
|
42
|
+
const safeFactor = Number.isFinite(factor) && factor > 0 ? factor : 1
|
|
43
|
+
const nextW = Math.min(width * maxScale, Math.max(width * minScale, view.w * safeFactor))
|
|
44
|
+
const k = nextW / view.w
|
|
45
|
+
return {
|
|
46
|
+
x: fx - (fx - view.x) * k,
|
|
47
|
+
y: fy - (fy - view.y) * k,
|
|
48
|
+
w: nextW,
|
|
49
|
+
h: height * (nextW / width),
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {{width?: number, height?: number}} [options] */
|
|
54
|
+
export function resetView(options = {}) {
|
|
55
|
+
return {
|
|
56
|
+
x: 0,
|
|
57
|
+
y: 0,
|
|
58
|
+
w: options.width ?? DEFAULT_VIEW.w,
|
|
59
|
+
h: options.height ?? DEFAULT_VIEW.h,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* One pan step: move the view by the pointer delta, converted from screen
|
|
65
|
+
* pixels to graph units.
|
|
66
|
+
*
|
|
67
|
+
* @param {{x: number, y: number, w: number, h: number}} start view when the drag began
|
|
68
|
+
* @param {number} dxPx pointer delta in screen pixels
|
|
69
|
+
* @param {number} dyPx pointer delta in screen pixels
|
|
70
|
+
* @param {{scaleX: number, scaleY: number}} scale graph-units per screen pixel
|
|
71
|
+
* @returns {{x: number, y: number, w: number, h: number}}
|
|
72
|
+
*/
|
|
73
|
+
export function panBy(start, dxPx, dyPx, scale) {
|
|
74
|
+
return {
|
|
75
|
+
x: start.x - (Number.isFinite(dxPx) ? dxPx : 0) * (scale?.scaleX ?? 1),
|
|
76
|
+
y: start.y - (Number.isFinite(dyPx) ? dyPx : 0) * (scale?.scaleY ?? 1),
|
|
77
|
+
w: start.w,
|
|
78
|
+
h: start.h,
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Screen point -> graph point for the current view. Node dragging needs this,
|
|
84
|
+
* otherwise a drag lands somewhere else as soon as the user zooms.
|
|
85
|
+
*
|
|
86
|
+
* @param {{x: number, y: number, w: number, h: number}} view
|
|
87
|
+
* @param {{left: number, top: number, width: number, height: number}} rect element box
|
|
88
|
+
* @param {number} clientX
|
|
89
|
+
* @param {number} clientY
|
|
90
|
+
* @returns {{x: number, y: number}}
|
|
91
|
+
*/
|
|
92
|
+
export function toGraphPoint(view, rect, clientX, clientY) {
|
|
93
|
+
if (rect === undefined || rect.width === 0 || rect.height === 0) return { x: clientX, y: clientY }
|
|
94
|
+
return {
|
|
95
|
+
x: view.x + ((clientX - rect.left) / rect.width) * view.w,
|
|
96
|
+
y: view.y + ((clientY - rect.top) / rect.height) * view.h,
|
|
97
|
+
}
|
|
98
|
+
}
|