@coda-console/resource-manager 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,7 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
19
19
  - 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「显示」›「排序」里选,当前项有对勾。两种视图用同一个排序。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
20
20
  - **文件名搜索**(`0.8.0`):目录树和图标视图顶上常驻一个搜索框,Mac 按 ⌘F 聚焦它(选中里面的字)。有字时列表换成结果,清空(Esc 或清除按钮)回到原来的浏览,展开、滚动、选中都还在。搜整个工作目录(后台逐层走,先浅后深),只比**名字**,不比路径(带斜杠的词找不到):不分大小写、包含就算,中文和分解形式的字(如 `é` 的两种写法)都能找到。始终不进 `.git`、`node_modules`(它们自己能作为结果),隐藏文件跟「显示隐藏文件」开关,不跟着链接进目录,不读 `.gitignore`。最多 500 条,最多看 20 万项或 5 秒,到了就停并注明「没搜完」,只显示已找到的;每次重新走树,没有索引。结果按「名字以搜索词开头的在前、浅的在前、再按名称」排,不跟「显示」菜单的排序走。每行是图标、名字(匹配的部分加粗)、所在目录(Mac 在右边,iPhone 在第二行)。Mac 单击选中、双击或 ⌘↓ 打开,↑ ↓ 移动;iPhone 轻点打开;右键或长按有「打开」「添加到聊天」「复制路径」「在目录中显示」「属性」。「在目录中显示」逐级展开(图标视图是进入它所在的目录)并把它选中、滚到中间;这期间你点、滚、按键、打开东西就停下,不会和你抢。结果里打开文件夹也是先定位再展开(或进入)它。刷新、「一轮结束」和切换「显示隐藏文件」会重搜;搜索词和结果不存进会话状态,页面重建后是空的。iPhone 的系统返回:结果里打开的预览或属性页返回到结果,结果本身不算一级。
