@coda-console/resource-manager 0.6.0 → 0.7.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/README.md CHANGED
@@ -8,8 +8,11 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
8
8
  ## 功能
9
9
 
10
10
  - 两种视图:**列表**(目录树,按需展开,超大目录分页显示)和**图标**(一次看一层,每个条目是类型图标加名字,名字最多两行,`package.json` 这样的名字优先在扩展名前折行)。在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「显示」›「视图」里切换,全局一份,两种视图各自保留滚动位置。
11
- - 图标视图里**单击文件夹进入这一层**,单击文件打开(Mac 在侧栏里切到文件,iPhone 推入文件页);回上一层:iPhone 用系统的返回,Mac 点头部最左边的返回键。**没有预览面板**:只有一个侧栏,不会单击选中再在旁边预览,也没有面包屑。
11
+ - **Mac 照 Finder**:单击只选中,**双击**打开——文件在侧栏里切到预览,文件夹在列表里展开或收起、在图标视图里进入;单击展开箭头只展开,选中不变;单击空白取消选中;右键菜单第一项是「打开」(文件夹在列表里写「展开」「收起」),不能打开的条目没有。**iPhone 不变**:轻点就打开(文件夹展开或进入,文件推入文件页)。
12
+ - 图标视图回上一层:iPhone 用系统的返回,Mac 点头部最左边的返回键或按 ⌘↑,退回的那一层里选中刚才进去的文件夹。**没有预览面板**:只有一个侧栏,也没有面包屑。
13
+ - **Mac 的键盘**:点一下目录树或图标视图让它拿到焦点(Tab 也能进来),↑ ↓ 移动选中(图标视图按行列走),列表里 → 展开、← 收起或选中所在的文件夹,图标视图里 ← → 选左右的条目;⌘↓ 同双击(打开、展开、进入);⌘↑ 在图标视图里回上一层,在预览里返回目录树或图标视图。不做多选、按字母跳转,Return 和空格也没绑定。读屏的 `aria-activedescendant` 没做(见 `docs/backlog.md`)。
12
14
  - 文本预览(带行号,可跨行选中复制,最多读 1 MiB)和图片预览(PNG、JPEG、GIF、WebP、SVG,最多 8 MiB)。
15
+ - 代码按语言上色:三十多种常见语言,只按文件名和扩展名认,不猜内容,深浅各一套配色;认不出的显示纯文本。超过 128 KiB 的文件不上色,说明区注明「不高亮」。用的是近似的语法规则,不是语法检查,个别文件会认错(如 `.h` 一律按 C++,`.m` 一律按 Objective-C),不保证完整支持。
13
16
  - Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
14
17
  - 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
15
18
  - 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「显示」›「排序」里选,当前项有对勾。两种视图用同一个排序。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
@@ -34,7 +37,7 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
34
37
 
35
38
  ## 开发
36
39
 
37
- 不需要安装依赖,也没有构建步骤。Node 由 Coda 提供(`$CODA_NODE`)。
40
+ 不需要安装依赖,也没有构建步骤;第三方代码只有 `view/vendor/highlight/` 下原样复制的 highlight.js(升级方法见三期设计第 15.2 节)。Node 由 Coda 提供(`$CODA_NODE`)。
38
41
 
