cladogram 0.5.5-beta.1 → 0.5.5-beta.3

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.
@@ -5,8 +5,101 @@ const vendor = { exports: {} };
5
5
  runInNewContext(readFileSync(new URL('../vendor/marked.umd.js', import.meta.url), 'utf8'), { module: vendor, exports: vendor.exports });
6
6
  const { lexer } = vendor.exports;
7
7
 
8
+ function safeDecode(value) {
9
+ try { return decodeURIComponent(value); } catch { return null; }
10
+ }
11
+
12
+ export function hasTargetSpec(title) {
13
+ return Boolean(title && (/^clado:to:/.test(title) || /;to:/.test(title)));
14
+ }
15
+
16
+ export function isTargetOnlyTitle(title) {
17
+ return Boolean(title && /^clado:to:/.test(title));
18
+ }
19
+
20
+ export function mediaTargetPoint(title) {
21
+ if (!title || typeof title !== 'string') return null;
22
+ let spec = null;
23
+ if (title.startsWith('clado:to:')) spec = title.slice('clado:to:'.length);
24
+ else {
25
+ const idx = title.indexOf(';to:');
26
+ if (idx < 0) return null;
27
+ spec = title.slice(idx + ';to:'.length);
28
+ }
29
+ if (!spec || /\s/.test(spec)) return null;
30
+
31
+ // 旧版简写:to:<tableIdx>:<row>
32
+ const legacyTable = /^([1-9]\d*):([1-9]\d*)$/.exec(spec);
33
+ if (legacyTable) {
34
+ const table = +legacyTable[1], row = +legacyTable[2];
35
+ if (!Number.isSafeInteger(table) || !Number.isSafeInteger(row)) return null;
36
+ return { kind: 'table', table, row };
37
+ }
38
+
39
+ // 对称表格行:to:table:<tableIdx>:<row>[:<encodedText>]
40
+ const tableMatch = /^table:([1-9]\d*):([1-9]\d*)(?::([^\s;]+))?$/.exec(spec);
41
+ if (tableMatch) {
42
+ const table = +tableMatch[1], row = +tableMatch[2];
43
+ if (!Number.isSafeInteger(table) || !Number.isSafeInteger(row)) return null;
44
+ const text = tableMatch[3] ? safeDecode(tableMatch[3]) : undefined;
45
+ if (tableMatch[3] && (!text || /[\r\n]/.test(text))) return null;
46
+ return { kind: 'table', table, row, ...(text ? { text } : {}) };
47
+ }
48
+
49
+ // 对称代码块行:to:code:<blockIdx>:<line>[:<encodedText>]
50
+ const codeMatch = /^code:([1-9]\d*):([1-9]\d*)(?::([^\s;]+))?$/.exec(spec);
51
+ if (codeMatch) {
52
+ const block = +codeMatch[1], line = +codeMatch[2];
53
+ if (!Number.isSafeInteger(block) || !Number.isSafeInteger(line)) return null;
54
+ const text = codeMatch[3] ? safeDecode(codeMatch[3]) : undefined;
55
+ if (codeMatch[3] && (!text || /[\r\n]/.test(text))) return null;
56
+ return { kind: 'code', block, line, ...(text ? { text } : {}) };
57
+ }
58
+
59
+ // 对称 Mermaid 节点:to:mermaid:<blockIdx>:<nodeId>
60
+ const mermaidMatch = /^mermaid:([1-9]\d*):([\w.-]+)$/.exec(spec);
61
+ if (mermaidMatch) {
62
+ const block = +mermaidMatch[1];
63
+ if (!Number.isSafeInteger(block)) return null;
64
+ return { kind: 'mermaid', block, nodeId: mermaidMatch[2] };
65
+ }
66
+
67
+ // 稳定语义正文/列表行锚点:to:line:<encodedText>
68
+ const lineMatch = /^line:([^\s;]+)$/.exec(spec);
69
+ if (lineMatch) {
70
+ const text = safeDecode(lineMatch[1]);
71
+ if (!text || !text.trim() || /[\r\n]/.test(text)) return null;
72
+ return { kind: 'line', text };
73
+ }
74
+
75
+ return null;
76
+ }
77
+
78
+ export function formatTargetPoint(point, { standalone = false } = {}) {
79
+ if (!point || !point.kind) return '';
80
+ const prefix = standalone ? 'clado:to:' : 'to:';
81
+ if (point.kind === 'line') {
82
+ return prefix + 'line:' + encodeURIComponent(point.text);
83
+ }
84
+ if (point.kind === 'code') {
85
+ return prefix + 'code:' + point.block + ':' + point.line + (point.text ? ':' + encodeURIComponent(point.text) : '');
86
+ }
87
+ if (point.kind === 'mermaid') {
88
+ return prefix + 'mermaid:' + point.block + ':' + point.nodeId;
89
+ }
90
+ if (point.kind === 'table') {
91
+ if (!standalone && !point.text) return 'to:' + point.table + ':' + point.row;
92
+ return prefix + 'table:' + point.table + ':' + point.row + (point.text ? ':' + encodeURIComponent(point.text) : '');
93
+ }
94
+ return '';
95
+ }
96
+
8
97
  export function mediaLinkPoint(title) {
9
- const match = /^clado:(code|table|mermaid):([^\s;]+)(?:;text:([^\s;]+))?(?:;to:[1-9]\d*:[1-9]\d*)?$/.exec(title || '');
98
+ if (!title || typeof title !== 'string') return null;
99
+ const toIdx = title.indexOf(';to:');
100
+ if (toIdx >= 0 && !mediaTargetPoint(title)) return null;
101
+ const head = toIdx >= 0 ? title.slice(0, toIdx) : title;
102
+ const match = /^clado:(code|table|mermaid):([^\s;]+)(?:;text:([^\s;]+))?$/.exec(head);
10
103
  if (!match) return null;
11
104
  const [, kind, value, encodedText] = match;
12
105
  if (encodedText && kind !== 'code') return null;
@@ -16,11 +109,6 @@ export function mediaLinkPoint(title) {
16
109
  catch { return null; }
17
110
  }
18
111
 
19
- export function mediaTargetPoint(title) {
20
- const match = /;to:([1-9]\d*):([1-9]\d*)$/.exec(title || '');
21
- return match ? { kind: 'table', table: +match[1], row: +match[2] } : null;
22
- }
23
-
24
112
  export function mediaLinkTitle(point) {
25
113
  return 'clado:' + point.kind + ':' + (point.line ?? point.row ?? point.nodeId) + (point.text ? ';text:' + encodeURIComponent(point.text) : '');
26
114
  }
@@ -40,7 +128,7 @@ export function codeReferenceOffset(line, reference) {
40
128
  }
41
129
 
42
130
  export function mediaBlock(token) {
43
- if (token?.type === 'table') return { kind: 'table', rows: token.rows.length };
131
+ if (token?.type === 'table') return { kind: 'table', rows: token.rows.length, rawRows: token.rows.map(r => r.map(c => c.text).join(' | ')) };
44
132
  if (token?.type !== 'code') return null;
45
133
  if (/^mermaid(?:\s|$)/i.test(token.lang || '')) return { kind: 'mermaid', source: token.text };
46
134
  return { kind: 'code', lines: token.text.split('\n') };
@@ -51,15 +139,49 @@ export function blockMedia(text) {
51
139
  return tokens.length === 1 ? mediaBlock(tokens[0]) : null;
52
140
  }
53
141
 
54
- export function tableBlock(markdown, index) {
142
+ export function mediaBlockByIndex(markdown, kind, index) {
55
143
  let offset = 0, count = 0;
56
144
  for (const token of lexer(markdown)) {
57
- if (token.type === 'table' && ++count === index) return { blockStart: offset, blockEnd: offset + token.raw.trimEnd().length, rows: token.rows.length };
145
+ const block = mediaBlock(token);
146
+ if (block?.kind === kind && ++count === index) {
147
+ return {
148
+ blockStart: offset,
149
+ blockEnd: offset + token.raw.trimEnd().length,
150
+ media: block,
151
+ ...(kind === 'table' ? { rows: block.rows } : {}),
152
+ };
153
+ }
58
154
  offset += token.raw.length;
59
155
  }
60
156
  return null;
61
157
  }
62
158
 
159
+ export function tableBlock(markdown, index) {
160
+ return mediaBlockByIndex(markdown, 'table', index);
161
+ }
162
+
163
+ export function findTargetLineOffset(markdown, needle) {
164
+ if (!markdown || !needle || !needle.trim()) return null;
165
+ const lines = markdown.split('\n');
166
+ let fence = null, offset = 0;
167
+ for (let i = 0; i < lines.length; i++) {
168
+ const line = lines[i];
169
+ const f = /^ {0,3}(`{3,}|~{3,})/.exec(line);
170
+ if (f) {
171
+ if (!fence) fence = f[1];
172
+ else if (f[1][0] === fence[0] && f[1].length >= fence.length) fence = null;
173
+ offset += line.length + 1;
174
+ continue;
175
+ }
176
+ if (!fence && line.includes(needle)) {
177
+ const idx = line.indexOf(needle);
178
+ return { lineNumber: i + 1, start: offset + idx, end: offset + idx + needle.length };
179
+ }
180
+ offset += line.length + 1;
181
+ }
182
+ return null;
183
+ }
184
+
63
185
  export function mediaPointFits(media, point) {
64
186
  if (media?.kind !== point?.kind) return false;
65
187
  if (point.kind === 'code') {
@@ -68,7 +190,11 @@ export function mediaPointFits(media, point) {
68
190
  if (!point.text) return true;
69
191
  return codeReferenceOffset(line, point.text) >= 0;
70
192
  }
71
- if (point.kind === 'table') return point.row <= media.rows;
193
+ if (point.kind === 'table') {
194
+ if (point.row > media.rows) return false;
195
+ if (!point.text) return true;
196
+ return Boolean(media.rawRows?.[point.row - 1]?.includes(point.text));
197
+ }
72
198
  const statements = media.source.split(/\n|;/).filter(line => !/^\s*(?:%%|flowchart\b|graph\b|classDef\b|class\s|style\s|linkStyle\b|direction\b|end\s*$)/.test(line));
73
199
  return statements.some(line => {
74
200
  const graph = line.replace(/"(?:[^"\\]|\\.)*"|\[[^\]\n]*\]|\{[^{}\n]*\}|\([^()\n]*\)|\|[^|\n]*\|/g, ' ');
@@ -76,9 +202,37 @@ export function mediaPointFits(media, point) {
76
202
  });
77
203
  }
78
204
 
205
+ export function targetPointFits(markdown, point) {
206
+ if (!point || !point.kind) return false;
207
+ if (point.kind === 'line') return Boolean(findTargetLineOffset(markdown, point.text));
208
+ if (point.kind === 'table') {
209
+ const found = mediaBlockByIndex(markdown, 'table', point.table);
210
+ if (!found) return false;
211
+ if (point.row <= found.media.rows && (!point.text || found.media.rawRows?.[point.row - 1]?.includes(point.text))) return true;
212
+ if (point.text && found.media.rawRows?.some(r => r.includes(point.text))) return true;
213
+ return false;
214
+ }
215
+ if (point.kind === 'code') {
216
+ const found = mediaBlockByIndex(markdown, 'code', point.block);
217
+ if (!found) return false;
218
+ if (mediaPointFits(found.media, { kind: 'code', line: point.line, text: point.text })) return true;
219
+ // 语义漂移兜底:若目标代码块行号移动,但带了稳定 text 锚点且在块内唯一匹配,仍视为有效!
220
+ if (point.text) {
221
+ const hits = found.media.lines.filter(line => codeReferenceOffset(line, point.text) >= 0);
222
+ return hits.length === 1;
223
+ }
224
+ return false;
225
+ }
226
+ if (point.kind === 'mermaid') {
227
+ const found = mediaBlockByIndex(markdown, 'mermaid', point.block);
228
+ return Boolean(found && mediaPointFits(found.media, { kind: 'mermaid', nodeId: point.nodeId }));
229
+ }
230
+ return false;
231
+ }
232
+
79
233
  // A standalone annotation follows its media block. Consecutive annotations share that block.
80
234
  export function mediaLinkLocations(markdown, links) {
81
- const annotated = links.filter(link => link.title?.startsWith('clado:'));
235
+ const annotated = links.filter(link => link.title?.startsWith('clado:') && !isTargetOnlyTitle(link.title));
82
236
  if (!annotated.length) return new Map();
83
237
  const locations = new Map();
84
238
  let offset = 0, media = null, blockStart, blockEnd;
package/src/core/parse.js CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { parse as parseYaml } from 'yaml';
8
8
  import { markdownLinks } from './links.js';
9
- import { mediaLinkLocations } from './media-links.js';
9
+ import { hasTargetSpec, isTargetOnlyTitle, mediaLinkLocations, mediaTargetPoint, targetPointFits } from './media-links.js';
10
10
 
11
11
  /** 开头 `---` 包的 front matter */
12
12
  const FRONT_MATTER = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
@@ -320,8 +320,17 @@ export function parseDocument(text, opts = {}) {
320
320
  * 字段,把线连到对方的 `## id` 上才说得清是哪个字段对哪个字段。
321
321
  * 键和 targets 一样用链接的**原文**(客户端是拿渲染出来的 href 查表的)。
322
322
  */
323
- const anchors = Object.create(null), targetNodes = Object.create(null), titleOf = new Map();
324
- for (const c of cards) { titleOf.set(c.id,c.title); const walk=ns=>ns.forEach(n=>{titleOf.set(n.id,n.title);walk(n.kids);});walk(c.nodes); }
323
+ const anchors = Object.create(null), targetNodes = Object.create(null), titleOf = new Map(), bodyOf = new Map();
324
+ for (const c of cards) {
325
+ titleOf.set(c.id, c.title);
326
+ bodyOf.set(c.id, c._entry.body.join('\n'));
327
+ const walk = ns => ns.forEach(n => {
328
+ titleOf.set(n.id, n.title);
329
+ bodyOf.set(n.id, n._entry.body.join('\n'));
330
+ walk(n.kids);
331
+ });
332
+ walk(c.nodes);
333
+ }
325
334
  const edgePairs = [];
326
335
 
327
336
  /** 从一张卡出发,逐层处理每个节点 */
@@ -343,7 +352,12 @@ export function parseDocument(text, opts = {}) {
343
352
  // 围栏里示范用的 `[文字](目标)` 不该在图上长出一条线来。
344
353
  for (const link of links) {
345
354
  const lineNo = e.line + source.slice(0, link.start).split('\n').length;
346
- if (link.title?.startsWith('clado:') && !mediaLocations.get(link.start)?.valid) {
355
+ if (isTargetOnlyTitle(link.title)) {
356
+ if (!mediaTargetPoint(link.title)) {
357
+ at('error', 'MD_MEDIA_LINK_TARGET', '连线落点语法不合法。', '使用 clado:to:line:<锚点文本>、clado:to:code:<块>:<行>、clado:to:table:<表>:<行> 或 clado:to:mermaid:<图>:<节点ID>。', lineNo);
358
+ continue;
359
+ }
360
+ } else if (link.title?.startsWith('clado:') && !mediaLocations.get(link.start)?.valid) {
347
361
  at('error', 'MD_MEDIA_LINK_SOURCE', '连线起点未匹配到对应代码行、表格行或 Mermaid 节点。', '用 MCP 重新定位到正确的内容块。', lineNo);
348
362
  continue;
349
363
  }
@@ -395,6 +409,13 @@ export function parseDocument(text, opts = {}) {
395
409
  targets[raw] = '';
396
410
  continue;
397
411
  }
412
+ if (hasTargetSpec(link.title)) {
413
+ const tp = mediaTargetPoint(link.title);
414
+ if (!tp || !targetPointFits(bodyOf.get(got.id) || '', tp)) {
415
+ at('error', 'MD_MEDIA_LINK_TARGET', '连线落点未匹配到目标节点内的对应正文行、代码行、表格行或 Mermaid 节点。', '核对目标卡片中的锚点文本、行号或块编号。', lineNo);
416
+ continue;
417
+ }
418
+ }
398
419
  const mine = e.level === 1 ? card.id : node.id;
399
420
  const theirs = cardOf.get(got.id) || got.id;
400
421
  if (got.id === mine && !anchor) continue;
@@ -12,7 +12,7 @@
12
12
  .markdown-body a.media-jump{position:absolute;z-index:3;width:20px;height:20px;transform:translate(-50%,-50%);border:0;border-radius:50%;background:transparent}
13
13
  .media-jump::after{content:'';position:absolute;inset:7px;border:1px solid var(--accent);border-radius:50%;background:var(--panel)}
14
14
  .media-jump:hover::after,.media-jump:focus-visible::after{background:var(--accent)}
15
- .markdown-body tr.media-target-flash>td{background:var(--accent-soft)}
15
+ .markdown-body tr.media-target-flash>td,.markdown-body .media-target-flash:not(tr){background:var(--accent-soft);border-radius:4px}
16
16
  .media-stems{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none;z-index:2}
17
17
  .media-stems path{fill:none;stroke:var(--accent);stroke-width:1.2;stroke-opacity:.38;stroke-dasharray:3 4;stroke-linecap:round}
18
18
  .media-stems circle{fill:var(--panel);stroke:var(--accent);stroke-width:1.2;stroke-opacity:.65}
@@ -64,3 +64,66 @@
64
64
  .clado-ai-selected::after{animation:selection-light-around 8s linear infinite}
65
65
  }
66
66
  .slice.clado-ai-selected::before,.slice.clado-ai-selected::after{inset:-2px -4px;border-radius:6px}
67
+ @keyframes clado-ai-touch-pulse{
68
+ 0%{box-shadow:0 0 0 0 color-mix(in srgb,var(--accent) 55%,transparent),var(--shadow)}
69
+ 30%{box-shadow:0 0 0 4px color-mix(in srgb,var(--accent) 32%,transparent),0 10px 30px color-mix(in srgb,var(--accent) 18%,transparent)}
70
+ 100%{box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 16%,transparent),var(--shadow)}
71
+ }
72
+ @keyframes clado-ai-waiting-pulse{
73
+ 0%,100%{box-shadow:0 0 0 2px rgb(217 119 6 / .22),0 8px 24px rgb(217 119 6 / .12)}
74
+ 50%{box-shadow:0 0 0 4px rgb(217 119 6 / .36),0 10px 28px rgb(217 119 6 / .2)}
75
+ }
76
+ .canvas-card.clado-ai-touched,.mnode.clado-ai-touched{
77
+ border-color:color-mix(in srgb,var(--accent) 62%,var(--line));
78
+ animation:clado-ai-touch-pulse 1.1s cubic-bezier(.22,.75,.24,1) 1 forwards;
79
+ }
80
+ .canvas-card.clado-ai-reading,.mnode.clado-ai-reading{
81
+ border-color:color-mix(in srgb,var(--accent) 40%,var(--line));
82
+ box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 16%,transparent),var(--shadow);
83
+ }
84
+ .canvas-card.clado-ai-waiting,.mnode.clado-ai-waiting{
85
+ border-color:#d97706;
86
+ animation:clado-ai-waiting-pulse 2.2s ease-in-out infinite;
87
+ }
88
+ [data-theme="dark"] .canvas-card.clado-ai-waiting,[data-theme="dark"] .mnode.clado-ai-waiting{
89
+ border-color:#f59e0b;
90
+ }
91
+ .slice.clado-ai-touched,.slice.clado-ai-reading{
92
+ background:color-mix(in srgb,var(--accent) 7%,transparent);
93
+ border-radius:6px;
94
+ }
95
+ .slice.clado-ai-waiting{
96
+ background:rgb(217 119 6 / .12);
97
+ border-radius:6px;
98
+ }
99
+ @media(prefers-reduced-motion:reduce){
100
+ .canvas-card.clado-ai-touched,.mnode.clado-ai-touched,.canvas-card.clado-ai-waiting,.mnode.clado-ai-waiting{animation:none}
101
+ }
102
+ #cladoAiToast{
103
+ position:fixed;left:50%;bottom:18px;z-index:42;
104
+ display:inline-flex;align-items:center;gap:7px;
105
+ max-width:min(460px,calc(100vw - 40px));padding:7px 14px;
106
+ border:0;border-radius:999px;font-size:12px;font-weight:500;line-height:1.25;
107
+ color:var(--fg);cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
108
+ background:color-mix(in srgb,var(--panel) 78%,transparent);
109
+ backdrop-filter:blur(14px) saturate(145%);-webkit-backdrop-filter:blur(14px) saturate(145%);
110
+ box-shadow:0 6px 24px rgb(0 0 0 / .12);
111
+ opacity:0;transform:translate(-50%,8px);pointer-events:none;
112
+ transition:opacity 180ms cubic-bezier(.22,.75,.24,1),transform 180ms cubic-bezier(.22,.75,.24,1);
113
+ }
114
+ #cladoAiToast.open{opacity:1;transform:translate(-50%,0);pointer-events:auto}
115
+ #cladoAiToast .dot{
116
+ width:7px;height:7px;border-radius:50%;flex:none;
117
+ background:var(--accent);box-shadow:0 0 8px color-mix(in srgb,var(--accent) 70%,transparent);
118
+ }
119
+ #cladoAiToast.waiting .dot{
120
+ background:#d97706;box-shadow:0 0 8px rgb(217 119 6 / .72);
121
+ }
122
+ [data-theme="dark"] #cladoAiToast.waiting .dot{
123
+ background:#f59e0b;box-shadow:0 0 8px rgb(245 158 11 / .75);
124
+ }
125
+ [data-theme="dark"] #cladoAiToast{
126
+ background:color-mix(in srgb,var(--panel) 72%,transparent);
127
+ box-shadow:0 8px 28px rgb(0 0 0 / .36);
128
+ }
129
+
@@ -49,7 +49,7 @@ drawWires = function () {
49
49
  input.dataset.edge = targetId;
50
50
  target.append(input);
51
51
  canvasMediaStem(input, landing, true);
52
- } else if (port.dataset.mediaPoint?.includes(';to:')) return;
52
+ } else if (canvasHasTargetSpec(port.dataset.mediaPoint)) return;
53
53
  else if (port.dataset.anchor) {
54
54
  var heading = $$('.slice-head', target).find(function (h) { return port.dataset.anchorId ? h.closest('.slice').dataset.id === port.dataset.anchorId : h.textContent.trim() === port.dataset.anchor; });
55
55
  if (heading) {
@@ -67,7 +67,7 @@ drawWires = function () {
67
67
  }
68
68
  var from = point ? canvasSourceStem(svg, port, point) : canvasPort(svg, port);
69
69
  var d = canvasWirePath(from, canvasPort(svg, input));
70
- paths.push('<path class="' + (port.dataset.soft ? 'w-soft' : '') + '" data-source-id="' + esc(sourceId) + '" data-target-id="' + esc(targetId) + '"' + (point ? ' data-media-point="' + esc(port.dataset.mediaPoint) + '"' : '') + ' d="' + d + '"/>');
70
+ paths.push('<path class="' + (port.dataset.soft ? 'w-soft' : '') + '" data-source-id="' + esc(sourceId) + '" data-target-id="' + esc(targetId) + '"' + (port.dataset.mediaPoint ? ' data-media-point="' + esc(port.dataset.mediaPoint) + '"' : '') + ' d="' + d + '"/>');
71
71
  });
