@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/app.mjs CHANGED
@@ -1,11 +1,14 @@
1
- // 资源管理器的页面入口:消息收发、状态保留、工具栏和「更多」菜单、图标视图的进入和返回。状态在 model.mjs,渲染在 tree.mjs、grid.mjs、preview.mjs 和 info.mjs,菜单和提示在 menu.mjs 和 hint.mjs,滚动位置的恢复在 restore.mjs。
1
+ // 资源管理器的页面入口:消息收发、状态保留、工具栏和「更多」菜单、图标视图的进入和返回、搜索。状态在 model.mjs,渲染在 tree.mjs、grid.mjs、preview.mjs 和 info.mjs,菜单和提示在 menu.mjs 和 hint.mjs,滚动位置的恢复在 restore.mjs,
2
+ // 文件名搜索的状态在 search.mjs、搜索框在 searchbar.mjs、「在目录中显示」在 locate.mjs。
2
3
  import { EXIT, paintBar } from './bar.mjs';
3
4
  import { createChat } from './chat.mjs';
4
5
  import { connect } from './connection.mjs';
5
6
  import { infoText, sortName } from './format.mjs';
7
+ import { h } from './dom.mjs';
6
8
  import { mountGrid } from './grid.mjs';
7
9
  import { mountHint } from './hint.mjs';
8
10
  import { mountInfo } from './info.mjs';
11
+ import { createLocator } from './locate.mjs';
9
12
  import { mountMenu } from './menu.mjs';
10
13
  import { Model, STATE_LIMIT, View, noticeText, parseState, putSession, trimState } from './model.mjs';
11
14
  import { showNotice } from './notice.mjs';
@@ -13,6 +16,8 @@ import { mountPreview } from './preview.mjs';
13
16
  import { mountPress, onMotionChange, reducedMotion } from './press.mjs';
14
17
  import { EntryKind, RootState, SortKey, Type } from './protocol.mjs';
15
18
  import { createRestore, createTrail } from './restore.mjs';
19
+ import { createSearch } from './search.mjs';
20
+ import { mountSearchbar } from './searchbar.mjs';
16
21
  import { browseAction, previewAction } from './keys.mjs';
17
22
  import { mountTree, rootName } from './tree.mjs';
18
23
 
@@ -35,6 +40,7 @@ model.view = persisted.view;
35
40
  const hint = mountHint($('hint'));
36
41
  const menu = mountMenu($('menu'), $('submenu'), { flyout: !isIOS, animate: isIOS }); // Mac 的二级菜单在左边弹出,iPhone 在菜单里切到下一层,菜单出现时有动画
37
42
  // 按下反馈:页面里只有一份(press.mjs);菜单开着时点外面的那一下已被菜单消费,不加反馈、不选中。
43
+ let menuFrom = null; // 现在开着的菜单从哪里打开的:'browse'(目录树、图标视图的行)、'result'(搜索结果的行)、null(别的);changed 时按它决定关不关
38
44
  const press = mountPress({ identity: () => `${model.session}\n${model.scope}`, consumed: menu.consumed });
39
45
  const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint });
40
46
  // 属性页和图标视图的上一层:iPhone 用原生返回(coda.back);Mac 的客户端会替声明了返回的页面画一个带小箭头的导航,
@@ -59,13 +65,83 @@ const grid = mountGrid($('grid'), model, {
59
65
  }, { draggable: !isIOS, longPress: isIOS, keyboard: !isIOS, press, consumed: menu.consumed });
60
66
  const restore = createRestore(model, { tree, grid });
61
67
  const trail = createTrail();