39
42
  ```sh
40
43
  # 测试,也可以用 npm test。Node 24 上不能写成 node --test test/
@@ -77,4 +80,6 @@ npx --yes github:coda-console/coda-plugins#<提交> . --manifest
77
80
 
78
81
  ## 许可
79
82
 
80
- MIT
83
+ MIT。
84
+
85
+ 第三方:`view/vendor/highlight/` 里是 [highlight.js](https://highlightjs.org/) 11.12.0 的浏览器构建,BSD-3-Clause 许可,版权声明和许可全文在同目录的 `LICENSE`,文件原样复制,没有修改。
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "@coda-console/resource-manager",
4
4
  "displayName": "资源管理器",
5
5
  "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本和图片,把路径交给对话。",
6
- "version": "0.6.0",
6
+ "version": "0.7.0",
7
7
  "categories": ["工作流程"],
8
8
  "license": "MIT",
9
9
  "repository": {
package/view/app.mjs CHANGED
@@ -12,13 +12,15 @@ import { showNotice } from './notice.mjs';
12
12
  import { mountPreview } from './preview.mjs';
13
13
  import { EntryKind, RootState, SortKey, Type } from './protocol.mjs';
14
14
  import { createRestore, createTrail } from './restore.mjs';
15
+ import { browseAction, previewAction } from './keys.mjs';
15
16
  import { mountTree, rootName } from './tree.mjs';
16
17
 
17
18
  const coda = window.coda;
18
19
  const $ = id => document.getElementById(id);
19
20
  const quiet = fn => { try { return fn(); } catch { return undefined; } };
20
21
  const hasToolbar = typeof coda.toolbar === 'function' && coda.platform === 'mac';
21
- // iPhone 上打开文件推入新视图,树页不进预览模式;selected 只用来高亮,从保存的状态恢复出来也一样。
22
+ // iPhone 上打开文件推入新视图,树页不进预览模式;opened 一直是 null,selected 只用来高亮。
23
+ // Mac 照 Finder:单击选中、双击打开,键盘接在目录树和图标视图的滚动容器上。
22
24
  const isIOS = coda.platform === 'ios';
23
25
 
24
26
  let persisted = parseState(quiet(() => coda.getState()));
@@ -42,7 +44,8 @@ const tree = mountTree($('tree'), model, {
42
44
  more: path => model.loadMore(path),
43
45
  retry: path => model.retry(path),
44
46
  menu: (event, row) => pathMenu(event, row),
45
- }, { draggable: !isIOS, longPress: isIOS });
47
+ select: isIOS ? null : path => selectEntry(path),
48
+ }, { draggable: !isIOS, longPress: isIOS, keyboard: !isIOS });
46
49
  const grid = mountGrid($('grid'), model, {
47
50
  open: openFile,
48
51
  enter: path => enterDir(path),
@@ -50,13 +53,14 @@ const grid = mountGrid($('grid'), model, {
50
53
  retry: path => model.retry(path),
51
54
  menu: (event, cell) => pathMenu(event, cell),
52
55
  back: nativeBack ? null : () => leaveDir(),
53
- }, { draggable: !isIOS, longPress: isIOS });
56
+ select: isIOS ? null : path => selectEntry(path),
57
+ }, { draggable: !isIOS, longPress: isIOS, keyboard: !isIOS });
54
58
  const restore = createRestore(model, { tree, grid });
55
59
  const trail = createTrail();
56
60
  const preview = mountPreview($('preview'), {
57
61
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
58
62
  actions: isIOS ? [] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
59
- back: isIOS ? null : () => { backPressed = true; model.select(null); },
63
+ back: isIOS ? null : closePreview,
60
64
  // 选中文字的右键菜单只有 Mac:iPhone 用系统的选区菜单。
61
65
  selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
62
66
  });
@@ -93,8 +97,11 @@ function openInView(path) {
93
97
  }
94
98
  function openFile(path) {
95
99
  if (isIOS && opening) return; // 先于 select 和保存:被忽略的点击什么都不改
96
- model.select(path);
97
- if (!isIOS) return;
100
+ if (!isIOS) {
101
+ openPressed = true; // 用户打开的:render 把焦点交给预览面板
102
+ return model.openFile(path);
103
+ }
104
+ selectEntry(path);
98
105
  saveNow(); // 视图随即卸载,这一刻的展开状态、条数和滚动位置先存下
99
106
  openInView(path);
100
107
  }
@@ -108,9 +115,23 @@ function schedule() {
108
115
  queueMicrotask(() => { queued = false; render(); });
109
116
  }
110
117
 
111
- // 用户点了预览头部的返回:render 据此决定焦点要不要交给目录树,别的模式变化不动焦点。
118
+ // 选中:页面里唯一的入口(单击、取消选中、键盘移动、回上一层)。只改 model.selected 和现有节点上的 .sel,不重画,也不经 onChange;保存自己排。
119
+ function selectEntry(path) {
120
+ if (!model.select(path)) return;
121
+ (model.view === View.ICONS ? grid : tree).select();
122
+ queueSave();
123
+ }
124
+ const browser = () => (model.view === View.ICONS ? grid : tree);
125
+
126
+ // 预览头部的返回和预览里的 ⌘↑ 是同一个动作:opened 清掉,selected 留着。
127
+ function closePreview() {
128
+ backPressed = true;
129
+ model.closeFile();
130
+ }
131
+ // 用户点了预览头部的返回:render 据此决定焦点要不要交给浏览区,别的模式变化不动焦点。
112
132
  let backPressed = false;
113
- const mode = () => (infoOpen ? 'info' : !model.ready ? 'notice' : model.selected !== null && !isIOS ? 'preview' : model.view === View.ICONS ? 'grid' : 'tree');
133
+ let openPressed = false; // 用户打开了文件:同返回对称,页面持有焦点时 render 把焦点交给预览面板
134
+ const mode = () => (infoOpen ? 'info' : !model.ready ? 'notice' : model.opened !== null && !isIOS ? 'preview' : model.view === View.ICONS ? 'grid' : 'tree');
114
135
 
115
136
  // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
116
137
  let noticeKey = null;
@@ -124,8 +145,8 @@ function paintNotice() {
124
145
 
125
146
  function render() {
126
147
  const current = mode();
127
- const refocus = backPressed && document.hasFocus();
128
- backPressed = false;
148
+ const refocus = backPressed && document.hasFocus(), handoff = openPressed && document.hasFocus();
149
+ backPressed = openPressed = false;
129
150
  for (const id of ['tree', 'grid', 'preview', 'notice', 'info']) {
130
151
  $(id).classList.toggle('off', current !== id);
131
152
  $(id).inert = current !== id;
@@ -135,13 +156,15 @@ function render() {
135
156
  (model.view === View.ICONS ? grid : tree).render(); // 只画正在用的视图,另一个留着它的内容和滚动位置
136
157
  landed();
137
158
  restore.settle();
138
- if (current === 'preview' && preview.path !== model.selected) {
139
- preview.open(model.selected, pending.preview);
159
+ if (current === 'preview' && preview.path !== model.opened) {
160
+ preview.open(model.opened, pending.preview);
140
161
  pending.preview = null;
141
162
  } else if ((browsing || current === 'notice') && preview.path !== null) preview.close(); // 属性页和预览一样只切可见性,不动别的面板的内容
142
163
  // 返回按钮随预览一起 inert,焦点会掉到页面外:用户刚点了返回、页面又持有焦点时交给目录树或网格。
143
164
  // 后台刷新、切会话、root 变化造成的切换不动焦点,免得抢走客户端输入框的焦点。
144
- if (refocus && browsing) { $(current).tabIndex = -1; $(current).focus(); }
165
+ if (refocus && browsing) browser().focus();
166
+ // 打开时浏览区变 inert,焦点本来就会掉:交给预览面板,⌘↑ 才收得到。
167
+ if (handoff && current === 'preview') $('preview').focus();
145
168
  syncToolbar();
146
169
  declareBack();
147
170
  }
@@ -273,7 +296,11 @@ preview.onScroll(menu.hide);
273
296
  // 不能打开的条目(指向外面或失效的链接、other)没有「添加到聊天」,和不能拖动一致;它们仍有复制路径和属性。
274
297
  function pathMenu(event, row) {
275
298
  const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER;
299
+ // Mac 的第一项和双击是同一个动作(右键不改选中);文件夹在列表里写展开或收起,别的写打开。iPhone 轻点就是打开,菜单不变。
300
+ const folder = row.kind === EntryKind.DIR, listed = model.view !== View.ICONS;
301
+ const open = isIOS || dead ? [] : [{ label: folder && listed ? (row.open ? '收起' : '展开') : '打开', run: () => browser().activate(row) }, { separator: true }];
276
302
  menu.open(event, { title: row.path, detail: dead ? undefined : infoText(row) || undefined, items: [
303
+ ...open,
277
304
  ...(dead ? [] : [{ label: '添加到聊天', run: () => chat.add(row.path) }]),
278
305
  { label: '复制相对路径', run: () => coda.copy(row.path) },
279
306
  { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${row.path}`) },
