inkmap-mcp 0.0.0-stage → 0.2.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.
package/bin/inkmap.cjs ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ require("../dist/cli.cjs").main(process.argv.slice(2)).catch(err => {
4
+ console.error(err instanceof Error ? err.message : err);
5
+ process.exit(1);
6
+ });
@@ -0,0 +1,24 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#4f8cff"/>
5
+ <stop offset="1" stop-color="#2848c8"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect x="8" y="8" width="240" height="240" rx="52" fill="url(#bg)"/>
9
+ <g fill="none" stroke="#fff" stroke-width="10" stroke-linecap="round" opacity="0.9">
10
+ <path d="M128 128 C 160 128, 160 74, 192 74"/>
11
+ <path d="M128 128 L 192 128"/>
12
+ <path d="M128 128 C 160 128, 160 182, 192 182"/>
13
+ <path d="M128 128 C 96 128, 96 92, 64 92"/>
14
+ <path d="M128 128 C 96 128, 96 164, 64 164"/>
15
+ </g>
16
+ <g fill="#fff">
17
+ <rect x="178" y="62" width="44" height="24" rx="12"/>
18
+ <rect x="178" y="116" width="44" height="24" rx="12"/>
19
+ <rect x="178" y="170" width="44" height="24" rx="12"/>
20
+ <rect x="34" y="80" width="44" height="24" rx="12"/>
21
+ <rect x="34" y="152" width="44" height="24" rx="12"/>
22
+ </g>
23
+ <path d="M128 92 C 128 92, 102 122, 102 140 A 26 26 0 0 0 154 140 C 154 122, 128 92, 128 92 Z" fill="#ffd166" stroke="#fff" stroke-width="6" stroke-linejoin="round"/>
24
+ </svg>
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "inkmap": {
4
+ "command": "node",
5
+ "args": ["${PLUGIN_ROOT}/server.cjs"]
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "inkmap",
3
+ "displayName": "Inkmap",
4
+ "version": "0.2.0",
5
+ "description": "MCP App mind map editor for local Markdown (.md, .markmap.md) outlines: auto-opens in the Antigravity side pane with live file write-back and Mermaid diagram editing. 在右侧面板自动打开并实时编辑 Markdown 思维导图。",
6
+ "logo": "assets/logo.svg",
7
+ "homepage": "https://www.zhiyuanv.com/software.html",
8
+ "repository": "https://github.com/zhiyuanvision-lang/InkMap",
9
+ "suggestedPrompts": [
10
+ "用 Inkmap 在右侧打开当前项目的 Markdown 思维导图",
11
+ "把这份设计文档整理成 Markdown 大纲并用 Inkmap 打开",
12
+ "Open this Markdown outline in Inkmap mind map"
13
+ ]
14
+ }
@@ -0,0 +1,628 @@
1
+ (function () {
2
+ const isZh = () => /^zh\b/i.test(localStorage.getItem("inkmap.language") || navigator.language || "zh");
3
+ const text = (zh, en) => (isZh() ? zh : en);
4
+
5
+ window.INKMAP_ASSET_BASE = "/api/doc-asset?path=";
6
+ window.INKMAP_LOCALE = navigator.language;
7
+
8
+ const params = new URLSearchParams(window.location.search);
9
+ const initialRequestedFile = params.get("file") || "";
10
+
11
+ let workspaceUris = [];
12
+ let currentFile = null;
13
+ let currentFileUri = null;
14
+ let currentVersion = "";
15
+ let currentMd = "";
16
+ let targetSeq = 0;
17
+ let saving = false;
18
+
19
+ const apiFetch = async (path, options = {}) => {
20
+ const fn = window.sidecar?.fetch ? window.sidecar.fetch.bind(window.sidecar) : window.fetch.bind(window);
21
+ const method = (options.method || "GET").toUpperCase();
22
+ const res = await fn(path, {
23
+ ...options,
24
+ method,
25
+ headers: {
26
+ "Content-Type": "application/json",
27
+ ...(options.headers || {}),
28
+ },
29
+ });
30
+ const data = await res.json().catch(() => ({}));
31
+ if (!res.ok) throw new Error(data.error || `${path}: ${res.status}`);
32
+ return data;
33
+ };
34
+
35
+ const debugLog = (event, detail = {}) => {
36
+ void apiFetch("/api/debug", {
37
+ method: "POST",
38
+ body: JSON.stringify({ event, ...detail, href: window.location.href, ts: Date.now() }),
39
+ }).catch(() => {});
40
+ };
41
+
42
+ window.addEventListener("error", e => {
43
+ debugLog("window.error", { message: e.message, filename: e.filename, lineno: e.lineno });
44
+ });
45
+ window.addEventListener("unhandledrejection", e => {
46
+ debugLog("unhandledrejection", { reason: String(e.reason?.stack || e.reason) });
47
+ });
48
+ window.addEventListener("message", e => {
49
+ if (e.data && typeof e.data === "object" && e.data.type === "__inkmap_debug") {
50
+ debugLog(e.data.event || "client.debug", e.data);
51
+ }
52
+ });
53
+ debugLog("bridge.loaded");
54
+
55
+ const emitToEditor = msg => {
56
+ window.postMessage(msg, "*");
57
+ };
58
+
59
+ async function resolveWorkspaces() {
60
+ if (!window.sidecar?.getWorkspaceUris) return workspaceUris;
61
+ try {
62
+ const uris = await Promise.race([
63
+ window.sidecar.getWorkspaceUris(),
64
+ new Promise(resolve => setTimeout(() => resolve([]), 600)),
65
+ ]);
66
+ if (Array.isArray(uris) && uris.length) workspaceUris = uris;
67
+ } catch {}
68
+ return workspaceUris;
69
+ }
70
+
71
+ let fileSelectEl = null;
72
+ let openRawBtn = null;
73
+ let splitMdBtn = null;
74
+ let mdPaneEl = null;
75
+ let mdTextareaEl = null;
76
+ let mdTitleEl = null;
77
+ let splitOpen = false;
78
+ let splitWidthPct = 42;
79
+ let mdEditTimer = 0;
80
+
81
+ function syncMdPaneContent(md = currentMd, force = false) {
82
+ if (mdTitleEl) {
83
+ const fileName = currentFile ? currentFile.split(/[\\/]/).pop() : "Markdown";
84
+ mdTitleEl.textContent = fileName;
85
+ mdTitleEl.title = currentFile || fileName;
86
+ }
87
+ if (!mdTextareaEl) return;
88
+ if (force || document.activeElement !== mdTextareaEl) {
89
+ if (mdTextareaEl.value !== md) mdTextareaEl.value = md;
90
+ }
91
+ }
92
+
93
+ function applySplitLayout(fitAfter = false) {
94
+ document.documentElement.classList.toggle("ag-split-active", splitOpen);
95
+ document.documentElement.style.setProperty("--ag-split-left", `${splitWidthPct}vw`);
96
+ if (mdPaneEl) mdPaneEl.hidden = !splitOpen;
97
+ if (splitMdBtn) {
98
+ splitMdBtn.dataset.active = splitOpen ? "true" : "false";
99
+ splitMdBtn.textContent = splitOpen ? text("仅留导图", "Map Only") : text("左MD/右导图", "Split MD");
100
+ splitMdBtn.title = splitOpen
101
+ ? text("关闭左侧 Markdown,仅保留右侧思维导图", "Close left Markdown pane and keep mind map only")
102
+ : text("开启左 Markdown 文件、右思维导图分屏对比与编辑", "Split screen: Markdown on left, Mind Map on right");
103
+ }
104
+ if (splitOpen) syncMdPaneContent(currentMd, true);
105
+ requestAnimationFrame(() => {
106
+ try {
107
+ window.inkmap?.mindMap?.resize();
108
+ if (fitAfter) window.inkmap?.mindMap?.view?.fit();
109
+ } catch {}
110
+ });
111
+ }
112
+
113
+ function renderFilePicker(files = [], selected = currentFile) {
114
+ if (!fileSelectEl) return;
115
+ fileSelectEl.innerHTML = "";
116
+ if (!files.length) {
117
+ const opt = document.createElement("option");
118
+ opt.value = "";
119
+ opt.textContent = text("未找到 Markdown 文件", "No Markdown files");
120
+ fileSelectEl.appendChild(opt);
121
+ fileSelectEl.disabled = true;
122
+ if (openRawBtn) openRawBtn.disabled = true;
123
+ return;
124
+ }
125
+ fileSelectEl.disabled = false;
126
+ if (openRawBtn) openRawBtn.disabled = !selected;
127
+
128
+ const activeFiles = files.filter(f => f.group === "active");
129
+ const projectFiles = files.filter(f => f.group !== "active");
130
+
131
+ const appendOptions = (parent, list) => {
132
+ for (const item of list) {
133
+ const opt = document.createElement("option");
134
+ opt.value = item.path;
135
+ opt.textContent = item.label;
136
+ opt.title = item.path;
137
+ if (item.path === selected) opt.selected = true;
138
+ parent.appendChild(opt);
139
+ }
140
+ };
141
+
142
+ if (activeFiles.length && projectFiles.length) {
143
+ const g1 = document.createElement("optgroup");
144
+ g1.label = text("当前工作区", "Active Workspace");
145
+ appendOptions(g1, activeFiles);
146
+ const g2 = document.createElement("optgroup");
147
+ g2.label = text("其他项目", "Other Projects");
148
+ appendOptions(g2, projectFiles);
149
+ fileSelectEl.append(g1, g2);
150
+ } else {
151
+ appendOptions(fileSelectEl, files);
152
+ }
153
+ }
154
+
155
+ async function switchFile(filePath) {
156
+ if (!filePath || filePath === currentFile) return;
157
+ try {
158
+ const data = await apiFetch("/api/open", {
159
+ method: "POST",
160
+ body: JSON.stringify({ workspaceUris, file: filePath }),
161
+ });
162
+ currentFile = data.currentFile;
163
+ currentFileUri = data.currentFileUri;
164
+ currentVersion = data.doc.version;
165
+ currentMd = data.doc.md;
166
+ targetSeq = data.targetSeq || targetSeq;
167
+ renderFilePicker(data.files, currentFile);
168
+ pushDocToEditor(data.doc);
169
+ setTimeout(() => {
170
+ try { window.inkmap?.mindMap?.view?.fit(); } catch {}
171
+ }, 120);
172
+ } catch (err) {
173
+ console.error("Failed to switch file:", err);
174
+ }
175
+ }
176
+
177
+ function mountToolbarControls() {
178
+ const bar = document.getElementById("bar");
179
+ if (!bar || document.getElementById("ag-file-select")) return;
180
+
181
+ const style = document.createElement("style");
182
+ style.textContent = `
183
+ html, body { margin: 0; height: 100%; overflow: hidden; background: var(--ink-bg) !important; color: var(--ui-text) !important; }
184
+ #map { position: fixed; inset: 0; width: 100vw; height: 100vh; transition: left .12s ease, width .12s ease; }
185
+ :root.ag-split-active #map { left: var(--ag-split-left, 42vw); width: calc(100vw - var(--ag-split-left, 42vw)); }
186
+ #ag-file-select { max-width: 200px; font-weight: 550; text-overflow: ellipsis; overflow: hidden; }
187
+ #ag-open-raw, #ag-split-md { display: inline-flex; align-items: center; gap: 4px; font-size: 12px; }
188
+ #ag-split-md[data-active="true"] { background: color-mix(in srgb, var(--ui-primary, #336df4) 14%, transparent); color: var(--ui-primary, #336df4); font-weight: 600; }
189
+ #ag-md-pane {
190
+ position: fixed; top: calc(var(--toolbar-height, 40px) + 18px); left: 12px; bottom: 12px;
191
+ width: calc(var(--ag-split-left, 42vw) - 16px); z-index: 30;
192
+ display: flex; flex-direction: column;
193
+ background: var(--ui-solid, #fff); color: var(--ui-text, #1f2329);
194
+ border: 1px solid var(--ui-border-strong, rgba(31,35,41,.15)); border-radius: 10px;
195
+ box-shadow: var(--ui-shadow, 0 4px 16px rgba(31,35,41,.08)); overflow: hidden;
196
+ }
197
+ #ag-md-pane[hidden] { display: none !important; }
198
+ .ag-md-header {
199
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
200
+ padding: 7px 10px; border-bottom: 1px solid var(--ui-border, rgba(31,35,41,.09));
201
+ background: var(--ui-subtle, #f6f7f9); font-size: 12px;
202
+ }
203
+ .ag-md-title {
204
+ font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0;
205
+ }
206
+ .ag-md-actions { display: inline-flex; align-items: center; gap: 4px; flex: none; }
207
+ .ag-md-close {
208
+ border: 1px solid var(--ui-border-strong, rgba(31,35,41,.15)); background: var(--ui-solid, #fff);
209
+ color: var(--ui-text, #1f2329); border-radius: 5px; padding: 2px 8px; font-size: 11.5px; cursor: pointer;
210
+ }
211
+ .ag-md-close:hover { background: var(--ui-hover, rgba(31,35,41,.06)); }
212
+ #ag-md-textarea {
213
+ flex: 1; width: 100%; box-sizing: border-box; border: 0; outline: none; resize: none;
214
+ padding: 12px 14px; background: var(--ui-solid, #fff); color: var(--ui-text, #1f2329);
215
+ font: 12.5px/1.6 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
216
+ tab-size: 2;
217
+ }
218
+ #ag-md-resizer {
219
+ position: absolute; top: 0; right: 0; bottom: 0; width: 5px; cursor: col-resize;
220
+ background: transparent;
221
+ }
222
+ #ag-md-resizer:hover { background: color-mix(in srgb, var(--ui-primary, #336df4) 35%, transparent); }
223
+ `;
224
+ document.head.appendChild(style);
225
+
226
+ fileSelectEl = document.createElement("select");
227
+ fileSelectEl.id = "ag-file-select";
228
+ fileSelectEl.setAttribute("aria-label", text("选择 Markdown 文件", "Select Markdown file"));
229
+ fileSelectEl.title = text("切换要编辑的 Markdown 导图文件", "Switch Markdown file");
230
+ fileSelectEl.addEventListener("change", () => {
231
+ if (fileSelectEl.value) void switchFile(fileSelectEl.value);
232
+ fileSelectEl.blur();
233
+ });
234
+
235
+ splitMdBtn = document.createElement("button");
236
+ splitMdBtn.id = "ag-split-md";
237
+ splitMdBtn.type = "button";
238
+ splitMdBtn.addEventListener("click", () => {
239
+ splitOpen = !splitOpen;
240
+ applySplitLayout(true);
241
+ splitMdBtn.blur();
242
+ });
243
+
244
+ openRawBtn = document.createElement("button");
245
+ openRawBtn.id = "ag-open-raw";
246
+ openRawBtn.type = "button";
247
+ openRawBtn.textContent = text("原文件", "Raw");
248
+ openRawBtn.title = text("在编辑器中打开 Markdown 原文件(也可关闭原文件仅留导图)", "Open raw Markdown file in editor");
249
+ openRawBtn.addEventListener("click", () => {
250
+ if (currentFileUri) {
251
+ if (window.sidecar?.openUrl) {
252
+ window.sidecar.openUrl(currentFileUri);
253
+ } else if (window.sidecar?.ui?.toggleAuxPane) {
254
+ window.sidecar.ui.toggleAuxPane({ tabType: "fileView", uri: currentFileUri });
255
+ }
256
+ }
257
+ openRawBtn.blur();
258
+ });
259
+
260
+ const sep = document.createElement("span");
261
+ sep.className = "sep";
262
+
263
+ bar.prepend(fileSelectEl, splitMdBtn, openRawBtn, sep);
264
+
265
+ mdPaneEl = document.createElement("aside");
266
+ mdPaneEl.id = "ag-md-pane";
267
+ mdPaneEl.hidden = true;
268
+ mdPaneEl.innerHTML = `
269
+ <div class="ag-md-header">
270
+ <span class="ag-md-title" id="ag-md-title">Markdown</span>
271
+ <div class="ag-md-actions">
272
+ <button type="button" class="ag-md-close" id="ag-md-close"></button>
273
+ </div>
274
+ </div>
275
+ <textarea id="ag-md-textarea" spellcheck="false"></textarea>
276
+ <div id="ag-md-resizer" title="拖拽调整分屏宽度"></div>
277
+ `;
278
+ document.body.appendChild(mdPaneEl);
279
+ mdTitleEl = document.getElementById("ag-md-title");
280
+ mdTextareaEl = document.getElementById("ag-md-textarea");
281
+ const closeBtn = document.getElementById("ag-md-close");
282
+ if (closeBtn) {
283
+ closeBtn.textContent = text("× 关闭MD(仅留导图)", "× Close MD");
284
+ closeBtn.title = text("关闭左侧 Markdown 面板,只保留思维导图", "Close Markdown pane and keep mind map only");
285
+ closeBtn.addEventListener("click", () => {
286
+ splitOpen = false;
287
+ applySplitLayout(true);
288
+ });
289
+ }
290
+ if (mdTextareaEl) {
291
+ mdTextareaEl.addEventListener("input", () => {
292
+ const nextMd = mdTextareaEl.value;
293
+ currentMd = nextMd;
294
+ clearTimeout(mdEditTimer);
295
+ mdEditTimer = window.setTimeout(() => {
296
+ if (window.inkmap?.load) {
297
+ void window.inkmap.load(nextMd, true);
298
+ }
299
+ }, 320);
300
+ });
301
+ }
302
+ const resizer = document.getElementById("ag-md-resizer");
303
+ if (resizer) {
304
+ resizer.addEventListener("pointerdown", e => {
305
+ e.preventDefault();
306
+ resizer.setPointerCapture(e.pointerId);
307
+ const onMove = ev => {
308
+ const pct = Math.max(24, Math.min(68, (ev.clientX / Math.max(1, window.innerWidth)) * 100));
309
+ splitWidthPct = Math.round(pct * 10) / 10;
310
+ applySplitLayout(false);
311
+ };
312
+ const onUp = () => {
313
+ resizer.removeEventListener("pointermove", onMove);
314
+ resizer.removeEventListener("pointerup", onUp);
315
+ resizer.removeEventListener("pointercancel", onUp);
316
+ try { window.inkmap?.mindMap?.view?.fit(); } catch {}
317
+ };
318
+ resizer.addEventListener("pointermove", onMove);
319
+ resizer.addEventListener("pointerup", onUp);
320
+ resizer.addEventListener("pointercancel", onUp);
321
+ });
322
+ }
323
+ applySplitLayout(false);
324
+ }
325
+
326
+ if (document.readyState === "loading") {
327
+ document.addEventListener("DOMContentLoaded", mountToolbarControls);
328
+ } else {
329
+ mountToolbarControls();
330
+ }
331
+
332
+ let readyReceived = false;
333
+ let initialDocSent = false;
334
+ let lastLicense = { pro: false };
335
+
336
+ function pushDocToEditor(doc, license = lastLicense) {
337
+ if (!doc) return;
338
+ if (license) lastLicense = license;
339
+ syncMdPaneContent(doc.md, true);
340
+ if (!initialDocSent) {
341
+ if (!readyReceived) return;
342
+ initialDocSent = true;
343
+ debugLog("emit.doc", { name: doc.name, mdLen: doc.md?.length });
344
+ emitToEditor({
345
+ type: "doc",
346
+ doc,
347
+ license: lastLicense || { pro: false },
348
+ ads: [],
349
+ chat: true,
350
+ });
351
+ setTimeout(() => {
352
+ const mapEl = document.getElementById("map");
353
+ debugLog("map.check.500ms", {
354
+ hasInkmap: Boolean(window.inkmap),
355
+ mapChildren: mapEl ? mapEl.children.length : -1,
356
+ mapRect: mapEl ? mapEl.getBoundingClientRect() : null,
357
+ innerW: window.innerWidth,
358
+ innerH: window.innerHeight,
359
+ bodyText: document.body?.innerText?.slice(0, 120),
360
+ });
361
+ }, 500);
362
+ setTimeout(() => {
363
+ const mapEl = document.getElementById("map");
364
+ debugLog("map.check.2500ms", {
365
+ hasInkmap: Boolean(window.inkmap),
366
+ mapChildren: mapEl ? mapEl.children.length : -1,
367
+ mapRect: mapEl ? mapEl.getBoundingClientRect() : null,
368
+ innerW: window.innerWidth,
369
+ innerH: window.innerHeight,
370
+ bodyText: document.body?.innerText?.slice(0, 120),
371
+ });
372
+ }, 2500);
373
+ } else {
374
+ debugLog("emit.change", { name: doc.name, mdLen: doc.md?.length });
375
+ emitToEditor({ type: "change", doc });
376
+ }
377
+ }
378
+
379
+ if (window.sidecar?.onWorkspaceChange) {
380
+ window.sidecar.onWorkspaceChange(async nextUris => {
381
+ workspaceUris = Array.isArray(nextUris) ? nextUris : [];
382
+ debugLog("workspace.change", { workspaceUris });
383
+ try {
384
+ const data = await apiFetch("/api/init", {
385
+ method: "POST",
386
+ body: JSON.stringify({ workspaceUris }),
387
+ });
388
+ if (data.targetSeq) targetSeq = data.targetSeq;
389
+ if (data.license) lastLicense = data.license;
390
+ renderFilePicker(data.files, currentFile || data.currentFile);
391
+ if (!currentFile && data.currentFile) {
392
+ currentFile = data.currentFile;
393
+ currentFileUri = data.currentFileUri;
394
+ currentVersion = data.doc.version;
395
+ currentMd = data.doc.md;
396
+ pushDocToEditor(data.doc, data.license);
397
+ }
398
+ } catch (err) {
399
+ debugLog("workspace.change.err", { error: String(err) });
400
+ }
401
+ });
402
+ }
403
+
404
+ // Poll for external file edits or AI skill file switches (`select.mjs`).
405
+ setInterval(async () => {
406
+ if (!initialDocSent || saving) return;
407
+ try {
408
+ const res = await apiFetch("/api/poll", {
409
+ method: "POST",
410
+ body: JSON.stringify({
411
+ ...(currentFile && { file: currentFile }),
412
+ ...(currentVersion && { version: currentVersion }),
413
+ targetSeq: String(targetSeq),
414
+ }),
415
+ });
416
+ if (res.targetSeq) targetSeq = res.targetSeq;
417
+ if (res.switchedFile && res.doc) {
418
+ currentFile = res.switchedFile;
419
+ currentFileUri = res.currentFileUri;
420
+ currentVersion = res.doc.version;
421
+ currentMd = res.doc.md;
422
+ const initData = await apiFetch("/api/init", {
423
+ method: "POST",
424
+ body: JSON.stringify({ workspaceUris, requestedFile: currentFile }),
425
+ }).catch(() => null);
426
+ if (initData?.files) renderFilePicker(initData.files, currentFile);
427
+ pushDocToEditor(res.doc, initData?.license);
428
+ setTimeout(() => {
429
+ try { window.inkmap?.mindMap?.view?.fit(); } catch {}
430
+ }, 120);
431
+ } else if (res.changed && res.doc) {
432
+ currentVersion = res.doc.version;
433
+ currentMd = res.doc.md;
434
+ pushDocToEditor(res.doc);
435
+ }
436
+ } catch {}
437
+ }, 1200);
438
+
439
+ function sliceLines(md, startLine, endLine, subText) {
440
+ if (subText) return subText;
441
+ const lines = String(md || "").split("\n");
442
+ const s = Math.max(0, Math.min(startLine ?? 0, lines.length - 1));
443
+ const e = Math.max(s, Math.min(endLine ?? s, lines.length - 1));
444
+ return lines.slice(s, e + 1).join("\n");
445
+ }
446
+
447
+ window.acquireVsCodeApi = () => ({
448
+ async postMessage(msg) {
449
+ if (!msg || typeof msg !== "object") return;
450
+ debugLog("postMessage", { type: msg.type });
451
+ try {
452
+ switch (msg.type) {
453
+ case "ready": {
454
+ readyReceived = true;
455
+ await resolveWorkspaces();
456
+ mountToolbarControls();
457
+ const data = await apiFetch("/api/init", {
458
+ method: "POST",
459
+ body: JSON.stringify({ workspaceUris, requestedFile: initialRequestedFile }),
460
+ });
461
+ currentFile = data.currentFile;
462
+ currentFileUri = data.currentFileUri;
463
+ currentVersion = data.doc.version;
464
+ currentMd = data.doc.md;
465
+ targetSeq = data.targetSeq || 0;
466
+ lastLicense = data.license || { pro: false };
467
+ renderFilePicker(data.files, currentFile);
468
+ pushDocToEditor(data.doc, lastLicense);
469
+ return;
470
+ }
471
+ case "save": {
472
+ saving = true;
473
+ try {
474
+ const res = await apiFetch("/api/save", {
475
+ method: "POST",
476
+ body: JSON.stringify({
477
+ workspaceUris,
478
+ file: currentFile,
479
+ md: msg.md,
480
+ baseVersion: msg.baseVersion,
481
+ }),
482
+ });
483
+ if (res.conflict && res.doc) {
484
+ currentVersion = res.doc.version;
485
+ currentMd = res.doc.md;
486
+ syncMdPaneContent(currentMd, true);
487
+ emitToEditor({ type: "conflict", id: msg.id, doc: res.doc });
488
+ } else {
489
+ currentVersion = res.version;
490
+ currentMd = msg.md;
491
+ syncMdPaneContent(currentMd, false);
492
+ emitToEditor({ type: "saved", id: msg.id, version: res.version });
493
+ }
494
+ } finally {
495
+ saving = false;
496
+ }
497
+ return;
498
+ }
499
+ case "viewState": {
500
+ if (!currentFile) return;
501
+ void apiFetch("/api/view", {
502
+ method: "POST",
503
+ body: JSON.stringify({ workspaceUris, file: currentFile, state: msg.state }),
504
+ }).catch(() => {});
505
+ return;
506
+ }
507
+ case "undo": {
508
+ window.inkmap?.mindMap?.execCommand("BACK");
509
+ return;
510
+ }
511
+ case "redo": {
512
+ window.inkmap?.mindMap?.execCommand("FORWARD");
513
+ return;
514
+ }
515
+ case "addToChat": {
516
+ if (!currentFile) return;
517
+ const snippet = sliceLines(currentMd, msg.startLine, msg.endLine, msg.text);
518
+ if (window.sidecar?.ui?.addArtifactComment && currentFileUri) {
519
+ window.sidecar.ui.addArtifactComment({
520
+ uri: currentFileUri,
521
+ comment: snippet,
522
+ selection: {
523
+ startLine: (msg.startLine ?? 0) + 1,
524
+ endLine: (msg.endLine ?? msg.startLine ?? 0) + 1,
525
+ },
526
+ pageTitle: currentFile.split(/[\\/]/).pop() || "Inkmap",
527
+ });
528
+ } else if (window.sidecar?.agent?.sendMessage && window.sidecar.conversationId) {
529
+ await window.sidecar.agent.sendMessage(
530
+ `来自 \`${currentFile}\`(第 ${(msg.startLine ?? 0) + 1}–${(msg.endLine ?? 0) + 1} 行):\n\`\`\`markdown\n${snippet}\n\`\`\``,
531
+ window.sidecar.conversationId,
532
+ );
533
+ }
534
+ return;
535
+ }
536
+ case "checkout": {
537
+ const res = await apiFetch("/api/checkout", {
538
+ method: "POST",
539
+ body: JSON.stringify({ mode: msg.mode }),
540
+ });
541
+ emitToEditor({ type: "checkout", id: msg.id });
542
+ // Poll license state after checkout link opens
543
+ const checkTimer = setInterval(async () => {
544
+ const state = await apiFetch("/api/license", { method: "GET" }).catch(() => null);
545
+ if (state) emitToEditor({ type: "license", state });
546
+ if (state?.pro || state?.connected) clearInterval(checkTimer);
547
+ }, 3000);
548
+ setTimeout(() => clearInterval(checkTimer), 120_000);
549
+ if (res.url && !window.sidecar) window.open(res.url, "_blank", "noopener,noreferrer");
550
+ return;
551
+ }
552
+ case "orderPro": {
553
+ const { result } = await apiFetch("/api/order-pro", {
554
+ method: "POST",
555
+ body: "{}",
556
+ });
557
+ emitToEditor({ type: "proOrder", id: msg.id, result });
558
+ if (result?.status === "qr" || result?.status === "redirect") {
559
+ const checkTimer = setInterval(async () => {
560
+ const state = await apiFetch("/api/license", { method: "GET" }).catch(() => null);
561
+ if (state) emitToEditor({ type: "license", state });
562
+ if (state?.pro) clearInterval(checkTimer);
563
+ }, 3000);
564
+ setTimeout(() => clearInterval(checkTimer), 15 * 60_000);
565
+ }
566
+ return;
567
+ }
568
+ case "sendPhoneCode": {
569
+ const { result } = await apiFetch("/api/phone-send", {
570
+ method: "POST",
571
+ body: JSON.stringify({ phone: msg.phone }),
572
+ });
573
+ emitToEditor({ type: "phoneCodeSent", id: msg.id, result });
574
+ return;
575
+ }
576
+ case "signInByPhone": {
577
+ const { result } = await apiFetch("/api/phone-verify", {
578
+ method: "POST",
579
+ body: JSON.stringify({ phone: msg.phone, code: msg.code }),
580
+ });
581
+ emitToEditor({ type: "phoneSignIn", id: msg.id, result });
582
+ return;
583
+ }
584
+ case "signOut": {
585
+ const { state } = await apiFetch("/api/signout", { method: "POST", body: "{}" });
586
+ emitToEditor({ type: "signedOut", id: msg.id });
587
+ if (state) emitToEditor({ type: "license", state });
588
+ return;
589
+ }
590
+ case "saveFile": {
591
+ const a = document.createElement("a");
592
+ a.href = msg.dataUrl;
593
+ a.download = msg.name;
594
+ a.click();
595
+ emitToEditor({ type: "fileSaved", id: msg.id, saved: true });
596
+ return;
597
+ }
598
+ }
599
+ } catch (err) {
600
+ debugLog("postMessage.error", { type: msg.type, error: String(err?.stack || err) });
601
+ if ("id" in msg) {
602
+ emitToEditor({
603
+ type: "error",
604
+ id: msg.id,
605
+ message: err instanceof Error ? err.message : String(err),
606
+ });
607
+ }
608
+ }
609
+ },
610
+ });
611
+
612
+ // Restore keyboard undo/redo since VsCodeHost removes simple-mind-map's default Control+z / Control+y
613
+ window.addEventListener("keydown", e => {
614
+ if (e.defaultPrevented || e.isComposing) return;
615
+ const tag = (e.target?.tagName || "").toUpperCase();
616
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || e.target?.isContentEditable) return;
617
+ if ((e.metaKey || e.ctrlKey) && !e.altKey) {
618
+ const k = e.key.toLowerCase();
619
+ if (k === "z" && !e.shiftKey) {
620
+ e.preventDefault();
621
+ window.inkmap?.mindMap?.execCommand("BACK");
622
+ } else if ((k === "z" && e.shiftKey) || (k === "y" && !e.shiftKey)) {
623
+ e.preventDefault();
624
+ window.inkmap?.mindMap?.execCommand("FORWARD");
625
+ }
626
+ }
627
+ });
628
+ })();