agent-loft 0.2.132 → 0.2.133

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.
@@ -1,11 +1,14 @@
1
1
  import { api } from "../lib/api.js";
2
2
  import { h, fill, icon, toast } from "../lib/dom.js";
3
- import { renderMarkdown } from "../lib/markdown.js";
4
- import { confirmDialog } from "../lib/overlay.js";
3
+ import { patchMarkdown } from "../lib/markdown.js";
4
+ import { closeMenu, confirmDialog, placePopover, showPopover } from "../lib/overlay.js";
5
5
  import { WS } from "../lib/ws.js";
6
6
  import { S, setContentHash, ui } from "../state.js";
7
7
  import { createEditor } from "./file-editor.js";
8
- import { askMemoName, chooseMemoVersion, connectSource, memoAccessSettings, shareMemoSource } from "./memo-dialogs.js";
8
+ import { findMemo, rememberFile, relocatePreference, vaultFiles, trashDir } from "./memo-find.js";
9
+ import { organizeDialog } from "./memo-organize.js";
10
+ import { createMemoOutline } from "./memo-outline.js";
11
+ import { askMemoName, chooseMemoVersion, confirmDisconnect, connectSource, memoAccessSettings, shareMemoSource } from "./memo-dialogs.js";
9
12
  import { closeSide, renderSidebar } from "./sidebar.js";
10
13
  import { renderTopbar } from "./topbar.js";
11
14
 
@@ -31,6 +34,48 @@ function relativePath(note, ref) {
31
34
  return parts.join("/");
32
35
  }
33
36
 
