cladogram 0.6.0-beta.3 → 0.6.0-beta.5

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.
@@ -120,6 +120,229 @@
120
120
  });
121
121
  }
122
122
 
123
+ /* ══ ①-b 富媒体块渲染注册表(SVG 矢量/动画、UI 沙盒预览、可扩展插件入口) ═══ */
124
+
125
+ var CladoBlockRegistry = (function () {
126
+ var handlers = [];
127
+ return {
128
+ register: function (match, renderFn) {
129
+ if (typeof renderFn !== 'function') return;
130
+ handlers.push({ match: match, render: renderFn });
131
+ },
132
+ resolve: function (lang, codeText, ctx) {
133
+ for (var i = handlers.length - 1; i >= 0; i--) {
134
+ var h = handlers[i];
135
+ var ok = typeof h.match === 'function'
136
+ ? h.match(lang, codeText)
137
+ : Array.isArray(h.match)
138
+ ? h.match.indexOf(lang) >= 0
139
+ : h.match === lang;
140
+ if (ok) {
141
+ var out = h.render(codeText, lang, ctx);
142
+ if (out) return out;
143
+ }
144
+ }
145
+ return null;
146
+ },
147
+ list: function () { return handlers.slice(); },
148
+ };
149
+ })();
150
+ window.CladoBlockRegistry = CladoBlockRegistry;
151
+
152
+ var CLADO_SVG_TAGS = new Set(
153
+ 'svg g defs symbol use title desc path circle ellipse rect line polyline polygon text tspan textpath lineargradient radialgradient stop clippath mask pattern marker filter fegaussianblur fedropshadow feoffset femerge femergenode fecolormatrix feblend feflood fecomposite style animate animatetransform animatemotion mpath set'.split(' ')
154
+ );
155
+
156
+ function sanitizeSvgMarkup(raw) {
157
+ var src = String(raw || '').trim();
158
+ if (!src || !/<svg\b/i.test(src)) return null;
159
+ if (!/\bxmlns\s*=/i.test(src)) {
160
+ src = src.replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');
161
+ }
162
+ if (/\bxlink:/i.test(src) && !/\bxmlns:xlink\s*=/i.test(src)) {
163
+ src = src.replace(/<svg\b/i, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
164
+ }
165
+ var svg = null;
166
+ try {
167
+ var parsed = new DOMParser().parseFromString(src, 'image/svg+xml');
168
+ if (
169
+ parsed
170
+ && !parsed.querySelector('parsererror')
171
+ && parsed.documentElement
172
+ && parsed.documentElement.localName === 'svg'
173
+ && parsed.documentElement.namespaceURI === 'http://www.w3.org/2000/svg'
174
+ ) {
175
+ svg = document.importNode(parsed.documentElement, true);
176
+ }
177
+ } catch (e) {}
178
+ if (!svg) {
179
+ var tpl = document.createElement('template');
180
+ tpl.innerHTML = src;
181
+ var found = tpl.content.querySelector('svg');
182
+ if (found) svg = found.cloneNode(true);
183
+ }
184
+ if (!svg) return null;
185
+
186
+ var cleanNode = function (el) {
187
+ var tag = String(el.localName || el.tagName || '').toLowerCase();
188
+ if (!CLADO_SVG_TAGS.has(tag)) {
189
+ el.remove();
190
+ return;
191
+ }
192
+ Array.from(el.attributes || []).forEach(function (attr) {
193
+ var name = String(attr.name || '').toLowerCase();
194
+ var val = String(attr.value || '');
195
+ if (/^on/.test(name)) { el.removeAttribute(attr.name); return; }
196
+ if (name === 'href' || name === 'xlink:href') {
197
+ if (!/^#[a-zA-Z0-9_.:-]+$/.test(val.trim())) el.removeAttribute(attr.name);
198
+ return;
199
+ }
200
+ if (name === 'style' && /(?:javascript:|expression\s*\(|@import|url\s*\(\s*['"]?\s*(?:https?:|data:|javascript:))/i.test(val)) {
201
+ el.removeAttribute(attr.name);
202
+ return;
203
+ }
204
+ if (/javascript:/i.test(val.replace(/[\x00-\x20]/g, ''))) {
205
+ el.removeAttribute(attr.name);
206
+ }
207
+ });
208
+ if (tag === 'style') {
209
+ el.textContent = String(el.textContent || '')
210
+ .replace(/@import[^;]*;?/gi, '')
211
+ .replace(/expression\s*\([^)]*\)/gi, '')
212
+ .replace(/javascript:/gi, '')
213
+ .replace(/-moz-binding\s*:[^;]*;?/gi, '')
214
+ .replace(/url\s*\(\s*['"]?\s*(?:https?:|data:|javascript:)[^)]*\)/gi, '');
215
+ return;
216
+ }
217
+ Array.from(el.children || []).forEach(cleanNode);
218
+ };
219
+ cleanNode(svg);
220
+
221
+ if (!svg.getAttribute('viewBox')) {
222
+ var w = parseFloat(svg.getAttribute('width') || '');
223
+ var h = parseFloat(svg.getAttribute('height') || '');
224
+ if (w > 0 && h > 0) svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
225
+ }
226
+ return svg;
227
+ }
228
+
229
+ var cladoUiFrameSeq = 0;
230
+ var cladoUiFrames = new Map();
231
+ window.addEventListener('message', function (ev) {
232
+ var d = ev.data;
233
+ if (!d || d.type !== 'clado-ui-height' || !d.id) return;
234
+ var fr = cladoUiFrames.get(String(d.id));
235
+ if (!fr || !fr.isConnected) { cladoUiFrames.delete(String(d.id)); return; }
236
+ var nextH = Math.max(180, Math.min(540, Math.ceil(Number(d.height) || 260)));
237
+ if (Math.abs((parseInt(fr.style.height, 10) || 260) - nextH) > 4) {
238
+ fr.style.height = nextH + 'px';
239
+ if (document.body.dataset.mode === 'cards') {
240
+ try { repinPorts(); drawWires(); } catch (e) {}
241
+ }
242
+ }
243
+ });
244
+
245
+ function buildUiSandboxDoc(rawCode, frameId) {
246
+ var src = String(rawCode || '');
247
+ var dark = document.documentElement.dataset.theme === 'dark';
248
+ var baseStyle =
249
+ '<style>'
250
+ + ':root{color-scheme:' + (dark ? 'dark' : 'light') + ';--bg:' + (dark ? '#0f172a' : '#f8fafc') + ';--surface:' + (dark ? '#1e293b' : '#ffffff') + ';--text:' + (dark ? '#f1f5f9' : '#0f172a') + ';--muted:' + (dark ? '#94a3b8' : '#64748b') + ';--border:' + (dark ? 'rgba(148,163,184,.22)' : 'rgba(15,23,42,.10)') + ';--accent:#0ea5e9;}'
251
+ + '*,*::before,*::after{box-sizing:border-box}'
252
+ + 'html,body{margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Noto Sans SC",sans-serif;background:var(--bg);color:var(--text);font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased}'
253
+ + 'body{padding:12px}'
254
+ + 'button,input,select,textarea{font:inherit}'
255
+ + '</style>';
256
+ var resizeHook = frameId
257
+ ? ('\x3cscript>(function(){var id=' + JSON.stringify(frameId) + ';function send(){try{var h=Math.max(document.body?document.body.scrollHeight:0,document.documentElement?document.documentElement.scrollHeight:0);parent.postMessage({type:"clado-ui-height",id:id,height:h},"*");}catch(e){}}window.addEventListener("load",send);if(typeof ResizeObserver==="function"){new ResizeObserver(send).observe(document.documentElement);}setTimeout(send,60);setTimeout(send,240);})();\x3c/script>')
258
+ : '';
259
+ if (/^\s*<!doctype|^\s*<html\b/i.test(src)) {
260
+ if (/<\/head>/i.test(src)) src = src.replace(/<\/head>/i, baseStyle + '</head>');
261
+ if (resizeHook && /<\/body>/i.test(src)) src = src.replace(/<\/body>/i, resizeHook + '</body>');
262
+ else if (resizeHook) src += resizeHook;
263
+ return src;
264
+ }
265
+ return '<!DOCTYPE html><html lang="zh-CN" data-theme="' + (dark ? 'dark' : 'light') + '"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
266
+ + baseStyle + '</head><body>' + src + resizeHook + '</body></html>';
267
+ }
268
+
269
+ function createUiPreviewBlock(rawCode, preEl) {
270
+ var wrap = document.createElement('div');
271
+ wrap.className = 'zoomable zui';
272
+ wrap.dataset.label = 'UI 原型预览';
273
+ wrap.dataset.rawSource = rawCode;
274
+
275
+ var bar = document.createElement('div');
276
+ bar.className = 'zblock-bar';
277
+ bar.innerHTML =
278
+ '<span class="zblock-title">UI 原型预览</span>'
279
+ + '<span class="zblock-actions">'
280
+ + '<button type="button" class="zblock-btn active" data-ui-vp="desktop">桌面</button>'
281
+ + '<button type="button" class="zblock-btn" data-ui-vp="mobile">手机</button>'
282
+ + '<button type="button" class="zblock-btn" data-ui-zoom>放大</button>'
283
+ + '<button type="button" class="zblock-btn" data-ui-mode>代码</button>'
284
+ + '</span>';
285
+
286
+ var stage = document.createElement('div');
287
+ stage.className = 'zui-stage';
288
+ var frameId = 'ui_' + (++cladoUiFrameSeq);
289
+ var iframe = document.createElement('iframe');
290
+ iframe.className = 'zui-frame';
291
+ iframe.setAttribute('sandbox', 'allow-scripts');
292
+ iframe.setAttribute('loading', 'lazy');
293
+ iframe.setAttribute('title', 'UI 原型预览');
294
+ iframe.dataset.uiFrameId = frameId;
295
+ iframe._cladoUiSource = rawCode;
296
+ iframe.srcdoc = buildUiSandboxDoc(rawCode, frameId);
297
+ cladoUiFrames.set(frameId, iframe);
298
+ stage.appendChild(iframe);
299
+
300
+ preEl.classList.add('zui-code');
301
+ wrap.appendChild(bar);
302
+ wrap.appendChild(stage);
303
+ wrap.appendChild(preEl);
304
+ return wrap;
305
+ }
306
+
307
+ function createSvgBlock(rawCode, cleanSvg, preEl) {
308
+ var wrap = document.createElement('div');
309
+ wrap.className = 'zoomable zsvg';
310
+ wrap.dataset.label = 'SVG 矢量图';
311
+ wrap.dataset.rawSource = rawCode;
312
+
313
+ var bar = document.createElement('div');
314
+ bar.className = 'zblock-bar';
315
+ bar.innerHTML =
316
+ '<span class="zblock-title">SVG 矢量图</span>'
317
+ + '<span class="zblock-actions">'
318
+ + '<button type="button" class="zblock-btn" data-svg-zoom>放大</button>'
319
+ + '<button type="button" class="zblock-btn" data-svg-mode>源码</button>'
320
+ + '</span>';
321
+
322
+ var stage = document.createElement('div');
323
+ stage.className = 'zsvg-stage';
324
+ stage.title = '点一下放大';
325
+ stage.appendChild(cleanSvg);
326
+
327
+ preEl.classList.add('zsvg-code');
328
+ wrap.appendChild(bar);
329
+ wrap.appendChild(stage);
330
+ wrap.appendChild(preEl);
331
+ return wrap;
332
+ }
333
+
334
+ CladoBlockRegistry.register('svg', function (rawCode, lang, ctx) {
335
+ var cleanSvg = sanitizeSvgMarkup(rawCode);
336
+ if (!cleanSvg) return null;
337
+ if (window.hljs && ctx.code) { try { hljs.highlightElement(ctx.code); } catch (e) {} }
338
+ return createSvgBlock(rawCode, cleanSvg, ctx.pre);
339
+ });
340
+
341
+ CladoBlockRegistry.register(['ui', 'html-preview'], function (rawCode, lang, ctx) {
342
+ if (window.hljs && ctx.code) { try { hljs.highlightElement(ctx.code); } catch (e) {} }
343
+ return createUiPreviewBlock(rawCode, ctx.pre);
344
+ });
345
+
123
346
  /**
124
347
  * 一段原文 Markdown → 一个 `.markdown-body` 元素。
125
348
  *
@@ -131,12 +354,24 @@
131
354
  box.className = 'markdown-body';
132
355
  if (!md) return box;
133
356
  var template = document.createElement('template'); template.innerHTML = marked.parse(md);
357
+ // 兼容 AI 直接在正文中裸写 <svg>...</svg>(不带 ```svg 围栏)时同样安全清洗并支持放大
358
+ var inlineSvgs = [];
359
+ Array.from(template.content.querySelectorAll('svg')).forEach(function (svgNode) {
360
+ if (svgNode.parentNode && svgNode.parentNode.closest && svgNode.parentNode.closest('svg')) return;
361
+ var rawSvg = svgNode.outerHTML || '';
362
+ var cleaned = sanitizeSvgMarkup(rawSvg);
363
+ if (!cleaned) { svgNode.remove(); return; }
364
+ var ph = document.createElement('div');
365
+ ph.dataset.cladoInlineSvg = String(inlineSvgs.length);
366
+ inlineSvgs.push({ raw: rawSvg, node: cleaned });
367
+ svgNode.parentNode.replaceChild(ph, svgNode);
368
+ });
134
369
  var tags = new Set('a p br hr em strong del code pre blockquote ul ol li table thead tbody tr th td img h1 h2 h3 h4 h5 h6 details summary sub sup kbd span div'.split(' '));
135
370
  Array.from(template.content.querySelectorAll('*')).forEach(function (element) {
136
371
  var tag = element.localName;
137
372
  if (!tags.has(tag)) { element.remove(); return; }
138
373
  Array.from(element.attributes).forEach(function (attribute) {
139
- var name=attribute.name, value=attribute.value, allow=['title','alt','width','height','start','align'].includes(name);
374
+ var name=attribute.name, value=attribute.value, allow=['title','alt','width','height','start','align','data-clado-inline-svg'].includes(name);
140
375
  if (name === 'class' && tag === 'code') allow = /^language-[\w+#.-]+$/.test(value);
141
376
  if (name === 'href' && tag === 'a') allow = !/^[a-z][a-z0-9+.-]*:/i.test(value.replace(/[\x00-\x20]/g,'')) || /^(https?:|mailto:|tel:)/i.test(value);
142
377
  if (name === 'src' && tag === 'img') allow = !/^[a-z][a-z0-9+.-]*:/i.test(value.replace(/[\x00-\x20]/g,'')) || /^(https?:|data:image\/(png|jpeg|gif|webp);base64,)/i.test(value);
@@ -145,6 +380,76 @@
145
380
  });
146
381
  box.appendChild(template.content);
147
382
 
383
+ // 还原裸写 <svg> 为带「放大 / 源码」的 .zoomable.zsvg
384
+ $$('[data-clado-inline-svg]', box).forEach(function (ph) {
385
+ var entry = inlineSvgs[Number(ph.dataset.cladoInlineSvg)];
386
+ if (!entry) { ph.remove(); return; }
387
+ var pre = document.createElement('pre');
388
+ var code = document.createElement('code');
389
+ code.className = 'language-svg';
390
+ code.textContent = entry.raw;
391
+ pre.appendChild(code);
392
+ if (window.hljs) { try { hljs.highlightElement(code); } catch (e) {} }
393
+ var svgBlock = createSvgBlock(entry.raw, entry.node, pre);
394
+ ph.parentNode.replaceChild(svgBlock, ph);
395
+ });
396
+
397
+ // 媒体交付件升级:视频 / 音频 / 可放大普通图片(含 .png/.jpg/.webp/.gif/.svg)
398
+ $$('img[src]', box).forEach(function (img) {
399
+ var src = img.getAttribute('src') || '';
400
+ var alt = (img.getAttribute('alt') || '').trim();
401
+ if (/\.(?:mp4|webm|mov|ogv)(?:[?#].*)?$/i.test(src)) {
402
+ var vw = document.createElement('div');
403
+ vw.className = 'zvideo';
404
+ var video = document.createElement('video');
405
+ video.setAttribute('controls', '');
406
+ video.setAttribute('playsinline', '');
407
+ video.setAttribute('preload', 'metadata');
408
+ video.setAttribute('src', src);
409
+ vw.appendChild(video);
410
+ if (alt) {
411
+ var vcap = document.createElement('div');
412
+ vcap.className = 'zmedia-cap';
413
+ vcap.textContent = alt;
414
+ vw.appendChild(vcap);
415
+ }
416
+ img.parentNode.replaceChild(vw, img);
417
+ return;
418
+ }
419
+ if (/\.(?:mp3|wav|m4a|ogg|flac)(?:[?#].*)?$/i.test(src)) {
420
+ var aw = document.createElement('div');
421
+ aw.className = 'zaudio';
422
+ if (alt) {
423
+ var acap = document.createElement('div');
424
+ acap.className = 'zmedia-cap';
425
+ acap.textContent = alt;
426
+ aw.appendChild(acap);
427
+ }
428
+ var audio = document.createElement('audio');
429
+ audio.setAttribute('controls', '');
430
+ audio.setAttribute('preload', 'metadata');
431
+ audio.setAttribute('src', src);
432
+ aw.appendChild(audio);
433
+ img.parentNode.replaceChild(aw, img);
434
+ return;
435
+ }
436
+ // 普通图片同样包进 .zoomable.zimg,点击即弹出放大镜全屏缩放查看
437
+ if (!img.closest('.zoomable')) {
438
+ var iw = document.createElement('div');
439
+ iw.className = 'zoomable zimg';
440
+ iw.dataset.label = alt || '图片';
441
+ iw.title = '点一下放大';
442
+ img.parentNode.insertBefore(iw, img);
443
+ iw.appendChild(img);
444
+ if (alt) {
445
+ var icap = document.createElement('div');
446
+ icap.className = 'zmedia-cap';
447
+ icap.textContent = alt;
448
+ iw.appendChild(icap);
449
+ }
450
+ }
451
+ });
452
+
148
453
  // 表格:左右到顶、列多了自己左右滑、点一下能放大
149
454
  $$('table', box).forEach(function (t) {
150
455
  var shell = document.createElement('div');
@@ -158,11 +463,12 @@
158
463
  shell.appendChild(sc);
159
464
  });
160
465
 
161
- // 代码:先把 mermaid 挑出来(它交给 mermaid 渲染),其余交给 hljs 上色,都点得开
466
+ // 代码:依次经过 mermaid / CladoBlockRegistry(svg、ui、扩展块)/ hljs 代码块
162
467
  $$('pre > code', box).forEach(function (code) {
163
468
  var pre = code.parentNode;
164
469
  var m = /(?:^|\s)language-([\w+#.-]+)/.exec(code.className || '');
165
470
  var lang = m ? m[1].toLowerCase() : '';
471
+ var rawCode = code.textContent || '';
166
472
  if (lang === 'mermaid') {
167
473
  var wrap = document.createElement('div');
168
474
  wrap.className = 'zoomable';
@@ -170,18 +476,41 @@
170
476
  wrap.title = '点一下放大';
171
477
  var d = document.createElement('div');
172
478
  d.className = 'mermaid';
173
- d.dataset.src = code.textContent; // 浏览器已经把实体解回来了
479
+ d.dataset.src = rawCode; // 浏览器已经把实体解回来了
174
480
  wrap.appendChild(d);
175
481
  pre.parentNode.replaceChild(wrap, pre);
176
482
  return;
177
483
  }
484
+ var effectiveLang = (lang === 'html' && /^\s*<!--\s*(?:preview|ui)\s*-->/i.test(rawCode)) ? 'ui' : lang;
485
+ var origParent = pre.parentNode;
486
+ var origNext = pre.nextSibling;
487
+ var customBlock = CladoBlockRegistry.resolve(effectiveLang, rawCode, { pre: pre, code: code });
488
+ if (customBlock) {
489
+ if (origParent) {
490
+ origParent.insertBefore(customBlock, origNext);
491
+ if (pre.parentNode === origParent) origParent.removeChild(pre);
492
+ }
493
+ return;
494
+ }
178
495
  if (window.hljs) { try { hljs.highlightElement(code); } catch (e) { /* 高亮挂了也得能看 */ } }
179
496
  var z = document.createElement('div');
180
497
  z.className = 'zoomable zcode';
181
498
  z.dataset.label = (lang || '代码') + ' 代码';
182
499
  z.title = '点一下放大';
500
+ if (lang === 'html') {
501
+ z.dataset.lang = 'html';
502
+ z.dataset.rawSource = rawCode;
503
+ }
183
504
  pre.parentNode.insertBefore(z, pre);
184
505
  z.appendChild(pre);
506
+ if (lang === 'html') {
507
+ var prevBtn = document.createElement('button');
508
+ prevBtn.type = 'button';
509
+ prevBtn.className = 'zcode-preview-btn';
510
+ prevBtn.textContent = '预览';
511
+ prevBtn.title = '在隔离沙盒中实时预览此 HTML';
512
+ z.appendChild(prevBtn);
513
+ }
185
514
  });
186
515
 
187
516
  $$('pre code', box).forEach(linkifyCode);
@@ -1311,9 +1640,11 @@
1311
1640
  function lensFit() {
1312
1641
  var st = $('#lensStage').getBoundingClientRect(), inn = $('#lensInner');
1313
1642
  var w = inn.offsetWidth, h = inn.offsetHeight;
1643
+ if (!w || !h || !st.width || !st.height) return;
1314
1644
  // 一行代码也撑到 400% 就太夸张了,留个上限
1315
1645
  var cap = Number(inn.dataset.cap || 4);
1316
- ls = Math.min(cap, Math.min((st.width - 90) / w, (st.height - 140) / h));
1646
+ var fitScale = Math.min((st.width - 90) / w, (st.height - 140) / h);
1647
+ ls = Math.max(0.2, Math.min(cap, isFinite(fitScale) && fitScale > 0 ? fitScale : 1));
1317
1648
  lx = (st.width - w * ls) / 2; ly = (st.height - h * ls) / 2;
1318
1649
  lensApply();
1319
1650
  }
@@ -1322,15 +1653,33 @@
1322
1653
  lensSeq++;
1323
1654
  var inn = $('#lensInner');
1324
1655
  inn.innerHTML = kind ? '<div class="markdown-body">' + html + '</div>' : html;
1325
- if (kind) { inn.dataset.cap = kind === 'code' ? '2.2' : '3'; inn.dataset.kind = kind; }
1326
- else { delete inn.dataset.cap; delete inn.dataset.kind; }
1656
+ if (kind) {
1657
+ inn.dataset.cap = kind === 'code' ? '2.2' : kind === 'ui' ? '1.5' : '3';
1658
+ inn.dataset.kind = kind;
1659
+ } else {
1660
+ delete inn.dataset.cap; delete inn.dataset.kind;
1661
+ }
1327
1662
  $$('svg', inn).forEach(function (s) {
1328
1663
  var vb = s.viewBox && s.viewBox.baseVal;
1664
+ var vbW = (vb && vb.width > 0) ? vb.width : 0;
1665
+ var vbH = (vb && vb.height > 0) ? vb.height : 0;
1666
+ if (!vbW || !vbH) {
1667
+ var vbAttr = String(s.getAttribute('viewBox') || '').trim().split(/[\s,]+/);
1668
+ if (vbAttr.length === 4) {
1669
+ vbW = parseFloat(vbAttr[2]) || vbW;
1670
+ vbH = parseFloat(vbAttr[3]) || vbH;
1671
+ }
1672
+ }
1673
+ var targetW = vbW || 640;
1674
+ var targetH = vbH || Math.round(targetW * 0.625);
1329
1675
  s.removeAttribute('width'); s.removeAttribute('height');
1330
- s.style.width = ((vb && vb.width) || 640) + 'px';
1331
- s.style.height = 'auto';
1676
+ s.style.width = targetW + 'px';
1677
+ s.style.height = targetH + 'px';
1678
+ });
1679
+ $$('img', inn).forEach(function (i) {
1680
+ i.style.maxWidth = 'none';
1681
+ if (!i.complete) i.addEventListener('load', function () { requestAnimationFrame(lensFit); }, { once: true });
1332
1682
  });
1333
- $$('img', inn).forEach(function (i) { i.style.maxWidth = 'none'; });
1334
1683
  $('#lensLabel').textContent = label || '图';
1335
1684
  if (!$('#lens').classList.contains('open')) {
1336
1685
  $('#lens').classList.add('open');
@@ -1359,8 +1708,96 @@
1359
1708
  var st = $('#lensStage');
1360
1709
  var pointer = null, dragged = false, sx = 0, sy = 0, ox = 0, oy = 0;
1361
1710
  document.addEventListener('click', function (e) {
1711
+ // 1. 富媒体块工具栏按钮统一委托(兼容卡片/脑图/文档与克隆链路弹窗)
1712
+ var svgZoomBtn = e.target.closest('[data-svg-zoom]');
1713
+ if (svgZoomBtn) {
1714
+ e.stopPropagation();
1715
+ var svgWrap = svgZoomBtn.closest('.zsvg');
1716
+ var svgNode = svgWrap && $('.zsvg-stage svg', svgWrap);
1717
+ if (svgNode) openLens(svgNode.outerHTML, svgWrap.dataset.label || 'SVG 矢量图', 'media');
1718
+ return;
1719
+ }
1720
+ var svgModeBtn = e.target.closest('[data-svg-mode]');
1721
+ if (svgModeBtn) {
1722
+ e.stopPropagation();
1723
+ var svgW = svgModeBtn.closest('.zsvg');
1724
+ if (!svgW) return;
1725
+ var showSvgCode = svgW.classList.toggle('is-code');
1726
+ svgModeBtn.textContent = showSvgCode ? '视图' : '源码';
1727
+ svgModeBtn.classList.toggle('active', showSvgCode);
1728
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (err) {} }
1729
+ return;
1730
+ }
1731
+ var uiVpBtn = e.target.closest('[data-ui-vp]');
1732
+ if (uiVpBtn) {
1733
+ e.stopPropagation();
1734
+ var uiW = uiVpBtn.closest('.zui');
1735
+ if (!uiW) return;
1736
+ var isMob = uiVpBtn.dataset.uiVp === 'mobile';
1737
+ uiW.classList.toggle('is-mobile', isMob);
1738
+ $$('[data-ui-vp]', uiW).forEach(function (b) { b.classList.toggle('active', b === uiVpBtn); });
1739
+ return;
1740
+ }
1741
+ var uiModeBtn = e.target.closest('[data-ui-mode]');
1742
+ if (uiModeBtn) {
1743
+ e.stopPropagation();
1744
+ var uiM = uiModeBtn.closest('.zui');
1745
+ if (!uiM) return;
1746
+ var showUiCode = uiM.classList.toggle('is-code');
1747
+ uiModeBtn.textContent = showUiCode ? '预览' : '代码';
1748
+ uiModeBtn.classList.toggle('active', showUiCode);
1749
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (err) {} }
1750
+ return;
1751
+ }
1752
+ var uiZoomBtn = e.target.closest('[data-ui-zoom]');
1753
+ if (uiZoomBtn) {
1754
+ e.stopPropagation();
1755
+ var uiZ = uiZoomBtn.closest('.zui');
1756
+ var uiRaw = uiZ ? (uiZ.dataset.rawSource || ($('pre code', uiZ)?.textContent || '')) : '';
1757
+ var lensHtml = '<iframe class="zui-lens-frame" sandbox="allow-scripts" title="UI 原型全屏预览"></iframe>';
1758
+ openLens(lensHtml, 'UI 原型预览', 'ui');
1759
+ var lensFr = $('#lensInner .zui-lens-frame');
1760
+ if (lensFr) lensFr.srcdoc = buildUiSandboxDoc(uiRaw, '');
1761
+ return;
1762
+ }
1763
+ var htmlPrevBtn = e.target.closest('.zcode-preview-btn');
1764
+ if (htmlPrevBtn) {
1765
+ e.stopPropagation();
1766
+ var zc = htmlPrevBtn.closest('.zcode');
1767
+ var preEl = zc && $('pre', zc);
1768
+ if (!zc || !preEl) return;
1769
+ var rawHtml = zc.dataset.rawSource || ($('code', preEl)?.textContent || '');
1770
+ var uiBlock = createUiPreviewBlock(rawHtml, preEl);
1771
+ if (zc.parentNode) zc.parentNode.replaceChild(uiBlock, zc);
1772
+ if (document.body.dataset.mode === 'cards') { try { repinPorts(); drawWires(); } catch (err) {} }
1773
+ return;
1774
+ }
1775
+
1776
+ // 2. 点击任意 .zoomable 内容区(图片 / SVG / Mermaid / 代码 / 表格)直接弹出放大镜
1362
1777
  var z = e.target.closest('.zoomable');
1363
- if (z && !e.target.closest('a.edge')) {
1778
+ if (z && !e.target.closest('a.edge,.zblock-bar,.zblock-btn,.zcode-preview-btn,iframe,video,audio')) {
1779
+ if (z.classList.contains('zui')) {
1780
+ if (z.classList.contains('is-code')) {
1781
+ var uiCode = $('pre', z);
1782
+ if (uiCode) openLens(uiCode.outerHTML, 'UI 源码', 'code');
1783
+ } else {
1784
+ var uiSrc = z.dataset.rawSource || ($('pre code', z)?.textContent || '');
1785
+ openLens('<iframe class="zui-lens-frame" sandbox="allow-scripts" title="UI 原型全屏预览"></iframe>', 'UI 原型预览', 'ui');
1786
+ var lFr = $('#lensInner .zui-lens-frame');
1787
+ if (lFr) lFr.srcdoc = buildUiSandboxDoc(uiSrc, '');
1788
+ }
1789
+ return;
1790
+ }
1791
+ if (z.classList.contains('zsvg')) {
1792
+ if (z.classList.contains('is-code')) {
1793
+ var svgCode = $('pre', z);
1794
+ if (svgCode) openLens(svgCode.outerHTML, 'SVG 源码', 'code');
1795
+ } else {
1796
+ var svgEl = $('.zsvg-stage svg', z);
1797
+ if (svgEl) openLens(svgEl.outerHTML, z.dataset.label || 'SVG 矢量图', 'media');
1798
+ }
1799
+ return;
1800
+ }
1364
1801
  var media = $('svg,img', z), code = $('pre', z), tbl = $('table', z);
1365
1802
  if (media) openLens(media.outerHTML, z.dataset.label, 'media');
1366
1803
  else if (code) openLens(code.outerHTML, z.dataset.label, 'code');
@@ -1390,7 +1827,7 @@
1390
1827
  st.addEventListener('pointerdown', function (e) {
1391
1828
  if (pointer !== null) return;
1392
1829
  dragged = false;
1393
- if (e.button !== 0 || e.target.closest('pre,table,svg text,svg foreignObject,a')) return;
1830
+ if (e.button !== 0 || e.target.closest('pre,table,svg text,svg foreignObject,a,iframe')) return;
1394
1831
  pointer = e.pointerId;
1395
1832
  sx = e.clientX; sy = e.clientY; ox = lx; oy = ly;
1396
1833
  });
@@ -1478,6 +1915,11 @@
1478
1915
  function setTheme(t, save) {
1479
1916
  document.documentElement.dataset.theme = t;
1480
1917
  if (save !== false) { try { localStorage.setItem('clado-theme', t); } catch (e) {} }
1918
+ $$('.zui-frame').forEach(function (fr) {
1919
+ if (fr._cladoUiSource != null) {
1920
+ fr.srcdoc = buildUiSandboxDoc(fr._cladoUiSource, fr.dataset.uiFrameId || '');
1921
+ }
1922
+ });
1481
1923
  renderMermaid(true).then(afterMedia);
1482
1924
  document.dispatchEvent(new CustomEvent('clado:view-state'));
1483
1925
  }
@@ -17,6 +17,7 @@ import {
17
17
  deletePiSkill,
18
18
  deleteProviderConfig,
19
19
  deleteRole,
20
+ ensureCladoPlatformDocs,
20
21
  importPiMcpJson,
21
22
  inspectPiEcosystem,
22
23
  installPiPackage,
@@ -26,9 +27,11 @@ import {
26
27
  readCanvasComponentsConfig,
27
28
  readRuntimeSettings,
28
29
  removePiPackage,
30
+ resetCladoPlatformDocs,
29
31
  resolvePiAgentDir,
30
32
  resolveRole,
31
33
  saveAgentsMemory,
34
+ saveCladoPlatformContext,
32
35
  savePiMcpServer,
33
36
  savePiPrompt,
34
37
  savePiSkill,
@@ -171,6 +174,7 @@ export function createAgentHandler({
171
174
  const runtimeSettings = readRuntimeSettings(rt.workspace, agentDir, modelsInfo.activeContextWindow);
172
175
  const roles = listRoles(agentDir);
173
176
  const memory = readAgentsMemory(rt.workspace);
177
+ const platformDocs = ensureCladoPlatformDocs(agentDir);
174
178
  const canvasComponents = readCanvasComponentsConfig(agentDir);
175
179
  const sessions = listSessions(rt.stateDir, { includeArchived: true, agentDir });
176
180
 
@@ -193,6 +197,7 @@ export function createAgentHandler({
193
197
  canvasComponents,
194
198
  workspacePlugins: rt.pluginDescriptors,
195
199
  memory,
200
+ platformDocs,
196
201
  sessions,
197
202
  };
198
203
  }
@@ -373,6 +378,16 @@ export function createAgentHandler({
373
378
  sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
374
379
  return;
375
380
  }
381
+ if (action === 'save_platform_context') {
382
+ const result = saveCladoPlatformContext(body.content, agentDir);
383
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
384
+ return;
385
+ }
386
+ if (action === 'reset_platform_context') {
387
+ const result = resetCladoPlatformDocs(agentDir);
388
+ sendJson(res, 200, { ...result, meta: await buildFullMeta(targetWorkspace) });
389
+ return;
390
+ }
376
391
  if (action === 'toggle_canvas_component') {
377
392
  const canvasComponents = toggleCanvasComponent(body.id, body.enabled, agentDir);
378
393
  sendJson(res, 200, { ok: true, canvasComponents, meta: await buildFullMeta(targetWorkspace) });
@@ -82,13 +82,13 @@
82
82
  return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path)+workspace);
83
83
  }
84
84
  function rewriteDocumentLinks() {
85
- document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
86
- const src=img.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
87
- try { const url=resourceUrl(src);if(url){img.dataset.resource='1';img.src=url;} } catch {}
85
+ document.querySelectorAll('img[src]:not([data-resource]),video[src]:not([data-resource]),audio[src]:not([data-resource])').forEach(el=>{
86
+ const src=el.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
87
+ try { const url=resourceUrl(src);if(url){el.dataset.resource='1';el.src=url;} } catch {}
88
88
  });
89
89
  document.querySelectorAll('a[href]:not(.edge):not([data-resource])').forEach(a=>{
90
90
  const href=a.getAttribute('href');if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#)/i.test(href) || /\.mdc?(?:#|$)/i.test(href))return;
91
- if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json)(?:#|$)/i.test(href))return;
91
+ if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json|mp4|webm|mov|ogv|mp3|wav|m4a|ogg|flac)(?:#|$)/i.test(href))return;
92
92
  try { const url=resourceUrl(href);if(url){a.dataset.resource='1';a.href=url;} } catch {}
93
93
  });
94
94
  document.querySelectorAll('a[href]:not(.edge):not([data-canvas-file])').forEach(a => {
@@ -662,6 +662,14 @@
662
662
  runtime.highlightActivity?.(event.data);
663
663
  return;
664
664
  }
665
+ if (event.data?.type === 'clado-workspace:presence') {
666
+ runtime.setCardPresence?.(event.data.presence);
667
+ return;
668
+ }
669
+ if (event.data?.type === 'clado-workspace:presence-config') {
670
+ runtime.setPresenceConfig?.(event.data.config);
671
+ return;
672
+ }
665
673
  if (event.data?.type === 'clado-workspace:live-diff') {
666
674
  runtime.playLiveDiff?.(event.data.prevDoc, event.data.touch, event.data.follow);
667
675
  return;