@coda-console/resource-manager 0.7.2 → 0.8.1

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