37
+ function bindTreeWidth(root, handle, key) {
38
+ const defaultWidth = 248;
39
+ let preferred = Number(localStorage.getItem(key)) || defaultWidth;
40
+ let startX, startWidth;
41
+ function resize(value, remember = false) {
42
+ if (!root.clientWidth) return;
43
+ const max = Math.min(600, Math.floor(root.clientWidth * 0.58));
44
+ const min = Math.min(184, max);
45
+ const width = Math.round(Math.max(min, Math.min(max, value)));
46
+ root.style.setProperty("--memo-tree-width", width + "px");
47
+ handle.setAttribute("aria-valuemin", min);
48
+ handle.setAttribute("aria-valuemax", max);
49
+ handle.setAttribute("aria-valuenow", width);
50
+ handle.setAttribute("aria-valuetext", width + " 像素");
51
+ if (remember) {
52
+ preferred = width;
53
+ localStorage.setItem(key, width);
54
+ }
55
+ }
56
+ const observer = new ResizeObserver(() => resize(preferred));
57
+ observer.observe(root);
58
+ handle.onpointerdown = e => {
59
+ if (!e.isPrimary || e.button !== 0) return;
60
+ e.preventDefault();
61
+ startX = e.clientX;
62
+ startWidth = Number(handle.getAttribute("aria-valuenow"));
63
+ handle.setPointerCapture(e.pointerId);
64
+ root.classList.add("resizing");
65
+ };
66
+ const dragWidth = e => startWidth + e.clientX - startX;
67
+ handle.onpointermove = e => { if (handle.hasPointerCapture(e.pointerId)) resize(dragWidth(e)); };
68
+ handle.onpointerup = e => { if (handle.hasPointerCapture(e.pointerId)) resize(dragWidth(e), true); };
69
+ handle.onlostpointercapture = () => { root.classList.remove("resizing"); resize(preferred); };
70
+ handle.ondblclick = () => { preferred = defaultWidth; localStorage.removeItem(key); resize(preferred); };
71
+ handle.onkeydown = e => {
72
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
73
+ e.preventDefault();
74
+ resize(Number(handle.getAttribute("aria-valuenow")) + (e.key === "ArrowLeft" ? -16 : 16), true);
75
+ };
76
+ return observer;
77
+ }
78
+
34
79
  function notebook() {
35
80
  let sources = [], source, dir = "", path = "", editor, original = "", version, dirty = false, busy = false, preview = false;
36
81
  let expanded = new Set(), conflict = false;
@@ -38,6 +83,8 @@ function notebook() {
38
83
  const owner = S.user.id;
39
84
  const chooseKey = "aim.memoSource." + owner;
40
85
  const draftKey = "aim.memoDraft." + owner;
86
+ const readingKey = s => "aim.memoReading." + owner + "." + s.id;
87
+ const collapsedKey = "aim.memoTreeCollapsed." + owner;
41
88
  const pauseMs = 1200;
42
89
  let draftTimer, saveTimer, saving, savingText, saveError = "", retryMs = 0;
43
90
 
@@ -46,58 +93,202 @@ function notebook() {
46
93
  if (!editor) return;
47
94
  try {
48
95
  if (dirty || (saving && editor.text() !== savingText)) sessionStorage.setItem(draftKey, JSON.stringify({ source: source.id, path, version, text: editor.text() }));
49
- else sessionStorage.removeItem(draftKey);
96
+ else if (!readOnly()) {
97
+ const saved = savedDraft();
98
+ if (saved?.source === source.id && saved.path === path) sessionStorage.removeItem(draftKey);
99
+ }
50
100
  } catch { /* Storage may be full or disabled. The live editor still holds the draft. */ }
51
101
  }
52
102
  function savedDraft() {
53
103
  try { return JSON.parse(sessionStorage.getItem(draftKey)); }
54
104
  catch { return null; }
55
105
  }
56
- const root = h("section", { class: "memo-page", "aria-label": "备忘录" });
57
- const tree = h("div", { class: "memo-tree", "aria-label": "文件目录" });
106
+ const root = h("section", { class: "memo-page no-source", "aria-label": "备忘录" });
107
+ const tree = h("nav", { class: "memo-tree", id: "memo-tree", "aria-label": "文件目录" });
58
108
  const toolbar = h("div", { class: "memo-bar" });
59
109
  const pane = h("section", { class: "memo-pane" });
60
110
  const editorHost = h("div", { class: "memo-editor" });
61
111
  const reading = h("div", { class: "memo-reading" });
112
+ const outline = createMemoOutline(reading);
113
+ let positionTimer, lastPosition = "", pendingPosition;
114
+ function savedPosition(s) {
115
+ try {
116
+ const value = JSON.parse(localStorage.getItem(readingKey(s)));
117
+ return typeof value?.path === "string" && value.path ? value : null;
118
+ } catch { return null; }
119
+ }
120
+ function writePosition(value) {
121
+ const json = JSON.stringify(value);
122
+ if (json === lastPosition) return;
123
+ try { localStorage.setItem(readingKey(source), json); lastPosition = json; }
124
+ catch { /* A full or private browser store must not interrupt reading. */ }
125
+ }
126
+ function forgetPosition(s) {
127
+ try { localStorage.removeItem(readingKey(s)); } catch { /* Storage may be disabled. */ }
128
+ }
129
+ function savePosition() {
130
+ clearTimeout(positionTimer);
131
+ if (editor && preview && !pendingPosition && reading.clientHeight) writePosition({ path, ...outline.position() });
132
+ }
133
+ function restorePosition() {
134
+ if (!pendingPosition || !preview || !reading.clientHeight) return;
135
+ outline.restore(pendingPosition);
136
+ pendingPosition = null;
137
+ }
138
+ reading.addEventListener("scroll", () => {
139
+ clearTimeout(positionTimer);
140
+ positionTimer = setTimeout(savePosition, 250);
141
+ }, { passive: true });
142
+ const noteTitle = h("h1", { class: "memo-note-title" });
143
+ const markdownBody = h("div", { class: "md" });
144
+ const paper = h("article", { class: "memo-paper" }, noteTitle, markdownBody);
62
145
  const status = h("span", { class: "memo-status", role: "status" });
146
+ const footer = h("div", { class: "memo-footer" });
63
147
  const retryButton = button("重试保存", () => void saveNow().catch(err => toast(err.message)));
64
148
  const historyButton = button("版本历史", () => run(openHistory), "clock");
65
- const toggle = button("预览", () => {
66
- if (busy || !editor) return;
67
- preview = !preview;
149
+ function switchMode(readingMode) {
150
+ if (busy || !editor || readOnly() || readingMode === preview) return;
151
+ savePosition();
152
+ preview = readingMode;
68
153
  modes();
154
+ restorePosition();
69
155
  if (!preview) editor.focus();
70
- });
71
- const toggleTree = button("文件目录", () => root.classList.toggle("show-tree"), "folder");
156
+ }
157
+ const modeButton = (label, symbol, readingMode) => h("button", { type: "button", title: label,
158
+ "aria-label": label, onclick: () => switchMode(readingMode) }, icon(symbol), h("span", {}, label));
159
+ const readMode = modeButton("阅读", "eye", true);
160
+ const editMode = modeButton("编辑", "edit", false);
161
+ const modeGroup = h("div", { class: "memo-modes", role: "group", "aria-label": "笔记模式" }, readMode, editMode);
162
+ const narrow = matchMedia("(max-width: 768px)");
163
+ function setTreeOpen(open) {
164
+ root.classList.toggle("show-tree", open);
165
+ pane.inert = open && narrow.matches && root.classList.contains("has-file");
166
+ openTree.setAttribute("aria-expanded", String(open));
167
+ }
168
+ const onScreenChange = () => setTreeOpen(!path);
169
+ narrow.addEventListener("change", onScreenChange);
170
+ const openTree = button("文件目录", () => {
171
+ savePosition();
172
+ setTreeOpen(true);
173
+ (tree.querySelector(".selected") || tree.querySelector("button"))?.focus();
174
+ }, "panel");
175
+ openTree.classList.add("memo-mobile", "memo-panel-button");
176
+ openTree.setAttribute("aria-controls", "memo-side");
177
+ function returnToFile() {
178
+ setTreeOpen(false);
179
+ restorePosition();
180
+ openTree.focus();
181
+ }
182
+ const scrim = h("button", { class: "memo-scrim", type: "button", tabindex: -1, "aria-label": "关闭文件目录", onclick: returnToFile });
183
+ const backToFile = button("返回文件", returnToFile, "back");
184
+ backToFile.classList.add("memo-return");
185
+ const foldTree = button("收起文件树", () => {
186
+ const collapsed = !root.classList.contains("tree-collapsed");
187
+ setCollapsed(collapsed);
188
+ if (collapsed) localStorage.setItem(collapsedKey, "1");
189
+ else localStorage.removeItem(collapsedKey);
190
+ editor?.measure();
191
+ }, "panel");
192
+ foldTree.classList.add("memo-desktop", "memo-panel-button");
193
+ foldTree.setAttribute("aria-controls", tree.id);
194
+ function setCollapsed(collapsed) {
195
+ root.classList.toggle("tree-collapsed", collapsed);
196
+ foldTree.title = collapsed ? "展开文件树" : "收起文件树";
197
+ foldTree.setAttribute("aria-label", foldTree.title);
198
+ foldTree.setAttribute("aria-expanded", String(!collapsed));
199
+ }
200
+ setCollapsed(localStorage.getItem(collapsedKey) === "1");
72
201
  const copyButton = button("另存副本", () => run(() => create(false, true)));
73
202
  const choose = h("select", { class: "input", "aria-label": "切换笔记库", onchange: () => {
74
203
  const selected = sources.find(s => s.id === choose.value);
75
204
  choose.value = source.id;
76
- void run(async () => { if (await discardable()) select(selected); });
205
+ void run(async () => { if (await discardable()) await select(selected); });
77
206
  } });
78
- const side = h("aside", { class: "memo-side" });
79
- const pathLabel = h("strong", { class: "memo-path" });
207
+ const side = h("aside", { class: "memo-side", id: "memo-side", "aria-label": "笔记库文件" });
208
+ side.addEventListener("keydown", e => {
209
+ if (e.key === "Escape" && pane.inert && !ui.menu) { e.preventDefault(); returnToFile(); }
210
+ });
211
+ const pathLabel = h("div", { class: "memo-breadcrumb" });
80
212
  const entryButton = button("连接笔记库", () => addSource());
81
- const accessButton = h("button", { class: "btn", onclick: () => run(() => memoAccessSettings(source)) }, icon("gear"), "智能体访问");
82
- const shareButton = button("共享给成员", () => run(() => shareMemoSource(source)));
83
- const disconnectButton = button("断开笔记库", () => run(disconnect), "unplug");
84
- const newNote = button("新建笔记", () => run(() => create(false)));
85
- const newFolder = button("新建文件夹", () => run(() => create(true)), "folder");
213
+ const settings = button("笔记库设置", openSettings, "gear");
214
+ const handle = h("div", { class: "memo-divider", role: "separator", tabindex: 0, "aria-label": "文件树宽度",
215
+ "aria-controls": tree.id, "aria-orientation": "vertical", title: "拖动调整文件树宽度,双击恢复默认" });
216
+ const widthObserver = bindTreeWidth(root, handle, "aim.memoTreeWidth." + owner);
217
+ const newNote = button("新建笔记", () => run(() => create(false)), "compose");
218
+ const newFolder = button("新建文件夹", () => run(() => create(true)), "folderPlus");
86
219
  const readOnly = () => source?.permission === "read";
87
220
  function endpoint(action, file = "", cursor = "") {
88
221
  return "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id, path: file,
89
222
  ...(source.sharedBy ? { owner: source.sharedBy.id } : {}), ...(action === "file" ? { collab: "1" } : {}), ...(cursor ? { cursor } : {}) });
90
223
  }
