@coda-console/resource-manager 0.6.0 → 0.7.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.
@@ -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) {
package/view/model.mjs CHANGED
@@ -42,7 +42,8 @@ export class Model {
42
42
  dirs = new Map(); // path → { entries, next, loaded, loading, error, token }
43
43
  expanded = new Set(); // 不变量:展开的目录,它的每一级上层也展开
44
44
  wanted = new Map(); // 恢复状态时各目录要取够的条数,第一次取用后删掉
45
- selected = null;
45
+ selected = null; // 选中的条目(高亮和键盘移动用,文件夹、不能打开的条目都可以)
46
+ opened = null; // 页内预览中的文件(两端一样);null 是在看目录
46
47
  showHidden = false;
47
48
  sort = DEFAULT_SORT; // 全局一份,由页面存进 persisted
48
49
  view = View.LIST; // 全局一份,由页面存进 persisted
@@ -88,6 +89,7 @@ export class Model {
88
89
  const paths = (saved?.expanded ?? []).filter(path => path !== '');
89
90
  this.expanded = new Set(paths.filter(path => !path.includes('/') || paths.includes(path.slice(0, path.lastIndexOf('/')))));
90
91
  this.selected = saved?.selected ?? null;
92
+ this.opened = saved?.opened ?? null;
91
93
  this.onChange();
92
94
  }
93
95
 
@@ -110,6 +112,7 @@ export class Model {
110
112
  this.scope++;
111
113
  this.#nav++;
112
114
  this.cwd = '';
115
+ this.selected = this.opened = null;
113
116
  this.#quiet = false;
114
117
  this.wanted = new Map();
115
118
  }
@@ -279,7 +282,15 @@ export class Model {
279
282
  }
280
283
  }
281
284
 
282
- select(path) { this.selected = path; this.onChange(); }
285
+ // 选中只影响高亮,不发 onChange:重画会换掉全部行节点,双击的第二下点击之后 dblclick 就丢了。页面的 selectEntry 负责切高亮和保存。返回是不是变了。
286
+ select(path) {
287
+ if (this.selected === path) return false;
288
+ this.selected = path;
289
+ return true;
290
+ }
291
+ // Mac 打开文件:选中它并切到预览。返回(closeFile)只清 opened,选中留着。
292
+ openFile(path) { this.selected = this.opened = path; this.onChange(); }
293
+ closeFile() { this.opened = null; this.onChange(); }
283
294
  setShowHidden(on) { this.showHidden = on; this.onChange(); }
284
295
  // loaded:取过不止一页的目录已加载的条数,只存条数不存内容;第一页每次都会重新取,不用存。
285
296
  snapshot() {
@@ -287,7 +298,7 @@ export class Model {
287
298
  for (const [path, dir] of this.dirs) if (dir.pages > 1 && dir.entries.length > 0) loaded[path] = dir.entries.length;
288
299
  // 还没收到这个会话就绪的 root 时,cwd 和根目录还是保存的那一份,原样存回去,不能被重建途中的一次保存冲掉。
289
300
  const root = this.#resolved ? this.#rootPath : this.#savedRoot;
290
- return { expanded: [...this.expanded], selected: this.selected, loaded, cwd: this.cwd, ...(root === null ? {} : { root }) };
301
+ return { expanded: [...this.expanded], selected: this.selected, opened: this.opened, loaded, cwd: this.cwd, ...(root === null ? {} : { root }) };
291
302
  }
292
303
  }
293
304
 
@@ -317,6 +328,8 @@ export function parseState(raw) {
317
328
  state.sessions[id] = {
318
329
  at: Number.isSafeInteger(item.at) ? item.at : 0, expanded: strings(item.expanded, 5000),
319
330
  selected: typeof item.selected === 'string' && item.selected.length <= 1024 ? item.selected : null,
331
+ // 0.6.0 的状态没有 opened:selected 只当选中,不打开预览。
332
+ opened: typeof item.opened === 'string' && item.opened.length <= 1024 ? item.opened : null,
320
333
  // 滚动位置是按当时的排序存的;旧版本没有这个字段,那时一定是默认排序。
321
334
  // 两种视图各存各的位置和当时的排序:tree 和 sort 是列表的,grid 和 gridSort 是图标的(旧版本没有后两个)。
322
335
  scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left), sort: parseSort(scroll.sort) ?? DEFAULT_SORT,
package/view/preview.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  // 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
2
2
  import { h } from './dom.mjs';
3
3
  import { formatSize } from './format.mjs';
4
+ import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
4
5
  import { icon, iconFor } from './icons.mjs';
6
+ import { languageOf } from './languages.mjs';
5
7
  import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType } from './protocol.mjs';
6
8
  import { clippedSelection, linesOf } from './selection.mjs';
7
9
 
@@ -51,9 +53,11 @@ const formatTime = ms => new Date(ms).toLocaleString('zh-CN', { hour12: false })
51
53
  export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0));
