cladogram 0.5.4 → 0.5.5-beta.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.
@@ -529,35 +529,59 @@
529
529
  DOC.cards.forEach(function (c) { if (!indeg[c.id]) sink(c.id); });
530
530
  // 一个根都没有(整张图全是环)时,随便挑一张起头,剩下的照样能排开
531
531
  DOC.cards.forEach(function (c) { if (!walked[c.id]) sink(c.id); });
532
- var kids = {}, focused = typeof canvasVisibleCards !== 'undefined' && canvasVisibleCards;
532
+ var kids = {}, incoming = {}, focused = typeof canvasVisibleCards !== 'undefined' && canvasVisibleCards;
533
533
  DOC.edges.forEach(function (e) {
534
534
  if (!seen[e[0]] || !seen[e[1]] || (!focused && !openEdge[edgeKey(e[0], e[1])])) return;
535
- (kids[e[0]] = kids[e[0]] || []).push(e[1]);
536
- });
537
- /*
538
- * ★ 同一列里的上下顺序,按**边出现的先后**排,不按卡片在文档里的先后。
539
- * 原来直接 `vis.forEach` 走卡片顺序:`订单明细表` 那一段写在文档最前面,
540
- * 它就先被塞进第 2 列、排在最上面 —— 可它明明是从「明细」那一节连出去的,
541
- * 应该排在 `用户表`、`商品表` 后面。用户看到的「订单明细表跑到最上面去了」
542
- * 就是这个。改成先按 DOC.edges 的顺序收,剩下的(没有入边的根)再补。
543
- */
544
- var cols = {}, inCol = {};
545
- DOC.edges.forEach(function (e) {
546
- if (!seen[e[0]] || !seen[e[1]] || (!focused && !openEdge[edgeKey(e[0], e[1])]) || inCol[e[1]]) return;
547
- inCol[e[1]] = 1;
548
- (cols[depth[e[1]]] = cols[depth[e[1]]] || []).push(e[1]);
535
+ var list = kids[e[0]] || (kids[e[0]] = []);
536
+ if (list.indexOf(e[1]) < 0) list.push(e[1]);
537
+ if (depth[e[0]] < depth[e[1]]) {
538
+ var parents = incoming[e[1]] || (incoming[e[1]] = []);
539
+ if (parents.indexOf(e[0]) < 0) parents.push(e[0]);
540
+ }
549
541
  });
