@coda-console/resource-manager 0.3.0 → 0.4.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
@@ -10,9 +10,11 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
10
10
  - 按需展开目录,超大目录分页显示。
11
11
  - 文本预览(带行号,可跨行选中复制,最多读 1 MiB)和图片预览(PNG、JPEG、GIF、WebP、SVG,最多 8 MiB)。
12
12
  - Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
13
+ - 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
14
+ - 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「排序」一组里选,当前项有对勾。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
13
15
  - 切换会话时换成新会话的内容,切回来恢复展开状态和滚动位置。
14
- - Mac:右键复制相对或绝对路径,或把文件拖到输入框;预览可以开到独立窗口;工具栏只有一个「更多」按钮,按下弹出菜单(刷新、显示隐藏文件),侧栏预览头部最左边的「返回」回到目录树。
15
- - iPhone:长按复制路径;目录树页右上角「⋯」里有刷新和显示隐藏文件;文件页底部工具条有刷新和「复制路径」。
16
+ - Mac:右键复制相对或绝对路径,或把文件拖到输入框;预览可以开到独立窗口;工具栏只有一个「更多」按钮,按下弹出菜单(刷新、显示隐藏文件、排序),侧栏预览头部最左边的「返回」回到目录树。
17
+ - iPhone:长按复制路径;目录树页右上角「⋯」里有刷新、显示隐藏文件和排序;文件页底部工具条有刷新和「复制路径」。
16
18
  - 默认隐藏 `.git`、`.DS_Store`,Mac 在工具栏的「更多」菜单里、iPhone 在目录树页右上角的「⋯」里可切换显示全部。
17
19
 
18
20
  只能读这个会话的工作目录。指向工作目录之外的符号链接只显示,不能打开。
@@ -63,6 +65,8 @@ npx --yes github:coda-console/coda-plugins#<提交> . --manifest
63
65
 
64
66
  工作流用 npm 可信发布,不需要令牌。只有手动运行才会发布,合并到 `main` 不会自动发布。
65
67
 
68
+ 发布后 npm 可能要约 10 分钟才公开,工作流最多等 15 分钟确认。超时会显示失败,但摘要写着「发布已接受,公开确认超时,不要重发」:包已经发出,不要重跑工作流,先到 npm 上查这个版本。
69
+
66
70
  首次发布要先有包,可信发布才能配置:在本机 `npm login` 后手动运行 `npm publish --access public`,再到 npm 上 `@coda-console/resource-manager` 的设置里配置可信发布,仓库填 `sealiu1997/coda_plugins_resource_manager`,流程文件填 `publish.yml`,并勾选允许 `npm publish`(Allow npm publish)。新配置默认只允许 `npm stage publish`,不勾选的话工作流的发布步骤会被拒绝。之后就按上面的步骤走。
67
71
 
68
72
  ## 许可
package/lib/content.mjs CHANGED
@@ -1,10 +1,14 @@
1
1
  // 分块读文件并判断类型。页面一块一块要,模块不记状态。
2
+ import { constants } from 'node:fs';
2
3
  import { open } from 'node:fs/promises';
3
4
  import {
4
5
  CHUNK_BYTES, ContentKind, ErrorCode, IMAGE_LIMIT, SNIFF_BYTES, TEXT_LIMIT, fail, imageType,
5
6
  } from '../view/protocol.mjs';
6
7
  import { fromFsError, parseRelative, resolveInRoot } from './paths.mjs';
7
8
 
