@coda-console/resource-manager 0.7.2 → 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 +4 -1
- package/lib/info.mjs +9 -75
- package/lib/root.mjs +54 -9
- package/lib/search.mjs +138 -0
- package/lib/tree.mjs +8 -3
- package/lib/walk.mjs +154 -0
- package/main.mjs +20 -10
- package/package.json +1 -1
- package/view/app.mjs +216 -30
- package/view/bar.mjs +22 -2
- package/view/connection.mjs +17 -7
- package/view/file-app.mjs +8 -0
- package/view/find.mjs +254 -0
- package/view/grid.mjs +28 -12
- package/view/icons.mjs +2 -0
- package/view/index.html +8 -2
- package/view/locate.mjs +82 -0
- package/view/menu.mjs +16 -5
- package/view/model.mjs +67 -20
- package/view/press.mjs +2 -1
- package/view/preview.mjs +47 -8
- package/view/protocol.mjs +36 -4
- package/view/rootname.mjs +109 -0
- package/view/search.mjs +144 -0
- package/view/searchbar.mjs +27 -0
- package/view/style.css +56 -2
- package/view/tree.mjs +44 -25
package/view/model.mjs
CHANGED
|
@@ -8,8 +8,6 @@ export const MAX_LOADED = 100_000; // 读回保存的条数时认的上界(vie
|
|
|
8
8
|
// 只管「按保存的条数恢复」,用户已经翻出来的条数不受限;也和 lib/tree.mjs 的目录上限无关。
|
|
9
9
|
export const RESTORE_LIMIT = 20_000;
|
|
10
10
|
const MAX_LOADED_DIRS = 500;
|
|
11
|
-
const HIDDEN = new Set(['.git', '.DS_Store']);
|
|
12
|
-
export const isHidden = name => HIDDEN.has(name);
|
|
13
11
|
export const joinPath = (dir, name) => (dir ? `${dir}/${name}` : name);
|
|
14
12
|
export const parentOf = path => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
|
|
15
13
|
const inside = (path, dir) => path === dir || path.startsWith(`${dir}/`);
|
|
@@ -61,6 +59,8 @@ export class Model {
|
|
|
61
59
|
constructor({ link, onChange = () => {}, onLost = () => {} }) { Object.assign(this, { link, onChange, onLost }); }
|
|
62
60
|
|
|
63
61
|
get ready() { return this.root?.state === RootState.READY; }
|
|
62
|
+
// 刷新的轮次:换会话和每次 refresh(含换排序、换视图、changed)都加一。定位操作拿它判断「期间有没有刷新过」。
|
|
63
|
+
get round() { return this.#round; }
|
|
64
64
|
|
|
65
65
|
// 模块来的消息统一从这里进。session 带上这个会话保存的状态;返回值同各个处理方法。
|
|
66
66
|
receive(message, saved = null) {
|
|
@@ -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
|
}
|
|
@@ -173,15 +174,22 @@ export class Model {
|
|
|
173
174
|
|
|
174
175
|
// 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。一次加载固定一种排序。
|
|
175
176
|
// more、expired:「再显示」遇到游标过期转过来时,条数要比现在多一条,而且已经算重取过一次,不再重取。
|
|
176
|
-
|
|
177
|
-
|
|
177
|
+
// 返回结局(定位操作等着它):ok(取够并提交了)、failed(失败,失败行照常显示)、void(被作废:会话换了、有更新的加载、目录没了)。
|
|
178
|
+
// 正在进行的这一次记在 dir.pending 上,whenLoaded 等它。
|
|
179
|
+
#reload(path, generation, { cap = Infinity, more = false, expired = false } = {}) {
|
|
180
|
+
if (this.link.generation !== generation) return Promise.resolve('void'); // 排队时会话已换,旧任务不碰新会话
|
|
178
181
|
let dir = this.dirs.get(path);
|
|
179
|
-
if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false });
|
|
182
|
+
if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false, pending: null });
|
|
183
|
+
return dir.pending = this.#load(dir, path, generation, { cap, more, expired });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #load(dir, path, generation, { cap, more, expired }) {
|
|
180
187
|
const token = ++dir.token, { sort } = this, nav = this.#nav;
|
|
181
188
|
const want = more ? dir.entries.length + 1 : Math.min(Math.max(dir.entries.length, this.wanted.get(path) ?? 0), cap);
|
|
182
189
|
dir.loading = true;
|
|
183
190
|
this.onChange();
|
|
184
191
|
const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
|
|
192
|
+
let outcome = 'void';
|
|
185
193
|
try {
|
|
186
194
|
let entries = [], next = null, pages = 0, sortFallback = false;
|
|
187
195
|
do {
|
|
@@ -195,27 +203,39 @@ export class Model {
|
|
|
195
203
|
entries = []; next = null; pages = 0; sortFallback = false;
|
|
196
204
|
continue;
|
|
197
205
|
}
|
|
198
|
-
if (!current()) return; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
|
|
206
|
+
if (!current()) return 'void'; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
|
|
199
207
|
if (pages === 0) sortFallback = reply.sortFallback === true;
|
|
200
208
|
entries.push(...reply.entries);
|
|
201
209
|
next = reply.nextCursor ?? null;
|
|
202
210
|
pages++;
|
|
203
211
|
} while (pages === 0 || (next && entries.length < want));
|
|
204
|
-
if (!current()) return;
|
|
212
|
+
if (!current()) return 'void';
|
|
205
213
|
Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback, sort });
|
|
206
214
|
this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
|
|
207
215
|
if (path === this.cwd) this.#quiet = false;
|
|
216
|
+
outcome = 'ok';
|
|
208
217
|
} catch (error) {
|
|
209
|
-
if (error.stale || !current()) return;
|
|
218
|
+
if (error.stale || !current()) return 'void';
|
|
210
219
|
if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#lost(path, nav);
|
|
211
220
|
else if (error.code !== ErrorCode.NO_ROOT) {
|
|
212
221
|
dir.error = { code: error.code, message: error.message };
|
|
213
222
|
if (path === this.cwd) this.#quiet = false;
|
|
223
|
+
outcome = 'failed';
|
|
214
224
|
}
|
|
215
225
|
} finally {
|
|
216
226
|
if (current()) dir.loading = false;
|
|
217
227
|
this.onChange();
|
|
218
228
|
}
|
|
229
|
+
return outcome;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// 等这个目录正在进行的加载(或「再显示」)结束,给出同样的四种结局:ok、end(没有下一页了,只对 fetchNext)、failed、void。
|
|
233
|
+
// 没在加载:已加载的是 ok,只有失败行的是 failed,没有这个目录的是 void。
|
|
234
|
+
async whenLoaded(path) {
|
|
235
|
+
const dir = this.dirs.get(path);
|
|
236
|
+
if (!dir) return 'void';
|
|
237
|
+
if (dir.loading && dir.pending) return dir.pending;
|
|
238
|
+
return dir.loaded ? 'ok' : dir.error ? 'failed' : 'void';
|
|
219
239
|
}
|
|
220
240
|
|
|
221
241
|
// 目录没了(not_found):所有列目录入口都走这里。先清掉失效的子树;cwd 在里面、而且发出请求以来没有导航过,就退到上一层。
|
|
@@ -256,30 +276,51 @@ export class Model {
|
|
|
256
276
|
retry(path) { return this.ready ? this.#reload(path, this.link.generation) : Promise.resolve(); }
|
|
257
277
|
|
|
258
278
|
// 「再显示」:取下一页接在后面。
|
|
259
|
-
async loadMore(path) {
|
|
279
|
+
async loadMore(path) { await this.#more(path); }
|
|
280
|
+
|
|
281
|
+
// 取下一页接在后面,告诉调用方结局(定位操作用):ok(接上了新条目)、end(没有下一页了)、failed(失败,失败行照常显示)、void(这次读取被作废了)。
|
|
282
|
+
// 不碰 wanted,也不按 wanted 取够;目录正在加载时由调用方先 whenLoaded。
|
|
283
|
+
async fetchNext(path) { return this.#more(path); }
|
|
284
|
+
|
|
285
|
+
async #more(path) {
|
|
260
286
|
const dir = this.dirs.get(path), { generation } = this.link;
|
|
261
|
-
if (!dir
|
|
287
|
+
if (!dir || !this.ready || dir.loading) return 'void';
|
|
288
|
+
if (!dir.next) return 'end';
|
|
262
289
|
// 游标是按另一种排序取的(换排序时这个目录没重建过):不用它,从第一页重取,条数比现在多一条。
|
|
263
|
-
if (dir.sort !== this.sort) return this.#
|
|
290
|
+
if (dir.sort !== this.sort) return this.#grown(path, dir, generation);
|
|
291
|
+
return dir.pending = this.#page(dir, path, generation); // 本次读取登记在 dir.pending 上:whenLoaded 等的就是它(游标过期后的重取经 #reload,自己登记)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async #page(dir, path, generation) {
|
|
264
295
|
const token = ++dir.token, nav = this.#nav;
|
|
265
296
|
dir.loading = true;
|
|
266
297
|
this.onChange();
|
|
267
298
|
const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
|
|
299
|
+
let outcome = 'void';
|
|
268
300
|
try {
|
|
269
301
|
const reply = await this.link.call('list', { path, cursor: dir.next, sort: this.sort });
|
|
270
|
-
if (!current()) return;
|
|
302
|
+
if (!current()) return 'void';
|
|
271
303
|
dir.entries = dir.entries.concat(reply.entries);
|
|
272
304
|
Object.assign(dir, { next: reply.nextCursor ?? null, error: null, pages: dir.pages + 1 });
|
|
305
|
+
outcome = 'ok';
|
|
273
306
|
} catch (error) {
|
|
274
|
-
if (error.stale || !current()) return;
|
|
307
|
+
if (error.stale || !current()) return 'void';
|
|
275
308
|
// 游标过期:从第一页重取,条数比现在多一条,所以还会接着往下取。重取自己管 loading。
|
|
276
|
-
if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#
|
|
277
|
-
if (error.code === ErrorCode.NOT_FOUND && path !== '')
|
|
278
|
-
dir.error = { code: error.code, message: error.message };
|
|
309
|
+
if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#grown(path, dir, generation);
|
|
310
|
+
if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#lost(path, nav);
|
|
311
|
+
else { dir.error = { code: error.code, message: error.message }; outcome = 'failed'; }
|
|
279
312
|
} finally {
|
|
280
313
|
if (current()) dir.loading = false;
|
|
281
314
|
this.onChange();
|
|
282
315
|
}
|
|
316
|
+
return outcome;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// 从第一页重取、条数比现在多一条(已经算重取过一次):结局按条数有没有增加给。
|
|
320
|
+
async #grown(path, dir, generation) {
|
|
321
|
+
const before = dir.entries.length;
|
|
322
|
+
const outcome = await this.#reload(path, generation, { more: true, expired: true });
|
|
323
|
+
return outcome === 'ok' ? (this.dirs.get(path)?.entries.length > before ? 'ok' : 'end') : outcome;
|
|
283
324
|
}
|
|
284
325
|
|
|
285
326
|
// 选中只影响高亮,不发 onChange:重画会换掉全部行节点,双击的第二下点击之后 dblclick 就丢了。页面的 selectEntry 负责切高亮和保存。返回是不是变了。
|
|
@@ -288,8 +329,14 @@ export class Model {
|
|
|
288
329
|
this.selected = path;
|
|
289
330
|
return true;
|
|
290
331
|
}
|
|
291
|
-
//
|
|
292
|
-
|
|
332
|
+
// 打开文件分两步:设预览(opened)、设选中(selected),在同一次同步操作里做完,只触发一次重画。
|
|
333
|
+
// 目录树里打开两步都做;从搜索结果里打开只设预览(结果有自己的选中,不改被遮住的目录树的选中)。
|
|
334
|
+
// 返回(closeFile)只清 opened,选中留着。
|
|
335
|
+
openFile(path, { select = true } = {}) {
|
|
336
|
+
this.opened = path;
|
|
337
|
+
if (select) this.selected = path;
|
|
338
|
+
this.onChange();
|
|
339
|
+
}
|
|
293
340
|
closeFile() { this.opened = null; this.onChange(); }
|
|
294
341
|
setShowHidden(on) { this.showHidden = on; this.onChange(); }
|
|
295
342
|
// loaded:取过不止一页的目录已加载的条数,只存条数不存内容;第一页每次都会重新取,不用存。
|
package/view/press.mjs
CHANGED
|
@@ -15,13 +15,14 @@ export const onMotionChange = fn => globalThis.matchMedia?.(QUERY)?.addEventList
|
|
|
15
15
|
|
|
16
16
|
// 点到的可按元素:{ node, key }。key 是列表里一行的身份(视图、种类、路径),按钮没有(按节点记)。
|
|
17
17
|
// 可按:没有 disabled 的 button、.row.entry、.row.more、.row.retry、.cell、.gnote.more、.gnote.retry;.dead 的条目也算(它们能选中、能右键)。
|
|
18
|
+
// 列表的行有三种画面:目录树(tree)、搜索结果(search,行上带 .hit)、图标视图(grid),身份里记哪一种,同一路径在不同画面里不是同一个按下。
|
|
18
19
|
function targetOf(event) {
|
|
19
20
|
const node = event.target?.closest?.('.row, .cell, .gnote, button');
|
|
20
21
|
if (!node) return null;
|
|
21
22
|
if (node.tagName === 'BUTTON') return node.disabled || node.getAttribute('disabled') !== null ? null : { node, key: null };
|
|
22
23
|
const has = name => node.classList.contains(name), path = node.dataset.path;
|
|
23
24
|
const kind = has('cell') || has('entry') ? 'entry' : has('retry') ? 'retry' : has('more') ? 'more' : null;
|
|
24
|
-
return kind === null || path === undefined ? null : { node, key: `${has('row') ? 'tree' : 'grid'}\n${kind}\n${path}` };
|
|
25
|
+
return kind === null || path === undefined ? null : { node, key: `${has('hit') ? 'search' : has('row') ? 'tree' : 'grid'}\n${kind}\n${path}` };
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
// identity():会话和根目录的身份(model.session、model.scope 拼成的字符串);换了就不是同一个按下。
|
package/view/preview.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
|
|
2
2
|
import { h } from './dom.mjs';
|
|
3
|
+
import { createFind } from './find.mjs';
|
|
3
4
|
import { formatSize } from './format.mjs';
|
|
4
5
|
import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
|
|
5
6
|
import { icon, iconFor } from './icons.mjs';
|
|
@@ -58,19 +59,39 @@ export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (t
|
|
|
58
59
|
// back:给了就在头部最左边放「返回」(Mac 侧栏预览:原生工具栏项目只能在右侧);文件页和 iPhone 不传。
|
|
59
60
|
// open(path, scroll) 带了要恢复的位置时,返回的 Promise 在「位置用上了」时变 true(正文到了、已设好位置;读取失败不算,位置留着等重试),
|
|
60
61
|
// 在「位置作废」时变 false(预览关了、改看别的文件)。读取被刷新、重载或 changed 作废时位置不丢:接替它的那次读取接着带上,用上才算完。
|
|
62
|
+
// 文件内查找(第 18.6 节)是预览自己的一部分,接在预览已有的生命周期上:open 换了文件、reload、stop、close 关查找;refresh 保留;release 不碰。
|
|
63
|
+
// 页面只负责入口:canFind(有显示着的文本才有)、openFind()(⌘F、iPhone 的「查找」菜单项)。consumed(event):这个按键已经被菜单消费了(菜单开着时的 Esc)。
|
|
61
64
|
// selectionMenu(event, { path, text, startLine, endLine }):给了就接管正文里选中文字的右键(只有 Mac 传);预览不知道菜单里是什么。
|
|
62
65
|
// 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
|
|
63
|
-
export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null }) {
|
|
66
|
+
export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false }) {
|
|
64
67
|
const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
|
|
65
68
|
const fileIcon = h('span', { class: 'pico', 'aria-hidden': 'true' });
|
|
66
69
|
// 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
|
|
67
70
|
const action = (label, glyph, run) => h('button', { class: glyph ? 'icon' : 'link', 'aria-label': label, title: label, onclick: run }, glyph ? icon(glyph, 18) : label);
|
|
68
71
|
const copyPath = () => path !== null && copy(path);
|
|
69
72
|
const retryButton = h('button', { class: 'link', onclick: () => load(true), hidden: true }, '重试');
|
|
70
|
-
const body = h('div', { class: 'pbody' });
|
|
73
|
+
const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
|
|
74
|
+
let gutterEl = null;
|
|
75
|
+
const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
|
|
71
76
|
const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
|
|
72
77
|
el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), retryButton,
|
|
73
|
-
...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), body);
|
|
78
|
+
...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), find.el, body);
|
|
79
|
+
find.done.addEventListener('click', () => { find.close(); body.focus(); });
|
|
80
|
+
// 查找条的键盘:Esc 关(从查找条里关,焦点回正文;焦点在正文里,焦点留在正文);⌘G、⇧⌘G 下一个、上一个。输入法组字中的按键不管,菜单消费掉的 Esc 不再处理。
|
|
81
|
+
el.addEventListener('keydown', event => {
|
|
82
|
+
if (!find.isOpen || event.isComposing) return;
|
|
83
|
+
if (event.key === 'Escape' && consumed(event)) { event.preventDefault(); return; } // 菜单关掉的 Esc:查找输入框是 type=search,默认动作会清空它,要拦下
|
|
84
|
+
if (event.key === 'Escape') {
|
|
85
|
+
event.preventDefault();
|
|
86
|
+
const fromBar = find.el.contains(document.activeElement);
|
|
87
|
+
find.close();
|
|
88
|
+
if (fromBar) body.focus();
|
|
89
|
+
} else if (event.key?.toLowerCase() === 'g' && event.metaKey && !event.ctrlKey && !event.altKey) {
|
|
90
|
+
event.preventDefault();
|
|
91
|
+
if (event.shiftKey) find.prev(); else find.next();
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
let textShown = false, pendingFind = null, longLine = false; // 现在显示的是不是文本;show() 换好的正文,等滚动位置设好再交给查找
|
|
74
95
|
|
|
75
96
|
let path = null, token = 0, shown = null, objectUrl = null; // shown:当前显示的 { size, mtimeMs }
|
|
76
97
|
let opens = 0, stoppedAt = -1; // 打开次数和上一次停止时的次数:释放只在停止之后没有再打开过时才做(返回的退场还没结束又打开了)
|
|
@@ -93,6 +114,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
93
114
|
|
|
94
115
|
function show(result) {
|
|
95
116
|
revoke();
|
|
117
|
+
textShown = result.kind === ContentKind.TEXT;
|
|
118
|
+
pendingFind = null;
|
|
119
|
+
if (!textShown) find.close(); // 图片、二进制没有查找
|
|
96
120
|
shown = { size: result.size, mtimeMs: result.mtimeMs };
|
|
97
121
|
// 元信息:目录 · 行数 · 大小;根目录下的文件没有目录,非文本没有行数。修改时间放进 title。
|
|
98
122
|
// 高亮:认得出语言才试;超过上限不试,库或解析出错就退回纯文本,都在元信息里注明。认不出语言的不加说明。
|
|
@@ -100,7 +124,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
100
124
|
const lines = result.kind === ContentKind.TEXT ? `${lineCount(result.text)} 行` : '';
|
|
101
125
|
const language = result.kind === ContentKind.TEXT ? languageOf(path.split('/').pop()) : null;
|
|
102
126
|
// 先判大小,超过只写「不高亮」;没超再判行长。
|
|
103
|
-
|
|
127
|
+
// 有长行:上色已经按它判断,查找也用同一个结果(不再扫一遍正文):长行里注册高亮会让浏览器同步重画整行,所以只计数、导航、滚动。
|
|
128
|
+
longLine = result.kind === ContentKind.TEXT && hasLongLine(result.text);
|
|
129
|
+
const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : longLine ? '行太长,不高亮' : '';
|
|
104
130
|
const colored = language && !skip ? highlight(result.text, language) : null;
|
|
105
131
|
const plain = !language ? '' : skip || (colored ? '' : '没能高亮');
|
|
106
132
|
const note = [result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '', plain].filter(Boolean).join(',');
|
|
@@ -109,6 +135,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
109
135
|
const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
|
|
110
136
|
const text = h('pre', { class: 'text selectable' }, ...(colored ? [] : [result.text]));
|
|
111
137
|
if (colored) appendAll(text, colored);
|
|
138
|
+
gutterEl = gutter;
|
|
139
|
+
pendingFind = { el: text, text: result.text, highlight: !longLine };
|
|
112
140
|
if (selectionMenu) text.addEventListener('contextmenu', event => onSelect(event, text));
|
|
113
141
|
body.replaceChildren(h('div', { class: 'code' }, gutter, text));
|
|
114
142
|
} else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
|
|
@@ -129,15 +157,17 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
129
157
|
|
|
130
158
|
function failure(error, silent, retry) {
|
|
131
159
|
if (error.stale) return;
|
|
132
|
-
if (error.code === ErrorCode.NOT_FOUND) { shown = null; setMeta(' '); return notice('文件已不存在', path); }
|
|
160
|
+
if (error.code === ErrorCode.NOT_FOUND) { shown = null; textShown = false; find.clearContent(); setMeta(' '); return notice('文件已不存在', path); }
|
|
133
161
|
if (silent && shown) return setStale(error.message); // 后台刷新失败:保留正文,提示原因
|
|
162
|
+
textShown = false;
|
|
163
|
+
find.clearContent(); // 整页重读失败:标记清掉,计数写「—」,之后再读成功就重新找
|
|
134
164
|
notice('读不到这个文件', error.message, { label: '重试', run: retry });
|
|
135
165
|
}
|
|
136
166
|
|
|
137
167
|
// silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置;有待恢复的位置时用它。
|
|
138
168
|
async function load(silent) {
|
|
139
169
|
const mine = ++token, mark = () => mine === token;
|
|
140
|
-
if (!silent) { shown = null; setMeta('读取中…'); revoke(); body.replaceChildren(); }
|
|
170
|
+
if (!silent) { shown = null; textShown = false; find.clearContent(); setMeta('读取中…'); revoke(); body.replaceChildren(); }
|
|
141
171
|
try {
|
|
142
172
|
const result = await readFile(offset => read(path, offset), {
|
|
143
173
|
prev: silent ? shown : null, cancelled: () => !mark(),
|
|
@@ -149,6 +179,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
149
179
|
const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
|
|
150
180
|
show(result);
|
|
151
181
|
body.scrollTop = keep.top; body.scrollLeft = keep.left;
|
|
182
|
+
// 顺序:换正文 → 设好滚动位置 → 重建查找(刷新和换正文时查找不滚动,不盖掉恢复)
|
|
183
|
+
if (pendingFind) find.setContent(pendingFind.el, pendingFind.text, { highlight: pendingFind.highlight });
|
|
152
184
|
settle(true);
|
|
153
185
|
} catch (error) {
|
|
154
186
|
if (mark()) failure(error, silent, () => load(false)); // 失败不算用上:待恢复的位置留着,重试或之后的刷新成功才用、才清
|
|
@@ -158,6 +190,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
158
190
|
return {
|
|
159
191
|
open(next, scroll = null) {
|
|
160
192
|
settle(false);
|
|
193
|
+
if (next !== path) find.close(); // 换了文件就关查找,不靠调用方先 stop()
|
|
161
194
|
opens++;
|
|
162
195
|
path = next;
|
|
163
196
|
const base = next.split('/').pop();
|
|
@@ -171,9 +204,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
171
204
|
copyPath,
|
|
172
205
|
refresh() { return path === null ? undefined : load(true); },
|
|
173
206
|
// 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
|
|
174
|
-
reload() { return path === null ? undefined : load(false); },
|
|
207
|
+
reload() { find.close(); return path === null ? undefined : load(false); }, // 来源变了:查找也关
|
|
175
208
|
// 停止(逻辑关闭,立即):不再读、不再刷新,待恢复的位置结算;画面(正文、图片的 URL)留着,由 release 在退场结束时清掉。
|
|
176
|
-
stop() { settle(false); token++; path = null; shown = null; stoppedAt = opens; },
|
|
209
|
+
stop() { settle(false); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
|
|
177
210
|
// 释放(画面):停止之后又打开过就什么都不做。
|
|
178
211
|
release() {
|
|
179
212
|
if (stoppedAt !== opens) return; // 停止之后又打开过(打开次数变了):这一屏是新的,不是退场的旧页
|
|
@@ -187,5 +220,11 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
187
220
|
scroll: () => (path === null ? { top: 0, left: 0 } : { top: body.scrollTop, left: body.scrollLeft }),
|
|
188
221
|
onScroll: fn => body.addEventListener('scroll', fn, { passive: true }),
|
|
189
222
|
get path() { return path; },
|
|
223
|
+
// 文件内查找的入口:有显示着的文本(或查找条已经开着)才有。
|
|
224
|
+
get canFind() { return path !== null && (textShown || find.isOpen); },
|
|
225
|
+
get findOpen() { return find.isOpen; },
|
|
226
|
+
openFind() { if (this.canFind) find.open(); return this.canFind; },
|
|
227
|
+
closeFind() { find.close(); },
|
|
228
|
+
find,
|
|
190
229
|
};
|
|
191
230
|
}
|
package/view/protocol.mjs
CHANGED
|
@@ -13,18 +13,22 @@ export const SNIFF_BYTES = 8000;
|
|
|
13
13
|
export const REQUEST_ID_MAX = 64;
|
|
14
14
|
// 输入框草稿的文字上限(UTF-16 单元);拼完超过就不写。
|
|
15
15
|
export const DRAFT_LIMIT = 100_000;
|
|
16
|
+
// 文件名搜索(设计见 docs/design/phase-3.md 第 18 节):搜索词去掉首尾空白后的长度上限(UTF-16 单元)、结果条数上限。
|
|
17
|
+
export const QUERY_MAX = 256;
|
|
18
|
+
export const SEARCH_RESULTS = 500;
|
|
16
19
|
|
|
17
20
|
export const Type = Object.freeze({
|
|
18
21
|
HELLO: 'hello', REFRESH: 'refresh', LIST: 'list', READ: 'read', STAT: 'stat', DIR_SIZE: 'dir_size', ADD_TEXT: 'add_text',
|
|
19
|
-
|
|
22
|
+
SEARCH: 'search',
|
|
23
|
+
DIR_SIZE_CANCEL: 'dir_size_cancel', SEARCH_CANCEL: 'search_cancel', // 没有回答
|
|
20
24
|
SESSION: 'session', ROOT: 'root', CHANGED: 'changed',
|
|
21
|
-
LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added',
|
|
25
|
+
LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added', SEARCHED: 'searched',
|
|
22
26
|
});
|
|
23
27
|
|
|
24
28
|
// 请求 → 回答的类型。模块回答、页面分发都查这一张。
|
|
25
29
|
export const ReplyOf = Object.freeze({
|
|
26
30
|
[Type.LIST]: Type.LISTED, [Type.READ]: Type.CHUNK, [Type.STAT]: Type.STATTED,
|
|
27
|
-
[Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED,
|
|
31
|
+
[Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED, [Type.SEARCH]: Type.SEARCHED,
|
|
28
32
|
});
|
|
29
33
|
export const isReply = type => Object.values(ReplyOf).includes(type);
|
|
30
34
|
|
|
@@ -34,7 +38,7 @@ export const ErrorCode = Object.freeze({
|
|
|
34
38
|
NO_ROOT: 'no_root', INVALID_PATH: 'invalid_path', OUTSIDE_ROOT: 'outside_root', NOT_FOUND: 'not_found',
|
|
35
39
|
NOT_DIR: 'not_dir', NOT_FILE: 'not_file', DENIED: 'denied', CURSOR_EXPIRED: 'cursor_expired',
|
|
36
40
|
INVALID_OFFSET: 'invalid_offset', INVALID_SORT: 'invalid_sort', TOO_LARGE: 'too_large', IO: 'io_error',
|
|
37
|
-
DRAFT_FAILED: 'draft_failed', DRAFT_TOO_LONG: 'draft_too_long',
|
|
41
|
+
DRAFT_FAILED: 'draft_failed', DRAFT_TOO_LONG: 'draft_too_long', INVALID_QUERY: 'invalid_query',
|
|
38
42
|
});
|
|
39
43
|
|
|
40
44
|
// 目录排序:值是下面四种之一,缺省(请求不带 sort)是名称。方向由排序键决定,只在 lib/tree.mjs 里定义一处。
|
|
@@ -74,6 +78,34 @@ export function splitRelative(path) {
|
|
|
74
78
|
return { segments };
|
|
75
79
|
}
|
|
76
80
|
|
|
81
|
+
// 隐藏名单:按全名比。目录树、图标视图的「显示隐藏文件」和文件名搜索(模块和页面)共用这一处。
|
|
82
|
+
const HIDDEN = new Set(['.git', '.DS_Store']);
|
|
83
|
+
export const isHidden = name => HIDDEN.has(name);
|
|
84
|
+
|
|
85
|
+
// 文件名搜索的比较:名字和搜索词都先 NFC 规范化再 toLowerCase,包含就算。模块判断匹配、页面加粗用同一个函数。
|
|
86
|
+
export const foldName = text => text.normalize('NFC').toLowerCase();
|
|
87
|
+
|
|
88
|
+
// 页面加粗:搜索词(已 foldName)在名字里第一次出现的位置,返回原名字里的 [起点, 终点)(UTF-16 下标),没有或映射不出来返回 null。
|
|
89
|
+
// 比较是在规范化后的串上做的:把原名字切成「一个基字符加它的组合符号」,每段各自规范化、变小写,拼起来要等于整串的结果,
|
|
90
|
+
// 这样才能建「规范化后的位置 → 原名字的位置」的对照;拼不起来(如谚文字母的组合)、命中段的两端落在一段中间(一个字符变小写后变成两个)都不加粗。
|
|
91
|
+
const CLUSTER = /\P{M}\p{M}*|\p{M}+/gu;
|
|
92
|
+
export function matchSpan(name, folded) {
|
|
93
|
+
const whole = foldName(name), at = whole.indexOf(folded);
|
|
94
|
+
if (at < 0 || folded === '') return null;
|
|
95
|
+
const starts = new Map(), ends = new Map(); // 规范化后的位置 → 原名字的位置
|
|
96
|
+
let from = 0, to = 0, out = '';
|
|
97
|
+
for (const [piece] of name.matchAll(CLUSTER)) {
|
|
98
|
+
const folding = foldName(piece);
|
|
99
|
+
starts.set(from, to);
|
|
100
|
+
from += folding.length;
|
|
101
|
+
to += piece.length;
|
|
102
|
+
ends.set(from, to);
|
|
103
|
+
out += folding;
|
|
104
|
+
}
|
|
105
|
+
if (out !== whole || !starts.has(at) || !ends.has(at + folded.length)) return null;
|
|
106
|
+
return [starts.get(at), ends.get(at + folded.length)];
|
|
107
|
+
}
|
|
108
|
+
|
|
77
109
|
export const messageSize = message => JSON.stringify({ message }).length;
|
|
78
110
|
|
|
79
111
|
// 带 code 的错误,模块里到处抛,主模块转成回答里的 error。
|
|
@@ -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
|
+
}
|