@coda-console/resource-manager 0.7.1 → 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.
@@ -1,6 +1,6 @@
1
1
  // 页面到模块的连接:请求与回答(Link)、hello 握手与超时、按代次分发协议消息。
2
2
  // 树页和文件页共用。只管连接:树的 Model、状态保存、提示文案和 DOM 都在各自的页面里。
3
- import { ErrorCode, Type, isReply, messageSize } from './protocol.mjs';
3
+ import { ErrorCode, REQUEST_ID_MAX, ReplyOf, Type, isReply, messageSize } from './protocol.mjs';
4
4
 
5
5
  export const TIMEOUT_MS = 30_000;
6
6
 
@@ -10,17 +10,24 @@ export class Stale extends Error { constructor() { super('已过期'); this.stal
10
10
  export class Cancelled extends Stale { constructor() { super(); this.cancelled = true; } }
11
11
  export class RequestError extends Error { constructor(code, message) { super(message); this.code = code; } }
12
12
 
13
- // 请求与回答按 requestId 对应。回答要代次相同、请求号还在等待才算;换会话时 reset 作废所有等待并停掉超时。
13
+ // 页面实例的请求号前缀:页面加载时生成一次。重建后的新页面请求号从 1 重新数,没有前缀就会和旧页面还在路上的回答撞上。
14
+ export const newPrefix = () => Math.random().toString(36).slice(2, 10);
15
+
16
+ // 请求与回答按 requestId 对应。回答要代次相同、请求号还在等待、类型是这个请求该收的那种才算;换会话时 reset 作废所有等待并停掉超时。
14
17
  // 一个请求只在 #finish 里结算:回答、发送失败、超时、代次失效、取消都走它,只结算一次,同时清掉定时器和取消监听。
15
18
  export class Link {
16
19
  generation = null;
17
20
  pending = new Map();
18
21
  #next = 1;
19
22
 
20
- constructor({ post, timers = globalThis, timeoutMs = TIMEOUT_MS }) {
23
+ // prefix:请求号带它(<前缀>-q1),总长不超过 REQUEST_ID_MAX;不给就是 q1,测试和手动传输用。
24
+ constructor({ post, timers = globalThis, timeoutMs = TIMEOUT_MS, prefix = '' }) {
21
25
  Object.assign(this, { post, timers, timeoutMs });
26
+ this.prefix = prefix === '' ? '' : `${prefix.slice(0, REQUEST_ID_MAX - 12)}-`;
22
27
  }
23
28
 
29
+ #id(n) { return `${this.prefix}q${n}`; }
30
+
24
31
  // 结算 requestId 对应的等待:还在等才算,返回是否结算了。
25
32
  #finish(requestId, settle) {
26
33
  const entry = this.pending.get(requestId);
@@ -39,7 +46,7 @@ export class Link {
39
46
 
40
47
  // 这条请求发出去的消息有多大(含信封):用下一个请求号算,和 call 真正发出的一致。页面用它在发之前判断会不会超过消息上限。
41
48
  size(type, fields) {
42
- return messageSize({ type, generation: this.generation, requestId: `q${this.#next}`, ...fields });
49
+ return messageSize({ type, generation: this.generation, requestId: this.#id(this.#next), ...fields });
43
50
  }
44
51
 
45
52
  // options.signal:中止后请求静默作废(Cancelled)。options.cancel:中止时还要告诉模块的消息类型,带 generation 和 requestId;
@@ -47,11 +54,11 @@ export class Link {
47
54
  call(type, fields, { signal, cancel } = {}) {
48
55
  if (this.generation === null) return Promise.reject(new Stale());
49
56
  if (signal?.aborted) return Promise.reject(new Cancelled());
50
- const { generation } = this, requestId = `q${this.#next++}`;
57
+ const { generation } = this, requestId = this.#id(this.#next++);
51
58
  return new Promise((resolve, reject) => {
52
59
  const fire = error => this.#finish(requestId, entry => entry.reject(error));
53
60
  const timer = this.timers.setTimeout(() => fire(new RequestError('timeout', '30 秒没有回答')), this.timeoutMs);
54
- const entry = { resolve, reject, timer, signal, posted: false };
61
+ const entry = { resolve, reject, timer, signal, posted: false, type };
55
62
  entry.onAbort = () => {
56
63
  const { posted } = entry;
57
64
  if (fire(new Cancelled()) && cancel && posted) this.#notify({ type: cancel, generation, requestId });
@@ -73,6 +80,9 @@ export class Link {
73
80
 
74
81
  receive(message) {
75
82
  if (message.generation !== this.generation) return false;
83
+ // 回答的类型不是这个请求该收的(别的页面实例的旧回答撞上了同一个请求号):不结算,请求继续等它自己的回答。
84
+ const entry = this.pending.get(message.requestId);
85
+ if (entry && ReplyOf[entry.type] !== message.type) return false;
76
86
  return this.#finish(message.requestId, entry => {
77
87
  if (message.error) entry.reject(new RequestError(message.error.code, message.error.message));
78
88
  else entry.resolve(message);
@@ -86,7 +96,7 @@ export class Link {
86
96
  // 握手的结束条件是收到首个 root;之后不再提示超时。
87
97
  // onStatus:握手状态变了(开始、失败、重试)时调用,页面据此重画说明。
88
98
  export function connect(coda, { handlers, onStatus = () => {} }) {
89
- const link = new Link({ post: message => coda.postMessage(message) });
99
+ const link = new Link({ post: message => coda.postMessage(message), prefix: newPrefix() });
90
100
  let answered = false, timer = null, failure = null;
91
101
 
92
102
  function fail(reason) {
package/view/file-app.mjs CHANGED
@@ -10,6 +10,7 @@ import { mountMenu } from './menu.mjs';
10
10
  import { noticeText } from './model.mjs';
11
11
  import { showNotice } from './notice.mjs';
12
12
  import { mountPreview } from './preview.mjs';
13
+ import { mountPress } from './press.mjs';
13
14
  import { RootState } from './protocol.mjs';
14
15
 
15
16
  const coda = window.coda;
@@ -36,10 +37,12 @@ let restore = parseScroll(quiet(() => coda.getState()));
36
37
  const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
37
38
  const hint = mountHint($('hint'));
38
39
  const menu = mountMenu($('menu'));
40
+ const press = mountPress({ consumed: menu.consumed }); // 按下反馈:刷新、复制、重试等按钮同资源页(第 17.3 节)
39
41
  const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint });
40
42
  const preview = mountPreview($('preview'), {
41
43
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
42
44
  selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
45
+ consumed: menu.consumed,
43
46
  });
44
47
 
45
48
  // 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
@@ -94,6 +97,7 @@ function paintNotice() {
94
97
 
95
98
  // ---- 模块的消息(代次和握手由 connection 处理)----
96
99
  function onSession(data) {
100
+ press.reset();
97
101
  park();
98
102
  preview.close();
99
103
  menu.hide();
@@ -105,6 +109,7 @@ function onSession(data) {
105
109
 
106
110
  function onRoot(data) {
107
111
  const before = root;
112
+ if (data.state !== before?.state || data.path !== before?.path) press.reset();
108
113
  if (data.state !== before?.state || data.path !== before?.path) menu.hide(); // 选区和行号是旧内容上的
109
114
  root = { state: data.state, path: data.path };
110
115
  if (data.state === RootState.READY) {
@@ -122,7 +127,7 @@ function onChanged() {
122
127
  // ---- 参数变了:换文件或换会话,旧文件的滚动位置不带过去 ----
123
128
  quiet(() => coda.on('context', ({ args }) => {
124
129
  const next = argsOf(args);
125
- if (next.path !== want.path || next.session !== want.session) { restore = null; preview.close(); menu.hide(); hint.hide(); }
130
+ if (next.path !== want.path || next.session !== want.session) { press.reset(); restore = null; preview.close(); menu.hide(); hint.hide(); }
126
131
  want = next;
127
132
  schedule();
128
133
  }));
@@ -147,9 +152,16 @@ function saveNow() {
147
152
  if (at) quiet(() => coda.setState({ v: 1, top: at.top, left: at.left }));
148
153
  }
149
154
  // visibility: false 之后只保证同步事件处理完,所以同步保存。
150
- quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
155
+ quiet(() => coda.on('visibility', visible => { if (!visible) { press.reset(); saveNow(); } }));
151
156
  preview.onScroll(queueSave);
152
157
  preview.onScroll(menu.hide);
153
158
 
159
+ // ⌘F:能查找的文本打开查找条(「窗口」同一个预览,同一个查找);其他不拦。菜单开着时先关菜单。
160
+ document.addEventListener('keydown', event => {
161
+ if (isIOS || event.isComposing || !event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.key?.toLowerCase() !== 'f') return;
162
+ if (!menu.hidden) menu.hide();
163
+ if (preview.canFind) { event.preventDefault(); preview.openFind(); }
164
+ });
165
+
154
166
  render();
155
167
  conn.hello();
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/gestures.mjs CHANGED
@@ -7,10 +7,11 @@ export const HOLD_SLOP = 10;
7
7
  // hit(event) → 点到的那一项或 undefined;pressable(item):能不能弹菜单、拖动、长按(目录树的说明行、「再显示」不能);
8
8
  // activate(item):点击(iPhone);Mac 给了 select 就按 Finder 的规则:单击条目只 select(item),单击空白 select(null),双击条目才 activate(item);
9
9
  // 说明行、「再显示」这类不能选的项单击就 activate,direct(event, item) 为真的点击(展开箭头)也直接 activate、不选中,双击它不再重复激活。
10
+ // Mac 的选中在按下时做(左键,同 Finder),不等松开:右键、按住 Control 的左键(Mac 上是右键菜单)、被菜单消费的按下(consumed(event):菜单开着时点外面只关菜单)都不选中。
10
11
  // 双击靠浏览器的 dblclick,要求派发时目标节点还在容器里,所以 select 不能重画。menu(event, item):右键,长按到点时收到 { clientX, clientY };dragText(item):拖动时带的文字(元素是否可拖由调用方设 draggable);
11
12
  // longPress:触屏上按住一项打开 menu,不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
12
13
  // 返回 { reset, dispose }:reset 在切会话时调用,长按的等待和吞点击的标记都属于上一个会话;dispose 摘掉全部监听。
13
- export function mountGestures(el, { hit, pressable, activate, select, direct = () => false, menu, dragText, longPress = false, scroller = el }) {
14
+ export function mountGestures(el, { hit, pressable, activate, select, direct = () => false, menu, dragText, longPress = false, consumed = () => false, scroller = el }) {
14
15
  const listeners = [];
15
16
  const on = (target, type, fn, options) => { target.addEventListener(type, fn, options); listeners.push([target, type, fn]); };
16
17
 
@@ -23,7 +24,7 @@ export function mountGestures(el, { hit, pressable, activate, select, direct = (
23
24
  cancelHold();
24
25
  swallow = false;
25
26
  const item = hit(event);
26
- if (event.isPrimary === false || !item || !pressable(item)) return;
27
+ if (event.isPrimary === false || !item || !pressable(item) || consumed(event)) return;
27
28
  const { clientX: x, clientY: y, pointerId: id } = event;
28
29
  hold = { id, x, y, timer: setTimeout(() => {
29
30
  hold = null;
@@ -38,13 +39,18 @@ export function mountGestures(el, { hit, pressable, activate, select, direct = (
38
39
  on(scroller, 'scroll', cancelHold, { passive: true });
39
40
  }
40
41
 
42
+ if (select) on(el, 'pointerdown', event => {
43
+ if (event.button > 0 || event.ctrlKey || event.isPrimary === false || consumed(event)) return;
44
+ // 按在滚动条上(目标是滚动容器自己,点的位置在内容区之外):不是点空白,不取消选中。
45
+ if (event.target === scroller && (event.offsetX >= scroller.clientWidth || event.offsetY >= scroller.clientHeight)) return;
46
+ const item = hit(event);
47
+ if (!item) select(null);
48
+ else if (pressable(item) && !direct(event, item)) select(item);
49
+ });
41
50
  on(el, 'click', event => {
42
51
  if (swallow) { swallow = false; return; }
43
52
  const item = hit(event);
44
- if (!select) { if (item) activate(item); return; }
45
- if (!item) select(null);
46
- else if (!pressable(item) || direct(event, item)) activate(item);
47
- else select(item);
53
+ if (item && (!select || !pressable(item) || direct(event, item))) activate(item); // 选中已在按下时做过
48
54
  });
49
55
  if (select) on(el, 'dblclick', event => {
50
56
  const item = hit(event);
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; // 上下多画几行
@@ -122,9 +122,9 @@ export function stepCells(cells, layout, selected, action) {
122
122
  // handlers: { open(path), enter(path), more(path), retry(path), menu(event, cell), back?, select?(path | null) }
123
123
  // select 是 Mac 单击选中,不给就是 iPhone 的轻点打开。
124
124
  // back 给了就在头部最左边放「返回」(Mac,和没有原生返回的环境);不给就没有头部,iPhone 用原生返回,标题在工具条上。
125
- // draggable、longPress 同 mountTree。
125
+ // draggable、longPress、press、consumed 同 mountTree。
126
126
  // keyboard:滚动容器(.gbody)可以获得焦点,键盘才接得上(Mac)。
127
- export function mountGrid(el, model, handlers, { draggable = true, longPress = false, keyboard = false } = {}) {
127
+ export function mountGrid(el, model, handlers, { draggable = true, longPress = false, keyboard = false, press = null, consumed = () => false } = {}) {
128
128
  const head = h('div', { class: 'ghead' }), body = h('div', { class: 'gbody' }), spacer = h('div', { class: 'gspacer' }), win = h('div', { class: 'gwin' });
129
129
  head.hidden = true;
130
130
  if (keyboard) body.tabIndex = 0;
@@ -172,14 +172,17 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
172
172
  function cellNode(cell, index) {
173
173
  const node = h('div', { class: 'gi' });
174
174
  node.dataset.i = index;
175
+ node.dataset.path = cell.path; // 按下反馈认的身份
175
176
  if (cell.type !== 'entry') {
176
177
  node.className = `gi gnote ${cell.type}`;
177
178
  node.textContent = cell.text;
178
179
  if (cell.retry) { node.classList.add('retry'); node.title = cell.text; } // 长原因在行里被截断,Mac 悬停看全
180
+ if (cell.retry || cell.type === 'more') press?.paint(node, 'grid', cell.retry ? 'retry' : 'more', cell.path);
179
181
  return node;
180
182
  }
181
183
  const dead = cell.kind === EntryKind.LINK || cell.kind === EntryKind.OTHER;
182
184
  node.className = `gi cell ${cell.kind}${dead ? ' dead' : ''}${cell.path === model.selected ? ' sel' : ''}`;
185
+ press?.paint(node, 'grid', 'entry', cell.path);
183
186
  if (!dead && draggable) node.draggable = true;
184
187
  // 扩展名前给一个优先断点:package.json 折成 package / .json,不在字母中间断;没有点(或点在最前面)、太长时 overflow-wrap 才在任意位置断。
185
188
  const dot = cell.name.lastIndexOf('.');
@@ -219,6 +222,7 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
219
222
  menu: (event, cell) => handlers.menu(event, cell),
220
223
  dragText: cell => cell.path,
221
224
  longPress,
225
+ consumed,
222
226
  scroller: body,
223
227
  });
224
228
  // 选中变了只在现有节点上切 .sel,不重建:双击的 dblclick 要落在还在容器里的节点上。
@@ -230,6 +234,15 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
230
234
  else if (top + cellH > body.scrollTop + body.clientHeight) body.scrollTop = top + cellH - body.clientHeight;
231
235
  paint();
232
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
+ };
233
246
  body.addEventListener('scroll', paint, { passive: true });
234
247
  new ResizeObserver(relayout).observe(body);
235
248
 
@@ -244,10 +257,13 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
244
257
  },
245
258
  remeasure() { measuredWidth = body.clientWidth; measure(); this.render(); },
246
259
  scroll: () => body.scrollTop,
260
+ // 进出目录的淡入:只给内容(win),头部和滚动条不动;返回动画,由页面记着并在需要时结束。
261
+ fadeIn(duration) { return typeof win.animate === 'function' ? win.animate([{ opacity: 0 }, { opacity: 1 }], { duration, easing: 'ease-out' }) : null; },
247
262
  scrollTo(top) { body.scrollTop = top; paint(); }, // 浏览器的滚动事件随后还会画一次;这里先画,位置才马上对
248
263
  onScroll(fn) { body.addEventListener('scroll', fn, { passive: true }); },
249
264
  get layout() { return layout; },
250
265
  select: mark,
266
+ center,
251
267
  activate,
252
268
  focus() { body.focus(); },
253
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>
package/view/info.mjs CHANGED
@@ -17,6 +17,7 @@ export function mountInfo(el, { stat, size, rootPath, round, back = null }) {
17
17
  let reply = null, failure = null; // 属性的回答;取属性失败的原因
18
18
  let sizing = null; // 文件夹大小这一次统计:{ abort, round, phase: 'running' | 'done' | 'failed', result, message }
19
19
  let token = 0; // 取属性的序号:新的取代旧的,旧的回答不再用
20
+ let opens = 0, stoppedAt = -1; // 同预览:释放只在停止之后没有再打开过时才做
20
21
 
21
22
  const entry = () => reply ?? seed;
22
23
  // 指向工作目录内的链接按目标显示:种类和图标看目标的名字(链接自己叫什么不管),没有目标的(外链接)看自己。
@@ -98,20 +99,27 @@ export function mountInfo(el, { stat, size, rootPath, round, back = null }) {
98
99
  // seed:目录树里这一行(名字、种类),属性回来之前先画头部。
99
100
  open(next, row) {
100
101
  this.close();
102
+ opens++;
101
103
  path = next;
102
104
  seed = { name: row.name, kind: row.kind };
103
105
  load();
104
106
  },
105
107
  // 一轮结束:重取属性,不自动重新统计;已有的统计结果马上标成上次统计(页面的数据轮次变了)。
106
108
  refresh() { if (path !== null) { if (reply !== null) paint(); load(); } },
107
- close() {
109
+ // 停止(逻辑关闭,立即):取消统计、作废在途的回答;画面留着,由 release 在退场结束时清掉。
110
+ stop() {
108
111
  sizing?.abort.abort();
109
112
  sizing = null;
110
113
  token++;
111
114
  path = seed = reply = failure = null;
115
+ stoppedAt = opens;
116
+ },
117
+ release() {
118
+ if (stoppedAt !== opens) return;
112
119
  head.replaceChildren();
113
120
  body.replaceChildren();
114
121
  },
122
+ close() { this.stop(); this.release(); },
115
123
  get path() { return path; },
116
124
  };
117
125
  }