@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.
@@ -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
@@ -3,15 +3,18 @@
3
3
  // 菜单可以有一层二级菜单(项里写 submenu)。「整次菜单」(current)和「当前层」(layer、fly)分开记:
4
4
  // 在面板里切到下一层、退回来,整次菜单还是同一次,但上一层的按钮不再响应。第二个面板(sub)也算菜单里面,点它不是点外面。
5
5
  import { icon } from './icons.mjs';
6
+ import { onMotionChange, reducedMotion } from './press.mjs';
6
7
 
7
8
  const CLOSE_MS = 150; // 鼠标移到别的项之后,侧面板收起前等多久:斜着移过去不会误关
8
9
  const GAP = 2; // 侧面板和根面板之间留的空隙
10
+ const APPEAR_MS = 150; // iPhone 菜单出现:透明度 0→1,根层同时缩放 0.96→1;换层只淡入
9
11
 
10
12
  // el:页面里的 #menu。sub:侧面板(#submenu),没有就不能弹出,二级菜单总是在 el 里切到下一层。
11
13
  // flyout:true 时(Mac)鼠标移上去或点击「显示」这类项,侧面板在根面板左边弹出;放不下就退成切到下一层(iPhone 总是这样)。
12
14
  // open 之后的位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
13
15
  // 高度有上限(style.css 的 .menu):内容多时在菜单里滚动,不超出安全区。
14
- export function mountMenu(el, sub = null, { flyout = false } = {}) {
16
+ // animate:iPhone 的出现动画(Mac 的原生菜单立刻出现,不做);关闭不做动画。减弱动态效果时也不做。
17
+ export function mountMenu(el, sub = null, { flyout = false, animate = false } = {}) {
15
18
  let opener = null; // 打开菜单的按钮;用点打开的没有
16
19
  let current = null; // 这一次打开的标记:关闭之后留在手里的按钮不再响应
17
20
  let layer = 0; // el 里现在是哪一层:每次换层(进下一层、退回、重新打开、关闭)加一,旧层的按钮据此作废
@@ -19,6 +22,25 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
19
22
  let spec = null, anchor = null; // 根层的内容和锚点:退回根层、换层后重新定位要用
20
23
  let flyButton = null; // 展开着侧面板的那个项
21
24
  let closeTimer = null;
25
+ let playing = null; // 正在播的出现动画
26
+
27
+ // 出现动画:scale 为真是根层(从锚点那一侧缩放),否则只淡入。开着的动画先停在终点,免得叠在一起。
28
+ function appear(scale) {
29
+ settle();
30
+ if (!animate || reducedMotion() || typeof el.animate !== 'function') return;
31
+ const frames = scale ? [{ opacity: 0, transform: 'scale(.96)' }, { opacity: 1, transform: 'scale(1)' }] : [{ opacity: 0 }, { opacity: 1 }];
32
+ if (scale) {
33
+ // 缩放原点按夹进安全区之后的最终位置定:菜单在锚点下方从上沿缩放,在上方从下沿;横向贴着锚点的右边或点的位置。
34
+ const box = el.getBoundingClientRect(), at = anchor.getBoundingClientRect?.();
35
+ const below = box.top >= (at ? at.bottom : anchor.clientY) - 1;
36
+ el.style.transformOrigin = `${at ? 'right' : `${Math.max(0, Math.min(box.width, anchor.clientX - box.left))}px`} ${below ? 'top' : 'bottom'}`;
37
+ }
38
+ const mine = playing = el.animate(frames, { duration: APPEAR_MS, easing: 'ease-out' });
39
+ mine.onfinish = mine.oncancel = () => { if (playing === mine) playing = null; };
40
+ }
41
+ // 停止开着的动画:没有 fill,取消就是停在终点;根层的出现动画还没播完就换层、或关闭时调用。
42
+ function settle() { const mine = playing; playing = null; mine?.cancel(); }
43
+ onMotionChange(settle); // 设置在动画进行中变成减弱:结束到终点
22
44
 
23
45
  // items:[{ label, run, checked?, radio? } | { label, submenu: { items } } | { separator: true } | { heading }],checked 不是 undefined 的带对勾(radio 的是单选,其余是开关);
24
46
  // 分隔线和小标题不是菜单项,不可点。hover:这一层的项在鼠标移上去时管侧面板(只有根层,且 flyout)。
@@ -59,7 +81,7 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
59
81
  if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
60
82
  button.addEventListener('click', () => {
61
83
  if (!alive()) return; // 菜单已经关了(换成了别的、退回了上一层):留在手里的按钮不再响应
62
- hide();
84
+ hide(true);
63
85
  run();
64
86
  });
65
87
  }
@@ -99,6 +121,7 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
99
121
  paintRoot();
100
122
  el.hidden = false;
101
123
  place();
124
+ appear(true);
102
125
  if (at.getBoundingClientRect) { opener = at; opener.setAttribute?.('aria-expanded', 'true'); }
103
126
  }
