@cheemsup/dsh-plugin-console 0.1.1 → 0.2.1

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.
@@ -9,11 +9,12 @@
9
9
  *
10
10
  * 视图因此是纯函数:只读 `vc`,不闭包隐藏状态,可以脱离页面单独调用。
11
11
  *
12
- * 四个视图各自回答一个独立问题:
12
+ * 五个视图各自回答一个独立问题:
13
13
  * 插件 —— 这台机器到底装了什么、按能力分类看;
14
14
  * 会话 —— 从某个会话往上追它的插件是哪来的;
15
15
  * 工具 —— 模型能看到哪些工具、谁给的;
16
- * 预演 —— 首条消息发出去之前模型会收到什么;从页底进「定制」。
16
+ * 上下文预演 —— 首条消息发出去之前模型会收到什么;从页底进「定制」;
17
+ * 插件禁用预演 —— 禁用某个插件会失去什么、谁受影响、config 逐层声明了什么。
17
18
  */
18
19
 
19
20
  window.__ModuleLoader__.load({
@@ -21,12 +22,12 @@ window.__ModuleLoader__.load({
21
22
  chunk: 'client.page.js',
22
23
  factory: (require) => {
23
24
  const React = require('react')
24
- const { createElement: h, useEffect, useMemo, useState } = React
25
+ const { createElement: h, useEffect, useMemo, useRef, useState } = React
25
26
 
26
27
  return function create(deps) {
27
28
  // 三个名字各管一摊:`preview` 是预演结果,`previewView` 是视图 chunk,
28
29
  // `previewStore` 是条件与请求状态。混用会在 PluginTreePage 里被内层解构遮蔽。
29
- const { runtimeCtx, shared, store, plugins, pluginFilters, sessions, tools, preview: previewView, previewStore, editorStore, editor, influence, activity, changes, control, search } = deps
30
+ const { runtimeCtx, shared, store, plugins, pluginFilters, sessions, tools, preview: previewView, previewStore, editorStore, editor, influence, activity, changes, control, disablePreview, search } = deps
30
31
  const {
31
32
  CATEGORY_LABELS,
32
33
  isStructural,
@@ -125,6 +126,8 @@ window.__ModuleLoader__.load({
125
126
  const previewSearch = search.useSearchState()
126
127
  const { status: activityStatus, data: activityData, error: activityError, load: loadActivity } = activity.useActivityStore()
127
128
  const controlStore = control.useControlStore()
129
+ // 禁用预演:目标与结果都在这个 store 里;页面只负责切标签与传条件。
130
+ const disableState = disablePreview.useDisablePreviewStore()
128
131
  // 只属于「怎么摆」的 UI 状态,不进 store:换了视图就该重置。
129
132
  const [view, setView] = useState('plugins')
130
133
  const [query, setQuery] = useState('')
@@ -163,6 +166,27 @@ window.__ModuleLoader__.load({
163
166
  setView(next)
164
167
  }
165
168
 
169
+ /**
170
+ * 进入禁用预演且还没有目标时,默认选中本插件(控制台自身)。
171
+ *
172
+ * 只自动选一次:用户把选择器清空后不再抢回;从插件页跳进来的目标
173
+ * 已经有 rowId,也原样保留。
174
+ */
175
+ const disableAutoTargetDone = useRef(false)
176
+ useEffect(() => {
177
+ if (disableAutoTargetDone.current || view !== 'disable') return
178
+ if (disableState.rowId !== null) {
179
+ disableAutoTargetDone.current = true
180
+ return
181
+ }
182
+ const entries = snapshot?.entries ?? []
183
+ const own = entries.find((entry) => entry.rowId === 'plugin-console')
184
+ ?? entries.find((entry) => entry.moduleName === '@cheemsup/dsh-plugin-console')
185
+ if (own === undefined) return
186
+ disableAutoTargetDone.current = true
187
+ disableState.choose(own.rowId)
188
+ }, [view, snapshot, disableState.rowId, disableState.choose])
189
+
166
190
  /**
167
191
  * 跳到插件视图并展开某个条目。
168
192
  *
@@ -195,7 +219,11 @@ window.__ModuleLoader__.load({
195
219
  setQuery('')
196
220
  setToolOwner(null)
197
221
  setPreviewOnlyUnowned(false)
198
- setPreviewTab('prompt')
222
+ // 运行时上下文不是提示词段:它在「运行时消息与注入」标签里,跳到提示词标签
223
+ // 只会得到「这段不在装配结果里」,等于没定位到。同名时提示词段优先。
224
+ const isSection = (snapshot?.prompt?.sections ?? []).some((row) => row.name === name)
225
+ const isContext = !isSection && (snapshot?.prompt?.contexts ?? []).some((row) => row.name === name)
226
+ setPreviewTab(isContext ? 'messages' : 'prompt')
199
227
  // 从插件页跳过来时编辑器可能还开着;先回到预演,否则目标段落在编辑器里不可见。
200
228
  editorState.setEditing(false)
201
229
  setView('preview')
@@ -224,6 +252,19 @@ window.__ModuleLoader__.load({
224
252
  setFocusSection(null)
225
253
  }
226
254
 
255
+ /** 跳到「插件禁用预演」页并选中一个插件;目标由 store 懒加载。 */
256
+ const gotoDisablePreview = (rowId) => {
257
+ if (typeof rowId !== 'string' || rowId === '') return
258
+ setQuery('')
259
+ setToolOwner(null)
260
+ setFocusTool(null)
261
+ setFocusSection(null)
262
+ setPreviewOnlyUnowned(false)
263
+ editorState.setEditing(false)
264
+ setView('disable')
265
+ disableState.choose(rowId)
266
+ }
267
+
227
268
  /**
228
269
  * 进入 / 离开定制编辑器。
229
270
  *
@@ -268,6 +309,21 @@ window.__ModuleLoader__.load({
268
309
  void loadActivity()
269
310
  }, [view, activityStatus, loadActivity])
270
311
 
312
+ // 快照静默刷新后,已选目标的数字可能过期。只在 generatedAt 真的变了时重算一次;
313
+ // 选择目标那次由 `choose` 自己发请求,这里不能重复发,否则每次筛选都双倍计算。
314
+ const disableStamp = useRef(null)
315
+ useEffect(() => {
316
+ if (snapshot === null) return
317
+ const stamp = snapshot.generatedAt
318
+ if (disableStamp.current === null) {
319
+ disableStamp.current = stamp
320
+ return
321
+ }
322
+ if (disableStamp.current === stamp) return
323
+ disableStamp.current = stamp
324
+ if (view === 'disable' && disableState.rowId !== null) disableState.reload()
325
+ }, [snapshot, view])
326
+
271
327
  // 跳转到工具/提示词后把目标滚进视野。与插件详情的滚动同一套理由:
272
328
  // 滚动容器是 .ptBody 而不是 window,交给 scrollIntoView 自己找。
273
329
  useEffect(() => {
@@ -385,6 +441,7 @@ window.__ModuleLoader__.load({
385
441
  activityError,
386
442
  loadActivity,
387
443
  control: controlStore,
444
+ disablePreview: disableState,
388
445
  changes: changeSet,
389
446
  query,
390
447
  setQuery,
@@ -434,6 +491,7 @@ window.__ModuleLoader__.load({
434
491
  gotoSection,
435
492
  gotoToolsUnattributed,
436
493
  gotoPromptUnattributed,
494
+ gotoDisablePreview,
437
495
  }
438
496
  const inEditor = view === 'preview' && editorState.editing
439
497
  // 占位符跟着子标签走:预演页的四个标签能筛的东西不同,不能共用一句话。
@@ -518,7 +576,8 @@ window.__ModuleLoader__.load({
518
576
  tabButton('plugins', '插件', view, switchView, snapshot ? entries.length : undefined),
519
577
  tabButton('sessions', '会话', view, switchView, snapshot ? allSessions.size : undefined),
520
578
  tabButton('tools', '工具', view, switchView, snapshot?.tools?.attributed?.length),
521
- tabButton('preview', '预演', view, switchView),
579
+ tabButton('preview', '上下文预演', view, switchView),
580
+ tabButton('disable', '插件禁用预演', view, switchView),
522
581
  ),
523
582
  // 快照未到位或处于定制编辑器时没有页内筛选器;空工具条不占位置。
524
583
  snapshot === null || inEditor
@@ -534,7 +593,9 @@ window.__ModuleLoader__.load({
534
593
  ? tools.renderToolFilters(vc)
535
594
  : view === 'preview'
536
595
  ? previewView.renderPreviewFilters(vc)
537
- : null,
596
+ : view === 'disable'
597
+ ? disablePreview.renderDisablePreviewFilters(vc)
598
+ : null,
538
599
  ),
539
600
  ),
540
601
  h(
@@ -570,6 +631,7 @@ window.__ModuleLoader__.load({
570
631
  }
571
632
  if (view === 'sessions') return sessions.renderSessionsView(vc)
572
633
  if (view === 'tools') return tools.renderToolsView(vc)
634
+ if (view === 'disable') return disablePreview.renderDisablePreviewView(vc)
573
635
  if (view === 'preview') {
574
636
  // 定制模式接管整页:先在预演里看清最终构造,再决定怎么改并发送。
575
637
  if (vc.editing) return editor.renderTemplateEditorView(vc)
@@ -173,6 +173,7 @@ window.__ModuleLoader__.load({
173
173
  onOpenTool: props.onOpenTool,
174
174
  onOpenSection: props.onOpenSection,
175
175
  onOpenPlugin: props.onOpenPlugin,
176
+ onPreviewDisable: props.onPreviewDisable,
176
177
  anchorId: focused ? 'pt-focused' : undefined,
177
178
  onClose: () => onSelect(null),
178
179
  })
@@ -181,7 +182,7 @@ window.__ModuleLoader__.load({
181
182
  }
182
183
 
183
184
  /** 选中行的若干段事实。 */
184
- function Detail({ entry, snapshot, byId, onOpenTool, onOpenSection, onOpenPlugin, anchorId, onClose, usage, activityStatus, activityError, control, sessions, reload }) {
185
+ function Detail({ entry, snapshot, byId, onOpenTool, onOpenSection, onOpenPlugin, onPreviewDisable, anchorId, onClose, usage, activityStatus, activityError, control, sessions, reload }) {
185
186
  // 被跳转定位时把详情滚进视野。
186
187
  //
187
188
  // 展开发生在虚拟的高度里,浏览器不会自己滚动;而滚动容器不是 window,
@@ -275,7 +276,7 @@ window.__ModuleLoader__.load({
275
276
  : (entry.configKeys?.length ? h('code', null, entry.configKeys.join(', ')) : null)
276
277
 
277
278
  // 控制是唯一会写宿主状态的一段:先算好节点,再和分隔线一起放到最后。
278
- const controlNode = control?.renderControlSection?.(entry, { control, sessions, reload }) ?? null
279
+ const controlNode = control?.renderControlSection?.(entry, { control, sessions, reload, onPreviewDisable }) ?? null
279
280
 
280
281
  return h(
281
282
  'div',
@@ -380,7 +381,7 @@ window.__ModuleLoader__.load({
380
381
  h('span', { className: 'ptSub' }, `提示词区块 ${regSections.length}`),
381
382
  regSections.map((name) => h(
382
383
  'button',
383
- { key: name, type: 'button', className: 'ptTag ptLink', title: '在「提示词」页查看该段落', onClick: () => onOpenSection(name) },
384
+ { key: name, type: 'button', className: 'ptTag ptLink', title: '在「上下文预演」页查看该段落', onClick: () => onOpenSection(name) },
384
385
  name,
385
386
  )),
386
387
  )
@@ -489,6 +490,7 @@ window.__ModuleLoader__.load({
489
490
  onOpenTool: gotoTool,
490
491
  onOpenSection: gotoSection,
491
492
  onOpenPlugin: vc.gotoPlugin,
493
+ onPreviewDisable: vc.gotoDisablePreview,
492
494
  }),
493
495
  ),
494
496
  )
@@ -163,13 +163,18 @@ window.__ModuleLoader__.load({
163
163
  : registry.get(segment.name)?.owners ?? []
164
164
  const text = typeof segment.text === 'string' ? segment.text : ''
165
165
  // 命中的分段自动展开,否则用户只看到一个段名,还得自己点开确认。
166
+ // 从禁用预演跳过来的分段同样要展开,并挂上滚动锚点。
166
167
  const hit = search.matchesQuery(query, [segment.name, text])
168
+ const focused = vc.focusSection === segment.name
167
169
  return h(
168
170
  'li',
169
171
  { key: segment.name },
170
172
  h(
171
173
  'details',
172
- { className: 'ptToolBlock ptFold ptFoldable', ...(hit ? { open: true } : {}) },
174
+ {
175
+ className: 'ptToolBlock ptFold ptFoldable',
176
+ ...(focused ? { open: true, id: 'pt-section-focus' } : (hit ? { open: true } : {})),
177
+ },
173
178
  h(
174
179
  'summary',
175
180
  null,
@@ -262,7 +267,10 @@ window.__ModuleLoader__.load({
262
267
  { key: row.name },
263
268
  h(
264
269
  'details',
265
- { className: 'ptToolBlock ptFold ptFoldable' },
270
+ {
271
+ className: 'ptToolBlock ptFold ptFoldable',
272
+ ...(vc.focusSection === row.name ? { open: true, id: 'pt-section-focus' } : {}),
273
+ },
266
274
  h(
267
275
  'summary',
268
276
  null,
@@ -330,6 +338,9 @@ window.__ModuleLoader__.load({
330
338
  ? skillList(message.parts, query)
331
339
  : null
332
340
  const hint = summaryHint(message)
341
+ // 目标分段在折叠的消息里时,外层消息必须一起展开,否则锚点不可见。
342
+ const focusedPart = vc.focusSection !== null && vc.focusSection !== undefined
343
+ && (message.parts ?? []).some((part) => part.name === vc.focusSection)
333
344
  // user 与 time-context 只保留原文:它们的机制/依据不解释任何模型可见内容。
334
345
  const mechanism = MECHANISM_IN_BODY.has(message.sourceKind)
335
346
  ? h(
@@ -358,7 +369,7 @@ window.__ModuleLoader__.load({
358
369
  {
359
370
  className: 'ptPromptBlock ptFold ptFoldable',
360
371
  // 筛选激活时列出来的每一条都命中过,展开才能看到命中处;平时只展开第一条。
361
- ...(index === 0 || searching ? { open: true } : {}),
372
+ ...(index === 0 || searching || focusedPart ? { open: true } : {}),
362
373
  },
363
374
  h(
364
375
  'summary',
@@ -196,7 +196,7 @@ window.__ModuleLoader__.load({
196
196
  ),
197
197
  h(
198
198
  'div',
199
- { className: 'ptTabs ptTabsSmall', role: 'tablist', 'aria-label': '预演内容' },
199
+ { className: 'ptTabs ptTabsSmall', role: 'tablist', 'aria-label': '上下文预演内容' },
200
200
  tabButton('prompt', `系统提示词(${formatBytes(computed)})`, previewTab, setPreviewTab, undefined, { prefix: 'pt-subtab-' }),
201
201
  // 与请求的真实结构一致:system → tools → messages;会话页的「首次请求分析」也是这个顺序。
202
202
  tabButton('tools', `工具 schema(${preview.stats.tools})`, previewTab, setPreviewTab, undefined, { prefix: 'pt-subtab-' }),
@@ -265,6 +265,7 @@ window.__ModuleLoader__.load({
265
265
  ? previewMessages.renderSkippedLine(preview.skippedMessages)
266
266
  : null,
267
267
  // 定制是这一页的下一步,放在页底并居中,避免和筛选器抢位置。
268
+ // 这一页没有提交动作,所以用 soft 色调底而不是实底:实底留给真正提交的那个按钮。
268
269
  // 定制页的「预览定制结果」复用这份视图,但它已经在编辑器里,不再给入口。
269
270
  vc.appliedPreview === true
270
271
  ? null
@@ -276,7 +277,7 @@ window.__ModuleLoader__.load({
276
277
  {
277
278
  type: 'button',
278
279
  className: 'ptBtn ptBtnLarge',
279
- 'data-tone': 'primary',
280
+ 'data-tone': 'soft',
280
281
  onClick: () => {
281
282
  // 进入编辑器时继承预演页当前看着的模式,并载入它的整份基线。
282
283
  void loadTemplates()
@@ -0,0 +1,364 @@
1
+ /**
2
+ * 「插件禁用预演」里的关系图画布:固定视口 + 缩放/拖拽。
3
+ *
4
+ * 单独成一个 chunk:图不是 React 状态驱动的——拖拽与滚轮每秒几十次,直接改
5
+ * 画布的 transform 才不会把整页重渲染;固定视口让图像地图一样在内部任意移动。
6
+ * 数据与几何仍由 `client.impact-tree.js` 纯计算,这里只负责挂上去。
7
+ * @module dsh-plugin-console/client-relation-graph
8
+ */
9
+
10
+ window.__ModuleLoader__.load({
11
+ id: '@cheemsup/dsh-plugin-console',
12
+ chunk: 'client.relation-graph.js',
13
+ factory: (require) => {
14
+ const React = require('react')
15
+ const { createElement: h } = React
16
+
17
+ return function create(deps) {
18
+ const { activateOnKey, impactTree, textButton } = deps
19
+
20
+ /** 关系图缩放:按钮与滚轮共用同一组边界与步长;100% 表示整图适配视口。 */
21
+ const GRAPH_ZOOM_MIN = 0.4
22
+ const GRAPH_ZOOM_MAX = 4
23
+ const GRAPH_ZOOM_STEP = 0.2
24
+
25
+ /** 视口高度:clamp(最小, 视口占比, 最大);CSS 里同步了一份。 */
26
+ const GRAPH_VIEWPORT_HEIGHT = 'clamp(360px,65vh,640px)'
27
+ const GRAPH_VIEWPORT_MIN_HEIGHT = '360px'
28
+
29
+ /** 把任意输入夹到缩放范围内;非数字回到 100%。 */
30
+ function clampZoom(value) {
31
+ const number = Number(value)
32
+ if (!Number.isFinite(number)) return 1
33
+ return Number(Math.min(GRAPH_ZOOM_MAX, Math.max(GRAPH_ZOOM_MIN, number)).toFixed(2))
34
+ }
35
+
36
+ /** 图表/节点里的定长截断;不改变数据,只影响文本节点。 */
37
+ function clip(text, limit) {
38
+ const value = typeof text === 'string' ? text : String(text ?? '')
39
+ return value.length > limit ? value.slice(0, limit - 1) + '…' : value
40
+ }
41
+
42
+ /**
43
+ * 节点的一句话说明,只出现在悬浮提示与读屏标签里。
44
+ *
45
+ * 方块本身只放插件名:状态、层级与服务边都收进这里,避免挤掉名称。
46
+ * 下游页面另有「受影响的下游插件」逐行给出同样的因果路径。
47
+ */
48
+ function nodeTooltip(node, data) {
49
+ if (node.side === 'root') {
50
+ return `目标插件 · 工具 ${data.tools.owned.length} · 段 ${data.prompt.sections.owned.length} · 服务 ${data.target.provides.length}`
51
+ }
52
+ if (node.blocked === true) {
53
+ const missing = (node.missingServices ?? []).join('、')
54
+ return `失去 ${missing || node.edgeLabel || '必需服务'}${node.distance ? ` · 第 ${node.distance} 层` : ''}`
55
+ }
56
+ if (node.edgeKind === 'config-reference') return `config.${node.edgeLabel} 引用了它`
57
+ if (node.edgeKind === 'group-child') return '同组子行'
58
+ const relation = node.side === 'upstream' ? `上游:提供 ${node.edgeLabel}` : `下游:需要 ${node.edgeLabel}`
59
+ return node.again === true ? `已在上方 · ${relation}` : relation
60
+ }
61
+
62
+ /**
63
+ * 视口的缩放/平移状态。
64
+ *
65
+ * 直接改画布的 transform,不重渲染:拖拽和滚轮每秒会触发很多次,用 React
66
+ * state 会卡;画布固定在视口内,超出部分裁掉,像地图一样任意移动。
67
+ */
68
+ const graphView = { x: 0, y: 0, scale: 1, key: null }
69
+ const graphZoomControl = { zoom: 1, set: undefined }
70
+ const graphPan = { active: false, moved: false, x: 0, y: 0 }
71
+ /** 适配比例与画布/视口尺寸;100% 表示整张图刚好放进视口。 */
72
+ const graphFit = { scale: 1, width: 0, height: 0, boxWidth: 0, boxHeight: 0 }
73
+ let graphViewportElement = null
74
+ let graphStageElement = null
75
+ let graphWheelListener = null
76
+
77
+ /** 量视口与画布尺寸并重算适配比例;返回视口尺寸是否变了。 */
78
+ function measureGraph() {
79
+ const viewport = graphViewportElement
80
+ if (viewport === null) return false
81
+ const boxWidth = viewport.clientWidth
82
+ const boxHeight = viewport.clientHeight
83
+ if (!(boxWidth > 0) || !(boxHeight > 0)) return false
84
+ const resized = graphFit.boxWidth !== boxWidth || graphFit.boxHeight !== boxHeight
85
+ graphFit.boxWidth = boxWidth
86
+ graphFit.boxHeight = boxHeight
87
+ if (graphFit.width > 0 && graphFit.height > 0) {
88
+ graphFit.scale = Math.min(1, (boxWidth - 32) / graphFit.width, (boxHeight - 32) / graphFit.height)
89
+ }
90
+ return resized
91
+ }
92
+
93
+ /** 把整张图放到视口中央;画布左上角为原点。 */
94
+ function centerGraph() {
95
+ if (!(graphFit.boxWidth > 0) || !(graphFit.boxHeight > 0)) return
96
+ graphView.x = (graphFit.boxWidth - graphFit.width * graphView.scale) / 2
97
+ graphView.y = (graphFit.boxHeight - graphFit.height * graphView.scale) / 2
98
+ }
99
+
100
+ /** 画布变换:左上角原点 + 平移/缩放;视口负责裁切。 */
101
+ function graphTransform(view, scale) {
102
+ // 两位小数足够,避免浮点尾数把 style 字符串写得又长又难比对。
103
+ const x = Math.round(view.x * 100) / 100
104
+ const y = Math.round(view.y * 100) / 100
105
+ return `translate(${x}px,${y}px) scale(${scale})`
106
+ }
107
+
108
+ /** 只改画布 transform,供拖拽/滚轮这类高频操作直接调用。 */
109
+ function applyGraphView() {
110
+ if (graphStageElement !== null) graphStageElement.style.transform = graphTransform(graphView, graphView.scale)
111
+ }
112
+
113
+ function setGraphStage(element) {
114
+ graphStageElement = element
115
+ }
116
+
117
+ /**
118
+ * 视口 ref。
119
+ *
120
+ * 滚轮必须用原生监听并 `passive:false`:React 的 onWheel 是 passive 的,
121
+ * preventDefault 拦不住浏览器把整页滚走。普通滚轮仍归页面,Ctrl + 滚轮
122
+ * 才缩放——与常见制图软件一致。
123
+ */
124
+ function setGraphViewport(element) {
125
+ if (graphWheelListener !== null) graphViewportElement?.removeEventListener('wheel', graphWheelListener)
126
+ graphViewportElement = element
127
+ graphWheelListener = element === null
128
+ ? null
129
+ : (event) => {
130
+ if (event.ctrlKey !== true) return
131
+ if (typeof graphZoomControl.set !== 'function') return
132
+ event.preventDefault()
133
+ zoomGraph(element, event.clientX, event.clientY, event.deltaY < 0 ? 1 : -1)
134
+ }
135
+ if (graphWheelListener !== null) element.addEventListener('wheel', graphWheelListener, { passive: false })
136
+ // 视口尺寸只有挂载后才知道:第一次拿到就按「整张图放进视口」定初始比例。
137
+ measureGraph()
138
+ graphView.scale = graphFit.scale * graphZoomControl.zoom
139
+ centerGraph()
140
+ applyGraphView()
141
+ }
142
+
143
+ /** 以视口内某点为锚缩放;按钮不传坐标时绕视口中心。 */
144
+ function zoomGraph(viewport, clientX, clientY, direction) {
145
+ const current = graphZoomControl.zoom
146
+ if (typeof graphZoomControl.set !== 'function') return
147
+ const next = clampZoom(current + direction * GRAPH_ZOOM_STEP)
148
+ if (next === current) return
149
+ const rect = viewport?.getBoundingClientRect?.()
150
+ const previous = graphFit.scale * current
151
+ const scale = graphFit.scale * next
152
+ if (rect !== undefined && previous > 0) {
153
+ // 缩放前后保持光标下的那一点不动:先把屏幕点换算成画布坐标再回推。
154
+ const px = Number.isFinite(clientX) ? clientX - rect.left : rect.width / 2
155
+ const py = Number.isFinite(clientY) ? clientY - rect.top : rect.height / 2
156
+ graphView.x = px - ((px - graphView.x) / previous) * scale
157
+ graphView.y = py - ((py - graphView.y) / previous) * scale
158
+ }
159
+ graphView.scale = scale
160
+ applyGraphView()
161
+ graphZoomControl.set(next)
162
+ }
163
+
164
+ /** 任意位置按下都先记起点,但只有移动超过阈值才算拖拽,点击节点仍然可用。 */
165
+ function startGraphPan(event) {
166
+ if (event.button !== 0) return
167
+ graphPan.active = true
168
+ graphPan.moved = false
169
+ graphPan.x = event.clientX
170
+ graphPan.y = event.clientY
171
+ }
172
+
173
+ /** 拖拽时增量平移画布;超过阈值才捕获指针。 */
174
+ function moveGraphPan(event) {
175
+ if (!graphPan.active) return
176
+ const dx = event.clientX - graphPan.x
177
+ const dy = event.clientY - graphPan.y
178
+ if (!graphPan.moved) {
179
+ if (Math.abs(dx) + Math.abs(dy) <= 4) return
180
+ graphPan.moved = true
181
+ event.currentTarget.setPointerCapture?.(event.pointerId)
182
+ event.currentTarget.dataset.panning = 'true'
183
+ }
184
+ graphPan.x = event.clientX
185
+ graphPan.y = event.clientY
186
+ graphView.x += dx
187
+ graphView.y += dy
188
+ applyGraphView()
189
+ }
190
+
191
+ /** 结束平移;指针抬起或取消都要收尾,避免下次渲染还停在拖拽态。 */
192
+ function endGraphPan(event) {
193
+ if (!graphPan.active) return
194
+ graphPan.active = false
195
+ const viewport = event.currentTarget
196
+ delete viewport.dataset.panning
197
+ if (viewport.hasPointerCapture?.(event.pointerId) === true) viewport.releasePointerCapture(event.pointerId)
198
+ // click 在 pointerup 之后才派发;等它过去再清掉「刚拖过」,避免误开插件。
199
+ if (graphPan.moved) globalThis.setTimeout?.(() => { graphPan.moved = false }, 0)
200
+ }
201
+
202
+ /** 上下游树状图;右上角缩放,并可切换「影响图 / 完整链路」。 */
203
+ function renderRelations(vc, data) {
204
+ const graphMode = vc.disablePreview?.graphMode === 'full' ? 'full' : 'impact'
205
+ const setGraphMode = typeof vc.disablePreview?.setGraphMode === 'function' ? vc.disablePreview.setGraphMode : undefined
206
+ const graphZoom = clampZoom(vc.disablePreview?.graphZoom ?? 1)
207
+ const setGraphZoom = typeof vc.disablePreview?.setGraphZoom === 'function' ? vc.disablePreview.setGraphZoom : undefined
208
+ // 两张图必须共用本次预演的快照;页面级快照可能早于或晚于这次采集。
209
+ const graphSnapshot = data.graph ?? vc.snapshot
210
+ const impactGraph = impactTree.buildRelationTree(graphSnapshot, data.target, {
211
+ depth: 2,
212
+ chain: data.chain,
213
+ groupChildren: data.descendants,
214
+ })
215
+ const fullGraph = impactTree.buildFullChain(graphSnapshot, data.target)
216
+ const tree = graphMode === 'full' ? fullGraph : impactGraph
217
+ const layout = impactTree.layoutRelationTree(tree)
218
+ const rows = impactTree.flattenRelationTree(tree)
219
+ const pending = new Set((data.services?.pending ?? []).map((row) => row.rowId))
220
+ const blockedCount = rows.filter((row) => row.blocked === true).length
221
+ const upstreamCount = rows.filter((row) => row.side === 'upstream').length
222
+ const downstreamCount = rows.filter((row) => row.side === 'downstream').length
223
+ const hasGraph = tree.root !== null && layout.nodes.length > 1
224
+ const openPlugin = typeof vc.gotoPlugin === 'function' ? vc.gotoPlugin : () => {}
225
+ // 换目标或换视图时回到居中;同一张图内的缩放与平移保留。
226
+ const viewKey = `${graphMode}|${data.target?.rowId ?? ''}|${layout.width}x${layout.height}`
227
+ // 图换了就按新尺寸重算适配比例;视口尺寸变了也在每次渲染时跟上。
228
+ if (graphFit.width !== layout.width || graphFit.height !== layout.height) {
229
+ graphFit.width = layout.width
230
+ graphFit.height = layout.height
231
+ }
232
+ const resized = measureGraph()
233
+ graphView.scale = graphFit.scale * graphZoom
234
+ graphZoomControl.zoom = graphZoom
235
+ graphZoomControl.set = setGraphZoom
236
+ if (graphView.key !== viewKey || resized) {
237
+ graphView.key = viewKey
238
+ centerGraph()
239
+ }
240
+ const resetGraphView = () => {
241
+ graphView.scale = graphFit.scale
242
+ centerGraph()
243
+ applyGraphView()
244
+ if (setGraphZoom !== undefined) setGraphZoom(1)
245
+ }
246
+ const zoomControls = setGraphZoom === undefined ? null : h(
247
+ 'span',
248
+ { className: 'ptGraphZoom' },
249
+ textButton('−', () => zoomGraph(graphViewportElement, undefined, undefined, -1), { disabled: graphZoom <= GRAPH_ZOOM_MIN, title: '缩小关系图(也可以按住 Ctrl 滚动滚轮)' }),
250
+ h('span', { className: 'ptGraphZoomValue', title: '当前缩放比例;100% 表示整图适配视口,Ctrl + 滚轮可直接缩放' }, `${Math.round(graphZoom * 100)}%`),
251
+ textButton('+', () => zoomGraph(graphViewportElement, undefined, undefined, 1), { disabled: graphZoom >= GRAPH_ZOOM_MAX, title: '放大关系图(也可以按住 Ctrl 滚动滚轮)' }),
252
+ textButton('重置', resetGraphView, { title: '回到整图适配并居中' }),
253
+ )
254
+ const toggle = setGraphMode === undefined ? null : textButton(
255
+ graphMode === 'full' ? '切换到影响图' : '切换到完整链路图',
256
+ () => setGraphMode(graphMode === 'full' ? 'impact' : 'full'),
257
+ )
258
+ const actions = zoomControls === null && toggle === null ? null : h('span', { className: 'ptActions' }, zoomControls, toggle)
259
+ const graphLabel = graphMode === 'full'
260
+ ? `插件完整依赖链:目标 ${data.target.title},上游 ${upstreamCount} 个,下游 ${downstreamCount} 个。`
261
+ : `插件关系图:目标 ${data.target.title},上游 ${upstreamCount} 个,下游 ${downstreamCount} 个${blockedCount > 0 ? `(其中受阻 ${blockedCount} 个)` : ''}。`
262
+ return h(
263
+ 'div',
264
+ { className: 'ptSection' },
265
+ h(
266
+ 'div',
267
+ { className: 'ptSectionHead' },
268
+ h('p', { className: 'ptSectionTitle' }, '依赖关系图'),
269
+ actions,
270
+ ),
271
+ hasGraph
272
+ ? h(
273
+ 'div',
274
+ {
275
+ className: 'ptGraphViewport',
276
+ ref: setGraphViewport,
277
+ title: '按住 Ctrl 滚动滚轮缩放,按住拖拽平移',
278
+ // 关键布局也写在行内:即使宿主还挂着旧样式,图也不会跑出固定区域。
279
+ style: { position: 'relative', overflow: 'hidden', flex: 'none', height: GRAPH_VIEWPORT_HEIGHT, minHeight: GRAPH_VIEWPORT_MIN_HEIGHT },
280
+ onPointerDown: startGraphPan,
281
+ onPointerMove: moveGraphPan,
282
+ onPointerUp: endGraphPan,
283
+ onPointerLeave: () => { if (graphPan.moved !== true) graphPan.active = false },
284
+ onPointerCancel: endGraphPan,
285
+ },
286
+ h(
287
+ 'div',
288
+ {
289
+ className: 'ptGraphStage',
290
+ ref: setGraphStage,
291
+ style: {
292
+ position: 'absolute',
293
+ top: 0,
294
+ left: 0,
295
+ width: `${layout.width}px`,
296
+ height: `${layout.height}px`,
297
+ transformOrigin: '0 0',
298
+ transform: graphTransform(graphView, graphView.scale),
299
+ },
300
+ },
301
+ h(
302
+ 'svg',
303
+ {
304
+ className: 'ptGraph',
305
+ viewBox: `0 0 ${layout.width} ${layout.height}`,
306
+ role: 'group',
307
+ 'aria-label': graphLabel,
308
+ },
309
+ layout.edges.map((edge) => h(
310
+ 'g',
311
+ { key: edge.key },
312
+ h('path', { className: 'ptGraphEdge', 'data-kind': edge.kind, d: edge.d }),
313
+ h('polygon', { className: 'ptGraphArrow', points: edge.arrow }),
314
+ edge.label
315
+ ? h('text', { className: 'ptGraphEdgeLabel', x: edge.labelX, y: edge.labelY, textAnchor: 'middle' }, clip(edge.label, 18))
316
+ : null,
317
+ )),
318
+ layout.nodes.map((node) => {
319
+ // 方块里只有插件名;状态、层级与服务边都收进悬浮提示。
320
+ const tooltip = nodeTooltip(node, data)
321
+ const titleLines = impactTree.wrapGraphTitle(node.title, 2, node.width)
322
+ const labelY = titleLines.length > 1 ? 28 : 36
323
+ return h(
324
+ 'g',
325
+ {
326
+ key: node.key,
327
+ className: 'ptGraphNode',
328
+ 'data-tone': node.side === 'root' ? 'target' : node.blocked === true || pending.has(node.rowId) ? 'pending' : undefined,
329
+ role: 'button',
330
+ tabIndex: 0,
331
+ 'aria-label': `${node.title}:${tooltip},点击在插件页打开`,
332
+ onClick: () => {
333
+ if (graphPan.moved === true) return
334
+ openPlugin(node.rowId)
335
+ },
336
+ onKeyDown: (event) => activateOnKey(event, () => openPlugin(node.rowId)),
337
+ },
338
+ h('title', null, `${node.title} · ${tooltip}`),
339
+ h('rect', { x: node.x, y: node.y, width: node.width, height: node.height, rx: 8 }),
340
+ h(
341
+ 'text',
342
+ { className: 'ptGraphLabel', x: node.x + 10, y: node.y + labelY },
343
+ titleLines.map((line, index) => h(
344
+ 'tspan',
345
+ { key: index, x: node.x + 10, dy: index === 0 ? 0 : 16 },
346
+ line,
347
+ )),
348
+ ),
349
+ )
350
+ }),
351
+ ),
352
+ ),
353
+ )
354
+ : h('p', { className: 'ptEmpty' }, '没有可绘制的上下游关系'),
355
+ tree.notes.length > 0
356
+ ? h('div', null, tree.notes.map((note) => h('p', { key: note, className: 'ptHint', style: { margin: 0 } }, note)))
357
+ : null,
358
+ )
359
+ }
360
+
361
+ return { renderRelations }
362
+ }
363
+ },
364
+ })