@wagq/dsh-obsidian 0.0.0-stage → 1.1.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.
package/client.js ADDED
@@ -0,0 +1,1331 @@
1
+ /**
2
+ * 浏览器端:@wagq/dsh-obsidian —— 知识库工作区
3
+ *
4
+ * 三栏布局:
5
+ * 左:文件库(类型筛选 chip + 搜索 + 文件夹/笔记树)
6
+ * 中:文档(面包屑 + 标题 + 标签 + 元信息 chip + 正文渲染/编辑)
7
+ * 右:大纲(标题跳转)与关联笔记(反链/出链)
8
+ */
9
+ window.__ModuleLoader__.load({
10
+ id: '@wagq/dsh-obsidian',
11
+ factory(require) {
12
+ const React = require('react');
13
+ const h = React.createElement;
14
+
15
+ const PANEL_ID = 'wagq-dsh-obsidian';
16
+ const NS = 'kb-panel';
17
+ const API = '/kb/api';
18
+ const RAW = '/kb/raw';
19
+
20
+ const DICT = {
21
+ zh: {
22
+ panel: '知识库', vault: '知识库',
23
+ files: '文件库', search: '搜标题、标签或正文…', all: '全部', notes: '笔记',
24
+ pdf: 'PDF', images: '图片', others: '其他', folders: '文件夹',
25
+ newNote: '新建笔记', newFolder: '新建文件夹', refresh: '刷新',
26
+ preview: '预览', outline: '大纲', related: '关联', edit: '编辑', save: '保存',
27
+ saved: '已保存', saving: '保存中…', cancel: '取消', delete: '删除', rename: '重命名',
28
+ fullscreen: '全屏', exitFullscreen: '退出全屏', more: '更多', unsaved: '未保存',
29
+ selectNote: '从左侧选择一篇笔记开始阅读', empty: '这里还没有内容',
30
+ noOutline: '这篇笔记还没有标题', noRelated: '还没有关联笔记',
31
+ noResult: '没有匹配的内容', notConnected: '未连接知识库',
32
+ notConnectedHint: '请先在 Obsidian 中打开一个 vault,再点刷新。',
33
+ words: '字', chars: '字符', lines: '行', modified: '修改',
34
+ reading: '只读渲染', editing: '编辑中', linkOut: '出链', linkIn: '反链',
35
+ pathPlaceholder: '例如:00-收件箱/新笔记', confirmDelete: '确定把这篇笔记移入回收站?',
36
+ today: '今天', yesterday: '昨天', previewNote: '预览', backlinksTitle: '关联笔记',
37
+ toc: '大纲', untitled: '未命名', loading: '加载中…',
38
+ ask: '问答', askPlaceholder: '问整个知识库…(Ctrl+Enter 发送)', askSend: '提问',
39
+ asking: '正在检索并回答…', evidenceOnly: '未接入模型,已返回最相关的笔记片段',
40
+ citations: '出处', noEvidence: '知识库里没有找到相关内容', clear: '清空',
41
+ discardChanges: '当前笔记有未保存的更改,确定放弃并打开其他笔记?', searching: '搜索中…',
42
+ reload: '重新检测', create: '创建', continue: '继续', created: '已创建',
43
+ switchVault: '切换知识库 vault', noVaults: '没有发现其它 vault。请先在 Obsidian 中打开一个库。',
44
+ newMenu: '新建', createVault: '新建知识库项目', createVaultTitle: '新建知识库项目 — 位置', createVaultName: '新建知识库项目 — 名称',
45
+ next: '下一步', confirmDeleteFolder: '确定删除这个文件夹?(整棵子树移入 .trash)', deleted: '已删除', renamed: '已重命名', renameFolder: '重命名文件夹',
46
+ noteNamePlaceholder: '输入笔记名,如:产品需求(自动加 .md)',
47
+ folderNamePlaceholder: '输入文件夹名,如:需求文档',
48
+ open: '打开', hintContextMenu: '右键:新建 / 重命名 / 删除',
49
+ },
50
+ en: {
51
+ panel: 'Knowledge base', vault: 'Knowledge base',
52
+ files: 'Library', search: 'Search titles, tags or text…', all: 'All', notes: 'Notes',
53
+ pdf: 'PDF', images: 'Images', others: 'Others', folders: 'Folders',
54
+ newNote: 'New note', newFolder: 'New folder', refresh: 'Refresh',
55
+ preview: 'Preview', outline: 'Outline', related: 'Related', edit: 'Edit', save: 'Save',
56
+ saved: 'Saved', saving: 'Saving…', cancel: 'Cancel', delete: 'Delete', rename: 'Rename',
57
+ fullscreen: 'Fullscreen', exitFullscreen: 'Exit fullscreen', more: 'More', unsaved: 'Unsaved',
58
+ selectNote: 'Pick a note on the left to read', empty: 'Nothing here yet',
59
+ noOutline: 'No headings in this note', noRelated: 'No related notes',
60
+ noResult: 'No matches', notConnected: 'Not connected',
61
+ notConnectedHint: 'Open a vault in Obsidian, then refresh.',
62
+ words: 'words', chars: 'chars', lines: 'lines', modified: 'Modified',
63
+ reading: 'Rendered', editing: 'Editing', linkOut: 'outgoing', linkIn: 'backlinks',
64
+ pathPlaceholder: 'e.g. 00-inbox/New note', confirmDelete: 'Move this note to trash?',
65
+ today: 'Today', yesterday: 'Yesterday', previewNote: 'Preview', backlinksTitle: 'Related notes',
66
+ toc: 'Outline', untitled: 'Untitled', loading: 'Loading…',
67
+ ask: 'Q&A', askPlaceholder: 'Ask across the vault… (Ctrl+Enter)', askSend: 'Ask',
68
+ asking: 'Retrieving and answering…', evidenceOnly: 'No model attached — showing the most relevant passages',
69
+ citations: 'Sources', noEvidence: 'Nothing relevant found in the vault', clear: 'Clear',
70
+ discardChanges: 'This note has unsaved changes. Discard and open another note?', searching: 'Searching…',
71
+ reload: 'Redetect', create: 'Create', continue: 'Continue', created: 'Created',
72
+ switchVault: 'Switch vault', noVaults: 'No other vault found. Open one in Obsidian first.',
73
+ newMenu: 'New', createVault: 'New knowledge base project', createVaultTitle: 'New knowledge base — location', createVaultName: 'New knowledge base — name',
74
+ next: 'Next', confirmDeleteFolder: 'Delete this folder? (whole subtree moves to .trash)', deleted: 'Deleted', renamed: 'Renamed', renameFolder: 'Rename folder',
75
+ noteNamePlaceholder: 'Note name, e.g. Product brief (.md added)',
76
+ folderNamePlaceholder: 'Folder name, e.g. Requirements',
77
+ open: 'Open', hintContextMenu: 'Right-click: new / rename / delete',
78
+ },
79
+ };
80
+ let t = k => (DICT.en[k] ?? k);
81
+
82
+ async function api(path, body) {
83
+ const opt = body === undefined
84
+ ? { method: 'GET' }
85
+ : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) };
86
+ const r = await fetch(`${API}/${path}`, opt);
87
+ const ct = r.headers.get('content-type') || '';
88
+ if (!ct.includes('json')) throw new Error(`HTTP ${r.status}`);
89
+ return r.json();
90
+ }
91
+
92
+ const fmtDate = ms => {
93
+ if (!ms) return '';
94
+ const d = new Date(ms);
95
+ const p = n => String(n).padStart(2, '0');
96
+ return `${d.getFullYear()}/${p(d.getMonth() + 1)}/${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
97
+ };
98
+ const fmtSize = n => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(0)} KB` : `${(n / 1048576).toFixed(1)} MB`);
99
+
100
+ // ── 极简 Markdown 渲染(标题/段落/列表/引用/代码/表格/链接/wikilink)──
101
+ function inline(text, key) {
102
+ const nodes = [];
103
+ let rest = String(text);
104
+ let i = 0;
105
+ const push = (node) => nodes.push(node);
106
+ const patterns = [
107
+ { re: /^`([^`]+)`/, make: m => h('code', { key: `c${key}-${i++}`, style: { background: 'var(--dsw-alias-bg-layer-2)', padding: '1px 5px', borderRadius: 4, fontSize: '0.92em', fontFamily: 'ui-monospace, monospace' } }, m[1]) },
108
+ { re: /^\*\*([^*]+)\*\*/, make: m => h('strong', { key: `b${key}-${i++}` }, m[1]) },
109
+ { re: /^\*([^*]+)\*/, make: m => h('em', { key: `i${key}-${i++}` }, m[1]) },
110
+ { re: /^\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/, make: m => h('span', { key: `w${key}-${i++}`, style: { color: 'var(--dsw-alias-brand-primary)', borderBottom: '1px dashed currentColor' }, title: m[1] }, m[2] || m[1]) },
111
+ { re: /^\[([^\]]+)\]\(([^)]+)\)/, make: m => h('a', { key: `a${key}-${i++}`, href: m[2], target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-brand-primary)' } }, m[1]) },
112
+ { re: /^#([\p{L}\p{N}_\-/]+)/u, make: m => h('span', { key: `t${key}-${i++}`, style: { color: 'var(--dsw-alias-brand-primary)' } }, `#${m[1]}`) },
113
+ ];
114
+ while (rest.length) {
115
+ let matched = false;
116
+ for (const p of patterns) {
117
+ const m = rest.match(p.re);
118
+ if (m) { push(p.make(m)); rest = rest.slice(m[0].length); matched = true; break; }
119
+ }
120
+ if (matched) continue;
121
+
122
+ // 找到最近的下一个可匹配起点,把之前的纯文本一次性输出
123
+ let cut = rest.length;
124
+ for (const p of patterns) {
125
+ const probe = rest.slice(1);
126
+ const idx = probe.search(new RegExp(p.re.source));
127
+ if (idx >= 0) cut = Math.min(cut, idx + 1);
128
+ }
129
+ if (cut <= 1) { push(rest[0]); rest = rest.slice(1); }
130
+ else { push(rest.slice(0, cut)); rest = rest.slice(cut); }
131
+ }
132
+ return nodes;
133
+ }
134
+
135
+ function renderMarkdown(src, onHeading) {
136
+ const lines = String(src || '').replace(/\r/g, '').split('\n');
137
+ const out = [];
138
+ let i = 0, k = 0, hIndex = -1;
139
+ const H = (level, children, id) => h(`h${level}`, {
140
+ key: `h${k++}`, id: id !== undefined ? `kb-h-${id}` : undefined,
141
+ onClick: id !== undefined && onHeading ? () => onHeading(id) : undefined,
142
+ style: {
143
+ margin: level <= 2 ? '22px 0 10px' : '18px 0 8px',
144
+ fontSize: level === 1 ? 26 : level === 2 ? 21 : level === 3 ? 17.5 : 15.5,
145
+ fontWeight: level <= 2 ? 700 : 600,
146
+ lineHeight: 1.35,
147
+ color: 'var(--dsw-alias-label-primary)',
148
+ cursor: id && onHeading ? 'pointer' : 'default',
149
+ },
150
+ }, ...children);
151
+
152
+ while (i < lines.length) {
153
+ const line = lines[i];
154
+ if (/^\s*$/.test(line)) { i++; continue; }
155
+
156
+ if (/^\s*```/.test(line)) {
157
+ const buf = [];
158
+ i++;
159
+ while (i < lines.length && !/^\s*```/.test(lines[i])) buf.push(lines[i++]);
160
+ i++;
161
+ out.push(h('pre', {
162
+ key: `pre${k++}`,
163
+ style: {
164
+ background: 'var(--dsw-alias-bg-layer-2)', border: '1px solid var(--dsw-alias-border-l1)',
165
+ borderRadius: 8, padding: '12px 14px', overflowX: 'auto', margin: '12px 0',
166
+ fontSize: 12.5, lineHeight: 1.6, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
167
+ },
168
+ }, h('code', null, buf.join('\n'))));
169
+ continue;
170
+ }
171
+
172
+ const hm = line.match(/^(#{1,6})\s+(.+?)\s*$/);
173
+ if (hm) {
174
+ const level = hm[1].length;
175
+ const text = hm[2];
176
+ const hid = String(++hIndex);
177
+ out.push(H(level, inline(text, `hd${k}`), hid));
178
+ i++;
179
+ continue;
180
+ }
181
+
182
+ if (/^\s*(---|\*\*\*|___)\s*$/.test(line)) {
183
+ out.push(h('hr', { key: `hr${k++}`, style: { border: 'none', borderTop: '1px solid var(--dsw-alias-border-l1)', margin: '20px 0' } }));
184
+ i++;
185
+ continue;
186
+ }
187
+
188
+ if (/^\s*>\s?/.test(line)) {
189
+ const buf = [];
190
+ while (i < lines.length && /^\s*>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^\s*>\s?/, ''));
191
+ out.push(h('blockquote', {
192
+ key: `bq${k++}`,
193
+ style: {
194
+ margin: '12px 0', padding: '8px 14px', borderLeft: '3px solid var(--dsw-alias-brand-primary)',
195
+ background: 'var(--dsw-alias-bg-layer-2)', borderRadius: '0 6px 6px 0',
196
+ color: 'var(--dsw-alias-label-secondary)',
197
+ },
198
+ }, ...buf.filter(Boolean).map((b, bi) => h('div', { key: bi, style: { margin: '3px 0' } }, inline(b, `bq${k}-${bi}`)))));
199
+ continue;
200
+ }
201
+
202
+ if (/^\s*([-*+]|\d+\.)\s+/.test(line)) {
203
+ const items = [];
204
+ const ordered = /^\s*\d+\./.test(line);
205
+ while (i < lines.length && /^\s*([-*+]|\d+\.)\s+/.test(lines[i])) {
206
+ items.push(lines[i].replace(/^\s*([-*+]|\d+\.)\s+/, ''));
207
+ i++;
208
+ }
209
+ const Tag = ordered ? 'ol' : 'ul';
210
+ out.push(h(Tag, {
211
+ key: `list${k++}`,
212
+ style: { margin: '10px 0', paddingLeft: 22, lineHeight: 1.75 },
213
+ }, ...items.map((it, ii) => h('li', { key: ii, style: { margin: '2px 0' } }, inline(it, `li${k}-${ii}`)))));
214
+ continue;
215
+ }
216
+
217
+ // 表格
218
+ if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1])) {
219
+ const head = line.split('|').slice(1, -1).map(s => s.trim());
220
+ i += 2;
221
+ const rows = [];
222
+ while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
223
+ rows.push(lines[i].split('|').slice(1, -1).map(s => s.trim()));
224
+ i++;
225
+ }
226
+ out.push(h('div', { key: `tb${k++}`, style: { overflowX: 'auto', margin: '14px 0' } },
227
+ h('table', { style: { borderCollapse: 'collapse', width: '100%', fontSize: 13 } },
228
+ h('thead', null, h('tr', null, ...head.map((c, ci) => h('th', {
229
+ key: ci,
230
+ style: { textAlign: 'left', padding: '8px 10px', borderBottom: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-2)', fontWeight: 600 },
231
+ }, inline(c, `th${k}-${ci}`))))),
232
+ h('tbody', null, ...rows.map((r, ri) => h('tr', { key: ri }, ...r.map((c, ci) => h('td', {
233
+ key: ci,
234
+ style: { padding: '7px 10px', borderBottom: '1px solid var(--dsw-alias-border-l1)' },
235
+ }, inline(c, `td${k}-${ri}-${ci}`)))))),
236
+ )));
237
+ continue;
238
+ }
239
+
240
+ // 普通段落:合并连续行
241
+ const para = [line];
242
+ i++;
243
+ while (i < lines.length && !/^\s*$/.test(lines[i]) && !/^(#{1,6})\s|^\s*```|^\s*>|^\s*([-*+]|\d+\.)\s|^\s*\|/.test(lines[i])) {
244
+ para.push(lines[i++]);
245
+ }
246
+ out.push(h('p', {
247
+ key: `p${k++}`,
248
+ style: { margin: '11px 0', lineHeight: 1.85, fontSize: 14.5, color: 'var(--dsw-alias-label-primary)' },
249
+ }, ...inline(para.join(' '), `p${k}`)));
250
+ }
251
+ return out;
252
+ }
253
+
254
+ function BookGlyph({ size = 15 }) {
255
+ return h('svg', {
256
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
257
+ stroke: 'currentColor', strokeWidth: 2.1, strokeLinecap: 'round',
258
+ strokeLinejoin: 'round', 'aria-hidden': true, focusable: false,
259
+ style: { display: 'block', flexShrink: 0 },
260
+ },
261
+ h('rect', { x: 3.5, y: 3.5, width: 17, height: 17, rx: 3 }),
262
+ h('path', { d: 'M8 3.5v17' }),
263
+ h('path', { d: 'M11.5 8h5.5M11.5 12h5.5M11.5 16h3.5' }),
264
+ );
265
+ }
266
+
267
+ const Icon = ({ d, size = 14 }) => h('svg', {
268
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
269
+ stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round',
270
+ 'aria-hidden': true, focusable: false, style: { flexShrink: 0 },
271
+ }, h('path', { d }));
272
+
273
+ // ═══════════════ 主工作区 ═══════════════
274
+ function KnowledgePanel() {
275
+ const [status, setStatus] = React.useState(null);
276
+ const [files, setFiles] = React.useState([]);
277
+ const [filter, setFilter] = React.useState('all');
278
+ const [query, setQuery] = React.useState('');
279
+ const [results, setResults] = React.useState(null);
280
+ const [selected, setSelected] = React.useState('');
281
+ const [note, setNote] = React.useState(null);
282
+ const [related, setRelated] = React.useState([]);
283
+ const [draft, setDraft] = React.useState('');
284
+ const [mode, setMode] = React.useState('read');
285
+ const [rightTab, setRightTab] = React.useState('outline');
286
+ const [askQ, setAskQ] = React.useState('');
287
+ const [askBusy, setAskBusy] = React.useState(false);
288
+ const [askRes, setAskRes] = React.useState(null);
289
+ const [notice, setNotice] = React.useState('');
290
+ const [busy, setBusy] = React.useState(false);
291
+ const [collapsed, setCollapsed] = React.useState({});
292
+ const [full, setFull] = React.useState(false);
293
+ // 内联输入/确认:DSH 的 WebView 禁用了 window.prompt/confirm,必须自带
294
+ const [dialog, setDialog] = React.useState(null);
295
+ // dialog: { kind:'prompt'|'confirm', title, value, placeholder, confirmText, onOk }
296
+ const [picker, setPicker] = React.useState(null);
297
+ const [menu, setMenu] = React.useState(null);
298
+ const rootRef = React.useRef(null);
299
+ // 把视口坐标换算成面板内坐标
300
+ const toLocal = (clientX, clientY) => {
301
+ const r = rootRef.current?.getBoundingClientRect?.();
302
+ return r ? { x: clientX - r.left, y: clientY - r.top } : { x: 40, y: 40 };
303
+ };
304
+
305
+ const dirty = note && draft !== note.body;
306
+
307
+ const loadTree = React.useCallback(async () => {
308
+ try {
309
+ const r = await api('tree');
310
+ if (r.ok) setFiles(r.files || []);
311
+ } catch (e) { setNotice(String(e)); }
312
+ }, []);
313
+
314
+ const loadStatus = React.useCallback(async () => {
315
+ try { setStatus(await api('status')); } catch (e) { setNotice(String(e)); }
316
+ }, []);
317
+
318
+ React.useEffect(() => { loadStatus(); loadTree(); }, [loadStatus, loadTree]);
319
+
320
+ // 全屏时:Esc 退出、锁定页面滚动、卸载时复位
321
+ React.useEffect(() => {
322
+ if (!full) return undefined;
323
+ const onKey = e => { if (e.key === 'Escape') setFull(false); };
324
+ window.addEventListener('keydown', onKey);
325
+ const prevOverflow = document.body.style.overflow;
326
+ document.body.style.overflow = 'hidden';
327
+ return () => {
328
+ window.removeEventListener('keydown', onKey);
329
+ document.body.style.overflow = prevOverflow;
330
+ };
331
+ }, [full]);
332
+
333
+ const openNote = async (p) => {
334
+ if (dirty && p !== selected) {
335
+ const ok = await askConfirm({ title: t('discardChanges'), confirmText: t('continue') });
336
+ if (!ok) return;
337
+ }
338
+ setBusy(true);
339
+ try {
340
+ const r = await api(`note?path=${encodeURIComponent(p)}`);
341
+ if (!r.ok) { setNotice(r.error || 'open failed'); return; }
342
+ setSelected(p); setNote(r.note); setDraft(r.note.body); setMode('read'); setNotice('');
343
+ const rel = await api(`related?path=${encodeURIComponent(p)}`);
344
+ setRelated(rel.ok ? rel.related : []);
345
+ } catch (e) { setNotice(String(e)); }
346
+ finally { setBusy(false); }
347
+ };
348
+
349
+ const askVault = async () => {
350
+ const q = askQ.trim();
351
+ if (!q) return;
352
+ setAskBusy(true); setAskRes(null);
353
+ try {
354
+ const r = await api('ask', { question: q });
355
+ if (r.ok) setAskRes(r);
356
+ else setNotice(r.error || 'ask failed');
357
+ } catch (e) { setNotice(String(e)); }
358
+ finally { setAskBusy(false); }
359
+ };
360
+
361
+ const runSearch = React.useCallback(async (q) => {
362
+ setQuery(q);
363
+ if (!q.trim()) { setResults(null); return; }
364
+ try {
365
+ const r = await api(`search?query=${encodeURIComponent(q)}`);
366
+ setResults(r.ok ? r.results : []);
367
+ } catch (e) { setNotice(String(e)); }
368
+ }, []);
369
+
370
+ const save = async () => {
371
+ if (!note) return;
372
+ // DSH WebView 中 React 受控 textarea 的 onChange 偶发不更新 draft;
373
+ // 这里直接读 DOM 当前值兜底,保证「保存」一定能拿到用户看到的内容。
374
+ const el = rootRef.current?.querySelector?.('[data-kb-editor]');
375
+ const content = el && typeof el.value === 'string' ? el.value : draft;
376
+ setBusy(true);
377
+ try {
378
+ const r = await api('save', { path: note.path, content });
379
+ if (r.ok) {
380
+ const fresh = await api(`note?path=${encodeURIComponent(note.path)}`);
381
+ if (fresh.ok) { setNote(fresh.note); setDraft(fresh.note.body); }
382
+ else setDraft(content);
383
+ setMode('read');
384
+ setNotice(t('saved')); loadTree();
385
+ } else setNotice(r.error || 'save failed');
386
+ } catch (e) { setNotice(String(e)); }
387
+ finally { setBusy(false); }
388
+ };
389
+
390
+ const cancelEdit = () => {
391
+ setDraft(note?.body ?? '');
392
+ setMode('read');
393
+ setNotice('');
394
+ };
395
+
396
+ // DSH 的 WebView 禁用了 window.prompt / window.confirm,
397
+ // 所有需要输入的交互都走这里的内联对话框。
398
+ // 用 ref 保存 resolve 与当前值,避免在闭包里读到过期的 state。
399
+ const dialogRef = React.useRef(null);
400
+ const dialogValueRef = React.useRef('');
401
+ const askPrompt = (opts) => new Promise(resolve => {
402
+ dialogRef.current = { kind: 'prompt', resolve };
403
+ dialogValueRef.current = opts.value ?? '';
404
+ setDialog({
405
+ kind: 'prompt',
406
+ title: opts.title,
407
+ value: opts.value ?? '',
408
+ placeholder: opts.placeholder ?? '',
409
+ confirmText: opts.confirmText ?? t('save'),
410
+ });
411
+ });
412
+ const askConfirm = (opts) => new Promise(resolve => {
413
+ dialogRef.current = { kind: 'confirm', resolve };
414
+ dialogValueRef.current = '';
415
+ setDialog({
416
+ kind: 'confirm',
417
+ title: opts.title,
418
+ confirmText: opts.confirmText ?? t('delete'),
419
+ });
420
+ });
421
+ const closeDialog = (value) => {
422
+ const pending = dialogRef.current;
423
+ dialogRef.current = null;
424
+ setDialog(null);
425
+ try { pending?.resolve?.(value); } catch { /* ignore */ }
426
+ };
427
+ const submitDialog = () => {
428
+ const pending = dialogRef.current;
429
+ const kind = pending?.kind;
430
+ dialogRef.current = null;
431
+ setDialog(null);
432
+ const value = kind === 'confirm' ? true : dialogValueRef.current;
433
+ try { pending?.resolve?.(value); } catch { /* ignore */ }
434
+ };
435
+
436
+ // 从当前 vault 路径推出父目录,作为新建项目的默认位置
437
+ const vaultParentGuess = () => {
438
+ const p = status?.vaultPath || '';
439
+ if (!p) return '';
440
+ const norm = p.replace(/\//g, '\\').replace(/\\+$/, '');
441
+ const idx = norm.lastIndexOf('\\');
442
+ return idx > 0 ? norm.slice(0, idx) : norm;
443
+ };
444
+
445
+ const switchVault = async (p) => { setPicker(null);
446
+ setBusy(true);
447
+ try {
448
+ const r = await api('switch', { path: p });
449
+ if (r.ok) {
450
+ setStatus(r);
451
+ setSelected(''); setNote(null); setDraft(''); setRelated([]); setResults(null); setQuery('');
452
+ await loadTree();
453
+ setNotice('');
454
+ } else setNotice(r.error || 'switch failed');
455
+ } catch (e) { setNotice(String(e)); }
456
+ finally { setBusy(false); }
457
+ };
458
+
459
+ const removeFolder = async (rel, name) => {
460
+ const ok = await askConfirm({
461
+ title: `${t('confirmDeleteFolder')}\n\n${rel}`,
462
+ confirmText: t('delete'),
463
+ });
464
+ if (!ok) return;
465
+ setBusy(true);
466
+ try {
467
+ const r = await api('rmdir', { path: rel });
468
+ if (r.ok) { await loadTree(); await loadStatus(); setNotice(`${t('deleted')}: ${rel}${r.result.files ? ` (${r.result.files} 个文件)` : ''}`); }
469
+ else setNotice(r.error || 'rmdir failed');
470
+ } catch (e) { setNotice(String(e)); }
471
+ finally { setBusy(false); }
472
+ };
473
+
474
+ const renameFolder = async (rel, name) => {
475
+ const to = await askPrompt({ title: t('renameFolder'), value: name, confirmText: t('save') });
476
+ if (!to || !to.trim() || to.trim() === name) return;
477
+ const parent = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
478
+ const target = parent ? `${parent}/${to.trim()}` : to.trim();
479
+ setBusy(true);
480
+ try {
481
+ const r = await api('move', { from: rel, to: target });
482
+ if (r.ok) { await loadTree(); setNotice(`${t('renamed')}: ${target}`); }
483
+ else setNotice(r.error || 'rename failed');
484
+ } catch (e) { setNotice(String(e)); }
485
+ finally { setBusy(false); }
486
+ };
487
+
488
+ const createVaultProject = async () => {
489
+ setPicker(null);
490
+ const parent = await askPrompt({
491
+ title: t('createVaultTitle'),
492
+ value: vaultParentGuess(),
493
+ placeholder: 'D:\\知识库',
494
+ confirmText: t('next'),
495
+ });
496
+ if (!parent || !parent.trim()) return;
497
+ const name = await askPrompt({
498
+ title: `${t('createVaultName')}\n${parent.trim()}`,
499
+ value: '',
500
+ placeholder: '我的新知识库',
501
+ confirmText: t('create'),
502
+ });
503
+ if (!name || !name.trim()) return;
504
+ setBusy(true);
505
+ try {
506
+ const r = await api('create-vault', { parent: parent.trim(), name: name.trim() });
507
+ if (r.ok) {
508
+ setStatus(r);
509
+ setSelected(''); setNote(null); setDraft(''); setRelated([]); setResults(null); setQuery('');
510
+ await loadTree();
511
+ setNotice(`${t('created')}: ${r.result.path}`);
512
+ } else setNotice(r.error || 'create vault failed');
513
+ } catch (e) { setNotice(String(e)); }
514
+ finally { setBusy(false); }
515
+ };
516
+
517
+ // parent:在哪个文件夹里新建(空字符串 = vault 根目录)
518
+ const joinPath = (parent, name) => (parent ? `${parent}/${name}` : name);
519
+
520
+ const createNote = async (parent = '') => {
521
+ const name = await askPrompt({
522
+ title: parent ? `${t('newNote')} · ${parent}` : t('newNote'),
523
+ placeholder: t('noteNamePlaceholder'),
524
+ confirmText: t('create'),
525
+ });
526
+ if (!name || !name.trim()) return;
527
+ const rel = joinPath(parent, name.trim().replace(/^\/+/, ''));
528
+ setBusy(true);
529
+ try {
530
+ const r = await api('create', { path: rel });
531
+ if (r.ok) { await loadTree(); await openNote(r.result.path); setNotice(''); }
532
+ else setNotice(r.error || 'create failed');
533
+ } catch (e) { setNotice(String(e)); }
534
+ finally { setBusy(false); }
535
+ };
536
+
537
+ const createFolder = async (parent = '') => {
538
+ const name = await askPrompt({
539
+ title: parent ? `${t('newFolder')} · ${parent}` : t('newFolder'),
540
+ placeholder: t('folderNamePlaceholder'),
541
+ confirmText: t('create'),
542
+ });
543
+ if (!name || !name.trim()) return;
544
+ const rel = joinPath(parent, name.trim().replace(/^\/+/, ''));
545
+ setBusy(true);
546
+ try {
547
+ const r = await api('mkdir', { path: rel });
548
+ if (r.ok) { await loadTree(); await loadStatus(); setNotice(`${t('created')}: ${r.result.path}`); }
549
+ else setNotice(r.error || 'mkdir failed');
550
+ } catch (e) { setNotice(String(e)); }
551
+ finally { setBusy(false); }
552
+ };
553
+
554
+ const removeNote = async () => {
555
+ if (!note) return;
556
+ if (!(await askConfirm({ title: t('confirmDelete'), confirmText: t('delete') }))) return;
557
+ try {
558
+ const r = await api('delete', { path: note.path });
559
+ if (r.ok) { setSelected(''); setNote(null); setDraft(''); setRelated([]); loadTree(); }
560
+ else setNotice(r.error || 'delete failed');
561
+ } catch (e) { setNotice(String(e)); }
562
+ };
563
+
564
+ const renameNote = async () => {
565
+ if (!note) return;
566
+ const to = await askPrompt({ title: t('rename'), value: note.path, confirmText: t('save') });
567
+ if (!to || to.trim() === note.path) return;
568
+ try {
569
+ if (dirty) await api('save', { path: note.path, content: draft });
570
+ const r = await api('move', { from: note.path, to: to.trim() });
571
+ if (r.ok) { await loadTree(); await openNote(r.result.to); }
572
+ else setNotice(r.error || 'rename failed');
573
+ } catch (e) { setNotice(String(e)); }
574
+ };
575
+
576
+ // 右键菜单里按路径重命名笔记
577
+ const renameNoteAt = async (rel) => {
578
+ const base = rel.split('/').pop() || rel;
579
+ const name = await askPrompt({ title: t('rename'), value: base.replace(/\.md$/i, ''), confirmText: t('save') });
580
+ if (!name || !name.trim()) return;
581
+ const parent = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '';
582
+ const target = joinPath(parent, name.trim().replace(/^\/+/, ''));
583
+ setBusy(true);
584
+ try {
585
+ if (selected === rel && dirty) await api('save', { path: rel, content: draft });
586
+ const r = await api('move', { from: rel, to: target });
587
+ if (r.ok) {
588
+ await loadTree();
589
+ if (selected === rel) await openNote(r.result.to);
590
+ setNotice(`${t('renamed')}: ${target}`);
591
+ } else setNotice(r.error || 'rename failed');
592
+ } catch (e) { setNotice(String(e)); }
593
+ finally { setBusy(false); }
594
+ };
595
+
596
+ // 右键菜单里按路径删除笔记
597
+ const removeNoteAt = async (rel) => {
598
+ const ok = await askConfirm({ title: `${t('confirmDelete')}\n\n${rel}`, confirmText: t('delete') });
599
+ if (!ok) return;
600
+ setBusy(true);
601
+ try {
602
+ const r = await api('delete', { path: rel });
603
+ if (r.ok) {
604
+ if (selected === rel) { setSelected(''); setNote(null); setDraft(''); setRelated([]); }
605
+ await loadTree(); await loadStatus();
606
+ setNotice(`${t('deleted')}: ${rel}`);
607
+ } else setNotice(r.error || 'delete failed');
608
+ } catch (e) { setNotice(String(e)); }
609
+ finally { setBusy(false); }
610
+ };
611
+
612
+ // ── 样式 ──
613
+ const C = {
614
+ text: 'var(--dsw-alias-label-primary, CanvasText)',
615
+ text2: 'var(--dsw-alias-label-secondary, GrayText)',
616
+ bg: 'var(--dsw-alias-bg-base, Canvas)',
617
+ bg1: 'var(--dsw-alias-bg-layer-1, Canvas)',
618
+ bg2: 'var(--dsw-alias-bg-layer-2, ButtonFace)',
619
+ overlay: 'var(--dsw-alias-bg-overlay, ButtonFace)',
620
+ line: 'var(--dsw-alias-border-l1, rgba(128,128,128,.22))',
621
+ line2: 'var(--dsw-alias-border-l2, rgba(128,128,128,.38))',
622
+ brand: 'var(--dsw-alias-brand-primary, #6b5cff)',
623
+ err: 'var(--dsw-alias-state-error-primary, #d33)',
624
+ warn: 'var(--dsw-alias-state-warn-primary, #c98b00)',
625
+ ok: 'var(--dsw-alias-state-success-primary, #2ea043)',
626
+ side: 'var(--dsw-specific-sidebar-fill, Canvas)',
627
+ onBrand: 'var(--dsw-alias-bg-base, #ffffff)',
628
+ };
629
+ const S = {
630
+ root: {
631
+ display: 'flex', height: full ? 'calc(100vh - 34px)' : '100%', minHeight: 0, boxSizing: 'border-box',
632
+ color: C.text, background: C.bg, fontSize: 13,
633
+ overflow: 'hidden',
634
+ position: full ? 'fixed' : 'relative',
635
+ ...(full
636
+ ? { top: 34, left: 0, right: 0, zIndex: 95, width: '100vw' }
637
+ : {}),
638
+ },
639
+ colLeft: {
640
+ width: 268, flexShrink: 0, display: 'flex', flexDirection: 'column', minHeight: 0,
641
+ borderRight: `1px solid ${C.line}`, background: C.side,
642
+ },
643
+ colMid: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', minHeight: 0, background: C.bg },
644
+ colRight: {
645
+ width: 252, flexShrink: 0, display: 'flex', flexDirection: 'column', minHeight: 0,
646
+ borderLeft: `1px solid ${C.line}`, background: C.side,
647
+ },
648
+ bar: { display: 'flex', alignItems: 'center', gap: 6, padding: '9px 10px', borderBottom: `1px solid ${C.line}`, flexShrink: 0 },
649
+ barTitle: { fontWeight: 600, fontSize: 13.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
650
+ iconBtn: {
651
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
652
+ border: 'none', background: 'transparent', color: C.text2, cursor: 'pointer',
653
+ borderRadius: 6, padding: '5px 7px', fontSize: 12, fontFamily: 'inherit',
654
+ },
655
+ btn: {
656
+ display: 'inline-flex', alignItems: 'center', gap: 5,
657
+ border: `1px solid ${C.line2}`, background: C.bg2, color: C.text,
658
+ borderRadius: 6, padding: '5px 10px', cursor: 'pointer', fontSize: 12, fontFamily: 'inherit',
659
+ },
660
+ btnOn: { background: C.bg1, color: C.text, borderColor: C.brand },
661
+ btnPrimary: {
662
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
663
+ border: `1px solid ${C.brand}`, background: C.brand, color: C.onBrand,
664
+ borderRadius: 6, padding: '6px 12px', cursor: 'pointer', fontSize: 12,
665
+ fontFamily: 'inherit', fontWeight: 600,
666
+ },
667
+ input: {
668
+ width: '100%', boxSizing: 'border-box', background: C.bg1, color: C.text,
669
+ border: `1px solid ${C.line}`, borderRadius: 6, padding: '6px 9px',
670
+ fontSize: 12, fontFamily: 'inherit', outline: 'none',
671
+ },
672
+ chips: { display: 'flex', gap: 6, flexWrap: 'wrap', padding: '8px 10px', borderBottom: `1px solid ${C.line}`, flexShrink: 0 },
673
+ chip: {
674
+ border: 'none', background: 'transparent', color: C.text2, cursor: 'pointer',
675
+ borderRadius: 999, padding: '3px 9px', fontSize: 11.5, fontFamily: 'inherit',
676
+ },
677
+ chipOn: {
678
+ background: C.bg1, color: C.text, fontWeight: 600,
679
+ boxShadow: `inset 0 0 0 1.5px ${C.brand}`,
680
+ padding: '3px 9px',
681
+ }, tree: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '6px 6px 14px' },
682
+ row: {
683
+ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 7px',
684
+ borderRadius: 5, cursor: 'pointer', fontSize: 12.5, color: C.text,
685
+ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
686
+ },
687
+ rowSel: { background: C.bg2, fontWeight: 600 },
688
+ rowText: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, textAlign: 'left' },
689
+ doc: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '22px 40px 80px' },
690
+ crumb: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 11.5, color: C.text2, marginBottom: 10, flexWrap: 'wrap' },
691
+ docTitle: { fontSize: 27, fontWeight: 700, lineHeight: 1.3, margin: '0 0 10px', letterSpacing: '-0.3px' },
692
+ tagRow: { display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 12 },
693
+ tag: {
694
+ fontSize: 11, padding: '2px 8px', borderRadius: 999,
695
+ border: `1px solid ${C.line2}`, color: C.text2, background: C.bg1,
696
+ },
697
+ metaRow: { display: 'flex', gap: 12, flexWrap: 'wrap', fontSize: 11.5, color: C.text2, marginBottom: 18, alignItems: 'center' },
698
+ loader: { fontSize: 11.5, color: C.text2, padding: '3px 8px', borderRadius: 5, background: C.bg2 },
699
+ textarea: {
700
+ display: 'block',
701
+ width: '100%',
702
+ boxSizing: 'border-box',
703
+ height: 460,
704
+ minHeight: 240,
705
+ resize: 'vertical',
706
+ background: C.bg2,
707
+ color: C.text,
708
+ border: `1px solid ${C.line2}`,
709
+ borderRadius: 8,
710
+ padding: 14,
711
+ fontSize: 13,
712
+ lineHeight: 1.85,
713
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
714
+ outline: 'none',
715
+ },
716
+ tabs: {
717
+ display: 'flex', gap: 2, padding: '0 6px', flexShrink: 0,
718
+ borderBottom: `1px solid ${C.line}`, minHeight: 41, alignItems: 'flex-end',
719
+ boxSizing: 'border-box',
720
+ },
721
+ tab: {
722
+ borderTop: 'none', borderLeft: 'none', borderRight: 'none',
723
+ background: 'transparent', color: C.text2, cursor: 'pointer',
724
+ padding: '8px 9px', fontSize: 12, fontFamily: 'inherit',
725
+ borderBottom: '2px solid transparent', marginBottom: -1, lineHeight: 1.5,
726
+ },
727
+ tabOn: { color: C.text, borderBottom: `2px solid ${C.brand}`, fontWeight: 600 },
728
+ rightBody: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '8px 8px 20px' },
729
+ outRow: {
730
+ display: 'block', width: '100%', textAlign: 'left', border: 'none',
731
+ background: 'transparent', color: C.text, cursor: 'pointer',
732
+ padding: '4px 8px', borderRadius: 5, fontSize: 12.5, fontFamily: 'inherit',
733
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
734
+ },
735
+ relRow: {
736
+ display: 'flex', alignItems: 'center', gap: 6, width: '100%',
737
+ border: 'none', background: 'transparent', color: C.text, cursor: 'pointer',
738
+ padding: '6px 8px', borderRadius: 5, fontSize: 12, fontFamily: 'inherit',
739
+ textAlign: 'left',
740
+ },
741
+ rowBtn: {
742
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
743
+ border: 'none', background: 'transparent', color: C.text2, cursor: 'pointer',
744
+ padding: 2, borderRadius: 4, opacity: 0.65, flexShrink: 0,
745
+ },
746
+ empty: { padding: 28, textAlign: 'center', color: C.text2, fontSize: 12.5, lineHeight: 1.8 },
747
+ notice: { margin: '0 10px 8px', fontSize: 11.5, color: C.warn, background: C.bg2, borderRadius: 6, padding: '6px 9px' },
748
+ badge: { fontSize: 10.5, padding: '1px 6px', borderRadius: 4, background: C.bg2, color: C.text2 },
749
+ menuGroup: { display: 'flex', flexDirection: 'column' },
750
+ menuSep: { height: 1, background: C.line, margin: '5px 4px' },
751
+ };
752
+
753
+ // 右键菜单条目
754
+ const menuItem = (label, d, fn, color) => h('button', {
755
+ style: {
756
+ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
757
+ border: 'none', background: 'transparent', color: color || C.text,
758
+ cursor: 'pointer', padding: '7px 9px', borderRadius: 6,
759
+ fontFamily: 'inherit', fontSize: 12.5,
760
+ },
761
+ onClick: fn,
762
+ },
763
+ h(Icon, { d, size: 13 }),
764
+ h('span', null, label),
765
+ );
766
+
767
+ const connected = status?.connected;
768
+
769
+ // 文件树分组
770
+ const filtered = React.useMemo(() => {
771
+ if (results) return results.map(r => ({ ...r, type: 'note', fromSearch: true }));
772
+ const list = filter === 'all' ? files : files.filter(f => f.type === filter);
773
+ return list;
774
+ }, [files, filter, results]);
775
+
776
+ const tree = React.useMemo(() => {
777
+ const root = { name: '', dirs: new Map(), files: [] };
778
+ const ensureDir = (segs) => {
779
+ let node = root;
780
+ for (const s of segs) {
781
+ if (!node.dirs.has(s)) node.dirs.set(s, { name: s, dirs: new Map(), files: [] });
782
+ node = node.dirs.get(s);
783
+ }
784
+ return node;
785
+ };
786
+ for (const f of filtered) {
787
+ const segs = f.path.split('/');
788
+ if (f.type === 'folder') {
789
+ // 空文件夹也要建出节点
790
+ ensureDir(segs);
791
+ continue;
792
+ }
793
+ const name = segs.pop();
794
+ const node = ensureDir(segs);
795
+ node.files.push({ ...f, name });
796
+ }
797
+ return root;
798
+ }, [filtered]);
799
+
800
+ const renderTree = (node, depth, prefix = '') => {
801
+ const items = [];
802
+ const dirs = [...node.dirs.entries()].sort((a, b) => a[0].localeCompare(b[0]));
803
+ for (const [name, child] of dirs) {
804
+ const id = `${depth}:${name}`;
805
+ const isOpen = !collapsed[id];
806
+ const dirRel = prefix ? `${prefix}/${name}` : name;
807
+ items.push(h('div', {
808
+ key: `d-${id}`,
809
+ 'data-kb-row': 'folder',
810
+ style: { ...S.row, paddingLeft: 7 + depth * 12, color: C.text2 },
811
+ onClick: () => setCollapsed(c => ({ ...c, [id]: !c[id] })),
812
+ onContextMenu: e => {
813
+ e.preventDefault();
814
+ e.stopPropagation();
815
+ setMenu({ kind: 'folder', path: dirRel, name, ...toLocal(e.clientX, e.clientY) });
816
+ },
817
+ title: `${dirRel}\n${t('hintContextMenu')}`,
818
+ },
819
+ h('span', { style: { width: 12, display: 'inline-flex', transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform .12s' } },
820
+ h(Icon, { d: 'M9 6l6 6-6 6', size: 11 })),
821
+ h('span', { style: S.rowText }, name),
822
+ h('button', {
823
+ style: S.rowBtn,
824
+ title: t('delete'),
825
+ onClick: e => { e.stopPropagation(); removeFolder(dirRel, name); },
826
+ }, h(Icon, { d: 'M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14', size: 11 })),
827
+ h('button', {
828
+ style: S.rowBtn,
829
+ title: t('rename'),
830
+ onClick: e => { e.stopPropagation(); renameFolder(dirRel, name); },
831
+ }, h(Icon, { d: 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z', size: 11 })),
832
+ ));
833
+ if (isOpen) items.push(...renderTree(child, depth + 1, dirRel));
834
+ }
835
+ const fs = node.files.slice().sort((a, b) => (b.mtime || 0) - (a.mtime || 0));
836
+ for (const f of fs) {
837
+ const isPdf = f.type === 'pdf';
838
+ const isImg = f.type === 'image';
839
+ const glyph = isPdf ? 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z'
840
+ : isImg ? 'M4 5h16v14H4zM4 15l5-5 5 5M15 12l5 5'
841
+ : 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5';
842
+ items.push(h('div', {
843
+ key: `f-${f.path}`,
844
+ 'data-kb-row': 'note',
845
+ style: { ...S.row, paddingLeft: 7 + depth * 12 + 12, ...(selected === f.path ? S.rowSel : {}) },
846
+ onClick: () => openNote(f.path),
847
+ onContextMenu: e => {
848
+ e.preventDefault();
849
+ e.stopPropagation();
850
+ setMenu({ kind: 'note', path: f.path, name: f.title || f.name, ...toLocal(e.clientX, e.clientY) });
851
+ },
852
+ title: `${f.path}\n${t('hintContextMenu')}`,
853
+ },
854
+ h('span', { style: { color: C.text2, display: 'inline-flex' } }, h(Icon, { d: glyph, size: 12 })),
855
+ h('span', { style: S.rowText }, f.title || f.name),
856
+ f.fromSearch && f.line ? h('span', { style: { ...S.badge, fontSize: 10 } }, `:${f.line}`) : null,
857
+ ));
858
+ }
859
+ return items;
860
+ };
861
+
862
+ const headings = note?.headings || [];
863
+ const jumpTo = (id) => {
864
+ const el = document.getElementById(`kb-h-${id}`);
865
+ if (el?.scrollIntoView) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
866
+ };
867
+
868
+ return h('div', { ref: rootRef, style: S.root, 'data-dsh-plugin': '@wagq/dsh-obsidian', 'data-dsh-part': 'kb-workspace' },
869
+
870
+ // ═════ 左:文件库 ═════
871
+ h('div', { style: S.colLeft },
872
+ h('div', { style: S.bar },
873
+ h('button', {
874
+ style: {
875
+ display: 'inline-flex', alignItems: 'center', gap: 6, flex: 1, minWidth: 0,
876
+ border: 'none', background: 'transparent', color: C.text, cursor: 'pointer',
877
+ padding: '3px 4px', borderRadius: 6, fontFamily: 'inherit', textAlign: 'left',
878
+ },
879
+ title: status?.vaultPath || t('files'),
880
+ onClick: async () => {
881
+ try {
882
+ const r = await api('vaults');
883
+ setPicker(r.ok ? (r.vaults || []) : []);
884
+ } catch { setPicker([]); }
885
+ },
886
+ },
887
+ h('span', { style: { display: 'inline-flex', color: C.brand } }, h(BookGlyph)),
888
+ h('span', { style: { ...S.barTitle, flex: 1 } }, status?.name || t('files')),
889
+ h('span', { style: { display: 'inline-flex', color: C.text2, transform: 'rotate(90deg)' } },
890
+ h(Icon, { d: 'M9 6l6 6-6 6', size: 10 })),
891
+ ),
892
+ h('button', {
893
+ style: S.iconBtn, title: t('newMenu'),
894
+ onClick: e => {
895
+ const r = e.currentTarget.getBoundingClientRect();
896
+ const p = toLocal(r.left, r.bottom + 4);
897
+ setMenu({ kind: 'new', x: p.x, y: p.y });
898
+ },
899
+ }, h(Icon, { d: 'M12 5v14M5 12h14' })),
900
+ h('button', { style: S.iconBtn, title: t('newFolder'), onClick: () => createFolder('') },
901
+ h(Icon, { d: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zM12 11v6M9 14h6' })),
902
+ h('button', { style: S.iconBtn, title: t('refresh'), onClick: () => { loadStatus(); loadTree(); } }, h(Icon, { d: 'M21 12a9 9 0 1 1-3-6.7M21 3v6h-6' })),
903
+ ),
904
+ h('div', { style: { padding: '8px 10px 0' } },
905
+ h('input', {
906
+ style: S.input, value: query, placeholder: t('search'),
907
+ onChange: e => runSearch(e.target.value),
908
+ 'aria-label': t('search'),
909
+ }),
910
+ ),
911
+ h('div', { style: S.chips },
912
+ ...[['all', t('all')], ['note', t('notes')], ['pdf', t('pdf')], ['image', t('images')], ['file', t('others')]].map(([k, label]) =>
913
+ h('button', {
914
+ key: k,
915
+ style: { ...S.chip, ...(filter === k && !results ? S.chipOn : {}) },
916
+ onClick: () => { setFilter(k); setResults(null); setQuery(''); },
917
+ }, label)),
918
+ ),
919
+ !connected && status
920
+ ? h('div', { style: { ...S.notice, margin: '8px 10px' } }, t('notConnectedHint'))
921
+ : null,
922
+ notice ? h('div', { style: S.notice }, notice) : null,
923
+ h('div', {
924
+ style: S.tree,
925
+ onContextMenu: e => {
926
+ if (e.target.closest && e.target.closest('[data-kb-row]')) return;
927
+ e.preventDefault();
928
+ setMenu({ kind: 'root', ...toLocal(e.clientX, e.clientY) });
929
+ },
930
+ },
931
+ filtered.length === 0
932
+ ? h('div', { style: S.empty }, results ? t('noResult') : t('empty'))
933
+ : renderTree(tree, 0),
934
+ ),
935
+ h('div', { style: { ...S.bar, borderBottom: 'none', borderTop: `1px solid ${C.line}`, justifyContent: 'space-between' } },
936
+ h('span', { style: { fontSize: 11, color: C.text2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
937
+ connected ? status?.vaultPath : t('notConnected')),
938
+ h('span', { style: { fontSize: 11, color: C.text2, flexShrink: 0 } },
939
+ connected ? `${status.counts.note} ${t('notes')} · ${status.counts.folders} ${t('folders')}` : ''),
940
+ ),
941
+ ),
942
+
943
+ // ═════ 中:文档 ═════
944
+ h('div', { style: S.colMid },
945
+ h('div', { style: S.bar },
946
+ h('span', { style: { ...S.barTitle, flex: 1 } }, note ? note.title : t('vault')),
947
+ note ? h('span', { style: { ...S.loader, color: dirty ? C.warn : C.text2 } },
948
+ dirty ? t('unsaved')
949
+ : note.kind === 'note' ? (mode === 'edit' ? t('editing') : t('reading'))
950
+ : note.kind === 'image' ? t('images')
951
+ : note.kind === 'pdf' ? t('pdf')
952
+ : fmtSize(note.size)) : null,
953
+ note ? h('button', {
954
+ style: { ...S.iconBtn, ...(mode === 'read' ? S.btnOn : {}) },
955
+ onClick: () => setMode('read'), title: t('preview'),
956
+ }, t('preview')) : null, note && note.kind === 'note' ? h('button', {
957
+ style: { ...S.iconBtn, ...(mode === 'edit' ? S.btnOn : {}) },
958
+ onClick: () => setMode('edit'), title: t('edit'),
959
+ }, t('edit')) : null,
960
+ note && (dirty || mode === 'edit') ? h('button', {
961
+ style: { ...S.btn, borderColor: C.brand, color: C.brand },
962
+ onClick: save,
963
+ onPointerDown: e => e.stopPropagation(),
964
+ disabled: busy,
965
+ }, busy ? t('saving') : t('save')) : null,
966
+ note ? h('button', { style: S.iconBtn, title: t('rename'), onClick: renameNote }, h(Icon, { d: 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z' })) : null,
967
+ note ? h('button', { style: S.iconBtn, title: t('delete'), onClick: removeNote }, h(Icon, { d: 'M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14', })) : null,
968
+ h('button', {
969
+ style: { ...S.iconBtn, ...(full ? S.btnOn : {}) },
970
+ title: full ? t('exitFullscreen') : t('fullscreen'),
971
+ onClick: () => setFull(f => !f),
972
+ }, h(Icon, { d: full ? 'M9 3v6H3M15 21v-6h6M3 15h6v6M21 9h-6V3' : 'M4 9V4h5M20 15v5h-5M20 9V4h-5M4 15v5h5' })),
973
+ ),
974
+
975
+ note
976
+ ? h('div', { style: S.doc },
977
+ h('div', { style: S.crumb },
978
+ ...note.path.split('/').map((seg, si, arr) =>
979
+ h('span', { key: si, style: { display: 'inline-flex', alignItems: 'center', gap: 5 } },
980
+ si > 0 ? h('span', { style: { opacity: .5 } }, '/') : null,
981
+ h('span', { style: si === arr.length - 1 ? { color: C.text } : undefined }, seg.replace(/\.(md|markdown)$/i, '')))),
982
+ ),
983
+ h('h1', { style: S.docTitle }, note.title),
984
+ note.tags.length
985
+ ? h('div', { style: S.tagRow }, ...note.tags.map(tag => h('span', { key: tag, style: S.tag }, `#${tag}`)))
986
+ : null,
987
+ h('div', { style: S.metaRow },
988
+ h('span', null, `📄 ${note.words} ${t('words')}`),
989
+ h('span', null, `↩ ${note.chars} ${t('chars')}`),
990
+ h('span', null, `☰ ${note.lines} ${t('lines')}`),
991
+ h('span', null, `🕒 ${fmtDate(note.mtime)}`),
992
+ h('span', { style: S.badge }, fmtSize(note.size)),
993
+ ),
994
+ mode === 'edit' && note.kind !== 'note' ? null : mode === 'edit'
995
+ ? h('textarea', {
996
+ style: S.textarea, value: draft ?? '', spellCheck: false,
997
+ 'data-kb-editor': '1',
998
+ onChange: e => setDraft(e.target.value),
999
+ onInput: e => setDraft(e.target.value),
1000
+ 'aria-label': note.title,
1001
+ })
1002
+ : note.kind === 'image'
1003
+ ? h('div', { style: { padding: '10px 0' } },
1004
+ h('img', {
1005
+ src: `${RAW}?path=${encodeURIComponent(note.path)}`,
1006
+ alt: note.title,
1007
+ style: { maxWidth: '100%', borderRadius: 8, border: `1px solid ${C.line}` },
1008
+ }))
1009
+ : note.kind === 'pdf'
1010
+ ? h('div', null,
1011
+ h('iframe', {
1012
+ src: `${RAW}?path=${encodeURIComponent(note.path)}`,
1013
+ title: note.title,
1014
+ style: { width: '100%', height: 620, border: `1px solid ${C.line}`, borderRadius: 8, background: C.bg1 },
1015
+ }),
1016
+ h('div', { style: { marginTop: 8, fontSize: 12, color: C.text2 } },
1017
+ h('a', { href: `${RAW}?path=${encodeURIComponent(note.path)}`, target: '_blank', rel: 'noreferrer', style: { color: C.brand } }, `↗ ${note.title}`)),
1018
+ )
1019
+ : note.kind && note.kind !== 'note'
1020
+ ? h('div', { style: S.empty },
1021
+ h('div', null, `${note.title} · ${fmtSize(note.size)}`),
1022
+ h('a', { href: `${RAW}?path=${encodeURIComponent(note.path)}`, target: '_blank', rel: 'noreferrer', style: { color: C.brand, fontSize: 12 } }, '↗ 下载/打开'))
1023
+ : h('div', null, ...renderMarkdown(note.body, jumpTo)),
1024
+ mode === 'edit'
1025
+ ? h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 14 } },
1026
+ h('button', {
1027
+ style: S.btn,
1028
+ onClick: cancelEdit,
1029
+ onPointerDown: e => e.stopPropagation(),
1030
+ disabled: busy,
1031
+ }, t('cancel')),
1032
+ h('button', {
1033
+ style: { ...S.btn, borderColor: C.brand, color: C.brand },
1034
+ onClick: save,
1035
+ onPointerDown: e => e.stopPropagation(),
1036
+ disabled: busy,
1037
+ }, busy ? t('saving') : t('save')),
1038
+ )
1039
+ : null,
1040
+ )
1041
+ : h('div', { style: S.empty },
1042
+ h('div', { style: { fontSize: 34, marginBottom: 10, opacity: .35 } }, '📚'),
1043
+ h('div', null, t('selectNote')),
1044
+ ),
1045
+ ),
1046
+
1047
+ // ═════ 右:大纲 / 关联 ═════
1048
+ h('div', { style: S.colRight },
1049
+ h('div', { style: S.tabs },
1050
+ h('button', { style: { ...S.tab, ...(rightTab === 'outline' ? S.tabOn : {}) }, onClick: () => setRightTab('outline') }, t('outline')),
1051
+ h('button', { style: { ...S.tab, ...(rightTab === 'related' ? S.tabOn : {}) }, onClick: () => setRightTab('related') }, `${t('related')}${related.length ? ` ${related.length}` : ''}`),
1052
+ h('button', { style: { ...S.tab, ...(rightTab === 'ask' ? S.tabOn : {}) }, onClick: () => setRightTab('ask') }, t('ask')),
1053
+ ),
1054
+ h('div', { style: S.rightBody },
1055
+ rightTab === 'ask'
1056
+ ? h('div', { style: { padding: '10px 8px 0' } },
1057
+ h('textarea', {
1058
+ style: { ...S.input, height: 62, resize: 'vertical', lineHeight: 1.6, padding: '7px 9px' },
1059
+ value: askQ, placeholder: t('askPlaceholder'),
1060
+ onChange: e => setAskQ(e.target.value),
1061
+ onKeyDown: e => {
1062
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); askVault(); }
1063
+ },
1064
+ 'aria-label': t('ask'),
1065
+ }),
1066
+ h('div', { style: { display: 'flex', gap: 6, marginTop: 6, alignItems: 'center' } },
1067
+ h('button', {
1068
+ style: {
1069
+ ...S.btnPrimary, flex: 1,
1070
+ ...(askBusy || !askQ.trim() ? { opacity: 0.55, cursor: 'default' } : {}),
1071
+ },
1072
+ onClick: askVault, disabled: askBusy || !askQ.trim(),
1073
+ }, askBusy ? t('asking') : t('askSend')),
1074
+ askRes ? h('button', { style: S.iconBtn, title: t('clear'), onClick: () => { setAskRes(null); setAskQ(''); } }, '✕') : null,
1075
+ ),
1076
+ askBusy ? h('div', { style: { ...S.match, padding: '8px 0' } }, t('asking')) : null,
1077
+ askRes && !askRes.synthesized ? h('div', { style: { fontSize: 11, color: C.warn, marginTop: 8, lineHeight: 1.6 } },
1078
+ `${t('evidenceOnly')}${askRes.reason ? `(${askRes.reason})` : ''}`) : null,
1079
+ askRes && askRes.answer ? h('div', {
1080
+ style: { marginTop: 10, fontSize: 12.5, lineHeight: 1.85, color: C.text, whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
1081
+ }, askRes.answer) : null,
1082
+ askRes && askRes.hits?.length
1083
+ ? h('div', { style: { marginTop: 12 } },
1084
+ h('div', { style: { ...S.match, padding: '0 0 6px', fontSize: 11 } }, `${t('citations')} · ${askRes.citations?.length || 0}`),
1085
+ ...askRes.hits.map((hh, hi) => h('button', {
1086
+ key: hi,
1087
+ style: { ...S.relRow, alignItems: 'flex-start' },
1088
+ onClick: () => openNote(hh.path),
1089
+ title: hh.text.slice(0, 240),
1090
+ },
1091
+ h('span', { style: { fontSize: 10, color: C.text2, minWidth: 16 } }, `[${hi + 1}]`),
1092
+ h('span', { style: { flex: 1, overflow: 'hidden' } },
1093
+ h('span', { style: { display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, hh.title),
1094
+ h('span', { style: { display: 'block', fontSize: 10.5, color: C.text2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, hh.heading || ''),
1095
+ ),
1096
+ )),
1097
+ )
1098
+ : null,
1099
+ askRes && !askRes.hits?.length ? h('div', { style: S.empty }, t('noEvidence')) : null,
1100
+ )
1101
+ : rightTab === 'outline'
1102
+ ? (headings.length
1103
+ ? headings.map((x, xi) => h('button', {
1104
+ key: xi,
1105
+ style: { ...S.outRow, paddingLeft: 8 + (x.level - 1) * 13, color: x.level <= 2 ? C.text : C.text2, fontWeight: x.level <= 2 ? 600 : 400 },
1106
+ onClick: () => jumpTo(String(xi)),
1107
+ title: x.text,
1108
+ }, x.text))
1109
+ : h('div', { style: S.empty }, t('noOutline')))
1110
+ : (related.length
1111
+ ? related.map((r, ri) => h('button', {
1112
+ key: ri,
1113
+ style: S.relRow,
1114
+ onClick: () => openNote(r.path),
1115
+ title: r.path,
1116
+ },
1117
+ h('span', { style: { color: r.kind === 'in' ? C.brand : C.text2, display: 'inline-flex' } },
1118
+ h(Icon, { d: r.kind === 'in' ? 'M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1' : 'M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1', size: 12 })),
1119
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, r.title),
1120
+ h('span', { style: { fontSize: 10, color: C.text2 } }, r.kind === 'in' ? t('linkIn') : t('linkOut')),
1121
+ ))
1122
+ : h('div', { style: S.empty }, t('noRelated'))),
1123
+ ),
1124
+ ),
1125
+
1126
+ // 新建菜单(笔记 / 文件夹 / 知识库项目)
1127
+ menu && menu.kind === 'new'
1128
+ ? h('div', {
1129
+ style: { position: 'absolute', inset: 0, zIndex: 280 },
1130
+ onClick: () => setMenu(null),
1131
+ },
1132
+ h('div', {
1133
+ style: {
1134
+ position: 'absolute', left: Math.max(8, menu.x), top: Math.max(8, menu.y),
1135
+ width: 200, background: C.bg2, border: `1px solid ${C.line2}`,
1136
+ borderRadius: 8, padding: 6, boxShadow: '0 12px 40px rgba(0,0,0,.45)',
1137
+ },
1138
+ onClick: e => e.stopPropagation(),
1139
+ },
1140
+ h('div', { style: S.menuGroup },
1141
+ menuItem(t('newNote'), 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5', () => { setMenu(null); createNote(''); }),
1142
+ menuItem(t('newFolder'), 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z', () => { setMenu(null); createFolder(''); }),
1143
+ ),
1144
+ h('div', { style: S.menuSep }),
1145
+ h('div', { style: S.menuGroup },
1146
+ menuItem(t('createVault'), 'M12 3v18M3 12h18', () => { setMenu(null); createVaultProject(); }, C.brand),
1147
+ ),
1148
+ ),
1149
+ )
1150
+ : null,
1151
+
1152
+ // 右键菜单(文件夹 / 笔记 / 空白处)
1153
+ menu && menu.kind !== 'new'
1154
+ ? h('div', {
1155
+ style: { position: 'absolute', inset: 0, zIndex: 280 },
1156
+ onClick: () => setMenu(null),
1157
+ },
1158
+ h('div', {
1159
+ style: {
1160
+ position: 'absolute', left: Math.max(8, menu.x), top: Math.max(8, menu.y),
1161
+ width: 196, background: C.bg2, border: `1px solid ${C.line2}`,
1162
+ borderRadius: 8, padding: 6, boxShadow: '0 12px 40px rgba(0,0,0,.45)',
1163
+ },
1164
+ onClick: e => e.stopPropagation(),
1165
+ },
1166
+ // 在文件夹里新建(仅文件夹菜单)
1167
+ menu.kind === 'folder'
1168
+ ? h('div', null,
1169
+ h('div', { style: S.menuGroup },
1170
+ menuItem(t('newNote'), 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5', () => { setMenu(null); createNote(menu.path); }),
1171
+ menuItem(t('newFolder'), 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z', () => { setMenu(null); createFolder(menu.path); }),
1172
+ ),
1173
+ h('div', { style: S.menuSep }),
1174
+ h('div', { style: S.menuGroup },
1175
+ menuItem(t('rename'), 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z', () => { setMenu(null); renameFolder(menu.path, menu.name); }),
1176
+ menuItem(t('delete'), 'M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14', () => { setMenu(null); removeFolder(menu.path, menu.name); }, C.err),
1177
+ ),
1178
+ )
1179
+ : null,
1180
+ // 笔记菜单
1181
+ menu.kind === 'note'
1182
+ ? h('div', null,
1183
+ h('div', { style: S.menuGroup },
1184
+ menuItem(t('open'), 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5', () => { setMenu(null); openNote(menu.path); }),
1185
+ ),
1186
+ h('div', { style: S.menuSep }),
1187
+ h('div', { style: S.menuGroup },
1188
+ menuItem(t('rename'), 'M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z', () => { setMenu(null); renameNoteAt(menu.path); }),
1189
+ menuItem(t('delete'), 'M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14', () => { setMenu(null); removeNoteAt(menu.path); }, C.err),
1190
+ ),
1191
+ )
1192
+ : null,
1193
+ // 空白处菜单(根目录)
1194
+ menu.kind === 'root'
1195
+ ? h('div', null,
1196
+ h('div', { style: S.menuGroup },
1197
+ menuItem(t('newNote'), 'M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8zM14 3v5h5', () => { setMenu(null); createNote(''); }),
1198
+ menuItem(t('newFolder'), 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z', () => { setMenu(null); createFolder(''); }),
1199
+ ),
1200
+ h('div', { style: S.menuSep }),
1201
+ h('div', { style: S.menuGroup },
1202
+ menuItem(t('createVault'), 'M12 3v18M3 12h18', () => { setMenu(null); createVaultProject(); }, C.brand),
1203
+ ),
1204
+ )
1205
+ : null,
1206
+ ),
1207
+ )
1208
+ : null,
1209
+
1210
+ // vault 切换下拉
1211
+ picker
1212
+ ? h('div', {
1213
+ style: {
1214
+ position: 'absolute', inset: 0, zIndex: 290,
1215
+ background: 'rgba(0,0,0,.35)', display: 'flex',
1216
+ alignItems: 'flex-start', justifyContent: 'flex-start', padding: 16,
1217
+ },
1218
+ onClick: e => { if (e.target === e.currentTarget) setPicker(null); },
1219
+ },
1220
+ h('div', {
1221
+ style: {
1222
+ width: 320, maxHeight: '70%', overflowY: 'auto',
1223
+ background: C.bg2, border: `1px solid ${C.line2}`, borderRadius: 10,
1224
+ padding: 8, boxShadow: '0 12px 40px rgba(0,0,0,.45)',
1225
+ },
1226
+ },
1227
+ h('div', { style: { fontSize: 11.5, color: C.text2, padding: '4px 8px 8px' } }, t('switchVault')),
1228
+ picker.length === 0
1229
+ ? h('div', { style: { fontSize: 11.5, color: C.text2, padding: '6px 8px' } }, t('noVaults'))
1230
+ : picker.map(v => h('button', {
1231
+ key: v.path,
1232
+ style: {
1233
+ display: 'block', width: '100%', textAlign: 'left', border: 'none',
1234
+ background: v.path === status?.vaultPath ? C.bg1 : 'transparent',
1235
+ color: C.text, cursor: 'pointer', padding: '8px 9px',
1236
+ borderRadius: 6, fontFamily: 'inherit', fontSize: 12.5,
1237
+ },
1238
+ onClick: () => switchVault(v.path),
1239
+ title: v.path,
1240
+ },
1241
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1242
+ h('span', { style: { fontWeight: 600 } }, v.name),
1243
+ v.open ? h('span', { style: S.badge }, 'open') : null,
1244
+ v.path === status?.vaultPath ? h('span', { style: { ...S.badge, color: C.brand } }, '✓') : null,
1245
+ ),
1246
+ h('div', { style: { fontSize: 10.5, color: C.text2, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, v.path),
1247
+ )),
1248
+ h('div', { style: { height: 1, background: C.line, margin: '8px 4px' } }),
1249
+ h('button', {
1250
+ style: {
1251
+ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'left',
1252
+ border: 'none', background: 'transparent', color: C.brand, cursor: 'pointer',
1253
+ padding: '9px 9px', borderRadius: 6, fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600,
1254
+ },
1255
+ onClick: createVaultProject,
1256
+ },
1257
+ h(Icon, { d: 'M12 5v14M5 12h14', size: 13 }),
1258
+ h('span', null, t('createVault')),
1259
+ ),
1260
+ ),
1261
+ )
1262
+ : null,
1263
+
1264
+ // 内联对话框(替代被禁用的 window.prompt / window.confirm)
1265
+ dialog
1266
+ ? h('div', {
1267
+ style: {
1268
+ position: 'absolute', inset: 0, zIndex: 300,
1269
+ background: 'rgba(0,0,0,.42)', display: 'flex',
1270
+ alignItems: 'center', justifyContent: 'center', padding: 20,
1271
+ },
1272
+ onClick: e => { if (e.target === e.currentTarget) closeDialog(dialog.kind === 'confirm' ? false : null); },
1273
+ },
1274
+ h('div', {
1275
+ style: {
1276
+ width: 'min(420px, 100%)', background: C.bg2, color: C.text,
1277
+ border: `1px solid ${C.line2}`, borderRadius: 10, padding: 16,
1278
+ boxShadow: '0 12px 40px rgba(0,0,0,.45)', display: 'flex',
1279
+ flexDirection: 'column', gap: 12,
1280
+ },
1281
+ role: 'dialog',
1282
+ 'aria-modal': 'true',
1283
+ },
1284
+ h('div', { style: { fontSize: 13.5, fontWeight: 600, lineHeight: 1.5 } }, dialog.title),
1285
+ dialog.kind === 'prompt'
1286
+ ? h('input', {
1287
+ style: S.input,
1288
+ value: dialog.value,
1289
+ placeholder: dialog.placeholder,
1290
+ autoFocus: true,
1291
+ onChange: e => {
1292
+ const v = e.target.value;
1293
+ dialogValueRef.current = v;
1294
+ setDialog(d => d && { ...d, value: v });
1295
+ },
1296
+ onKeyDown: e => {
1297
+ e.stopPropagation();
1298
+ if (e.key === 'Enter' && !e.nativeEvent?.isComposing) submitDialog();
1299
+ if (e.key === 'Escape') closeDialog(null);
1300
+ },
1301
+ })
1302
+ : null,
1303
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
1304
+ h('button', { style: S.btn, onClick: () => closeDialog(dialog.kind === 'confirm' ? false : null) }, t('cancel')),
1305
+ h('button', { style: S.btnPrimary, onClick: submitDialog }, dialog.confirmText || t('save')),
1306
+ ),
1307
+ ),
1308
+ )
1309
+ : null,
1310
+ );
1311
+ }
1312
+
1313
+ function registerUi(ctx) {
1314
+ ctx.slots.inject('main', () =>
1315
+ ctx.slots.register({ name: 'main', key: PANEL_ID, locale: NS }, KnowledgePanel));
1316
+ ctx.slots.inject('sidebar.panellist', () =>
1317
+ ctx.slots.register(
1318
+ { name: 'sidebar.panellist', id: PANEL_ID, order: 56, locale: NS, label: () => t('panel') },
1319
+ BookGlyph));
1320
+ }
1321
+
1322
+ function apply(ctx) {
1323
+ const disposeLocale = ctx.locale.register(NS, DICT);
1324
+ t = ctx.locale.bind(NS);
1325
+ const ui = ctx.inject(['slots'], () => registerUi(ctx));
1326
+ return () => { ui?.dispose?.(); disposeLocale?.(); };
1327
+ }
1328
+
1329
+ return { inject: ['slots', 'locale'], apply };
1330
+ },
1331
+ });