104
127
 
@@ -144,10 +167,12 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
144
167
  if (!alive()) return;
145
168
  paintRoot();
146
169
  place();
170
+ appear(false);
147
171
  });
148
172
  el.replaceChildren(back, Object.assign(document.createElement('hr'), { className: 'menu-sep' }), ...build(item.submenu.items, alive, false));
149
173
  el.scrollTop = 0;
150
174
  place();
175
+ appear(false);
151
176
  }
152
177
 
153
178
  // 鼠标回到「显示」或侧面板:取消正在等的收起。
@@ -168,33 +193,49 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
168
193
  // 安全区的左边:body 的左内边距就是它(style.css),算出来的是像素。读不到按 0。
169
194
  const safeLeft = () => { const px = parseFloat(globalThis.getComputedStyle?.(document.body)?.paddingLeft); return Number.isFinite(px) ? px : 0; };
170
195
 
171
- function hide() {
196
+ // restore:关菜单后把焦点交回打开它的按钮(Esc 关、选了一项之后)。点菜单外、滚动、旋转关的不交:点到哪里焦点就在哪里。
197
+ // 选项的操作在交回焦点之后才执行,操作自己要移焦点(如「查找」聚焦查找条)时以操作为准。没有按钮的菜单(右键、原生按钮的假锚点)焦点不动。
198
+ function hide(restore = false) {
199
+ settle();
172
200
  current = null;
173
201
  layer++;
174
202
  collapse();
175
203
  el.hidden = true;
204
+ const back = opener;
176
205
  opener?.setAttribute?.('aria-expanded', 'false');
177
206
  opener = null;
207
+ if (restore === true) back?.focus?.(); // 严格比较:hide 也被直接当事件回调用(滚动、resize、blur),Event 对象是真值
178
208
  }
179
209
 
180
210
  // 两个面板都算菜单里面。菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
181
211
  const inside = target => el.contains(target) || (sub !== null && sub.contains(target));
212
+ // 关菜单的那一下按下标成「已消费」:按下反馈和 Mac 的按下即选中都先看它(consumed),消费过的不加反馈、不选中。
182
213
  let dismissed = false;
214
+ const eaten = new WeakSet();
183
215
  document.addEventListener('pointerdown', event => {
184
216
  dismissed = !el.hidden && !inside(event.target);
217
+ if (dismissed) eaten.add(event);
185
218
  if (!inside(event.target)) hide();
186
219
  }, true);
187
220
  document.addEventListener('click', event => {
188
221
  if (dismissed) { dismissed = false; event.stopPropagation(); }
189
222
  }, true);
190
- document.addEventListener('keydown', event => { if (event.key === 'Escape') hide(); });
191
- window.addEventListener('blur', hide);
192
- 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()); // 旋转、拖窄侧栏:位置对不上了
193
233
  sub?.addEventListener('pointerenter', keep);
194
234
 