52
54
 
53
55
  // read(path, offset) → Promise<chunk 回答>,会话换了会以 stale 错误拒绝;copy(text) 复制路径。
54
- // actions:头部在「复制路径」旁额外加的按钮 [{ label, icon, run(path) }],预览不知道它们做什么。
55
- // copyInHead:false 时头部不放「复制路径」(iPhone 放在底部工具条),由页面调 copyPath()。
56
+ // actions:头部在「复制路径」旁额外加的按钮 [{ label, icon, run(path, button) }],button 是被点的按钮(菜单用它定位),预览不知道它们做什么。
57
+ // copyInHead:false 时头部不放「复制路径」(iPhone 的复制路径在 ⋯ 菜单里),由页面调 copyPath()。
56
58
  // back:给了就在头部最左边放「返回」(Mac 侧栏预览:原生工具栏项目只能在右侧);文件页和 iPhone 不传。
59
+ // open(path, scroll) 带了要恢复的位置时,返回的 Promise 在「位置用上了」时变 true(正文到了、已设好位置;读取失败不算,位置留着等重试),
60
+ // 在「位置作废」时变 false(预览关了、改看别的文件)。读取被刷新、重载或 changed 作废时位置不丢:接替它的那次读取接着带上,用上才算完。
57
61
  // selectionMenu(event, { path, text, startLine, endLine }):给了就接管正文里选中文字的右键(只有 Mac 传);预览不知道菜单里是什么。
58
62
  // 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
59
63
  export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null }) {
@@ -62,13 +66,15 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
62
66
  // 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
63
67
  const action = (label, glyph, run) => h('button', { class: glyph ? 'icon' : 'link', 'aria-label': label, title: label, onclick: run }, glyph ? icon(glyph, 18) : label);
64
68
  const copyPath = () => path !== null && copy(path);
65
- const retryButton = h('button', { class: 'link', onclick: () => load(null, true), hidden: true }, '重试');
69
+ const retryButton = h('button', { class: 'link', onclick: () => load(true), hidden: true }, '重试');
66
70
  const body = h('div', { class: 'pbody' });
67
- const extra = actions.map(({ label, icon: glyph, run }) => action(label, glyph, () => path !== null && run(path)));
71
+ const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
68
72
  el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), retryButton,
69
73
  ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), body);
70
74
 
71
75
  let path = null, token = 0, shown = null, objectUrl = null; // shown:当前显示的 { size, mtimeMs }
76
+ let carry = null; // 待恢复的位置 { scroll, settle }:open 带进来,读取真正用上或作废后才清
77
+ const settle = used => { const c = carry; carry = null; c?.settle(used); };
72
78
  let metaText = ' ', metaTitle = '', stale = null; // stale:后台刷新失败的原因,此时正文还是上次的
73
79
  // 更新失败的提示占用元信息那一行,重试按钮在头部,所以正文不会被顶动。
