@coda-console/resource-manager 0.8.0 → 0.9.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 +4 -2
- package/lib/media.mjs +79 -0
- package/lib/root.mjs +54 -9
- package/main.mjs +20 -7
- package/package.json +2 -2
- package/view/app.mjs +10 -7
- package/view/bar.mjs +22 -2
- package/view/file-app.mjs +1 -0
- package/view/format.mjs +6 -0
- package/view/grid.mjs +16 -10
- package/view/model.mjs +3 -2
- package/view/preview.mjs +72 -13
- package/view/protocol.mjs +25 -3
- package/view/rootname.mjs +109 -0
- package/view/style.css +9 -1
- package/view/tree.mjs +9 -8
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 资源管理器
|
|
2
2
|
|
|
3
|
-
Coda
|
|
3
|
+
Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,读文本、图片、音频和视频,把路径交给对话。只读。
|
|
4
4
|
|
|
5
5
|
- **Mac**:在会话侧栏里,和对话并排。
|
|
6
6
|
- **iPhone**:在会话右上角菜单里打开,点文件在资源页里切到预览,系统返回(左上「‹」、左边缘侧滑)回到打开它的那一层。iPad 和 iPhone Duo 用同一套界面,没有单独适配。
|
|
@@ -12,13 +12,15 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
|
|
|
12
12
|
- **按键的质感**(`0.7.2`):两端按下就有底色反馈(页面自己加状态,不靠 `:active`;快点一下也看得到,滑动时不闪;菜单开着时点外面那一下只关菜单),Mac 的按钮是箭头光标;菜单有阴影,iPhone 的菜单出现时有淡入加缩放;iPhone 打开文件、属性页和返回(含侧滑)是滑动过渡,图标视图进出目录是淡入。系统打开「减弱动态效果」后所有动画和过渡都不做,按下反馈照常。没有触感(契约没有这个接口)。
|
|
13
13
|
- 图标视图回上一层:iPhone 用系统的返回,Mac 点头部最左边的返回键或按 ⌘↑,退回的那一层里选中刚才进去的文件夹。**没有预览面板**:只有一个侧栏,也没有面包屑。
|
|
14
14
|
- **Mac 的键盘**:点一下目录树或图标视图让它拿到焦点(Tab 也能进来),↑ ↓ 移动选中(图标视图按行列走),列表里 → 展开、← 收起或选中所在的文件夹,图标视图里 ← → 选左右的条目;⌘↓ 同双击(打开、展开、进入);⌘↑ 在图标视图里回上一层,在预览里返回目录树或图标视图;⌘F 聚焦搜索框。搜索框里 ↓ 进结果,Esc 清空;结果里 Esc 回搜索框。不做多选、按字母跳转,Return 和空格也没绑定。读屏的 `aria-activedescendant` 没做(见 `docs/backlog.md`)。
|
|
15
|
-
- 文本预览(带行号,可跨行选中复制,最多读 1 MiB
|
|
15
|
+
- 文本预览(带行号,可跨行选中复制,最多读 1 MiB)。
|
|
16
|
+
- **图片、音频、视频预览**(`0.9.0`):经 Coda 开放的本机流式服务,边播边取,不分块传、没有大小上限,音视频可拖动进度。图片:PNG、JPEG、GIF、WebP、SVG、AVIF、HEIC、BMP、TIFF;音频:MP3、M4A、AAC、WAV、FLAC、OGG(Opus)、AIFF、CAF;视频:MP4、M4V、MOV、WebM。用系统自带的播放控件;元信息行写目录、大小,音视频加时长。能不能放取决于这台设备的浏览器内核(Mac 和 iPhone 不同),放不了的写「这台设备放不了这种格式」;MKV、AVI 播放器不支持,直接写「这种格式不能预览」,只给大小和修改时间。不缓存,每次都向模块要。刷新不打断播放:文件变了,元信息行写「文件已变化」,点头部「重载」才换。旧版本的 Coda 没有这个服务:图片退回分块读取(最多 8 MiB),音视频不预览。
|
|
16
17
|
- 代码按语言上色:三十多种常见语言,只按文件名和扩展名认,不猜内容,深浅各一套配色;认不出的显示纯文本。超过 128 KiB 的文件不上色,说明区注明「不高亮」。用的是近似的语法规则,不是语法检查,个别文件会认错(如 `.h` 一律按 C++,`.m` 一律按 Objective-C),不保证完整支持。
|
|
17
18
|
- Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
|
|
18
19
|
- 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
|
|
19
20
|
- 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「显示」›「排序」里选,当前项有对勾。两种视图用同一个排序。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
|
|
20
21
|
- **文件名搜索**(`0.8.0`):目录树和图标视图顶上常驻一个搜索框,Mac 按 ⌘F 聚焦它(选中里面的字)。有字时列表换成结果,清空(Esc 或清除按钮)回到原来的浏览,展开、滚动、选中都还在。搜整个工作目录(后台逐层走,先浅后深),只比**名字**,不比路径(带斜杠的词找不到):不分大小写、包含就算,中文和分解形式的字(如 `é` 的两种写法)都能找到。始终不进 `.git`、`node_modules`(它们自己能作为结果),隐藏文件跟「显示隐藏文件」开关,不跟着链接进目录,不读 `.gitignore`。最多 500 条,最多看 20 万项或 5 秒,到了就停并注明「没搜完」,只显示已找到的;每次重新走树,没有索引。结果按「名字以搜索词开头的在前、浅的在前、再按名称」排,不跟「显示」菜单的排序走。每行是图标、名字(匹配的部分加粗)、所在目录(Mac 在右边,iPhone 在第二行)。Mac 单击选中、双击或 ⌘↓ 打开,↑ ↓ 移动;iPhone 轻点打开;右键或长按有「打开」「添加到聊天」「复制路径」「在目录中显示」「属性」。「在目录中显示」逐级展开(图标视图是进入它所在的目录)并把它选中、滚到中间;这期间你点、滚、按键、打开东西就停下,不会和你抢。结果里打开文件夹也是先定位再展开(或进入)它。刷新、「一轮结束」和切换「显示隐藏文件」会重搜;搜索词和结果不存进会话状态,页面重建后是空的。iPhone 的系统返回:结果里打开的预览或属性页返回到结果,结果本身不算一级。
|
|
21
22
|
- **文件内查找**(`0.8.0`):只找打开的这个文本文件。Mac 在侧栏预览或独立窗口里按 ⌘F,iPhone 在预览头部「⋯」菜单里点「查找」,预览头部下面出现查找条:输入框、「3/17」、上一个、下一个、完成。不分大小写,高亮全部匹配,当前这一处颜色更深并滚到可见区;回车或 ⌘G 下一个,Shift+回车或 ⇧⌘G 上一个(首尾循环);Esc 或「完成」关闭。最多标 10000 处,超过写「10000+」,导航只在前 10000 处里走。图片、二进制、读取中、读不到的文件没有查找(⌘F 不拦,菜单里没有这一项)。文件内容变了(刷新、Agent 一轮结束)时查找词和查找条留着、重新找,当前这一处取离原来最近的;打开别的文件、换了根目录、关预览,查找条一并关闭。高亮用浏览器的 Custom Highlight API,不支持的环境只计数、上一个下一个和滚动,不标颜色。有长行的文件(和代码上色共用的门槛:有一行超过 5000 字,如压缩过的 JS)不标高亮,只计数、上一个下一个和滚动:长行里注册高亮会让浏览器同步重画整行,页面会卡死(实测 50 KiB 单行超过 20 秒)。当前这一处文字用正文色,不显示代码着色。
|
|
23
|
+
- **worktree 会话的标题**(`0.8.1`):Coda 的 worktree 目录以一串 UUID 命名,只看目录名认不出项目。会话的工作目录是 worktree 时,根目录标题(Mac 目录树上方、iPhone 顶部工具条、图标视图头部)写成「项目名 worktree-编号」,如 `ActaView worktree-c037`:项目名是 Coda 里这个会话所属项目的名字(粗体;默认就是原仓库的文件夹名,在 Coda 里改过名字时显示改后的),后缀用常规字重、浅灰、小一号;编号是目录名(UUID)的前 4 位,目录名不是 UUID 时取整个目录名。放不下时依次:后缀缩成 `wt-编号`(完整写法超过可用宽度的 90% 就缩,不贴边),再把项目名从中间省略(至少留 2 个字,`wt-编号` 不动),最后整段从尾部省略;拖侧栏、转屏时重算。Mac 目录树的标题比以前大一号(普通文件夹名也是);悬停标题显示完整路径,属性页的名称和路径不变;iPhone 的系统返回里是纯文字的完整写法。项目名从 Coda 的项目列表取(会话详情里的项目 id,加上 `agents` 回答里的项目列表,这两样都不是文档写明的接口,集中在 `lib/root.mjs` 一处;列表缓存一分钟,查不到 id 时重取),不读 git 元数据,也不读工作目录之外的任何文件;取不到、或者会话的工作目录不是 worktree 时,照旧显示文件夹名。
|
|
22
24
|
- 切换会话时换成新会话的内容,切回来恢复展开状态和滚动位置。
|
|
23
25
|
- 右键(Mac)或长按(iPhone)一行:添加到聊天、复制相对路径、复制绝对路径、属性。「添加到聊天」把相对路径接在输入框已有文字后面;指向工作目录外或已失效的链接、不能打开的条目没有这一项。成功时底部提示「已添加到输入框」,约 2 秒消失;写不进去时改为复制,提示「没能写入输入框,已复制」;剪贴板也写不进去时提示「没能写入,也没能复制」。
|
|
24
26
|
- **选中文字右键(只有 Mac)**:在文件预览(侧栏和独立窗口)里选中文字后右键,有「添加到聊天(内容)」「添加到聊天(位置)」「复制」。位置是 `src/app.ts:12-18`,只选一行时是 `src/app.ts:12`,只精确到行。选中的内容太长放不进一条消息时直接复制,提示「选中内容太长,已复制」。iPhone 用系统自带的选区菜单,不加这一项。
|
package/lib/media.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// 音视频和图片的本机流式服务(设计见 docs/design/phase-3.md 第 20 节):页面的 <audio>、<video>、<img> 指向 coda-view://service/media/<口令>/<相对路径>。
|
|
2
|
+
// 口令由主模块按视图发,映射到那个视图当时的根目录;根目录变了、换会话、视图关了就作废。只接 GET、HEAD,只读文件,路径校验同 READ。
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { open } from 'node:fs/promises';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { ErrorCode, mediaOf } from '../view/protocol.mjs';
|
|
8
|
+
import { fromFsError, resolveInRoot } from './paths.mjs';
|
|
9
|
+
|
|
10
|
+
const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
|
|
11
|
+
|
|
12
|
+
const STATUS = {
|
|
13
|
+
[ErrorCode.INVALID_PATH]: 400, [ErrorCode.OUTSIDE_ROOT]: 403, [ErrorCode.DENIED]: 403,
|
|
14
|
+
[ErrorCode.NOT_FOUND]: 404, [ErrorCode.NOT_DIR]: 404, [ErrorCode.NOT_FILE]: 404,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// 'bytes=a-b' | 'bytes=a-' | 'bytes=-n' → { start, end }(含 end);不认得的写法(含多段)当作没带 Range,越界返回 'bad'。
|
|
18
|
+
function parseRange(header, size) {
|
|
19
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(header ?? '');
|
|
20
|
+
if (!m || (m[1] === '' && m[2] === '')) return null;
|
|
21
|
+
let start, end;
|
|
22
|
+
if (m[1] === '') { start = Math.max(0, size - Number(m[2])); end = size - 1; } else {
|
|
23
|
+
start = Number(m[1]); end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
|
|
24
|
+
}
|
|
25
|
+
return start > end || start >= size ? 'bad' : { start, end };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createMedia() {
|
|
29
|
+
const grants = new Map(); // 口令 → 根目录
|
|
30
|
+
|
|
31
|
+
const grant = root => {
|
|
32
|
+
const token = randomUUID().replaceAll('-', '');
|
|
33
|
+
grants.set(token, root);
|
|
34
|
+
return token;
|
|
35
|
+
};
|
|
36
|
+
const revoke = token => { if (token) grants.delete(token); };
|
|
37
|
+
|
|
38
|
+
async function handler(req, res) {
|
|
39
|
+
const end = status => { res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' }); res.end(); };
|
|
40
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return end(405);
|
|
41
|
+
const [, token, ...rest] = new URL(req.url, 'http://x').pathname.split('/');
|
|
42
|
+
const root = grants.get(token);
|
|
43
|
+
if (root === undefined) return end(404);
|
|
44
|
+
let path;
|
|
45
|
+
try { path = rest.map(decodeURIComponent).join('/'); } catch { return end(400); }
|
|
46
|
+
const media = mediaOf(path);
|
|
47
|
+
if (!media?.preview) return end(415);
|
|
48
|
+
let handle;
|
|
49
|
+
try {
|
|
50
|
+
handle = await open(await resolveInRoot(root, path), constants.O_RDONLY | NOFOLLOW);
|
|
51
|
+
const info = await handle.stat();
|
|
52
|
+
if (!info.isFile()) return end(404);
|
|
53
|
+
const { size } = info;
|
|
54
|
+
// 不缓存:每次都问(no-cache);内容没变回 304,续传带的 If-Range 对不上就整份重来。
|
|
55
|
+
const etag = `"${size}-${Math.floor(info.mtimeMs)}"`;
|
|
56
|
+
const headers = { 'content-type': media.type, 'accept-ranges': 'bytes', etag, 'cache-control': 'no-cache' };
|
|
57
|
+
if (String(req.headers['if-none-match'] ?? '').split(',').some(tag => tag.trim().replace(/^W\//, '') === etag)) {
|
|
58
|
+
res.writeHead(304, { etag, 'cache-control': 'no-cache' });
|
|
59
|
+
return res.end();
|
|
60
|
+
}
|
|
61
|
+
const ifRange = req.headers['if-range'];
|
|
62
|
+
const range = ifRange && ifRange !== etag ? null : parseRange(req.headers.range, size);
|
|
63
|
+
if (range === 'bad') { res.writeHead(416, { 'content-range': `bytes */${size}` }); return res.end(); }
|
|
64
|
+
const [status, start, last] = range ? [206, range.start, range.end] : [200, 0, size - 1];
|
|
65
|
+
if (range) headers['content-range'] = `bytes ${start}-${last}/${size}`;
|
|
66
|
+
headers['content-length'] = String(size === 0 ? 0 : last - start + 1);
|
|
67
|
+
res.writeHead(status, headers);
|
|
68
|
+
if (req.method === 'HEAD' || size === 0) return res.end();
|
|
69
|
+
// 客户端中途断开:pipeline 随 res 关闭销毁读流。
|
|
70
|
+
await pipeline(handle.createReadStream({ start, end: last, autoClose: false }), res).catch(() => {});
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// 被 O_NOFOLLOW 拒绝说明校验后被换成了链接,同读文本按越界处理。
|
|
73
|
+
const code = NOFOLLOW && (error?.code === 'ELOOP' || error?.code === 'EMLINK') ? ErrorCode.OUTSIDE_ROOT : fromFsError(error).code;
|
|
74
|
+
if (!res.headersSent) end(STATUS[code] ?? 500); else res.destroy();
|
|
75
|
+
} finally { await handle?.close().catch(() => {}); }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { handler, grant, revoke };
|
|
79
|
+
}
|
package/lib/root.mjs
CHANGED
|
@@ -1,26 +1,71 @@
|
|
|
1
|
-
// 从会话取根目录。这是唯一读取 `threads/<id>` 返回结构(checkout
|
|
1
|
+
// 从会话取根目录。这是唯一读取 `threads/<id>` 返回结构(checkout)和 `agents` 返回结构(projects)的地方,它们都不是文档写明的契约。
|
|
2
2
|
import { realpath, stat } from 'node:fs/promises';
|
|
3
3
|
import { RootState } from '../view/protocol.mjs';
|
|
4
4
|
|
|
5
|
-
export const NO_ROOT = Object.freeze({ state: RootState.NONE, path: null });
|
|
5
|
+
export const NO_ROOT = Object.freeze({ state: RootState.NONE, path: null, project: null });
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
// project 不是根目录的身份(保存、恢复、换根都只看路径),但变了页面要重画标题,所以算进来。
|
|
8
|
+
export const sameRoot = (a, b) => a?.state === b?.state && a?.path === b?.path && (a?.project ?? null) === (b?.project ?? null);
|
|
9
|
+
|
|
10
|
+
// worktree 的项目名:Coda 里这个会话所属项目的名字。Coda 的 worktree 目录以 UUID 命名,只看目录名认不出项目。
|
|
11
|
+
// 项目 id 是会话详情里 checkout 的 projectId(缺了看 detail.thread.projectId),名字查 `agents` 回答里的 projects([{ id, name }])。
|
|
12
|
+
// 会话详情 `threads/<id>` 的回答结构是 { thread: { …, projectId }, draft, checkout, … }:thread 是详情里的一个字段,checkout 和它并列,不是 thread 的子字段。
|
|
13
|
+
// 项目名默认是原仓库的文件夹名;在 Coda 里改过名字时显示改后的。不读任何文件:项目名不来自工作目录之外的东西(设计第 19.7 节)。
|
|
14
|
+
// 取不到(没有 id、接口失败、列表里没有这个 id、名字为空)都是 null,页面退回显示文件夹名;这里从不抛:
|
|
15
|
+
// queryRoot 抛出的意思是「保留上一次的根目录」,项目名取不到不该触发它。
|
|
16
|
+
// 项目列表按机器缓存(WeakMap:一个 coda 一份),很少变:超过 MAX_AGE 或查不到这个 id 时重取,两次请求之间至少隔 MISS_AGE(接口失败也算一次),不会反复请求;同时发起的查询共用一次请求。
|
|
17
|
+
const MAX_AGE = 60_000, MISS_AGE = 5_000, NAME_LIMIT = 256;
|
|
18
|
+
const caches = new WeakMap(); // coda → { names: Map(id → name) | null, at: 上次请求的时间, pending: 在途的请求 | null }
|
|
19
|
+
|
|
20
|
+
// 名字:去掉首尾空白,空的、含控制字符的不用,太长的按码点截断。
|
|
21
|
+
function cleanName(name) {
|
|
22
|
+
if (typeof name !== 'string') return null;
|
|
23
|
+
const text = name.trim();
|
|
24
|
+
if (!text || /\p{Cc}/u.test(text)) return null;
|
|
25
|
+
return Array.from(text).slice(0, NAME_LIMIT).join('');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function fetchNames(coda, cache, now) {
|
|
29
|
+
cache.at = now();
|
|
30
|
+
try {
|
|
31
|
+
const reply = await coda.api('agents');
|
|
32
|
+
const names = new Map();
|
|
33
|
+
for (const project of Array.isArray(reply?.projects) ? reply.projects : []) {
|
|
34
|
+
if (typeof project?.id === 'string' && project.id) names.set(project.id, cleanName(project.name));
|
|
35
|
+
}
|
|
36
|
+
cache.names = names;
|
|
37
|
+
} catch { /* 取不到:保留上一次的列表,名字退回文件夹名 */ }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function projectNameOf(coda, projectId, now) {
|
|
41
|
+
if (typeof projectId !== 'string' || !projectId) return null;
|
|
42
|
+
try {
|
|
43
|
+
let cache = caches.get(coda);
|
|
44
|
+
if (!cache) caches.set(coda, cache = { names: null, at: -Infinity, pending: null });
|
|
45
|
+
const age = now() - cache.at, stale = !cache.names || age >= MAX_AGE || (!cache.names.has(projectId) && age >= MISS_AGE);
|
|
46
|
+
if (stale) await (cache.pending ??= fetchNames(coda, cache, now).finally(() => { cache.pending = null; }));
|
|
47
|
+
else if (cache.pending) await cache.pending;
|
|
48
|
+
return cache.names?.get(projectId) ?? null;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
8
53
|
|
|
9
54
|
// checkout.state 是 preparing、ready、failed。failed 没有可看的目录,按 none;
|
|
10
55
|
// ready 但目录已不在(归档后工作树被回收)是 gone。
|
|
11
56
|
// 查询失败(接口出错、读目录权限)直接抛出,由调用方保留上一次的结果。
|
|
12
|
-
export async function queryRoot(coda, session) {
|
|
57
|
+
export async function queryRoot(coda, session, { now = Date.now } = {}) {
|
|
13
58
|
if (!session) return NO_ROOT;
|
|
14
|
-
const
|
|
15
|
-
const checkout =
|
|
59
|
+
const detail = await coda.api(`threads/${encodeURIComponent(session)}`);
|
|
60
|
+
const checkout = detail?.checkout;
|
|
16
61
|
if (!checkout || typeof checkout !== 'object') return NO_ROOT;
|
|
17
|
-
if (checkout.state === 'preparing') return { state: RootState.PREPARING, path: null };
|
|
62
|
+
if (checkout.state === 'preparing') return { state: RootState.PREPARING, path: null, project: null };
|
|
18
63
|
if (checkout.state !== 'ready' || typeof checkout.path !== 'string' || !checkout.path) return NO_ROOT;
|
|
19
64
|
try {
|
|
20
65
|
const real = await realpath(checkout.path);
|
|
21
|
-
if ((await stat(real)).isDirectory()) return { state: RootState.READY, path: real };
|
|
66
|
+
if ((await stat(real)).isDirectory()) return { state: RootState.READY, path: real, project: checkout.kind === 'worktree' ? await projectNameOf(coda, checkout.projectId ?? detail.thread?.projectId, now) : null };
|
|
22
67
|
} catch (error) {
|
|
23
68
|
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;
|
|
24
69
|
}
|
|
25
|
-
return { state: RootState.GONE, path: checkout.path };
|
|
70
|
+
return { state: RootState.GONE, path: checkout.path, project: null };
|
|
26
71
|
}
|
package/main.mjs
CHANGED
|
@@ -4,10 +4,11 @@ import { createListing, listDirectory } from './lib/tree.mjs';
|
|
|
4
4
|
import { readChunk } from './lib/content.mjs';
|
|
5
5
|
import { addText } from './lib/draft.mjs';
|
|
6
6
|
import { dirSize, statPath } from './lib/info.mjs';
|
|
7
|
+
import { createMedia } from './lib/media.mjs';
|
|
7
8
|
import { createSearcher } from './lib/search.mjs';
|
|
8
9
|
import { NO_ROOT, queryRoot, sameRoot } from './lib/root.mjs';
|
|
9
10
|
import {
|
|
10
|
-
ErrorCode, MESSAGE_LIMIT, REQUEST_ID_MAX, ReplyOf, RootState, Type, fail, messageSize,
|
|
11
|
+
EntryKind, ErrorCode, MESSAGE_LIMIT, REQUEST_ID_MAX, ReplyOf, RootState, Type, fail, messageSize,
|
|
11
12
|
} from './view/protocol.mjs';
|
|
12
13
|
|
|
13
14
|
const POLL_MS = 2000;
|
|
@@ -22,7 +23,10 @@ const sessionOfFile = context => {
|
|
|
22
23
|
|
|
23
24
|
// options 只给测试用,运行时不传:makeListing 换成带假文件系统的读取状态;sizeLimits 调文件夹大小的项数、用时上限;searchLimits 调文件名搜索的条数、项数、用时、队列字节、回答字节上限。
|
|
24
25
|
export function activate(coda, { makeListing = createListing, sizeLimits = {}, searchLimits = {} } = {}) {
|
|
25
|
-
|
|
26
|
+
// 音视频和图片的本机流式服务,所有视图共用一个,口令按视图发。宿主没有这个接口(旧版本)或登记失败时 service.on 为假,页面退回分块读取。
|
|
27
|
+
const media = createMedia(), service = { on: true };
|
|
28
|
+
try { Promise.resolve(coda.services.register('media', media.handler)).catch(() => { service.on = false; }); } catch { service.on = false; }
|
|
29
|
+
const options = { makeListing, sizeLimits, searchLimits, media, service };
|
|
26
30
|
coda.views.register('files', { open: view => serve(coda, view, sessionOfTree, options) });
|
|
27
31
|
coda.views.register('file', { open: view => serve(coda, view, sessionOfFile, options) });
|
|
28
32
|
}
|
|
@@ -30,7 +34,7 @@ export function activate(coda, { makeListing = createListing, sizeLimits = {}, s
|
|
|
30
34
|
const validRequestId = id => (typeof id === 'string' && id.length <= REQUEST_ID_MAX) || Number.isSafeInteger(id);
|
|
31
35
|
const errorOf = error => (error?.protocol ? { code: error.code, message: error.message } : { code: ErrorCode.IO, message: '读取失败' });
|
|
32
36
|
|
|
33
|
-
function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits }) {
|
|
37
|
+
function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, media, service }) {
|
|
34
38
|
// 代次:每换一次会话加 1,所有异步出口回来后都要核对。
|
|
35
39
|
const s = {
|
|
36
40
|
session: sessionOf(view.context), generation: 1, root: NO_ROOT, sent: null,
|
|
@@ -45,8 +49,10 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits })
|
|
|
45
49
|
const stopSizing = () => { sizing?.abort.abort(); sizing = null; };
|
|
46
50
|
// 文件名搜索:同样每个视图同时只有一次,槽、待启动位和排空屏障都在 lib/search.mjs 的 searcher 里。
|
|
47
51
|
const searcher = createSearcher(s.listing, searchLimits);
|
|
48
|
-
//
|
|
49
|
-
|
|
52
|
+
// 媒体口令:这个视图第一次要放音视频或图片时发,映射到当时的根目录。
|
|
53
|
+
let token = null;
|
|
54
|
+
// 换会话、根目录变化、视图关闭:读取状态丢弃,统计和搜索也停,媒体口令作废。
|
|
55
|
+
const resetReads = () => { s.listing.clear(); stopSizing(); searcher.clear(); media.revoke(token); token = null; };
|
|
50
56
|
|
|
51
57
|
function post(message) {
|
|
52
58
|
if (s.closed) return;
|
|
@@ -62,7 +68,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits })
|
|
|
62
68
|
const postSession = () => post({ type: Type.SESSION, generation: s.generation, session: s.session });
|
|
63
69
|
function postRoot() {
|
|
64
70
|
s.sent = s.root;
|
|
65
|
-
post({ type: Type.ROOT, generation: s.generation, state: s.root.state, path: s.root.path });
|
|
71
|
+
post({ type: Type.ROOT, generation: s.generation, state: s.root.state, path: s.root.path, project: s.root.project });
|
|
66
72
|
}
|
|
67
73
|
|
|
68
74
|
// 重新查询根目录。结果和上次推给页面的不同才推送;查询失败保留上一次的。
|
|
@@ -119,6 +125,13 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits })
|
|
|
119
125
|
} finally { if (sizing === mine) sizing = null; }
|
|
120
126
|
},
|
|
121
127
|
[Type.SEARCH]: (message, { root, valid, generation, requestId }) => searcher.search(message, { root, valid, generation, requestId }),
|
|
128
|
+
async [Type.MEDIA](message, { root, valid }) {
|
|
129
|
+
const info = await statPath(s.listing, root, message.path);
|
|
130
|
+
if (info.kind !== EntryKind.FILE) throw fail(ErrorCode.NOT_FILE, '不是文件');
|
|
131
|
+
if (!valid()) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
|
|
132
|
+
if (service.on) token ??= media.grant(root);
|
|
133
|
+
return { token, size: info.size, mtimeMs: info.mtimeMs }; // token 为 null:没有流式服务,页面退回分块读取
|
|
134
|
+
},
|
|
122
135
|
async [Type.ADD_TEXT](message, { generation }) {
|
|
123
136
|
if (!s.session) throw fail(ErrorCode.NO_ROOT, '没有会话');
|
|
124
137
|
return await addText(coda, s.session, message, { valid: () => !stale(generation) }) ? {} : null;
|
|
@@ -164,7 +177,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits })
|
|
|
164
177
|
if (stale(message.generation)) return undefined;
|
|
165
178
|
s.listing.detach();
|
|
166
179
|
return refreshRoot();
|
|
167
|
-
case Type.LIST: case Type.READ: case Type.STAT: case Type.DIR_SIZE: case Type.ADD_TEXT: case Type.SEARCH: return request(message);
|
|
180
|
+
case Type.LIST: case Type.READ: case Type.STAT: case Type.DIR_SIZE: case Type.ADD_TEXT: case Type.SEARCH: case Type.MEDIA: return request(message);
|
|
168
181
|
case Type.DIR_SIZE_CANCEL: return cancelSizing(message);
|
|
169
182
|
case Type.SEARCH_CANCEL: return cancelSearch(message);
|
|
170
183
|
}
|
package/package.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"id": "resource-manager",
|
|
3
3
|
"name": "@coda-console/resource-manager",
|
|
4
4
|
"displayName": "资源管理器",
|
|
5
|
-
"description": "
|
|
6
|
-
"version": "0.
|
|
5
|
+
"description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本、图片、音频和视频,把路径交给对话。",
|
|
6
|
+
"version": "0.9.0",
|
|
7
7
|
"categories": ["工作流程"],
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"repository": {
|
package/view/app.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 资源管理器的页面入口:消息收发、状态保留、工具栏和「更多」菜单、图标视图的进入和返回、搜索。状态在 model.mjs,渲染在 tree.mjs、grid.mjs、preview.mjs 和 info.mjs,菜单和提示在 menu.mjs 和 hint.mjs,滚动位置的恢复在 restore.mjs,
|
|
2
2
|
// 文件名搜索的状态在 search.mjs、搜索框在 searchbar.mjs、「在目录中显示」在 locate.mjs。
|
|
3
|
-
import { EXIT, paintBar } from './bar.mjs';
|
|
3
|
+
import { EXIT, paintBar, refitBar } from './bar.mjs';
|
|
4
4
|
import { createChat } from './chat.mjs';
|
|
5
5
|
import { connect } from './connection.mjs';
|
|
6
6
|
import { infoText, sortName } from './format.mjs';
|
|
@@ -19,7 +19,8 @@ import { createRestore, createTrail } from './restore.mjs';
|
|
|
19
19
|
import { createSearch } from './search.mjs';
|
|
20
20
|
import { mountSearchbar } from './searchbar.mjs';
|
|
21
21
|
import { browseAction, previewAction } from './keys.mjs';
|
|
22
|
-
import {
|
|
22
|
+
import { rootLabel } from './rootname.mjs';
|
|
23
|
+
import { mountTree } from './tree.mjs';
|
|
23
24
|
|
|
24
25
|
const coda = window.coda;
|
|
25
26
|
const $ = id => document.getElementById(id);
|
|
@@ -136,6 +137,7 @@ function clearSearch() {
|
|
|
136
137
|
}
|
|
137
138
|
const preview = mountPreview($('preview'), {
|
|
138
139
|
read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
|
|
140
|
+
media: path => conn.link.call('media', { path }),
|
|
139
141
|
// iPhone 预览头部右边的 ⋯(刷新、复制路径):顶部工具条在预览时只有「返回」,只留头部一行标题
|
|
140
142
|
actions: isIOS ? [{ label: '更多', icon: 'ellipsis', run: (_, button) => toggleMore(button) }] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
|
|
141
143
|
back: isIOS ? null : closePreview,
|
|
@@ -374,7 +376,7 @@ const toolbarItems = () => infoOpen ? [] : hasToolbar
|
|
|
374
376
|
// 预览时和属性页一样只留返回(竖屏整条不显示):标题和 ⋯ 在预览头部,⋯ 里只有刷新和复制路径。
|
|
375
377
|
// 属性页上只留返回:竖屏有原生导航栏,整条工具条不显示;横屏导航栏隐藏,页面自己给返回(显示与否都由 style.css 的横屏媒体查询决定)。
|
|
376
378
|
const MORE = { id: 'more', label: '更多', kind: 'button', glyph: 'ellipsis', iconOnly: true, menu: true };
|
|
377
|
-
const phoneItems = () => infoOpen || mode() === 'preview' ? [EXIT] : [EXIT, { kind: 'title', label: model.ready ? dirTitle() : '' }, MORE];
|
|
379
|
+
const phoneItems = () => infoOpen || mode() === 'preview' ? [EXIT] : [EXIT, { kind: 'title', label: model.ready ? dirTitle() : '', ...(model.ready && titleIsRoot() && model.root.project ? { root: { path: model.root.path, project: model.root.project } } : {}) }, MORE];
|
|
378
380
|
// 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
|
|
379
381
|
let lastItems = '';
|
|
380
382
|
function syncToolbar() {
|
|
@@ -647,14 +649,15 @@ function landed() {
|
|
|
647
649
|
// ---- 上一层:iPhone 用原生返回,路径只在这里声明 ----
|
|
648
650
|
// 路径是上层的标题,由远到近,不含当前页:图标视图在 a/b 是 [根目录名, 'a'];列表视图没有。属性页、预览各多一层当前页(要回到的那一页):列表视图是 '资源管理器',图标视图是当前目录名。
|
|
649
651
|
// 预览开着是 opened 不为空、且根目录就绪;没就绪时页面是说明区,路径为空。
|
|
650
|
-
//
|
|
652
|
+
// 标题是当前目录名:根目录是根目录名(worktree 是「项目名-wt-编号」,这里给完整写法,不省略:文字由客户端排版)。
|
|
651
653
|
// 搜索时结果盖住了图标视图的目录:标题是根目录名。
|
|
652
|
-
const
|
|
654
|
+
const titleIsRoot = () => model.cwd === '' || model.view !== View.ICONS || searching();
|
|
655
|
+
const dirTitle = () => (titleIsRoot() ? rootLabel(model.root) : model.cwd.slice(model.cwd.lastIndexOf('/') + 1));
|
|
653
656
|
const previewOpen = () => model.ready && model.opened !== null;
|
|
654
657
|
// 搜索本身不是一级:搜索模式下图标视图的目录层级不声明(搜索盖住了它们),从结果打开的预览和属性页要回到的那一页叫「搜索」(第 18.5 节的表)。
|
|
655
658
|
function backPath() {
|
|
656
659
|
const icons = model.view === View.ICONS && model.ready && !searching();
|
|
657
|
-
const upper = icons && model.cwd !== '' ? [
|
|
660
|
+
const upper = icons && model.cwd !== '' ? [rootLabel(model.root), ...model.cwd.split('/').slice(0, -1)] : [];
|
|
658
661
|
const here = searching() ? '搜索' : icons ? dirTitle() : '资源管理器';
|
|
659
662
|
return [...upper, ...(infoOpen ? [here] : []), ...(previewOpen() ? [here] : [])];
|
|
660
663
|
}
|
|
@@ -757,7 +760,7 @@ function onChanged(data) {
|
|
|
757
760
|
search.research(); // 搜索期间目录模型照常刷新;有搜索词就重搜,旧结果留到新结果来
|
|
758
761
|
}
|
|
759
762
|
|
|
760
|
-
const remeasure = () => { tree.remeasure(); grid.remeasure(); hits.remeasure(); };
|
|
763
|
+
const remeasure = () => { tree.remeasure(); grid.remeasure(); hits.remeasure(); refitBar($('bar')); };
|
|
761
764
|
remeasure();
|
|
762
765
|
quiet(() => coda.on('theme', remeasure));
|
|
763
766
|
render();
|
package/view/bar.mjs
CHANGED
|
@@ -1,16 +1,32 @@
|
|
|
1
1
|
// 页内工具条:没有 coda.toolbar 的平台(iPhone)用,两个页面共用,按钮由页面给。
|
|
2
2
|
// 「返回」只在横屏出现(导航栏隐藏时),显示与否由 style.css 的媒体查询决定,这里一律画出来。
|
|
3
|
-
// 项:{ id, label, kind: 'button' | 'toggle' | 'title', glyph?, iconOnly?, on?, menu? };menu 的按钮打开菜单。title 不是按钮,只显示 label。
|
|
3
|
+
// 项:{ id, label, kind: 'button' | 'toggle' | 'title', glyph?, iconOnly?, on?, menu?, root? };menu 的按钮打开菜单。title 不是按钮,只显示 label。
|
|
4
|
+
// title 带 root({ path, project },worktree 的根目录)时,label 是完整写法,画出来按标题现在的宽度省略(第 19 节),宽度变了(旋转、字号)重算;不带的交给 CSS 截断。
|
|
4
5
|
// 有 glyph 画图标;iconOnly 的只留图标,label 当可访问名称;否则图标后面跟文字(没有 glyph 就只有文字)。
|
|
5
6
|
import { icon } from './icons.mjs';
|
|
7
|
+
import { paintRootName } from './rootname.mjs';
|
|
6
8
|
|
|
7
9
|
export const EXIT = { id: 'exit', label: '返回', kind: 'button', glyph: 'back' };
|
|
8
10
|
|
|
11
|
+
const fitted = new WeakMap(); // 工具条 → { title, root, observer }:现在画着的要省略的标题
|
|
12
|
+
|
|
13
|
+
// 按现在的宽度重新省略标题(字号变了时页面调用);没有要省略的标题什么都不做。
|
|
14
|
+
export function refitBar(el) {
|
|
15
|
+
const entry = fitted.get(el);
|
|
16
|
+
if (entry) paintRootName(entry.title, entry.root);
|
|
17
|
+
}
|
|
18
|
+
|
|
9
19
|
// act(id, button):button 是被点的元素,菜单要用它定位。
|
|
10
20
|
export function paintBar(el, items, act) {
|
|
21
|
+
fitted.get(el)?.observer?.disconnect();
|
|
22
|
+
fitted.delete(el);
|
|
11
23
|
el.hidden = false;
|
|
12
24
|
el.replaceChildren(...items.map(item => {
|
|
13
|
-
if (item.kind === 'title')
|
|
25
|
+
if (item.kind === 'title') {
|
|
26
|
+
const title = Object.assign(document.createElement('span'), { className: 'bar-title grow truncate', textContent: item.label });
|
|
27
|
+
if (item.root) fitted.set(el, { title, root: item.root, observer: null });
|
|
28
|
+
return title;
|
|
29
|
+
}
|
|
14
30
|
const button = document.createElement('button');
|
|
15
31
|
if (item.glyph) button.append(icon(item.glyph, 20));
|
|
16
32
|
if (item.iconOnly) button.setAttribute('aria-label', item.label);
|
|
@@ -23,4 +39,8 @@ export function paintBar(el, items, act) {
|
|
|
23
39
|
button.addEventListener('click', () => act(item.id, button));
|
|
24
40
|
return button;
|
|
25
41
|
}));
|
|
42
|
+
const entry = fitted.get(el);
|
|
43
|
+
if (!entry) return;
|
|
44
|
+
paintRootName(entry.title, entry.root); // 标题已在页面里,有了宽度
|
|
45
|
+
if (typeof ResizeObserver === 'function') (entry.observer = new ResizeObserver(() => paintRootName(entry.title, entry.root))).observe(entry.title);
|
|
26
46
|
}
|
package/view/file-app.mjs
CHANGED
|
@@ -41,6 +41,7 @@ const press = mountPress({ consumed: menu.consumed }); // 按下反馈:刷新
|
|
|
41
41
|
const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint });
|
|
42
42
|
const preview = mountPreview($('preview'), {
|
|
43
43
|
read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
|
|
44
|
+
media: path => conn.link.call('media', { path }),
|
|
44
45
|
selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
|
|
45
46
|
consumed: menu.consumed,
|
|
46
47
|
});
|
package/view/format.mjs
CHANGED
|
@@ -11,6 +11,12 @@ export function formatSize(bytes) {
|
|
|
11
11
|
|
|
12
12
|
const two = n => String(n).padStart(2, '0');
|
|
13
13
|
|
|
14
|
+
// 音视频时长:3:07,不到一小时不写小时。
|
|
15
|
+
export function formatDuration(seconds) {
|
|
16
|
+
const total = Math.round(seconds), hours = Math.floor(total / 3600), minutes = Math.floor(total % 3600 / 60);
|
|
17
|
+
return hours > 0 ? `${hours}:${two(minutes)}:${two(total % 60)}` : `${minutes}:${two(total % 60)}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
14
20
|
// 相对格式,按本地时间:今天 14:05,今年 11月4日,往年 2025年3月。
|
|
15
21
|
export function formatDate(ms, now) {
|
|
16
22
|
const date = new Date(ms), current = new Date(now);
|
package/view/grid.mjs
CHANGED
|
@@ -6,7 +6,8 @@ import { mountGestures } from './gestures.mjs';
|
|
|
6
6
|
import { icon, iconFor } from './icons.mjs';
|
|
7
7
|
import { joinPath } from './model.mjs';
|
|
8
8
|
import { EntryKind, isHidden } from './protocol.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { paintRootName, rootLabel } from './rootname.mjs';
|
|
10
|
+
import { TITLES } from './tree.mjs';
|
|
10
11
|
|
|
11
12
|
const OVERSCAN = 2; // 上下多画几行
|
|
12
13
|
|
|
@@ -131,7 +132,7 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
|
|
|
131
132
|
spacer.append(win);
|
|
132
133
|
body.append(spacer);
|
|
133
134
|
el.replaceChildren(head, body);
|
|
134
|
-
let cells = [], layout = layoutOf([], 1), cellW = 72, cellH = 76, noteH = 32, measuredWidth = -1, headKey = null;
|
|
135
|
+
let cells = [], layout = layoutOf([], 1), cellW = 72, cellH = 76, noteH = 32, measuredWidth = -1, headKey = null, headName = null;
|
|
135
136
|
|
|
136
137
|
// 探针放在 win 里:量到的是单元格和说明行在真实结构里的尺寸,两种行高不同。
|
|
137
138
|
const measure = () => {
|
|
@@ -147,16 +148,20 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
|
|
|
147
148
|
};
|
|
148
149
|
const columns = () => Math.max(1, Math.floor(body.clientWidth / cellW));
|
|
149
150
|
|
|
150
|
-
//
|
|
151
|
+
// 头部:返回、当前目录名。在根目录时没有返回键,标题是根目录名(第 19 节:worktree 写成「项目名-wt-编号」,放不下时按宽度省略,悬停是完整路径)。
|
|
151
152
|
function paintHead() {
|
|
152
|
-
const
|
|
153
|
-
const
|
|
153
|
+
const atRoot = model.cwd === '', name = atRoot ? (model.ready ? rootLabel(model.root) : '') : model.cwd.slice(model.cwd.lastIndexOf('/') + 1);
|
|
154
|
+
const project = atRoot && model.ready ? model.root.project : null;
|
|
155
|
+
const key = `${model.cwd}\n${name}\n${project ? model.root.path : ''}`;
|
|
154
156
|
head.hidden = !handlers.back || name === '';
|
|
155
|
-
if (key
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
h('
|
|
159
|
-
|
|
157
|
+
if (key !== headKey) {
|
|
158
|
+
headKey = key;
|
|
159
|
+
headName = h('div', { class: 'gname-head truncate', title: project ? model.root.path : model.cwd || name }, name);
|
|
160
|
+
head.replaceChildren(...(handlers.back && model.cwd !== '' ? [h('button', { class: 'icon', 'aria-label': '返回', title: '返回', onclick: handlers.back }, icon('back', 18))] : []),
|
|
161
|
+
h('span', { class: 'ghico', 'aria-hidden': 'true' }, icon('folder', 22)),
|
|
162
|
+
h('div', { class: 'grow' }, headName));
|
|
163
|
+
}
|
|
164
|
+
if (project && !head.hidden) paintRootName(headName, model.root); // 头部显示出来、有了宽度才能省略;宽度变了(relayout)重算
|
|
160
165
|
}
|
|
161
166
|
|
|
162
167
|
function paint() {
|
|
@@ -203,6 +208,7 @@ export function mountGrid(el, model, handlers, { draggable = true, longPress = f
|
|
|
203
208
|
}
|
|
204
209
|
function relayout() {
|
|
205
210
|
if (columns() !== layout.cols) rebuild();
|
|
211
|
+
paintHead();
|
|
206
212
|
paint();
|
|
207
213
|
}
|
|
208
214
|
|
package/view/model.mjs
CHANGED
|
@@ -94,10 +94,11 @@ export class Model {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
// 只换根目录状态,不动会话状态;ready 时重新取全部。
|
|
97
|
-
|
|
97
|
+
// project:worktree 的原仓库文件夹名(根目录标题用),不是根目录的身份。
|
|
98
|
+
onRoot({ generation, state, path, project = null }) {
|
|
98
99
|
if (generation !== this.link.generation) return null;
|
|
99
100
|
if (state === RootState.READY) this.#identify(path);
|
|
100
|
-
this.root = { state, path };
|
|
101
|
+
this.root = { state, path, project: typeof project === 'string' && project ? project : null };
|
|
101
102
|
this.onChange();
|
|
102
103
|
return state === RootState.READY ? this.refresh() : Promise.resolve();
|
|
103
104
|
}
|
package/view/preview.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
|
|
2
2
|
import { h } from './dom.mjs';
|
|
3
3
|
import { createFind } from './find.mjs';
|
|
4
|
-
import { formatSize } from './format.mjs';
|
|
4
|
+
import { formatDuration, formatSize } from './format.mjs';
|
|
5
5
|
import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
|
|
6
6
|
import { icon, iconFor } from './icons.mjs';
|
|
7
7
|
import { languageOf } from './languages.mjs';
|
|
8
|
-
import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType } from './protocol.mjs';
|
|
8
|
+
import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType, mediaOf } from './protocol.mjs';
|
|
9
9
|
import { clippedSelection, linesOf } from './selection.mjs';
|
|
10
10
|
|
|
11
11
|
function fromBase64(data) {
|
|
@@ -63,13 +63,15 @@ export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (t
|
|
|
63
63
|
// 页面只负责入口:canFind(有显示着的文本才有)、openFind()(⌘F、iPhone 的「查找」菜单项)。consumed(event):这个按键已经被菜单消费了(菜单开着时的 Esc)。
|
|
64
64
|
// selectionMenu(event, { path, text, startLine, endLine }):给了就接管正文里选中文字的右键(只有 Mac 传);预览不知道菜单里是什么。
|
|
65
65
|
// 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
|
|
66
|
-
|
|
66
|
+
// media(path) → Promise<{ token, size, mtimeMs }>(第 20 节):音视频和图片经模块的本机流式服务显示,token 是这个视图的口令;token 为 null 表示宿主没有流式服务。
|
|
67
|
+
// 不传 media 就一律走分块读取(直接挂载预览的测试用)。
|
|
68
|
+
export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false, media = null }) {
|
|
67
69
|
const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
|
|
68
70
|
const fileIcon = h('span', { class: 'pico', 'aria-hidden': 'true' });
|
|
69
71
|
// 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
|
|
70
72
|
const action = (label, glyph, run) => h('button', { class: glyph ? 'icon' : 'link', 'aria-label': label, title: label, onclick: run }, glyph ? icon(glyph, 18) : label);
|
|
71
73
|
const copyPath = () => path !== null && copy(path);
|
|
72
|
-
const retryButton = h('button', { class: 'link', onclick: () => load(
|
|
74
|
+
const retryButton = h('button', { class: 'link', onclick: () => load(!changed), hidden: true }, '重试');
|
|
73
75
|
const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
|
|
74
76
|
let gutterEl = null;
|
|
75
77
|
const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
|
|
@@ -97,17 +99,24 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
97
99
|
let opens = 0, stoppedAt = -1; // 打开次数和上一次停止时的次数:释放只在停止之后没有再打开过时才做(返回的退场还没结束又打开了)
|
|
98
100
|
let carry = null; // 待恢复的位置 { scroll, settle }:open 带进来,读取真正用上或作废后才清
|
|
99
101
|
const settle = used => { const c = carry; carry = null; c?.settle(used); };
|
|
100
|
-
let metaText = ' ', metaTitle = '', stale = null; // stale
|
|
101
|
-
//
|
|
102
|
+
let metaText = ' ', metaTitle = '', stale = null, changed = false; // stale:后台刷新失败的原因,此时正文还是上次的;changed:正在播放的文件变了,等用户点「重载」
|
|
103
|
+
// 更新失败和文件已变化的提示占用元信息那一行,重试(重载)按钮在头部,所以正文不会被顶动。
|
|
102
104
|
const paintMeta = () => {
|
|
103
|
-
meta.textContent = stale ? `更新失败:${stale}` : metaText;
|
|
104
|
-
meta.title = stale ?? metaTitle;
|
|
105
|
-
meta.classList.toggle('warn', stale !== null);
|
|
106
|
-
retryButton.hidden = stale === null;
|
|
105
|
+
meta.textContent = stale ? `更新失败:${stale}` : changed ? '文件已变化' : metaText;
|
|
106
|
+
meta.title = stale ?? (changed ? '点「重载」按新内容重新播放' : metaTitle);
|
|
107
|
+
meta.classList.toggle('warn', stale !== null || changed);
|
|
108
|
+
retryButton.hidden = stale === null && !changed;
|
|
109
|
+
retryButton.textContent = !stale && changed ? '重载' : '重试';
|
|
107
110
|
};
|
|
108
|
-
const setMeta = (text, title = '') => { metaText = text; metaTitle = title; stale = null; paintMeta(); };
|
|
111
|
+
const setMeta = (text, title = '') => { metaText = text; metaTitle = title; stale = null; changed = false; paintMeta(); };
|
|
109
112
|
const setStale = reason => { stale = reason; paintMeta(); };
|
|
110
|
-
|
|
113
|
+
let player = null; // 正在显示的音视频或图片元素
|
|
114
|
+
const stopMedia = () => {
|
|
115
|
+
if (!player) return;
|
|
116
|
+
player.pause?.(); player.removeAttribute('src'); player.load?.();
|
|
117
|
+
player = null;
|
|
118
|
+
};
|
|
119
|
+
const revoke = () => { stopMedia(); if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
|
|
111
120
|
const notice = (title, detail, action) => body.replaceChildren(h('div', { class: 'empty' },
|
|
112
121
|
h('p', {}, title), detail ? h('p', { class: 'secondary' }, detail) : null,
|
|
113
122
|
action ? h('button', { class: 'link', onclick: action.run }, action.label) : null));
|
|
@@ -164,11 +173,61 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
164
173
|
notice('读不到这个文件', error.message, { label: '重试', run: retry });
|
|
165
174
|
}
|
|
166
175
|
|
|
176
|
+
const mediaMeta = size => [path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '', formatSize(size)];
|
|
177
|
+
const line = parts => parts.filter(Boolean).join(' · ');
|
|
178
|
+
const setMetaText = (text, title) => { metaText = text; metaTitle = title; paintMeta(); }; // 只换文字(时长到了),不清更新失败和文件已变化的提示
|
|
179
|
+
const unplayable = (size, mtimeMs, title) => {
|
|
180
|
+
stopMedia();
|
|
181
|
+
notice(title, `${formatSize(size)},修改于 ${formatTime(mtimeMs)}`);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
// 图片和音视频:地址指向模块的流式服务,元素自己按需取,不经分块读取(第 20 节)。
|
|
185
|
+
function showMedia(kind, { token: key, size, mtimeMs }) {
|
|
186
|
+
revoke();
|
|
187
|
+
textShown = false; find.close(); pendingFind = null;
|
|
188
|
+
shown = { size, mtimeMs };
|
|
189
|
+
const parts = mediaMeta(size), title = `修改于 ${formatTime(mtimeMs)}`;
|
|
190
|
+
setMeta(line(parts), title);
|
|
191
|
+
const el = kind === 'image' ? h('img', { alt: path, draggable: 'false' }) : h(kind, { controls: '', playsinline: '', preload: 'metadata' });
|
|
192
|
+
el.addEventListener('error', () => { if (player === el) unplayable(size, mtimeMs, '这台设备放不了这种格式'); });
|
|
193
|
+
if (kind !== 'image') el.addEventListener('loadedmetadata', () => { if (player === el && Number.isFinite(el.duration)) setMetaText(line([...parts, formatDuration(el.duration)]), title); });
|
|
194
|
+
player = el;
|
|
195
|
+
body.replaceChildren(h('div', { class: kind === 'image' ? 'image' : 'media' }, el));
|
|
196
|
+
el.src = `coda-view://service/media/${key}/${path.split('/').map(encodeURIComponent).join('/')}?v=${size}-${mtimeMs}`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 媒体文件(按扩展名):返回 true 表示已经处理(显示、提示或已作废),false 表示这个文件走分块读取(宿主没有流式服务时的图片)。
|
|
200
|
+
// 刷新不打断播放:音视频变了只在元信息行提示「文件已变化」,点「重载」才换;图片和提示页变了直接换。
|
|
201
|
+
async function loadMedia({ kind, preview }, silent, mark) {
|
|
202
|
+
const granted = await media(path);
|
|
203
|
+
if (!mark()) return true;
|
|
204
|
+
const { token: key, size, mtimeMs } = granted;
|
|
205
|
+
if (key === null && preview && kind === 'image') return false;
|
|
206
|
+
if (silent && shown) {
|
|
207
|
+
if (shown.size === size && shown.mtimeMs === mtimeMs) { changed = false; setStale(null); return true; }
|
|
208
|
+
if (player && kind !== 'image') { changed = true; paintMeta(); return true; }
|
|
209
|
+
}
|
|
210
|
+
const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
|
|
211
|
+
if (preview && key !== null) showMedia(kind, granted);
|
|
212
|
+
else {
|
|
213
|
+
revoke();
|
|
214
|
+
textShown = false; find.close(); pendingFind = null;
|
|
215
|
+
shown = { size, mtimeMs };
|
|
216
|
+
setMeta(line(mediaMeta(size)), `修改于 ${formatTime(mtimeMs)}`);
|
|
217
|
+
unplayable(size, mtimeMs, preview ? '这个版本的 Coda 不能预览音视频' : '这种格式不能预览');
|
|
218
|
+
}
|
|
219
|
+
body.scrollTop = keep.top; body.scrollLeft = keep.left;
|
|
220
|
+
settle(true);
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
|
|
167
224
|
// silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置;有待恢复的位置时用它。
|
|
168
225
|
async function load(silent) {
|
|
169
226
|
const mine = ++token, mark = () => mine === token;
|
|
170
227
|
if (!silent) { shown = null; textShown = false; find.clearContent(); setMeta('读取中…'); revoke(); body.replaceChildren(); }
|
|
171
228
|
try {
|
|
229
|
+
const kind = media && mediaOf(path);
|
|
230
|
+
if (kind && await loadMedia(kind, silent, mark)) return;
|
|
172
231
|
const result = await readFile(offset => read(path, offset), {
|
|
173
232
|
prev: silent ? shown : null, cancelled: () => !mark(),
|
|
174
233
|
onProgress: (got, total) => { if (mark() && !silent && total > TEXT_LIMIT / 4) setMeta(`读取中 ${formatSize(got)} / ${formatSize(total)}`); },
|
|
@@ -206,7 +265,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
206
265
|
// 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
|
|
207
266
|
reload() { find.close(); return path === null ? undefined : load(false); }, // 来源变了:查找也关
|
|
208
267
|
// 停止(逻辑关闭,立即):不再读、不再刷新,待恢复的位置结算;画面(正文、图片的 URL)留着,由 release 在退场结束时清掉。
|
|
209
|
-
stop() { settle(false); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
|
|
268
|
+
stop() { settle(false); player?.pause?.(); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
|
|
210
269
|
// 释放(画面):停止之后又打开过就什么都不做。
|
|
211
270
|
release() {
|
|
212
271
|
if (stoppedAt !== opens) return; // 停止之后又打开过(打开次数变了):这一屏是新的,不是退场的旧页
|
package/view/protocol.mjs
CHANGED
|
@@ -19,16 +19,16 @@ export const SEARCH_RESULTS = 500;
|
|
|
19
19
|
|
|
20
20
|
export const Type = Object.freeze({
|
|
21
21
|
HELLO: 'hello', REFRESH: 'refresh', LIST: 'list', READ: 'read', STAT: 'stat', DIR_SIZE: 'dir_size', ADD_TEXT: 'add_text',
|
|
22
|
-
SEARCH: 'search',
|
|
22
|
+
SEARCH: 'search', MEDIA: 'media',
|
|
23
23
|
DIR_SIZE_CANCEL: 'dir_size_cancel', SEARCH_CANCEL: 'search_cancel', // 没有回答
|
|
24
24
|
SESSION: 'session', ROOT: 'root', CHANGED: 'changed',
|
|
25
|
-
LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added', SEARCHED: 'searched',
|
|
25
|
+
LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added', SEARCHED: 'searched', MEDIA_GRANTED: 'media_granted',
|
|
26
26
|
});
|
|
27
27
|
|
|
28
28
|
// 请求 → 回答的类型。模块回答、页面分发都查这一张。
|
|
29
29
|
export const ReplyOf = Object.freeze({
|
|
30
30
|
[Type.LIST]: Type.LISTED, [Type.READ]: Type.CHUNK, [Type.STAT]: Type.STATTED,
|
|
31
|
-
[Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED, [Type.SEARCH]: Type.SEARCHED,
|
|
31
|
+
[Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED, [Type.SEARCH]: Type.SEARCHED, [Type.MEDIA]: Type.MEDIA_GRANTED,
|
|
32
32
|
});
|
|
33
33
|
export const isReply = type => Object.values(ReplyOf).includes(type);
|
|
34
34
|
|
|
@@ -64,6 +64,28 @@ export function imageType(name) {
|
|
|
64
64
|
return dot < 0 ? null : IMAGE_TYPES[name.slice(dot + 1).toLowerCase()] ?? null;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
// 音视频和图片走模块的本机流式服务(设计见 docs/design/phase-3.md 第 20 节):扩展名 → [种类, MIME 类型],页面决定怎么显示、模块决定服务哪些,都查这一张。
|
|
68
|
+
const MEDIA_TYPES = {
|
|
69
|
+
mp3: ['audio', 'audio/mpeg'], m4a: ['audio', 'audio/mp4'], aac: ['audio', 'audio/aac'], wav: ['audio', 'audio/wav'], flac: ['audio', 'audio/flac'],
|
|
70
|
+
ogg: ['audio', 'audio/ogg'], opus: ['audio', 'audio/ogg'], aiff: ['audio', 'audio/aiff'], aif: ['audio', 'audio/aiff'], caf: ['audio', 'audio/x-caf'],
|
|
71
|
+
mp4: ['video', 'video/mp4'], m4v: ['video', 'video/x-m4v'], mov: ['video', 'video/quicktime'], webm: ['video', 'video/webm'],
|
|
72
|
+
png: ['image', 'image/png'], jpg: ['image', 'image/jpeg'], jpeg: ['image', 'image/jpeg'], gif: ['image', 'image/gif'], webp: ['image', 'image/webp'],
|
|
73
|
+
svg: ['image', 'image/svg+xml'], avif: ['image', 'image/avif'], heic: ['image', 'image/heic'], heif: ['image', 'image/heif'],
|
|
74
|
+
bmp: ['image', 'image/bmp'], tif: ['image', 'image/tiff'], tiff: ['image', 'image/tiff'],
|
|
75
|
+
};
|
|
76
|
+
// 查证过 Coda 播放器不支持的视频:按扩展名直接不预览,不读字节(mkv 容器不支持,avi 的 canPlayType 说 maybe 但实际报错)。
|
|
77
|
+
const NO_PREVIEW = new Set(['mkv', 'avi']);
|
|
78
|
+
|
|
79
|
+
// 按扩展名给出 { kind: 'audio' | 'video' | 'image', type, preview };不是媒体文件返回 null。preview 为 false 的没有 type,不经服务。
|
|
80
|
+
export function mediaOf(name) {
|
|
81
|
+
const dot = String(name).lastIndexOf('.');
|
|
82
|
+
if (dot < 0) return null;
|
|
83
|
+
const ext = name.slice(dot + 1).toLowerCase();
|
|
84
|
+
if (NO_PREVIEW.has(ext)) return { kind: 'video', type: null, preview: false };
|
|
85
|
+
const entry = MEDIA_TYPES[ext];
|
|
86
|
+
return entry ? { kind: entry[0], type: entry[1], preview: true } : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
67
89
|
// 相对路径的规则只在这一处:模块(lib/paths.mjs)校验请求,页面恢复保存的 cwd 时用同一个函数。
|
|
68
90
|
// 空串是根目录;拒绝过长、控制字符、绝对路径和 `..`。返回 { segments }(去掉空段和 `.`)或 { problem }(给人看的原因)。
|
|
69
91
|
export const MAX_PATH = 4096;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// 根目录的名字,四处共用:Mac 目录树标题、iPhone 页内工具条的标题、图标视图头部、系统返回的路径(设计见 docs/design/phase-3.md 第 19 节)。
|
|
2
|
+
// 普通目录是路径的最后一段;worktree 会话(模块从 Coda 的项目列表取到了 project,项目名,默认是原仓库的文件夹名)写成 `<项目名> worktree-<编号>`,中间是空格,缩写是 `<项目名> wt-<编号>`。
|
|
3
|
+
// 编号是 worktree 目录名为 UUID 时的前 4 位,否则整个目录名。Coda 的 worktree 目录以 UUID 命名,只显示目录名认不出项目。
|
|
4
|
+
// 页面里两段是两个元素:项目名(.rn-name,继承标题的粗体)和后缀(.rn-tag,常规字重、三级灰、小一号,样式在 style.css);空格归后缀那一段。系统返回只能是纯文字(rootLabel)。
|
|
5
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
|
+
const ELLIPSIS = '…';
|
|
7
|
+
const MIN_PROJECT = 2; // 项目名从中间省略时至少留的字数(字素簇)
|
|
8
|
+
const ROOMY = 0.9; // 完整写法不超过可用宽度的 90% 才完整显示:宽度够时不贴边
|
|
9
|
+
|
|
10
|
+
export const baseName = path => path.split('/').filter(Boolean).pop() ?? path;
|
|
11
|
+
export const tagOf = name => (UUID.test(name) ? name.slice(0, 4) : name);
|
|
12
|
+
|
|
13
|
+
// 后缀(带前面的空格):长的是 ` worktree-<编号>`,短的是 ` wt-<编号>`。
|
|
14
|
+
const suffixOf = (root, short) => ` ${short ? 'wt' : 'worktree'}-${tagOf(baseName(root.path))}`;
|
|
15
|
+
|
|
16
|
+
// 完整写法:系统返回的文字由客户端排版,直接用它,不省略。
|
|
17
|
+
export const rootLabel = root => (root.project ? `${root.project}${suffixOf(root, false)}` : baseName(root.path));
|
|
18
|
+
|
|
19
|
+
// 按字素簇切(Intl.Segmenter),不能按 UTF-16 切:emoji、非 BMP 的汉字、组合字符会被切坏;没有 Segmenter 时退回按码点。
|
|
20
|
+
const segmenter = typeof Intl?.Segmenter === 'function' ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;
|
|
21
|
+
export const glyphs = text => (segmenter ? Array.from(segmenter.segment(text), part => part.segment) : Array.from(text));
|
|
22
|
+
|
|
23
|
+
// 项目名从中间省略(同 Finder,保留首尾),留 keep 个字;多出来的一个字给前面。
|
|
24
|
+
const middle = (chars, keep) => `${chars.slice(0, Math.ceil(keep / 2)).join('')}${ELLIPSIS}${chars.slice(chars.length - Math.floor(keep / 2)).join('')}`;
|
|
25
|
+
|
|
26
|
+
// 放不下时按顺序省略,前一步放得下就停。measure(text, role) 是文字的宽度:role 是 'name'(项目名)或 'tag'(后缀,含前面的空格),两段字体不同,要各按各的量;
|
|
27
|
+
// width 是可用宽度,单位自定,两者一致即可。
|
|
28
|
+
// 1 完整写法不超过 width 的 90%:完整显示;2 后缀缩成 wt-<编号>,整行放得下(100%)就停;3 项目名从中间省略,至少留 2 个字;4 整段从尾部省略(在第 3 步的最短形式上)。
|
|
29
|
+
// 字都按字素簇数;wt-<编号> 在第 4 步前不省略。
|
|
30
|
+
// 返回 { name, tag, text, step }:name、tag 是两段文字,text 是它们连起来;step 0 是没有项目名的普通目录(name 就是文件夹名,tag 空):不在这里省略,交给 CSS 的 text-overflow(和从前一样)。
|
|
31
|
+
const result = (name, tag, step) => ({ name, tag, text: `${name}${tag}`, step });
|
|
32
|
+
export function fitRootLabel(root, width, measure) {
|
|
33
|
+
if (!root.project) return result(baseName(root.path), '', 0);
|
|
34
|
+
const { project } = root, long = suffixOf(root, false), short = suffixOf(root, true), chars = glyphs(project);
|
|
35
|
+
const size = (name, tag) => measure(name, 'name') + measure(tag, 'tag');
|
|
36
|
+
if (size(project, long) <= width * ROOMY) return result(project, long, 1);
|
|
37
|
+
if (size(project, short) <= width) return result(project, short, 2);
|
|
38
|
+
for (let keep = chars.length - 1; keep >= MIN_PROJECT; keep--) {
|
|
39
|
+
const name = middle(chars, keep);
|
|
40
|
+
if (size(name, short) <= width) return result(name, short, 3);
|
|
41
|
+
}
|
|
42
|
+
const nameChars = glyphs(chars.length > MIN_PROJECT ? middle(chars, MIN_PROJECT) : project), all = [...nameChars, ...glyphs(short)];
|
|
43
|
+
// 取前 length 个字,补一个省略号(截在项目名中间的省略号上时不再叠一个);省略号跟着最后一个字所在的那段。
|
|
44
|
+
const cut = length => {
|
|
45
|
+
const head = all.slice(0, Math.max(1, length));
|
|
46
|
+
while (head.length > 1 && head.at(-1) === ' ') head.pop(); // 空格后面不跟省略号
|
|
47
|
+
const text = head.at(-1) === ELLIPSIS ? head : [...head, ELLIPSIS];
|
|
48
|
+
return head.length <= nameChars.length ? { name: text.join(''), tag: '' } : { name: nameChars.join(''), tag: text.slice(nameChars.length).join('') };
|
|
49
|
+
};
|
|
50
|
+
const fits = length => { const { name, tag } = cut(length); return size(name, tag) <= width; };
|
|
51
|
+
let lo = 0, hi = all.length - 1; // 最长的放得下的前缀(至少留一个字);宽度对前缀长度单调
|
|
52
|
+
while (lo < hi) {
|
|
53
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
54
|
+
if (fits(mid)) lo = mid; else hi = mid - 1;
|
|
55
|
+
}
|
|
56
|
+
const { name, tag } = cut(lo);
|
|
57
|
+
return result(name, tag, 4);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 页面里量文字:用元素自己的字体在 canvas 上量(项目名和后缀的字号、字重不同,各量各的)。没有 canvas(测试的假 DOM)时一个字算 1。
|
|
61
|
+
// 每次量之前都设字体:几个量字函数共用一个 canvas 上下文。
|
|
62
|
+
let canvas = null;
|
|
63
|
+
export function measurerOf(el) {
|
|
64
|
+
let context = null;
|
|
65
|
+
try { context = (canvas ??= globalThis.document.createElement('canvas')).getContext?.('2d') ?? null; } catch { /* 没有 canvas */ }
|
|
66
|
+
const style = globalThis.getComputedStyle?.(el);
|
|
67
|
+
if (!context || !style) return text => text.length;
|
|
68
|
+
const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
|
|
69
|
+
return text => { context.font = font; return context.measureText(text).width; };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 元素里能放文字的宽度:内容宽,再留 2 个像素给量字的误差。没排版(隐藏、display: none)时是 0,不省略。
|
|
73
|
+
export function widthOf(el) {
|
|
74
|
+
if (!el.clientWidth) return 0;
|
|
75
|
+
const style = globalThis.getComputedStyle?.(el), pad = style ? (parseFloat(style.paddingLeft) || 0) + (parseFloat(style.paddingRight) || 0) : 0;
|
|
76
|
+
return el.clientWidth - pad - (style ? 2 : 0);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 元素里的两段(项目名、后缀):元素的内容不是它们(换过别的文字)就重建。
|
|
80
|
+
const spans = new WeakMap();
|
|
81
|
+
function spansOf(el) {
|
|
82
|
+
let pair = spans.get(el);
|
|
83
|
+
if (!pair || !el.contains(pair.name) || !el.contains(pair.tag)) {
|
|
84
|
+
const make = className => Object.assign(globalThis.document.createElement('span'), { className });
|
|
85
|
+
pair = { name: make('rn-name'), tag: make('rn-tag') };
|
|
86
|
+
spans.set(el, pair);
|
|
87
|
+
el.replaceChildren(pair.name, pair.tag);
|
|
88
|
+
}
|
|
89
|
+
return pair;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 把根目录名写进元素:worktree 写成两段(项目名、后缀),按元素现在的宽度省略;普通目录就是一个文本节点,交给 CSS 截断。宽度变了再调一次。
|
|
93
|
+
// 元素还没有宽度(隐藏)时写完整写法(第 1 步),显示出来、有了宽度之后再调。measure(可选)按 (text, role) 量,测试注入;返回写进去的 { name, tag, text, step }。
|
|
94
|
+
export function paintRootName(el, root, measure = null) {
|
|
95
|
+
if (!root.project) {
|
|
96
|
+
const plain = result(baseName(root.path), '', 0);
|
|
97
|
+
if (spans.delete(el) || el.textContent !== plain.text) el.textContent = plain.text; // 从两段换回纯文字:整个换掉
|
|
98
|
+
return plain;
|
|
99
|
+
}
|
|
100
|
+
const pair = spansOf(el), width = widthOf(el);
|
|
101
|
+
let fit = result(root.project, suffixOf(root, false), 1);
|
|
102
|
+
if (width > 0) {
|
|
103
|
+
const names = measurerOf(pair.name), tags = measurerOf(pair.tag);
|
|
104
|
+
fit = fitRootLabel(root, width, measure ?? ((text, role) => (role === 'tag' ? tags : names)(text)));
|
|
105
|
+
}
|
|
106
|
+
if (pair.name.textContent !== fit.name) pair.name.textContent = fit.name;
|
|
107
|
+
if (pair.tag.textContent !== fit.tag) pair.tag.textContent = fit.tag;
|
|
108
|
+
return fit;
|
|
109
|
+
}
|
package/view/style.css
CHANGED
|
@@ -108,7 +108,12 @@ html.moving, html.moving body, html.moving #stage { pointer-events: none; }
|
|
|
108
108
|
/* 树:只画可见的一段,行高固定(tree.mjs 量 .row 的高度)。
|
|
109
109
|
Mac 是侧栏列表:左右缩进 8 点,行有圆角,选中用 --coda-selection。 */
|
|
110
110
|
/* 标题行:根目录名,随内容滚走。它在滚动容器里占着自己的高度,tree.mjs 把 spacer 的 offsetTop 扣掉。 */
|
|
111
|
-
.
|
|
111
|
+
/* 字号比 0.8.0 之前(.85em,约 11 点)大一号(.92em,约 12 点):worktree 的项目名是主,后缀 .rn-tag 用回原来的字号(第 19.6 节);普通文件夹名同样大一号,标题不因会话不同忽大忽小。 */
|
|
112
|
+
.section { padding: 10px 16px 4px; font-size: .92em; font-weight: 600; color: var(--coda-secondary, #6e6e73); cursor: default; }
|
|
113
|
+
/* worktree 根目录名的后缀(`worktree-c037`、`wt-c037`,前面的空格也在里面):常规字重、三级灰、比项目名小一号;em 跟着标题走(跟 --coda-font-size,不写死点数)。
|
|
114
|
+
后缀的颜色在浅色下对比度约 2.6:1(作者选的,第 19.6 节第 4 条),它是次要信息。 */
|
|
115
|
+
.rn-tag { font-weight: 400; font-size: .88em; color: var(--coda-tertiary, #a1a1a6); }
|
|
116
|
+
.section .rn-tag { font-size: .924em; } /* .92em 的标题里 .924em 是约 11 点,即原来标题的字号 */
|
|
112
117
|
/* 行宽按 #tree 的宽度查询:窄于约 220 点时 Mac 的 meta 不显示。 */
|
|
113
118
|
#tree { container: tree / inline-size; }
|
|
114
119
|
.spacer { position: relative; margin: 0 8px; }
|
|
@@ -171,6 +176,9 @@ button.icon svg { display: block; }
|
|
|
171
176
|
.code .text .hljs-addition { color: var(--hl-addition); }
|
|
172
177
|
.code .text .hljs-deletion { color: var(--hl-deletion); }
|
|
173
178
|
.code .text .hljs-section { color: var(--hl-section); }
|
|
179
|
+
.media { display: grid; place-items: start center; padding: 12px; }
|
|
180
|
+
.media video { width: 100%; max-height: 70vh; border-radius: var(--coda-radius, 6px); background: #000; }
|
|
181
|
+
.media audio { width: 100%; }
|
|
174
182
|
.image { display: grid; place-items: start center; padding: 12px; }
|
|
175
183
|
.image img { max-width: 100%; height: auto; border-radius: var(--coda-radius, 6px); background: var(--coda-secondary-background, transparent); }
|
|
176
184
|
|
package/view/tree.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { dateText, infoText, sizeText, subText } from './format.mjs';
|
|
|
4
4
|
import { mountGestures } from './gestures.mjs';
|
|
5
5
|
import { icon, iconFor } from './icons.mjs';
|
|
6
6
|
import { joinPath, parentOf } from './model.mjs';
|
|
7
|
+
import { paintRootName } from './rootname.mjs';
|
|
7
8
|
|
|
8
9
|
const OVERSCAN = 8;
|
|
9
10
|
|
|
@@ -56,9 +57,6 @@ export function stepRows(rows, selected, action) {
|
|
|
56
57
|
return up < 0 ? null : { select: up };
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
// 根目录的名字:路径的最后一段,分区标题和 iPhone 的页内工具条共用。
|
|
60
|
-
export const rootName = path => path.split('/').filter(Boolean).pop() ?? path;
|
|
61
|
-
|
|
62
60
|
export const TITLES = { [EntryKind.LINK]: '指向工作目录外的链接,不能打开', [EntryKind.OTHER]: '不能打开的文件' };
|
|
63
61
|
|
|
64
62
|
// handlers: { open(path), toggle(path), more(path), retry(path), menu(event, row), select(path | null) };select 是 Mac 单击选中,不给就是 iPhone 的轻点打开
|
|
@@ -92,11 +90,14 @@ export function mountTree(el, model, handlers, {
|
|
|
92
90
|
probe.remove();
|
|
93
91
|
};
|
|
94
92
|
|
|
95
|
-
//
|
|
93
|
+
// 分区标题:根目录的名字(第 19 节:worktree 写成「项目名-wt-编号」,放不下时按宽度省略;普通目录是路径的最后一段,交给 CSS),不是 ready 时不显示。iPhone 上由 CSS 隐藏。
|
|
94
|
+
// worktree 的标题悬停显示完整路径。先写完整写法、取消隐藏,再按有了排版的宽度省略。
|
|
96
95
|
const paintTitle = () => {
|
|
97
|
-
const
|
|
98
|
-
if (title.textContent
|
|
99
|
-
title.hidden =
|
|
96
|
+
const shown = showTitle && model.ready;
|
|
97
|
+
if (!shown) { title.textContent = ''; title.hidden = true; title.title = ''; return; }
|
|
98
|
+
title.hidden = false;
|
|
99
|
+
paintRootName(title, model.root);
|
|
100
|
+
title.title = model.root.project ? model.root.path : '';
|
|
100
101
|
};
|
|
101
102
|
|
|
102
103
|
// 标题在滚动容器里,把 spacer 推下去 offsetTop:行的位置按 spacer 内部算,滚动值(保存和恢复的)仍是容器的。
|
|
@@ -205,7 +206,7 @@ export function mountTree(el, model, handlers, {
|
|
|
205
206
|
return true;
|
|
206
207
|
};
|
|
207
208
|
el.addEventListener('scroll', paint, { passive: true });
|
|
208
|
-
new ResizeObserver(paint).observe(el);
|
|
209
|
+
new ResizeObserver(() => { paintTitle(); paint(); }).observe(el); // 侧栏宽度变了,标题的省略重算
|
|
209
210
|
|
|
210
211
|
return {
|
|
211
212
|
render() { rows = rowsOf(); spacer.style.height = `${rows.length * rowH}px`; paintTitle(); paint(); },
|