cladogram 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +90 -349
- package/bin/clado.js +99 -17
- package/examples/showcase/README.md +3 -1
- package/examples/showcase/build.sh +3 -3
- package/package.json +2 -2
- package/skills/clado/SKILL.md +50 -791
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/backend.md +80 -0
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/data.md +53 -0
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/interaction.md +70 -0
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/overview.md +30 -0
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/verify.md +35 -0
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/approval.md +69 -0
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/data-verify.md +49 -0
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/interaction.md +47 -0
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/overview.md +39 -0
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/evidence.md +42 -0
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/overview.md +26 -0
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/response.md +64 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/api.md +127 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/caller.md +50 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/calls.md +185 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/code.md +249 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/consumer.md +93 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/contracts.md +89 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/data.md +237 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/overview.md +75 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/publisher.md +175 -0
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/verify.md +53 -0
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/01-/347/224/263/350/257/267/350/275/254/345/215/225.md +499 -0
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/02-/345/267/262/346/234/211/350/256/242/345/215/225/346/216/245/345/217/243.md +46 -0
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/03-/350/241/250/347/273/223/346/236/204.md +100 -0
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/overview.md +47 -0
- package/skills/clado/examples/build.sh +4 -1
- package/skills/clado/references/content-patterns.md +61 -0
- package/skills/clado/references/data.md +37 -0
- package/skills/clado/references/delivery.md +57 -0
- package/skills/clado/references/diagnostics.md +20 -123
- package/skills/clado/references/editing.md +49 -0
- package/skills/clado/references/engineering.md +167 -0
- package/skills/clado/references/flows.md +53 -0
- package/skills/clado/references/interactions.md +46 -0
- package/skills/clado/references/operations.md +39 -0
- package/skills/clado/references/requirements.md +37 -0
- package/skills/clado/references/verification.md +27 -0
- package/src/core/parse.js +18 -7
- package/src/html/app-css.js +52 -66
- package/src/html/canvas-card.js +66 -0
- package/src/html/canvas-chain.js +203 -0
- package/src/html/canvas-focus.js +175 -0
- package/src/html/canvas-ui.css +21 -0
- package/src/html/canvas-ui.js +38 -0
- package/src/html/canvas-wires.js +56 -0
- package/src/html/mindmap-connectors.js +57 -0
- package/src/html/mindmap-media.js +39 -0
- package/src/html/mindmap-motion.js +69 -0
- package/src/html/page.js +18 -2
- package/src/html/runtime-api.js +62 -0
- package/src/html/runtime-fixes.js +41 -0
- package/src/html/runtime.js +182 -157
- package/src/server/assets/editor.css +1 -0
- package/src/server/assets/editor.js +79 -0
- package/src/server/assets/library-canvas.js +90 -0
- package/src/server/assets/library.css +9 -0
- package/src/server/assets/library.html +20 -0
- package/src/server/assets/library.js +94 -0
- package/src/server/assets/tree.js +26 -0
- package/src/server/export.js +53 -0
- package/src/server/workspace.js +95 -0
- package/src/skill/targets.js +18 -9
- package/src/workspace/commands.js +42 -0
- package/src/workspace/documents.js +143 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const runtime = window.CladoRuntime;
|
|
3
|
+
const params = new URLSearchParams(location.search), file = window.__CLADO_FILE_PATH__ || params.get('file');
|
|
4
|
+
let designKey = '', cardsInitialized = false;
|
|
5
|
+
const post = (type, detail = {}) => parent.postMessage({ type: 'clado-library:' + type, file, ...detail }, '*');
|
|
6
|
+
const labels = { mindmap: '脑图', cards: '卡片', doc: '文档' };
|
|
7
|
+
const hints = { mindmap: '节点单击聚焦,双击收放子节点 · 拖动空白平移,滚轮缩放', cards: '端口单击收放 · 标题单击聚焦、双击收放子节点 · 拖动空白平移,滚轮缩放', doc: '单击大纲或标题聚焦章节 · 点击表格、代码或图表放大' };
|
|
8
|
+
const hint = () => { document.querySelector('#hint').textContent = hints[document.body.dataset.mode]; };
|
|
9
|
+
const modes = document.querySelector('#modes');
|
|
10
|
+
['mindmap','cards','doc'].forEach(mode => { const button = modes.querySelector('[data-mode="' + mode + '"]'); button.textContent = labels[mode]; modes.append(button); });
|
|
11
|
+
document.addEventListener('pointerdown', () => post('dismiss-directory'), true);
|
|
12
|
+
document.addEventListener('keydown', event => { if (event.key === 'Escape') post('dismiss-directory'); });
|
|
13
|
+
function resourceUrl(href) {
|
|
14
|
+
const target = new URL(href,'https://clado.local/documents/'+file);
|
|
15
|
+
if (!target.pathname.startsWith('/documents/')) return null;
|
|
16
|
+
const path=decodeURIComponent(target.pathname.slice('/documents/'.length));
|
|
17
|
+
return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path));
|
|
18
|
+
}
|
|
19
|
+
function rewriteDocumentLinks() {
|
|
20
|
+
document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
|
|
21
|
+
const src=img.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
|
|
22
|
+
try { const url=resourceUrl(src);if(url){img.dataset.resource='1';img.src=url;} } catch {}
|
|
23
|
+
});
|
|
24
|
+
document.querySelectorAll('a[href]:not(.edge):not([data-resource])').forEach(a=>{
|
|
25
|
+
const href=a.getAttribute('href');if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#)/i.test(href) || /\.md(?:#|$)/i.test(href))return;
|
|
26
|
+
if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json)(?:#|$)/i.test(href))return;
|
|
27
|
+
try { const url=resourceUrl(href);if(url){a.dataset.resource='1';a.href=url;} } catch {}
|
|
28
|
+
});
|
|
29
|
+
document.querySelectorAll('a[href]:not(.edge):not([data-canvas-file])').forEach(a => {
|
|
30
|
+
const href = a.getAttribute('href');
|
|
31
|
+
if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(href)) return;
|
|
32
|
+
const parts = href.split('#'); if (!/\.md$/i.test(parts[0])) return;
|
|
33
|
+
const target = new URL(parts[0], 'https://clado.local/documents/' + file);
|
|
34
|
+
if (!target.pathname.startsWith('/documents/')) return;
|
|
35
|
+
let targetFile; try { targetFile = decodeURIComponent(target.pathname.slice('/documents/'.length)); } catch { return; }
|
|
36
|
+
a.dataset.canvasFile = targetFile; a.dataset.canvasAnchor = parts.slice(1).join('#');
|
|
37
|
+
a.href = '/library.html?file=' + encodeURIComponent(targetFile);
|
|
38
|
+
a.removeAttribute('target');
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
new MutationObserver(rewriteDocumentLinks).observe(document.querySelector('#world'), { childList: true, subtree: true });
|
|
42
|
+
rewriteDocumentLinks();
|
|
43
|
+
async function settle() {
|
|
44
|
+
await new Promise(resolve => requestAnimationFrame(resolve));
|
|
45
|
+
if (document.body.dataset.mode === 'cards') { if (!cardsInitialized) { cardsInitialized=true; await runtime.allEdges(true); } else { await runtime.whenMedia(); runtime.refresh(); } }
|
|
46
|
+
else { await runtime.whenMedia(); if (document.body.dataset.mode === 'mindmap') runtime.refresh(); }
|
|
47
|
+
hint();
|
|
48
|
+
}
|
|
49
|
+
document.addEventListener('click', event => {
|
|
50
|
+
const a = event.target.closest('a[href]');
|
|
51
|
+
if (!a || a.classList.contains('edge')) return;
|
|
52
|
+
if (a.dataset.canvasFile) { event.preventDefault(); event.stopImmediatePropagation(); post('open', { target: a.dataset.canvasFile, anchor: a.dataset.canvasAnchor }); return; }
|
|
53
|
+
const href = a.getAttribute('href');
|
|
54
|
+
if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(href)) return;
|
|
55
|
+
const parts = href.split('#');
|
|
56
|
+
if (!/\.md$/i.test(parts[0])) return;
|
|
57
|
+
event.preventDefault(); event.stopImmediatePropagation();
|
|
58
|
+
const target = new URL(parts[0], 'https://clado.local/documents/' + file);
|
|
59
|
+
if (!target.pathname.startsWith('/documents/')) { post('missing', { target: href }); return; }
|
|
60
|
+
let targetFile; try { targetFile = decodeURIComponent(target.pathname.slice('/documents/'.length)); } catch { return; }
|
|
61
|
+
post('open', { target: targetFile, anchor: parts.slice(1).join('#') });
|
|
62
|
+
}, true);
|
|
63
|
+
modes.addEventListener('click', async event => { if (!event.target.closest('button')) return; await settle(); post('mode', { mode: document.body.dataset.mode }); });
|
|
64
|
+
document.querySelector('#theme').addEventListener('click', () => post('theme', { theme: document.documentElement.dataset.theme }));
|
|
65
|
+
function setDesign(design) {
|
|
66
|
+
const key = JSON.stringify(design); if (key === designKey) return; designKey = key;
|
|
67
|
+
const root = document.documentElement;
|
|
68
|
+
if (root.dataset.theme !== design.theme) runtime.setTheme(design.theme || 'light', false);
|
|
69
|
+
root.style.setProperty('--proto-font', (design.font || 14) + 'px'); root.style.setProperty('--proto-radius', (design.radius ?? 11) + 'px'); root.style.setProperty('--proto-reading-width', (design.readingWidth || 1000) + 'px');
|
|
70
|
+
if (design.accent) { root.style.setProperty('--accent', design.accent); root.style.setProperty('--accent-soft', 'color-mix(in srgb,' + design.accent + ' 12%,var(--panel))'); }
|
|
71
|
+
document.querySelectorAll('#world > .card').forEach(card => card.style.width = (design.cardWidth || 500) + 'px');
|
|
72
|
+
requestAnimationFrame(() => { if (document.body.dataset.mode !== 'doc') runtime.refresh(); });
|
|
73
|
+
}
|
|
74
|
+
window.addEventListener('message', async event => {
|
|
75
|
+
if(event.source!==parent || event.data?.type!=='clado-workspace:display')return;
|
|
76
|
+
const {mode,theme,anchor}=event.data;
|
|
77
|
+
if(['doc','cards','mindmap'].includes(mode))runtime.setMode(mode);
|
|
78
|
+
if(['light','dark'].includes(theme))runtime.setTheme(theme,false);
|
|
79
|
+
await settle();
|
|
80
|
+
if(anchor) { let title=anchor;try{title=decodeURIComponent(anchor);}catch{}runtime.focusTitle(title); }
|
|
81
|
+
post('mode',{mode:document.body.dataset.mode});
|
|
82
|
+
});
|
|
83
|
+
window.CladoPrototype = { setDesign, fit: runtime.refresh, closeLens: runtime.closeLens, captureView: runtime.captureView, restoreView: runtime.restoreView };
|
|
84
|
+
let resizeTimer; addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { if (document.body.dataset.mode !== 'doc') runtime.refresh(); }, 120); });
|
|
85
|
+
settle().then(() => {
|
|
86
|
+
let anchor; try { anchor = decodeURIComponent(params.get('anchor') || ''); } catch { anchor = ''; }
|
|
87
|
+
if (anchor) runtime.focusTitle(anchor);
|
|
88
|
+
post('ready', { mode: document.body.dataset.mode });
|
|
89
|
+
}).catch(() => post('ready', { mode: document.body.dataset.mode }));
|
|
90
|
+
})();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
:root{color-scheme:light;--panel:#fff;--bg:#f6f8fb;--ink:#263140;--muted:#8290a0;--line:#e2e7ef;--accent:#0969da;--soft:#edf4ff;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;font-size:12px}
|
|
2
|
+
*{box-sizing:border-box}body{margin:0;height:100vh;overflow:hidden;color:var(--ink);background:var(--panel)}button{font:inherit;border:1px solid var(--line);background:var(--panel);color:var(--muted);border-radius:6px;padding:5px 9px;cursor:pointer;white-space:nowrap}button:hover{color:var(--accent);border-color:var(--accent)}button:disabled{opacity:.4;cursor:default}button:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
|
3
|
+
.viewer,.viewer main{position:absolute;inset:0}iframe{height:100%;width:100%;display:block;border:0}.directory-toggle{position:fixed;left:18px;bottom:18px;z-index:20;border-radius:22px;padding:10px 15px;color:var(--ink);box-shadow:0 3px 15px #172b4318;background:var(--panel);font-size:12px}.directory-toggle span{font-size:10px;margin-left:7px;color:var(--muted)}.directory-toggle[data-sync="ok"]:before,.directory-toggle[data-sync="error"]:before{content:'';display:inline-block;width:5px;height:5px;border-radius:50%;background:#6ba882;vertical-align:middle;margin-right:7px}.directory-toggle[data-sync="error"]:before{background:#c99b40}
|
|
4
|
+
#directory{position:fixed;left:18px;bottom:68px;width:288px;max-height:calc(100vh - 94px);overflow:auto;padding:17px 10px 10px;border:1px solid var(--line);border-radius:12px;background:var(--panel);z-index:25;box-shadow:0 12px 40px #15243b24}.directory-heading{padding:0 9px 13px}.directory-heading strong{font-size:12px;font-weight:600}.directory-heading span{display:block;font-size:10px;color:var(--muted);margin-top:5px}#documentList{display:flex;flex-direction:column;gap:4px}.document-button{display:block;text-align:left;padding:9px 10px;white-space:normal;border-color:transparent;width:100%}.document-button strong{font-size:11px;font-weight:500;display:block;color:var(--ink)}.document-button small{font-size:9px;color:var(--muted);display:block;margin-top:4px;overflow-wrap:anywhere}.document-button[aria-current="page"]{background:var(--soft);border-color:var(--soft)}.document-button[aria-current="page"] strong{color:var(--accent)}.directory-current{padding:12px 10px 8px;margin-top:10px;border-top:1px solid var(--line)}.directory-current strong{font-size:10px;font-weight:500;display:block;color:var(--muted)}.directory-current span{display:block;color:var(--muted);font-size:9px;margin-top:4px;overflow-wrap:anywhere}.directory-actions{display:flex;gap:7px;padding:0 10px}.directory-actions button{font-size:10px;padding:4px 7px}.directory-actions #sourceButton{margin-left:auto}.skipped{margin-top:10px;border:0;border-top:1px solid var(--line);border-radius:0;width:100%;text-align:left;padding:11px 10px 2px;font-size:9px;color:var(--muted);white-space:normal}
|
|
5
|
+
.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}
|
|
6
|
+
.sync-error{color:#b88628!important}.sync-good:before{content:'';display:inline-block;width:4px;height:4px;border-radius:50%;background:#69a57f;vertical-align:middle;margin-right:5px}dialog{width:min(660px,calc(100vw - 32px));max-height:calc(100vh - 36px);border:1px solid var(--line);border-radius:10px;padding:0;background:var(--panel);color:var(--ink);box-shadow:0 15px 70px #13213e33}dialog::backdrop{background:#15243a66;backdrop-filter:blur(2px)}dialog>header{padding:15px 20px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:12px}dialog>header strong{font-size:13px;font-weight:600}dialog>header button{margin-left:auto;font-size:19px;line-height:1;border:0}#detailsBody{padding:18px 20px;max-height:calc(100vh - 130px);overflow:auto}#detailsBody p{font-size:11px;color:var(--muted);line-height:1.8;margin:0 0 14px}#detailsBody pre{font:11px/1.9 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:0;background:var(--bg);padding:15px;border:1px solid var(--line);border-radius:7px}.skip-item{padding:10px 0;border-bottom:1px solid var(--line)}.skip-item strong{font-size:12px}.skip-item p{margin:5px 0!important}.skip-item code{font-size:10px}
|
|
7
|
+
[data-theme="dark"]{color-scheme:dark;--panel:#1c222b;--bg:#151a22;--ink:#dfe7ef;--muted:#9ba8b8;--line:#343e4c;--soft:#203753}@media(max-width:450px){.directory-toggle{left:12px;bottom:12px;padding:8px 12px}#directory{left:12px;bottom:58px;width:min(288px,calc(100vw - 24px));max-height:calc(100vh - 80px)}}
|
|
8
|
+
[hidden]{display:none!important}
|
|
9
|
+
.directory-search{display:block;padding:0 9px 10px}.directory-search input{box-sizing:border-box;width:100%;border:1px solid var(--line);border-radius:7px;background:var(--bg);color:var(--ink);font:inherit;padding:8px 10px;outline-color:var(--accent)}.tree-folder>summary{cursor:pointer;padding:8px;color:var(--ink);font-size:12px;font-weight:550}.tree-children{margin-left:11px;padding-left:5px;border-left:1px solid var(--line)}.tree-empty{padding:8px;color:var(--muted);font-size:12px}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN" data-theme="light">
|
|
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"></head>
|
|
4
|
+
<body>
|
|
5
|
+
<button id="directoryButton" class="directory-toggle" aria-expanded="false" aria-controls="directory" title="切换 Markdown 画布">文档 <span id="fileCount">…</span></button>
|
|
6
|
+
<aside id="directory" aria-label="Markdown 画布目录" hidden>
|
|
7
|
+
<div class="directory-heading"><strong>Markdown/</strong><span>选择文档,打开对应画布</span></div>
|
|
8
|
+
<label class="directory-search"><input id="documentSearch" type="search" aria-label="搜索文档" placeholder="搜索名称或路径…"></label>
|
|
9
|
+
<nav id="documentList" aria-label="可用 Markdown"></nav>
|
|
10
|
+
<div class="directory-current"><strong id="currentTitle" hidden>正在扫描 Markdown…</strong><span id="currentPath" hidden>Markdown/</span><span id="syncStatus" role="status">连接本地目录</span></div>
|
|
11
|
+
<div class="directory-actions"><button id="backButton" disabled>← 返回</button><button id="refreshButton" title="重新扫描目录并刷新当前文档">刷新</button><button id="sourceButton">源文</button><button id="newDocument">新文档</button></div>
|
|
12
|
+
<button id="skippedButton" class="skipped" hidden></button>
|
|
13
|
+
</aside>
|
|
14
|
+
<div class="viewer">
|
|
15
|
+
<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 在此目录创建符合约定的 Markdown,保存后会自动出现在这里。</p></div></main>
|
|
16
|
+
</div>
|
|
17
|
+
<dialog id="details"><header><strong id="detailsTitle"></strong><button id="closeDetails" aria-label="关闭详情">×</button></header><div id="detailsBody"></div></dialog>
|
|
18
|
+
<script src="/tree.js"></script>
|
|
19
|
+
<script src="library.js"></script>
|
|
20
|
+
</body></html>
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const $ = selector => document.querySelector(selector), frame = $('#canvas');
|
|
3
|
+
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
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, directorySignature = '', pendingOpen = null, pendingAnchor = '', editing = false, creating = false;
|
|
5
|
+
const config=window.__CLADO_WORKSPACE__ || {}, offline=config.offline, folders=new Set();
|
|
6
|
+
const storageKey='clado-library-view:v2:'+location.pathname;
|
|
7
|
+
const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
|
|
8
|
+
try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['mindmap','cards','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
|
|
9
|
+
const requestedFile = new URLSearchParams(location.search).get('file');
|
|
10
|
+
if (requestedFile || config.entry) selected = requestedFile || config.entry;
|
|
11
|
+
if(offline) $('#newDocument').hidden=true;
|
|
12
|
+
function saveView() { try { sessionStorage.setItem(storageKey, JSON.stringify({ file: selected, mode })); } catch {} }
|
|
13
|
+
function directory(open) { $('#directory').hidden = !open; $('#directoryButton').setAttribute('aria-expanded', String(open)); }
|
|
14
|
+
function details(title, html) { $('#detailsTitle').textContent = title; $('#detailsBody').innerHTML = html; if (!$('#details').open) $('#details').showModal(); }
|
|
15
|
+
function renderDirectory() {
|
|
16
|
+
const signature = JSON.stringify({ documents: index.documents, skipped: index.skipped, selected, query:$('#documentSearch').value, history: history.length });
|
|
17
|
+
if (signature === directorySignature) return;
|
|
18
|
+
directorySignature = signature;
|
|
19
|
+
$('#fileCount').textContent = index.documents.length;
|
|
20
|
+
document.querySelector('.directory-heading strong').textContent = index.root || 'Markdown';
|
|
21
|
+
CladoDocumentTree($('#documentList'),index.documents,{selected,query:$('#documentSearch').value,folders,onOpen:file=>{open(file);directory(false);}});
|
|
22
|
+
$('#skippedButton').hidden = !index.skipped.length; $('#skippedButton').textContent = index.skipped.length + ' 份 Markdown 未收录 · 查看原因';
|
|
23
|
+
$('#backButton').disabled = history.length === 0;
|
|
24
|
+
}
|
|
25
|
+
function open(file, anchor = '', options = {}) {
|
|
26
|
+
if(editing){ status('请先保存或取消文档编辑',true);return; }
|
|
27
|
+
creating=false;pendingAnchor=anchor;
|
|
28
|
+
const doc = index.documents.find(d => d.file === file);
|
|
29
|
+
if (!doc) { details('这个 Markdown 暂未收录', '<p>' + esc(file) + ' 不在有效画布目录中。可以让 AI 检查文件是否存在、路径是否正确,以及能否通过解析。</p>'); return; }
|
|
30
|
+
if (selected && file !== selected && !options.back) history.push(selected);
|
|
31
|
+
if (options.update) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
|
|
32
|
+
else pendingView = null;
|
|
33
|
+
selected = file; version = doc.version; saveView(); renderDirectory();
|
|
34
|
+
$('#currentTitle').textContent = doc.title; $('#currentPath').textContent = (index.root || '') + file;
|
|
35
|
+
$('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
|
|
36
|
+
if(offline) { frame.srcdoc=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');return; }
|
|
37
|
+
frame.removeAttribute('srcdoc');
|
|
38
|
+
frame.src = '/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : '');
|
|
39
|
+
}
|
|
40
|
+
function status(text, error = false) { $('#syncStatus').textContent = text; $('#syncStatus').className = error ? 'sync-error' : 'sync-good'; $('#directoryButton').dataset.sync = error ? 'error' : 'ok'; $('#directoryButton').title = '切换 Markdown 画布 · ' + text; }
|
|
41
|
+
async function scan(force = false) {
|
|
42
|
+
if (busy) return; busy = true;
|
|
43
|
+
try {
|
|
44
|
+
if(offline) index=offline.index;
|
|
45
|
+
else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
|
|
46
|
+
renderDirectory();
|
|
47
|
+
try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
|
|
48
|
+
if(creating)return;
|
|
49
|
+
if (pendingOpen && index.documents.some(d=>d.file===pendingOpen)) { const file=pendingOpen;pendingOpen=null;open(file); }
|
|
50
|
+
if (selected && !version && !index.documents.some(d=>d.file===selected)) { selected='';saveView(); }
|
|
51
|
+
if (!selected && index.documents.length) open(index.documents[0].file);
|
|
52
|
+
else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; $('#currentTitle').textContent = '等待 Markdown'; status('目录已扫描'); post('ready'); }
|
|
53
|
+
else {
|
|
54
|
+
const doc = index.documents.find(d => d.file === selected);
|
|
55
|
+
if (!doc && !version && index.documents.length) open(index.documents[0].file);
|
|
56
|
+
else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
|
|
57
|
+
else { $('#updateError').hidden = true; if (force || doc.version !== version) { if(editing){status('源文件已变化;保存时将检查冲突',true);}else open(selected, '', { update: true }); } else status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); }
|
|
58
|
+
}
|
|
59
|
+
} catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
|
|
60
|
+
finally { busy = false; }
|
|
61
|
+
}
|
|
62
|
+
addEventListener('message', event => {
|
|
63
|
+
if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
|
|
64
|
+
const data = event.data;
|
|
65
|
+
if(data?.type === 'clado-library:editing') { editing=!!data.value;return; }
|
|
66
|
+
if(data?.type === 'clado-library:create-cancel') { editing=false;creating=false;if(selected)open(selected);else scan();return; }
|
|
67
|
+
if (data?.type === 'clado-library:open') { directory(false); open(data.target, data.anchor); }
|
|
68
|
+
else if (data?.type === 'clado-library:changed') { editing=false;creating=false; if (data.file !== selected) pendingOpen=data.file; scan(true); }
|
|
69
|
+
else if (data?.type === 'clado-library:dismiss-directory') directory(false);
|
|
70
|
+
else if (data?.type === 'clado-library:missing') details('链接超出当前目录', '<p>请选择当前扫描目录里的 Markdown。链接:' + esc(data.target) + '</p>');
|
|
71
|
+
else if (data?.type === 'clado-library:mode') { mode = data.mode; saveView(); }
|
|
72
|
+
else if (data?.type === 'clado-library:theme') { design.theme = data.theme; setDesign(design); post('theme', { theme: data.theme }); }
|
|
73
|
+
else if (data?.type === 'clado-library:ready') {
|
|
74
|
+
if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
|
|
75
|
+
else mode = data.mode; saveView(); $('#canvasLoading').hidden = true;
|
|
76
|
+
try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
|
|
77
|
+
if (!offline && pendingView) { const view = pendingView; pendingView = null; requestAnimationFrame(() => requestAnimationFrame(() => frame.contentWindow.CladoPrototype?.restoreView?.(view))); }
|
|
78
|
+
status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} }
|
|
82
|
+
window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
|
|
83
|
+
$('#documentSearch').oninput=renderDirectory;
|
|
84
|
+
$('#newDocument').onclick = () => { if(editing)return;creating=true;directory(false);$('#emptyState').hidden=true;$('#updateError').hidden=true;$('#canvasLoading').hidden=false;frame.removeAttribute('srcdoc');frame.src='/library/new'; };
|
|
85
|
+
$('#directoryButton').onclick = () => directory($('#directory').hidden);
|
|
86
|
+
document.addEventListener('pointerdown', event => { if (!event.target.closest('#directory, #directoryButton')) directory(false); });
|
|
87
|
+
document.addEventListener('keydown', event => { if (event.key === 'Escape' && !$('#directory').hidden) { directory(false); $('#directoryButton').focus(); } });
|
|
88
|
+
$('#refreshButton').onclick = () => scan(true);
|
|
89
|
+
$('#backButton').onclick = () => { if(editing){status('请先保存或取消文档编辑',true);return;}const previous = history.pop(); if (previous) open(previous, '', { back: true }); };
|
|
90
|
+
$('#closeDetails').onclick = () => $('#details').close();
|
|
91
|
+
$('#skippedButton').onclick = () => details('扫描后未收录的 Markdown', '<p>目录只显示能通过解析的画布。解析失败可能来自普通说明文档,也可能需要修正内容;具体原因如下。</p>' + index.skipped.map(item => '<section class="skip-item"><strong>' + esc(item.file) + '</strong>' + item.diagnostics.map(d => '<p><code>' + esc(d.code) + '</code> · ' + esc(d.message) + '</p>').join('') + '</section>').join(''));
|
|
92
|
+
$('#sourceButton').onclick = async () => { try { const response = offline ? {ok:true,text:async()=>offline.sources[selected]} : await fetch('/library/source.md?file=' + encodeURIComponent(selected), { cache: 'no-store' }); if (!response.ok) throw new Error('source'); details(selected, (offline?'<p>这是 HTML 内嵌的只读源文。修改源 Markdown 后重新构建以更新交付文件。</p><pre>':'<p>源文只读预览。由 AI 或编辑器修改这个 Markdown,保存到磁盘后,当前画布会自动同步。</p><pre>') + esc(await response.text()) + '</pre>'); } catch { details('暂时读不到源文', '<p>请检查文档是否已删除,或是否出现解析错误。</p>'); } };
|
|
93
|
+
directory(false); scan(); if(!offline)setInterval(() => scan(), 1200);
|
|
94
|
+
})();
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
window.CladoDocumentTree = function (container, documents, { selected='', query='', onOpen=()=>{}, folders=new Set() } = {}) {
|
|
3
|
+
const needle=query.trim().toLocaleLowerCase(), root={folders:new Map(),files:[]};
|
|
4
|
+
for(const doc of documents) {
|
|
5
|
+
if(needle && !(doc.title+' '+doc.file).toLocaleLowerCase().includes(needle))continue;
|
|
6
|
+
const parts=doc.file.split('/');let node=root;
|
|
7
|
+
parts.slice(0,-1).forEach((name,i)=>{const path=parts.slice(0,i+1).join('/');if(!node.folders.has(name))node.folders.set(name,{path,folders:new Map(),files:[]});node=node.folders.get(name);});node.files.push(doc);
|
|
8
|
+
}
|
|
9
|
+
container.replaceChildren();
|
|
10
|
+
function render(node, parent) {
|
|
11
|
+
for(const [name,folder] of node.folders) {
|
|
12
|
+
const details=document.createElement('details');details.className='tree-folder';details.open=!!needle||!folders.has('closed:'+folder.path);
|
|
13
|
+
const summary=document.createElement('summary');summary.textContent=name;details.append(summary);
|
|
14
|
+
details.addEventListener('toggle',()=>{if(!needle){if(details.open)folders.delete('closed:'+folder.path);else folders.add('closed:'+folder.path);}});
|
|
15
|
+
const children=document.createElement('div');children.className='tree-children';details.append(children);render(folder,children);parent.append(details);
|
|
16
|
+
}
|
|
17
|
+
for(const doc of node.files) {
|
|
18
|
+
const button=document.createElement('button');button.className='document-button';button.dataset.file=doc.file;if(doc.file===selected)button.setAttribute('aria-current','page');
|
|
19
|
+
const strong=document.createElement('strong');strong.textContent=doc.title;
|
|
20
|
+
const small=document.createElement('small');small.textContent=doc.file.split('/').pop();button.append(strong,small);button.onclick=()=>onOpen(doc.file);parent.append(button);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
render(root,container);
|
|
24
|
+
if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'还没有可展示的 Markdown';container.append(empty);}
|
|
25
|
+
};
|
|
26
|
+
})();
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, resolve, basename } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { renderHtml } from '../html/page.js';
|
|
5
|
+
import { workspacePath } from '../workspace/documents.js';
|
|
6
|
+
const assets=join(dirname(fileURLToPath(import.meta.url)),'assets');
|
|
7
|
+
const read=name=>readFileSync(join(assets,name),'utf8');
|
|
8
|
+
const json=value=>JSON.stringify(value).replace(/</g,'\\u003c');
|
|
9
|
+
const script=value=>'<script>'+value.replace(/<\/script/gi,'<\\/script')+'</script>';
|
|
10
|
+
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'};
|
|
11
|
+
/** One portable workspace, including all canvases, navigation, sources and local media. */
|
|
12
|
+
export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',title}={}) {
|
|
13
|
+
root=resolve(root);
|
|
14
|
+
const documents=jobs.map(j=>({file:relative(root,j.file).split('\\').join('/'),title:j.doc.title,version:'offline',modified:0}));
|
|
15
|
+
const index={root:basename(root)+'/',documents,skipped:[]},canvases={},sources={},shared=[],assetIds=new Map();
|
|
16
|
+
for(let i=0;i<jobs.length;i++) {
|
|
17
|
+
const job=jobs[i],file=documents[i].file,source=readFileSync(job.file,'utf8'),resources={};
|
|
18
|
+
// Resolve only contained local resources; remote URLs remain ordinary remote links.
|
|
19
|
+
const refs=[
|
|
20
|
+
...Array.from(source.matchAll(/!?\[[^\]]*\]\(\s*(?:<([^>]+)>|([^\s)]+))/g),m=>m[1] || m[2]),
|
|
21
|
+
...Array.from(source.matchAll(/^ {0,3}\[[^\]]+\]:\s*(?:<([^>]+)>|(\S+))/gm),m=>m[1] || m[2]),
|
|
22
|
+
...Array.from(source.matchAll(/<(?:img|a)\b[^>]*?\b(?:src|href)\s*=\s*(?:"([^"]+)"|'([^']+)')/gi),m=>m[1] || m[2])
|
|
23
|
+
];
|
|
24
|
+
for(const ref of refs) {
|
|
25
|
+
if(/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref))continue;
|
|
26
|
+
try {
|
|
27
|
+
const url=new URL(ref,'https://clado.local/documents/'+file);
|
|
28
|
+
if(!url.pathname.startsWith('/documents/'))continue;
|
|
29
|
+
const name=decodeURIComponent(url.pathname.slice(11)),type=mime[name.split('.').pop().toLowerCase()];
|
|
30
|
+
if(!type)continue;
|
|
31
|
+
const path=workspacePath(root,name,false,true);
|
|
32
|
+
if(existsSync(path))resources[name]='data:'+type+';base64,'+readFileSync(path).toString('base64');
|
|
33
|
+
}catch{}
|
|
34
|
+
}
|
|
35
|
+
let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true});
|
|
36
|
+
const end=html.lastIndexOf('</body>');
|
|
37
|
+
const boot='window.__CLADO_OFFLINE__=true;window.__CLADO_FILE_PATH__='+json(file)+';window.__CLADO_WORKSPACE_INDEX__='+json(index)+';window.__CLADO_RESOURCES__='+json(resources)+';';
|
|
38
|
+
html=html.slice(0,end)+script(boot)+script(read('library-canvas.js'))+html.slice(end);
|
|
39
|
+
// Store identical renderer/style blocks once, then hydrate each iframe locally.
|
|
40
|
+
html=html.replace(/<(script|style)>([\s\S]*?)<\/\1>/g,(block)=>{
|
|
41
|
+
if(block.length<4096)return block;
|
|
42
|
+
if(!assetIds.has(block)){assetIds.set(block,shared.length);shared.push(block);}
|
|
43
|
+
return '<!--CLADO-ASSET:'+assetIds.get(block)+'-->';
|
|
44
|
+
});
|
|
45
|
+
canvases[file]=html;sources[file]=source;
|
|
46
|
+
}
|
|
47
|
+
let html=read('library.html');
|
|
48
|
+
html=html.replace('<link rel="stylesheet" href="library.css">',()=>'<style>'+read('library.css')+'</style>');
|
|
49
|
+
html=html.replace('<script src="/tree.js"></script>',()=>script(read('tree.js')));
|
|
50
|
+
html=html.replace('<script src="library.js"></script>',()=>script('window.__CLADO_WORKSPACE__='+json({entry,mode,theme,offline:{index,canvases,sources,shared}})+';')+script(read('library.js')));
|
|
51
|
+
html=html.replace('<title>Clado · Markdown 目录预览</title>','<title>'+String(title || 'Clado').replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'}[c]))+'</title>');
|
|
52
|
+
return html;
|
|
53
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { dirname, resolve, basename, join, relative } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { renderHtml } from '../html/page.js';
|
|
7
|
+
import { scanDirectory, workspacePath, readDocument, writeDocument, mutateNode, inspectSource, DocumentError } from '../workspace/documents.js';
|
|
8
|
+
const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
|
|
9
|
+
const resourceTypes = {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'};
|
|
10
|
+
const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
|
|
11
|
+
export function createWorkspaceHandler(directory, options = {}) {
|
|
12
|
+
const root = resolve(directory), token = randomBytes(24).toString('hex');
|
|
13
|
+
const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js','editor.js','editor.css','tree.js']);
|
|
14
|
+
const send = (res, status, type, body) => { res.writeHead(status, { 'content-type': type + '; charset=utf-8', 'cache-control':'no-store', 'x-content-type-options':'nosniff' }); res.end(body); };
|
|
15
|
+
const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
|
|
16
|
+
const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
|
|
17
|
+
return async function handle(req, res, url) {
|
|
18
|
+
const route = url.pathname.slice(1);
|
|
19
|
+
if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !(options.entrypoint && route === '')) return false;
|
|
20
|
+
try {
|
|
21
|
+
const host = req.headers.host;
|
|
22
|
+
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
|
|
23
|
+
if (req.headers.origin && req.headers.origin !== 'http://' + host) throw new DocumentError('来源不匹配。',403);
|
|
24
|
+
if (req.method === 'POST') {
|
|
25
|
+
if (req.headers['x-clado-token'] !== token) throw new DocumentError('编辑凭证不匹配,请刷新页面。',403);
|
|
26
|
+
if (!String(req.headers['content-type']).startsWith('application/json')) throw new DocumentError('只接受 JSON 请求。',415);
|
|
27
|
+
let body = ''; for await (const chunk of req) { body += chunk; if (Buffer.byteLength(body) > 2_000_000) throw new DocumentError('内容超过 2 MB。',413); }
|
|
28
|
+
const data = JSON.parse(body);
|
|
29
|
+
if (!data || Array.isArray(data) || typeof data !== 'object') throw new DocumentError('需要 JSON 对象。');
|
|
30
|
+
if (url.pathname === '/library/document' && !['create','update'].includes(data.action || 'update')) throw new DocumentError('文档操作只能是 create / update。');
|
|
31
|
+
const file = workspacePath(root, data.file, data.action === 'create');
|
|
32
|
+
if (data.action !== 'create' && !data.version) throw new DocumentError('保存前需要读取最新版本。',409);
|
|
33
|
+
let result;
|
|
34
|
+
if (url.pathname === '/library/document') result = writeDocument(file, data.source, { create: data.action === 'create', version: data.version });
|
|
35
|
+
else if (url.pathname === '/library/node') result = mutateNode(file, data.action, data);
|
|
36
|
+
else throw new DocumentError('没有这个编辑入口。',404);
|
|
37
|
+
json(res,200,{file:data.file,version:result.version,diagnostics:result.diagnostics}); return true;
|
|
38
|
+
}
|
|
39
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
|
|
40
|
+
if (assetNames.has(route) || (options.entrypoint && route === '')) {
|
|
41
|
+
const name = route || 'library.html'; let body = readFileSync(join(assets,name),'utf8');
|
|
42
|
+
if (name === 'library.html') {
|
|
43
|
+
body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'mindmap',theme:options.theme || 'light',entry:options.entry || ''})+';</script><script src="library.js">');
|
|
44
|
+
}
|
|
45
|
+
send(res,200,types[name.split('.').pop()],body); return true;
|
|
46
|
+
}
|
|
47
|
+
if (url.pathname === '/library/index.json') {
|
|
48
|
+
const result = scanDirectory(root);
|
|
49
|
+
json(res,200,{root:basename(root)+'/',documents:result.documents,skipped:result.skipped}); return true;
|
|
50
|
+
}
|
|
51
|
+
const name = url.searchParams.get('file');
|
|
52
|
+
if (url.pathname === '/library/resource') {
|
|
53
|
+
const type = resourceTypes[String(name).split('.').pop().toLowerCase()];
|
|
54
|
+
if (!type) throw new DocumentError('不支持的资源类型。',415);
|
|
55
|
+
const path=workspacePath(root,name,false,true);
|
|
56
|
+
res.writeHead(200,{'content-type':type,'x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; sandbox",'cache-control':'no-store'});res.end(readFileSync(path));return true;
|
|
57
|
+
}
|
|
58
|
+
const creating = url.pathname === '/library/new';
|
|
59
|
+
const file = creating ? null : workspacePath(root,name);
|
|
60
|
+
const item = creating ? inspectSource('# 新文档\n\n在文档视图中填写 Markdown,然后保存。\n') : readDocument(file);
|
|
61
|
+
if (url.pathname === '/library/source.md') { send(res,200,types.md,item.source); return true; }
|
|
62
|
+
if (url.pathname === '/library/document') {
|
|
63
|
+
json(res,200,{source:item.source,version:item.version,sections:item.sections,diagnostics:item.diagnostics}); return true;
|
|
64
|
+
}
|
|
65
|
+
if (url.pathname !== '/library/canvas' && !creating) throw new DocumentError('没有这个预览入口。',404);
|
|
66
|
+
if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('Markdown 暂时无法解析。',422,item.diagnostics);
|
|
67
|
+
const mode = creating ? 'doc' : ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
|
|
68
|
+
let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:options.theme || 'light',library:true});
|
|
69
|
+
html = html.replace('</head>','<link rel="stylesheet" href="/editor.css"></head>');
|
|
70
|
+
const bodyEnd = html.lastIndexOf('</body>');
|
|
71
|
+
html = html.slice(0,bodyEnd) + '<script>window.__CLADO_EDIT__='+safeJson({file:creating?'':name,token,create:creating})+';</script><script src="/library-canvas.js"></script><script src="/editor.js"></script>' + html.slice(bodyEnd);
|
|
72
|
+
send(res,200,types.html,html); return true;
|
|
73
|
+
} catch (error) {
|
|
74
|
+
json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || []}); return true;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry } = {}) {
|
|
79
|
+
const path = resolve(input);
|
|
80
|
+
if (statSync(path).isFile() && !/\.md$/i.test(path)) throw new DocumentError('serve 文件需要 .md 扩展名。');
|
|
81
|
+
const root = statSync(path).isDirectory() ? path : dirname(path);
|
|
82
|
+
const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
|
|
83
|
+
if (entryFile) {
|
|
84
|
+
const item=readDocument(workspacePath(root,entryFile));
|
|
85
|
+
if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
|
|
86
|
+
}
|
|
87
|
+
const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile});
|
|
88
|
+
const server = createServer(async (req,res) => {
|
|
89
|
+
try { if (!await handle(req,res,new URL(req.url,'http://127.0.0.1'))) { res.writeHead(404);res.end('Not found'); } }
|
|
90
|
+
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|
|
91
|
+
});
|
|
92
|
+
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
|
|
93
|
+
const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
|
|
94
|
+
return {server,url:'http://127.0.0.1:'+server.address().port+'/'+file,root};
|
|
95
|
+
}
|
package/src/skill/targets.js
CHANGED
|
@@ -148,21 +148,30 @@ export function findTarget(id) {
|
|
|
148
148
|
* @param {string} skillPath bundle 在本项目里的相对路径(正斜杠)
|
|
149
149
|
*/
|
|
150
150
|
export function ruleBody(skillPath) {
|
|
151
|
-
return `# clado ——
|
|
151
|
+
return `# clado —— Markdown 三视图工作区
|
|
152
152
|
|
|
153
|
-
这个项目用
|
|
154
|
-
同一份 \`.md\` 能长成 **文档 / 卡片 / 脑图** 三种模式,双击就能离线打开。
|
|
153
|
+
这个项目用 Clado 维护 Markdown 画布,在脑图、卡片和文档视图中讨论与迭代,也可打包成单个离线 HTML。
|
|
155
154
|
|
|
156
|
-
|
|
155
|
+
写或改画布前,先读 Skill 入口:
|
|
157
156
|
|
|
158
157
|
${skillPath}/SKILL.md
|
|
159
158
|
|
|
160
|
-
|
|
161
|
-
目标对不上就当普通链接、不报错)、表格 / 代码块 / Mermaid 怎么摆、八种诊断码各是什么意思。
|
|
159
|
+
再按当前任务加载它指向的 references 和案例;不要预先通读全部材料。指南说明如何拆文档、组织节点、表达流程关系、修改内容和检查交付。默认工作区为项目的 \`.clado/doc/\`,与 Skill 安装目录分开。
|
|
162
160
|
|
|
163
|
-
|
|
161
|
+
先确认 CLI 版本与能力:
|
|
164
162
|
|
|
165
|
-
|
|
166
|
-
clado
|
|
163
|
+
clado version
|
|
164
|
+
clado help
|
|
165
|
+
|
|
166
|
+
本文对应 0.4.0。若公共 npm 版本不含 init/serve/doc/node,请使用本次交付的源码,在源码目录运行 npm link,或运行 node /Clado源码路径/bin/clado.js;不要假设本次源码已经发布到公共 npm。
|
|
167
|
+
|
|
168
|
+
从项目根开始:
|
|
169
|
+
|
|
170
|
+
clado init
|
|
171
|
+
clado doc read .clado/doc/overview.md --json
|
|
172
|
+
clado serve --entry overview.md
|
|
173
|
+
clado build --entry overview.md --mode=cards
|
|
174
|
+
|
|
175
|
+
init 保留已有文件;先读后改。build 默认生成 clado.html,离线只读;网页编辑位于 serve 的文档视图左上角阅读/编辑切换中。工具不执行文档内的 SQL、脚本或上线步骤。
|
|
167
176
|
`;
|
|
168
177
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { readDocument, writeDocument, mutateNode, scanDirectory, DocumentError } from './documents.js';
|
|
4
|
+
export function runDocumentCommand(command, args, flags) {
|
|
5
|
+
const [action, input] = args;
|
|
6
|
+
if (!input) throw new DocumentError('用法:clado '+command+' <操作> <文件或目录>;查看 clado help。');
|
|
7
|
+
const file = resolve(input);
|
|
8
|
+
const content = () => {
|
|
9
|
+
if (flags['content-file'] === undefined) throw new DocumentError('需要 --content-file,写 - 从标准输入读取。');
|
|
10
|
+
return readFileSync(flags['content-file'] === '-' ? 0 : resolve(flags['content-file']),'utf8');
|
|
11
|
+
};
|
|
12
|
+
let result;
|
|
13
|
+
if (command === 'doc') {
|
|
14
|
+
if (action === 'list') {
|
|
15
|
+
if (!statSync(file).isDirectory()) throw new DocumentError('doc list 需要目录。');
|
|
16
|
+
const {documents,skipped} = scanDirectory(file); result={documents,skipped};
|
|
17
|
+
} else if (action === 'read') {
|
|
18
|
+
const item = readDocument(file); result={file:input,source:item.source,version:item.version,sections:item.sections,diagnostics:item.diagnostics};
|
|
19
|
+
} else if (action === 'create') {
|
|
20
|
+
const title=flags.title || '新画布';
|
|
21
|
+
if (/[\r\n]/.test(title)) throw new DocumentError('--title 必须是单行。');
|
|
22
|
+
const source = flags['content-file'] !== undefined ? content() : '---\ntitle: '+JSON.stringify(title)+'\n---\n\n# '+title+'\n\n描述目标、范围、输入和预期结果。\n';
|
|
23
|
+
const item=writeDocument(file,source,{create:true});result={file:input,version:item.version,diagnostics:item.diagnostics};
|
|
24
|
+
} else if (action === 'update') {
|
|
25
|
+
const item=writeDocument(file,content(),{version:flags['if-version']});result={file:input,version:item.version,diagnostics:item.diagnostics};
|
|
26
|
+
} else throw new DocumentError('doc 支持 list / read / create / update。');
|
|
27
|
+
} else {
|
|
28
|
+
if (!['add','update'].includes(action)) throw new DocumentError('node 支持 add / update。');
|
|
29
|
+
if (action==='update' && flags['content-file'] === undefined) throw new DocumentError('node update 需要 --content-file;清空正文时提供空文件。');
|
|
30
|
+
if (action==='update' && !flags.target) throw new DocumentError('node update 需要 --target 完整节点路径。');
|
|
31
|
+
const item=mutateNode(file,action,{parent:flags.parent,target:flags.target,title:flags.title,
|
|
32
|
+
content:flags['content-file'] !== undefined ? content() : '',version:flags['if-version']});
|
|
33
|
+
result={file:input,version:item.version,diagnostics:item.diagnostics};
|
|
34
|
+
}
|
|
35
|
+
if (flags.json) process.stdout.write(JSON.stringify(result,null,2)+'\n');
|
|
36
|
+
else if (!flags.quiet) {
|
|
37
|
+
if (command==='doc' && action==='read') process.stdout.write(result.source);
|
|
38
|
+
else if (action==='list') { for (const item of result.documents) process.stdout.write(item.file+'\t'+item.title+'\n'); if(result.skipped.length)process.stderr.write(result.skipped.length+' 份 Markdown 未收录;--json 查看原因。\n'); }
|
|
39
|
+
else process.stdout.write('已保存 '+input+'\n');
|
|
40
|
+
}
|
|
41
|
+
return 0;
|
|
42
|
+
}
|