195
235
  return {
196
236
  open, hide,
197
237
  get hidden() { return el.hidden; },
238
+ consumed: event => eaten.has(event),
198
239
  // 谁打开的菜单:同一个按钮再次激活就关闭(键盘激活没有 pointerdown,上面那条规则管不到)。
199
240
  get opener() { return opener; },
200
241
  };
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 ADDED
@@ -0,0 +1,110 @@
1
+ // 按下反馈:页面里只有一份按下状态,两端共用(设计见 docs/design/phase-3.md 第 17.3 节)。
2
+ // 不靠 :active(WebKit 对滚动区域里的触摸会延迟它):文档上监听 pointerdown,给最近的可按元素加 .pressed,样子在 style.css。
3
+ // 虚拟列表重画会换掉节点,所以列表的行由 tree.mjs、grid.mjs 画行时问 paint() 是不是正在按下的那一行。
4
+ import { HOLD_SLOP } from './gestures.mjs';
5
+
6
+ export const SHOW_MS = 80; // 触摸按下后这么久没移动、没取消才亮:一滑动就闪不好看
7
+ export const MIN_MS = 100; // 正常抬起:从亮起算至少显示这么久
8
+ export const FADE_MS = 200; // iPhone 正常抬起后的淡出(样式在 style.css 的 .fade)
9
+
10
+ const QUERY = '(prefers-reduced-motion: reduce)';
11
+ // 系统「减弱动态效果」:按下的淡出、菜单、层级过渡、目录淡入都按它统一判断。读不到按「减弱」算,宁可不动。
12
+ export const reducedMotion = () => { const query = globalThis.matchMedia?.(QUERY); return !query || query.matches; };
13
+ // 设置在动画进行中变了:调用 fn,让正在播的动画结束到终点。
14
+ export const onMotionChange = fn => globalThis.matchMedia?.(QUERY)?.addEventListener?.('change', fn);
15
+
16
+ // 点到的可按元素:{ node, key }。key 是列表里一行的身份(视图、种类、路径),按钮没有(按节点记)。
17
+ // 可按:没有 disabled 的 button、.row.entry、.row.more、.row.retry、.cell、.gnote.more、.gnote.retry;.dead 的条目也算(它们能选中、能右键)。
18
+ // 列表的行有三种画面:目录树(tree)、搜索结果(search,行上带 .hit)、图标视图(grid),身份里记哪一种,同一路径在不同画面里不是同一个按下。
19
+ function targetOf(event) {
20
+ const node = event.target?.closest?.('.row, .cell, .gnote, button');
21
+ if (!node) return null;
22
+ if (node.tagName === 'BUTTON') return node.disabled || node.getAttribute('disabled') !== null ? null : { node, key: null };
23
+ const has = name => node.classList.contains(name), path = node.dataset.path;
24
+ const kind = has('cell') || has('entry') ? 'entry' : has('retry') ? 'retry' : has('more') ? 'more' : null;
25
+ return kind === null || path === undefined ? null : { node, key: `${has('hit') ? 'search' : has('row') ? 'tree' : 'grid'}\n${kind}\n${path}` };
26
+ }
27
+
28
+ // identity():会话和根目录的身份(model.session、model.scope 拼成的字符串);换了就不是同一个按下。
29
+ // consumed(event):这次 pointerdown 已经被别人用掉了(菜单开着时点外面只关菜单):不加反馈。
30
+ export function mountPress({ identity = () => '', consumed = () => false, doc = document } = {}) {
31
+ let state = null; // { id, x, y, key, base, node, shown, released, minDone, timers }
32
+ const tagged = new Set(); // 加过 .pressed 的节点:去掉时一并清掉,不靠记住的旧节点
33
+ const fading = new Map(); // 正在淡出的节点 → 它的定时器
34
+
35
+ const unfade = () => { for (const [node, timer] of fading) { clearTimeout(timer); node.classList.remove('fade'); } fading.clear(); };
36
+ const strip = () => { for (const node of tagged) node.classList.remove('pressed'); tagged.clear(); };
37
+ const tag = node => { node.classList.add('pressed'); tagged.add(node); };
38
+ const stop = () => { if (state) { clearTimeout(state.showTimer); clearTimeout(state.minTimer); } };
39
+
40
+ // 作废:立即去掉,不淡出,不受最短时间限制;还没亮的之后也不会补亮。
41
+ function clear() {
42
+ stop();
43
+ state = null;
44
+ strip();
45
+ unfade();
46
+ }
47
+ // 正常结束:iPhone 淡出(减弱动态效果时不淡)。
48
+ function finish() {
49
+ stop();
50
+ state = null;
51
+ const nodes = [...tagged];
52
+ strip();
53
+ if (reducedMotion()) return;
54
+ for (const node of nodes) {
55
+ node.classList.add('fade');
56
+ fading.set(node, setTimeout(() => { node.classList.remove('fade'); fading.delete(node); }, FADE_MS));
57
+ }
58
+ }
59
+ function show() {
60
+ const mine = state;
61
+ mine.shown = true;
62
+ tag(mine.node);
63
+ mine.minTimer = setTimeout(() => { mine.minDone = true; if (mine.released && state === mine) finish(); }, MIN_MS);
64
+ }
65
+
66
+ const on = (type, fn, target = doc, capture = true) => { target.addEventListener(type, fn, capture); return () => target.removeEventListener(type, fn, capture); };
67
+ onMotionChange(unfade); // 设置在淡出进行中变成减弱:淡出结束到终点;仍按着的反馈保留
68
+ const offs = [
69
+ on('pointerdown', event => {
70
+ if (event.isPrimary === false) return clear(); // 第二根手指
71
+ clear();
72
+ if (consumed(event) || (event.pointerType === 'mouse' || event.pointerType === undefined) && (event.button > 0 || event.ctrlKey)) return; // 右键、Control 左键是菜单
73
+ const target = targetOf(event);
74
+ if (!target) return;
75
+ state = { id: event.pointerId, x: event.clientX, y: event.clientY, key: target.key, base: identity(), node: target.node, shown: false, released: false, minDone: false };
76
+ if (event.pointerType === 'touch') {
77
+ const mine = state;
78
+ state.showTimer = setTimeout(() => { if (state === mine) show(); }, SHOW_MS);
79
+ } else show();
80
+ }),
81
+ on('pointermove', event => {
82
+ if (state && event.pointerId === state.id && Math.hypot(event.clientX - state.x, event.clientY - state.y) > HOLD_SLOP) clear();
83
+ }),
84
+ on('pointerup', event => {
85
+ if (!state || event.pointerId !== state.id) return;
86
+ if (!state.shown) { clearTimeout(state.showTimer); show(); } // 快点一下:在抬起时补上
87
+ state.released = true;
88
+ if (state.minDone) finish();
89
+ }),
90
+ on('pointercancel', clear),
91
+ on('scroll', clear), // 滚动事件不冒泡,捕获才收得到
92
+ on('dragstart', clear),
93
+ on('contextmenu', clear),
94
+ on('blur', clear, globalThis.window ?? doc, false), // 窗口失焦。不能用捕获:元素失焦(点按钮时焦点从目录树移走)的 blur 也会经过 window 的捕获阶段
95
+ on('visibilitychange', () => { if (doc.hidden) clear(); }),
96
+ ];
97
+
98
+ return {
99
+ // 画行时问:这一行是不是正在按下的(会话和根目录、视图、种类、路径都对得上),是就带上 .pressed。
100
+ paint(node, view, kind, path) {
101
+ if (!state || state.key !== `${view}\n${kind}\n${path}` || state.base !== identity()) return;
102
+ state.node = node; // 还没亮(触摸等待期间)重画了:show() 要给新节点加,旧节点已经脱离
103
+ if (state.shown) tag(node);
104
+ },
105
+ // 正在亮着的:{ key },没有就是 null。测试用。
106
+ current: () => (state?.shown ? { key: state.key } : null),
107
+ reset: clear,
108
+ dispose() { clear(); for (const off of offs.splice(0)) off(); },
109
+ };
110
+ }
package/view/preview.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
2
2
  import { h } from './dom.mjs';
