@coda-console/resource-manager 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/view/find.mjs ADDED
@@ -0,0 +1,254 @@
1
+ // 文件内查找(设计见 docs/design/phase-3.md 第 18.6 节):预览里的查找条,高亮全部匹配,显示「第几个 / 共几个」,上一个、下一个,不分大小写。
2
+ // 全部在页面里做,只找当前显示的这份正文。纯函数(findMatches、buildIndex、rangesFor)和查找条(createFind)在这里,预览(preview.mjs)负责接上自己的生命周期。
3
+ //
4
+ // 每个异步机制的五样:
5
+ // - 输入防抖:输入框 input 时开始,停顿 FIND_DEBOUNCE_MS 才找;找之前、关查找条、换正文时取消;到点只做一次。
6
+ // - 分批标记:一次查找(runId)持有。找完匹配先同步标第一批,之后每批 BATCH 个,批间 setTimeout(0) 让出;
7
+ // 每批开始时核对 runId 和正文版本,变了就停(关查找条、换词、换正文、清掉都会让它作废)。
8
+ // - 正文版本 version:show() 换正文、clearContent 都加一,之前的批次和待执行的防抖据此作废。
9
+ // - 高亮注册:find(全部匹配)和 find-current(当前这处,priority 更高)两个 Highlight,一次查找新建一份,关闭、换词、清掉时从 CSS.highlights 删掉。
10
+ // 不支持 Highlight API、或正文有长行(hasLongLine,预览给的)时不注册,只计数、导航、滚动。
11
+ // - 超时:没有;10000 处的上限和每批 2000 个让出就是它的界。
12
+ import { h } from './dom.mjs';
13
+ import { icon } from './icons.mjs';
14
+
15
+ export const FIND_MAX = 10_000;
16
+ export const FIND_BATCH = 2000;
17
+ export const FIND_DEBOUNCE_MS = 150;
18
+
19
+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+
21
+ // 在原文上找:转义后的搜索词建 RegExp(giu),返回 UTF-16 下标(和文本节点的 Range 偏移一致),不靠 toLowerCase 再换算。
22
+ // 不重叠(g 的语义);最多 max 处,多找到一处就是 more(界面写「10000+」)。空词不建正则。
23
+ export function findMatches(text, term, max = FIND_MAX) {
24
+ if (term === '') return { list: [], more: false };
25
+ const pattern = new RegExp(escape(term), 'giu'), list = [];
26
+ for (let match = pattern.exec(text); match; match = pattern.exec(text)) {
27
+ if (match[0].length === 0) { pattern.lastIndex++; continue; } // 非空词不会走到这里,防死循环
28
+ if (list.length >= max) return { list, more: true };
29
+ list.push([match.index, match.index + match[0].length]);
30
+ }
31
+ return { list, more: false };
32
+ }
33
+
34
+ // 正文里的文本节点和它们的累计起点:每个正文版本只建一次。
35
+ const isText = node => node.nodeType === 3 || (node.nodeType === undefined && node.children === undefined);
36
+ export function buildIndex(root) {
37
+ const nodes = [];
38
+ let at = 0;
39
+ const walk = parent => {
40
+ for (const node of parent.childNodes ?? parent.children) {
41
+ if (isText(node)) {
42
+ const length = node.data.length;
43
+ if (length > 0) { nodes.push({ node, start: at, end: at + length }); at += length; }
44
+ } else walk(node);
45
+ }
46
+ };
47
+ walk(root);
48
+ return { nodes, length: at };
49
+ }
50
+
51
+ // 第一个包含 offset 的节点(end > offset)的下标,从 from 起往后找。
52
+ const startNode = (nodes, offset, from = 0) => { let i = from; while (i < nodes.length && nodes[i].end <= offset) i++; return i; };
53
+ // 第一个 end 不小于 end 的节点:匹配的终点(不含)落在它里面。
54
+ const endNode = (nodes, end, from = 0) => { let i = from; while (i < nodes.length && nodes[i].end < end) i++; return i; };
55
+ // 二分:第一个 end > offset 的节点,单个匹配用。
56
+ function bisect(nodes, offset) {
57
+ let low = 0, high = nodes.length;
58
+ while (low < high) { const mid = (low + high) >> 1; if (nodes[mid].end <= offset) low = mid + 1; else high = mid; }
59
+ return low;
60
+ }
61
+
62
+ // 一批匹配的 Range:匹配是递增的,起点和终点各用一个指针在表里往前走,不从头找。
63
+ export function rangesFor(index, list, from, to, makeRange) {
64
+ const { nodes } = index, ranges = [];
65
+ let p = bisect(nodes, list[from][0]), q = p;
66
+ for (let i = from; i < to; i++) {
67
+ const [start, end] = list[i];
68
+ p = startNode(nodes, start, p);
69
+ q = endNode(nodes, end, Math.max(q, p));
70
+ const range = makeRange();
71
+ range.setStart(nodes[p].node, start - nodes[p].start);
72
+ range.setEnd(nodes[q].node, end - nodes[q].start);
73
+ ranges.push(range);
74
+ }
75
+ return ranges;
76
+ }
77
+ // 单个匹配的 Range(不靠指针,二分定位)。
78
+ export function rangeAt(index, [start, end], makeRange) {
79
+ const { nodes } = index, p = bisect(nodes, start), q = endNode(nodes, end, p), range = makeRange();
80
+ range.setStart(nodes[p].node, start - nodes[p].start);
81
+ range.setEnd(nodes[q].node, end - nodes[q].start);
82
+ return range;
83
+ }
84
+
85
+ const highlightsSupported = () => typeof globalThis.CSS !== 'undefined' && !!globalThis.CSS.highlights && typeof globalThis.Highlight === 'function';
86
+ const mark = (name, options) => { try { globalThis.performance?.measure?.(name, options); } catch { /* 没有也不影响 */ } };
87
+
88
+ // body:正文滚动容器(.pbody);gutterWidth():行号列(sticky)的宽度,横向滚动要扣掉;
89
+ // makeRange():造 Range,测试可换。返回查找条(el)和控制它的方法。
90
+ export function createFind({ body, gutterWidth = () => 0, makeRange = () => document.createRange() }) {
91
+ const input = h('input', { type: 'search', class: 'finput', placeholder: '查找', enterkeyhint: 'search', autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off', spellcheck: 'false', 'aria-label': '在文件里查找' });
92
+ const count = h('span', { class: 'fcount caption secondary', 'aria-live': 'polite' });
93
+ const prev = h('button', { class: 'icon fprev', 'aria-label': '上一个', title: '上一个(⇧⌘G)' }, icon('chevron', 18));
94
+ const next = h('button', { class: 'icon fnext', 'aria-label': '下一个', title: '下一个(⌘G)' }, icon('chevron', 18));
95
+ const done = h('button', { class: 'link fdone' }, '完成');
96
+ const el = h('div', { class: 'fbar', role: 'search', hidden: true }, input, count, prev, next, done);
97
+
98
+ let open = false, term = '';
99
+ let content = null; // { el, text, index }:现在显示的这一版正文
100
+ let version = 0, runId = 0, debounce = null, batch = null;
101
+ let list = [], more = false, current = -1;
102
+ let marks = null; // { all, now }
103
+
104
+ const cancelWork = () => { runId++; clearTimeout(debounce); clearTimeout(batch); debounce = batch = null; };
105
+ const clearMarks = () => {
106
+ if (highlightsSupported()) { globalThis.CSS.highlights.delete('find'); globalThis.CSS.highlights.delete('find-current'); }
107
+ marks = null;
108
+ };
109
+ const indexOf = () => (content.index ??= buildIndex(content.el));
110
+
111
+ function paint() {
112
+ count.textContent = term === '' ? '' : !content ? '—' : list.length === 0 ? '0' : `${current + 1}/${more ? `${FIND_MAX}+` : list.length}`;
113
+ prev.disabled = next.disabled = list.length === 0;
114
+ }
115
+
116
+ // 可见区顶部之后的第一个匹配的下标:按行算(正文不折行,每行一样高);没有就是第一个。
117
+ function firstAfterTop() {
118
+ const text = content.el, box = text.getBoundingClientRect(), top = body.getBoundingClientRect().top - box.top;
119
+ const lh = parseFloat(globalThis.getComputedStyle?.(text)?.lineHeight) || 20, line = Math.max(0, Math.floor(top / lh));
120
+ let offset = 0;
121
+ for (let n = 0, at = content.text.indexOf('\n'); n < line && at !== -1; n++, at = content.text.indexOf('\n', at + 1)) offset = at + 1;
122
+ const at = list.findIndex(([start]) => start >= offset);
123
+ return at < 0 ? 0 : at;
124
+ }
125
+ // 起点离 near 最近的(差的绝对值最小,一样近取前一个)。
126
+ function nearest(near) {
127
+ let best = 0;
128
+ for (let i = 1; i < list.length; i++) if (Math.abs(list[i][0] - near) < Math.abs(list[best][0] - near)) best = i;
129
+ return best;
130
+ }
131
+
132
+ // 滚到这一处:只滚 body,竖向和横向都让它的起点进入可见区(横向扣掉行号列,键盘弹起时和 visualViewport 取交集),已经在可见区就不动。
133
+ function scrollInto(range) {
134
+ const r = range.getBoundingClientRect(), b = body.getBoundingClientRect(), view = globalThis.visualViewport;
135
+ const left = b.left + gutterWidth(), top = view ? Math.max(b.top, view.offsetTop) : b.top, bottom = view ? Math.min(b.bottom, view.offsetTop + view.height) : b.bottom;
136
+ if (bottom - top <= 0) return; // 可见区和 visualViewport 的交集是空的:没有地方可看,不滚
137
+ if (r.top < top || r.bottom > bottom) body.scrollTop += r.top - (top + Math.max(0, (bottom - top - r.height) / 2));
138
+ if (r.left < left || r.left > b.right) body.scrollLeft += r.left - (left + 24);
139
+ }
140
+
141
+ function showCurrent(scroll) {
142
+ const range = rangeAt(indexOf(), list[current], makeRange);
143
+ marks?.now.clear();
144
+ marks?.now.add(range);
145
+ if (scroll) scrollInto(range);
146
+ }
147
+
148
+ // 一次查找:scroll 为假时不滚动(正文换了、刷新);near 是旧的当前处的起点,给了就取离它最近的。
149
+ function run({ scroll = true, near = null } = {}) {
150
+ cancelWork();
151
+ clearMarks();
152
+ list = []; more = false; current = -1;
153
+ const mine = runId, ver = version, began = globalThis.performance?.now?.() ?? 0;
154
+ if (term !== '' && content) {
155
+ ({ list, more } = findMatches(content.text, term));
156
+ if (list.length) current = near === null ? firstAfterTop() : nearest(near);
157
+ }
158
+ paint();
159
+ if (list.length === 0) { mark('find-run', { start: began }); globalThis.performance?.mark?.('find-done'); return; }
160
+ if (highlightsSupported() && content.highlight) {
161
+ const all = new globalThis.Highlight(), now = new globalThis.Highlight();
162
+ all.priority = 0;
163
+ now.priority = 1; // 当前这处盖在全部匹配上面,不靠注册的先后
164
+ marks = { all, now };
165
+ globalThis.CSS.highlights.set('find', all);
166
+ globalThis.CSS.highlights.set('find-current', now);
167
+ }
168
+ showCurrent(scroll);
169
+ if (!marks) { mark('find-run', { start: began }); globalThis.performance?.mark?.('find-done'); return; }
170
+ let at = 0;
171
+ const step = () => {
172
+ if (mine !== runId || ver !== version) return; // 换词、换正文、关闭:停
173
+ const t0 = globalThis.performance?.now?.() ?? 0, to = Math.min(list.length, at + FIND_BATCH);
174
+ for (const range of rangesFor(indexOf(), list, at, to, makeRange)) marks.all.add(range);
175
+ at = to;
176
+ mark('find-batch', { start: t0 });
177
+ if (at < list.length) batch = setTimeout(step, 0); // 让出到宏任务:输入和绘制能插进来
178
+ else globalThis.performance?.mark?.('find-done');
179
+ };
180
+ step();
181
+ mark('find-run', { start: began }); // 这次查找同步算的部分:找匹配、定当前这处、标第一批
182
+ }
183
+
184
+ const go = step => {
185
+ if (list.length === 0) return;
186
+ current = (current + step + list.length) % list.length;
187
+ paint();
188
+ showCurrent(true);
189
+ };
190
+
191
+ input.addEventListener('input', () => {
192
+ term = input.value;
193
+ cancelWork();
194
+ if (term === '') return run();
195
+ debounce = setTimeout(() => { debounce = null; run(); }, FIND_DEBOUNCE_MS);
196
+ });
197
+ input.addEventListener('keydown', event => {
198
+ if (event.isComposing) return;
199
+ const bare = !event.metaKey && !event.ctrlKey && !event.altKey;
200
+ if (event.key === 'Enter' && bare) { event.preventDefault(); go(event.shiftKey ? -1 : 1); }
201
+ });
202
+ prev.addEventListener('click', () => go(-1));
203
+ next.addEventListener('click', () => go(1));
204
+
205
+ return {
206
+ el, input, done,
207
+ get isOpen() { return open; },
208
+ get term() { return term; },
209
+ get count() { return count.textContent; },
210
+ get current() { return list.length ? list[current] : null; },
211
+ get total() { return list.length; },
212
+ get supported() { return highlightsSupported(); },
213
+ // 打开并聚焦;已经开着就选中输入框里的字。
214
+ open() {
215
+ const was = open;
216
+ open = true;
217
+ el.hidden = false;
218
+ body.classList.add('finding'); // 高亮的样式规则只在查找开着时生效(style.css)
219
+ input.focus();
220
+ if (was) input.select?.();
221
+ },
222
+ // 关:立刻取消防抖和计算,删掉注册的 Highlight,关查找条;搜索词一并清掉。
223
+ close() {
224
+ cancelWork();
225
+ clearMarks();
226
+ open = false;
227
+ body.classList.remove('finding');
228
+ term = '';
229
+ input.value = '';
230
+ list = []; more = false; current = -1;
231
+ el.hidden = true;
232
+ paint();
233
+ },
234
+ // 换了一版正文(show):词和查找条留着,重新找;当前这处取离旧起点最近的,不滚动。
235
+ // highlight 为假(有长行的文件)时不标颜色,只计数、导航、滚动,同浏览器不支持 Highlight API。
236
+ setContent(textEl, text, { highlight = true } = {}) {
237
+ content = { el: textEl, text, index: null, highlight };
238
+ version++;
239
+ if (open) run({ scroll: false, near: current >= 0 ? list[current][0] : null });
240
+ },
241
+ // 正文没了(读取中、文件没了、整页重读失败):清掉标记,计数写「—」;之后再 setContent 就重新找。
242
+ clearContent() {
243
+ content = null;
244
+ version++;
245
+ cancelWork();
246
+ clearMarks();
247
+ list = []; more = false; current = -1;
248
+ paint();
249
+ },
250
+ next: () => go(1),
251
+ prev: () => go(-1),
252
+ // 跳到上一个、下一个(⌘G、⇧⌘G)由预览的键盘处理调用。
253
+ };
254
+ }
package/view/grid.mjs CHANGED
@@ -4,8 +4,8 @@ import { h } from './dom.mjs';
4
4
  import { infoText } from './format.mjs';
5
5
  import { mountGestures } from './gestures.mjs';
6
6
  import { icon, iconFor } from './icons.mjs';
7
- import { isHidden, joinPath } from './model.mjs';
8
- import { EntryKind } from './protocol.mjs';
7
+ import { joinPath } from './model.mjs';
8
+ import { EntryKind, isHidden } from './protocol.mjs';
9
9
  import { TITLES, rootName } from './tree.mjs';
10
10
 
11
11
  const OVERSCAN = 2; // 上下多画几行
@@ -234,6 +234,15 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
234
234
  else if (top + cellH > body.scrollTop + body.clientHeight) body.scrollTop = top + cellH - body.clientHeight;
235
235
  paint();
236
236
  };
237
+ // 滚到这个条目在可见区中间(定位操作的最后一步);找不到返回 false。调用前先 render()。
238
+ const center = path => {
239
+ const index = cells.findIndex(cell => cell.type === 'entry' && cell.path === path);
240
+ if (index < 0) return false;
241
+ const top = (spacer.offsetTop || 0) + rowTop(layout, rowOfCell(layout, index), cellH, noteH);
242
+ body.scrollTop = Math.max(0, top - (body.clientHeight - cellH) / 2);
243
+ paint();
244
+ return true;
245
+ };
237
246
  body.addEventListener('scroll', paint, { passive: true });
238
247
  new ResizeObserver(relayout).observe(body);
239
248
 
@@ -254,6 +263,7 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
254
263
  onScroll(fn) { body.addEventListener('scroll', fn, { passive: true }); },
255
264
  get layout() { return layout; },
256
265
  select: mark,
266
+ center,
257
267
  activate,
258
268
  focus() { body.focus(); },
259
269
  onKey(fn) { body.addEventListener('keydown', fn); },
package/view/icons.mjs CHANGED
@@ -56,6 +56,8 @@ const SHAPES = {
56
56
  refresh: { shapes: [['path', { d: 'M19 12a7 7 0 1 1-2.05-4.95' }], ['path', { d: 'M19 4.5v3.8h-3.8' }]] },
57
57
  copy: { shapes: [['rect', { x: 8.5, y: 8.5, width: 11, height: 11, rx: 2.2 }], ['path', { d: 'M15.5 8.5V6.7a2.2 2.2 0 0 0-2.2-2.2H6.7a2.2 2.2 0 0 0-2.2 2.2v6.6a2.2 2.2 0 0 0 2.2 2.2h1.8' }]] },
58
58
  window: { shapes: [['rect', { x: 3.5, y: 5, width: 17, height: 14, rx: 2.5 }], ['path', { d: 'M3.5 9.5h17' }]] },
59
+ search: { shapes: [['circle', { cx: 10.5, cy: 10.5, r: 6 }], ['path', { d: 'm15 15 5.5 5.5' }]] },
60
+ clear: { shapes: [['circle', { cx: 12, cy: 12, r: 8.5 }], ['path', { d: 'm9 9 6 6M15 9l-6 6' }]] },
59
61
  turn: { shapes: [['path', { d: 'M5 18v-4a4 4 0 0 1 4-4h10' }], ['path', { d: 'm15 6 4 4-4 4' }]] },
60
62
  };
61
63
 
package/view/index.html CHANGED
@@ -9,8 +9,14 @@
9
9
  <body>
10
10
  <div id="bar" class="bar" hidden></div>
11
11
  <main id="stage">
12
- <div id="tree" class="pane tree" role="tree"></div>
13
- <div id="grid" class="pane grid"></div>
12
+ <div id="browse" class="pane browse">
13
+ <div id="searchbar" class="searchbar" role="search"></div>
14
+ <div id="panes">
15
+ <div id="tree" class="pane tree" role="tree"></div>
16
+ <div id="grid" class="pane grid"></div>
17
+ <div id="search" class="pane search"></div>
18
+ </div>
19
+ </div>
14
20
  <div id="preview" class="pane preview" tabindex="-1"></div>
15
21
  <div id="notice" class="pane empty secondary"></div>
16
22
  <div id="info" class="pane preview info"></div>
@@ -0,0 +1,82 @@
1
+ // 「在目录中显示」:一次可以取消的定位操作,由页面发起、页面持有,读目录复用模型的接口(设计见 docs/design/phase-3.md 第 18.3 节)。
2
+ // 五样:
3
+ // - 持有:这个 locator,run 是定位轮次;开始时加一,又发起一次、cancel()、完成时都加一。
4
+ // - 作废:身份(会话、根目录、排序、视图、隐藏开关、模型的刷新轮次,由页面拼成一个串)变了,或用户接管计数变了,或轮次变了。
5
+ // 用户接管只看用户的输入(pointerdown、wheel、touchstart、keydown、菜单里的操作),程序自己的展开、进入目录、滚动、选中都不算。
6
+ // - 结束:找到(最后一次核对身份,选中并居中,同一个同步过程里标成完成)、读尽了没有、到上限、读失败、作废。
7
+ // - 超时:每一页读取由 link 的 30 秒兜底;失败就结束,不按 next 自动重试同一页。
8
+ // - 被替换:新的定位让旧的作废;作废后不再选中、不再滚动,已经展开的上层和已经读到的条目留着。
9
+ import { RESTORE_LIMIT, View, parentOf } from './model.mjs';
10
+
11
+ export const MESSAGES = {
12
+ end: '找不到这一项,可能已被删除或改名',
13
+ limit: '已打开所在的文件夹,这一项在前 2 万条之外',
14
+ };
15
+
16
+ // model;identity():身份串;takeover():用户接管计数;
17
+ // ops:{ begin(parent | null):清空搜索、丢掉目标视图还在等的滚动恢复,图标视图时进入上一层(parent);render():同步重画正在用的视图;
18
+ // select(path)、center(path):选中并居中;openFolder(path):定位到文件夹之后展开它或进入它;notify(text):提示 }
19
+ export function createLocator({ model, identity, takeover, ops }) {
20
+ let run = 0;
21
+
22
+ // 这一级目录里有没有这一项:加载好,没有就取下一页,直到找到、读尽或到上限。
23
+ async function ensure(dir, name, alive) {
24
+ const first = await model.whenLoaded(dir);
25
+ if (!alive()) return 'void';
26
+ if (first !== 'ok') return first === 'failed' ? 'failed' : 'void';
27
+ for (;;) {
28
+ const state = model.dirs.get(dir);
29
+ if (!state) return 'void';
30
+ if (state.entries.some(entry => entry.name === name)) return 'found';
31
+ if (!state.next) return 'end';
32
+ if (state.entries.length >= RESTORE_LIMIT) return 'limit'; // 按这个目录已有的条数算:用户翻出来的留着;一页越过上限时这一页照样用完
33
+ const outcome = await model.fetchNext(dir);
34
+ if (!alive()) return 'void';
35
+ if (outcome === 'failed' || outcome === 'void') return outcome;
36
+ }
37
+ }
38
+
39
+ return {
40
+ // 作废在做的定位(页面里重新输入搜索词时调用)。
41
+ cancel() { run++; },
42
+
43
+ // 返回结局:found、end、limit、failed、void(测试用)。open:找到的是文件夹时再展开它或进入它。
44
+ async show(path, { open = false } = {}) {
45
+ const mine = ++run, id = identity(), taken = takeover();
46
+ const alive = () => run === mine && identity() === id && takeover() === taken;
47
+ const icons = model.view === View.ICONS, segments = path.split('/');
48
+ ops.begin(icons ? parentOf(path) : null);
49
+ const finish = outcome => {
50
+ if (outcome === 'end' || outcome === 'limit') ops.notify(MESSAGES[outcome]);
51
+ return outcome;
52
+ };
53
+ let outcome;
54
+ if (icons) outcome = await ensure(parentOf(path), segments[segments.length - 1], alive);
55
+ else {
56
+ let dir = '';
57
+ outcome = 'found';
58
+ for (let i = 0; i < segments.length && outcome === 'found'; i++) {
59
+ const here = dir === '' ? segments[i] : `${dir}/${segments[i]}`;
60
+ outcome = await ensure(dir, segments[i], alive);
61
+ if (outcome !== 'found') break;
62
+ if (i < segments.length - 1) { // 上层:确保已展开、并且读到了
63
+ if (!model.expanded.has(here)) model.toggle(here);
64
+ const loaded = await model.whenLoaded(here);
65
+ if (!alive()) return 'void';
66
+ if (loaded !== 'ok') outcome = loaded === 'failed' ? 'failed' : 'void';
67
+ }
68
+ dir = here;
69
+ }
70
+ }
71
+ if (!alive()) return 'void';
72
+ if (outcome !== 'found') return finish(outcome);
73
+ // 找到:最后一次核对身份之后,在同一个同步过程里选中、居中,并把定位标成完成;完成之后的任何事件都和它无关。
74
+ ops.render();
75
+ ops.select(path);
76
+ ops.center(path);
77
+ run++;
78
+ if (open) ops.openFolder(path);
79
+ return 'found';
80
+ },
81
+ };
82
+ }
package/view/menu.mjs CHANGED
@@ -81,7 +81,7 @@ export function mountMenu(el, sub = null, { flyout = false, animate = false } =
81
81
  if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
82
82
  button.addEventListener('click', () => {
83
83
  if (!alive()) return; // 菜单已经关了(换成了别的、退回了上一层):留在手里的按钮不再响应
84
- hide();
84
+ hide(true);
85
85
  run();
86
86
  });
87
87
  }
@@ -193,14 +193,18 @@ export function mountMenu(el, sub = null, { flyout = false, animate = false } =
193
193
  // 安全区的左边:body 的左内边距就是它(style.css),算出来的是像素。读不到按 0。
194
194
  const safeLeft = () => { const px = parseFloat(globalThis.getComputedStyle?.(document.body)?.paddingLeft); return Number.isFinite(px) ? px : 0; };
195
195
 
196
- function hide() {
196
+ // restore:关菜单后把焦点交回打开它的按钮(Esc 关、选了一项之后)。点菜单外、滚动、旋转关的不交:点到哪里焦点就在哪里。
197
+ // 选项的操作在交回焦点之后才执行,操作自己要移焦点(如「查找」聚焦查找条)时以操作为准。没有按钮的菜单(右键、原生按钮的假锚点)焦点不动。
198
+ function hide(restore = false) {
197
199
  settle();
198
200
  current = null;
199
201
  layer++;
200
202
  collapse();
201
203
  el.hidden = true;
204
+ const back = opener;
202
205
  opener?.setAttribute?.('aria-expanded', 'false');
203
206
  opener = null;
207
+ if (restore === true) back?.focus?.(); // 严格比较:hide 也被直接当事件回调用(滚动、resize、blur),Event 对象是真值
204
208
  }
205
209
 
206
210
  // 两个面板都算菜单里面。菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
@@ -216,9 +220,16 @@ export function mountMenu(el, sub = null, { flyout = false, animate = false } =
216
220
  document.addEventListener('click', event => {
217
221
  if (dismissed) { dismissed = false; event.stopPropagation(); }
218
222
  }, true);
219
- document.addEventListener('keydown', event => { if (event.key === 'Escape') hide(); });
220
- window.addEventListener('blur', hide);
221
- window.addEventListener('resize', hide); // 旋转、拖窄侧栏:位置对不上了
223
+ // Esc 关菜单时同样标成「已消费」:同一次按键上的搜索框、结果列表、查找条不再清搜索、关查找条或移焦点(第 18.5 节)。
224
+ // 挂在 document 的捕获阶段:捕获先于目标和冒泡经过的所有元素,「已消费」的标记一定在它们的监听执行之前加上(冒泡阶段就晚了:预览元素的监听先执行)。
225
+ // 关菜单和交还焦点之后,同一个事件还会派发到原目标,原目标上的监听看到 consumed 为真,什么都不做。
226
+ document.addEventListener('keydown', event => {
227
+ if (event.key !== 'Escape') return;
228
+ if (!el.hidden) eaten.add(event);
229
+ hide(true);
230
+ }, true);
231
+ window.addEventListener('blur', () => hide());
232
+ window.addEventListener('resize', () => hide()); // 旋转、拖窄侧栏:位置对不上了
222
233
  sub?.addEventListener('pointerenter', keep);
223
234
 
224
235
  return {
package/view/model.mjs CHANGED
@@ -8,8 +8,6 @@ export const MAX_LOADED = 100_000; // 读回保存的条数时认的上界(vie
8
8
  // 只管「按保存的条数恢复」,用户已经翻出来的条数不受限;也和 lib/tree.mjs 的目录上限无关。
9
9
  export const RESTORE_LIMIT = 20_000;
10
10
  const MAX_LOADED_DIRS = 500;
11
- const HIDDEN = new Set(['.git', '.DS_Store']);
12
- export const isHidden = name => HIDDEN.has(name);
13
11
  export const joinPath = (dir, name) => (dir ? `${dir}/${name}` : name);
14
12
  export const parentOf = path => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
15
13
  const inside = (path, dir) => path === dir || path.startsWith(`${dir}/`);
@@ -61,6 +59,8 @@ export class Model {
61
59
  constructor({ link, onChange = () => {}, onLost = () => {} }) { Object.assign(this, { link, onChange, onLost }); }
62
60
 
63
61
  get ready() { return this.root?.state === RootState.READY; }
62
+ // 刷新的轮次:换会话和每次 refresh(含换排序、换视图、changed)都加一。定位操作拿它判断「期间有没有刷新过」。
63
+ get round() { return this.#round; }
64
64
 
65
65
  // 模块来的消息统一从这里进。session 带上这个会话保存的状态;返回值同各个处理方法。
66
66
  receive(message, saved = null) {
@@ -173,15 +173,22 @@ export class Model {
173
173
 
174
174
  // 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。一次加载固定一种排序。
175
175
  // more、expired:「再显示」遇到游标过期转过来时,条数要比现在多一条,而且已经算重取过一次,不再重取。
176
- async #reload(path, generation, { cap = Infinity, more = false, expired = false } = {}) {
177
- if (this.link.generation !== generation) return; // 排队时会话已换,旧任务不碰新会话
176
+ // 返回结局(定位操作等着它):ok(取够并提交了)、failed(失败,失败行照常显示)、void(被作废:会话换了、有更新的加载、目录没了)。
177
+ // 正在进行的这一次记在 dir.pending 上,whenLoaded 等它。
178
+ #reload(path, generation, { cap = Infinity, more = false, expired = false } = {}) {
179
+ if (this.link.generation !== generation) return Promise.resolve('void'); // 排队时会话已换,旧任务不碰新会话
178
180
  let dir = this.dirs.get(path);
179
- if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false });
181
+ if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false, pending: null });
182
+ return dir.pending = this.#load(dir, path, generation, { cap, more, expired });
183
+ }
184
+
185
+ async #load(dir, path, generation, { cap, more, expired }) {
180
186
  const token = ++dir.token, { sort } = this, nav = this.#nav;
181
187
  const want = more ? dir.entries.length + 1 : Math.min(Math.max(dir.entries.length, this.wanted.get(path) ?? 0), cap);
182
188
  dir.loading = true;
183
189
  this.onChange();
184
190
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
191
+ let outcome = 'void';
185
192
  try {
186
193
  let entries = [], next = null, pages = 0, sortFallback = false;
187
194
  do {
@@ -195,27 +202,39 @@ export class Model {
195
202
  entries = []; next = null; pages = 0; sortFallback = false;
196
203
  continue;
197
204
  }
198
- if (!current()) return; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
205
+ if (!current()) return 'void'; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
199
206
  if (pages === 0) sortFallback = reply.sortFallback === true;
200
207
  entries.push(...reply.entries);
201
208
  next = reply.nextCursor ?? null;
202
209
  pages++;
203
210
  } while (pages === 0 || (next && entries.length < want));
204
- if (!current()) return;
211
+ if (!current()) return 'void';
205
212
  Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback, sort });
206
213
  this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
207
214
  if (path === this.cwd) this.#quiet = false;
215
+ outcome = 'ok';
208
216
  } catch (error) {
209
- if (error.stale || !current()) return;
217
+ if (error.stale || !current()) return 'void';
210
218
  if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#lost(path, nav);
211
219
  else if (error.code !== ErrorCode.NO_ROOT) {
212
220
  dir.error = { code: error.code, message: error.message };
213
221
  if (path === this.cwd) this.#quiet = false;
222
+ outcome = 'failed';
214
223
  }
215
224
  } finally {
216
225
  if (current()) dir.loading = false;
217
226
  this.onChange();
218
227
  }
228
+ return outcome;
229
+ }
230
+
231
+ // 等这个目录正在进行的加载(或「再显示」)结束,给出同样的四种结局:ok、end(没有下一页了,只对 fetchNext)、failed、void。
232
+ // 没在加载:已加载的是 ok,只有失败行的是 failed,没有这个目录的是 void。
233
+ async whenLoaded(path) {
234
+ const dir = this.dirs.get(path);
235
+ if (!dir) return 'void';
236
+ if (dir.loading && dir.pending) return dir.pending;
237
+ return dir.loaded ? 'ok' : dir.error ? 'failed' : 'void';
219
238
  }
220
239
 
221
240
  // 目录没了(not_found):所有列目录入口都走这里。先清掉失效的子树;cwd 在里面、而且发出请求以来没有导航过,就退到上一层。
@@ -256,30 +275,51 @@ export class Model {
256
275
  retry(path) { return this.ready ? this.#reload(path, this.link.generation) : Promise.resolve(); }
257
276
 
258
277
  // 「再显示」:取下一页接在后面。
259
- async loadMore(path) {
278
+ async loadMore(path) { await this.#more(path); }
279
+
280
+ // 取下一页接在后面,告诉调用方结局(定位操作用):ok(接上了新条目)、end(没有下一页了)、failed(失败,失败行照常显示)、void(这次读取被作废了)。
281
+ // 不碰 wanted,也不按 wanted 取够;目录正在加载时由调用方先 whenLoaded。
282
+ async fetchNext(path) { return this.#more(path); }
283
+
284
+ async #more(path) {
260
285
  const dir = this.dirs.get(path), { generation } = this.link;
261
- if (!dir?.next || dir.loading || !this.ready) return;
286
+ if (!dir || !this.ready || dir.loading) return 'void';
287
+ if (!dir.next) return 'end';
262
288
  // 游标是按另一种排序取的(换排序时这个目录没重建过):不用它,从第一页重取,条数比现在多一条。
263
- if (dir.sort !== this.sort) return this.#reload(path, generation, { more: true, expired: true });
289
+ if (dir.sort !== this.sort) return this.#grown(path, dir, generation);
290
+ return dir.pending = this.#page(dir, path, generation); // 本次读取登记在 dir.pending 上:whenLoaded 等的就是它(游标过期后的重取经 #reload,自己登记)
291
+ }
292
+
293
+ async #page(dir, path, generation) {
264
294
  const token = ++dir.token, nav = this.#nav;
265
295
  dir.loading = true;
266
296
  this.onChange();
267
297
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
298
+ let outcome = 'void';
268
299
  try {
269
300
  const reply = await this.link.call('list', { path, cursor: dir.next, sort: this.sort });
270
- if (!current()) return;
301
+ if (!current()) return 'void';
271
302
  dir.entries = dir.entries.concat(reply.entries);
272
303
  Object.assign(dir, { next: reply.nextCursor ?? null, error: null, pages: dir.pages + 1 });
304
+ outcome = 'ok';
273
305
  } catch (error) {
274
- if (error.stale || !current()) return;
306
+ if (error.stale || !current()) return 'void';
275
307
  // 游标过期:从第一页重取,条数比现在多一条,所以还会接着往下取。重取自己管 loading。
276
- if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#reload(path, generation, { more: true, expired: true });
277
- if (error.code === ErrorCode.NOT_FOUND && path !== '') return this.#lost(path, nav);
278
- dir.error = { code: error.code, message: error.message };
308
+ if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#grown(path, dir, generation);
309
+ if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#lost(path, nav);
310
+ else { dir.error = { code: error.code, message: error.message }; outcome = 'failed'; }
279
311
  } finally {
280
312
  if (current()) dir.loading = false;
281
313
  this.onChange();
282
314
  }
315
+ return outcome;
316
+ }
317
+
318
+ // 从第一页重取、条数比现在多一条(已经算重取过一次):结局按条数有没有增加给。
319
+ async #grown(path, dir, generation) {
320
+ const before = dir.entries.length;
321
+ const outcome = await this.#reload(path, generation, { more: true, expired: true });
322
+ return outcome === 'ok' ? (this.dirs.get(path)?.entries.length > before ? 'ok' : 'end') : outcome;
283
323
  }
284
324
 
285
325
  // 选中只影响高亮,不发 onChange:重画会换掉全部行节点,双击的第二下点击之后 dblclick 就丢了。页面的 selectEntry 负责切高亮和保存。返回是不是变了。
@@ -288,8 +328,14 @@ export class Model {
288
328
  this.selected = path;
289
329
  return true;
290
330
  }
291
- // Mac 打开文件:选中它并切到预览。返回(closeFile)只清 opened,选中留着。
292
- openFile(path) { this.selected = this.opened = path; this.onChange(); }
331
+ // 打开文件分两步:设预览(opened)、设选中(selected),在同一次同步操作里做完,只触发一次重画。
332
+ // 目录树里打开两步都做;从搜索结果里打开只设预览(结果有自己的选中,不改被遮住的目录树的选中)。
333
+ // 返回(closeFile)只清 opened,选中留着。
334
+ openFile(path, { select = true } = {}) {
335
+ this.opened = path;
336
+ if (select) this.selected = path;
337
+ this.onChange();
338
+ }
293
339
  closeFile() { this.opened = null; this.onChange(); }
294
340
  setShowHidden(on) { this.showHidden = on; this.onChange(); }
295
341
  // loaded:取过不止一页的目录已加载的条数,只存条数不存内容;第一页每次都会重新取,不用存。
package/view/press.mjs CHANGED
@@ -15,13 +15,14 @@ export const onMotionChange = fn => globalThis.matchMedia?.(QUERY)?.addEventList
15
15
 
16
16
  // 点到的可按元素:{ node, key }。key 是列表里一行的身份(视图、种类、路径),按钮没有(按节点记)。
17
17
  // 可按:没有 disabled 的 button、.row.entry、.row.more、.row.retry、.cell、.gnote.more、.gnote.retry;.dead 的条目也算(它们能选中、能右键)。
18
+ // 列表的行有三种画面:目录树(tree)、搜索结果(search,行上带 .hit)、图标视图(grid),身份里记哪一种,同一路径在不同画面里不是同一个按下。
18
19
  function targetOf(event) {
19
20
  const node = event.target?.closest?.('.row, .cell, .gnote, button');
20
21
  if (!node) return null;
21
22
  if (node.tagName === 'BUTTON') return node.disabled || node.getAttribute('disabled') !== null ? null : { node, key: null };
22
23
  const has = name => node.classList.contains(name), path = node.dataset.path;
23
24
  const kind = has('cell') || has('entry') ? 'entry' : has('retry') ? 'retry' : has('more') ? 'more' : null;
24
- return kind === null || path === undefined ? null : { node, key: `${has('row') ? 'tree' : 'grid'}\n${kind}\n${path}` };
25
+ return kind === null || path === undefined ? null : { node, key: `${has('hit') ? 'search' : has('row') ? 'tree' : 'grid'}\n${kind}\n${path}` };
25
26
  }
26
27
 
27
28
  // identity():会话和根目录的身份(model.session、model.scope 拼成的字符串);换了就不是同一个按下。