550
- vis.forEach(function (id) {
551
- if (inCol[id]) return;
542
+ // 按列自左向右排定列内初始顺序:遵循左侧已排好父卡的上下顺序及父卡内首次引用顺序,避免深层列上下颠倒。
543
+ var cols = {}, docIndex = {};
544
+ vis.forEach(function (id, index) {
545
+ docIndex[id] = index;
552
546
  (cols[depth[id]] = cols[depth[id]] || []).push(id);
553
547
  });
554
- pos = {};
555
548
  var keys = Object.keys(cols).map(Number).sort(function (a, b) { return a - b; });
549
+ var colRank = {};
550
+ keys.forEach(function (d, ki) {
551
+ if (ki > 0) {
552
+ var meta = {};
553
+ cols[d].forEach(function (id) {
554
+ var parents = (incoming[id] || []).filter(function (p) { return p in colRank; });
555
+ if (parents.length) {
556
+ var sum = 0, minRank = Infinity, minRef = Infinity;
557
+ parents.forEach(function (p) {
558
+ sum += colRank[p];
559
+ if (colRank[p] < minRank) {
560
+ minRank = colRank[p];
561
+ minRef = (kids[p] || []).indexOf(id);
562
+ }
563
+ });
564
+ meta[id] = { hasParent: 1, avg: sum / parents.length, minRank: minRank, minRef: minRef < 0 ? 1e9 : minRef };
565
+ } else {
566
+ meta[id] = { hasParent: 0, avg: 1e9, minRank: 1e9, minRef: 1e9 };
567
+ }
568
+ });
569
+ cols[d].sort(function (a, b) {
570
+ var ma = meta[a], mb = meta[b];
571
+ if (ma.hasParent !== mb.hasParent) return mb.hasParent - ma.hasParent;
572
+ if (ma.avg !== mb.avg) return ma.avg - mb.avg;
573
+ if (ma.minRank !== mb.minRank) return ma.minRank - mb.minRank;
574
+ if (ma.minRef !== mb.minRef) return ma.minRef - mb.minRef;
575
+ return docIndex[a] - docIndex[b];
576
+ });
577
+ }
578
+ cols[d].forEach(function (id, idx) { colRank[id] = idx; });
579
+ });
580
+ pos = {};
556
581
  /*
557
582
  * ★ 每一列的 x 得按**左边那一列最宽的那张卡**让位。
558
583
  * 卡片会被 Mermaid 图撑宽(最宽到 1500px),原来写死 `PAD + d * (W + COL)` ——
559
- * 一张被撑到 1200 的卡就直接压在右边那一列的卡身上了。这就是「缩放的时候
560
- * 卡片会重叠」的来源(不是只算了一层,是压根没算宽度)。
584
+ * 一张被撑到 1200 的卡就直接压在右边那一列的卡身上了。
561
585
  */
562
586
  var colX = {}, cx = PAD, naturalY = {};
563
587
  keys.forEach(function (d) {
@@ -566,50 +590,83 @@
566
590
  cols[d].forEach(function (id) { wmax = Math.max(wmax, render.card[id].offsetWidth || W); });
567
591
  cx += wmax + COL;
568
592
  });
593
+ // 统一按左上角蓝色竖条中心(y + 47px)对齐:
594
+ // 因为每张卡的蓝色竖条距离卡片顶部都是固定偏移,父卡蓝条对齐子卡蓝条中点即 parent.y = (minChildY + maxChildY) / 2。
595
+ // 无子卡的同列兄弟不再写死到 PAD,而是就近紧贴相邻已定位兄弟,避免长分支把上方叶卡甩飞。
569
596
  keys.slice().reverse().forEach(function (d) {
570
597
  var col = cols[d].map(function (id) {
571
598
  var h = render.card[id].offsetHeight;
572
- var ks = kids[id] || [], top = Infinity, bot = -Infinity;
599
+ var ks = kids[id] || [], topY = Infinity, botY = -Infinity;
573
600
  ks.forEach(function (q) {
574
- if (!pos[q]) return;
575
- top = Math.min(top, pos[q].y);
576
- bot = Math.max(bot, pos[q].y + render.card[q].offsetHeight);
601
+ if (!pos[q] || depth[q] <= d) return;
602
+ topY = Math.min(topY, pos[q].y);
603
+ botY = Math.max(botY, pos[q].y);
577
604
  });
578
- var want = isFinite(top) ? (top + bot) / 2 - h / 2 : PAD;
579
- naturalY[id] = want;
580
- return { id: id, h: h, want: want };
605
+ var hasWant = isFinite(topY);
606
+ var want = hasWant ? (topY + botY) / 2 : null;
607
+ if (hasWant) naturalY[id] = want;
608
+ return { id: id, h: h, hasWant: hasWant, want: want, y: 0 };
581
609
  });
582
- // 后代的位置只影响纵向对齐。同一父卡的子卡始终按正文首次引用的顺序排列。
583
- var prev = null;
610
+ var firstAnchored = col.findIndex(function (it) { return it.hasWant; });
611
+ if (firstAnchored < 0) {
612
+ var cursor = PAD;
613
+ col.forEach(function (it) {
614
+ it.y = cursor;
615
+ cursor += it.h + ROW;
616
+ });
617
+ } else {
618
+ // 先为有子卡的节点从上到下分配不重叠位置(为中间夹着的无子卡兄弟预留足够高度),
619
+ // 再把首段无子卡兄弟贴紧在首个有子卡节点上方、中间与尾段无子卡兄弟紧贴在上方兄弟下方。
620
+ var prevAnchor = -1;
621
+ for (var i = 0; i < col.length; i++) {
622
+ if (!col[i].hasWant) continue;
623
+ var y = col[i].want;
624
+ if (prevAnchor >= 0) {
625
+ var minY = col[prevAnchor].y + col[prevAnchor].h + ROW;
626
+ for (var m = prevAnchor + 1; m < i; m++) minY += col[m].h + ROW;
627
+ if (y < minY) y = minY;
628
+ }
629
+ col[i].y = y;
630
+ if (prevAnchor >= 0) {
631
+ var cur = col[prevAnchor].y + col[prevAnchor].h + ROW;
632
+ for (var m2 = prevAnchor + 1; m2 < i; m2++) {
633
+ col[m2].y = cur;
634
+ cur += col[m2].h + ROW;
635
+ }
636
+ }
637
+ prevAnchor = i;
638
+ }
639
+ // 首段无子卡节点向上紧贴首个已定位兄弟,不再飞到顶部 PAD。
640
+ for (var k = firstAnchored - 1; k >= 0; k--) {
641
+ col[k].y = col[k + 1].y - col[k].h - ROW;
642
+ }
643
+ // 尾段无子卡节点向下紧贴最后一个已定位兄弟。
644
+ for (var t = prevAnchor + 1; t < col.length; t++) {
645
+ col[t].y = col[t - 1].y + col[t - 1].h + ROW;
646
+ }
647
+ }
584
648
  col.forEach(function (it) {
585
- // 先不夹到 PAD:父亲比儿子们高一大截时「居中」是要往负数走的,
586
- // 夹住就退化成「跟第一个儿子齐平」——正好是这次要修的那个毛病。
587
- // 越界统一留到最后整体下移。
588
- var y = it.want;
589
- if (prev && y < prev.y + prev.h + ROW) y = prev.y + prev.h + ROW;
590
- pos[it.id] = { x: colX[d], y: y };
591
- prev = { y: y, h: it.h };
649
+ pos[it.id] = { x: colX[d], y: it.y };
592
650
  });
593
651
  });
594
- // 左列卡片互相让位后的位移要传给右列分支;共享子卡取所有父卡位移的平均值。
652
+ // 左列卡片互相让位后的位移传给右列分支,保序且用同列等距分组消解碰撞。
595
653
  if (!anchor || !prevPos) {
596
- var incoming = {};
597
- Object.keys(kids).forEach(function (parent) {
598
- kids[parent].forEach(function (child) {
599
- if (depth[parent] < depth[child]) (incoming[child] || (incoming[child] = [])).push(parent);
600
- });
601
- });
602
654
  keys.slice(1).forEach(function (d) {
603
- var parentY = {}, desiredY = {};
604
- cols[d].forEach(function (id) {
655
+ var parentY = {}, desiredY = {}, colOrder = {};
656
+ cols[d].forEach(function (id, idx) {
657
+ colOrder[id] = idx;
605
658
  var parents = incoming[id] || [];
606
659
  parentY[id] = parents.length ? parents.reduce(function (sum, parent) { return sum + pos[parent].y; }, 0) / parents.length : pos[id].y;
607
- var shift = parents.length ? parents.reduce(function (sum, parent) { return sum + pos[parent].y - naturalY[parent]; }, 0) / parents.length : 0;
660
+ var shifted = parents.filter(function (parent) { return naturalY[parent] !== undefined; });
661
+ var shift = shifted.length ? shifted.reduce(function (sum, parent) { return sum + (pos[parent].y - naturalY[parent]); }, 0) / shifted.length : 0;
608
662
  desiredY[id] = pos[id].y + shift;
609
663
  });
610
- // 同列先按父卡顺序分组。同组保留引用顺序,相撞时把间距分摊给两边。
664
+ var ordered = cols[d].slice().sort(function (a, b) {
665
+ if (parentY[a] !== parentY[b]) return parentY[a] - parentY[b];
666
+ return colOrder[a] - colOrder[b];
667
+ });
611
668
  var groups = [], offset = 0;
612
- cols[d].slice().sort(function (a, b) { return parentY[a] - parentY[b]; }).forEach(function (id) {
669
+ ordered.forEach(function (id) {
613
670
  groups.push({ cards: [{ id: id, offset: offset }], y: desiredY[id] - offset });
614
671
  offset += render.card[id].offsetHeight + ROW;
615
672
  while (groups.length > 1 && groups[groups.length - 2].y > groups[groups.length - 1].y) {
@@ -625,9 +682,8 @@
625
682
  }
626
683
  /*
627
684
  * ★ 收起 / 展开只动「被点的那张 + 它的**所有后代**」,别的卡一个像素都不挪。
628
- * 做法:先照常全局摆一遍,然后把不在 moved 里的卡片 y 换回快照里的旧值,
629
- * 最后按列把 moved 的卡片往下推开,避开这些钉住的卡。
630
- * (用户的原话:「除了当前节点以及它自己的儿子,其他的节点位置都不动」。)
685
+ * 避让同列固定卡时尊重父卡上下顺序:上方父卡的子卡优先往上让位,下方父卡的子卡优先往下让位,
686
+ * 避免上面的子卡被推到下面调用卡片的下方错位。
631
687
  */
632
688
  var moved = null;
633
689
  if (anchor && prevPos) {
@@ -639,7 +695,7 @@
639
695
  moved[walkId] = 1;
640
696
  (kids[walkId] || []).forEach(function (q) { stack.push(q); });
641
697
  }
642
- // 钉回父卡时整支一起平移,保留可见孩子围绕父卡的居中关系。
698
+ // 钉回父卡时整支一起平移,保留可见孩子围绕父卡蓝条的对齐关系。
643
699
  if (pos[anchor] && prevPos[anchor]) {
644
700
  var dx = prevPos[anchor].x - pos[anchor].x, dy = prevPos[anchor].y - pos[anchor].y;
645
701
  Object.keys(moved).forEach(function (id) {
@@ -650,23 +706,25 @@
650
706
  if (pos[c.id] && !moved[c.id] && prevPos[c.id]) pos[c.id].y = prevPos[c.id].y;
651
707
  if (pos[c.id] && !moved[c.id] && prevPos[c.id]) pos[c.id].x = prevPos[c.id].x;
652
708
  });
653
- /*
654
- * ★ 被点的这张**自己也不许动**。用户原话:「我点的这个标题的这个卡片,它能不动吗?」
655
- * 它虽然在 moved 里(要跟着走一遍好收放后代),但位置得钉死在原地 ——
656
- * 手指点哪儿,那张卡就待在哪儿,只有它右边那一串后代会重摆。
657
- */
658
709
  if (pos[anchor] && prevPos[anchor]) pos[anchor].y = prevPos[anchor].y;
710
+ var anchorY = pos[anchor] ? pos[anchor].y : 0;
659
711
  keys.forEach(function (d) {
660
- var moving = [], pinned = [], blocked = [];
712
+ var moving = [], pinned = [], blocked = [], collidingParents = [];
661
713
  cols[d].forEach(function (id) {
662
714
  if (CARD_PLACEMENTS[id]) pos[id] = Object.assign({}, CARD_PLACEMENTS[id]);
663
715
  (moved[id] && id !== anchor && !CARD_PLACEMENTS[id] ? moving : pinned).push(id);
664
716
  });
665
- // 整组让开固定卡,保持孩子间距;选择离父卡最近的上下空位。
717
+ if (!moving.length) return;
666
718
  moving.forEach(function (id) {
667
719
  pinned.forEach(function (fixed) {
668
- blocked.push({ lo: pos[fixed].y - ROW - pos[id].y - render.card[id].offsetHeight,
669
- hi: pos[fixed].y + render.card[fixed].offsetHeight + ROW - pos[id].y });
720
+ var lo = pos[fixed].y - ROW - pos[id].y - render.card[id].offsetHeight;
721
+ var hi = pos[fixed].y + render.card[fixed].offsetHeight + ROW - pos[id].y;
722
+ blocked.push({ lo: lo, hi: hi });
723
+ if (lo < 0 && hi > 0) {
724
+ var fp = (incoming[fixed] || []).filter(function (p) { return pos[p]; });
725
+ var py = fp.length ? fp.reduce(function (s, p) { return s + pos[p].y; }, 0) / fp.length : pos[fixed].y;
726
+ collidingParents.push(py);
727
+ }
670
728
  });
671
729
  });
672
730
  blocked.sort(function (a, b) { return a.lo - b.lo; });
@@ -677,11 +735,31 @@
677
735
  else intervals.push(range);
678
736
  });
679
737
  var shift = 0;
738
+ var avgPinnedParentY = collidingParents.length
739
+ ? collidingParents.reduce(function (s, y) { return s + y; }, 0) / collidingParents.length
740
+ : null;
680
741
  intervals.forEach(function (range) {
681
- if (range.lo < 0 && range.hi > 0) shift = Math.abs(range.lo) < Math.abs(range.hi) ? range.lo : range.hi;
742
+ if (range.lo < 0 && range.hi > 0) {
743
+ if (avgPinnedParentY !== null && Math.abs(anchorY - avgPinnedParentY) > 1) {
744
+ shift = anchorY < avgPinnedParentY ? range.lo : range.hi;
745
+ } else {
746
+ shift = Math.abs(range.lo) < Math.abs(range.hi) ? range.lo : range.hi;
747
+ }
748
+ }
682
749
  });
683
- // 无限画布允许负坐标,不能把上半组逐张夹到PAD而破坏居中。
684
- moving.forEach(function (id) { pos[id].y += shift; });
750
+ if (shift) {
751
+ // 同列移动组连同其后续列子孙一起平移,保持整支对齐不撕裂。
752
+ var sub = {}, q = moving.slice();
753
+ while (q.length) {
754
+ var cur = q.pop();
755
+ if (sub[cur]) continue;
756
+ sub[cur] = 1;
757
+ (kids[cur] || []).forEach(function (child) {
758
+ if (moved[child] && !CARD_PLACEMENTS[child] && depth[child] > d) q.push(child);
759
+ });
760
+ }
761
+ Object.keys(sub).forEach(function (id) { if (pos[id]) pos[id].y += shift; });
762
+ }
685
763
  });
686
764
  } else {
687
765
  // 整体下移,保证最上面那张卡正好落在 PAD 上(相对关系一个没动)
@@ -690,14 +768,6 @@
690
768
  var shift = isFinite(minY) ? PAD - minY : 0;
691
769
  DOC.cards.forEach(function (c) { if (pos[c.id]) pos[c.id].y += shift; });
692
770
  }
693
- /*
694
- * ★ 最后兜一次底:上面两个分支(整体摆 / 只动那一支)都是**摆的时候**量高度的,
695
- * 而卡片的高度会被异步的东西改(mermaid 渲染、字体加载、图片解码)。
696
- * 实测就是这么重叠的:摆的时候「库存服务」只有 151 高,之后长到 240,
697
- * 同一列下面的「通知服务」就被压住了。
698
- * 这里按**当前实测高度**把每一列从上往下再扫一遍,谁压住谁就往下推。
699
- * 只往下推、不往上提,也不改 x —— 列位置和镜头都不受影响。
700
- */
701
771
  keys.forEach(function (d) {
702
772
  var col = cols[d].map(function (id) { return { id: id, h: render.card[id].offsetHeight }; });
703
773
  col.sort(function (a, b) { return pos[a.id].y - pos[b.id].y; });
@@ -705,8 +775,6 @@
705
775
  col.forEach(function (it) {
706
776
  var y = pos[it.id].y;
707
777
  if (prev && y < prev.y + prev.h + ROW) y = prev.y + prev.h + ROW;
708
- // ★ 只推「这一支」里的卡。钉住的卡一个像素都不许动 ——
709
- // 用户报的「每次点标题,父节点就往下挪一点」就是这里把它推走的。
710
778
  if ((!moved || moved[it.id]) && it.id !== anchor) pos[it.id].y = y;
711
779
  prev = { y: pos[it.id].y, h: it.h };
712
780
  });
@@ -1316,10 +1384,13 @@
1316
1384
  lx = (st.width - w * ls) / 2; ly = (st.height - h * ls) / 2;
1317
1385
  lensApply();
1318
1386
  }
1387
+ var lensSeq = 0;
1319
1388
  function openLens(html, label, kind) {
1389
+ lensSeq++;
1320
1390
  var inn = $('#lensInner');
1321
1391
  inn.innerHTML = kind ? '<div class="markdown-body">' + html + '</div>' : html;
1322
- if (kind) inn.dataset.cap = kind === 'code' ? '2.2' : '3'; else delete inn.dataset.cap;
1392
+ if (kind) { inn.dataset.cap = kind === 'code' ? '2.2' : '3'; inn.dataset.kind = kind; }
1393
+ else { delete inn.dataset.cap; delete inn.dataset.kind; }
1323
1394
  $$('svg', inn).forEach(function (s) {
1324
1395
  var vb = s.viewBox && s.viewBox.baseVal;
1325
1396
  s.removeAttribute('width'); s.removeAttribute('height');
@@ -1336,9 +1407,12 @@
1336
1407
  }
1337
1408
  function closeLens() {
1338
1409
  if (!$('#lens').classList.contains('open')) return;
1410
+ var seq = ++lensSeq;
1339
1411
  $('#lens').classList.remove('open');
1340
- $('#lensInner').innerHTML = '';
1341
1412
  document.dispatchEvent(new CustomEvent('clado:lens-close'));
1413
+ setTimeout(function () {
1414
+ if (seq === lensSeq && !$('#lens').classList.contains('open')) $('#lensInner').innerHTML = '';
1415
+ }, 180);
1342
1416
  }
1343
1417
 
1344
1418
  function flash(id) {
@@ -119,7 +119,7 @@ export function createAgentHandler({
119
119
 
120
120
  async function connect(session) {
121
121
  session.agent = startAgent({
122
- workspace, ...resolveLaunch(), mcpName: mcpName(), emit: event => session.emit?.(event),
122
+ workspace: session.workspace, ...resolveLaunch(), mcpName: mcpName(), emit: event => session.emit?.(event),
123
123
  closed: error => close(session, error),
124
124
  });
125
125
  const { rpc } = session.agent;
@@ -131,13 +131,13 @@ export function createAgentHandler({
131
131
  if (init.protocolVersion !== PROTOCOL_VERSION) throw new Error('当前适配器不支持 Clado 的 ACP 协议版本。');
132
132
  session.hasMcp = !!init.agentCapabilities?.mcpCapabilities?.http;
133
133
  const result = await rpc.request('session/new', {
134
- cwd: workspace,
134
+ cwd: session.workspace,
135
135
  mcpServers: session.hasMcp ? [{ name: mcpName(), type: 'http', url: mcpUrl(), headers: [] }] : [],
136
136
  });
137
137
  session.id = result.sessionId;
138
138
  }
139
139
 
140
- async function handle(req, res) {
140
+ async function handle(req, res, targetWorkspace = workspace) {
141
141
  const host = req.headers.host || '';
142
142
  if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
143
143
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
@@ -161,9 +161,10 @@ export function createAgentHandler({
161
161
  return;
162
162
  }
163
163
  if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
164
+ if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
164
165
  if (!session) {
165
166
  if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
166
- session = { key: input.session };
167
+ session = { key: input.session, workspace: targetWorkspace };
167
168
  sessions.set(input.session, session);
168
169
  }
169
170
  session.running = true;
@@ -186,7 +187,7 @@ export function createAgentHandler({
186
187
  if (!session.agent) await connect(session);
187
188
  if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
188
189
  emit({ type: 'status', text: '正在生成' });
189
- const prompt = promptBlocks(workspace, input);
190
+ const prompt = promptBlocks(session.workspace, input);
190
191
  if (!session.started && session.hasMcp) {
191
192
  prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
192
193
  session.started = true;
@@ -67,7 +67,8 @@
67
67
  const target = new URL(href,'https://clado.local/documents/'+file);
68
68
  if (!target.pathname.startsWith('/documents/')) return null;
69
69
  const path=decodeURIComponent(target.pathname.slice('/documents/'.length));
70
- return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path));
70
+ const workspace = window.__CLADO_WORKSPACE_ID__ ? '&workspace=' + encodeURIComponent(window.__CLADO_WORKSPACE_ID__) : '';
71
+ return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path)+workspace);
71
72
  }
72
73
  function rewriteDocumentLinks() {
73
74
  document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
@@ -1,7 +1,7 @@
1
1
  (() => {
2
- window.CladoCapabilityBridge = () => {
2
+ window.CladoCapabilityBridge = (workspaceId = '') => {
3
3
  const viewId = crypto.randomUUID();
4
- const endpoint = '/library/plugin-bridge?viewId=' + encodeURIComponent(viewId);
4
+ const endpoint = '/library/plugin-bridge?viewId=' + encodeURIComponent(viewId) + (workspaceId ? '&workspace=' + encodeURIComponent(workspaceId) : '');
5
5
  const handlers = new Map();
6
6
  const keyOf = ({ pluginId, mountId }) => JSON.stringify([pluginId, mountId]);
7
7
  let stream, connected = false;
@@ -6,7 +6,7 @@
6
6
  new Set(value).size === value.length && value.every(item => expected.includes(item));
7
7
  const byteLength = value => new TextEncoder().encode(value).length;
8
8
 
9
- window.CladoPluginHost = ({ host, readView, capabilities, isEnabled }) => {
9
+ window.CladoPluginHost = ({ host, readView, capabilities, isEnabled, workspaceId = '' }) => {
10
10
  const viewId = capabilities.viewId;
11
11
  let catalog;
12
12
  const tickets = new Map(), registered = new Set();
@@ -186,7 +186,7 @@
186
186
  event.source.postMessage({ type: 'clado-plugin:port', ticket }, '*', [channel.port2]);
187
187
  }
188
188
  addEventListener('message', accept);
189
- fetch('/library/plugins.json', { cache: 'no-store' }).then(response => {
189
+ fetch('/library/plugins.json' + (workspaceId ? '?workspace=' + encodeURIComponent(workspaceId) : ''), { cache: 'no-store' }).then(response => {
190
190
  if (!response.ok) throw new Error('插件清单读取失败。');
191
191
  return response.json();
192
192
  }).then(data => {
@@ -3,4 +3,9 @@
3
3
  .viewer,.viewer main{position:absolute;inset:0}iframe{height:100%;width:100%;display:block;border:0}
4
4
  .canvas-loading{position:absolute;inset:0;background:var(--panel);color:var(--muted);display:grid;place-items:center;font-size:12px;z-index:2}.canvas-loading[hidden],#directory[hidden],.update-error[hidden],.empty-state[hidden],.skipped[hidden]{display:none}.update-error{position:absolute;top:60px;left:16px;right:16px;z-index:5;background:#fff6dd;color:#896213;border:1px solid #ecd9a6;border-radius:7px;padding:10px 13px;font-size:11px;box-shadow:0 3px 12px #0001}.empty-state{position:absolute;inset:0;background:var(--panel);padding:70px 35px;text-align:center}.empty-state h1{font-size:17px;font-weight:550}.empty-state p{font-size:12px;line-height:1.9;color:var(--muted);max-width:360px;margin:15px auto}
5
5
  [data-theme="dark"]{color-scheme:dark;--panel:#1c222b;--bg:#151a22;--ink:#dfe7ef;--muted:#9ba8b8;--line:#343e4c;--soft:#203753}
6
+ .empty-workspaces{margin:24px auto 0;max-width:460px;display:flex;flex-direction:column;gap:8px;text-align:left}
7
+ .empty-workspaces-title{font-size:11px;color:var(--muted);font-weight:600}
8
+ .empty-workspace-card{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px;border:1px solid var(--line);border-radius:10px;background:var(--bg);color:var(--ink);text-decoration:none;font-size:12px}
9
+ .empty-workspace-card:hover{border-color:var(--accent)}
10
+ .empty-workspace-card small{color:var(--muted);font-size:11px;flex:none}
6
11
  [hidden]{display:none!important}
@@ -3,7 +3,7 @@
3
3
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Clado · Markdown 目录预览</title><link rel="stylesheet" href="library.css"><!--CLADO-PLUGIN-STYLES--></head>
4
4
  <body>
5
5
  <div class="viewer">
6
- <main><div id="updateError" class="update-error" role="alert" hidden></div><iframe id="canvas" title="当前 Markdown 的脑图、卡片与文档"></iframe><div id="canvasLoading" class="canvas-loading">正在读取 Markdown…</div><div id="emptyState" class="empty-state" hidden><h1>目录中还没有可展示的画布</h1><p>让 AI 连接当前服务的 MCP,读取模板并创建 .mdc 文档,保存后会自动出现在这里。</p></div></main>
6
+ <main><div id="updateError" class="update-error" role="alert" hidden></div><iframe id="canvas" title="当前 Markdown 的卡片、脑图与文档"></iframe><div id="canvasLoading" class="canvas-loading">正在读取 Markdown…</div><div id="emptyState" class="empty-state" hidden><h1>目录中还没有可展示的画布</h1><p>让 AI 连接当前服务的 MCP,读取模板并创建 .mdc 文档,保存后会自动出现在这里。</p></div></main>
7
7
  </div>
8
8
  <!--CLADO-PLUGIN-SCRIPTS-->
9
9
  <script src="library.js"></script>
@@ -1,10 +1,14 @@
1
1
  (() => {
2
2
  const $ = selector => document.querySelector(selector);
3
3
  let frame = $('#canvas');
4
- let index = { documents: [], skipped: [] }, selected = '', mode = window.__CLADO_WORKSPACE__?.mode || 'mindmap', version = '', history = [], busy = false, design = { theme: window.__CLADO_WORKSPACE__?.theme || 'light' }, pendingView = null, pendingOpen = null, pendingAnchor = '', chainModal = false, deferredRefresh = false;
4
+ let index = { documents: [], skipped: [] }, selected = '', mode = ['cards', 'mindmap', 'doc'].includes(window.__CLADO_WORKSPACE__?.mode) ? window.__CLADO_WORKSPACE__.mode : 'cards', version = '', history = [], busy = false, design = { theme: window.__CLADO_WORKSPACE__?.theme || 'light' }, pendingView = null, pendingOpen = null, pendingAnchor = '', chainModal = false, deferredRefresh = false;
5
5
  const config = window.__CLADO_WORKSPACE__ || {}, offline = config.offline;
6
+ const workspaceId = config.workspaceId || '';
7
+ const withWorkspace = path => !workspaceId ? path : path + (path.includes('?') ? '&' : '?') + 'workspace=' + encodeURIComponent(workspaceId);
8
+ const workspaceUrl = id => id ? '/?workspace=' + encodeURIComponent(id) : '/';
9
+ if (workspaceId) document.title = (config.workspaceName || workspaceId) + ' · Clado';
6
10
  const settings = config.pluginSettings || {};
7
- mode = settings['clado.view-controls']?.defaultMode || mode;
11
+ if (['cards', 'mindmap', 'doc'].includes(settings['clado.view-controls']?.defaultMode)) mode = settings['clado.view-controls'].defaultMode;
8
12
  const pluginKey = 'clado-disabled-plugins:' + (config.pluginPreferenceKey || location.pathname);
9
13
  let disabledPlugins = new Set();
10
14
  try {
@@ -13,14 +17,14 @@
13
17
  } catch {}
14
18
  const items = [
15
19
  { id: 'clado.brand', name: 'Clado 设置', reason: '管理入口,始终启用' },
16
- { id: 'clado.view-controls', name: '视图切换', detail: '脑图、卡片和文档视图' },
20
+ { id: 'clado.view-controls', name: '视图切换', detail: '卡片、脑图和文档视图' },
17
21
  { id: 'clado.directory', name: '文档目录', detail: '查找和打开工作区文档' },
18
22
  { id: 'clado.agent', name: '灵感', detail: '与 Agent 对话并协作修改画布', ...(!config.agent && { reason: offline ? '需要在线服务' : '当前服务已关闭聊天' }) },
19
23
  ...(config.pluginCatalog || []),
20
24
  ];
21
25
  const isEnabled = id => id === 'clado.brand' || !items.some(item => item.id === id && item.reason) && !disabledPlugins.has(id);
22
26
  const ui = window.CladoPluginUI;
23
- const capabilities = window.CladoCapabilityBridge?.();
27
+ const capabilities = window.CladoCapabilityBridge?.(workspaceId);
24
28
  const host = ui.createHost(capabilities, isEnabled);
25
29
  const screenshot = window.CladoScreenshot?.();
26
30
  let lensOpen = false;
@@ -33,7 +37,7 @@
33
37
  }
34
38
  async function editPluginSettings(id, value, expected) {
35
39
  const write = arguments.length > 1;
36
- const response = await fetch('/library/plugin-settings?id=' + encodeURIComponent(id), write ? {
40
+ const response = await fetch(withWorkspace('/library/plugin-settings?id=' + encodeURIComponent(id)), write ? {
37
41
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value, expected }),
38
42
  } : { cache: 'no-store' });
39
43
  const result = await response.json();
@@ -46,7 +50,7 @@
46
50
  items, isEnabled,
47
51
  edit: config.hasPluginSettings ? editPluginSettings : null,
48
52
  install: config.canInstallPlugins && (async files => {
49
- const response = await fetch('/library/install-plugin', {
53
+ const response = await fetch(withWorkspace('/library/install-plugin'), {
50
54
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ files }),
51
55
  });
52
56
  const result = await response.json();
@@ -91,6 +95,8 @@
91
95
  showFilename: settings['clado.directory']?.showFilename !== false,
92
96
  open: file => open(file),
93
97
  openFromCapability,
98
+ workspaceUrl,
99
+ switchWorkspace: id => { location.href = workspaceUrl(id); },
94
100
  refresh: () => scan(true),
95
101
  back: () => {
96
102
  if (modalLocked()) return;
@@ -101,7 +107,7 @@
101
107
  if (!selected) throw new Error('no document');
102
108
  if (offline) return { file: selected, source: offline.sources[selected], offline: true };
103
109
  const file = selected;
104
- const response = await fetch('/library/source.mdc?file=' + encodeURIComponent(file), { cache: 'no-store' });
110
+ const response = await fetch(withWorkspace('/library/source.mdc?file=' + encodeURIComponent(file)), { cache: 'no-store' });
105
111
  if (!response.ok) throw new Error('source');
106
112
  return { file, source: await response.text() };
107
113
  },
@@ -128,6 +134,7 @@
128
134
  if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
129
135
  placeholder: settings['clado.agent']?.placeholder,
130
136
  agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
137
+ endpoint: withWorkspace('/library/agent'),
131
138
  readCanvas() {
132
139
  if (readyCanvas?.frame !== frame) return undefined;
133
140
  const { file, revision } = readyCanvas;
@@ -139,7 +146,7 @@
139
146
  if (!['light', 'dark'].includes(design.theme)) design.theme = 'light';
140
147
  try { const savedTheme = localStorage.getItem('clado-theme'); if (['light', 'dark'].includes(savedTheme)) design.theme = savedTheme; } catch {}
141
148
  if (config.plugins) window.CladoPluginHost({
142
- host, capabilities, isEnabled,
149
+ host, capabilities, isEnabled, workspaceId,
143
150
  readView() {
144
151
  if (readyCanvas?.frame !== frame) return null;
145
152
  const { file, revision } = readyCanvas;
@@ -151,7 +158,7 @@
151
158
  if (selectionTab) frame.contentWindow.postMessage({ type: 'clado-workspace:selection', nodes: aiSelection?.nodes || [] }, location.origin);
152
159
  }
153
160
  async function publishSelection(selection) {
154
- const response = await fetch('/library/selection', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
161
+ const response = await fetch(withWorkspace('/library/selection'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
155
162
  if (!response.ok) throw new Error('selection');
156
163
  }
157
164
  function setSelection(next, refresh = false) {
@@ -181,12 +188,12 @@
181
188
  if (aiSelection && !pageHidden) publishSelection({ ...aiSelection, refresh: 'heartbeat' }).catch(() => {});
182
189
  }, 20000);
183
190
  }
184
- const storageKey='clado-library-view:v2:'+location.pathname;
191
+ const storageKey='clado-library-view:v2:'+location.pathname+(workspaceId?':'+workspaceId:'');
185
192
  const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
186
- try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['mindmap','cards','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
193
+ try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['cards','mindmap','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
187
194
  try {
188
195
  const restoredMode = sessionStorage.getItem(pluginKey + ':mode');
189
- if (['mindmap','cards','doc'].includes(restoredMode)) mode = restoredMode;
196
+ if (['cards','mindmap','doc'].includes(restoredMode)) mode = restoredMode;
190
197
  if (restoredMode) sessionStorage.removeItem(pluginKey + ':mode');
191
198
  } catch {}
192
199
  const requestedFile = new URLSearchParams(location.search).get('file');
@@ -204,13 +211,43 @@
204
211
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
205
212
  }
206
213
  function renderDirectory() { directory.update(index, selected, history.length > 0); }
214
+ let emptyWorkspaceSignature = '';
215
+ function renderEmptyWorkspaces(list) {
216
+ const others = list.filter(item => item.id !== workspaceId);
217
+ const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
218
+ if (next === emptyWorkspaceSignature) return;
219
+ emptyWorkspaceSignature = next;
220
+ let container = $('#emptyState .empty-workspaces');
221
+ if (!others.length) { container?.remove(); return; }
222
+ if (!container) {
223
+ container = document.createElement('div');
224
+ container.className = 'empty-workspaces';
225
+ $('#emptyState').append(container);
226
+ }
227
+ container.replaceChildren();
228
+ const title = document.createElement('div');
229
+ title.className = 'empty-workspaces-title';
230
+ title.textContent = '已发现的子工作区(点击打开)';
231
+ container.append(title);
232
+ for (const item of others) {
233
+ const link = document.createElement('a');
234
+ link.className = 'empty-workspace-card';
235
+ link.href = workspaceUrl(item.id);
236
+ const name = document.createElement('span');
237
+ name.textContent = item.id || (item.name + '(根目录)');
238
+ const count = document.createElement('small');
239
+ count.textContent = (item.documents ?? 0) + ' 份画布';
240
+ link.append(name, count);
241
+ container.append(link);
242
+ }
243
+ }
207
244
  let renderRequest = 0;
208
245
  async function openFromCapability(file) {
209
246
  const failure = (kind, message) => Object.assign(new Error(message), { kind });
210
247
  if (modalLocked() || lensOpen) throw failure('VIEW_LOCKED', '请先关闭链路或内容放大窗口。');
211
248
  let targetDocument = index.documents.find(entry => entry.file === file);
212
249
  if (!targetDocument) {
213
- const response = await fetch('/library/index.json', { cache: 'no-store' });
250
+ const response = await fetch(withWorkspace('/library/index.json'), { cache: 'no-store' });
214
251
  if (!response.ok) throw failure('NAVIGATION_FAILED', '读取文档目录失败,请重试。');
215
252
  const latest = await response.json();
216
253
  targetDocument = latest.documents.find(entry => entry.file === file);
@@ -254,7 +291,7 @@
254
291
  let html;
255
292
  if(offline) html=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');
256
293
  else {
257
- const response = await fetch('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&theme=' + design.theme + '&chrome=workspace&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : ''), {cache:'no-store'});
294
+ const response = await fetch(withWorkspace('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&theme=' + design.theme + '&chrome=workspace&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : '')), {cache:'no-store'});
258
295
  if(!response.ok)throw new Error('render');
259
296
  html = await response.text();
260
297
  }
@@ -281,7 +318,20 @@
281
318
  if (busy) return; busy = true;
282
319
  try {
283
320
  if(offline) index=offline.index;
284
- else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
321
+ else {
322
+ const [indexRes, workspacesRes] = await Promise.all([
323
+ fetch(withWorkspace('/library/index.json'), { cache: 'no-store' }),
324
+ config.multiWorkspace ? fetch('/library/workspaces.json', { cache: 'no-store' }).catch(() => null) : Promise.resolve(null),
325
+ ]);
326
+ if(!indexRes.ok)throw new Error('scan');
327
+ index=await indexRes.json();
328
+ if (workspacesRes?.ok) {
329
+ const data = await workspacesRes.json();
330
+ const list = Array.isArray(data.workspaces) ? data.workspaces : [];
331
+ directory.updateWorkspaces?.(workspaceId, list);
332
+ renderEmptyWorkspaces(list);
333
+ }
334
+ }
285
335
  renderDirectory();
286
336
  try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
287
337
  if(modalLocked()) {
@@ -10,7 +10,7 @@ const json=value=>JSON.stringify(value).replace(/</g,'\\u003c');
10
10
  const script=value=>'<script>'+value.replace(/<\/script/gi,'<\\/script')+'</script>';
11
11
  const mime={png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
12
12
  /** One portable workspace, including all canvases, navigation, sources and local media. */
13
- export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',title}={}) {
13
+ export function renderWorkspace(jobs,{root,entry,mode='cards',theme='light',title}={}) {
14
14
  root=resolve(root);
15
15
  const documents=jobs.map(j=>({file:relative(root,j.file).split('\\').join('/'),title:j.doc.title,version:'offline',modified:0}));
16
16
  const index={root:basename(root)+'/',documents,skipped:[]},canvases={},sources={},shared=[],assetIds=new Map();