@coda-console/resource-manager 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +64 -2
- package/lib/content.mjs +36 -0
- package/lib/paths.mjs +47 -0
- package/lib/root.mjs +26 -0
- package/lib/tree.mjs +74 -0
- package/main.mjs +137 -0
- package/package.json +24 -4
- package/view/app.mjs +227 -0
- package/view/bar.mjs +16 -0
- package/view/connection.mjs +109 -0
- package/view/file-app.mjs +139 -0
- package/view/file.html +17 -0
- package/view/index.html +20 -0
- package/view/model.mjs +222 -0
- package/view/notice.mjs +19 -0
- package/view/preview.mjs +144 -0
- package/view/protocol.mjs +49 -0
- package/view/style.css +98 -0
- package/view/tree.mjs +148 -0
package/view/preview.mjs
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
|
|
2
|
+
import { ContentKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType } from './protocol.mjs';
|
|
3
|
+
|
|
4
|
+
function fromBase64(data) {
|
|
5
|
+
const binary = atob(data), bytes = new Uint8Array(binary.length);
|
|
6
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
7
|
+
return bytes;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// 一块一块读完一个文件。read(offset) 返回 chunk 回答。
|
|
11
|
+
// 文本把所有块拼成字节后再解码,多字节字符被块边界切开也没关系。
|
|
12
|
+
// 传入 prev(上次的 size、mtimeMs)时,没变就只返回 { same: true };读的途中文件变了就重读,最多三次。
|
|
13
|
+
export async function readFile(read, { prev = null, onProgress = () => {}, cancelled = () => false } = {}) {
|
|
14
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
15
|
+
let chunk = await read(0);
|
|
16
|
+
if (prev && chunk.size === prev.size && chunk.mtimeMs === prev.mtimeMs) return { same: true };
|
|
17
|
+
const { kind, size, mtimeMs } = chunk;
|
|
18
|
+
const total = kind === ContentKind.TEXT ? Math.min(size, TEXT_LIMIT) : kind === ContentKind.IMAGE && size <= IMAGE_LIMIT ? size : 0;
|
|
19
|
+
const parts = [];
|
|
20
|
+
let got = 0, moved = false;
|
|
21
|
+
for (;;) {
|
|
22
|
+
const bytes = fromBase64(chunk.data);
|
|
23
|
+
parts.push(bytes);
|
|
24
|
+
got += bytes.length;
|
|
25
|
+
onProgress(got, total);
|
|
26
|
+
if (chunk.eof || bytes.length === 0) break;
|
|
27
|
+
if (cancelled()) return { cancelled: true };
|
|
28
|
+
chunk = await read(got);
|
|
29
|
+
if (chunk.size !== size || chunk.mtimeMs !== mtimeMs) { moved = true; break; }
|
|
30
|
+
}
|
|
31
|
+
if (moved) continue;
|
|
32
|
+
const all = new Uint8Array(got);
|
|
33
|
+
let at = 0;
|
|
34
|
+
for (const part of parts) { all.set(part, at); at += part.length; }
|
|
35
|
+
const result = { same: false, kind, size, mtimeMs, bytes: all, truncated: kind === ContentKind.TEXT && size > TEXT_LIMIT };
|
|
36
|
+
if (kind === ContentKind.TEXT) {
|
|
37
|
+
result.text = new TextDecoder().decode(all);
|
|
38
|
+
if (result.truncated && result.text.endsWith('�')) result.text = result.text.slice(0, -1); // 1 MiB 处可能切在字符中间
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
const error = new Error('文件一直在变化,稍后再试');
|
|
43
|
+
throw Object.assign(error, { code: ErrorCode.IO });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function formatSize(bytes) {
|
|
47
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
48
|
+
const units = ['KiB', 'MiB', 'GiB'];
|
|
49
|
+
let value = bytes / 1024, unit = 0;
|
|
50
|
+
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
|
|
51
|
+
return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
|
|
52
|
+
}
|
|
53
|
+
const formatTime = ms => new Date(ms).toLocaleString('zh-CN', { hour12: false });
|
|
54
|
+
export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0));
|
|
55
|
+
|
|
56
|
+
const h = (tag, attributes = {}, ...children) => {
|
|
57
|
+
const node = document.createElement(tag);
|
|
58
|
+
for (const [key, value] of Object.entries(attributes)) {
|
|
59
|
+
if (key.startsWith('on')) node.addEventListener(key.slice(2), value); else if (value != null && value !== false) node.setAttribute(key, value);
|
|
60
|
+
}
|
|
61
|
+
node.append(...children.flat().filter(child => child != null));
|
|
62
|
+
return node;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// read(path, offset) → Promise<chunk 回答>,会话换了会以 stale 错误拒绝;copy(text) 复制路径。
|
|
66
|
+
// actions:头部在「复制路径」旁额外加的按钮 [{ label, run(path) }],预览不知道它们做什么。
|
|
67
|
+
export function mountPreview(el, { read, copy, actions = [] }) {
|
|
68
|
+
const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
|
|
69
|
+
const copyButton = h('button', { class: 'link', onclick: () => path !== null && copy(path) }, '复制路径');
|
|
70
|
+
const retryButton = h('button', { class: 'link', onclick: () => load(null, true), hidden: true }, '重试');
|
|
71
|
+
const body = h('div', { class: 'pbody' });
|
|
72
|
+
const extra = actions.map(({ label, run }) => h('button', { class: 'link', onclick: () => path !== null && run(path) }, label));
|
|
73
|
+
el.replaceChildren(h('div', { class: 'phead' }, h('div', { class: 'grow' }, name, meta), retryButton, copyButton, ...extra), body);
|
|
74
|
+
|
|
75
|
+
let path = null, token = 0, shown = null, objectUrl = null; // shown:当前显示的 { size, mtimeMs }
|
|
76
|
+
let metaText = ' ', stale = null; // stale:后台刷新失败的原因,此时正文还是上次的
|
|
77
|
+
// 更新失败的提示占用元信息那一行,重试按钮在头部,所以正文不会被顶动。
|
|
78
|
+
const paintMeta = () => {
|
|
79
|
+
meta.textContent = stale ? `更新失败:${stale}` : metaText;
|
|
80
|
+
meta.title = stale ?? '';
|
|
81
|
+
meta.classList.toggle('warn', stale !== null);
|
|
82
|
+
retryButton.hidden = stale === null;
|
|
83
|
+
};
|
|
84
|
+
const setMeta = text => { metaText = text; stale = null; paintMeta(); };
|
|
85
|
+
const setStale = reason => { stale = reason; paintMeta(); };
|
|
86
|
+
const revoke = () => { if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
|
|
87
|
+
const notice = (title, detail, action) => body.replaceChildren(h('div', { class: 'empty' },
|
|
88
|
+
h('p', {}, title), detail ? h('p', { class: 'secondary' }, detail) : null,
|
|
89
|
+
action ? h('button', { class: 'link', onclick: action.run }, action.label) : null));
|
|
90
|
+
|
|
91
|
+
function show(result) {
|
|
92
|
+
revoke();
|
|
93
|
+
shown = { size: result.size, mtimeMs: result.mtimeMs };
|
|
94
|
+
const note = result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '';
|
|
95
|
+
setMeta([formatSize(result.size), formatTime(result.mtimeMs), note].filter(Boolean).join(' · '));
|
|
96
|
+
if (result.kind === ContentKind.TEXT) {
|
|
97
|
+
const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
|
|
98
|
+
body.replaceChildren(h('div', { class: 'code' }, gutter, h('pre', { class: 'text selectable' }, result.text)));
|
|
99
|
+
} else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
|
|
100
|
+
objectUrl = URL.createObjectURL(new Blob([result.bytes], { type: imageType(path) }));
|
|
101
|
+
body.replaceChildren(h('div', { class: 'image' }, h('img', { src: objectUrl, alt: path, draggable: 'false' })));
|
|
102
|
+
} else {
|
|
103
|
+
const big = result.kind === ContentKind.IMAGE ? `图片超过 ${formatSize(IMAGE_LIMIT)},不预览。` : '二进制文件,不预览。';
|
|
104
|
+
notice(big, `${formatSize(result.size)},修改于 ${formatTime(result.mtimeMs)}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function failure(error, silent, retry) {
|
|
109
|
+
if (error.stale) return;
|
|
110
|
+
if (error.code === ErrorCode.NOT_FOUND) { shown = null; setMeta(' '); return notice('文件已不存在', path); }
|
|
111
|
+
if (silent && shown) return setStale(error.message); // 后台刷新失败:保留正文,提示原因
|
|
112
|
+
notice('读不到这个文件', error.message, { label: '重试', run: retry });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置。
|
|
116
|
+
async function load(scroll, silent) {
|
|
117
|
+
const mine = ++token, mark = () => mine === token;
|
|
118
|
+
if (!silent) { shown = null; setMeta('读取中…'); revoke(); body.replaceChildren(); }
|
|
119
|
+
try {
|
|
120
|
+
const result = await readFile(offset => read(path, offset), {
|
|
121
|
+
prev: silent ? shown : null, cancelled: () => !mark(),
|
|
122
|
+
onProgress: (got, total) => { if (mark() && !silent && total > TEXT_LIMIT / 4) setMeta(`读取中 ${formatSize(got)} / ${formatSize(total)}`); },
|
|
123
|
+
});
|
|
124
|
+
if (!mark() || result.cancelled) return;
|
|
125
|
+
if (result.same) return setStale(null);
|
|
126
|
+
const keep = scroll ?? { top: body.scrollTop, left: body.scrollLeft };
|
|
127
|
+
show(result);
|
|
128
|
+
body.scrollTop = keep.top; body.scrollLeft = keep.left;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (mark()) failure(error, silent, () => load(null, false));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
open(next, scroll = null) { path = next; name.textContent = next.split('/').pop(); name.title = next; return load(scroll, false); },
|
|
136
|
+
refresh() { return path === null ? undefined : load(null, true); },
|
|
137
|
+
// 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
|
|
138
|
+
reload() { return path === null ? undefined : load(null, false); },
|
|
139
|
+
close() { token++; path = null; shown = null; setMeta(' '); revoke(); body.replaceChildren(); },
|
|
140
|
+
scroll: () => ({ top: body.scrollTop, left: body.scrollLeft }),
|
|
141
|
+
onScroll: fn => body.addEventListener('scroll', fn, { passive: true }),
|
|
142
|
+
get path() { return path; },
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// 模块和页面共用的消息格式与上限。只用浏览器和 Node 都有的东西。
|
|
2
|
+
|
|
3
|
+
// 宿主按 JSON.stringify({ message }).length 计量,超过的消息会被丢弃。
|
|
4
|
+
export const MESSAGE_LIMIT = 128 * 1024;
|
|
5
|
+
export const CHUNK_BYTES = 64 * 1024;
|
|
6
|
+
// 目录一页的上限(序列化后的 UTF-8 字节,含信封);信封(类型、代次、请求号、游标)留给下面这些字节。
|
|
7
|
+
export const PAGE_BYTES = 96 * 1024;
|
|
8
|
+
export const ENVELOPE_BYTES = 4096;
|
|
9
|
+
export const TEXT_LIMIT = 1024 * 1024;
|
|
10
|
+
export const IMAGE_LIMIT = 8 * 1024 * 1024;
|
|
11
|
+
// 前这么多字节里有 NUL 就当二进制(同 Coda 的 worktree-changes)。
|
|
12
|
+
export const SNIFF_BYTES = 8000;
|
|
13
|
+
export const REQUEST_ID_MAX = 64;
|
|
14
|
+
|
|
15
|
+
export const Type = Object.freeze({
|
|
16
|
+
HELLO: 'hello', REFRESH: 'refresh', LIST: 'list', READ: 'read',
|
|
17
|
+
SESSION: 'session', ROOT: 'root', CHANGED: 'changed', LISTED: 'listed', CHUNK: 'chunk',
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export const RootState = Object.freeze({ READY: 'ready', NONE: 'none', PREPARING: 'preparing', GONE: 'gone' });
|
|
21
|
+
|
|
22
|
+
export const ErrorCode = Object.freeze({
|
|
23
|
+
NO_ROOT: 'no_root', INVALID_PATH: 'invalid_path', OUTSIDE_ROOT: 'outside_root', NOT_FOUND: 'not_found',
|
|
24
|
+
NOT_DIR: 'not_dir', NOT_FILE: 'not_file', DENIED: 'denied', INVALID_CURSOR: 'invalid_cursor',
|
|
25
|
+
INVALID_OFFSET: 'invalid_offset', TOO_LARGE: 'too_large', IO: 'io_error',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// 目录条目的 kind:dir、file;link 是指向工作目录外或已失效的链接;other 是不能打开的(套接字、名字含控制字符等)。
|
|
29
|
+
// 指向工作目录内的链接按目标显示成 dir 或 file,并带 link: true。
|
|
30
|
+
export const EntryKind = Object.freeze({ DIR: 'dir', FILE: 'file', LINK: 'link', OTHER: 'other' });
|
|
31
|
+
// 文件块的 kind。
|
|
32
|
+
export const ContentKind = Object.freeze({ TEXT: 'text', IMAGE: 'image', BINARY: 'binary' });
|
|
33
|
+
|
|
34
|
+
const IMAGE_TYPES = {
|
|
35
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// 按扩展名给出图片的 MIME 类型,不是图片返回 null。
|
|
39
|
+
export function imageType(name) {
|
|
40
|
+
const dot = String(name).lastIndexOf('.');
|
|
41
|
+
return dot < 0 ? null : IMAGE_TYPES[name.slice(dot + 1).toLowerCase()] ?? null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const messageSize = message => JSON.stringify({ message }).length;
|
|
45
|
+
|
|
46
|
+
// 带 code 的错误,模块里到处抛,主模块转成回答里的 error。
|
|
47
|
+
export function fail(code, message) {
|
|
48
|
+
return Object.assign(new Error(message), { code, protocol: true });
|
|
49
|
+
}
|
package/view/style.css
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/* 资源管理器的页面,颜色、字体、字号只用 App 给的 --coda-* 变量(docs/plugins.md「视图」)。 */
|
|
2
|
+
:root {
|
|
3
|
+
--hover: var(--coda-hover, var(--coda-fill, rgba(0,0,0,.05)));
|
|
4
|
+
--line: var(--coda-separator, rgba(0,0,0,.1));
|
|
5
|
+
--row-h: calc(var(--coda-font-size, 13px) * 1.9);
|
|
6
|
+
--indent: 12px; --pad: 8px;
|
|
7
|
+
/* 安全区:横屏时客户端不替页面留,页面自己按这几个值留白;变量便于 harness 模拟。 */
|
|
8
|
+
--safe-top: env(safe-area-inset-top, 0px); --safe-right: env(safe-area-inset-right, 0px);
|
|
9
|
+
--safe-bottom: env(safe-area-inset-bottom, 0px); --safe-left: env(safe-area-inset-left, 0px);
|
|
10
|
+
font: var(--coda-font-size, 13px)/1.45 var(--coda-font, -apple-system, system-ui, sans-serif);
|
|
11
|
+
color: var(--coda-foreground, #1d1d1f); background: transparent;
|
|
12
|
+
}
|
|
13
|
+
* { box-sizing: border-box; }
|
|
14
|
+
html, body { margin: 0; height: 100%; }
|
|
15
|
+
body { display: flex; flex-direction: column; overflow: hidden; -webkit-user-select: none; user-select: none;
|
|
16
|
+
padding: var(--safe-top) var(--safe-right) 0 var(--safe-left); }
|
|
17
|
+
.selectable { -webkit-user-select: text; user-select: text; }
|
|
18
|
+
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; text-align: inherit; cursor: pointer; }
|
|
19
|
+
button:focus-visible { outline: 2px solid var(--coda-accent, #0a84ff); outline-offset: 2px; border-radius: 6px; }
|
|
20
|
+
button.link { color: var(--coda-accent, #0a84ff); }
|
|
21
|
+
p { margin: 0; }
|
|
22
|
+
.secondary { color: var(--coda-secondary, #6e6e73); }
|
|
23
|
+
.caption { font-size: .85em; }
|
|
24
|
+
.grow { flex: 1 1 auto; min-width: 0; }
|
|
25
|
+
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
26
|
+
[hidden] { display: none !important; }
|
|
27
|
+
|
|
28
|
+
/* 三个面板叠在同一处,只切可见性:隐藏的树保留滚动位置,切换不改变布局。 */
|
|
29
|
+
#stage { position: relative; flex: 1 1 auto; min-height: 0; }
|
|
30
|
+
.pane { position: absolute; inset: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: var(--safe-bottom); }
|
|
31
|
+
.pane.off { visibility: hidden; pointer-events: none; }
|
|
32
|
+
.empty { display: grid; align-content: start; justify-items: center; gap: 6px; padding: 32px 20px; text-align: center; }
|
|
33
|
+
|
|
34
|
+
.bar { display: flex; gap: 4px; padding: 6px 8px; border-bottom: 1px solid var(--line); }
|
|
35
|
+
.bar button { padding: 3px 8px; border-radius: var(--coda-radius, 6px); color: var(--coda-secondary, #6e6e73); }
|
|
36
|
+
.bar button.on { color: var(--coda-accent, #0a84ff); }
|
|
37
|
+
|
|
38
|
+
/* 树:只画可见的一段,行高固定(tree.mjs 量 .row 的高度)。 */
|
|
39
|
+
.spacer { position: relative; }
|
|
40
|
+
.win { position: absolute; left: 0; right: 0; top: 0; }
|
|
41
|
+
.row { display: flex; align-items: center; gap: 4px; height: var(--row-h); padding-right: 8px; white-space: nowrap; cursor: default; }
|
|
42
|
+
.row.sel { background: var(--coda-selection, var(--hover)); }
|
|
43
|
+
.row.more, .row.retry { color: var(--coda-accent, #0a84ff); cursor: pointer; }
|
|
44
|
+
.row.status { display: block; overflow: hidden; text-overflow: ellipsis; line-height: var(--row-h); color: var(--coda-secondary, #6e6e73); }
|
|
45
|
+
.row.dead .name { color: var(--coda-tertiary, #a1a1a6); }
|
|
46
|
+
.chev { flex: none; width: 14px; text-align: center; font-size: .8em; color: var(--coda-secondary, #6e6e73); }
|
|
47
|
+
.name { flex: 1 1 auto; min-width: 0; }
|
|
48
|
+
.tail { flex: none; width: 1em; text-align: center; color: var(--coda-secondary, #6e6e73); }
|
|
49
|
+
.tail.warn { color: var(--coda-orange, #b25000); }
|
|
50
|
+
|
|
51
|
+
/* 预览:头部永远占一行名字加一行说明,加载和失败只换下面的内容。 */
|
|
52
|
+
.preview { display: flex; flex-direction: column; overflow: hidden; }
|
|
53
|
+
.phead button { flex: none; white-space: nowrap; }
|
|
54
|
+
.phead { flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-bottom: 1px solid var(--line); }
|
|
55
|
+
.pname { font-weight: 600; }
|
|
56
|
+
.pbody { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
57
|
+
.code { display: flex; width: max-content; min-width: 100%; font: .9em/1.55 var(--coda-mono, ui-monospace, Menlo, monospace); }
|
|
58
|
+
.code pre { margin: 0; font: inherit; }
|
|
59
|
+
.gutter { position: sticky; left: 0; flex: none; padding: 6px 8px 6px 12px; text-align: right; background: var(--coda-background, #fff);
|
|
60
|
+
color: var(--coda-tertiary, #a1a1a6); -webkit-user-select: none; user-select: none; }
|
|
61
|
+
.text { flex: 1 0 auto; padding: 6px 12px 6px 4px; tab-size: 4; }
|
|
62
|
+
.image { display: grid; place-items: start center; padding: 12px; }
|
|
63
|
+
.image img { max-width: 100%; height: auto; border-radius: var(--coda-radius, 6px); background: var(--coda-secondary-background, transparent); }
|
|
64
|
+
|
|
65
|
+
#notice:focus { outline: none; }
|
|
66
|
+
.menu { position: fixed; z-index: 10; min-width: 150px; padding: 4px; border: 1px solid var(--coda-outline, var(--line)); border-radius: var(--coda-radius-card, 10px);
|
|
67
|
+
background: var(--coda-card, var(--coda-background, #fff)); }
|
|
68
|
+
.menu button { display: block; width: 100%; padding: 5px 10px; border-radius: var(--coda-radius, 6px); }
|
|
69
|
+
.menu-path { max-width: 280px; padding: 4px 10px 6px; overflow-wrap: anywhere; }
|
|
70
|
+
.pmeta.warn { color: var(--coda-orange, #b25000); }
|
|
71
|
+
|
|
72
|
+
.hint { position: fixed; left: calc(8px + var(--safe-left)); right: calc(8px + var(--safe-right)); bottom: calc(8px + var(--safe-bottom)); z-index: 10;
|
|
73
|
+
padding: 8px 12px; border: 1px solid var(--coda-outline, var(--line)); border-radius: var(--coda-radius-card, 10px);
|
|
74
|
+
background: var(--coda-card, var(--coda-background, #fff)); color: var(--coda-orange, #b25000); }
|
|
75
|
+
|
|
76
|
+
/* 悬停只在有鼠标时:触摸后不会留着。 */
|
|
77
|
+
@media (hover: hover) {
|
|
78
|
+
.bar button:hover { background: var(--hover); }
|
|
79
|
+
.row.entry:hover { background: var(--hover); }
|
|
80
|
+
.menu button:hover { background: var(--coda-selection, var(--hover)); }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/* iPhone:行和按钮至少 44 点;行高在这里定,tree.mjs 量 .row 得到,不另写一份。 */
|
|
84
|
+
.coda-ios { --row-h: 44px; --indent: 20px; --pad: 16px; }
|
|
85
|
+
.coda-ios .row { padding-right: 16px; gap: 8px; }
|
|
86
|
+
.coda-ios .chev { width: 24px; }
|
|
87
|
+
.coda-ios .row { -webkit-touch-callout: none; } /* 长按由页面接管,不弹系统菜单;选择和拖动另外已关 */
|
|
88
|
+
.coda-ios .row.entry:active { background: var(--hover); }
|
|
89
|
+
.coda-ios .bar { gap: 8px; padding: 4px 8px; }
|
|
90
|
+
.coda-ios button { min-height: 44px; min-width: 44px; }
|
|
91
|
+
.coda-ios .bar button { padding: 0 12px; border-radius: var(--coda-radius, 10px); }
|
|
92
|
+
.coda-ios .phead { padding: 4px 12px; gap: 4px; }
|
|
93
|
+
.coda-ios .phead button { padding: 0 8px; }
|
|
94
|
+
.coda-ios .menu button { padding: 0 12px; text-align: left; }
|
|
95
|
+
|
|
96
|
+
/* 横屏:客户端隐藏导航栏,页面自己给返回。近似 verticalSizeClass 的判断,不等价(iPad、Duo 不单独适配)。 */
|
|
97
|
+
.exit { display: none; }
|
|
98
|
+
@media (orientation: landscape) and (max-height: 500px) { .coda-ios .exit { display: inline-flex; align-items: center; } }
|
package/view/tree.mjs
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// 目录树:visibleRows 把模型压成扁平行(纯逻辑);mountTree 只画可见的那一段,上万条也不卡。
|
|
2
|
+
import { EntryKind } from './protocol.mjs';
|
|
3
|
+
import { isHidden, joinPath } from './model.mjs';
|
|
4
|
+
|
|
5
|
+
const OVERSCAN = 8;
|
|
6
|
+
// 长按:按住这么久、移动不超过这个距离才算。
|
|
7
|
+
export const HOLD_MS = 500;
|
|
8
|
+
export const HOLD_SLOP = 10;
|
|
9
|
+
|
|
10
|
+
// 行:{ type: 'entry' | 'status' | 'more', path, name, depth, kind, link, open, busy, failed, text }
|
|
11
|
+
export function visibleRows(model) {
|
|
12
|
+
const rows = [];
|
|
13
|
+
const walk = (dir, depth) => {
|
|
14
|
+
const state = model.dirs.get(dir);
|
|
15
|
+
if (!state || (!state.loaded && !state.error)) return rows.push({ type: 'status', path: dir, depth, text: '正在读取…' });
|
|
16
|
+
if (!state.loaded) return rows.push({ type: 'status', path: dir, depth, text: `读取失败:${state.error.message}`, retry: true });
|
|
17
|
+
// 刷新失败:旧条目保留,最上方加一行原因,点它重试。这一行不算内容,空目录的判断在它之后。
|
|
18
|
+
if (state.error) rows.push({ type: 'status', path: dir, depth, text: `更新失败:${state.error.message}`, retry: true });
|
|
19
|
+
const before = rows.length;
|
|
20
|
+
for (const entry of state.entries) {
|
|
21
|
+
if (!model.showHidden && isHidden(entry.name)) continue;
|
|
22
|
+
const path = joinPath(dir, entry.name), open = entry.kind === EntryKind.DIR && model.expanded.has(path);
|
|
23
|
+
rows.push({
|
|
24
|
+
type: 'entry', path, name: entry.name, depth, kind: entry.kind, link: entry.link === true, open,
|
|
25
|
+
busy: open && model.dirs.get(path)?.loading === true, failed: open ? model.dirs.get(path)?.error?.message : undefined,
|
|
26
|
+
});
|
|
27
|
+
if (open) walk(path, depth + 1);
|
|
28
|
+
}
|
|
29
|
+
if (state.next) rows.push({ type: 'more', path: dir, depth, text: state.loading ? '正在读取…' : '再显示' });
|
|
30
|
+
else if (rows.length === before) rows.push({ type: 'status', path: dir, depth, text: state.entries.length ? '只有隐藏项' : '空目录' });
|
|
31
|
+
};
|
|
32
|
+
walk('', 0);
|
|
33
|
+
return rows;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const TITLES = { [EntryKind.LINK]: '指向工作目录外的链接,不能打开', [EntryKind.OTHER]: '不能打开的文件' };
|
|
37
|
+
|
|
38
|
+
// handlers: { open(path), toggle(path), more(path), retry(path), menu(event, path, kind) }
|
|
39
|
+
// draggable:触屏上拖行没有用处,还会抢滚动,关掉。
|
|
40
|
+
// longPress:触屏上按住一行打开 handlers.menu(Mac 用右键)。不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
|
|
41
|
+
export function mountTree(el, model, handlers, { draggable = true, longPress = false } = {}) {
|
|
42
|
+
const spacer = document.createElement('div'), win = document.createElement('div');
|
|
43
|
+
spacer.className = 'spacer'; win.className = 'win';
|
|
44
|
+
spacer.append(win);
|
|
45
|
+
el.replaceChildren(spacer);
|
|
46
|
+
let rows = [], rowH = 24;
|
|
47
|
+
|
|
48
|
+
const measure = () => {
|
|
49
|
+
const probe = document.createElement('div');
|
|
50
|
+
probe.className = 'row';
|
|
51
|
+
probe.style.visibility = 'hidden';
|
|
52
|
+
el.append(probe);
|
|
53
|
+
rowH = probe.getBoundingClientRect().height || rowH;
|
|
54
|
+
probe.remove();
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
function paint() {
|
|
58
|
+
const first = Math.max(0, Math.floor(el.scrollTop / rowH) - OVERSCAN);
|
|
59
|
+
const last = Math.min(rows.length, Math.ceil((el.scrollTop + el.clientHeight) / rowH) + OVERSCAN);
|
|
60
|
+
win.style.transform = `translateY(${first * rowH}px)`;
|
|
61
|
+
win.replaceChildren(...rows.slice(first, last).map((row, i) => rowNode(row, first + i)));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function rowNode(row, index) {
|
|
65
|
+
const node = document.createElement('div');
|
|
66
|
+
node.className = `row ${row.type}`;
|
|
67
|
+
node.dataset.i = index;
|
|
68
|
+
node.style.paddingLeft = `calc(var(--indent) * ${row.depth} + var(--pad))`;
|
|
69
|
+
if (row.type !== 'entry') {
|
|
70
|
+
node.textContent = row.text;
|
|
71
|
+
if (row.retry) { node.classList.add('retry'); node.title = row.text; } // 长原因在行里被截断,Mac 悬停看全
|
|
72
|
+
return node;
|
|
73
|
+
}
|
|
74
|
+
const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER;
|
|
75
|
+
node.classList.add(row.kind);
|
|
76
|
+
if (dead) node.classList.add('dead');
|
|
77
|
+
if (row.path === model.selected) node.classList.add('sel');
|
|
78
|
+
if (row.kind === EntryKind.DIR) node.setAttribute('aria-expanded', row.open);
|
|
79
|
+
if (!dead && draggable) node.draggable = true;
|
|
80
|
+
const chevron = document.createElement('span'), label = document.createElement('span'), tail = document.createElement('span');
|
|
81
|
+
chevron.className = 'chev';
|
|
82
|
+
chevron.textContent = row.kind === EntryKind.DIR ? (row.busy ? '…' : row.open ? '▾' : '▸') : '';
|
|
83
|
+
label.className = 'name truncate';
|
|
84
|
+
label.textContent = row.name;
|
|
85
|
+
tail.className = row.failed ? 'tail warn' : 'tail';
|
|
86
|
+
tail.textContent = row.failed ? '!' : row.link ? '↪' : '';
|
|
87
|
+
node.title = row.failed ? `${row.path}\n读取失败:${row.failed}` : TITLES[row.kind] ? `${row.path}\n${TITLES[row.kind]}` : row.path;
|
|
88
|
+
node.append(chevron, label, tail);
|
|
89
|
+
return node;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const rowOf = event => rows[event.target.closest?.('.row')?.dataset.i];
|
|
93
|
+
|
|
94
|
+
// 长按:按下只记一个等待;移动超限、抬起、取消、滚动、第二根手指都作废。
|
|
95
|
+
// 触发后吞掉紧接着的那次点击;没有点击跟来时,下一次按下清掉,不会误吞后面真正的点击。
|
|
96
|
+
let hold = null, swallow = false;
|
|
97
|
+
const cancelHold = () => { if (hold) { clearTimeout(hold.timer); hold = null; } };
|
|
98
|
+
if (longPress) {
|
|
99
|
+
el.addEventListener('pointerdown', event => {
|
|
100
|
+
cancelHold();
|
|
101
|
+
swallow = false;
|
|
102
|
+
const row = rowOf(event);
|
|
103
|
+
if (event.isPrimary === false || row?.type !== 'entry') return;
|
|
104
|
+
const { clientX: x, clientY: y, pointerId: id } = event;
|
|
105
|
+
hold = { id, x, y, timer: setTimeout(() => {
|
|
106
|
+
hold = null;
|
|
107
|
+
swallow = true;
|
|
108
|
+
handlers.menu({ clientX: x, clientY: y }, row.path);
|
|
109
|
+
}, HOLD_MS) };
|
|
110
|
+
});
|
|
111
|
+
el.addEventListener('pointermove', event => {
|
|
112
|
+
if (hold && event.pointerId === hold.id && Math.hypot(event.clientX - hold.x, event.clientY - hold.y) > HOLD_SLOP) cancelHold();
|
|
113
|
+
});
|
|
114
|
+
for (const type of ['pointerup', 'pointercancel']) el.addEventListener(type, cancelHold);
|
|
115
|
+
el.addEventListener('scroll', cancelHold, { passive: true });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
el.addEventListener('click', event => {
|
|
119
|
+
if (swallow) { swallow = false; return; }
|
|
120
|
+
const row = rowOf(event);
|
|
121
|
+
if (!row) return;
|
|
122
|
+
if (row.type === 'more') return handlers.more(row.path);
|
|
123
|
+
if (row.type === 'status') return row.retry ? handlers.retry(row.path) : undefined;
|
|
124
|
+
if (row.kind === EntryKind.DIR) handlers.toggle(row.path);
|
|
125
|
+
else if (row.kind === EntryKind.FILE) handlers.open(row.path);
|
|
126
|
+
});
|
|
127
|
+
el.addEventListener('contextmenu', event => {
|
|
128
|
+
const row = rowOf(event);
|
|
129
|
+
if (row?.type === 'entry') { event.preventDefault(); handlers.menu(event, row.path); }
|
|
130
|
+
});
|
|
131
|
+
el.addEventListener('dragstart', event => {
|
|
132
|
+
const row = rowOf(event);
|
|
133
|
+
if (row?.type !== 'entry') return event.preventDefault();
|
|
134
|
+
event.dataTransfer.setData('text/plain', row.path); // 相对路径
|
|
135
|
+
event.dataTransfer.effectAllowed = 'copy';
|
|
136
|
+
});
|
|
137
|
+
el.addEventListener('scroll', paint, { passive: true });
|
|
138
|
+
new ResizeObserver(paint).observe(el);
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
render() { rows = visibleRows(model); spacer.style.height = `${rows.length * rowH}px`; paint(); },
|
|
142
|
+
remeasure() { measure(); this.render(); },
|
|
143
|
+
scroll: () => el.scrollTop,
|
|
144
|
+
scrollTo(top) { el.scrollTop = top; },
|
|
145
|
+
// 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。
|
|
146
|
+
reset() { cancelHold(); swallow = false; },
|
|
147
|
+
};
|
|
148
|
+
}
|