3
+ import { createFind } from './find.mjs';
3
4
  import { formatSize } from './format.mjs';
4
5
  import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
5
6
  import { icon, iconFor } from './icons.mjs';
@@ -58,21 +59,42 @@ export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (t
58
59
  // back:给了就在头部最左边放「返回」(Mac 侧栏预览:原生工具栏项目只能在右侧);文件页和 iPhone 不传。
59
60
  // open(path, scroll) 带了要恢复的位置时,返回的 Promise 在「位置用上了」时变 true(正文到了、已设好位置;读取失败不算,位置留着等重试),
60
61
  // 在「位置作废」时变 false(预览关了、改看别的文件)。读取被刷新、重载或 changed 作废时位置不丢:接替它的那次读取接着带上,用上才算完。
62
+ // 文件内查找(第 18.6 节)是预览自己的一部分,接在预览已有的生命周期上:open 换了文件、reload、stop、close 关查找;refresh 保留;release 不碰。
63
+ // 页面只负责入口:canFind(有显示着的文本才有)、openFind()(⌘F、iPhone 的「查找」菜单项)。consumed(event):这个按键已经被菜单消费了(菜单开着时的 Esc)。
61
64
  // selectionMenu(event, { path, text, startLine, endLine }):给了就接管正文里选中文字的右键(只有 Mac 传);预览不知道菜单里是什么。
62
65
  // 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
63
- export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null }) {
66
+ export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false }) {
64
67
  const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
65
68
  const fileIcon = h('span', { class: 'pico', 'aria-hidden': 'true' });
66
69
  // 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
67
70
  const action = (label, glyph, run) => h('button', { class: glyph ? 'icon' : 'link', 'aria-label': label, title: label, onclick: run }, glyph ? icon(glyph, 18) : label);
68
71
  const copyPath = () => path !== null && copy(path);
69
72
  const retryButton = h('button', { class: 'link', onclick: () => load(true), hidden: true }, '重试');
70
- const body = h('div', { class: 'pbody' });
73
+ const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
74
+ let gutterEl = null;
75
+ const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
71
76
  const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
72
77
  el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), retryButton,