@@ -284,12 +311,35 @@ function pathMenu(event, row) {
284
311
  $('tree').addEventListener('scroll', menu.hide, { passive: true });
285
312
  grid.onScroll(menu.hide);
286
313
 
314
+ // ---- 键盘(Mac)----
315
+ // 两个作用域各管各的,匹配的键同步 preventDefault,不匹配的不拦;菜单开着不处理,两处都不主动抢焦点。
316
+ // 浏览区:按了键就算用户自己动了,作废这个视图还在等的滚动恢复,即使这次不用滚动;⌘↑ 只有图标视图有(回上一层,同头部的返回),根目录什么都不做。
317
+ function browseKey(event) {
318
+ if (isIOS || !menu.hidden) return;
319
+ const action = browseAction(event), icons = model.view === View.ICONS;
320
+ if (!action || (action === 'parent' && !icons)) return;
321
+ event.preventDefault();
322
+ restore.drop(icons ? 'grid' : 'tree');
323
+ if (action === 'open') browser().openSelected();
324
+ else if (action === 'parent') leaveDir();
325
+ else browser().key(action);
326
+ }
327
+ tree.onKey(browseKey);
328
+ grid.onKey(browseKey);
329
+ // 侧栏预览:只有 ⌘↑,返回。焦点要在面板里才收得到(点正文、打开时交接)。
330
+ $('preview').addEventListener('keydown', event => {
331
+ if (isIOS || infoOpen || !menu.hidden || !previewAction(event)) return;
332
+ event.preventDefault();
333
+ closePreview();
334
+ });
335
+
287
336
  // ---- 图标视图的进入和返回 ----
288
337
  // 进入子目录滚到顶部,先记下上层的位置;回上一层恢复进去之前的位置(记录在内存里,页面卸载后没有,回到顶部)。
289
338
  // shownCwd:页面已经处理过的 cwd;它被模型自己换掉(目录没了退到上一层、根目录变了回到根目录)时,在 landed 里补上滚动。
290
339
  let shownCwd = '';
291
340
  function enterDir(path) {
292
341
  trail.remember(model.cwd, grid.scroll());
342
+ selectEntry(null); // 进入新的一层:选中清空
293
343
  model.enter(path);
294
344
  shownCwd = model.cwd;
295
345
  restore.drop('grid');
@@ -299,8 +349,11 @@ function enterDir(path) {
299
349
  // 退 levels 层(到根为止);已经在根目录返回 false。
300
350
  function leaveDir(levels = 1) {
301
351
  if (model.cwd === '') return false;
352
+ const from = model.cwd.split('/');
302
353
  model.leave(levels);
303
354
  land(trail.take(model.cwd) ?? 0);
355
+ // 选中来时经过的那个文件夹(退到的那一层的直接子项)。目录被删、模型自己退回上层走 landed,不改选中。
356
+ selectEntry(from.slice(0, model.cwd === '' ? 1 : model.cwd.split('/').length + 1).join('/'));
304
357
  declareBack();
305
358
  return true;
306
359
  }
@@ -372,7 +425,7 @@ function onSession(data) {
372
425
  clearTimeout(unlockTimer);
373
426
  hint.hide();
374
427
  const saved = persisted.sessions[data.session] ?? null;
375
- pending = { preview: saved ? { top: saved.scroll.top, left: saved.scroll.left } : null };
428
+ pending = { preview: saved?.opened ? { top: saved.scroll.top, left: saved.scroll.left } : null };
376
429
  model.receive(data, saved);
377
430
  trail.clear();
378
431
  restore.clear();
@@ -391,7 +444,7 @@ function onRoot(data) {
391
444
  const done = model.receive(data);
392
445
  if (model.scope !== scope) invalidateScroll(); // 换了根目录(同根重建不算):旧根目录的位置和记录不能给新的用
393
446
  if (done && data.state === RootState.READY) {
394
- if (before?.path !== data.path) preview.reload(); else preview.refresh();
447
+ if (before?.path !== data.path) { if (model.opened !== null) preview.reload(); } else preview.refresh(); // 换了根目录,opened 已清空:旧预览随即关掉,不再读
395
448
  }
396
449
  }
397
450
 
package/view/gestures.mjs CHANGED
@@ -5,10 +5,12 @@ export const HOLD_SLOP = 10;
5
5
 
6
6
  // el:接事件的元素;scroller:滚动的元素(滚动事件不冒泡),缺省同 el。选项:
7
7
  // hit(event) → 点到的那一项或 undefined;pressable(item):能不能弹菜单、拖动、长按(目录树的说明行、「再显示」不能);
8
- // activate(item):点击;menu(event, item):右键,长按到点时收到 { clientX, clientY };dragText(item):拖动时带的文字(元素是否可拖由调用方设 draggable);
8
+ // activate(item):点击(iPhone);Mac 给了 select 就按 Finder 的规则:单击条目只 select(item),单击空白 select(null),双击条目才 activate(item);
9
+ // 说明行、「再显示」这类不能选的项单击就 activate,direct(event, item) 为真的点击(展开箭头)也直接 activate、不选中,双击它不再重复激活。
10
+ // 双击靠浏览器的 dblclick,要求派发时目标节点还在容器里,所以 select 不能重画。menu(event, item):右键,长按到点时收到 { clientX, clientY };dragText(item):拖动时带的文字(元素是否可拖由调用方设 draggable);
9
11
  // longPress:触屏上按住一项打开 menu,不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
10
12
  // 返回 { reset, dispose }:reset 在切会话时调用,长按的等待和吞点击的标记都属于上一个会话;dispose 摘掉全部监听。
11
- export function mountGestures(el, { hit, pressable, activate, menu, dragText, longPress = false, scroller = el }) {
13
+ export function mountGestures(el, { hit, pressable, activate, select, direct = () => false, menu, dragText, longPress = false, scroller = el }) {
12
14
  const listeners = [];
13
15
  const on = (target, type, fn, options) => { target.addEventListener(type, fn, options); listeners.push([target, type, fn]); };
14
16
 
@@ -39,7 +41,14 @@ export function mountGestures(el, { hit, pressable, activate, menu, dragText, lo
39
41
  on(el, 'click', event => {
40
42
  if (swallow) { swallow = false; return; }
41
43
  const item = hit(event);
42
- if (item) activate(item);
44
+ if (!select) { if (item) activate(item); return; }
45
+ if (!item) select(null);
46
+ else if (!pressable(item) || direct(event, item)) activate(item);
47
+ else select(item);
48
+ });
49
+ if (select) on(el, 'dblclick', event => {
50
+ const item = hit(event);
51
+ if (item && pressable(item) && !direct(event, item)) activate(item);
43
52
  });
44
53
  on(el, 'contextmenu', event => {
45
54
  const item = hit(event);
package/view/grid.mjs CHANGED
@@ -94,12 +94,40 @@ export function windowOf(layout, first, last) {
94
94
  return { from, to: Math.min(tail.from + tail.count, tail.note ? tail.from + 1 : firstOfRow(layout, last - 1) + layout.cols) };
95
95
  }
96
96
 
97
- // handlers: { open(path), enter(path), more(path), retry(path), menu(event, cell), back? }
97
+ // 键盘在图标视图里的一步(纯逻辑):action 是 up、down、left、right。返回 { select: 序号 } 或 null。
98
+ // 上下走同一列:跳过说明项独占的行,目标行不满、没有这一列时选那一行的最后一个;左右在条目之间走(行尾接下一行的第一个)。
99
+ // 选中的条目不在 cells 里按没有选中算:↓ 选第一个条目,↑ 选最后一个。
100
+ export function stepCells(cells, layout, selected, action) {
101
+ const at = selected === null ? -1 : cells.findIndex(cell => cell.type === 'entry' && cell.path === selected);
102
+ const first = cells.findIndex(cell => cell.type === 'entry');
103
+ if (first < 0) return null;
104
+ if (at < 0) {
105
+ if (action === 'down') return { select: first };
106
+ if (action === 'up') return { select: cells.map(cell => cell.type).lastIndexOf('entry') };
107
+ return null;
108
+ }
109
+ if (action === 'left' || action === 'right') {
110
+ const next = at + (action === 'right' ? 1 : -1);
111
+ return cells[next]?.type === 'entry' ? { select: next } : null;
112
+ }
113
+ const row = rowOfCell(layout, at), column = at - firstOfRow(layout, row), step = action === 'down' ? 1 : -1;
114
+ for (let r = row + step; r >= 0 && r < layout.rows; r += step) {
115
+ const span = spanAt(layout, r);
116
+ if (span.note) continue;
117
+ return { select: Math.min(firstOfRow(layout, r) + column, span.from + span.count - 1) };
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // handlers: { open(path), enter(path), more(path), retry(path), menu(event, cell), back?, select?(path | null) }
123
+ // select 是 Mac 单击选中,不给就是 iPhone 的轻点打开。
98
124
  // back 给了就在头部最左边放「返回」(Mac,和没有原生返回的环境);不给就没有头部,iPhone 用原生返回,标题在工具条上。
99
125
  // draggable、longPress 同 mountTree。
100
- export function mountGrid(el, model, handlers, { draggable = true, longPress = false } = {}) {
126
+ // keyboard:滚动容器(.gbody)可以获得焦点,键盘才接得上(Mac)。
127
+ export function mountGrid(el, model, handlers, { draggable = true, longPress = false, keyboard = false } = {}) {
101
128
  const head = h('div', { class: 'ghead' }), body = h('div', { class: 'gbody' }), spacer = h('div', { class: 'gspacer' }), win = h('div', { class: 'gwin' });
102
129
  head.hidden = true;
130
+ if (keyboard) body.tabIndex = 0;
103
131
  spacer.append(win);
104
132
  body.append(spacer);
105
133
  el.replaceChildren(head, body);
@@ -175,20 +203,33 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
175
203
  paint();
176
204
  }
177
205
 
178
- const gestures = mountGestures(el, {
206
+ // 点击(iPhone)、双击、⌘↓ 和右键「打开」共用这一份。
207
+ const activate = cell => {
208
+ if (cell.type === 'more') return handlers.more(cell.path);
209
+ if (cell.type === 'status') return cell.retry ? handlers.retry(cell.path) : undefined;
210
+ if (cell.kind === EntryKind.DIR) handlers.enter(cell.path);
211
+ else if (cell.kind === EntryKind.FILE) handlers.open(cell.path);
212
+ };
213
+ // 事件挂在 body 上:头部的返回键点击不算「点空白」。
214
+ const gestures = mountGestures(body, {
179
215
  hit: event => cells[event.target.closest?.('.gi')?.dataset.i],
180
216
  pressable: cell => cell.type === 'entry',
181
- activate: cell => {
182
- if (cell.type === 'more') return handlers.more(cell.path);
183
- if (cell.type === 'status') return cell.retry ? handlers.retry(cell.path) : undefined;
184
- if (cell.kind === EntryKind.DIR) handlers.enter(cell.path);
185
- else if (cell.kind === EntryKind.FILE) handlers.open(cell.path);
186
- },
217
+ activate,
218
+ select: handlers.select && (cell => handlers.select(cell ? cell.path : null)),
187
219
  menu: (event, cell) => handlers.menu(event, cell),
188
220
  dragText: cell => cell.path,
189
221
  longPress,
190
222
  scroller: body,
191
223
  });
224
+ // 选中变了只在现有节点上切 .sel,不重建:双击的 dblclick 要落在还在容器里的节点上。
225
+ const mark = () => { for (const node of win.children) node.classList.toggle('sel', cells[node.dataset.i]?.type === 'entry' && cells[node.dataset.i].path === model.selected); };
226
+ // 滚到这个单元格能看见,只滚最少的距离。
227
+ const reveal = index => {
228
+ const top = (spacer.offsetTop || 0) + rowTop(layout, rowOfCell(layout, index), cellH, noteH);
229
+ if (top < body.scrollTop) body.scrollTop = top;
230
+ else if (top + cellH > body.scrollTop + body.clientHeight) body.scrollTop = top + cellH - body.clientHeight;
231
+ paint();
232
+ };
192
233
  body.addEventListener('scroll', paint, { passive: true });
193
234
  new ResizeObserver(relayout).observe(body);
194
235
 
@@ -206,6 +247,20 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
206
247
  scrollTo(top) { body.scrollTop = top; paint(); }, // 浏览器的滚动事件随后还会画一次;这里先画,位置才马上对
207
248
  onScroll(fn) { body.addEventListener('scroll', fn, { passive: true }); },
208
249
  get layout() { return layout; },
250
+ select: mark,
251
+ activate,
252
+ focus() { body.focus(); },
253
+ onKey(fn) { body.addEventListener('keydown', fn); },
254
+ key(action) {
255
+ const step = stepCells(cells, layout, model.selected, action);
256
+ if (!step) return;
257
+ handlers.select(cells[step.select].path);
258
+ reveal(step.select);
259
+ },
260
+ openSelected() {
261
+ const cell = model.selected === null ? undefined : cells.find(item => item.type === 'entry' && item.path === model.selected);
262
+ if (cell) activate(cell);
263
+ },
209
264
  // 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。
210
265
  reset() { gestures.reset(); },
211
266
  dispose() { gestures.dispose(); },
@@ -0,0 +1,93 @@
1
+ // 语法高亮:调用 highlight.js,把它的输出解析成节点。文件内容不经过 HTML 解析,所以 CR、NUL 和未配对的代理项都原样保留。
2
+ // highlight.js 的输出只有 <span class="…">、</span> 和五种转义;格式之外的任何内容都算失败,调用方显示纯文本。
3
+ import hljs from './vendor/highlight/highlight.min.mjs';
4
+ import dart from './vendor/highlight/languages/dart.min.mjs';
5
+ import dockerfile from './vendor/highlight/languages/dockerfile.min.mjs';
6
+ import scala from './vendor/highlight/languages/scala.min.mjs';
7
+ import { h } from './dom.mjs';
8
+
9
+ hljs.registerLanguage('dart', dart);
10
+ hljs.registerLanguage('dockerfile', dockerfile);
11
+ hljs.registerLanguage('scala', scala);
12
+
13
+ // 超过这个字节数不高亮(实测依据和为什么是 128 KiB 见 docs/design/phase-3.md 第 15.4 节)。
14
+ export const HIGHLIGHT_LIMIT = 128 * 1024;
15
+ // 有一行超过这个字符数(UTF-16 长度)也不高亮:压成一行的文件上色慢,也帮不上阅读(第 15.4 节)。
16
+ export const LINE_LIMIT = 5000;
17
+
18
+ // 有没有一行超过 LINE_LIMIT:按 \n 分行(\r 留在行里),只扫一遍,不建数组。
19
+ export function hasLongLine(text) {
20
+ for (let start = 0; start < text.length;) {
21
+ const end = text.indexOf('\n', start);
22
+ if ((end < 0 ? text.length : end) - start > LINE_LIMIT) return true;
23
+ if (end < 0) break;
24
+ start = end + 1;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ const ENTITIES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#x27;': "'" };
30
+ const ENTITY = /&(?:amp|lt|gt|quot|#x27);/y;
31
+ const OPEN = /<span class="([A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*)">/y;
32
+ const CLOSE = '</span>';
33
+ const NEXT = /[<&]/g;
34
+ const CHUNK = 2000; // append(...nodes) 的参数个数有上限,节点多的时候分批
35
+
36
+ export function appendAll(parent, nodes) {
37
+ for (let at = 0; at < nodes.length; at += CHUNK) parent.append(...nodes.slice(at, at + CHUNK));
38
+ }
39
+
40
+ // 解析 html,返回顶层节点(字符串和 span 元素);格式不对返回 null。expected:原文的长度,文字总长不符也算格式不对。
41
+ export function parse(html, expected) {
42
+ const stack = [{ nodes: [], cls: null }];
43
+ let at = 0, length = 0;
44
+ const push = text => {
45
+ const { nodes } = stack.at(-1);
46
+ length += text.length;
47
+ if (typeof nodes.at(-1) === 'string') nodes[nodes.length - 1] += text; else nodes.push(text);
48
+ };
49
+ while (at < html.length) {
50
+ NEXT.lastIndex = at;
51
+ const found = NEXT.exec(html);
52
+ const next = found ? found.index : html.length;
53
+ if (next > at) push(html.slice(at, next));
54
+ if (!found) break;
55
+ at = next;
56
+ if (html[at] === '&') {
57
+ ENTITY.lastIndex = at;
58
+ const entity = ENTITY.exec(html);
59
+ if (!entity) return null;
60
+ push(ENTITIES[entity[0]]);
61
+ at += entity[0].length;
62
+ } else if (html.startsWith(CLOSE, at)) {
63
+ if (stack.length === 1) return null;
64
+ const { nodes, cls } = stack.pop();
65
+ const span = h('span', { class: cls });
66
+ appendAll(span, nodes);
67
+ stack.at(-1).nodes.push(span);
68
+ at += CLOSE.length;
69
+ } else {
70
+ OPEN.lastIndex = at;
71
+ const open = OPEN.exec(html);
72
+ if (!open) return null;
73
+ stack.push({ nodes: [], cls: open[1] });
74
+ at += open[0].length;
75
+ }
76
+ }
77
+ return stack.length === 1 && length === expected ? stack[0].nodes : null;
78
+ }
79
+
80
+ // text 按 language 上色,返回节点数组;没能高亮(库抛错、库自己吞掉了内部错误、输出格式不对)返回 null。
81
+ // 输出里没有 span 不算失败(空文件、只有普通标识符的文件)。
82
+ export function highlight(text, language) {
83
+ try {
84
+ const result = hljs.highlight(text, { language, ignoreIllegals: true });
85
+ if (result.errorRaised) return null;
86
+ return parse(result.value, text.length);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ // 给测试:打包的库本身。
93
+ export { hljs };
package/view/icons.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // 图标:页面里自己画的 SVG,形状近似 SF Symbol,不打包 Apple 的符号,也不用任何第三方素材。颜色都是 currentColor,由 CSS 定:
2
2
  // 种类图标带 tone-* 类(颜色见 style.css 的 --tone-*),没有色调的(工具条、菜单的图标)跟随所在位置的文字色。
3
+ import { invert, lookupByName } from './lookup.mjs';
3
4
  import { EntryKind } from './protocol.mjs';
4
5
 
5
6
  const SVG_NS = 'http://www.w3.org/2000/svg';
@@ -132,7 +133,6 @@ const EXTENSIONS = {
132
133
  database: ['db', 'sqlite', 'sqlite3'],
133
134
  font: ['ttf', 'otf', 'woff', 'woff2'],
134
135
  };
135
- const invert = table => new Map(Object.entries(table).flatMap(([id, keys]) => keys.map(key => [key, id])));
136
136
  const BY_NAME = invert(NAMES), BY_EXT = invert(EXTENSIONS);
137
137
 
138
138
  // 一个条目的种类:{ glyph, tone, label }。目录、链接、其他按种类;文件先按整个文件名,再按扩展名(点开头的名字没有扩展名)。
@@ -141,8 +141,7 @@ export function kindOf({ kind, name }) {
141
141
  if (kind === EntryKind.DIR) return KINDS.dir;
142
142
  if (kind === EntryKind.LINK) return KINDS.link;
143
143
  if (kind === EntryKind.OTHER) return KINDS.other;
144
- const lower = String(name).toLowerCase(), dot = lower.lastIndexOf('.');
145
- return KINDS[BY_NAME.get(lower) ?? (lower.startsWith('.env.') ? 'env' : undefined) ?? (dot > 0 ? BY_EXT.get(lower.slice(dot + 1)) : undefined) ?? 'file'];
144
+ return KINDS[lookupByName(name, BY_NAME, BY_EXT, lower => (lower.startsWith('.env.') ? 'env' : undefined)) ?? 'file'];
146
145
  }
147
146
 
148
147
  // 图标名:种类表里的 glyph。
package/view/index.html CHANGED
@@ -11,7 +11,7 @@
11
11
  <main id="stage">
12
12
  <div id="tree" class="pane tree" role="tree"></div>
13
13
  <div id="grid" class="pane grid"></div>
14
- <div id="preview" class="pane preview"></div>
14
+ <div id="preview" class="pane preview" tabindex="-1"></div>
15
15
  <div id="notice" class="pane empty secondary"></div>
16
16
  <div id="info" class="pane preview info"></div>
17
17
  </main>
package/view/keys.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // Mac 的键盘:只认一组最小的键,不匹配的(含其他修饰键组合)返回 null,页面不拦。设计见 docs/design/phase-3.md 第 15.10 节。
2
+ const ARROWS = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
3
+ const bare = event => !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
4
+ const command = event => event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
5
+
6
+ // 浏览区:↑ ↓ ← → 移动,⌘↓ 打开(同双击),⌘↑ 回上一层。输入法组字中的按键不管。
7
+ export function browseAction(event) {
8
+ if (event.isComposing) return null;
9
+ if (bare(event)) return ARROWS[event.key] ?? null;
10
+ if (command(event)) return event.key === 'ArrowDown' ? 'open' : event.key === 'ArrowUp' ? 'parent' : null;
11
+ return null;
12
+ }
13
+
14
+ // 侧栏预览:只有 ⌘↑(返回)。
15
+ export const previewAction = event => (!event.isComposing && command(event) && event.key === 'ArrowUp' ? 'back' : null);
@@ -0,0 +1,49 @@
1
+ // 认语言:文件名到 highlight.js 的语言 id,只按文件名和扩展名,不猜内容;不在表里的是 null,显示纯文本。
2
+ import { invert, lookupByName } from './lookup.mjs';
3
+
4
+ const NAMES = {
5
+ ruby: ['gemfile', 'rakefile', 'podfile'],
6
+ makefile: ['makefile', 'gnumakefile'],
7
+ dockerfile: ['dockerfile', 'containerfile'],
8
+ };
9
+ const EXTENSIONS = {
10
+ javascript: ['js', 'mjs', 'cjs', 'jsx'],
11
+ typescript: ['ts', 'tsx', 'mts', 'cts'],
12
+ json: ['json', 'jsonc', 'json5'],
13
+ python: ['py', 'pyw', 'pyi'],
14
+ go: ['go'],
15
+ rust: ['rs'],
16
+ swift: ['swift'],
17
+ java: ['java'],
18
+ kotlin: ['kt', 'kts'],
19
+ c: ['c'],
20
+ cpp: ['h', 'cc', 'cpp', 'cxx', 'hpp', 'hh'], // .h 一律按 C++
21
+ objectivec: ['m', 'mm'], // .m 一律按 Objective-C
22
+ csharp: ['cs'],
23
+ php: ['php'],
24
+ ruby: ['rb'],
25
+ lua: ['lua'],
26
+ sql: ['sql'],
27
+ r: ['r'],
28
+ perl: ['pl', 'pm'],
29
+ dart: ['dart'],
30
+ scala: ['scala'],
31
+ xml: ['html', 'htm', 'xml', 'xhtml', 'plist', 'vue'],
32
+ css: ['css'],
33
+ scss: ['scss'],
34
+ less: ['less'],
35
+ yaml: ['yml', 'yaml'],
36
+ ini: ['toml', 'ini', 'cfg'],
37
+ markdown: ['md', 'markdown', 'mdx'],
38
+ bash: ['sh', 'bash', 'zsh'],
39
+ makefile: ['mk'],
40
+ dockerfile: ['dockerfile'],
41
+ diff: ['diff', 'patch'],
42
+ graphql: ['graphql', 'gql'],
43
+ };
44
+ const BY_NAME = invert(NAMES), BY_EXTENSION = invert(EXTENSIONS);
45
+
46
+ export const languageOf = name => lookupByName(name, BY_NAME, BY_EXTENSION) ?? null;
47
+
48
+ // 给测试:表里出现的所有语言 id。
49
+ export const LANGUAGE_IDS = [...new Set([...Object.keys(NAMES), ...Object.keys(EXTENSIONS)])];
@@ -0,0 +1,8 @@
1
+ // 按文件名查表:图标表和语言表各用一份数据、同一套查找。
2
+ // 整个文件名(小写)优先,再是 special(各表自己的规则,如图标的 .env.*),最后是扩展名(小写);扩展名取最后一个点之后,点在开头的名字没有扩展名。
3
+ export const invert = table => new Map(Object.entries(table).flatMap(([id, keys]) => keys.map(key => [key, id])));
4
+
5
+ export function lookupByName(name, byName, byExtension, special = () => undefined) {
6
+ const lower = String(name).toLowerCase(), dot = lower.lastIndexOf('.');
7
+ return byName.get(lower) ?? special(lower) ?? (dot > 0 ? byExtension.get(lower.slice(dot + 1)) : undefined);
8
+ }
package/view/menu.mjs CHANGED
@@ -28,7 +28,13 @@ export function mountMenu(el, sub = null, { flyout = false } = {}) {
28
28
  return items.map(item => {
29
29
  const { label, run, checked, radio, separator, heading, submenu } = item;
30
30
  if (separator) return Object.assign(document.createElement('hr'), { className: 'menu-sep' });
31
- if (heading !== undefined) return Object.assign(document.createElement('p'), { className: 'menu-head secondary caption', textContent: heading });
31
+ if (heading !== undefined) {
32
+ // 小标题和选项走同一套布局:这一层有对勾列时,小标题前也放一个同宽的空位,文字才和选项的文字左边对齐。
33
+ const head = Object.assign(document.createElement('p'), { className: 'menu-head secondary caption' });
34
+ if (checkable) head.append(Object.assign(document.createElement('span'), { className: 'check' }));
35
+ head.append(Object.assign(document.createElement('span'), { textContent: heading }));
36
+ return head;
37
+ }
32
38
  const button = document.createElement('button'), name = document.createElement('span');
33
39
  name.textContent = label;
34
40
  if (checkable) {