21
21
  - **文件内查找**(`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 秒)。当前这一处文字用正文色,不显示代码着色。
22
+ - **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
23
  - 切换会话时换成新会话的内容,切回来恢复展开状态和滚动位置。
23
24
  - 右键(Mac)或长按(iPhone)一行:添加到聊天、复制相对路径、复制绝对路径、属性。「添加到聊天」把相对路径接在输入框已有文字后面;指向工作目录外或已失效的链接、不能打开的条目没有这一项。成功时底部提示「已添加到输入框」,约 2 秒消失;写不进去时改为复制,提示「没能写入输入框,已复制」;剪贴板也写不进去时提示「没能写入,也没能复制」。
24
25
  - **选中文字右键(只有 Mac)**:在文件预览(侧栏和独立窗口)里选中文字后右键,有「添加到聊天(内容)」「添加到聊天(位置)」「复制」。位置是 `src/app.ts:12-18`,只选一行时是 `src/app.ts:12`,只精确到行。选中的内容太长放不进一条消息时直接复制,提示「选中内容太长,已复制」。iPhone 用系统自带的选区菜单,不加这一项。
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
- export const sameRoot = (a, b) => a?.state === b?.state && a?.path === b?.path;
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 thread = await coda.api(`threads/${encodeURIComponent(session)}`);
15
- const checkout = thread?.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
@@ -62,7 +62,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits })
62
62
  const postSession = () => post({ type: Type.SESSION, generation: s.generation, session: s.session });
63
63
  function postRoot() {
64
64
  s.sent = s.root;
65
- post({ type: Type.ROOT, generation: s.generation, state: s.root.state, path: s.root.path });
65
+ post({ type: Type.ROOT, generation: s.generation, state: s.root.state, path: s.root.path, project: s.root.project });
66
66
  }
67
67
 
68
68
  // 重新查询根目录。结果和上次推给页面的不同才推送;查询失败保留上一次的。
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "@coda-console/resource-manager",
4
4
  "displayName": "资源管理器",
5
5
  "description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本和图片,把路径交给对话。",
6
- "version": "0.8.0",
6
+ "version": "0.8.1",
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 { mountTree, rootName } from './tree.mjs';
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);
@@ -374,7 +375,7 @@ const toolbarItems = () => infoOpen ? [] : hasToolbar
374
375
  // 预览时和属性页一样只留返回(竖屏整条不显示):标题和 ⋯ 在预览头部,⋯ 里只有刷新和复制路径。
375
376
  // 属性页上只留返回:竖屏有原生导航栏,整条工具条不显示;横屏导航栏隐藏,页面自己给返回(显示与否都由 style.css 的横屏媒体查询决定)。
376
377
  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];
378
+ const phoneItems = () => infoOpen || mode() === 'preview' ? [EXIT] : [EXIT, { kind: 'title', label: model.ready ? dirTitle() : '', ...(model.ready && titleIsRoot() && model.root.project ? { root: { path: model.root.path, project: model.root.project } } : {}) }, MORE];
378
379
  // 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
379
380
  let lastItems = '';
380
381
  function syncToolbar() {
@@ -647,14 +648,15 @@ function landed() {
647
648
  // ---- 上一层:iPhone 用原生返回,路径只在这里声明 ----
648
649
  // 路径是上层的标题,由远到近,不含当前页:图标视图在 a/b 是 [根目录名, 'a'];列表视图没有。属性页、预览各多一层当前页(要回到的那一页):列表视图是 '资源管理器',图标视图是当前目录名。
649
650
  // 预览开着是 opened 不为空、且根目录就绪;没就绪时页面是说明区,路径为空。
650
- // 标题是当前目录名:根目录是根目录名。
651
+ // 标题是当前目录名:根目录是根目录名(worktree 是「项目名-wt-编号」,这里给完整写法,不省略:文字由客户端排版)。
651
652
  // 搜索时结果盖住了图标视图的目录:标题是根目录名。
652
- const dirTitle = () => (model.cwd === '' || model.view !== View.ICONS || searching() ? rootName(model.root.path) : model.cwd.slice(model.cwd.lastIndexOf('/') + 1));
653
+ const titleIsRoot = () => model.cwd === '' || model.view !== View.ICONS || searching();
654
+ const dirTitle = () => (titleIsRoot() ? rootLabel(model.root) : model.cwd.slice(model.cwd.lastIndexOf('/') + 1));
653
655
  const previewOpen = () => model.ready && model.opened !== null;
654
656
  // 搜索本身不是一级:搜索模式下图标视图的目录层级不声明(搜索盖住了它们),从结果打开的预览和属性页要回到的那一页叫「搜索」(第 18.5 节的表)。
655
657
  function backPath() {
656
658
  const icons = model.view === View.ICONS && model.ready && !searching();
657
- const upper = icons && model.cwd !== '' ? [rootName(model.root.path), ...model.cwd.split('/').slice(0, -1)] : [];
659
+ const upper = icons && model.cwd !== '' ? [rootLabel(model.root), ...model.cwd.split('/').slice(0, -1)] : [];
658
660
  const here = searching() ? '搜索' : icons ? dirTitle() : '资源管理器';
659
661
  return [...upper, ...(infoOpen ? [here] : []), ...(previewOpen() ? [here] : [])];
660
662
  }
@@ -757,7 +759,7 @@ function onChanged(data) {
757
759
  search.research(); // 搜索期间目录模型照常刷新;有搜索词就重搜,旧结果留到新结果来
758
760
  }
759
761
 
760
- const remeasure = () => { tree.remeasure(); grid.remeasure(); hits.remeasure(); };
762
+ const remeasure = () => { tree.remeasure(); grid.remeasure(); hits.remeasure(); refitBar($('bar')); };
761
763
  remeasure();
762
764
  quiet(() => coda.on('theme', remeasure));
763
765
  render();
package/view/bar.mjs CHANGED
@@ -1,16 +1,32 @@
1
1
  // 页内工具条:没有 coda.toolbar 的平台(iPhone)用,两个页面共用,按钮由页面给。
2
2
  // 「返回」只在横屏出现(导航栏隐藏时),显示与否由 style.css 的媒体查询决定,这里一律画出来。
3
- // 项:{ id, label, kind: 'button' | 'toggle' | 'title', glyph?, iconOnly?, on?, menu? };menu 的按钮打开菜单。title 不是按钮,只显示 label。
3
+ // 项:{ id, label, kind: 'button' | 'toggle' | 'title', glyph?, iconOnly?, on?, menu?, root? };menu 的按钮打开菜单。title 不是按钮,只显示 label。
4
+ // title 带 root({ path, project },worktree 的根目录)时,label 是完整写法,画出来按标题现在的宽度省略(第 19 节),宽度变了(旋转、字号)重算;不带的交给 CSS 截断。
4
5
  // 有 glyph 画图标;iconOnly 的只留图标,label 当可访问名称;否则图标后面跟文字(没有 glyph 就只有文字)。
5
6
  import { icon } from './icons.mjs';
7
+ import { paintRootName } from './rootname.mjs';
6
8
 
7
9
  export const EXIT = { id: 'exit', label: '返回', kind: 'button', glyph: 'back' };
8
10
 
11
+ const fitted = new WeakMap(); // 工具条 → { title, root, observer }:现在画着的要省略的标题
12
+
13
+ // 按现在的宽度重新省略标题(字号变了时页面调用);没有要省略的标题什么都不做。
14
+ export function refitBar(el) {
15
+ const entry = fitted.get(el);
16
+ if (entry) paintRootName(entry.title, entry.root);
17
+ }
18
+
9
19
  // act(id, button):button 是被点的元素,菜单要用它定位。
10
20
  export function paintBar(el, items, act) {
21
+ fitted.get(el)?.observer?.disconnect();
22
+ fitted.delete(el);
11
23
  el.hidden = false;
12
24
  el.replaceChildren(...items.map(item => {
13
- if (item.kind === 'title') return Object.assign(document.createElement('span'), { className: 'bar-title grow truncate', textContent: item.label });
25
+ if (item.kind === 'title') {
26
+ const title = Object.assign(document.createElement('span'), { className: 'bar-title grow truncate', textContent: item.label });
27
+ if (item.root) fitted.set(el, { title, root: item.root, observer: null });
28
+ return title;
29
+ }
14
30
  const button = document.createElement('button');
15
31
  if (item.glyph) button.append(icon(item.glyph, 20));
16
32
  if (item.iconOnly) button.setAttribute('aria-label', item.label);
@@ -23,4 +39,8 @@ export function paintBar(el, items, act) {
23
39
  button.addEventListener('click', () => act(item.id, button));
24
40
  return button;
25
41
  }));
42
+ const entry = fitted.get(el);
43
+ if (!entry) return;
44
+ paintRootName(entry.title, entry.root); // 标题已在页面里,有了宽度
45
+ if (typeof ResizeObserver === 'function') (entry.observer = new ResizeObserver(() => paintRootName(entry.title, entry.root))).observe(entry.title);
26
46
  }
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 { TITLES, rootName } from './tree.mjs';
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 name = model.cwd === '' ? (model.ready ? rootName(model.root.path) : '') : model.cwd.slice(model.cwd.lastIndexOf('/') + 1);
153
- const key = `${model.cwd}\n${name}`;
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 === headKey) return;
156
- headKey = key;
157
- head.replaceChildren(...(handlers.back && model.cwd !== '' ? [h('button', { class: 'icon', 'aria-label': '返回', title: '返回', onclick: handlers.back }, icon('back', 18))] : []),
158
- h('span', { class: 'ghico', 'aria-hidden': 'true' }, icon('folder', 22)),
159
- h('div', { class: 'grow' }, h('div', { class: 'gname-head truncate', title: model.cwd || name }, name)));
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
- onRoot({ generation, state, path }) {
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
  }
@@ -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
- .section { padding: 10px 16px 4px; font-size: .85em; font-weight: 600; color: var(--coda-secondary, #6e6e73); cursor: default; }
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; }
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
- // 分区标题:根目录的名字(root.path 的最后一段),不是 ready 时不显示。iPhone 上由 CSS 隐藏。
93
+ // 分区标题:根目录的名字(第 19 节:worktree 写成「项目名-wt-编号」,放不下时按宽度省略;普通目录是路径的最后一段,交给 CSS),不是 ready 时不显示。iPhone 上由 CSS 隐藏。
94
+ // worktree 的标题悬停显示完整路径。先写完整写法、取消隐藏,再按有了排版的宽度省略。
96
95
  const paintTitle = () => {
97
- const text = showTitle && model.ready ? rootName(model.root.path) : '';
98
- if (title.textContent !== text) title.textContent = text;
99
- title.hidden = text === '';
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(); },