68
+
69
+ // ---- 文件名搜索(第 18 节):搜索框常驻在 #browse 顶上,有字时结果换掉目录树和图标视图 ----
70
+ // 搜索的身份是会话和根目录(model.scope):回答回来时对不上就作废。
71
+ const search = createSearch({
72
+ call: (fields, signal) => conn.link.call(Type.SEARCH, fields, { signal, cancel: Type.SEARCH_CANCEL }),
73
+ hidden: () => model.showHidden,
74
+ identity: () => `${model.session}\n${model.scope}`,
75
+ // 结果整体没了(搜索词清空、reset、根目录不可用 suspend 都走这里):结果行的菜单一并作废——它的操作指着旧结果。
76
+ // 非空重搜时旧结果留着(shown 不为空或在搜索中),菜单照旧留着,操作按打开菜单时的路径做。
77
+ onChange: () => {
78
+ if (menuFrom === 'result' && (!search.active || (search.shown === null && search.status === 'idle'))) { menu.hide(); menuFrom = null; }
79
+ schedule();
80
+ },
81
+ });
82
+ const searchbar = mountSearchbar($('searchbar'), { onInput: searchInput, onClear: () => { clearSearch(); searchbar.focus(); }, onKey: searchBoxKey, onEnter: () => { if (isIOS) searchbar.blur(); } });
83
+ const hitStatus = h('span', { class: 'sstatus-text' }), hitRetry = h('button', { class: 'link', onclick: () => search.research() }, '重试'), hitsEl = h('div', { class: 'shits', role: 'listbox' });
84
+ hitRetry.hidden = true;
85
+ $('search').replaceChildren(h('div', { class: 'sstatus secondary', role: 'status' }, hitStatus, hitRetry), hitsEl);
86
+ // 结果自己的选中(不改 model.selected)和键盘焦点;单击只切 .sel,不重画行(双击要落在还在容器里的节点上)。
87
+ const hits = mountTree(hitsEl, model, {
88
+ open: path => openResult(path),
89
+ toggle: path => revealResult(path, true), // 结果里的文件夹:同「在目录中显示」,然后展开它或进入它
90
+ more() {}, retry() {},
91
+ menu: (event, row) => resultMenu(event, row),
92
+ select: isIOS ? null : path => { if (search.select(path)) hits.select(); },
93
+ }, { draggable: !isIOS, longPress: isIOS, keyboard: !isIOS, press, consumed: menu.consumed, rows: () => search.rows(), selected: () => search.selected, view: 'search', title: false });
94
+
95
+ // 用户接管计数:浏览区上的 pointerdown、wheel、touchstart、keydown 各加一(点已选中的条目、点空白、右键和长按的起手都算,不管选中变没变);
96
+ // 经菜单、按钮执行的打开预览、属性页等在入口处另计一次。程序自己的展开、进入目录、滚动、选中都不经过这里。「在目录中显示」靠它判断用户有没有动过。
97
+ let takeover = 0;
98
+ for (const type of ['pointerdown', 'wheel', 'touchstart', 'keydown']) $('browse').addEventListener(type, () => { takeover++; }, true);
99
+ const taken = fn => (...args) => { takeover++; return fn(...args); };
100
+ const locator = createLocator({
101
+ model,
102
+ // 会话、根目录、排序、视图、隐藏开关和模型的刷新轮次:任何一个变了,定位就作废。
103
+ identity: () => [model.session, model.scope, model.sort, model.view, model.showHidden, model.round].join('\n'),
104
+ takeover: () => takeover,
105
+ ops: {
106
+ // 开始:清空搜索(搜索轮次加一);丢掉目标视图还在等的滚动恢复;图标视图进入目标所在的目录(和 enterDir 一样记 trail、滚到顶部,但不触发 landed 的补滚动)。
107
+ begin(parent) {
108
+ clearSearch();
109
+ restore.drop('tree');
110
+ restore.drop('grid');
111
+ if (parent === null || parent === model.cwd) return;
112
+ trail.remember(model.cwd, grid.scroll());
113
+ selectEntry(null);
114
+ model.enter(parent);
115
+ shownCwd = model.cwd;
116
+ grid.scrollTo(0);
117
+ declareBack();
118
+ },
119
+ render: () => browser().render(),
120
+ select: path => selectEntry(path),
121
+ center: path => browser().center(path),
122
+ // 文件夹结果:定位到它之后,列表视图展开它,图标视图进入它(程序自己的,不算接管)。
123
+ openFolder(path) { if (model.view === View.ICONS) enterInto(path); else if (!model.expanded.has(path)) model.toggle(path); },
124
+ notify: text => hint.show(text, { warn: false }),
125
+ },
126
+ });
127
+ function searchInput(value) {
128
+ locator.cancel(); // 重新输入搜索词:定位作废
129
+ search.input(value);
130
+ searchbar.set(value);
131
+ }
132
+ // 清空搜索:搜索词、结果、结果的选中都清掉(定位自己开始时、Esc、清除按钮)。
133
+ function clearSearch() {
134
+ search.reset();
135
+ searchbar.set('');
136
+ }
62
137
  const preview = mountPreview($('preview'), {
63
138
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
64
139
  // iPhone 预览头部右边的 ⋯(刷新、复制路径):顶部工具条在预览时只有「返回」,只留头部一行标题
65
140
  actions: isIOS ? [{ label: '更多', icon: 'ellipsis', run: (_, button) => toggleMore(button) }] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
66
141
  back: isIOS ? null : closePreview,
67
142
  // 选中文字的右键菜单只有 Mac:iPhone 用系统的选区菜单。
68
- selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
143
+ selectionMenu: isIOS ? null : (event, selection) => { menu.open(event, { items: chat.selectionItems(selection) }); menuFrom = null; },
144
+ consumed: menu.consumed, // 菜单开着时的 Esc 归菜单:查找条不处理
69
145
  });