73
- ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), body);
78
+ ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), find.el, body);
79
+ find.done.addEventListener('click', () => { find.close(); body.focus(); });
80
+ // 查找条的键盘:Esc 关(从查找条里关,焦点回正文;焦点在正文里,焦点留在正文);⌘G、⇧⌘G 下一个、上一个。输入法组字中的按键不管,菜单消费掉的 Esc 不再处理。
81
+ el.addEventListener('keydown', event => {
82
+ if (!find.isOpen || event.isComposing) return;
83
+ if (event.key === 'Escape' && consumed(event)) { event.preventDefault(); return; } // 菜单关掉的 Esc:查找输入框是 type=search,默认动作会清空它,要拦下
84
+ if (event.key === 'Escape') {
85
+ event.preventDefault();
86
+ const fromBar = find.el.contains(document.activeElement);
87
+ find.close();
88
+ if (fromBar) body.focus();
89
+ } else if (event.key?.toLowerCase() === 'g' && event.metaKey && !event.ctrlKey && !event.altKey) {
90
+ event.preventDefault();
91
+ if (event.shiftKey) find.prev(); else find.next();
92
+ }
93
+ });
94
+ let textShown = false, pendingFind = null, longLine = false; // 现在显示的是不是文本;show() 换好的正文,等滚动位置设好再交给查找
74
95
 
75
96
  let path = null, token = 0, shown = null, objectUrl = null; // shown:当前显示的 { size, mtimeMs }
97
+ let opens = 0, stoppedAt = -1; // 打开次数和上一次停止时的次数:释放只在停止之后没有再打开过时才做(返回的退场还没结束又打开了)
76
98
  let carry = null; // 待恢复的位置 { scroll, settle }:open 带进来,读取真正用上或作废后才清
77
99
  const settle = used => { const c = carry; carry = null; c?.settle(used); };
78
100
  let metaText = ' ', metaTitle = '', stale = null; // stale:后台刷新失败的原因,此时正文还是上次的
@@ -92,6 +114,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
92
114
 
93
115
  function show(result) {
94
116
  revoke();
117
+ textShown = result.kind === ContentKind.TEXT;
118
+ pendingFind = null;
119
+ if (!textShown) find.close(); // 图片、二进制没有查找
95
120
  shown = { size: result.size, mtimeMs: result.mtimeMs };
96
121
  // 元信息:目录 · 行数 · 大小;根目录下的文件没有目录,非文本没有行数。修改时间放进 title。
97
122
  // 高亮:认得出语言才试;超过上限不试,库或解析出错就退回纯文本,都在元信息里注明。认不出语言的不加说明。
@@ -99,7 +124,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
99
124
  const lines = result.kind === ContentKind.TEXT ? `${lineCount(result.text)} 行` : '';
100
125
  const language = result.kind === ContentKind.TEXT ? languageOf(path.split('/').pop()) : null;
101
126
  // 先判大小,超过只写「不高亮」;没超再判行长。
102
- const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : hasLongLine(result.text) ? '行太长,不高亮' : '';
127
+ // 有长行:上色已经按它判断,查找也用同一个结果(不再扫一遍正文):长行里注册高亮会让浏览器同步重画整行,所以只计数、导航、滚动。
128
+ longLine = result.kind === ContentKind.TEXT && hasLongLine(result.text);
129
+ const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : longLine ? '行太长,不高亮' : '';
103
130
  const colored = language && !skip ? highlight(result.text, language) : null;
104
131
  const plain = !language ? '' : skip || (colored ? '' : '没能高亮');
105
132
  const note = [result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '', plain].filter(Boolean).join(',');
@@ -108,6 +135,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
108
135
  const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
109
136
  const text = h('pre', { class: 'text selectable' }, ...(colored ? [] : [result.text]));
110
137
  if (colored) appendAll(text, colored);
138
+ gutterEl = gutter;
139
+ pendingFind = { el: text, text: result.text, highlight: !longLine };
111
140
  if (selectionMenu) text.addEventListener('contextmenu', event => onSelect(event, text));
112
141
  body.replaceChildren(h('div', { class: 'code' }, gutter, text));
113
142
  } else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