74
80
  const paintMeta = () => {
@@ -88,13 +94,20 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
88
94
  revoke();
89
95
  shown = { size: result.size, mtimeMs: result.mtimeMs };
90
96
  // 元信息:目录 · 行数 · 大小;根目录下的文件没有目录,非文本没有行数。修改时间放进 title。
97
+ // 高亮:认得出语言才试;超过上限不试,库或解析出错就退回纯文本,都在元信息里注明。认不出语言的不加说明。
91
98
  const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
92
99
  const lines = result.kind === ContentKind.TEXT ? `${lineCount(result.text)} 行` : '';
93
- const note = result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '';
100
+ const language = result.kind === ContentKind.TEXT ? languageOf(path.split('/').pop()) : null;
101
+ // 先判大小,超过只写「不高亮」;没超再判行长。
102
+ const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : hasLongLine(result.text) ? '行太长,不高亮' : '';
103
+ const colored = language && !skip ? highlight(result.text, language) : null;
104
+ const plain = !language ? '' : skip || (colored ? '' : '没能高亮');
105
+ const note = [result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '', plain].filter(Boolean).join(',');
94
106
  setMeta([dir, lines, formatSize(result.size), note].filter(Boolean).join(' · '), `修改于 ${formatTime(result.mtimeMs)}`);
95
107
  if (result.kind === ContentKind.TEXT) {
96
108
  const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
97
- const text = h('pre', { class: 'text selectable' }, result.text);
109
+ const text = h('pre', { class: 'text selectable' }, ...(colored ? [] : [result.text]));
110
+ if (colored) appendAll(text, colored);
98
111
  if (selectionMenu) text.addEventListener('contextmenu', event => onSelect(event, text));
99
112
  body.replaceChildren(h('div', { class: 'code' }, gutter, text));
100
113
  } else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
@@ -120,8 +133,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
120
133
  notice('读不到这个文件', error.message, { label: '重试', run: retry });
121
134
  }
122
135
 
123
- // silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置。
124
- async function load(scroll, silent) {
136
+ // silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置;有待恢复的位置时用它。
137
+ async function load(silent) {
125
138
  const mine = ++token, mark = () => mine === token;
126
139
  if (!silent) { shown = null; setMeta('读取中…'); revoke(); body.replaceChildren(); }
127
140
  try {
@@ -131,28 +144,33 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
131
144
  });
132
145
  if (!mark() || result.cancelled) return;
133
146
  if (result.same) return setStale(null);
134
- const keep = scroll ?? { top: body.scrollTop, left: body.scrollLeft };
147
+ // 刷新留在原位;整页重读(打开、重载、重试)没有要恢复的位置就明确从头开始,不靠清空正文后滚动条自己归零。
148
+ const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
135
149
  show(result);
136
150
  body.scrollTop = keep.top; body.scrollLeft = keep.left;
151
+ settle(true);
137
152
  } catch (error) {
138
- if (mark()) failure(error, silent, () => load(null, false));
153
+ if (mark()) failure(error, silent, () => load(false)); // 失败不算用上:待恢复的位置留着,重试或之后的刷新成功才用、才清
139
154
  }
140
155
  }
141
156
 