70
146
  // 属性页:页内一层。
71
147
  let infoOpen = false;
@@ -91,10 +167,11 @@ function openInView(path) {
91
167
  }
92
168
  // 两端都在页内打开:model.openFile 设 selected 和 opened,经 onChange 切到预览。iPhone 触屏没有键盘焦点,不交焦点;
93
169
  // 快速两次轻点:第一次已切到预览,目录树 .off 不接指针事件,第二次落不到条目上。
94
- function openFile(path) {
170
+ // 打开文件的统一入口(目录树、图标视图和搜索结果):焦点交接和过渡意图在这里记,不随调用方复制。select 为假(搜索结果)时只设预览,不改 model.selected。
171
+ function openFile(path, { select = true } = {}) {
95
172
  openPressed = !isIOS; // 用户在 Mac 上打开的:render 把焦点交给预览面板
96
173
  note({ kind: 'push', from: mode(), to: 'preview' });
97
- model.openFile(path);
174
+ model.openFile(path, { select });
98
175
  }
99
176
 
100
177
  // ---- 渲染:同一批变化合并成一次 ----
@@ -113,6 +190,16 @@ function selectEntry(path) {
113
190
  queueSave();
114
191
  }
115
192
  const browser = () => (model.view === View.ICONS ? grid : tree);
193
+ // 浏览区里键盘该落在哪:搜索时是结果,否则是目录树或图标视图。
194
+ const focusBrowse = () => (searching() ? hits : browser()).focus();
195
+
196
+ // 结果上面的状态行。
197
+ function paintSearch() {
198
+ const { text, retry } = search.statusLine();
199
+ if (hitStatus.textContent !== text) hitStatus.textContent = text;
200
+ hitRetry.hidden = !retry;
201
+ hits.render();
202
+ }
116
203
  // Mac 在按下时选中(选中条目或在空白处取消):和键盘一样算用户接管,这个视图还在等的滚动恢复作废,免得恢复到达时把刚选中的条目滚走。
117
204
  function mouseSelect(path) {
118
205
  restore.drop(model.view === View.ICONS ? 'grid' : 'tree');
@@ -126,8 +213,14 @@ function closePreview() {
126
213
  }
127
214
  // 用户点了预览头部的返回:render 据此决定焦点要不要交给浏览区,别的模式变化不动焦点。
128
215
  let backPressed = false;
216
+ let wantFocus = false; // 清空搜索后,等重画把目录树或图标视图放出来再把焦点交给它
129
217
  let openPressed = false; // 用户打开了文件:同返回对称,页面持有焦点时 render 把焦点交给预览面板
130
- const mode = () => (infoOpen ? 'info' : !model.ready ? 'notice' : model.opened !== null ? 'preview' : model.view === View.ICONS ? 'grid' : 'tree');
218
+ // 两级(第 18.3 节):外层是层(browse、preview、notice、info),管过渡、inert 和离开那层的释放;内层是 #browse 里当前的面板(search、grid、tree),只管三个面板的可见性。
219
+ // 预览或属性页盖在结果上面时,内层仍是结果:搜索不改外层。
220
+ const mode = () => (infoOpen ? 'info' : !model.ready ? 'notice' : model.opened !== null ? 'preview' : 'browse');
221
+ const searching = () => model.ready && search.active;
222
+ const pane = () => (searching() ? 'search' : model.view === View.ICONS ? 'grid' : 'tree');
223
+ const INNER = ['tree', 'grid', 'search'];
131
224
 
132
225
  // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
133
226
  let noticeKey = null;
@@ -143,7 +236,7 @@ function paintNotice() {
143
236
  // 只在用户操作引起时做:入口(openFile、openInfo、goBack、enterDir、leaveDir)在改模型之前记一个一次性的「过渡意图」,render 消费它:
144
237
  // 前后对得上就播,对不上就丢掉。换会话、换根目录、恢复、notice、changed 的刷新都没有意图,不播。意图由最外层的入口记,goBack 内部调用的 closeInfo、leaveDir 不记。
145
238
  // 层级的深浅:浏览区(tree、grid)浅,预览和属性页深。深的一层永远在上:打开时滑入盖住浅层,返回时滑出、露出浅层。
146
- const PANES = ['tree', 'grid', 'preview', 'notice', 'info'];
239
+ const PANES = ['browse', 'preview', 'notice', 'info'];
147
240
  const DEEP = new Set(['preview', 'info']);
148
241
  const SLIDE_MS = 280, FADE_IN_MS = 150;
149
242
  let intent = null; // { kind: 'push' | 'pop' | 'fade', from?, to }:from、to 是模式;fade 的 to 是目标 cwd
@@ -173,6 +266,7 @@ function begin(anims, { ids = [], leaving = null, after = [] } = {}) {
173
266
  }
174
267
 
175
268
  // 面板的可见和可操作:只有当前的一层能操作;离开的那一层在退场期间还看得见,但 inert 且不接指针。
269
+ // 内层(#browse 里的三个面板)按状态直接换,不做过渡,也不管外层在不在播过渡。
176
270
  function applyPanes(current) {
177
271
  const leaving = running?.leaving ?? null;
178
272
  for (const id of PANES) {
@@ -180,6 +274,11 @@ function applyPanes(current) {
180
274
  $(id).classList.toggle('leaving', leaving === id);
181
275
  $(id).inert = current !== id;
182
276
  }
277
+ const inner = pane();
278
+ for (const id of INNER) {
279
+ $(id).classList.toggle('off', inner !== id);
280
+ $(id).inert = current !== 'browse' || inner !== id; // 外层不是浏览区(被预览、属性页盖住)时里面的面板也不能操作
281
+ }
183
282
  }
184
283
 
185
284
  // 这次 render 要不要播层级切换:消费意图。fade 要等内容到了,不在这里。
@@ -210,7 +309,7 @@ function slide({ kind, from, to }, after) {
210
309
  // 图标视图进出目录:内容到了才播,只给内容播,不给「正在读取」播。
211
310
  function takeFade(current) {
212
311
  if (intent?.kind !== 'fade') return;
213
- if (current !== 'grid' || model.cwd !== intent.to) { intent = null; return; } // 中途换了目录、或打开了文件:作废
312
+ if (current !== 'browse' || pane() !== 'grid' || model.cwd !== intent.to) { intent = null; return; } // 中途换了目录、或打开了文件:作废
214
313
  const state = model.dirs.get(model.cwd);
215
314
  if (!state || !(state.loaded || state.error)) return; // 还在读取:意图留着,内容到了的那次 render 播
216
315
  intent = null;
@@ -224,12 +323,14 @@ let infoStopped = false;
224
323
 
225
324
  function render() {
226
325
  const current = mode();
227
- const refocus = backPressed && document.hasFocus(), handoff = openPressed && document.hasFocus();
228
- backPressed = openPressed = false;
326
+ const refocus = (backPressed || wantFocus) && document.hasFocus(), handoff = openPressed && document.hasFocus();
327
+ backPressed = openPressed = wantFocus = false;
229
328
  const slideIn = takeSlide(current);
230
329
  if (current === 'notice') paintNotice();
231
- const browsing = current === 'tree' || current === 'grid';
330
+ const browsing = current === 'browse';
232
331
  (model.view === View.ICONS ? grid : tree).render(); // 只画正在用的视图,另一个留着它的内容和滚动位置
332
+ searchbar.set(search.text);
333
+ if (searching()) paintSearch();
233
334
  landed();
234
335
  restore.settle();
235
336
  // 待恢复的位置只属于它那个文件:opened 清了或换成别的文件,位置作废。
@@ -250,7 +351,7 @@ function render() {
250
351
  lastMode = current;
251
352
  // 返回按钮随预览一起 inert,焦点会掉到页面外:用户刚点了返回、页面又持有焦点时交给目录树或网格。
252
353
  // 后台刷新、切会话、root 变化造成的切换不动焦点,免得抢走客户端输入框的焦点。
253
- if (refocus && browsing) browser().focus();
354
+ if (refocus && browsing) focusBrowse();
254
355
  // 打开时浏览区变 inert,焦点本来就会掉:交给预览面板,⌘↑ 才收得到。
255
356
  if (handoff && current === 'preview') $('preview').focus();
256
357
  syncToolbar();
@@ -292,6 +393,7 @@ const TOOLBAR = { getBoundingClientRect: () => ({ right: window.innerWidth, bott
292
393
  // 「更多」菜单的内容只写这一处,iPhone 的 ⋯ 和 Mac 的原生按钮共用:刷新、显示隐藏文件、「显示」›;「显示」里是视图和排序,当前项有对勾。
293
394
  const moreMenu = () => isIOS && mode() === 'preview' ? { items: [
294
395
  { label: '刷新', run: () => act('refresh') },
396
+ ...(preview.canFind ? [{ label: '查找', run: () => preview.openFind() }] : []), // 只有显示着的文本有查找
295
397
  { label: '复制路径', run: () => preview.copyPath() }, // 相对路径
296
398
  ] } : ({ items: [
297
399
  { label: '刷新', run: () => act('refresh') },
@@ -338,7 +440,7 @@ function changeView(view) {
338
440
  // 键盘激活没有 pointerdown,菜单外点击那条规则不管用:同一个按钮再次激活就关闭。
339
441
  function toggleMore(button) {
340
442
  if (!menu.hidden && menu.opener === button) menu.hide();
341
- else menu.open(button, moreMenu());
443
+ else { menu.open(button, moreMenu()); menuFrom = null; }
342
444
  }
343
445
 
344
446
  function act(id, button) {
@@ -351,11 +453,13 @@ function act(id, button) {
351
453
  model.setShowHidden(!model.showHidden);
352
454
  persisted.hidden = model.showHidden;
353
455
  invalidateScroll(); // 不管在哪种视图切换:显示的条目变了,两种视图的旧位置都对不上
456
+ search.research(); // 隐藏开关变了:有搜索词就按新的 hidden 重搜
354
457
  }
355
458
  else if (id === 'refresh') {
356
459
  conn.refresh();
357
460
  model.refresh();
358
461
  preview.refresh();
462
+ search.research();
359
463
  }
360
464
  }
361
465
  // 原生按钮的事件是 { id }:只认 more,别的什么都不做。
@@ -398,18 +502,47 @@ function pathMenu(event, row) {
398
502
  const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER;
399
503
  // Mac 的第一项和双击是同一个动作(右键不改选中);文件夹在列表里写展开或收起,别的写打开。iPhone 轻点就是打开,菜单不变。
400
504
  const folder = row.kind === EntryKind.DIR, listed = model.view !== View.ICONS;
401
- const open = isIOS || dead ? [] : [{ label: folder && listed ? (row.open ? '收起' : '展开') : '打开', run: () => browser().activate(row) }, { separator: true }];
505
+ const open = isIOS || dead ? [] : [{ label: folder && listed ? (row.open ? '收起' : '展开') : '打开', run: taken(() => browser().activate(row)) }, { separator: true }];
506
+ menuFrom = 'browse';
402
507
  menu.open(event, { title: row.path, detail: dead ? undefined : infoText(row) || undefined, items: [
403
508
  ...open,
404
- ...(dead ? [] : [{ label: '添加到聊天', run: () => chat.add(row.path) }]),
405
- { label: '复制相对路径', run: () => coda.copy(row.path) },
406
- { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${row.path}`) },
509
+ ...(dead ? [] : [{ label: '添加到聊天', run: taken(() => chat.add(row.path)) }]),
510
+ { label: '复制相对路径', run: taken(() => coda.copy(row.path)) },
511
+ { label: '复制绝对路径', run: taken(() => coda.copy(`${model.root.path}/${row.path}`)) },
407
512
  { separator: true },
408
- { label: '属性', run: () => openInfo(row) },
513
+ { label: '属性', run: taken(() => openInfo(row)) },
409
514
  ] });
410
515
  }
516
+
517
+ // 结果的行菜单:同目录树(打开、添加到聊天、复制路径、属性),另加「在目录中显示」。
518
+ // 菜单是按打开菜单时那一行的路径和来源(结果)做的:菜单开着时结果被换掉,执行的操作仍按那时的路径,来源仍算结果。
519
+ // iPhone 轻点就是打开,菜单里不放「打开」。
520
+ function resultMenu(event, row) {
521
+ press.reset();
522
+ const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER, { path } = row;
523
+ menuFrom = 'result';
524
+ menu.open(event, { title: path, items: [
525
+ ...(isIOS || dead ? [] : [{ label: '打开', run: taken(() => (row.kind === EntryKind.DIR ? revealResult(path, true) : openResult(path))) }, { separator: true }]),
526
+ ...(dead ? [] : [{ label: '添加到聊天', run: taken(() => chat.add(path)) }]),
527
+ { label: '复制相对路径', run: taken(() => coda.copy(path)) },
528
+ { label: '复制绝对路径', run: taken(() => coda.copy(`${model.root.path}/${path}`)) },
529
+ { separator: true },
530
+ { label: '在目录中显示', run: taken(() => revealResult(path)) },
531
+ { label: '属性', run: taken(() => openInfo(row)) },
532
+ ] });
533
+ }
534
+ // 结果里打开文件:设预览,不设 selected;结果自己的选中是刚打开的那个,返回后回到结果。
535
+ function openResult(path) {
536
+ if (search.select(path)) hits.select();
537
+ openFile(path, { select: false });
538
+ }
539
+ // 在目录中显示(open 为真:文件夹结果,找到之后再展开它或进入它)。
540
+ function revealResult(path, open = false) { locator.show(path, { open }); }
411
541
  $('tree').addEventListener('scroll', menu.hide, { passive: true });
412
542
  grid.onScroll(menu.hide);
543
+ hitsEl.addEventListener('scroll', menu.hide, { passive: true });
544
+ // iPhone:开始滚动结果时收起键盘。
545
+ hitsEl.addEventListener('scroll', () => { if (isIOS && searchbar.focused) searchbar.blur(); }, { passive: true });
413
546
 
414
547
  // ---- 键盘(Mac)----
415
548
  // 两个作用域各管各的,匹配的键同步 preventDefault,不匹配的不拦;菜单开着不处理,两处都不主动抢焦点。
@@ -426,6 +559,46 @@ function browseKey(event) {
426
559
  }
427
560
  tree.onKey(browseKey);
428
561
  grid.onKey(browseKey);
562
+ // 搜索框和结果的键盘(第 18.5 节的分派表):输入法组字中的按键一律不管;菜单开着时 Esc 归菜单(关菜单、消费掉这个 Esc),这里不处理。
563
+ // ⌘F 在浏览区(含结果和页面本身)聚焦搜索框并选中里面的字;预览、属性页、说明区不拦;菜单开着时先关菜单。
564
+ function searchBoxKey(event) {
565
+ if (event.key === 'Escape' && menu.consumed(event)) event.preventDefault(); // 菜单关掉的 Esc:搜索框是 type=search,默认动作会清空它,要拦下
566
+ if (isIOS || event.isComposing || !menu.hidden || menu.consumed(event)) return;
567
+ if (event.key === 'Escape') {
568
+ event.preventDefault();
569
+ const clearing = search.text !== '';
570
+ if (clearing) clearSearch();
571
+ if (clearing) wantFocus = true; else focusBrowse(); // 清空之后结果让位给目录树:等重画把它放出来再交焦点
572
+ } else if (event.key === 'ArrowDown' && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey && searching() && search.rows().length > 0) {
573
+ event.preventDefault();
574
+ hits.focus();
575
+ const first = search.rows()[0].path; // 明确选中第一条(不是相对移动:有旧选中时 ↓ 会选到下一条)
576
+ if (search.select(first)) hits.select();
577
+ hits.scrollTo(0);
578
+ }
579
+ }
580
+ hits.onKey(event => {
581
+ if (isIOS || event.isComposing || !menu.hidden || menu.consumed(event)) return;
582
+ if (event.key === 'Escape') { event.preventDefault(); searchbar.focus(); return; }
583
+ const action = browseAction(event);
584
+ if (!action) return;
585
+ event.preventDefault();
586
+ // ← →、⌘↑ 什么都不做:不改被遮住的目录树和图标视图的目录
587
+ if (action === 'up' || action === 'down') hits.key(action);
588
+ else if (action === 'open') hits.openSelected();
589
+ });
590
+ document.addEventListener('keydown', event => {
591
+ if (isIOS || event.isComposing || !event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.key?.toLowerCase() !== 'f') return;
592
+ if (!menu.hidden) menu.hide();
593
+ const layer = mode();
594
+ if (layer === 'preview') { // 能查找的文本:打开查找条并聚焦(已开就选中输入框的字);图片、二进制、读取中、读不到不拦
595
+ if (preview.canFind) { event.preventDefault(); preview.openFind(); }
596
+ return;
597
+ }
598
+ if (layer !== 'browse') return;
599
+ event.preventDefault();
600
+ searchbar.select();
601
+ });
429
602
  // 侧栏预览:只有 ⌘↑,返回。焦点要在面板里才收得到(点正文、打开时交接)。
430
603
  $('preview').addEventListener('keydown', event => {
431
604
  if (isIOS || infoOpen || !menu.hidden || !previewAction(event)) return;
@@ -437,7 +610,8 @@ $('preview').addEventListener('keydown', event => {
437
610
  // 进入子目录滚到顶部,先记下上层的位置;回上一层恢复进去之前的位置(记录在内存里,页面卸载后没有,回到顶部)。
438
611
  // shownCwd:页面已经处理过的 cwd;它被模型自己换掉(目录没了退到上一层、根目录变了回到根目录)时,在 landed 里补上滚动。
439
612
  let shownCwd = '';
440
- function enterDir(path) {
613
+ const enterDir = taken(path => enterInto(path));
614
+ function enterInto(path) {
441
615
  trail.remember(model.cwd, grid.scroll());
442
616
  selectEntry(null); // 进入新的一层:选中清空
443
617
  model.enter(path);
@@ -449,6 +623,7 @@ function enterDir(path) {
449
623
  }
450
624
  // 退 levels 层(到根为止);已经在根目录返回 false。record 为假时不记过渡意图(goBack 里的内部调用:意图由它记)。
451
625
  function leaveDir(levels = 1, record = true) {
626
+ takeover++; // 用户经按钮、键盘、返回退出图标视图的一层
452
627
  if (model.cwd === '') return false;
453
628
  const from = model.cwd.split('/');
454
629
  model.leave(levels);
@@ -473,12 +648,14 @@ function landed() {
473
648
  // 路径是上层的标题,由远到近,不含当前页:图标视图在 a/b 是 [根目录名, 'a'];列表视图没有。属性页、预览各多一层当前页(要回到的那一页):列表视图是 '资源管理器',图标视图是当前目录名。
474
649
  // 预览开着是 opened 不为空、且根目录就绪;没就绪时页面是说明区,路径为空。
475
650
  // 标题是当前目录名:根目录是根目录名。
476
- const dirTitle = () => (model.cwd === '' || model.view !== View.ICONS ? rootName(model.root.path) : model.cwd.slice(model.cwd.lastIndexOf('/') + 1));
651
+ // 搜索时结果盖住了图标视图的目录:标题是根目录名。
652
+ const dirTitle = () => (model.cwd === '' || model.view !== View.ICONS || searching() ? rootName(model.root.path) : model.cwd.slice(model.cwd.lastIndexOf('/') + 1));
477
653
  const previewOpen = () => model.ready && model.opened !== null;
654
+ // 搜索本身不是一级:搜索模式下图标视图的目录层级不声明(搜索盖住了它们),从结果打开的预览和属性页要回到的那一页叫「搜索」(第 18.5 节的表)。
478
655
  function backPath() {
479
- const icons = model.view === View.ICONS && model.ready;
656
+ const icons = model.view === View.ICONS && model.ready && !searching();
480
657
  const upper = icons && model.cwd !== '' ? [rootName(model.root.path), ...model.cwd.split('/').slice(0, -1)] : [];
481
- const here = icons ? dirTitle() : '资源管理器';
658
+ const here = searching() ? '搜索' : icons ? dirTitle() : '资源管理器';
482
659
  return [...upper, ...(infoOpen ? [here] : []), ...(previewOpen() ? [here] : [])];
483
660
  }
484
661
  let declared = [];
@@ -499,7 +676,7 @@ function goBack(steps) {
499
676
  let used = 0, layer = false;
500
677
  if (previewOpen() && steps > used) { model.closeFile(); used++; layer = true; } // 走和 Mac 一样的 closeFile:opened 清,selected 留着
501
678
  if (infoOpen && steps > used) { closeInfo(false); used++; layer = true; }
502
- const levels = Math.min(steps - used, model.view === View.ICONS && model.cwd !== '' ? model.cwd.split('/').length : 0);
679
+ const levels = Math.min(steps - used, model.view === View.ICONS && model.cwd !== '' && !searching() ? model.cwd.split('/').length : 0); // 搜索模式下不消耗被遮住的图标视图目录
503
680
  if (levels > 0) { leaveDir(levels, false); used += levels; }
504
681
  if (used > 0) note(layer ? { kind: 'pop', from, to: mode() } : { kind: 'fade', to: model.cwd });
505
682
  return used > 0;
@@ -539,6 +716,9 @@ function onSession(data) {
539
716
  menu.hide();
540
717
  tree.reset();
541
718
  grid.reset();
719
+ hits.reset();
720
+ locator.cancel();
721
+ clearSearch(); // 换会话:搜索词、结果、结果的选中、定位都清掉
542
722
  epoch++;
543
723
  hint.hide();
544
724
  const saved = persisted.sessions[data.session] ?? null;
@@ -558,8 +738,10 @@ function onRoot(data) {
558
738
  if (data.state !== before?.state || data.path !== before?.path) { menu.hide(); intent = null; endRunning(); } // 开着的菜单里的路径是旧根目录下的;换根目录不播过渡
559
739
  if (data.state !== RootState.READY || before?.path !== data.path) closeInfo(false, true); // 属性页看的是旧根目录下的路径
560
740
  const scope = model.scope;
741
+ if (data.state !== RootState.READY) { search.suspend(); locator.cancel(); } // 根目录暂不可用:取消在途搜索,丢掉结果,搜索词留着;定位作废(再就绪也不接着做)
561
742
  const done = model.receive(data);
562
- if (model.scope !== scope) { invalidateScroll(); pending.preview = null; press.reset(); } // 换了根目录(同根重建不算):旧根目录的位置和记录不能给新的用,待恢复的预览位置也是
743
+ if (model.scope !== scope) { invalidateScroll(); pending.preview = null; press.reset(); clearSearch(); locator.cancel(); } // 换了根目录(同根重建不算):旧根目录的位置和记录不能给新的用,待恢复的预览位置也是;搜索词和结果清空
744
+ else if (data.state === RootState.READY) search.resume(); // 再就绪时 scope 没变:重搜
563
745
  if (done && data.state === RootState.READY) {
564
746
  if (before?.path !== data.path) { if (model.opened !== null) preview.reload(); } else preview.refresh(); // 换了根目录,opened 已清空:旧预览随即关掉,不再读
565
747
  }
@@ -567,13 +749,15 @@ function onRoot(data) {
567
749
 
568
750
  function onChanged(data) {
569
751
  if (!model.receive(data)) return;
570
- menu.hide(); // 开着的菜单可能指着已经删除的路径
752
+ // 开着的菜单可能指着已经删除的路径:目录树、图标视图的行菜单照旧关。结果行的菜单留着(第 18.3、18.4 节:重搜替换结果时菜单留着,操作按打开菜单时的路径做)。
753
+ if (menuFrom !== 'result') menu.hide();
571
754
  dataRound++;
572
755
  preview.refresh();
573
756
  info.refresh();
757
+ search.research(); // 搜索期间目录模型照常刷新;有搜索词就重搜,旧结果留到新结果来
574
758
  }
575
759
 
576
- const remeasure = () => { tree.remeasure(); grid.remeasure(); };
760
+ const remeasure = () => { tree.remeasure(); grid.remeasure(); hits.remeasure(); };
577
761
  remeasure();
578
762
  quiet(() => coda.on('theme', remeasure));
579
763
  render();
@@ -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
@@ -42,6 +42,7 @@ const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint }
42
42
  const preview = mountPreview($('preview'), {
43
43
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
44
44
  selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
45
+ consumed: menu.consumed,
45
46
  });
46
47
 
47
48
  // 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
@@ -155,5 +156,12 @@ quiet(() => coda.on('visibility', visible => { if (!visible) { press.reset(); sa
155
156
  preview.onScroll(queueSave);
156
157
  preview.onScroll(menu.hide);
157
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
+
158
166
  render();
159
167
  conn.hello();