72
72
  svg.innerHTML = paths.join('');
73
73
  };
@@ -25,6 +25,50 @@ function canvasCodeLine(code, line) {
25
25
  return null;
26
26
  }
27
27
 
28
+ function canvasDecodeSpec(value) {
29
+ try { return decodeURIComponent(value); } catch { return null; }
30
+ }
31
+
32
+ function canvasParseTargetSpec(detail) {
33
+ if (!detail || typeof detail !== 'string') return null;
34
+ var spec = null;
35
+ if (detail.indexOf('clado:to:') === 0) spec = detail.slice(9);
36
+ else {
37
+ var idx = detail.indexOf(';to:');
38
+ if (idx >= 0) spec = detail.slice(idx + 4);
39
+ }
40
+ if (!spec) return null;
41
+ var legacy = /^([1-9]\d*):([1-9]\d*)$/.exec(spec);
42
+ if (legacy) return { kind: 'table', table: +legacy[1], row: +legacy[2] };
43
+ var table = /^table:([1-9]\d*):([1-9]\d*)(?::([^\s;]+))?$/.exec(spec);
44
+ if (table) return { kind: 'table', table: +table[1], row: +table[2], text: table[3] ? canvasDecodeSpec(table[3]) : null };
45
+ var code = /^code:([1-9]\d*):([1-9]\d*)(?::([^\s;]+))?$/.exec(spec);
46
+ if (code) return { kind: 'code', block: +code[1], line: +code[2], text: code[3] ? canvasDecodeSpec(code[3]) : null };
47
+ var mermaid = /^mermaid:([1-9]\d*):([\w.-]+)$/.exec(spec);
48
+ if (mermaid) return { kind: 'mermaid', block: +mermaid[1], nodeId: mermaid[2] };
49
+ var line = /^line:([^\s;]+)$/.exec(spec);
50
+ if (line) {
51
+ var text = canvasDecodeSpec(line[1]);
52
+ return text ? { kind: 'line', text: text } : null;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ function canvasHasTargetSpec(detail) {
58
+ return !!canvasParseTargetSpec(detail);
59
+ }
60
+
61
+ function canvasFindMermaidNode(diagram, nodeId) {
62
+ var nodes = $$('g.node[id],g.stateGroup[id],g.entityBox[id],rect.entityBox[id],g.actor[id],rect.actor[id]', diagram);
63
+ var node = nodes.find(function (el) {
64
+ var originalId = el.getAttribute('data-id');
65
+ var id = el.id.startsWith(diagram.id + '-') ? el.id.slice(diagram.id.length + 1) : el.id;
66
+ return originalId === nodeId || id === nodeId || id === 'state-' + nodeId ||
67
+ id.replace(/^(?:flowchart|state|entity|classId)-/, '').replace(/-\d+$/, '') === nodeId;
68
+ });
69
+ return { node: node || null, nodes: nodes };
70
+ }
71
+
28
72
  function canvasBindMediaLinks(box) {
29
73
  $$('.zoomable', box).forEach(function (block) {
30
74
  var next = block.nextElementSibling;
@@ -47,10 +91,21 @@ function canvasBindMediaLinks(box) {
47
91
  link.mediaTrigger = trigger;
48
92
  link.mediaBlock.appendChild(trigger);
49
93
  });
94
+ // 绑定行内对称落点链接(clado:to:...),保留正常可见文字,同时清理原生 title 气泡
95
+ $$('a.edge:not(.media-jump)', box).forEach(function (link) {
96
+ if (link.mediaBlock) return;
97
+ var title = link.getAttribute('title');
98
+ if (title && title.indexOf('clado:to:') === 0 && canvasHasTargetSpec(title)) {
99
+ link.dataset.mediaPoint = title;
100
+ link.title = link.textContent;
101
+ }
102
+ });
50
103
  $$('.ztable tbody', box).forEach(function (table) {
51
104
  $$('tr', table).forEach(function (row, index) {
52
105
  $$('a.edge', row).forEach(function (link) {
53
- link.dataset.mediaPoint = 'clado:table:' + (index + 1);
106
+ var existing = link.dataset.mediaPoint;
107
+ var suffix = existing && existing.indexOf('clado:to:') === 0 ? ';' + existing.slice(6) : '';
108
+ link.dataset.mediaPoint = 'clado:table:' + (index + 1) + suffix;
54
109
  link.mediaBlock = table.closest('.ztable');
55
110
  });
56
111
  });
@@ -74,17 +129,12 @@ function canvasMediaSource(link, card) {
74
129
  } else {
75
130
  var diagram = $('.mermaid svg', block);
76
131
  if (!diagram) return null;
77
- var nodes = $$('g.node[id],g.stateGroup[id],g.entityBox[id],rect.entityBox[id],g.actor[id],rect.actor[id]', diagram);
78
- var node = nodes.find(function (el) {
79
- var originalId = el.getAttribute('data-id');
80
- var id = el.id.startsWith(diagram.id + '-') ? el.id.slice(diagram.id.length + 1) : el.id;
81
- return originalId === parts[2] || id === parts[2] || id === 'state-' + parts[2] ||
82
- id.replace(/^(?:flowchart|state|entity|classId)-/, '').replace(/-\d+$/, '') === parts[2];
83
- });
132
+ var found = canvasFindMermaidNode(diagram, parts[2]);
133
+ var node = found.node;
84
134
  if (!node) return null;
85
135
  rect = node.getBoundingClientRect();
86
136
  right = rect.right;
87
- obstacles = nodes.filter(function (other) { return other !== node; }).map(function (other) { return other.getBoundingClientRect(); });
137
+ obstacles = found.nodes.filter(function (other) { return other !== node; }).map(function (other) { return other.getBoundingClientRect(); });
88
138
  }
89
139
  if (!rect || !rect.height) return null;
90
140
  var y = rect.top + rect.height / 2;
@@ -132,41 +182,137 @@ function canvasPlaceMediaJumps(root) {
132
182
  });
133
183
  }
134
184
 
135
- function canvasTargetRow(container, targetId, detail) {
136
- var match = /;to:(\d+):(\d+)$/.exec(detail || '');
137
- if (!match) return null;
185
+ function canvasScopeElements(container, targetId, selector) {
138
186
  var section = $$('.slice[data-id]', container).find(function (el) { return el.dataset.id === targetId; });
139
- var tables = $$('table', section || container).filter(function (table) { return !!section || table.closest('.slice') === (container.matches('.slice') ? container : null); });
140
- var table = tables[+match[1] - 1];
141
- return table && $$('tbody > tr', table)[+match[2] - 1];
187
+ var root = section || container;
188
+ var ownSlice = section || (container.matches('.slice') ? container : null);
189
+ return $$(selector, root).filter(function (el) {
190
+ if (el.closest('.media-reference')) return false;
191
+ var s = el.closest('.slice');
192
+ return s === ownSlice;
193
+ });
194
+ }
195
+
196
+ function canvasFindTextRangeRect(element, needle) {
197
+ var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
198
+ var full = '', nodes = [];
199
+ while (walker.nextNode()) {
200
+ var n = walker.currentNode;
201
+ if (n.parentElement && n.parentElement.closest('.media-reference,pre')) continue;
202
+ nodes.push({ node: n, start: full.length, end: full.length + n.length });
203
+ full += n.nodeValue || '';
204
+ }
205
+ var idx = full.indexOf(needle);
206
+ if (idx < 0) return null;
207
+ var endIdx = idx + needle.length;
208
+ var range = document.createRange();
209
+ var started = false;
210
+ for (var i = 0; i < nodes.length; i++) {
211
+ var entry = nodes[i];
212
+ if (!started && entry.end > idx) {
213
+ range.setStart(entry.node, Math.max(0, idx - entry.start));
214
+ started = true;
215
+ }
216
+ if (started && entry.end >= endIdx) {
217
+ range.setEnd(entry.node, Math.max(0, endIdx - entry.start));
218
+ var rects = Array.from(range.getClientRects()).filter(function (r) { return r.height; });
219
+ return rects[0] || range.getBoundingClientRect();
220
+ }
221
+ }
222
+ return null;
223
+ }
224
+
225
+ function canvasTargetAnchor(container, targetId, detail) {
226
+ var spec = canvasParseTargetSpec(detail);
227
+ if (!spec) return null;
228
+ if (spec.kind === 'table') {
229
+ var tables = canvasScopeElements(container, targetId, 'table');
230
+ var table = tables[spec.table - 1];
231
+ if (!table) return null;
232
+ var rows = $$('tbody > tr', table);
233
+ var row = rows[spec.row - 1];
234
+ if (spec.text && (!row || row.textContent.indexOf(spec.text) < 0)) {
235
+ row = rows.find(function (tr) { return tr.textContent.indexOf(spec.text) >= 0; }) || row;
236
+ }
237
+ if (!row) return null;
238
+ var rect = row.getBoundingClientRect();
239
+ var scrollEl = row.closest('.tscroll');
240
+ var x = scrollEl ? Math.max(rect.left, scrollEl.getBoundingClientRect().left) : rect.left;
241
+ return { x: x, y: rect.top + rect.height / 2, element: row };
242
+ }
243
+ if (spec.kind === 'code') {
244
+ var codes = canvasScopeElements(container, targetId, 'pre > code').filter(function (c) {
245
+ return !c.closest('.mermaid');
246
+ });
247
+ var code = codes[spec.block - 1];
248
+ if (!code) return null;
249
+ var targetLine = spec.line;
250
+ if (spec.text) {
251
+ var lines = code.textContent.split('\n');
252
+ if (!lines[targetLine - 1] || lines[targetLine - 1].indexOf(spec.text) < 0) {
253
+ var foundIdx = lines.findIndex(function (l) { return l.indexOf(spec.text) >= 0; });
254
+ if (foundIdx >= 0) targetLine = foundIdx + 1;
255
+ }
256
+ }
257
+ var lineRect = canvasCodeLine(code, targetLine);
258
+ if (!lineRect || !lineRect.height) return null;
259
+ var preRect = code.parentElement.getBoundingClientRect();
260
+ return { x: preRect.left, y: lineRect.top + lineRect.height / 2, element: code.parentElement };
261
+ }
262
+ if (spec.kind === 'mermaid') {
263
+ var diagrams = canvasScopeElements(container, targetId, '.mermaid svg');
264
+ var diagram = diagrams[spec.block - 1];
265
+ if (!diagram) return null;
266
+ var m = canvasFindMermaidNode(diagram, spec.nodeId);
267
+ if (!m.node) return null;
268
+ var mRect = m.node.getBoundingClientRect();
269
+ if (!mRect.height) return null;
270
+ return { x: mRect.left, y: mRect.top + mRect.height / 2, element: m.node };
271
+ }
272
+ if (spec.kind === 'line') {
273
+ var blocks = canvasScopeElements(container, targetId, 'li,p,blockquote,td,th').filter(function (el) {
274
+ return !el.closest('pre') && el.textContent.indexOf(spec.text) >= 0;
275
+ });
276
+ // 优先取最内层包含该锚点文本的元素(避免外层 li 抢占内层子 li)
277
+ blocks.sort(function (a, b) { return a.textContent.length - b.textContent.length; });
278
+ for (var i = 0; i < blocks.length; i++) {
279
+ var el = blocks[i];
280
+ var r = canvasFindTextRangeRect(el, spec.text);
281
+ if (r && r.height) {
282
+ var elRect = el.getBoundingClientRect();
283
+ return { x: Math.min(r.left, elRect.left), y: r.top + r.height / 2, element: el };
284
+ }
285
+ }
286
+ return null;
287
+ }
288
+ return null;
142
289
  }
143
290
 
144
291
  function canvasMediaTarget(card, targetId, detail) {
145
- var row = canvasTargetRow(card, targetId, detail);
146
- if (!row) return null;
147
- var rect = row.getBoundingClientRect(), scroll = row.closest('.tscroll').getBoundingClientRect();
148
- var x = Math.max(rect.left, scroll.left), y = rect.top + rect.height / 2;
292
+ var hit = canvasTargetAnchor(card, targetId, detail);
293
+ if (!hit) return null;
149
294
  var body = $('.body', card).getBoundingClientRect();
150
- return y >= body.top && y <= body.bottom && x <= body.right ? { x: x, y: y } : null;
295
+ return hit.y >= body.top && hit.y <= body.bottom && hit.x <= body.right ? { x: hit.x, y: hit.y } : null;
151
296
  }
152
297
 
153
298
  function canvasRevealMediaTarget(link, id) {
154
299
  var record = canvasRecords[id];
155
- if (!record || !link.dataset.mediaPoint?.includes(';to:')) return;
300
+ if (!record || !canvasHasTargetSpec(link.dataset.mediaPoint)) return;
156
301
  var mode = document.body.dataset.mode, container;
157
302
  if (mode === 'cards') container = render.card[record.card];
158
303
  else if (mode === 'mindmap') container = $('#mind .mnode[data-path="' + record.mindPath + '"]');
159
304
  else container = $('#article .slice[data-path="' + record.docPath + '"]');
160
- var row = container && canvasTargetRow(container, id, link.dataset.mediaPoint);
161
- if (!row) return;
162
- row.classList.add('media-target-flash');
163
- if (mode === 'doc') row.scrollIntoView({ block: 'center', inline: 'nearest' });
305
+ var hit = container && canvasTargetAnchor(container, id, link.dataset.mediaPoint);
306
+ if (!hit || !hit.element) return;
307
+ hit.element.classList.add('media-target-flash');
308
+ if (mode === 'doc') hit.element.scrollIntoView({ block: 'center', inline: 'nearest' });
164
309
  else {
165
- var stage = $('#stage').getBoundingClientRect(), rect = row.getBoundingClientRect();
166
- ty += stage.top + stage.height / 2 - (rect.top + rect.height / 2);
310
+ var stage = $('#stage').getBoundingClientRect();
311
+ ty += stage.top + stage.height / 2 - hit.y;
167
312
  apply();
313
+ if (mode === 'mindmap') drawMindWires(); else drawWires();
168
314
  }
169
- setTimeout(function () { row.classList.remove('media-target-flash'); }, 1100);
315
+ setTimeout(function () { hit.element.classList.remove('media-target-flash'); }, 1100);
170
316
  }
171
317
 
172
318
  function canvasSourceStem(svg, port, sourcePoint) {
@@ -39,18 +39,20 @@ function canvasDrawMindWires() {
39
39
  var anchored = Object.keys(nodes).find(function (key) { return key.indexOf(parentPath + '.') === 0 && nodes[key].record.title === link.dataset.anchor; });
40
40
  if (anchored) target = nodes[anchored];
41
41
  }
42
- if (target === source || (!link.mediaBlock && seen[target.path])) return;
43
- if (!link.mediaBlock) seen[target.path] = true;
42
+ var dedupKey = target.path + '|' + (link.dataset.mediaPoint || '');
43
+ if (target === source || (!link.mediaBlock && seen[dedupKey])) return;
44
+ if (!link.mediaBlock) seen[dedupKey] = true;
45
+ var landing = link.dataset.mediaPoint ? canvasMediaTarget(target.el, target.record.id, link.dataset.mediaPoint) : null;
46
+ var to;
47
+ if (landing) {
48
+ var input = document.createElement('span'); input.className = 'hbar incoming-anchor';
49
+ input.style.top = (canvasLocalPoint(svg, landing.x, landing.y).y - target.bounds.top - 10) + 'px';
50
+ input.dataset.mediaPoint = link.dataset.mediaPoint; input.dataset.sourceId = source.record.id; input.dataset.edge = target.record.id;
51
+ target.el.append(input); canvasMediaStem(input, landing, true); to = canvasPort(svg, input);
52
+ } else if (canvasHasTargetSpec(link.dataset.mediaPoint)) return;
44
53
  if (link.mediaBlock) {
45
54
  var point = canvasMediaSource(link, source.el);
46
55
  if (!point) return;
47
- var landing = canvasMediaTarget(target.el, target.record.id, link.dataset.mediaPoint), to;
48
- if (landing) {
49
- var input = document.createElement('span'); input.className = 'hbar incoming-anchor';
50
- input.style.top = (canvasLocalPoint(svg, landing.x, landing.y).y - target.bounds.top - 10) + 'px';
51
- input.dataset.mediaPoint = link.dataset.mediaPoint; input.dataset.sourceId = source.record.id; input.dataset.edge = target.record.id;
52
- target.el.append(input); canvasMediaStem(input, landing, true); to = canvasPort(svg, input);
53
- } else if (link.dataset.mediaPoint.includes(';to:')) return;
54
56
  var origin = canvasLocalPoint(svg, point.x, point.exitY);
55
57
  var port = output(source, origin.y, true);
56
58
  port.dataset.mediaPoint = link.dataset.mediaPoint;
@@ -62,7 +64,7 @@ function canvasDrawMindWires() {
62
64
  }
63
65
  var r = link.getBoundingClientRect(), p = canvasLocalPoint(svg, r.left, r.top + r.height / 2);
64
66
  if (!r.width || !r.height) return;
65
- connect(source, target, canvasPort(svg, output(source, p.y, true)), true, 'relation');
67
+ connect(source, target, canvasPort(svg, output(source, p.y, true)), true, 'relation', link.dataset.mediaPoint || '', to);
66
68
  });
67
69
  var children = Object.keys(nodes).filter(function (key) { return key.slice(0, key.lastIndexOf('.')) === path; });
68
70
  if (!children.length) return;