142
157
  return {
143
158
  open(next, scroll = null) {
159
+ settle(false);
144
160
  path = next;
145
161
  const base = next.split('/').pop();
146
162
  name.textContent = base;
147
163
  name.title = next;
148
164
  fileIcon.replaceChildren(icon(iconFor({ kind: EntryKind.FILE, name: base }), 22));
149
- return load(scroll, false);
165
+ const used = scroll ? new Promise(done => { carry = { scroll, settle: done }; }) : null;
166
+ const read = load(false);
167
+ return used ?? read;
150
168
  },
151
169
  copyPath,
152
- refresh() { return path === null ? undefined : load(null, true); },
170
+ refresh() { return path === null ? undefined : load(true); },
153
171
  // 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
154
- reload() { return path === null ? undefined : load(null, false); },
155
- close() { token++; path = null; shown = null; setMeta(' '); revoke(); body.replaceChildren(); },
172
+ reload() { return path === null ? undefined : load(false); },
173
+ close() { settle(false); token++; path = null; shown = null; setMeta(' '); revoke(); body.replaceChildren(); },
156
174
  scroll: () => ({ top: body.scrollTop, left: body.scrollLeft }),
157
175
  onScroll: fn => body.addEventListener('scroll', fn, { passive: true }),
158
176
  get path() { return path; },
@@ -1,7 +1,7 @@
1
1
  // 预览里选中的文字:裁到正文元素里面,算出覆盖的行。DOM 的部分只用 Range 的标准方法,行号是纯函数。
2
2
  const START_TO_START = 0, END_TO_END = 2; // Range.START_TO_START、Range.END_TO_END
3
3
 
4
- // el 是正文(一个 pre 加一个文本节点)。选区为空或和 el 不相交返回 null;
4
+ // el 是正文(一个 pre,里面是文本节点,上色后还有嵌套的 span)。选区为空或和 el 不相交返回 null;
5
5
  // 否则把选区裁到 el 里,返回 { text, start }:裁剪后的文字和它在 el 文字里的起点(UTF-16 偏移)。裁剪后为空也返回 null。
6
6
  // 选区的起点或终点落在 el 外面(跨出正文、从行号列开始拖)时,裁掉外面的部分。
7
7
  export function clippedSelection(el, selection = globalThis.getSelection?.()) {
package/view/style.css CHANGED
@@ -1,5 +1,5 @@
1
1
  /* 资源管理器的页面,颜色、字体、字号只用 App 给的 --coda-* 变量(插件视图的主题变量)。
2
- 唯一的例外是下面的 --tone-*:种类图标的色调,主题变量里没有这一组。 */
2
+ 两个例外是下面的 --tone-*(种类图标的色调)和 --hl-*(代码高亮),主题变量里没有这两组。 */
3
3
  :root {
4
4
  --hover: var(--coda-hover, var(--coda-fill, rgba(0,0,0,.05)));
5
5
  --line: var(--coda-separator, rgba(0,0,0,.1));
@@ -10,6 +10,8 @@
10
10
  --safe-bottom: env(safe-area-inset-bottom, 0px); --safe-left: env(safe-area-inset-left, 0px);
11
11
  font: var(--coda-font-size, 13px)/1.45 var(--coda-font, -apple-system, system-ui, sans-serif);
12
12
  color: var(--coda-foreground, #1d1d1f); background: transparent;
13
+ /* iOS WebKit 会自动放大文字,上色后正文是许多 span,被放大而行号列不放大,两列对不齐;整页关掉,字号只按 --coda-font-size。 */
14
+ -webkit-text-size-adjust: 100%; text-size-adjust: 100%;
13
15
  }
14
16
  /* 种类图标的色调。图标是 currentColor,.tone-* 把颜色给到 svg 上;文件夹用强调色,链接和特殊文件没有色调,跟随三级文字色。
15
17
  两种外观下,在 --coda-background 和 --coda-card 上的对比度都不低于 3:1(harness 读真实计算值检查);改色值要重新跑。 */
@@ -21,6 +23,15 @@
21
23
  --tone-gray: #a3a3a9; --tone-blue: #6aa9ec; --tone-yellow: #e3b63e; --tone-green: #63c77f; --tone-teal: #58c3dd;
22
24
  --tone-orange: #f0964f; --tone-red: #f0717a; --tone-purple: #ac87ec; --tone-pink: #ee77ac;
23
25
  }
26
+ /* 代码高亮的颜色,深浅各一套;自己定的,不照搬任何现成主题。每个 token 的最终颜色在代码区底色上不低于 4.5:1(harness 读真实计算值检查);改色值要重新跑。 */
27
+ :root {
28
+ --hl-keyword: #a2218f; --hl-string: #b82a1f; --hl-comment: #5f6b76; --hl-number: #2d3fc4; --hl-title: #0b62a0; --hl-type: #1b7280; --hl-attr: #7a5200;
29
+ --hl-meta: #8a4710; --hl-tag: #a02a5c; --hl-variable: #5a45b8; --hl-regexp: #9a3b00; --hl-addition: #1a7a2c; --hl-deletion: #c0262d; --hl-section: #0b5ca8;
30
+ }
31
+ :root.coda-dark {
32
+ --hl-keyword: #f58ac0; --hl-string: #f59a85; --hl-comment: #8f9ca8; --hl-number: #dcc46c; --hl-title: #62c0e8; --hl-type: #72d4d0; --hl-attr: #d8b46a;
33
+ --hl-meta: #f0a070; --hl-tag: #f58aa8; --hl-variable: #b3a4f5; --hl-regexp: #e6b27a; --hl-addition: #6fd185; --hl-deletion: #ff8a8f; --hl-section: #7cb8f5;
34
+ }
24
35
  .tone-accent { color: var(--coda-accent, #0a84ff); }
25
36
  .tone-gray { color: var(--tone-gray); } .tone-blue { color: var(--tone-blue); } .tone-yellow { color: var(--tone-yellow); }
26
37
  .tone-green { color: var(--tone-green); } .tone-teal { color: var(--tone-teal); } .tone-orange { color: var(--tone-orange); }
@@ -48,13 +59,12 @@ p { margin: 0; }
48
59
  .notice-icon { display: grid; place-items: center; margin-bottom: 6px; color: var(--coda-secondary, #6e6e73); }
49
60
  .notice-icon svg { display: block; color: inherit; } /* 说明区的图标不上色 */
50
61
 
51
- /* 页内工具条:iPhone 树页在顶部(返回、根目录名、⋯),文件页在底部(.bottom:返回、刷新、复制路径)。没有 coda.toolbar 的其他平台(harness)是一条文字按钮。 */
62
+ /* 页内工具条:iPhone 资源页在顶部(返回、根目录名或文件名、⋯)。没有 coda.toolbar 的其他平台(harness)是一条文字按钮。 */
52
63
  .bar { display: flex; align-items: center; gap: 4px; padding: 6px 8px; border-bottom: 1px solid var(--line); }
53
64
  .bar button { flex: none; white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; border-radius: var(--coda-radius, 6px); color: var(--coda-secondary, #6e6e73); }
54
65
  .bar button.on { color: var(--coda-accent, #0a84ff); }
55
66
  .bar svg { display: block; flex: none; }
56
67
  .bar-title { padding: 0 8px; font-weight: 600; }
57
- .bar.bottom { padding-bottom: var(--safe-bottom); border-top: 1px solid var(--line); border-bottom: 0; } /* 操作区 44 点(iPhone)之外只加安全区 */
58
68
 
59
69
  /* 树:只画可见的一段,行高固定(tree.mjs 量 .row 的高度)。
60
70
  Mac 是侧栏列表:左右缩进 8 点,行有圆角,选中用 --coda-selection。 */
@@ -93,7 +103,7 @@ p { margin: 0; }
93
103
  .tail.warn { color: var(--coda-orange, #b25000); }
94
104
 
95
105
  /* 预览:头部永远占一行名字加一行说明,加载和失败只换下面的内容。 */
96
- .preview { display: flex; flex-direction: column; overflow: hidden; padding-bottom: 0; } /* 底部的安全区归文件页的工具条 */
106
+ .preview { display: flex; flex-direction: column; overflow: hidden; padding-bottom: 0; } /* 底部的安全区归 .pbody(iPhone,见 .coda-ios .pbody) */
97
107
  .phead button, .ghead button { flex: none; white-space: nowrap; }
98
108
  .phead, .ghead { flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-bottom: 1px solid var(--line); }
99
109
  .pico, .ghico { flex: none; display: grid; place-items: center; color: var(--coda-secondary, #6e6e73); }
@@ -107,10 +117,28 @@ button.icon svg { display: block; }
107
117
  .gutter { position: sticky; left: 0; flex: none; padding: 6px 8px 6px 12px; text-align: right; background: var(--coda-background, #fff);
108
118
  color: var(--coda-tertiary, #a1a1a6); -webkit-user-select: none; user-select: none; }
109
119
  .text { flex: 1 0 auto; padding: 6px 12px 6px 4px; tab-size: 4; }
120
+ /* 高亮只设 color:不改字重、斜体、背景、字号,行高和行号对齐不变。highlight.js 的其他类不上色。 */
121
+ .code .text .hljs-keyword { color: var(--hl-keyword); }
122
+ .code .text .hljs-string { color: var(--hl-string); }
123
+ .code .text .hljs-comment { color: var(--hl-comment); }
124
+ .code .text .hljs-number, .code .text .hljs-literal { color: var(--hl-number); }
125
+ .code .text .hljs-title { color: var(--hl-title); }
126
+ .code .text .hljs-type, .code .text .hljs-built_in { color: var(--hl-type); }
127
+ .code .text .hljs-attr, .code .text .hljs-property, .code .text .hljs-attribute { color: var(--hl-attr); }
128
+ .code .text .hljs-meta { color: var(--hl-meta); }
129
+ .code .text .hljs-tag, .code .text .hljs-name, .code .text .hljs-selector-tag, .code .text .hljs-selector-class, .code .text .hljs-selector-id, .code .text .hljs-selector-pseudo, .code .text .hljs-selector-attr { color: var(--hl-tag); }
130
+ .code .text .hljs-variable { color: var(--hl-variable); }
131
+ .code .text .hljs-regexp { color: var(--hl-regexp); }
132
+ .code .text .hljs-addition { color: var(--hl-addition); }
133
+ .code .text .hljs-deletion { color: var(--hl-deletion); }
134
+ .code .text .hljs-section { color: var(--hl-section); }
110
135
  .image { display: grid; place-items: start center; padding: 12px; }
111
136
  .image img { max-width: 100%; height: auto; border-radius: var(--coda-radius, 6px); background: var(--coda-secondary-background, transparent); }
112
137
 
113
- #notice:focus { outline: none; }
138
+ #notice:focus, #preview:focus { outline: none; }
139
+ /* 键盘焦点:选中的高亮已经表示位置,点击时不画外框;只在键盘操作(:focus-visible)时给容器内边一圈细线。 */
140
+ #tree:focus, .gbody:focus { outline: none; }
141
+ #tree:focus-visible, .gbody:focus-visible { outline: 1px solid var(--coda-accent, #0a84ff); outline-offset: -2px; }
114
142
  .menu { position: fixed; z-index: 10; width: max-content; max-width: min(280px, calc(100vw - var(--safe-left) - var(--safe-right) - 8px)); padding: 4px; border: 1px solid var(--coda-outline, var(--line)); border-radius: var(--coda-radius-card, 10px);
115
143
  background: var(--coda-card, var(--coda-background, #fff));
116
144
  /* 高度有上限:内容多(长路径加五项)时在菜单里滚动,不超出安全区;位置由 menu.mjs 夹在安全区内。 */
@@ -127,7 +155,7 @@ button.icon svg { display: block; }
127
155
  .menu-path { padding: 4px 8px 6px; overflow-wrap: anywhere; }
128
156
  .menu-info { padding: 0 8px 6px; margin-top: -4px; white-space: nowrap; }
129
157
  .menu-sep { margin: 4px 6px; border: 0; border-top: 1px solid var(--line); }
130
- .menu-head { padding: 4px 8px 2px; font-weight: 600; }
158
+ .menu-head { display: flex; align-items: center; gap: 4px; padding: 4px 8px 2px; font-weight: 600; } /* 和 .menu button 同样的 flex 与 gap,空位用 .check */
131
159
  .pmeta.warn { color: var(--coda-orange, #b25000); }
132
160
 
133
161
  /* 底部的短提示:普通的是前景色(成功),.warn 是橙色(失败)。 */
@@ -201,10 +229,9 @@ button.icon svg { display: block; }
201
229
  .coda-ios .bar { gap: 0; padding: 0 8px; }
202
230
  .coda-ios .bar button { gap: 6px; padding: 0 12px; border-radius: var(--coda-radius, 10px); color: var(--coda-accent, #0a84ff); }
203
231
  .coda-ios .bar button.icon { padding: 0; justify-content: center; }
204
- .coda-ios .bar.bottom { padding: 0 8px var(--safe-bottom); }
205
- .coda-ios .bar.bottom button { flex: 1 1 0; justify-content: center; } /* 横排单行:横屏只有 390 点高 */
206
232
  .coda-ios .phead, .coda-ios .ghead { padding: 4px 12px; gap: 4px; }
207
233
  .coda-ios .phead button, .coda-ios .ghead button { padding: 0 8px; }
234
+ .coda-ios .preview:not(.info) .pbody { padding-bottom: var(--safe-bottom); } /* 资源页里没有底部工具条:最后一行不被 Home 指示条盖住 */
208
235
  .coda-ios .code { font-size: .8em; } /* 窄屏多看些:17 点下约 13.6 点 */
209
236
  .coda-ios .menu button { padding: 0 10px; }
210
237
  .coda-ios .menu button:active { background: var(--coda-selection, var(--hover)); }
package/view/tree.mjs CHANGED
@@ -3,7 +3,7 @@ import { EntryKind, SortKey } from './protocol.mjs';
3
3
  import { dateText, infoText, sizeText, subText } from './format.mjs';
4
4
  import { mountGestures } from './gestures.mjs';
5
5
  import { icon, iconFor } from './icons.mjs';
6
- import { isHidden, joinPath } from './model.mjs';
6
+ import { isHidden, joinPath, parentOf } from './model.mjs';
7
7
 
8
8
  const OVERSCAN = 8;
9
9
 
@@ -35,21 +35,44 @@ export function visibleRows(model) {
35
35
  return rows;
36
36
  }
37
37
 
38
+ // 键盘在列表里的一步(纯逻辑):action 是 up、down、left、right。返回 { select: 序号 }(选中那一行)、{ toggle: 序号 }(展开或收起那一行)或 null。
39
+ // 选中的条目不在 rows 里(被删、被藏)按没有选中算:↓ 选第一个条目,↑ 选最后一个;说明行和「再显示」跳过。
40
+ export function stepRows(rows, selected, action) {
41
+ const entries = [];
42
+ rows.forEach((row, i) => { if (row.type === 'entry') entries.push(i); });
43
+ if (entries.length === 0) return null;
44
+ const at = selected === null ? -1 : rows.findIndex(row => row.type === 'entry' && row.path === selected);
45
+ if (action === 'up' || action === 'down') {
46
+ if (at < 0) return { select: action === 'down' ? entries[0] : entries[entries.length - 1] };
47
+ const next = entries[entries.indexOf(at) + (action === 'down' ? 1 : -1)];
48
+ return next === undefined ? null : { select: next };
49
+ }
50
+ if (at < 0) return null;
51
+ const row = rows[at], folder = row.kind === EntryKind.DIR;
52
+ if (action === 'right') return folder && !row.open ? { toggle: at } : null;
53
+ if (folder && row.open) return { toggle: at }; // ←:展开的文件夹先收起
54
+ const parent = parentOf(row.path); // 已收起或是文件:选中它所在的文件夹(它一定在 rows 里,不管有没有画出来)
55
+ const up = parent === '' ? -1 : rows.findIndex(item => item.type === 'entry' && item.path === parent);
56
+ return up < 0 ? null : { select: up };
57
+ }
58
+
38
59
  // 根目录的名字:路径的最后一段,分区标题和 iPhone 的页内工具条共用。
39
60
  export const rootName = path => path.split('/').filter(Boolean).pop() ?? path;
40
61
 
41
62
  export const TITLES = { [EntryKind.LINK]: '指向工作目录外的链接,不能打开', [EntryKind.OTHER]: '不能打开的文件' };
42
63
 
43
- // handlers: { open(path), toggle(path), more(path), retry(path), menu(event, row) }
64
+ // handlers: { open(path), toggle(path), more(path), retry(path), menu(event, row), select(path | null) };select 是 Mac 单击选中,不给就是 iPhone 的轻点打开
44
65
  // menu 收到整行(路径、种类、大小、修改时间)。
45
66
  // draggable:触屏上拖行没有用处,还会抢滚动,关掉。now:当前时间,日期的相对格式用,测试可注入。
46
67
  // longPress:触屏上按住一行打开 handlers.menu(Mac 用右键)。不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
47
- export function mountTree(el, model, handlers, { draggable = true, longPress = false, now = Date.now } = {}) {
68
+ // keyboard:滚动容器可以获得焦点,键盘才接得上(Mac)。
69
+ export function mountTree(el, model, handlers, { draggable = true, longPress = false, keyboard = false, now = Date.now } = {}) {
48
70
  const title = document.createElement('div'), spacer = document.createElement('div'), win = document.createElement('div');
49
71
  title.className = 'section truncate'; spacer.className = 'spacer'; win.className = 'win';
50
72
  title.hidden = true;
51
73
  spacer.append(win);
52
74
  el.replaceChildren(title, spacer);
75
+ if (keyboard) el.tabIndex = 0;
53
76
  let rows = [], rowH = 24;
54
77
 
55
78
  // 探针放在 spacer 里:量到的是行在真实结构里的高度。
@@ -133,19 +156,32 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
133
156
  return node;
134
157
  }
135
158
 
159
+ // 点击(iPhone)、双击、⌘↓ 和右键「打开」共用这一份:文件夹展开或收起,文件打开,说明行执行它的动作。
160
+ const activate = row => {
161
+ if (row.type === 'more') return handlers.more(row.path);
162
+ if (row.type === 'status') return row.retry ? handlers.retry(row.path) : undefined;
163
+ if (row.kind === EntryKind.DIR) handlers.toggle(row.path);
164
+ else if (row.kind === EntryKind.FILE) handlers.open(row.path);
165
+ };
136
166
  const gestures = mountGestures(el, {
137
167
  hit: event => rows[event.target.closest?.('.row')?.dataset.i],
138
168
  pressable: row => row.type === 'entry',
139
- activate: row => {
140
- if (row.type === 'more') return handlers.more(row.path);
141
- if (row.type === 'status') return row.retry ? handlers.retry(row.path) : undefined;
142
- if (row.kind === EntryKind.DIR) handlers.toggle(row.path);
143
- else if (row.kind === EntryKind.FILE) handlers.open(row.path);
144
- },
169
+ activate,
170
+ select: handlers.select && (row => handlers.select(row ? row.path : null)),
171
+ direct: (event, row) => row.kind === EntryKind.DIR && !!event.target.closest?.('.chev'), // 展开箭头:展开或收起,选中不变
145
172
  menu: (event, row) => handlers.menu(event, row),
146
173
  dragText: row => row.path,
147
174
  longPress,
148
175
  });
176
+ // 选中变了只在现有节点上切 .sel,不重建:双击的 dblclick 要落在还在容器里的节点上。
177
+ const mark = () => { for (const node of win.children) node.classList.toggle('sel', rows[node.dataset.i]?.path === model.selected && rows[node.dataset.i]?.type === 'entry'); };
178
+ // 滚到这一行能看见,只滚最少的距离;按行号算位置,不找节点(没画出来的行也行)。
179
+ const reveal = index => {
180
+ const top = (spacer.offsetTop || 0) + index * rowH;
181
+ if (top < el.scrollTop) el.scrollTop = top;
182
+ else if (top + rowH > el.scrollTop + el.clientHeight) el.scrollTop = top + rowH - el.clientHeight;
183
+ paint();
184
+ };
149
185
  el.addEventListener('scroll', paint, { passive: true });
150
186
  new ResizeObserver(paint).observe(el);
151
187
 
@@ -154,6 +190,23 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
154
190
  remeasure() { measure(); this.render(); },
155
191
  scroll: () => el.scrollTop,
156
192
  scrollTo(top) { el.scrollTop = top; },
193
+ select: mark,
194
+ activate,
195
+ focus() { el.focus(); },
196
+ onKey(fn) { el.addEventListener('keydown', fn); },
197
+ // 键盘一步:选中移动并滚到能看见,→ ← 展开收起。
198
+ key(action) {
199
+ const step = stepRows(rows, model.selected, action);
200
+ if (!step) return;
201
+ if (step.toggle !== undefined) return handlers.toggle(rows[step.toggle].path);
202
+ handlers.select(rows[step.select].path);
203
+ reveal(step.select);
204
+ },
205
+ // ⌘↓:和双击同一个动作;没有选中或选中的不在了什么都不做。
206
+ openSelected() {
207
+ const row = model.selected === null ? undefined : rows.find(item => item.type === 'entry' && item.path === model.selected);
208
+ if (row) activate(row);
209
+ },
157
210
  // 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。
158
211
  reset() { gestures.reset(); },
159
212
  };