9
+ // 只作用于最后一级:校验之后目标被换成链接,打开会被拒绝而不是跟过去。平台没有这个常量就退回 0。
10
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
11
+
8
12
  async function readAt(handle, position, length) {
9
13
  const buffer = Buffer.allocUnsafe(length);
10
14
  const { bytesRead } = length ? await handle.read(buffer, 0, length, position) : { bytesRead: 0 };
@@ -13,11 +17,20 @@ async function readAt(handle, position, length) {
13
17
 
14
18
  // 返回 { data, offset, size, mtimeMs, kind, eof }。文本最多给前 TEXT_LIMIT 字节,
15
19
  // 超过限制的图片和二进制文件不给内容(页面看 size 和 kind 说明)。
16
- export async function readChunk(root, path, offset) {
20
+ // deps.open 只给测试换,用来在校验和打开之间插入时机。
21
+ export async function readChunk(root, path, offset, deps = { open }) {
17
22
  if (!Number.isSafeInteger(offset) || offset < 0) throw fail(ErrorCode.INVALID_OFFSET, '偏移无效');
18
23
  const real = await resolveInRoot(root, path);
19
24
  let handle;
20
- try { handle = await open(real, 'r'); } catch (error) { throw fromFsError(error); }
25
+ try {
26
+ handle = await deps.open(real, constants.O_RDONLY | NOFOLLOW);
27
+ } catch (error) {
28
+ // 被 O_NOFOLLOW 拒绝(macOS、Linux 是 ELOOP,BSD 是 EMLINK)说明校验后被换成了链接,按越界处理。
29
+ if (NOFOLLOW && (error?.code === 'ELOOP' || error?.code === 'EMLINK')) {
30
+ throw fail(ErrorCode.OUTSIDE_ROOT, '链接指向工作目录之外');
31
+ }
32
+ throw fromFsError(error);
33
+ }
21
34
  try {
22
35
  const info = await handle.stat();
23
36
  if (!info.isFile()) throw fail(ErrorCode.NOT_FILE, '不是文件');
@@ -0,0 +1,52 @@
1
+ // 日期、大小排序的快照:第一页读全部条目并排好序,之后的页只从这里取,不再碰文件系统。
2
+ // 快照属于一个视图,由 main.mjs 建一份传给 lib/tree.mjs;这里只管存放、淘汰和释放,不碰 fs。
3
+ export const MAX_SNAPSHOTS = 8;
4
+ export const MAX_SNAPSHOT_ENTRIES = 100_000;
5
+ export const SNAPSHOT_IDLE_MS = 60_000;
6
+
7
+ export function createSnapshots({
8
+ now = Date.now, maxCount = MAX_SNAPSHOTS, maxEntries = MAX_SNAPSHOT_ENTRIES, idleMs = SNAPSHOT_IDLE_MS,
9
+ } = {}) {
10
+ const items = new Map(); // id → 快照;Map 的顺序就是最近使用的顺序,最前面的最久没用
11
+ let nextId = 1, total = 0;
12
+
13
+ const drop = id => {
14
+ const item = items.get(id);
15
+ if (item) { total -= item.entries.length; items.delete(id); }
16
+ };
17
+ // 不起定时器:每次访问任何快照时顺便清掉闲置的。
18
+ const sweep = () => {
19
+ const time = now();
20
+ for (const [id, item] of items) if (time - item.used > idleMs) drop(id);
21
+ };
22
+
23
+ return {
24
+ get size() { return items.size; },
25
+ get total() { return total; },
26
+
27
+ // 取快照并记为刚用过;已被淘汰、释放或闲置过期的返回 null。
28
+ get(id) {
29
+ sweep();
30
+ const item = items.get(id);
31
+ if (!item) return null;
32
+ item.used = now();
33
+ items.delete(id);
34
+ items.set(id, item);
35
+ return item;
36
+ },
37
+
38
+ // 存一份,替换同身份的旧快照,超出数量或总条目时淘汰最久没用的。id 递增、不复用,旧游标不会指到新快照上。
39
+ put({ identity, root, path, entries }) {
40
+ sweep();
41
+ for (const [id, item] of items) if (item.identity === identity) drop(id);
42
+ while (items.size > 0 && (items.size >= maxCount || total + entries.length > maxEntries)) drop(items.keys().next().value);
43
+ const item = { id: nextId++, identity, root, path, entries, used: now() };
44
+ items.set(item.id, item);
45
+ total += entries.length;
46
+ return item;
47
+ },
48
+
49
+ release: drop,
50
+ clear() { items.clear(); total = 0; },
51
+ };
52
+ }
package/lib/tree.mjs CHANGED
@@ -1,74 +1,263 @@
1
- // 读目录:先目录后文件,按名字不分大小写排序,按序列化字节数分页。模块回答全部条目,隐藏规则在页面。
2
- import { readdir, realpath, stat } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { EntryKind, ENVELOPE_BYTES, ErrorCode, PAGE_BYTES, fail } from '../view/protocol.mjs';
5
- import { fromFsError, isInside, isSafeName, resolveInRoot } from './paths.mjs';
1
+ // 读目录:文件夹在前,按排序键排序,按序列化字节数分页。模块回答全部条目,隐藏规则在页面。
2
+ // 名称、种类排序每页重读目录,游标是上一条的排序键,只读当前页条目的元数据;
3
+ // 日期、大小排序第一页读全部条目的元数据并建快照,之后的页从快照取,不再碰文件系统(设计见 docs/design/phase-3.md 第 12.3 节)。
4
+ import { lstat, readdir, realpath, stat } from 'node:fs/promises';
5
+ import { extname, join } from 'node:path';
6
+ import {
7
+ DEFAULT_SORT, EntryKind, ENVELOPE_BYTES, ErrorCode, PAGE_BYTES, SortKey, fail, parseSort,
8
+ } from '../view/protocol.mjs';
9
+ import { fromFsError, isInside, isSafeName, parseRelative, resolveInRoot } from './paths.mjs';
10
+ import { createSnapshots } from './snapshots.mjs';
6
11
 
7
12
  const MAX_ENTRIES = 100_000;
8
- const LINK_CONCURRENCY = 8;
13
+ // 日期、大小排序要读全部条目的元数据,超过这个数的目录退回按名称排。
14
+ export const SORT_STAT_LIMIT = 20_000;
15
+ const CONCURRENCY = 8;
16
+ // 一条的元数据最多占的字节(两个都是 16 位整数),用来在读元数据之前保守地决定一页放几条。
17
+ const META_BYTES = Buffer.byteLength(',"size":9007199254740991,"mtimeMs":9007199254740991');
18
+
19
+ // 并发上限:每个视图一个,classify 和读元数据都经它,所以并行多个目录也不会超过 limit 个同时在读。
20
+ export function createLimiter(limit = CONCURRENCY) {
21
+ let active = 0;
22
+ const waiting = [];
23
+ return async fn => {
24
+ if (active < limit) active++; else await new Promise(resolve => waiting.push(resolve));
25
+ try { return await fn(); } finally {
26
+ const next = waiting.shift();
27
+ if (next) next(); else active--; // 有人等就把坑位直接交给它
28
+ }
29
+ };
30
+ }
31
+
32
+ const realFs = { lstat, readdir, realpath, stat };
33
+
34
+ // 一个视图的读取状态:文件系统、共用的并发上限、快照、进行中的第一页读取。
35
+ // refresh、changed 后 detach:进行中的读取不再被新请求共用;换会话、根目录变化、视图关闭后 clear。
36
+ // latest 记着每个身份最新发起的读取:只有它能存快照,旧的读取晚到也不会顶掉新快照。detach 不动它,clear 才清(清了之后谁都不能存)。
37
+ export function createListing({ fs = realFs, limit = CONCURRENCY, snapshots = createSnapshots() } = {}) {
38
+ return {
39
+ fs, snapshots, run: createLimiter(limit), reads: new Map(), latest: new Map(), started: 0,
40
+ detach() { this.reads.clear(); },
41
+ clear() { this.reads.clear(); this.latest.clear(); this.snapshots.clear(); },
42
+ };
43
+ }
44
+
45
+ // ---- 排序 ----
9
46
 
10
47
  const rank = entry => (entry.kind === EntryKind.DIR ? 0 : 1);
11
- function compare(a, b) {
12
- if (rank(a) !== rank(b)) return rank(a) - rank(b);
13
- const x = a.name.toLowerCase(), y = b.name.toLowerCase();
14
- if (x !== y) return x < y ? -1 : 1;
15
- return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
48
+ const extOf = name => extname(name).slice(1).toLowerCase();
49
+
50
+ // 排序键;undefined 是缺元数据(或文件夹没有大小),排在组内最后。
51
+ function keyOf(entry, key) {
52
+ switch (key) {
53
+ case SortKey.NAME: return entry.name.toLowerCase();
54
+ case SortKey.KIND: return entry.kind === EntryKind.DIR ? '' : extOf(entry.name);
55
+ case SortKey.DATE: return entry.mtimeMs;
56
+ default: return entry.kind === EntryKind.DIR ? undefined : entry.size;
57
+ }
58
+ }
59
+
60
+ // 每种排序的方向,只在这里定义:名称、种类升序,日期、大小降序(最新、最大在前)。
61
+ const DESCENDING = new Set([SortKey.DATE, SortKey.SIZE]);
62
+
63
+ // 全序:文件夹在前(不随方向反向);键按该排序的方向,缺的不管方向都在最后;平手按名字(不分大小写)升序,最后按原名。
64
+ function comparer(key) {
65
+ const desc = DESCENDING.has(key);
66
+ return (a, b) => {
67
+ if (rank(a) !== rank(b)) return rank(a) - rank(b);
68
+ const x = keyOf(a, key), y = keyOf(b, key);
69
+ if (x !== y) {
70
+ if (x === undefined) return 1;
71
+ if (y === undefined) return -1;
72
+ return (x < y ? -1 : 1) * (desc ? -1 : 1);
73
+ }
74
+ const p = a.name.toLowerCase(), q = b.name.toLowerCase();
75
+ if (p !== q) return p < q ? -1 : 1;
76
+ return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
77
+ };
16
78
  }
17
79
 
18
- const encodeCursor = entry => Buffer.from(JSON.stringify([rank(entry), entry.name])).toString('base64url');
80
+ // ---- 游标:名称、种类用排序键,日期、大小用快照编号加下标。解不开的一律当作过期。 ----
81
+
82
+ const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
83
+ const encodeKeyCursor = (sort, entry) => encode(['k', sort, rank(entry), entry.name]);
84
+ const encodeSnapshotCursor = (id, index) => encode(['s', id, index]);
85
+
19
86
  function decodeCursor(cursor) {
20
87
  try {
21
- const [group, name] = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
22
- if ((group === 0 || group === 1) && typeof name === 'string') return { kind: group === 0 ? EntryKind.DIR : EntryKind.FILE, name };
88
+ const value = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
89
+ if (Array.isArray(value)) {
90
+ if (value[0] === 's' && Number.isSafeInteger(value[1]) && Number.isSafeInteger(value[2]) && value[2] > 0) {
91
+ return { snapshot: value[1], index: value[2] };
92
+ }
93
+ const [tag, sort, group, name] = value;
94
+ if (value.length === 4 && tag === 'k' && (sort === SortKey.NAME || sort === SortKey.KIND)
95
+ && (group === 0 || group === 1) && typeof name === 'string') {
96
+ return { sort, after: { name, kind: group === 0 ? EntryKind.DIR : EntryKind.FILE } };
97
+ }
98
+ }
23
99
  } catch { /* 下面统一报错 */ }
24
- throw fail(ErrorCode.INVALID_CURSOR, '游标无效');
100
+ throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
25
101
  }
26
102
 
27
- async function mapLimit(items, limit, fn) {
28
- const results = new Array(items.length);
29
- let next = 0;
30
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
31
- while (next < items.length) { const index = next++; results[index] = await fn(items[index]); }
32
- }));
33
- return results;
103
+ // ---- 读条目 ----
104
+
105
+ // 只有符号链接要额外解析:目标在根目录内按目标显示(目标的 lstat 带回去给读元数据用,不解析第二次),在外或已失效显示为 link。
106
+ // 校验之后用 lstat 读目标,不跟随链接:realpath 之后目标被换成别的链接,读到的就是符号链接,按 link 处理,不带外面的元数据。
107
+ async function classifyLink(fs, root, dir, name) {
108
+ try {
109
+ const real = await fs.realpath(join(dir, name));
110
+ if (!isInside(root, real)) return { name, kind: EntryKind.LINK };
111
+ const info = await fs.lstat(real);
112
+ if (info.isSymbolicLink()) return { name, kind: EntryKind.LINK };
113
+ const kind = info.isDirectory() ? EntryKind.DIR : info.isFile() ? EntryKind.FILE : EntryKind.OTHER;
114
+ return { name, kind, link: true, info };
115
+ } catch { return { name, kind: EntryKind.LINK }; }
34
116
  }
35
117
 
36
- // 只有符号链接要额外解析:目标在根目录内按目标显示,在外或已失效显示为 link。
37
- async function classify(root, dir, dirent) {
118
+ function classifyPlain(dirent) {
38
119
  const { name } = dirent;
39
120
  if (!isSafeName(name)) return { name, kind: EntryKind.OTHER };
40
121
  if (dirent.isDirectory()) return { name, kind: EntryKind.DIR };
41
122
  if (dirent.isFile()) return { name, kind: EntryKind.FILE };
42
- if (!dirent.isSymbolicLink()) return { name, kind: EntryKind.OTHER };
123
+ return { name, kind: EntryKind.OTHER };
124
+ }
125
+
126
+ const needsResolve = dirent => dirent.isSymbolicLink() && isSafeName(dirent.name);
127
+ // 不是链接的不碰文件系统,不占并发坑位。
128
+ const classify = (listing, root, dir, dirent) => (needsResolve(dirent)
129
+ ? listing.run(() => classifyLink(listing.fs, root, dir, dirent.name))
130
+ : classifyPlain(dirent));
131
+
132
+ // 读失败(刚被删、没权限)不算错误,这个条目不带字段。普通条目用 lstat,不跟随链接:
133
+ // 条目在 readdir 之后被换成指向外面的链接,lstat 读到的也只是链接自己,类型对不上就不带字段。
134
+ // link: true 的用 classify 校验时拿到的目标 lstat。link、other 不读。size、mtimeMs 取整后只有这一份值。
135
+ async function addMeta(listing, dir, item) {
136
+ if (item.kind !== EntryKind.DIR && item.kind !== EntryKind.FILE) return;
43
137
  try {
44
- const real = await realpath(join(dir, name));
45
- if (!isInside(root, real)) return { name, kind: EntryKind.LINK };
46
- const info = await stat(real);
47
- const kind = info.isDirectory() ? EntryKind.DIR : info.isFile() ? EntryKind.FILE : EntryKind.OTHER;
48
- return { name, kind, link: true };
49
- } catch { return { name, kind: EntryKind.LINK }; }
138
+ const info = item.link ? item.info : await listing.fs.lstat(join(dir, item.name));
139
+ const isDir = info.isDirectory();
140
+ if (isDir !== (item.kind === EntryKind.DIR) || (!isDir && !info.isFile())) return;
141
+ const mtimeMs = Math.floor(info.mtimeMs), size = Math.floor(info.size);
142
+ if (Number.isFinite(mtimeMs)) item.mtimeMs = mtimeMs;
143
+ if (!isDir && Number.isFinite(size)) item.size = size;
144
+ } catch { /* 不带字段 */ }
50
145
  }
51
146
 
52
- // 游标是上一页最后一条的排序键,所以每页都重新读目录;条目增减不会造成重复,也不会漏掉游标之后的。
53
- export async function listDirectory(root, path, cursor, { maxEntries = MAX_ENTRIES, pageBytes = PAGE_BYTES } = {}) {
54
- const dir = await resolveInRoot(root, path);
55
- let dirents;
56
- try { dirents = await readdir(dir, { withFileTypes: true }); } catch (error) { throw fromFsError(error); }
57
- if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
58
- const entries = await mapLimit(dirents, LINK_CONCURRENCY, dirent => classify(root, dir, dirent));
59
- entries.sort(compare);
147
+ function toEntry({ name, kind, link, size, mtimeMs }) {
148
+ const entry = { name, kind };
149
+ if (link) entry.link = true;
150
+ if (size !== undefined) entry.size = size;
151
+ if (mtimeMs !== undefined) entry.mtimeMs = mtimeMs;
152
+ return entry;
153
+ }
60
154
 
61
- const after = cursor == null ? null : decodeCursor(cursor);
62
- let index = 0;
63
- if (after) while (index < entries.length && compare(entries[index], after) <= 0) index++;
155
+ const entryBytes = entry => Buffer.byteLength(JSON.stringify(entry)) + 1;
156
+
157
+ // 从 start 起取一页,至少一条;返回下一页的下标。
158
+ function cut(entries, start, pageBytes) {
159
+ let end = start, used = 0;
160
+ while (end < entries.length) {
161
+ const size = entryBytes(entries[end]);
162
+ if (end > start && used + size > pageBytes - ENVELOPE_BYTES) break;
163
+ used += size;
164
+ end++;
165
+ }
166
+ return { entries: entries.slice(start, end), end };
167
+ }
64
168
 
65
- const page = [];
169
+ async function readDirents(listing, dir) {
170
+ try { return await listing.fs.readdir(dir, { withFileTypes: true }); } catch (error) { throw fromFsError(error); }
171
+ }
172
+
173
+ // 名称、种类(和退回名称的日期、大小):读目录、classify 全部,排序,找到游标之后,只读这一页的元数据。
174
+ // 元数据的字节数在读之前不知道,所以按最大可能的字节数决定放几条,一页不会超。
175
+ async function pageByKey(listing, root, dir, dirents, sort, after, pageBytes) {
176
+ const items = await Promise.all(dirents.map(dirent => classify(listing, root, dir, dirent)));
177
+ const compare = comparer(sort);
178
+ items.sort(compare);
179
+ let index = 0;
180
+ if (after) while (index < items.length && compare(items[index], after) <= 0) index++;
181
+ const picked = [];
66
182
  let used = 0;
67
- while (index < entries.length) {
68
- const size = Buffer.byteLength(JSON.stringify(entries[index])) + 1;
69
- if (page.length && used + size > pageBytes - ENVELOPE_BYTES) break;
183
+ while (index < items.length) {
184
+ const size = entryBytes(toEntry(items[index])) + META_BYTES;
185
+ if (picked.length && used + size > pageBytes - ENVELOPE_BYTES) break;
70
186
  used += size;
71
- page.push(entries[index++]);
187
+ picked.push(items[index++]);
72
188
  }
73
- return { entries: page, nextCursor: index < entries.length ? encodeCursor(page[page.length - 1]) : null };
189
+ await Promise.all(picked.map(item => listing.run(() => addMeta(listing, dir, item))));
190
+ return { entries: picked.map(toEntry), nextCursor: index < items.length ? encodeKeyCursor(sort, picked[picked.length - 1]) : null };
191
+ }
192
+
193
+ // 日期、大小的第一页:读全部条目的元数据,排序,存快照。一页放得下就不存。
194
+ // 读完核对代次和根路径:对不上说明读的时候会话或根目录换了,不存快照也不回答内容。
195
+ // isLatest:这次读取是不是同身份最新发起的;不是的照常回答,但不存快照(回答里的游标指向编号 0,永远查不到,页面丢弃这份回答)。
196
+ async function firstSnapshotPage(listing, root, rel, path, sort, { pageBytes, maxEntries, statLimit, valid, isLatest }) {
197
+ const dir = await resolveInRoot(root, path);
198
+ const dirents = await readDirents(listing, dir);
199
+ if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
200
+ if (dirents.length > statLimit) {
201
+ return { ...await pageByKey(listing, root, dir, dirents, DEFAULT_SORT, null, pageBytes), sortFallback: true };
202
+ }
203
+ const items = await Promise.all(dirents.map(dirent => listing.run(async () => {
204
+ // 已经占着坑位,直接解析链接;再经 run 会等自己占的坑位。
205
+ const item = needsResolve(dirent) ? await classifyLink(listing.fs, root, dir, dirent.name) : classifyPlain(dirent);
206
+ await addMeta(listing, dir, item);
207
+ return item;
208
+ })));
209
+ const entries = items.map(toEntry).sort(comparer(sort));
210
+ if (!valid()) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
211
+ const page = cut(entries, 0, pageBytes);
212
+ if (page.end >= entries.length) return { entries, nextCursor: null };
213
+ if (!isLatest()) return { entries: page.entries, nextCursor: encodeSnapshotCursor(0, page.end) };
214
+ const snapshot = listing.snapshots.put({ identity: JSON.stringify([root, rel, sort]), root, path: rel, entries });
215
+ return { entries: page.entries, nextCursor: encodeSnapshotCursor(snapshot.id, page.end) };
216
+ }
217
+
218
+ function pageOfSnapshot(listing, root, rel, { snapshot: id, index }, pageBytes) {
219
+ const snapshot = listing.snapshots.get(id);
220
+ if (!snapshot || snapshot.root !== root || snapshot.path !== rel || index >= snapshot.entries.length) {
221
+ throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
222
+ }
223
+ const page = cut(snapshot.entries, index, pageBytes);
224
+ if (page.end < snapshot.entries.length) return { entries: page.entries, nextCursor: encodeSnapshotCursor(id, page.end) };
225
+ listing.snapshots.release(id);
226
+ return { entries: page.entries, nextCursor: null };
227
+ }
228
+
229
+ // options:sort(只对第一页有效,有游标时只认游标里的)、listing(视图共用的读取状态)、valid(回答前是否仍然有效,
230
+ // 由主模块按代次和根路径判断)、maxEntries、pageBytes、statLimit(测试可调)。
231
+ export async function listDirectory(root, path, cursor, options = {}) {
232
+ const {
233
+ listing = createListing(), maxEntries = MAX_ENTRIES, pageBytes = PAGE_BYTES, statLimit = SORT_STAT_LIMIT, valid = () => true,
234
+ } = options;
235
+ const requested = options.sort == null ? DEFAULT_SORT : parseSort(options.sort);
236
+ if (!requested) throw fail(ErrorCode.INVALID_SORT, '排序无效');
237
+ const rel = parseRelative(path).join('/');
238
+ const at = cursor == null ? null : decodeCursor(cursor);
239
+ if (at?.snapshot !== undefined) return pageOfSnapshot(listing, root, rel, at, pageBytes);
240
+
241
+ if (!at && (requested === SortKey.DATE || requested === SortKey.SIZE)) {
242
+ // 同身份的第一页并发时共用同一次读取。
243
+ const identity = JSON.stringify([root, rel, requested]);
244
+ let read = listing.reads.get(identity);
245
+ if (!read) {
246
+ const order = ++listing.started;
247
+ listing.latest.set(identity, order);
248
+ const isLatest = () => listing.latest.get(identity) === order;
249
+ read = firstSnapshotPage(listing, root, rel, path, requested, { pageBytes, maxEntries, statLimit, valid, isLatest })
250
+ .finally(() => {
251
+ if (listing.reads.get(identity) === read) listing.reads.delete(identity);
252
+ if (isLatest()) listing.latest.delete(identity);
253
+ });
254
+ listing.reads.set(identity, read);
255
+ }
256
+ return read;
257
+ }
258
+
259
+ const dir = await resolveInRoot(root, path);
260
+ const dirents = await readDirents(listing, dir);
261
+ if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
262
+ return pageByKey(listing, root, dir, dirents, at ? at.sort : requested, at?.after ?? null, pageBytes);
74
263
  }
package/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // 资源管理器的模块:跟踪侧栏的会话、代次和根目录,把页面的请求交给 lib/*,把变化推给页面。
2
2
  // 协议见 docs/design/phase-1.md 第 6 节,消息格式见 view/protocol.mjs。
3
- import { listDirectory } from './lib/tree.mjs';
3
+ import { createListing, listDirectory } from './lib/tree.mjs';
4
4
  import { readChunk } from './lib/content.mjs';
5
5
  import { NO_ROOT, queryRoot, sameRoot } from './lib/root.mjs';
6
6
  import {
@@ -17,19 +17,21 @@ const sessionOfFile = context => {
17
17
  return typeof session === 'string' && session !== '' ? session : null;
18
18
  };
19
19
 
20
- export function activate(coda) {
21
- coda.views.register('files', { open: view => serve(coda, view, sessionOfTree) });
22
- coda.views.register('file', { open: view => serve(coda, view, sessionOfFile) });
20
+ // options.makeListing 只给测试用:换成带假文件系统的读取状态,运行时不传。
21
+ export function activate(coda, { makeListing = createListing } = {}) {
22
+ coda.views.register('files', { open: view => serve(coda, view, sessionOfTree, makeListing) });
23
+ coda.views.register('file', { open: view => serve(coda, view, sessionOfFile, makeListing) });
23
24
  }
24
25
 
25
26
  const validRequestId = id => (typeof id === 'string' && id.length <= REQUEST_ID_MAX) || Number.isSafeInteger(id);
26
27
  const errorOf = error => (error?.protocol ? { code: error.code, message: error.message } : { code: ErrorCode.IO, message: '读取失败' });
27
28
 
28
- function serve(coda, view, sessionOf) {
29
+ function serve(coda, view, sessionOf, makeListing) {
29
30
  // 代次:每换一次会话加 1,所有异步出口回来后都要核对。
30
31
  const s = {
31
32
  session: sessionOf(view.context), generation: 1, root: NO_ROOT, sent: null,
32
33
  hello: false, closed: false, rootSeq: 0, poll: null,
34
+ listing: makeListing(), // 这个视图共用的并发上限和快照;视图关闭、换会话、根目录变化时丢弃
33
35
  };
34
36
  const turns = new Map();
35
37
  const stale = generation => s.closed || generation !== s.generation;
@@ -58,7 +60,10 @@ function serve(coda, view, sessionOf) {
58
60
  let next = null;
59
61
  try { next = await queryRoot(coda, s.session); } catch { /* 保留上一次 */ }
60
62
  if (stale(generation) || seq !== s.rootSeq) return;
61
- if (next) s.root = next;
63
+ if (next) {
64
+ if (next.path !== s.root.path) s.listing.clear();
65
+ s.root = next;
66
+ }
62
67
  syncPoll();
63
68
  if (s.hello && !sameRoot(s.sent, s.root)) postRoot();
64
69
  }
@@ -81,6 +86,7 @@ function serve(coda, view, sessionOf) {
81
86
  stopPoll();
82
87
  s.session = session ?? null;
83
88
  s.generation++;
89
+ s.listing.clear();
84
90
  s.root = NO_ROOT;
85
91
  s.sent = null;
86
92
  if (s.hello) postSession();
@@ -93,9 +99,13 @@ function serve(coda, view, sessionOf) {
93
99
  const reply = type === Type.LIST ? Type.LISTED : Type.CHUNK;
94
100
  try {
95
101
  if (s.root.state !== RootState.READY) throw fail(ErrorCode.NO_ROOT, '没有可浏览的工作目录');
102
+ const root = s.root.path;
103
+ // 读的途中根目录换了(同一会话从 A 换到 B),回答不能带 A 的内容。
104
+ const valid = () => !stale(generation) && s.root.state === RootState.READY && s.root.path === root;
96
105
  const body = type === Type.LIST
97
- ? await listDirectory(s.root.path, message.path, message.cursor)
98
- : await readChunk(s.root.path, message.path, message.offset);
106
+ ? await listDirectory(root, message.path, message.cursor, { listing: s.listing, sort: message.sort, valid })
107
+ : await readChunk(root, message.path, message.offset);
108
+ if (type === Type.LIST && !valid() && !stale(generation)) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
99
109
  if (!stale(generation)) post({ type: reply, generation, requestId, ...body });
100
110
  } catch (error) {
101
111
  if (!stale(generation)) post({ type: reply, generation, requestId, error: errorOf(error) });
@@ -107,7 +117,10 @@ function serve(coda, view, sessionOf) {
107
117
  switch (message.type) {
108
118
  // 页面(重新)就绪:它什么都不知道,所以不管有没有变,下一次查询的结果都要推。
109
119
  case Type.HELLO: s.hello = true; s.sent = null; postSession(); return refreshRoot();
110
- case Type.REFRESH: return stale(message.generation) ? undefined : refreshRoot();
120
+ case Type.REFRESH:
121
+ if (stale(message.generation)) return undefined;
122
+ s.listing.detach();
123
+ return refreshRoot();
111
124
  case Type.LIST: case Type.READ: return request(message);
112
125
  }
113
126
  });
@@ -124,11 +137,18 @@ function serve(coda, view, sessionOf) {
124
137
  if (s.closed || id !== s.session || before === undefined || after === undefined || before === after) return;
125
138
  const { generation } = s;
126
139
  const refreshed = refreshRoot();
127
- if (before) refreshed.then(() => { if (s.hello && !stale(generation)) post({ type: Type.CHANGED, generation }); });
140
+ if (before) {
141
+ refreshed.then(() => {
142
+ if (!s.hello || stale(generation)) return;
143
+ s.listing.detach(); // 页面接着重新取,进行中的旧读取不能再被共用
144
+ post({ type: Type.CHANGED, generation });
145
+ });
146
+ }
128
147
  })).catch(() => null);
129
148
 
130
149
  view.onClose(async () => {
131
150
  s.closed = true;
151
+ s.listing.clear();
132
152
  stopPoll();
133
153
  try { await (await watching)?.dispose(); } catch { /* 已经取消 */ }
134
154
  });
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "@coda-console/resource-manager",
4
4
  "displayName": "资源管理器",
5
5
  "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本和图片,把路径交给对话。",
6
- "version": "0.3.0",
6
+ "version": "0.4.0",
7
7
  "categories": ["工作流程"],
8
8
  "license": "MIT",
9
9
  "repository": {
package/view/app.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  // 资源管理器的页面入口:消息收发、状态保留、工具栏。状态在 model.mjs,渲染在 tree.mjs 和 preview.mjs。
2
2
  import { EXIT, paintBar } from './bar.mjs';
3
3
  import { connect } from './connection.mjs';
4
+ import { infoText, sortName } from './format.mjs';
4
5
  import { icon } from './icons.mjs';
5
6
  import { Model, STATE_LIMIT, noticeText, parseState, putSession, trimState } from './model.mjs';
6
7
  import { showNotice } from './notice.mjs';
7
8
  import { mountPreview } from './preview.mjs';
8
- import { RootState } from './protocol.mjs';
9
+ import { EntryKind, RootState, SortKey } from './protocol.mjs';
9
10
  import { mountTree, rootName } from './tree.mjs';
10
11
 
11
12
  const coda = window.coda;
@@ -22,12 +23,13 @@ let pending = { tree: null, preview: null };
22
23
  const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
23
24
  const model = new Model({ link: conn.link, onChange: () => schedule() });
24
25
  model.showHidden = persisted.hidden;
26
+ model.sort = persisted.sort;
25
27
  const tree = mountTree($('tree'), model, {
26
28
  open: openFile,
27
29
  toggle: path => model.toggle(path),
28
30
  more: path => model.loadMore(path),
29
31
  retry: path => model.retry(path),
30
- menu: (event, path) => pathMenu(event, path),
32
+ menu: (event, row) => pathMenu(event, row),
31
33
  }, { draggable: !isIOS, longPress: isIOS });
32
34
  const preview = mountPreview($('preview'), {
33
35
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
@@ -121,7 +123,7 @@ const toolbarItems = () => hasToolbar
121
123
  { id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' },
122
124
  { id: 'hidden', label: '显示隐藏文件', icon: 'eye', kind: 'toggle', on: model.showHidden },
123
125
  ];
124
- // iPhone 树页顶部:返回(仅横屏)、根目录名、⋯。刷新和显示隐藏文件在 ⋯ 的菜单里。
126
+ // iPhone 树页顶部:返回(仅横屏)、根目录名、⋯。刷新、显示隐藏文件和排序都在 ⋯ 的菜单里。
125
127
  const MORE = { id: 'more', label: '更多', kind: 'button', glyph: 'ellipsis', iconOnly: true, menu: true };
126
128
  const phoneItems = () => [EXIT, { kind: 'title', label: model.ready ? rootName(model.root.path) : '' }, MORE];
127
129
  // 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
@@ -137,12 +139,25 @@ function syncToolbar() {
137
139
 
138
140
  // 原生按钮没有 DOM 元素可以当锚点:用一个固定在页面右上角的假锚点,同时也是「谁打开的菜单」的标记。
139
141
  const TOOLBAR = { getBoundingClientRect: () => ({ right: window.innerWidth, bottom: 0 }) };
140
- // 「更多」菜单的内容只写这一处,iPhone 的 ⋯ 和 Mac 的原生按钮共用。
142
+ // 「更多」菜单的内容只写这一处,iPhone 的 ⋯ 和 Mac 的原生按钮共用:刷新、显示隐藏文件,分隔线,小标题和平铺的四个排序项。
141
143
  const moreMenu = () => ({ items: [
142
144
  { label: '刷新', run: () => act('refresh') },
143
145
  { label: '显示隐藏文件', checked: model.showHidden, run: () => act('hidden') },
146
+ { separator: true },
147
+ { heading: '排序' },
148
+ ...Object.values(SortKey).map(key => ({ label: sortName(key), checked: key === model.sort, radio: true, run: () => changeSort(key) })),
144
149
  ] });
145
150
 
151
+ // 换排序:旧的滚动位置对新顺序没有意义,待恢复的作废,回到顶部;排序是全局的,存进 persisted。选当前项什么都不做。
152
+ function changeSort(sort) {
153
+ const before = model.sort;
154
+ model.setSort(sort);
155
+ if (model.sort === before) return; // 同值:什么都没换
156
+ persisted.sort = model.sort;
157
+ pending.tree = null;
158
+ tree.scrollTo(0);
159
+ }
160
+
146
161
  function act(id, button) {
147
162
  if (id === EXIT.id) quiet(() => coda.close());
148
163
  else if (id === 'more') {
@@ -173,7 +188,7 @@ function saveNow() {
173
188
  const top = preview.scroll();
174
189
  putSession(persisted, session, {
175
190
  ...model.snapshot(),
176
- scroll: { tree: pending.tree ?? tree.scroll(), top: pending.preview?.top ?? top.top, left: pending.preview?.left ?? top.left },
191
+ scroll: { tree: pending.tree ?? tree.scroll(), top: pending.preview?.top ?? top.top, left: pending.preview?.left ?? top.left, sort: model.sort },
177
192
  });
178
193
  persisted = trimState(persisted, session);
179
194
  // setState 超限会同步抛错:再收紧一次,仍失败就放弃这次,不影响界面。
@@ -183,17 +198,22 @@ quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
183
198
  $('tree').addEventListener('scroll', queueSave, { passive: true });
184
199
  preview.onScroll(queueSave);
185
200
 
186
- // ---- 菜单:Mac 右键、iPhone 长按出复制路径,iPhone 的 ⋯ 和 Mac 的原生「更多」出刷新和显示隐藏文件 ----
187
- // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(菜单贴在它下面、右对齐)或 { clientX, clientY } 的点。items:[{ label, run, checked? }],
188
- // checked 不是 undefined 的是带对勾的开关项。title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全。
201
+ // ---- 菜单:Mac 右键、iPhone 长按出复制路径,iPhone 的 ⋯ 和 Mac 的原生「更多」出刷新、显示隐藏文件和排序 ----
202
+ // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(菜单贴在它下面、右对齐)或 { clientX, clientY } 的点。
203
+ // items:[{ label, run, checked?, radio? } | { separator: true } | { heading }],checked 不是 undefined 的带对勾(radio 的是单选,其余是开关);
204
+ // 分隔线和小标题不是菜单项,不可点。title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全;detail 是它下面的一行小字。
189
205
  // 位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
190
206
  const menu = $('menu');
191
207
  let opener = null; // 打开菜单的按钮;用点打开的没有
192
- function openMenu(anchor, { title, items }) {
208
+ function openMenu(anchor, { title, detail, items }) {
193
209
  hideMenu();
194
- const head = title === undefined ? [] : [Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title })];
210
+ const head = [];
211
+ if (title !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title }));
212
+ if (detail !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-info secondary caption', textContent: detail }));
195
213
  const checkable = items.some(item => item.checked !== undefined); // 有开关项时,每一项都留出对勾的位置,文字才对齐
196
- menu.replaceChildren(...head, ...items.map(({ label, run, checked }) => {
214
+ menu.replaceChildren(...head, ...items.map(({ label, run, checked, radio, separator, heading }) => {
215
+ if (separator) return Object.assign(document.createElement('hr'), { className: 'menu-sep' });
216
+ if (heading !== undefined) return Object.assign(document.createElement('p'), { className: 'menu-head secondary caption', textContent: heading });
197
217
  const button = document.createElement('button'), name = document.createElement('span');
198
218
  name.textContent = label;
199
219
  if (checkable) {
@@ -203,7 +223,7 @@ function openMenu(anchor, { title, items }) {
203
223
  button.append(mark);
204
224
  }
205
225
  button.append(name);
206
- button.setAttribute('role', checked === undefined ? 'menuitem' : 'menuitemcheckbox');
226
+ button.setAttribute('role', checked === undefined ? 'menuitem' : radio ? 'menuitemradio' : 'menuitemcheckbox');
207
227
  if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
208
228
  button.addEventListener('click', () => { run(); hideMenu(); });
209
229
  return button;
@@ -215,9 +235,10 @@ function openMenu(anchor, { title, items }) {
215
235
  menu.style.top = `max(var(--safe-top), min(${y}px, calc(100vh - var(--safe-bottom) - ${menu.offsetHeight + 4}px)))`;
216
236
  if (box) { opener = anchor; opener.setAttribute?.('aria-expanded', 'true'); }
217
237
  }
218
- const pathMenu = (event, path) => openMenu(event, { title: path, items: [
219
- { label: '复制相对路径', run: () => coda.copy(path) },
220
- { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${path}`) },
238
+ // 行菜单:路径下面一行 大小 · 完整修改时间(文件夹只有修改时间,读不到就没有这一行);指向外面的链接和不能打开的条目没有元数据,不显示这一行。
239
+ const pathMenu = (event, row) => openMenu(event, { title: row.path, detail: row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER ? undefined : infoText(row) || undefined, items: [
240
+ { label: '复制相对路径', run: () => coda.copy(row.path) },
241
+ { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${row.path}`) },
221
242
  ] });
222
243
  function hideMenu() {
223
244
  menu.hidden = true;
@@ -249,7 +270,8 @@ function onSession(data) {
249
270
  clearTimeout(hintTimer);
250
271
  $('hint').hidden = true;
251
272
  const saved = persisted.sessions[data.session] ?? null;
252
- pending = saved ? { tree: saved.scroll.tree, preview: { top: saved.scroll.top, left: saved.scroll.left } } : { tree: null, preview: null };
273
+ // 目录树的滚动位置是按当时的排序存的;排序是全局的,在别的会话换过就对不上,等内容到了回到顶部。
274
+ pending = saved ? { tree: saved.scroll.sort === model.sort ? saved.scroll.tree : 0, preview: { top: saved.scroll.top, left: saved.scroll.left } } : { tree: null, preview: null };
253
275
  model.receive(data, saved);
254
276
  }
255
277
 
@@ -0,0 +1,40 @@
1
+ // 目录树和菜单里的文字格式:大小、修改日期。纯函数,不依赖运行环境的语言设置;now 由调用方给。
2
+ import { EntryKind, SortKey } from './protocol.mjs';
3
+
4
+ export function formatSize(bytes) {
5
+ if (bytes < 1024) return `${bytes} B`;
6
+ const units = ['KiB', 'MiB', 'GiB'];
7
+ let value = bytes / 1024, unit = 0;
8
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
9
+ return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
10
+ }
11
+
12
+ const two = n => String(n).padStart(2, '0');
13
+
14
+ // 相对格式,按本地时间:今天 14:05,今年 11月4日,往年 2025年3月。
15
+ export function formatDate(ms, now) {
16
+ const date = new Date(ms), current = new Date(now);
17
+ if (date.getFullYear() !== current.getFullYear()) return `${date.getFullYear()}年${date.getMonth() + 1}月`;
18
+ if (date.getMonth() !== current.getMonth() || date.getDate() !== current.getDate()) return `${date.getMonth() + 1}月${date.getDate()}日`;
19
+ return `${two(date.getHours())}:${two(date.getMinutes())}`;
20
+ }
21
+
22
+ // 完整的修改时间:2025-03-04 14:05:09。
23
+ export function formatFullDate(ms) {
24
+ const d = new Date(ms);
25
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
26
+ }
27
+
28
+ const MISSING = '—';
29
+ const isDir = entry => entry.kind === EntryKind.DIR;
30
+ // 条目的大小和日期:文件读不到的部分是 —;文件夹不显示大小,读不到修改时间也不显示 —,返回空串。
31
+ export const sizeText = entry => (isDir(entry) ? '' : Number.isInteger(entry.size) ? formatSize(entry.size) : MISSING);
32
+ export const dateText = (entry, now) => (Number.isInteger(entry.mtimeMs) ? formatDate(entry.mtimeMs, now) : isDir(entry) ? '' : MISSING);
33
+ const joined = parts => parts.filter(Boolean).join(' · ');
34
+ // iPhone 第二行:日期 · 大小;文件夹只有日期。
35
+ export const subText = (entry, now) => joined([dateText(entry, now), sizeText(entry)]);
36
+ // 菜单信息行和 Mac 的 title:大小 · 完整修改时间;文件夹只有完整修改时间。没有内容时是空串。
37
+ export const infoText = entry => joined([sizeText(entry), Number.isInteger(entry.mtimeMs) ? formatFullDate(entry.mtimeMs) : isDir(entry) ? '' : MISSING]);
38
+
39
+ const NAMES = { [SortKey.NAME]: '名称', [SortKey.KIND]: '种类', [SortKey.DATE]: '日期', [SortKey.SIZE]: '大小' };
40
+ export const sortName = key => NAMES[key];
package/view/model.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // 页面的纯状态:目录树、状态保留。不碰 DOM,请求与代次在 connection.mjs,设计见 docs/design/phase-1.md 第 6、7 节。
2
- import { ErrorCode, RootState, Type } from './protocol.mjs';
2
+ import { DEFAULT_SORT, ErrorCode, RootState, Type, parseSort } from './protocol.mjs';
3
3
 
4
4
  export const STATE_LIMIT = 96 * 1024;
5
5
  export const MAX_PARALLEL = 8;
@@ -39,6 +39,8 @@ export class Model {
39
39
  wanted = new Map(); // 恢复状态时各目录要取够的条数,第一次取用后删掉
40
40
  selected = null;
41
41
  showHidden = false;
42
+ sort = DEFAULT_SORT; // 全局一份,由页面存进 persisted
43
+ #round = 0; // refresh 的轮次:新一轮开始后,旧一轮不再派发排队的目录
42
44
 
43
45
  constructor({ link, onChange = () => {} }) { Object.assign(this, { link, onChange }); }
44
46
 
@@ -57,6 +59,7 @@ export class Model {
57
59
  // 换会话:清空一切,展开状态换成这个会话保存的。
58
60
  onSession({ generation, session }, saved = null) {
59
61
  this.link.reset(generation);
62
+ this.#round++;
60
63
  this.session = session ?? null;
61
64
  this.root = null;
62
65
  this.dirs = new Map();
@@ -79,34 +82,55 @@ export class Model {
79
82
  return generation === this.link.generation && this.ready ? this.refresh() : null;
80
83
  }
81
84
 
82
- // 重新取根和全部已展开的目录,并行不超过 8 个。
83
- refresh() {
85
+ // 重新取根和全部已展开的目录,并行不超过 8 个。cap:这一轮每个目录最多取够这么多条(换排序时用)。
86
+ // 每一轮带递增的轮次:只查 current() 不够,旧一轮的池子还会启动排队中的目录,递增它们的 token,作废较新的加载。
87
+ refresh({ cap = Infinity } = {}) {
84
88
  if (!this.ready) return Promise.resolve();
85
- const { generation } = this.link;
86
- return pool(['', ...this.expanded], MAX_PARALLEL, path => this.#reload(path, generation));
89
+ const { generation } = this.link, round = ++this.#round;
90
+ return pool(['', ...this.expanded], MAX_PARALLEL, path => (round === this.#round ? this.#reload(path, generation, { cap }) : undefined));
87
91
  }
88
92
 
89
- // 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。
90
- async #reload(path, generation) {
93
+ // 换排序:已加载的目录按新顺序重新取,取够现在的条数,这次最多 RESTORE_LIMIT 条;每个目录一次替换。
94
+ setSort(sort) {
95
+ const next = parseSort(sort);
96
+ if (!next || next === this.sort) return Promise.resolve();
97
+ this.sort = next;
98
+ this.onChange();
99
+ return this.refresh({ cap: RESTORE_LIMIT });
100
+ }
101
+
102
+ // 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。一次加载固定一种排序。
103
+ // more、expired:「再显示」遇到游标过期转过来时,条数要比现在多一条,而且已经算重取过一次,不再重取。
104
+ async #reload(path, generation, { cap = Infinity, more = false, expired = false } = {}) {
91
105
  if (this.link.generation !== generation) return; // 排队时会话已换,旧任务不碰新会话
92
106
  let dir = this.dirs.get(path);
93
- if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0 });
94
- const token = ++dir.token, want = Math.max(dir.entries.length, this.wanted.get(path) ?? 0);
107
+ if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false });
108
+ const token = ++dir.token, { sort } = this;
109
+ const want = more ? dir.entries.length + 1 : Math.min(Math.max(dir.entries.length, this.wanted.get(path) ?? 0), cap);
95
110
  dir.loading = true;
96
111
  this.onChange();
97
112
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
98
113
  try {
99
- const entries = [];
100
- let next = null, pages = 0;
114
+ let entries = [], next = null, pages = 0, sortFallback = false;
101
115
  do {
102
- const reply = await this.link.call('list', { path, cursor: next });
103
- if (this.link.generation !== generation) return; // 回答到了、继续前会话换了,不再取下一页
116
+ let reply;
117
+ try {
118
+ reply = await this.link.call('list', { path, cursor: next, sort });
119
+ } catch (error) {
120
+ // 游标过期(快照被淘汰、释放,或根目录变了):丢掉这一轮累积的,从第一页重取一次,再失败走失败行。
121
+ if (error.code !== ErrorCode.CURSOR_EXPIRED || expired || !current()) throw error;
122
+ expired = true;
123
+ entries = []; next = null; pages = 0; sortFallback = false;
124
+ continue;
125
+ }
126
+ if (!current()) return; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
127
+ if (pages === 0) sortFallback = reply.sortFallback === true;
104
128
  entries.push(...reply.entries);
105
129
  next = reply.nextCursor ?? null;
106
130
  pages++;
107
- } while (next && entries.length < want);
131
+ } while (pages === 0 || (next && entries.length < want));
108
132
  if (!current()) return;
109
- Object.assign(dir, { entries, next, loaded: true, error: null, pages });
133
+ Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback });
110
134
  this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
111
135
  } catch (error) {
112
136
  if (error.stale || !current()) return;
@@ -145,12 +169,15 @@ export class Model {
145
169
  this.onChange();
146
170
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
147
171
  try {
148
- const reply = await this.link.call('list', { path, cursor: dir.next });
172
+ const reply = await this.link.call('list', { path, cursor: dir.next, sort: this.sort });
149
173
  if (!current()) return;
150
174
  dir.entries = dir.entries.concat(reply.entries);
151
175
  Object.assign(dir, { next: reply.nextCursor ?? null, error: null, pages: dir.pages + 1 });
152
176
  } catch (error) {
153
- if (!error.stale && current()) dir.error = { code: error.code, message: error.message };
177
+ if (error.stale || !current()) return;
178
+ // 游标过期:从第一页重取,条数比现在多一条,所以还会接着往下取。重取自己管 loading。
179
+ if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#reload(path, generation, { more: true, expired: true });
180
+ dir.error = { code: error.code, message: error.message };
154
181
  } finally {
155
182
  if (current()) dir.loading = false;
156
183
  this.onChange();
@@ -178,9 +205,10 @@ const parseLoaded = raw => Object.fromEntries(Object.entries(raw && typeof raw =
178
205
 
179
206
  // 读回来的值可能是别的版本或坏的,只认自己的形状。
180
207
  export function parseState(raw) {
181
- const state = { v: 1, seq: 0, hidden: false, sessions: {} };
208
+ const state = { v: 1, seq: 0, hidden: false, sort: DEFAULT_SORT, sessions: {} };
182
209
  if (!raw || typeof raw !== 'object' || raw.v !== 1) return state;
183
210
  state.hidden = raw.hidden === true;
211
+ state.sort = parseSort(raw.sort) ?? DEFAULT_SORT;
184
212
  state.seq = Number.isSafeInteger(raw.seq) ? raw.seq : 0;
185
213
  for (const [id, item] of Object.entries(raw.sessions ?? {})) {
186
214
  if (!item || typeof item !== 'object') continue;
@@ -188,7 +216,8 @@ export function parseState(raw) {
188
216
  state.sessions[id] = {
189
217
  at: Number.isSafeInteger(item.at) ? item.at : 0, expanded: strings(item.expanded, 5000),
190
218
  selected: typeof item.selected === 'string' && item.selected.length <= 1024 ? item.selected : null,
191
- scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left) },
219
+ // 滚动位置是按当时的排序存的;旧版本没有这个字段,那时一定是默认排序。
220
+ scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left), sort: parseSort(scroll.sort) ?? DEFAULT_SORT },
192
221
  };
193
222
  const loaded = parseLoaded(item.loaded);
194
223
  if (Object.keys(loaded).length > 0) state.sessions[id].loaded = loaded;
package/view/preview.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
2
+ import { formatSize } from './format.mjs';
2
3
  import { icon, iconFor } from './icons.mjs';
3
4
  import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType } from './protocol.mjs';
4
5
 
@@ -44,13 +45,6 @@ export async function readFile(read, { prev = null, onProgress = () => {}, cance
44
45
  throw Object.assign(error, { code: ErrorCode.IO });
45
46
  }
46
47
 
47
- export function formatSize(bytes) {
48
- if (bytes < 1024) return `${bytes} B`;
49
- const units = ['KiB', 'MiB', 'GiB'];
50
- let value = bytes / 1024, unit = 0;
51
- while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
52
- return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
53
- }
54
48
  const formatTime = ms => new Date(ms).toLocaleString('zh-CN', { hour12: false });
55
49
  export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0));
56
50
 
package/view/protocol.mjs CHANGED
@@ -8,7 +8,7 @@ export const PAGE_BYTES = 96 * 1024;
8
8
  export const ENVELOPE_BYTES = 4096;
9
9
  export const TEXT_LIMIT = 1024 * 1024;
10
10
  export const IMAGE_LIMIT = 8 * 1024 * 1024;
11
- // 前这么多字节里有 NUL 就当二进制(同 Coda 的 worktree-changes)。
11
+ // 前这么多字节里有 NUL 就当二进制(照 Coda 判断二进制的惯例)。
12
12
  export const SNIFF_BYTES = 8000;
13
13
  export const REQUEST_ID_MAX = 64;
14
14
 
@@ -21,12 +21,19 @@ export const RootState = Object.freeze({ READY: 'ready', NONE: 'none', PREPARING
21
21
 
22
22
  export const ErrorCode = Object.freeze({
23
23
  NO_ROOT: 'no_root', INVALID_PATH: 'invalid_path', OUTSIDE_ROOT: 'outside_root', NOT_FOUND: 'not_found',
24
- NOT_DIR: 'not_dir', NOT_FILE: 'not_file', DENIED: 'denied', INVALID_CURSOR: 'invalid_cursor',
25
- INVALID_OFFSET: 'invalid_offset', TOO_LARGE: 'too_large', IO: 'io_error',
24
+ NOT_DIR: 'not_dir', NOT_FILE: 'not_file', DENIED: 'denied', CURSOR_EXPIRED: 'cursor_expired',
25
+ INVALID_OFFSET: 'invalid_offset', INVALID_SORT: 'invalid_sort', TOO_LARGE: 'too_large', IO: 'io_error',
26
26
  });
27
27
 
28
+ // 目录排序:值是下面四种之一,缺省(请求不带 sort)是名称。方向由排序键决定,只在 lib/tree.mjs 里定义一处。
29
+ export const SortKey = Object.freeze({ NAME: 'name', KIND: 'kind', DATE: 'date', SIZE: 'size' });
30
+ export const DEFAULT_SORT = SortKey.NAME;
31
+ // 是四种之一的返回它,否则 null(含旧版本保存过的 { key, desc } 对象)。
32
+ export const parseSort = raw => (Object.values(SortKey).includes(raw) ? raw : null);
33
+
28
34
  // 目录条目的 kind:dir、file;link 是指向工作目录外或已失效的链接;other 是不能打开的(套接字、名字含控制字符等)。
29
35
  // 指向工作目录内的链接按目标显示成 dir 或 file,并带 link: true。
36
+ // 条目还可带整数 size(只有文件有)和 mtimeMs(向下取整);读不到时不带。
30
37
  export const EntryKind = Object.freeze({ DIR: 'dir', FILE: 'file', LINK: 'link', OTHER: 'other' });
31
38
  // 文件块的 kind。
32
39
  export const ContentKind = Object.freeze({ TEXT: 'text', IMAGE: 'image', BINARY: 'binary' });
package/view/style.css CHANGED
@@ -1,4 +1,4 @@
1
- /* 资源管理器的页面,颜色、字体、字号只用 App 给的 --coda-* 变量(docs/plugins.md「视图」)。 */
1
+ /* 资源管理器的页面,颜色、字体、字号只用 App 给的 --coda-* 变量(插件视图的主题变量)。 */
2
2
  :root {
3
3
  --hover: var(--coda-hover, var(--coda-fill, rgba(0,0,0,.05)));
4
4
  --line: var(--coda-separator, rgba(0,0,0,.1));
@@ -35,7 +35,7 @@ p { margin: 0; }
35
35
 
36
36
  /* 页内工具条:iPhone 树页在顶部(返回、根目录名、⋯),文件页在底部(.bottom:返回、刷新、复制路径)。没有 coda.toolbar 的其他平台(harness)是一条文字按钮。 */
37
37
  .bar { display: flex; align-items: center; gap: 4px; padding: 6px 8px; border-bottom: 1px solid var(--line); }
38
- .bar button { display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; border-radius: var(--coda-radius, 6px); color: var(--coda-secondary, #6e6e73); }
38
+ .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); }
39
39
  .bar button.on { color: var(--coda-accent, #0a84ff); }
40
40
  .bar svg { display: block; flex: none; }
41
41
  .bar-title { padding: 0 8px; font-weight: 600; }
@@ -43,7 +43,10 @@ p { margin: 0; }
43
43
 
44
44
  /* 树:只画可见的一段,行高固定(tree.mjs 量 .row 的高度)。
45
45
  Mac 是侧栏列表:左右缩进 8 点,行有圆角,选中用 --coda-selection。 */
46
+ /* 标题行:根目录名,随内容滚走。它在滚动容器里占着自己的高度,tree.mjs 把 spacer 的 offsetTop 扣掉。 */
46
47
  .section { padding: 10px 16px 4px; font-size: .85em; font-weight: 600; color: var(--coda-secondary, #6e6e73); cursor: default; }
48
+ /* 行宽按 #tree 的宽度查询:窄于约 220 点时 Mac 的 meta 不显示。 */
49
+ #tree { container: tree / inline-size; }
47
50
  .spacer { position: relative; margin: 0 8px; }
48
51
  .win { position: absolute; left: 0; right: 0; top: 0; }
49
52
  /* 缩进按行的 --d(深度)算,iPhone 的分隔线起点也用它。 */
@@ -60,7 +63,11 @@ p { margin: 0; }
60
63
  .ico { flex: none; display: grid; place-items: center; color: var(--coda-secondary, #6e6e73); }
61
64
  .ico svg { display: block; }
62
65
  .row.dir .ico { color: var(--coda-accent, #0a84ff); }
63
- .name { flex: 1 1 auto; min-width: 0; }
66
+ .main { flex: 1 1 auto; min-width: 0; }
67
+ .name { display: block; }
68
+ .sub { display: none; }
69
+ .meta { flex: none; padding-left: 4px; font-variant-numeric: tabular-nums; white-space: nowrap; }
70
+ @container tree (max-width: 220px) { .meta { display: none; } }
64
71
  .tail { flex: none; display: grid; place-items: center; color: var(--coda-secondary, #6e6e73); }
65
72
  .tail:empty { display: none; }
66
73
  .tail svg { display: block; }
@@ -85,12 +92,16 @@ button.icon svg { display: block; }
85
92
  .image img { max-width: 100%; height: auto; border-radius: var(--coda-radius, 6px); background: var(--coda-secondary-background, transparent); }
86
93
 
87
94
  #notice:focus { outline: none; }
88
- .menu { position: fixed; z-index: 10; min-width: 150px; padding: 4px; border: 1px solid var(--coda-outline, var(--line)); border-radius: var(--coda-radius-card, 10px);
95
+ .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);
89
96
  background: var(--coda-card, var(--coda-background, #fff)); }
90
97
  .menu button { display: flex; align-items: center; gap: 6px; width: 100%; padding: 5px 10px; border-radius: var(--coda-radius, 6px); }
91
98
  .check { flex: none; display: grid; place-items: center; width: 16px; color: var(--coda-accent, #0a84ff); }
92
99
  .check svg { display: block; }
93
- .menu-path { max-width: 280px; padding: 4px 10px 6px; overflow-wrap: anywhere; }
100
+ /* 菜单宽度随内容,上限见 .menu:路径超过上限折行,大小 · 完整修改时间不折。 */
101
+ .menu-path { padding: 4px 10px 6px; overflow-wrap: anywhere; }
102
+ .menu-info { padding: 0 10px 6px; margin-top: -4px; white-space: nowrap; }
103
+ .menu-sep { margin: 4px 6px; border: 0; border-top: 1px solid var(--line); }
104
+ .menu-head { padding: 4px 10px 2px; font-weight: 600; }
94
105
  .pmeta.warn { color: var(--coda-orange, #b25000); }
95
106
 
96
107
  .hint { position: fixed; left: calc(8px + var(--safe-left)); right: calc(8px + var(--safe-right)); bottom: calc(8px + var(--safe-bottom)); z-index: 10;
@@ -105,9 +116,9 @@ button.icon svg { display: block; }
105
116
  .menu button:hover { background: var(--coda-selection, var(--hover)); }
106
117
  }
107
118
 
108
- /* iPhone:行和按钮至少 44 点;行高在这里定,tree.mjs 量 .row 得到,不另写一份。
119
+ /* iPhone:行和按钮至少 44 点;行高 58 点(两行:名字、日期 · 大小)在这里定,tree.mjs 量 .row 得到,不另写一份。
109
120
  目录树是 Coda 卡片外形的分组列表:.spacer 就是卡片(高度已等于全部行高),首尾圆角不用逐行判断。 */
110
- .coda-ios { --row-h: 44px; --indent: 20px; --pad: 16px; }
121
+ .coda-ios { --row-h: 58px; --indent: 20px; --pad: 16px; }
111
122
  .coda-ios .section { display: none; } /* 根目录名归页内工具条 */
112
123
  .coda-ios .spacer { margin: 8px 16px; overflow: hidden; border-radius: var(--coda-radius-card, 12px); background: var(--coda-card, var(--coda-secondary-background, #fff)); }
113
124
  /* 描边用伪元素:不占尺寸,spacer 加 border 会让内容区少 2 点,末行被裁。 */
@@ -119,6 +130,9 @@ button.icon svg { display: block; }
119
130
  .coda-ios .row { -webkit-touch-callout: none; } /* 长按由页面接管,不弹系统菜单;选择和拖动另外已关 */
120
131
  .coda-ios .row.entry:active { background: var(--hover); }
121
132
  .coda-ios .ico svg { width: 22px; height: 22px; }
133
+ .coda-ios .main { display: flex; flex-direction: column; justify-content: center; } /* 没有第二行的条目,名字垂直居中 */
134
+ .coda-ios .sub { display: block; }
135
+ .coda-ios .meta { display: none; }
122
136
  .coda-ios .chev { order: 9; width: 14px; }
123
137
  .coda-ios .row.dir .chev { color: var(--coda-accent, #0a84ff); }
124
138
  .coda-ios .row.file .chev svg { visibility: visible; }
@@ -133,6 +147,7 @@ button.icon svg { display: block; }
133
147
  .coda-ios .phead button { padding: 0 8px; }
134
148
  .coda-ios .code { font-size: .8em; } /* 窄屏多看些:17 点下约 13.6 点 */
135
149
  .coda-ios .menu button { padding: 0 12px; }
150
+ .coda-ios .menu-head { padding: 6px 12px 2px; }
136
151
 
137
152
  /* 横屏:客户端隐藏导航栏,页面自己给返回。近似 verticalSizeClass 的判断,不等价(iPad、Duo 不单独适配)。 */
138
153
  .bar .exit { display: none; }
package/view/tree.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // 目录树:visibleRows 把模型压成扁平行(纯逻辑);mountTree 只画可见的那一段,上万条也不卡。
2
- import { EntryKind } from './protocol.mjs';
2
+ import { EntryKind, SortKey } from './protocol.mjs';
3
+ import { dateText, infoText, sizeText, subText } from './format.mjs';
3
4
  import { icon, iconFor } from './icons.mjs';
4
5
  import { isHidden, joinPath } from './model.mjs';
5
6
 
@@ -8,7 +9,7 @@ const OVERSCAN = 8;
8
9
  export const HOLD_MS = 500;
9
10
  export const HOLD_SLOP = 10;
10
11
 
11
- // 行:{ type: 'entry' | 'status' | 'more', path, name, depth, kind, link, open, busy, failed, text }
12
+ // 行:{ type: 'entry' | 'status' | 'more', path, name, depth, kind, link, size, mtimeMs, open, busy, failed, text };size、mtimeMs 读不到时没有
12
13
  export function visibleRows(model) {
13
14
  const rows = [];
14
15
  const walk = (dir, depth) => {
@@ -17,12 +18,14 @@ export function visibleRows(model) {
17
18
  if (!state.loaded) return rows.push({ type: 'status', path: dir, depth, text: `读取失败:${state.error.message}`, retry: true });
18
19
  // 刷新失败:旧条目保留,最上方加一行原因,点它重试。这一行不算内容,空目录的判断在它之后。
19
20
  if (state.error) rows.push({ type: 'status', path: dir, depth, text: `更新失败:${state.error.message}`, retry: true });
21
+ // 条目太多按名称排了:说明行固定行高,不算内容,不影响「空目录」的判断。
22
+ if (state.sortFallback) rows.push({ type: 'status', path: dir, depth, text: '条目太多,只能按名称排列' });
20
23
  const before = rows.length;
21
24
  for (const entry of state.entries) {
22
25
  if (!model.showHidden && isHidden(entry.name)) continue;
23
26
  const path = joinPath(dir, entry.name), open = entry.kind === EntryKind.DIR && model.expanded.has(path);
24
27
  rows.push({
25
- type: 'entry', path, name: entry.name, depth, kind: entry.kind, link: entry.link === true, open,
28
+ type: 'entry', path, name: entry.name, depth, kind: entry.kind, link: entry.link === true, size: entry.size, mtimeMs: entry.mtimeMs, open,
26
29
  busy: open && model.dirs.get(path)?.loading === true, failed: open ? model.dirs.get(path)?.error?.message : undefined,
27
30
  });
28
31
  if (open) walk(path, depth + 1);
@@ -39,10 +42,11 @@ export const rootName = path => path.split('/').filter(Boolean).pop() ?? path;
39
42
 
40
43
  const TITLES = { [EntryKind.LINK]: '指向工作目录外的链接,不能打开', [EntryKind.OTHER]: '不能打开的文件' };
41
44
 
42
- // handlers: { open(path), toggle(path), more(path), retry(path), menu(event, path, kind) }
43
- // draggable:触屏上拖行没有用处,还会抢滚动,关掉。
45
+ // handlers: { open(path), toggle(path), more(path), retry(path), menu(event, row) }
46
+ // menu 收到整行(路径、种类、大小、修改时间)。
47
+ // draggable:触屏上拖行没有用处,还会抢滚动,关掉。now:当前时间,日期的相对格式用,测试可注入。
44
48
  // longPress:触屏上按住一行打开 handlers.menu(Mac 用右键)。不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
45
- export function mountTree(el, model, handlers, { draggable = true, longPress = false } = {}) {
49
+ export function mountTree(el, model, handlers, { draggable = true, longPress = false, now = Date.now } = {}) {
46
50
  const title = document.createElement('div'), spacer = document.createElement('div'), win = document.createElement('div');
47
51
  title.className = 'section truncate'; spacer.className = 'spacer'; win.className = 'win';
48
52
  title.hidden = true;
@@ -73,10 +77,11 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
73
77
  const first = Math.max(0, Math.floor(top / rowH) - OVERSCAN);
74
78
  const last = Math.min(rows.length, Math.ceil((top + el.clientHeight) / rowH) + OVERSCAN);
75
79
  win.style.transform = `translateY(${first * rowH}px)`;
76
- win.replaceChildren(...rows.slice(first, last).map((row, i) => rowNode(row, first + i)));
80
+ const time = now();
81
+ win.replaceChildren(...rows.slice(first, last).map((row, i) => rowNode(row, first + i, time)));
77
82
  }
78
83
 
79
- function rowNode(row, index) {
84
+ function rowNode(row, index, time) {
80
85
  const node = document.createElement('div');
81
86
  node.className = `row ${row.type}`;
82
87
  node.dataset.i = index;
@@ -92,21 +97,41 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
92
97
  if (row.path === model.selected) node.classList.add('sel');
93
98
  if (row.kind === EntryKind.DIR) node.setAttribute('aria-expanded', row.open);
94
99
  if (!dead && draggable) node.draggable = true;
95
- // 一份 DOM:Mac 是 箭头、图标、名字、尾标,iPhone 的箭头用 CSS order 排到最后。
96
- const chevron = document.createElement('span'), glyph = document.createElement('span'), label = document.createElement('span'), tail = document.createElement('span');
100
+ // 一份 DOM:箭头、图标、名字(iPhone 下面跟日期 · 大小)、Mac 的 meta、尾标;iPhone 的箭头用 CSS order 排到最后,两端各用 CSS 藏起另一端的那段。
101
+ const chevron = document.createElement('span'), glyph = document.createElement('span'), main = document.createElement('span'), label = document.createElement('span'), tail = document.createElement('span');
97
102
  chevron.className = 'chev';
98
103
  if (row.busy) chevron.textContent = '…';
99
104
  else if (!dead) chevron.append(icon('chevron', 12)); // 文件的箭头 Mac 上由 CSS 藏起来,只占位
100
105
  if (row.open) node.classList.add('open');
101
106
  glyph.className = 'ico';
102
107
  glyph.append(icon(iconFor(row)));
108
+ main.className = 'main';
103
109
  label.className = 'name truncate';
104
110
  label.textContent = row.name;
111
+ main.append(label);
112
+ const parts = [chevron, glyph, main];
113
+ if (!dead) {
114
+ // 能打开的条目带信息;link、other 没有。文件夹没有的部分整个不画:iPhone 名字垂直居中,Mac 右侧不留空位。
115
+ const subContent = subText(row, time), metaContent = model.sort === SortKey.DATE ? dateText(row, time) : sizeText(row);
116
+ if (subContent) {
117
+ const sub = document.createElement('span');
118
+ sub.className = 'sub caption secondary truncate';
119
+ sub.textContent = subContent;
120
+ main.append(sub);
121
+ }
122
+ if (metaContent) {
123
+ const meta = document.createElement('span');
124
+ meta.className = 'meta caption secondary';
125
+ meta.textContent = metaContent;
126
+ parts.push(meta);
127
+ }
128
+ }
105
129
  tail.className = row.failed ? 'tail warn' : 'tail';
106
130
  if (row.failed) tail.append(icon('warning', 14));
107
131
  else if (row.link) tail.append(icon('turn', 14));
108
- node.title = row.failed ? `${row.path}\n读取失败:${row.failed}` : TITLES[row.kind] ? `${row.path}\n${TITLES[row.kind]}` : row.path;
109
- node.append(chevron, glyph, label, tail);
132
+ const info = row.failed || TITLES[row.kind] ? '' : infoText(row);
133
+ node.title = row.failed ? `${row.path}\n读取失败:${row.failed}` : TITLES[row.kind] ? `${row.path}\n${TITLES[row.kind]}` : info ? `${row.path}\n${info}` : row.path;
134
+ node.append(...parts, tail);
110
135
  return node;
111
136
  }
112
137
 
@@ -126,7 +151,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
126
151
  hold = { id, x, y, timer: setTimeout(() => {
127
152
  hold = null;
128
153
  swallow = true;
129
- handlers.menu({ clientX: x, clientY: y }, row.path);
154
+ handlers.menu({ clientX: x, clientY: y }, row);
130
155
  }, HOLD_MS) };
131
156
  });
132
157
  el.addEventListener('pointermove', event => {
@@ -147,7 +172,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
147
172
  });
148
173
  el.addEventListener('contextmenu', event => {
149
174
  const row = rowOf(event);
150
- if (row?.type === 'entry') { event.preventDefault(); handlers.menu(event, row.path); }
175
+ if (row?.type === 'entry') { event.preventDefault(); handlers.menu(event, row); }
151
176
  });
152
177
  el.addEventListener('dragstart', event => {
153
178
  const row = rowOf(event);