@@ -128,15 +157,17 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
128
157
 
129
158
  function failure(error, silent, retry) {
130
159
  if (error.stale) return;
131
- if (error.code === ErrorCode.NOT_FOUND) { shown = null; setMeta(' '); return notice('文件已不存在', path); }
160
+ if (error.code === ErrorCode.NOT_FOUND) { shown = null; textShown = false; find.clearContent(); setMeta(' '); return notice('文件已不存在', path); }
132
161
  if (silent && shown) return setStale(error.message); // 后台刷新失败:保留正文,提示原因
162
+ textShown = false;
163
+ find.clearContent(); // 整页重读失败:标记清掉,计数写「—」,之后再读成功就重新找
133
164
  notice('读不到这个文件', error.message, { label: '重试', run: retry });
134
165
  }
135
166
 
136
167
  // silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置;有待恢复的位置时用它。
137
168
  async function load(silent) {
138
169
  const mine = ++token, mark = () => mine === token;
139
- if (!silent) { shown = null; setMeta('读取中…'); revoke(); body.replaceChildren(); }
170
+ if (!silent) { shown = null; textShown = false; find.clearContent(); setMeta('读取中…'); revoke(); body.replaceChildren(); }
140
171
  try {
141
172
  const result = await readFile(offset => read(path, offset), {
142
173
  prev: silent ? shown : null, cancelled: () => !mark(),
@@ -148,6 +179,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
148
179
  const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
149
180
  show(result);
150
181
  body.scrollTop = keep.top; body.scrollLeft = keep.left;
182
+ // 顺序:换正文 → 设好滚动位置 → 重建查找(刷新和换正文时查找不滚动,不盖掉恢复)
183
+ if (pendingFind) find.setContent(pendingFind.el, pendingFind.text, { highlight: pendingFind.highlight });
151
184
  settle(true);
152
185
  } catch (error) {
153
186
  if (mark()) failure(error, silent, () => load(false)); // 失败不算用上:待恢复的位置留着,重试或之后的刷新成功才用、才清
@@ -157,6 +190,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
157
190
  return {
158
191
  open(next, scroll = null) {
159
192
  settle(false);
193
+ if (next !== path) find.close(); // 换了文件就关查找,不靠调用方先 stop()
194
+ opens++;
160
195
  path = next;
161
196
  const base = next.split('/').pop();
162
197
  name.textContent = base;
@@ -169,10 +204,27 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
169
204
  copyPath,
170
205
  refresh() { return path === null ? undefined : load(true); },
171
206
  // 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
172
- reload() { return path === null ? undefined : load(false); },
173
- close() { settle(false); token++; path = null; shown = null; setMeta(' '); revoke(); body.replaceChildren(); },
174
- scroll: () => ({ top: body.scrollTop, left: body.scrollLeft }),
207
+ reload() { find.close(); return path === null ? undefined : load(false); }, // 来源变了:查找也关
208
+ // 停止(逻辑关闭,立即):不再读、不再刷新,待恢复的位置结算;画面(正文、图片的 URL)留着,由 release 在退场结束时清掉。
209
+ stop() { settle(false); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
210
+ // 释放(画面):停止之后又打开过就什么都不做。
211
+ release() {
212
+ if (stoppedAt !== opens) return; // 停止之后又打开过(打开次数变了):这一屏是新的,不是退场的旧页
213
+ setMeta(' ');
214
+ revoke();
215
+ body.replaceChildren();
216
+ },
217
+ // 停止并立即释放:换会话、换根目录、Mac,以及没有过渡的所有关闭。
218
+ close() { this.stop(); this.release(); },
219
+ // 已停止的预览没有位置:保存状态时按 0 算,同关闭后清空正文的结果。
220
+ scroll: () => (path === null ? { top: 0, left: 0 } : { top: body.scrollTop, left: body.scrollLeft }),
175
221
  onScroll: fn => body.addEventListener('scroll', fn, { passive: true }),
176
222
  get path() { return path; },
223
+ // 文件内查找的入口:有显示着的文本(或查找条已经开着)才有。
224
+ get canFind() { return path !== null && (textShown || find.isOpen); },
225
+ get findOpen() { return find.isOpen; },
226
+ openFind() { if (this.canFind) find.open(); return this.canFind; },
227
+ closeFind() { find.close(); },
228
+ find,
177
229
  };
178
230
  }