224
+ const shelfKey = () => readingKey(source) + ".files";
225
+ async function reveal(file) {
226
+ await openFile(file);
227
+ if (path !== file) return;
228
+ let changed = false;
229
+ for (let p = parent(file); p; p = parent(p)) {
230
+ if (!expanded.has(p)) { expanded.add(p); changed = true; }
231
+ }
232
+ if (changed) refreshTree();
233
+ }
234
+ async function quick(initial = "", trash = false) {
235
+ const hit = await findMemo(endpoint, shelfKey(), initial, trash);
236
+ if (!hit) return;
237
+ if (trash) {
238
+ const result = await api(endpoint("organize",hit.path),{method:"POST",body:{op:"restore"}});
239
+ refreshTree(); toast("已恢复「"+result.path+"」"); return;
240
+ }
241
+ await reveal(hit.path);
242
+ if (path !== hit.path || !hit.needle) return;
243
+ const needle = hit.needle.toLowerCase();
244
+ const walker = document.createTreeWalker(reading, NodeFilter.SHOW_TEXT);
245
+ while (walker.nextNode()) {
246
+ const node = walker.currentNode;
247
+ if (node.parentElement?.closest("[hidden],button,.code-head")) continue;
248
+ const at = node.data.toLowerCase().indexOf(needle);
249
+ if (at < 0) continue;
250
+ const range = document.createRange();
251
+ range.setStart(node,at);
252
+ range.setEnd(node,at+hit.needle.length);
253
+ reading.scrollTop += range.getBoundingClientRect().top - reading.getBoundingClientRect().top - reading.clientHeight / 3;
254
+ if (globalThis.Highlight && globalThis.CSS?.highlights) CSS.highlights.set("memo-search",new Highlight(range));
255
+ return;
256
+ }
257
+ // Formatted links and nested markup can split the original phrase across text nodes.
258
+ const block = markdownBody._blocks?.find(b => b.raw.toLowerCase().includes(needle));
259
+ block?.nodes.find(n => n.nodeType === 1)?.scrollIntoView({block:"center"});
260
+ }
261
+ const findButton = button("快速打开", () => run(() => quick()), "search");
262
+ const shortcut = e => {
263
+ if (S.view === "memos" && source && !document.querySelector(".overlay") && (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "o") {
264
+ e.preventDefault(); void run(() => quick());
265
+ }
266
+ };
267
+ document.addEventListener("keydown",shortcut);
268
+ async function organize(file) {
269
+ if (readOnly() || !(await discardable())) return;
270
+ const op = await organizeDialog(endpoint,file);
271
+ if (!op) return;
272
+ const result = await api(endpoint("organize",file),{method:"POST",body:op});
273
+ relocatePreference(shelfKey(),file,op.op === "move" ? result.path : null);
274
+ if (path === file) {
275
+ resetDocument(); forgetPosition(source);
276
+ await select(source);
277
+ if (op.op === "move") await reveal(result.path);
278
+ } else refreshTree();
279
+ toast(op.op === "move" ? "已移动到 "+result.path : "已移入回收站,可在笔记库设置中恢复");
280
+ }
91
281
  function sync() {
92
282
  retryButton.hidden = !saveError || conflict;
93
283
  retryButton.disabled = busy || !!saving;
94
284
  status.title = saveError;
95
- toggle.disabled = busy;
285
+ readMode.disabled = editMode.disabled = busy;
96
286
  choose.disabled = busy;
97
- shareButton.disabled = accessButton.disabled = busy;
287
+ settings.disabled = busy;
98
288
  copyButton.hidden = !conflict || readOnly();
99
289
  status.textContent = conflict ? "远端已更改" : saving ? "正在保存…" : saveError ? "保存失败" :
100
290
  busy ? "处理中…" : dirty ? "待自动保存" : readOnly() ? "只读" : editor ? "已保存" : "";
291
+ status.dataset.state = conflict || saveError ? "error" : saving || busy || dirty ? "pending" : readOnly() ? "readonly" : "saved";
101
292
  }
102
293
  async function run(fn) {
103
294
  if (busy) return;
@@ -128,6 +319,10 @@ function notebook() {
128
319
  return confirmDialog({ title: "当前草稿尚未保存", message: saveError || "远端版本已更改。可以返回编辑器另存副本。", confirmText: "放弃修改", danger: true });
129
320
  }
130
321
  function resetDocument() {
322
+ globalThis.CSS?.highlights?.delete("memo-search");
323
+ savePosition();
324
+ lastPosition = "";
325
+ pendingPosition = null;
131
326
  pausePoll();
132
327
  session = null;
133
328
  clearTimeout(saveTimer);
@@ -146,27 +341,50 @@ function notebook() {
146
341
  root.classList.remove("has-file");
147
342
  path = original = "";
148
343
  fill(editorHost);
344
+ outline.update(null);
345
+ patchMarkdown(markdownBody, "");
149
346
  fill(reading);
150
347
  }
151
- function select(s) {
348
+ async function select(s, draft) {
152
349
  resetDocument();
153
350
  source = s;
154
351
  dir = "";
155
352
  expanded = new Set();
156
- root.classList.add("show-tree");
353
+ setTreeOpen(true);
157
354
  if (s) localStorage.setItem(chooseKey, s.id);
158
355
  fillChoices();
159
356
  if (s) choose.value = s.id;
160
- accessButton.hidden = shareButton.hidden = disconnectButton.hidden = !!s?.sharedBy;
161
- toggle.hidden = newNote.hidden = newFolder.hidden = readOnly();
357
+ modeGroup.hidden = newNote.hidden = newFolder.hidden = readOnly();
162
358
  side.hidden = !s;
163
359
  root.classList.toggle("no-source", !s);
164
360
  if (!s) {
165
361
  fill(pane, h("div", { class: "memo-empty" }, icon("clipboard"), h("h2", {}, "连接你的笔记库"), h("p", {}, "从 WebDAV 目录或 S3 存储桶打开笔记。"), entryButton));
166
362
  return;
167
363
  }
168
- fill(pane, h("div", { class: "memo-blankbar" }, toggleTree), h("div", { class: "memo-empty" }, icon("file"), h("p", {}, readOnly() ? "选择文件查看。" : "选择文件,或在当前目录新建笔记。")));
364
+ const position = savedPosition(s);
365
+ const recoverDraft = !readOnly() && draft?.source === s.id && typeof draft.path === "string" && typeof draft.text === "string";
366
+ const file = recoverDraft ? draft.path : position?.path;
367
+ const empty = h("div", { class: "memo-empty" }, icon("notebook"), h("h2", {}, "打开一篇笔记"), h("p", {}, readOnly() ? "从文件目录中选择文件查看。" : "从文件目录中选择文件,或新建一篇笔记。"));
368
+ const bar = h("div", { class: "memo-bar" }, openTree, icon("notebook"), s.name);
369
+ fill(pane, bar, file ? h("div", { class: "memo-empty", role: "status" }, "正在打开「" + file + "」…") : empty);
370
+ if (file) for (let p = parent(file); p; p = parent(p)) expanded.add(p);
169
371
  refreshTree();
372
+ if (!file) return;
373
+ let data;
374
+ try { data = await api(endpoint("file", file)); }
375
+ catch (err) {
376
+ if (recoverDraft && !s.sharedBy && (err.status === 404 || !err.status || err.status >= 500)) data = { text: null, version: null };
377
+ else {
378
+ fill(pane, bar, empty);
379
+ if (err.status === 404 || err.status === 403) {
380
+ if (position?.path === file) forgetPosition(s);
381
+ if (expanded.size) { expanded.clear(); refreshTree(); }
382
+ }
383
+ toast(err.status === 404 && !recoverDraft ? "找不到上次阅读的「" + file + "」,请从文件目录重新选择。" : err.message);
384
+ return;
385
+ }
386
+ }
387
+ await showText(file, data, recoverDraft, recoverDraft ? draft : null, position?.path === file ? position : null);
170
388
  }
171
389
  function fillChoices() {
172
390
  fill(choose, sources.map(item => h("option", { value: item.id }, item.sharedBy
@@ -177,7 +395,11 @@ function notebook() {
177
395
  if (busy || dirty || saving) return;
178
396
  sources = list;
179
397
  const latest = sources.find(s => s.id === source?.id);
180
- if (!latest || latest.permission !== source.permission) select(latest ?? sources[0]);
398
+ if (!latest || latest.permission !== source.permission) {
399
+ const previous = source;
400
+ await run(() => select(latest ?? sources[0]));
401
+ if (previous && !latest) forgetPosition(previous);
402
+ }
181
403
  else {
182
404
  Object.assign(source, latest);
183
405
  fillChoices();
@@ -187,20 +409,50 @@ function notebook() {
187
409
  function addSource() {
188
410
  void run(async () => {
189
411
  if (!(await discardable())) return;
190
- connectSource(async s => { sources.push(s); select(s); });
412
+ connectSource(async s => { sources.push(s); await run(() => select(s)); });
191
413
  });
192
414
  }
415
+ function openSettings() {
416
+ if (ui.menu?.anchor === settings) { closeMenu(); return; }
417
+ const menu = showPopover(settings, { align: "left" });
418
+ const library = source;
419
+ const action = (label, symbol, fn, danger = false) => h("button", {
420
+ class: danger ? "danger" : null, onclick: () => {
421
+ closeMenu();
422
+ settings.focus();
423
+ if (source === library && S.view === "memos") fn();
424
+ },
425
+ }, icon(symbol), label);
426
+ fill(menu, path && !readOnly() ? action("整理当前文件", "folder", () => run(() => organize(path))) : null,
427
+ !readOnly() ? action("回收站", "trash", () => run(() => quick("",true))) : null,
428
+ action("连接其他笔记库", "plus", addSource),
429
+ library.sharedBy ? null : [
430
+ action("智能体访问", "spark", () => run(() => memoAccessSettings(library))),
431
+ action("共享给成员", "handoff", () => run(() => shareMemoSource(library))),
432
+ h("div", { class: "sep" }),
433
+ action("断开笔记库", "unplug", () => run(disconnect), true),
434
+ ]);
435
+ menu.classList.add("memo-settings");
436
+ placePopover(menu, settings);
437
+ menu.querySelector("button").focus();
438
+ }
193
439
  async function disconnect() {
440
+ if (source.sharedBy || !(await confirmDisconnect(source))) return;
194
441
  if (!(await discardable())) return;
195
- if (!(await confirmDialog({ title: "断开笔记库?", message: `将移除「${source.name}」的连接,并撤回这个库的所有共享。远端文件和本地版本历史会保留。${dirty ? "当前草稿尚未保存。" : ""}`, confirmText: "断开连接" }))) return;
196
442
  await api(endpoint("sources"), { method: "DELETE" });
443
+ const disconnected = source;
197
444
  sources = sources.filter(s => s.id !== source.id);
198
- select(sources[0]);
445
+ await select(sources[0]);
446
+ forgetPosition(disconnected);
199
447
  }
200
448
 
201
449
  function highlight() {
202
450
  for (const el of tree.querySelectorAll("[data-path]")) {
203
- el.classList.toggle("selected", el.dataset.path === (el.dataset.directory ? dir : path));
451
+ const active = el.dataset.path === (el.dataset.directory ? dir : path);
452
+ if (active && !el.dataset.directory) el.setAttribute("aria-current", "page");
453
+ else el.removeAttribute("aria-current");
454
+ el.classList.toggle("selected", active && (!path || !el.dataset.directory));
455
+ el.classList.toggle("current-dir", active && !!el.dataset.directory);
204
456
  }
205
457
  }
206
458
  function branch(folder) {
@@ -215,8 +467,14 @@ function notebook() {
215
467
  if (source !== library || !tree.contains(box)) return;
216
468
  for (const item of entries) {
217
469
  const full = join(folder, item.name);
470
+ if (full === trashDir) continue;
471
+ const ext = !item.directory && item.name.match(/^(.+)(\.[^.]+)$/);
472
+ const label = ext ? h("span", {}, ext[1], h("small", { class: "memo-extension" }, ext[2])) : h("span", {}, item.name);
218
473
  const row = h("button", { class: "memo-row", title: full, "data-path": full, "data-directory": item.directory ? "1" : null },
219
- icon(item.directory ? "folder" : "file"), h("span", {}, item.name));
474
+ icon(item.directory ? "folder" : imageFile(full) ? "library" : "file"), label);
475
+ if (!item.directory && !readOnly()) row.oncontextmenu = e => {
476
+ e.preventDefault(); void run(() => organize(full));
477
+ };
220
478
  box.append(row);
221
479
  if (item.directory) {
222
480
  let children;
@@ -237,7 +495,17 @@ function notebook() {
237
495
  } else { expanded.add(full); expand(); }
238
496
  highlight();
239
497
  };
240
- } else row.onclick = () => run(() => openFile(full));
498
+ } else row.onclick = () => {
499
+ if (full === path && !conflict && !saveError && root.classList.contains("show-tree")) returnToFile();
500
+ else void run(async () => {
501
+ row.setAttribute("aria-busy", "true");
502
+ try {
503
+ await openFile(full);
504
+ if (narrow.matches && path === full) openTree.focus({ preventScroll: true });
505
+ }
506
+ finally { row.removeAttribute("aria-busy"); }
507
+ });
508
+ };
241
509
  }
242
510
  more.remove();
243
511
  if (!entries.length && !cursor) box.append(h("small", {}, "空目录"));
@@ -252,47 +520,142 @@ function notebook() {
252
520
  void load();
253
521
  return box;
254
522
  }
523
+ let holdTimer, holdRow, holdX, holdY;
524
+ function cancelHold() { clearTimeout(holdTimer); holdRow = null; }
525
+ tree.addEventListener("pointerdown", e => {
526
+ cancelHold();
527
+ if (e.pointerType !== "touch" || readOnly() || busy) return;
528
+ holdRow = e.target.closest(".memo-row:not([data-directory])");
529
+ if (!holdRow) return;
530
+ holdX = e.clientX; holdY = e.clientY;
531
+ holdTimer = setTimeout(() => {
532
+ const file = holdRow.dataset.path;
533
+ cancelHold();
534
+ void run(() => organize(file));
535
+ }, 520);
536
+ });
537
+ tree.addEventListener("pointermove", e => {
538
+ if (holdRow && Math.hypot(e.clientX-holdX,e.clientY-holdY)>8) cancelHold();
539
+ });
540
+ for (const event of ["pointerup","pointercancel","pointerleave","contextmenu"]) tree.addEventListener(event,cancelHold);
255
541
  function refreshTree() {
256
542
  if (!source) return;
257
- const home = h("button", { class: "memo-row memo-root", "data-path": "", "data-directory": "1", onclick: () => { dir = ""; highlight(); } }, icon("folderOpen"), source.name);
543
+ const home = h("button", { class: "memo-row memo-root", title: source.name, "data-path": "", "data-directory": "1", onclick: () => { dir = ""; highlight(); } }, icon("folderOpen"), h("span", {}, source.name));
258
544
  fill(tree, home, branch(""));
259
545
  highlight();
260
546
  }
261
547
 
262
548
  function modes() {
263
- toggle.textContent = preview ? "编辑" : "预览";
264
- toggle.setAttribute("aria-label", toggle.textContent);
265
- toggle.title = toggle.textContent;
549
+ readMode.setAttribute("aria-pressed", String(preview));
550
+ editMode.setAttribute("aria-pressed", String(!preview));
266
551
  reading.hidden = !preview;
267
552
  editorHost.hidden = preview;
268
- if (!preview) { editor?.measure(); return; }
553
+ if (!preview) { outline.update(null); editor?.measure(); return; }
269
554
  const text = editor.text();
270
555
  if (!markdown(path)) { fill(reading, h("pre", {}, text)); return; }
271
- fill(reading, renderMarkdown(text, { sanitizeOptions: noteMarkup, prepare(box) {
272
- for (const el of box.querySelectorAll("[class]")) {
273
- const language = el.tagName === "CODE" && /^language-[\w+-]+$/.test(el.className);
274
- if (!language) el.removeAttribute("class");
275
- }
276
- for (const input of box.querySelectorAll("input")) { input.type = "checkbox"; input.disabled = true; }
277
- for (const img of box.querySelectorAll("img")) {
278
- const file = relativePath(path, img.getAttribute("src"));
279
- img.removeAttribute("srcset");
280
- if (file && imageFile(file)) img.src = endpoint("image", file);
281
- else img.removeAttribute("src");
556
+ patchMarkdown(markdownBody, text, { sanitizeOptions: noteMarkup, prepare: prepareNote });
557
+ const title = path.split("/").pop().replace(/\.(md|markdown)$/i, "");
558
+ const heading = markdownBody.firstElementChild;
559
+ if (noteTitle.textContent !== title) noteTitle.textContent = title;
560
+ noteTitle.hidden = heading?.tagName === "H1" && heading.textContent === title;
561
+ if (paper.parentNode !== reading) fill(reading, paper);
562
+ outline.update(markdownBody);
563
+ }
564
+ function prepareNote(box, {raw, offset, chunk}) {
565
+ for (const el of box.querySelectorAll("[class]")) {
566
+ const language = el.tagName === "CODE" && /^language-[\w+-]+$/.test(el.className);
567
+ if (!language) el.removeAttribute("class");
568
+ }
569
+ const inputs = [...box.querySelectorAll("input")];
570
+ const markers = [...raw.matchAll(/^(?:[ \t]*>[ \t]?)*[ \t]*(?:[-+*]|\d+[.)])[ \t]+\[([ xX])\](?=\s|$)/gm)];
571
+ const tasks = !/<input\b/i.test(raw) && !readOnly() && chunk.every(t => ["list","blockquote","space"].includes(t.type)) &&
572
+ inputs.length === markers.length && inputs.every((el,i) => el.closest("li") && el.checked === (markers[i][1] !== " "));
573
+ inputs.forEach((el,i) => {
574
+ el.type = "checkbox"; el.disabled = !tasks;
575
+ if (!tasks) return;
576
+ const m = markers[i], at = offset + m.index + m[0].lastIndexOf("[") + 1;
577
+ el.setAttribute("aria-label",el.closest("li").textContent.trim());
578
+ el.onchange = () => {
579
+ if (busy || conflict || !editor.toggleTask(at,m[1])) { el.checked = m[1] !== " "; return; }
580
+ modes();
581
+ };
582
+ });
583
+ for (const img of box.querySelectorAll("img")) {
584
+ const file = relativePath(path, img.getAttribute("src"));
585
+ img.removeAttribute("srcset");
586
+ if (file && imageFile(file)) img.src = endpoint("image", file);
587
+ else img.removeAttribute("src");
588
+ }
589
+ for (const a of box.querySelectorAll("a")) {
590
+ const ref = a.getAttribute("href");
591
+ if (/^https?:\/\//i.test(ref)) continue;
592
+ const file = ref?.startsWith("#") ? path : relativePath(path, ref);
593
+ a.removeAttribute("href");
594
+ if (file) {
595
+ const hash = ref.indexOf("#");
596
+ a.href = "#memos";
597
+ a.onclick = e => {
598
+ e.preventDefault();
599
+ void run(async () => {
600
+ if (file !== path || hash < 0) await openFile(file);
601
+ if (hash < 0 || file !== path || !preview || !markdown(file)) return;
602
+ let fragment = ref.slice(hash + 1);
603
+ try { fragment = decodeURIComponent(fragment); } catch { /* A literal percent is valid in a title. */ }
604
+ if (fragment) outline.jump(fragment);
605
+ else reading.scrollTop = 0;
606
+ });
607
+ };
282
608
  }
283
- for (const a of box.querySelectorAll("a")) {
284
- const ref = a.getAttribute("href");
285
- if (/^https?:\/\//i.test(ref)) continue;
286
- const file = relativePath(path, ref);
287
- a.removeAttribute("href");
288
- if (file) {
289
- a.href = "#memos";
290
- a.onclick = e => { e.preventDefault(); void run(() => openFile(file)); };
291
- }
609
+ }
610
+ const walker = document.createTreeWalker(box, NodeFilter.SHOW_TEXT);
611
+ const texts = [];
612
+ while (walker.nextNode()) if (!walker.currentNode.parentElement?.closest("pre,code,a") && walker.currentNode.data.includes("[[")) texts.push(walker.currentNode);
613
+ for (const node of texts) {
614
+ const parts = [], value = node.data;
615
+ let start = 0;
616
+ for (const m of value.matchAll(/\[\[([^\]\n|]+)(?:\|([^\]\n]+))?\]\]/g)) {
617
+ const [name,...fragment] = m[1].split("#");
618
+ const link = h("a",{href:"#memos",onclick:e => {
619
+ e.preventDefault(); void run(async () => {
620
+ let file = path;
621
+ if (name) {
622
+ const matches = [];
623
+ for await (const item of vaultFiles(endpoint)) {
624
+ const normalized = item.replace(/\.(md|markdown)$/i,"");
625
+ const target = name.trim().replace(/\.(md|markdown)$/i,"");
626
+ if (normalized === target || normalized.endsWith("/"+target)) matches.push(item);
627
+ }
628
+ if (!matches.length) { toast("找不到笔记「"+name+"」"); return; }
629
+ const stem = value => value.replace(/\.(md|markdown)$/i,"");
630
+ const wanted = stem(name.trim());
631
+ const exact = matches.find(p => stem(p) === join(parent(path),wanted)) ?? matches.find(p => stem(p) === wanted);
632
+ file = exact || matches[0];
633
+ if (!exact && matches.length > 1) {
634
+ const hit = await findMemo(endpoint,shelfKey(),name);
635
+ if (!hit) return;
636
+ file = hit.path;
637
+ }
638
+ await reveal(file);
639
+ }
640
+ if (path === file && fragment.length) outline.jump(fragment.join("#"));
641
+ });
642
+ }},m[2] || m[1]);
643
+ parts.push(value.slice(start,m.index),link); start = m.index+m[0].length;
292
644
  }
293
- } }));
645
+ if (start) node.replaceWith(...parts,value.slice(start));
646
+ }
294
647
  }
295
- async function showText(file, data, edit, draft) {
648
+ function updatePath(file) {
649
+ const dirs = [source.name, parent(file)].filter(Boolean).join(" / ");
650
+ pathLabel.title = dirs + " / " + file.split("/").pop();
651
+ fill(pathLabel, h("span", {}, dirs), h("span", { "aria-hidden": "true" }, "/"), h("strong", {}, file.split("/").pop()));
652
+ }
653
+ async function showText(file, data, edit, draft, position = null) {
654
+ if (file === path && editor) {
655
+ savePosition();
656
+ position ??= savedPosition(source);
657
+ if (position?.path !== file) position = null;
658
+ }
296
659
  resetDocument();
297
660
  path = file;
298
661
  dir = parent(file);
@@ -301,9 +664,11 @@ function notebook() {
301
664
  dirty = !!draft && draft.text !== data.text;
302
665
  conflict = dirty && data.version !== null && draft.version !== data.version;
303
666
  root.classList.add("has-file");
304
- pathLabel.textContent = file;
305
- fill(toolbar, toggleTree, pathLabel, status, toggle, historyButton, copyButton, retryButton);
306
- fill(pane, toolbar, editorHost, reading);
667
+ updatePath(file);
668
+ editorHost.classList.toggle("memo-prose", markdown(file));
669
+ fill(toolbar, openTree, foldTree, pathLabel, modeGroup, outline.trigger, historyButton);
670
+ fill(footer, status, copyButton, retryButton);
671
+ fill(pane, toolbar, editorHost, reading, footer);
307
672
  session = conflict ? null : data.collab;
308
673
  editor = await createEditor({ parent: editorHost, readOnly: readOnly(), collaboration: session, text: session ? original : draft?.text ?? original, name: file, onSave: () => void saveNow().catch(err => toast(err.message)), onChange: () => {
309
674
  if (receiving) return;
@@ -321,9 +686,13 @@ function notebook() {
321
686
  }
322
687
  preview = !edit;
323
688
  modes();
689
+ setTreeOpen(false);
690
+ pendingPosition = position ?? { path: file, top: 0 };
691
+ writePosition(pendingPosition);
692
+ rememberFile(shelfKey(), file);
693
+ restorePosition();
324
694
  if (edit) editor.focus();
325
695
  resumePoll();
326
- root.classList.remove("show-tree");
327
696
  highlight();
328
697
  }
329
698
  async function openFile(file) {
@@ -332,10 +701,11 @@ function notebook() {
332
701
  resetDocument();
333
702
  path = file; dir = parent(file);
334
703
  root.classList.add("has-file");
335
- pathLabel.textContent = file;
336
- fill(toolbar, toggleTree, pathLabel);
704
+ updatePath(file);
705
+ fill(toolbar, openTree, foldTree, pathLabel);
706
+ rememberFile(shelfKey(),file);
337
707
  fill(pane, toolbar, h("div", { class: "memo-reading" }, h("img", { alt: file, src: endpoint("image", file), onerror: () => toast("图片读取失败") })));
338
- root.classList.remove("show-tree");
708
+ setTreeOpen(false);
339
709
  highlight();
340
710
  }
341
711
  function pausePoll() {
@@ -512,40 +882,32 @@ function notebook() {
512
882
  refreshTree();
513
883
  });
514
884
  }, true);
515
- fill(side, h("div", { class: "memo-sources" }, choose, accessButton, shareButton, button("连接其他笔记库", addSource, "plus"), disconnectButton),
516
- h("div", { class: "memo-tree-tools" }, newNote, newFolder, button("刷新目录", refreshTree, "refresh"), h("button", { class: "btn memo-return", onclick: () => root.classList.remove("show-tree") }, "返回文件")), tree);
517
- fill(root, side, pane);
885
+ fill(side, h("div", { class: "memo-tree-tools" }, backToFile, h("strong", {}, "文件"), findButton, newNote, newFolder, button("刷新目录", refreshTree, "refresh")),
886
+ tree, h("div", { class: "memo-sources" }, icon("notebook"), choose, settings), handle);
887
+ fill(root, side, pane, scrim);
518
888
  async function init() {
519
889
  fill(pane, h("div", { class: "memo-empty" }, "正在读取笔记库…"));
520
890
  try {
521
891
  sources = await api("/api/memos/sources");
522
892
  const draft = savedDraft();
523
- select(sources.find(s => s.id === (draft?.source ?? localStorage.getItem(chooseKey))) ?? sources[0]);
524
- if (source && !readOnly() && draft?.source === source.id && typeof draft.text === "string") {
525
- await run(async () => {
526
- let data;
527
- try { data = await api(endpoint("file", draft.path)); }
528
- catch (err) { if (source.sharedBy) throw err; data = { text: null, version: null }; }
529
- for (let p = parent(draft.path); p; p = parent(p)) expanded.add(p);
530
- await showText(draft.path, data, true, draft);
531
- refreshTree();
532
- });
533
- }
893
+ const initial = sources.find(s => s.id === draft?.source && s.permission !== "read")
894
+ ?? sources.find(s => s.id === localStorage.getItem(chooseKey)) ?? sources[0];
895
+ await run(() => select(initial, draft));
534
896
  }
535
897
  catch (err) { fill(pane, h("div", { class: "memo-empty" }, err.message, button("重试", init))); }
536
898
  }
537
899
  side.hidden = true;
538
900
  void init();
539
- return { owner, root, reloadSources, persistDraft, pausePoll, resumePoll, flush: () => {
901
+ return { owner, root, reloadSources, persistDraft, savePosition, pausePoll, resumePoll, flush: () => {
540
902
  if (!busy && !conflict) void saveNow().catch(() => {});
541
- }, pending: () => dirty || busy || !!saving, destroy: resetDocument, measure: () => editor?.measure() };
903
+ }, pending: () => dirty || busy || !!saving, destroy: () => { document.removeEventListener("keydown",shortcut); narrow.removeEventListener("change", onScreenChange); widthObserver.disconnect(); resetDocument(); }, measure: () => { editor?.measure(); restorePosition(); } };
542
904
  }
543
905
 
544
906
  let page;
545
- document.addEventListener("aim:leave-view", () => page?.pausePoll());
546
- window.addEventListener("pagehide", () => page?.persistDraft());
907
+ document.addEventListener("aim:leave-view", () => { page?.savePosition(); page?.pausePoll(); });
908
+ window.addEventListener("pagehide", () => { page?.savePosition(); page?.persistDraft(); });
547
909
  document.addEventListener("visibilitychange", () => {
548
- if (document.hidden) { page?.persistDraft(); page?.flush(); }
910
+ if (document.hidden) { page?.savePosition(); page?.persistDraft(); page?.flush(); }
549
911
  });
550
912
  window.addEventListener("online", () => page?.flush());
551
913
  window.addEventListener("beforeunload", e => { if (page?.pending()) { e.preventDefault(); e.returnValue = ""; } });