@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/bar.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// 页内工具条:没有 coda.toolbar 的平台(iPhone)用。两个页面共用,按钮由页面给。
|
|
2
|
+
// 「返回」只在横屏出现(导航栏隐藏时),显示与否由 style.css 的媒体查询决定,这里一律画出来。
|
|
3
|
+
export const EXIT = { id: 'exit', label: '返回', kind: 'button' };
|
|
4
|
+
|
|
5
|
+
export function paintBar(el, items, act) {
|
|
6
|
+
el.hidden = false;
|
|
7
|
+
el.replaceChildren(...items.map(item => {
|
|
8
|
+
const button = document.createElement('button');
|
|
9
|
+
button.textContent = item.label;
|
|
10
|
+
if (item.id === EXIT.id) button.classList.add('exit');
|
|
11
|
+
button.setAttribute('aria-pressed', item.kind === 'toggle' ? String(item.on) : 'false');
|
|
12
|
+
if (item.on) button.classList.add('on');
|
|
13
|
+
button.addEventListener('click', () => act(item.id));
|
|
14
|
+
return button;
|
|
15
|
+
}));
|
|
16
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// 页面到模块的连接:请求与回答(Link)、hello 握手与超时、按代次分发协议消息。
|
|
2
|
+
// 树页和文件页共用。只管连接:树的 Model、状态保存、提示文案和 DOM 都在各自的页面里。
|
|
3
|
+
import { ErrorCode, Type } from './protocol.mjs';
|
|
4
|
+
|
|
5
|
+
export const TIMEOUT_MS = 30_000;
|
|
6
|
+
|
|
7
|
+
// 会话已经换了,请求作废。调用方一律吞掉,不显示。
|
|
8
|
+
export class Stale extends Error { constructor() { super('已过期'); this.stale = true; } }
|
|
9
|
+
export class RequestError extends Error { constructor(code, message) { super(message); this.code = code; } }
|
|
10
|
+
|
|
11
|
+
// 请求与回答按 requestId 对应。回答要代次相同、请求号还在等待才算;换会话时 reset 作废所有等待并停掉超时。
|
|
12
|
+
export class Link {
|
|
13
|
+
generation = null;
|
|
14
|
+
pending = new Map();
|
|
15
|
+
#next = 1;
|
|
16
|
+
|
|
17
|
+
constructor({ post, timers = globalThis, timeoutMs = TIMEOUT_MS }) {
|
|
18
|
+
Object.assign(this, { post, timers, timeoutMs });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
reset(generation) {
|
|
22
|
+
this.generation = generation;
|
|
23
|
+
for (const entry of this.pending.values()) { this.timers.clearTimeout(entry.timer); entry.reject(new Stale()); }
|
|
24
|
+
this.pending.clear();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
call(type, fields) {
|
|
28
|
+
if (this.generation === null) return Promise.reject(new Stale());
|
|
29
|
+
const { generation } = this, requestId = `q${this.#next++}`;
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const settle = error => {
|
|
32
|
+
const entry = this.pending.get(requestId);
|
|
33
|
+
if (!entry) return;
|
|
34
|
+
this.pending.delete(requestId);
|
|
35
|
+
this.timers.clearTimeout(entry.timer);
|
|
36
|
+
reject(error);
|
|
37
|
+
};
|
|
38
|
+
const timer = this.timers.setTimeout(() => settle(new RequestError('timeout', '30 秒没有回答')), this.timeoutMs);
|
|
39
|
+
this.pending.set(requestId, { resolve, reject, timer });
|
|
40
|
+
Promise.resolve().then(() => this.post({ type, generation, requestId, ...fields }))
|
|
41
|
+
.catch(() => settle(new RequestError(ErrorCode.IO, '消息发不出去')));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
receive(message) {
|
|
46
|
+
if (message.generation !== this.generation) return false;
|
|
47
|
+
const entry = this.pending.get(message.requestId);
|
|
48
|
+
if (!entry) return false;
|
|
49
|
+
this.pending.delete(message.requestId);
|
|
50
|
+
this.timers.clearTimeout(entry.timer);
|
|
51
|
+
if (message.error) entry.reject(new RequestError(message.error.code, message.error.message));
|
|
52
|
+
else entry.resolve(message);
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 建立连接并开始监听模块的消息;调用 hello() 才发出握手。
|
|
58
|
+
// handlers:session、root、changed。session 先作废旧代次的请求再交给页面;
|
|
59
|
+
// root、changed 只在代次等于当前时才交出;listed、chunk 直接对应请求,页面不用管。
|
|
60
|
+
// 握手的结束条件是收到首个 root;之后不再提示超时。
|
|
61
|
+
// onStatus:握手状态变了(开始、失败、重试)时调用,页面据此重画说明。
|
|
62
|
+
export function connect(coda, { handlers, onStatus = () => {} }) {
|
|
63
|
+
const link = new Link({ post: message => coda.postMessage(message) });
|
|
64
|
+
let answered = false, timer = null, failure = null;
|
|
65
|
+
|
|
66
|
+
function fail(reason) {
|
|
67
|
+
if (answered) return;
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
failure = reason;
|
|
70
|
+
onStatus();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
window.addEventListener('message', ({ data }) => {
|
|
74
|
+
if (!data || typeof data !== 'object') return;
|
|
75
|
+
switch (data.type) {
|
|
76
|
+
case Type.SESSION:
|
|
77
|
+
link.reset(data.generation);
|
|
78
|
+
return handlers.session(data);
|
|
79
|
+
case Type.ROOT: case Type.CHANGED:
|
|
80
|
+
if (data.generation !== link.generation) return;
|
|
81
|
+
if (data.type === Type.ROOT) { // 首个 root 才算模块回答了:只收到 session 时页面还是空的,照样要提示
|
|
82
|
+
answered = true;
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
failure = null;
|
|
85
|
+
}
|
|
86
|
+
return handlers[data.type](data);
|
|
87
|
+
case Type.LISTED: case Type.CHUNK:
|
|
88
|
+
link.receive(data);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
link,
|
|
94
|
+
// 握手失败的原因,没有失败时为 null。
|
|
95
|
+
get failure() { return failure; },
|
|
96
|
+
async hello() {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
failure = null;
|
|
99
|
+
timer = setTimeout(() => fail('30 秒没有收到回答'), TIMEOUT_MS);
|
|
100
|
+
onStatus();
|
|
101
|
+
try { await coda.postMessage({ type: Type.HELLO }); } catch { fail('消息发不出去'); }
|
|
102
|
+
},
|
|
103
|
+
// 用户手动刷新:让模块先重新查询根目录。还没有代次(没收到 session)时无事可做。
|
|
104
|
+
refresh() {
|
|
105
|
+
if (link.generation === null) return;
|
|
106
|
+
try { Promise.resolve(coda.postMessage({ type: Type.REFRESH, generation: link.generation })).catch(() => {}); } catch { /* 宿主不可用 */ }
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// 文件视图的页面入口:读一个文件。会话和路径来自 coda.args(启动值),之后的变化走 context 事件;
|
|
2
|
+
// 连接在 connection.mjs,预览在 preview.mjs,这里不创建目录树。设计见 docs/design/phase-2.md 第 7 节。
|
|
3
|
+
import { EXIT, paintBar } from './bar.mjs';
|
|
4
|
+
import { connect } from './connection.mjs';
|
|
5
|
+
import { noticeText } from './model.mjs';
|
|
6
|
+
import { showNotice } from './notice.mjs';
|
|
7
|
+
import { mountPreview } from './preview.mjs';
|
|
8
|
+
import { RootState } from './protocol.mjs';
|
|
9
|
+
|
|
10
|
+
const coda = window.coda;
|
|
11
|
+
const $ = id => document.getElementById(id);
|
|
12
|
+
const quiet = fn => { try { return fn(); } catch { return undefined; } };
|
|
13
|
+
const hasToolbar = typeof coda.toolbar === 'function' && coda.platform === 'mac';
|
|
14
|
+
|
|
15
|
+
// 参数里的会话和路径,形状不对按没有处理。
|
|
16
|
+
const argsOf = args => ({
|
|
17
|
+
session: typeof args?.session === 'string' && args.session !== '' ? args.session : null,
|
|
18
|
+
path: typeof args?.path === 'string' && args.path !== '' ? args.path : null,
|
|
19
|
+
});
|
|
20
|
+
const num = n => (Number.isFinite(n) && n >= 0 ? n : 0);
|
|
21
|
+
// 读回来的值可能是别的版本或坏的,只认自己的形状。
|
|
22
|
+
const parseScroll = raw => (raw?.v === 1 ? { top: num(raw.top), left: num(raw.left) } : null);
|
|
23
|
+
|
|
24
|
+
let want = argsOf(coda.args); // 这个视图要看的会话和文件
|
|
25
|
+
let session; // 模块现在跟随的会话;undefined 表示还没收到 session
|
|
26
|
+
let root = null;
|
|
27
|
+
// 等内容到了再用一次的滚动位置。预览收起时也存在这里,恢复后接着用。
|
|
28
|
+
let restore = parseScroll(quiet(() => coda.getState()));
|
|
29
|
+
|
|
30
|
+
const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
|
|
31
|
+
const preview = mountPreview($('preview'), { read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text) });
|
|
32
|
+
|
|
33
|
+
// 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
|
|
34
|
+
const ready = () => want.path !== null && session === want.session && root?.state === RootState.READY;
|
|
35
|
+
|
|
36
|
+
// ---- 渲染:同一批变化合并成一次 ----
|
|
37
|
+
let queued = false;
|
|
38
|
+
function schedule() {
|
|
39
|
+
if (queued) return;
|
|
40
|
+
queued = true;
|
|
41
|
+
queueMicrotask(() => { queued = false; render(); });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function render() {
|
|
45
|
+
const open = ready();
|
|
46
|
+
$('preview').classList.toggle('off', !open);
|
|
47
|
+
$('preview').inert = !open;
|
|
48
|
+
$('notice').classList.toggle('off', open);
|
|
49
|
+
$('notice').inert = open;
|
|
50
|
+
if (open) {
|
|
51
|
+
if (preview.path !== want.path) openPreview();
|
|
52
|
+
} else {
|
|
53
|
+
park();
|
|
54
|
+
preview.close();
|
|
55
|
+
paintNotice();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function openPreview() {
|
|
60
|
+
const { path } = want, scroll = restore;
|
|
61
|
+
// 没有要恢复的位置就明确从头开始,不靠清空正文后滚动条自己归零。
|
|
62
|
+
preview.open(path, scroll ?? { top: 0, left: 0 }).then(() => { if (preview.path === path && restore === scroll) restore = null; });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 预览收起前记下滚动位置,恢复后接着用;内容还没到时 restore 还没用掉,不覆盖。
|
|
66
|
+
function park() {
|
|
67
|
+
if (preview.path !== null && restore === null) restore = preview.scroll();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
|
|
71
|
+
let noticeKey = null;
|
|
72
|
+
function paintNotice() {
|
|
73
|
+
const failed = conn.failure !== null && !root;
|
|
74
|
+
const key = want.path === null ? '没有指定要打开的文件。'
|
|
75
|
+
: failed ? `hello:${conn.failure}`
|
|
76
|
+
: noticeText(session === want.session ? root : null, session);
|
|
77
|
+
if (key === noticeKey) return;
|
|
78
|
+
noticeKey = key;
|
|
79
|
+
showNotice($('notice'), failed && want.path !== null ? { failure: conn.failure, retry: conn.hello } : { text: key });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- 模块的消息(代次和握手由 connection 处理)----
|
|
83
|
+
function onSession(data) {
|
|
84
|
+
park();
|
|
85
|
+
preview.close();
|
|
86
|
+
session = data.session ?? null;
|
|
87
|
+
root = null;
|
|
88
|
+
schedule();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function onRoot(data) {
|
|
92
|
+
const before = root;
|
|
93
|
+
root = { state: data.state, path: data.path };
|
|
94
|
+
if (data.state === RootState.READY) {
|
|
95
|
+
if (before?.path !== data.path) preview.reload(); else preview.refresh();
|
|
96
|
+
}
|
|
97
|
+
schedule();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function onChanged() {
|
|
101
|
+
if (root?.state === RootState.READY) preview.refresh();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ---- 参数变了:换文件或换会话,旧文件的滚动位置不带过去 ----
|
|
105
|
+
quiet(() => coda.on('context', ({ args }) => {
|
|
106
|
+
const next = argsOf(args);
|
|
107
|
+
if (next.path !== want.path || next.session !== want.session) { restore = null; preview.close(); }
|
|
108
|
+
want = next;
|
|
109
|
+
schedule();
|
|
110
|
+
}));
|
|
111
|
+
|
|
112
|
+
// ---- 工具条:Mac 用 coda.toolbar,没有的(iOS)退成页内一条 ----
|
|
113
|
+
const refresh = () => { conn.refresh(); preview.refresh(); };
|
|
114
|
+
const items = [{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }];
|
|
115
|
+
if (hasToolbar) {
|
|
116
|
+
quiet(() => coda.toolbar(items));
|
|
117
|
+
quiet(() => coda.on('toolbar', ({ id }) => { if (id === 'refresh') refresh(); }));
|
|
118
|
+
} else {
|
|
119
|
+
const exit = coda.platform === 'ios';
|
|
120
|
+
paintBar($('bar'), exit ? [EXIT, ...items] : items, id => (id === EXIT.id ? quiet(() => coda.close()) : refresh()));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---- 阅读位置:setState 按视图和 args 隔离,每个文件自然分开 ----
|
|
124
|
+
let saveTimer = null;
|
|
125
|
+
function queueSave() {
|
|
126
|
+
if (saveTimer === null) saveTimer = setTimeout(saveNow, 300);
|
|
127
|
+
}
|
|
128
|
+
function saveNow() {
|
|
129
|
+
clearTimeout(saveTimer);
|
|
130
|
+
saveTimer = null;
|
|
131
|
+
const at = restore ?? (preview.path !== null ? preview.scroll() : null);
|
|
132
|
+
if (at) quiet(() => coda.setState({ v: 1, top: at.top, left: at.left }));
|
|
133
|
+
}
|
|
134
|
+
// visibility: false 之后只保证同步事件处理完,所以同步保存。
|
|
135
|
+
quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
|
|
136
|
+
preview.onScroll(queueSave);
|
|
137
|
+
|
|
138
|
+
render();
|
|
139
|
+
conn.hello();
|
package/view/file.html
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<title>文件</title>
|
|
7
|
+
<link rel="stylesheet" href="style.css">
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<div id="bar" class="bar" hidden></div>
|
|
11
|
+
<main id="stage">
|
|
12
|
+
<div id="preview" class="pane preview"></div>
|
|
13
|
+
<div id="notice" class="pane empty secondary"></div>
|
|
14
|
+
</main>
|
|
15
|
+
<script type="module" src="file-app.mjs"></script>
|
|
16
|
+
</body>
|
|
17
|
+
</html>
|
package/view/index.html
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<title>资源管理器</title>
|
|
7
|
+
<link rel="stylesheet" href="style.css">
|
|
8
|
+
</head>
|
|
9
|
+
<body>
|
|
10
|
+
<div id="bar" class="bar" hidden></div>
|
|
11
|
+
<main id="stage">
|
|
12
|
+
<div id="tree" class="pane tree" role="tree"></div>
|
|
13
|
+
<div id="preview" class="pane preview"></div>
|
|
14
|
+
<div id="notice" class="pane empty secondary"></div>
|
|
15
|
+
</main>
|
|
16
|
+
<div id="menu" class="menu" role="menu" hidden></div>
|
|
17
|
+
<div id="hint" class="hint" role="status" hidden></div>
|
|
18
|
+
<script type="module" src="app.mjs"></script>
|
|
19
|
+
</body>
|
|
20
|
+
</html>
|
package/view/model.mjs
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// 页面的纯状态:目录树、状态保留。不碰 DOM,请求与代次在 connection.mjs,设计见 docs/design/phase-1.md 第 6、7 节。
|
|
2
|
+
import { ErrorCode, RootState, Type } from './protocol.mjs';
|
|
3
|
+
|
|
4
|
+
export const STATE_LIMIT = 96 * 1024;
|
|
5
|
+
export const MAX_PARALLEL = 8;
|
|
6
|
+
export const MAX_LOADED = 100_000; // 读回保存的条数时认的上界(view 侧校验用),与服务端的条目上限各自独立
|
|
7
|
+
// 恢复时每个目录最多取够这么多条(约 10 页):#reload 串行取够才显示,条数太大返回后会等很久。
|
|
8
|
+
// 只管「按保存的条数恢复」,用户已经翻出来的条数不受限;也和 lib/tree.mjs 的目录上限无关。
|
|
9
|
+
export const RESTORE_LIMIT = 20_000;
|
|
10
|
+
const MAX_LOADED_DIRS = 500;
|
|
11
|
+
const HIDDEN = new Set(['.git', '.DS_Store']);
|
|
12
|
+
export const isHidden = name => HIDDEN.has(name);
|
|
13
|
+
export const joinPath = (dir, name) => (dir ? `${dir}/${name}` : name);
|
|
14
|
+
const inside = (path, dir) => path === dir || path.startsWith(`${dir}/`);
|
|
15
|
+
|
|
16
|
+
async function pool(items, limit, fn) {
|
|
17
|
+
let index = 0;
|
|
18
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
19
|
+
while (index < items.length) await fn(items[index++]);
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// 根目录不可用时,树页和文件页显示的说明。root 为 null 表示还没收到。
|
|
24
|
+
export function noticeText(root, session) {
|
|
25
|
+
if (!root) return '正在读取…';
|
|
26
|
+
if (!session) return '没有打开的会话。';
|
|
27
|
+
return {
|
|
28
|
+
[RootState.NONE]: '这个会话没有可浏览的工作目录。',
|
|
29
|
+
[RootState.PREPARING]: '工作树还在准备,好了会自动显示。',
|
|
30
|
+
[RootState.GONE]: '工作目录已不存在,可能已随归档收回。再发消息会重建,之后自动恢复。',
|
|
31
|
+
}[root.state] ?? '';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class Model {
|
|
35
|
+
session = null;
|
|
36
|
+
root = null; // 收到 root 之前是 null
|
|
37
|
+
dirs = new Map(); // path → { entries, next, loaded, loading, error, token }
|
|
38
|
+
expanded = new Set(); // 不变量:展开的目录,它的每一级上层也展开
|
|
39
|
+
wanted = new Map(); // 恢复状态时各目录要取够的条数,第一次取用后删掉
|
|
40
|
+
selected = null;
|
|
41
|
+
showHidden = false;
|
|
42
|
+
|
|
43
|
+
constructor({ link, onChange = () => {} }) { Object.assign(this, { link, onChange }); }
|
|
44
|
+
|
|
45
|
+
get ready() { return this.root?.state === RootState.READY; }
|
|
46
|
+
|
|
47
|
+
// 模块来的消息统一从这里进。session 带上这个会话保存的状态;返回值同各个处理方法。
|
|
48
|
+
receive(message, saved = null) {
|
|
49
|
+
switch (message.type) {
|
|
50
|
+
case Type.SESSION: return this.onSession(message, saved);
|
|
51
|
+
case Type.ROOT: return this.onRoot(message);
|
|
52
|
+
case Type.CHANGED: return this.onChanged(message);
|
|
53
|
+
case Type.LISTED: case Type.CHUNK: return this.link.receive(message);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 换会话:清空一切,展开状态换成这个会话保存的。
|
|
58
|
+
onSession({ generation, session }, saved = null) {
|
|
59
|
+
this.link.reset(generation);
|
|
60
|
+
this.session = session ?? null;
|
|
61
|
+
this.root = null;
|
|
62
|
+
this.dirs = new Map();
|
|
63
|
+
this.wanted = new Map(Object.entries(saved?.loaded ?? {}).map(([path, count]) => [path, Math.min(count, RESTORE_LIMIT)]));
|
|
64
|
+
const paths = (saved?.expanded ?? []).filter(path => path !== '');
|
|
65
|
+
this.expanded = new Set(paths.filter(path => !path.includes('/') || paths.includes(path.slice(0, path.lastIndexOf('/')))));
|
|
66
|
+
this.selected = saved?.selected ?? null;
|
|
67
|
+
this.onChange();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 只换根目录状态,不动会话状态;ready 时重新取全部。
|
|
71
|
+
onRoot({ generation, state, path }) {
|
|
72
|
+
if (generation !== this.link.generation) return null;
|
|
73
|
+
this.root = { state, path };
|
|
74
|
+
this.onChange();
|
|
75
|
+
return state === RootState.READY ? this.refresh() : Promise.resolve();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
onChanged({ generation }) {
|
|
79
|
+
return generation === this.link.generation && this.ready ? this.refresh() : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 重新取根和全部已展开的目录,并行不超过 8 个。
|
|
83
|
+
refresh() {
|
|
84
|
+
if (!this.ready) return Promise.resolve();
|
|
85
|
+
const { generation } = this.link;
|
|
86
|
+
return pool(['', ...this.expanded], MAX_PARALLEL, path => this.#reload(path, generation));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。
|
|
90
|
+
async #reload(path, generation) {
|
|
91
|
+
if (this.link.generation !== generation) return; // 排队时会话已换,旧任务不碰新会话
|
|
92
|
+
let dir = this.dirs.get(path);
|
|
93
|
+
if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0 });
|
|
94
|
+
const token = ++dir.token, want = Math.max(dir.entries.length, this.wanted.get(path) ?? 0);
|
|
95
|
+
dir.loading = true;
|
|
96
|
+
this.onChange();
|
|
97
|
+
const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
|
|
98
|
+
try {
|
|
99
|
+
const entries = [];
|
|
100
|
+
let next = null, pages = 0;
|
|
101
|
+
do {
|
|
102
|
+
const reply = await this.link.call('list', { path, cursor: next });
|
|
103
|
+
if (this.link.generation !== generation) return; // 回答到了、继续前会话换了,不再取下一页
|
|
104
|
+
entries.push(...reply.entries);
|
|
105
|
+
next = reply.nextCursor ?? null;
|
|
106
|
+
pages++;
|
|
107
|
+
} while (next && entries.length < want);
|
|
108
|
+
if (!current()) return;
|
|
109
|
+
Object.assign(dir, { entries, next, loaded: true, error: null, pages });
|
|
110
|
+
this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (error.stale || !current()) return;
|
|
113
|
+
if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#drop(path);
|
|
114
|
+
else if (error.code !== ErrorCode.NO_ROOT) dir.error = { code: error.code, message: error.message };
|
|
115
|
+
} finally {
|
|
116
|
+
if (current()) dir.loading = false;
|
|
117
|
+
this.onChange();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
#drop(path) {
|
|
122
|
+
for (const key of [...this.dirs.keys()]) if (inside(key, path)) this.dirs.delete(key);
|
|
123
|
+
for (const key of [...this.expanded]) if (inside(key, path)) this.expanded.delete(key);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
toggle(path) {
|
|
127
|
+
if (this.expanded.has(path)) {
|
|
128
|
+
for (const key of [...this.expanded]) if (inside(key, path)) this.expanded.delete(key);
|
|
129
|
+
for (const key of [...this.dirs.keys()]) if (key !== '' && inside(key, path)) this.dirs.delete(key);
|
|
130
|
+
this.onChange();
|
|
131
|
+
} else {
|
|
132
|
+
this.expanded.add(path);
|
|
133
|
+
this.retry(path);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
retry(path) { return this.ready ? this.#reload(path, this.link.generation) : Promise.resolve(); }
|
|
138
|
+
|
|
139
|
+
// 「再显示」:取下一页接在后面。
|
|
140
|
+
async loadMore(path) {
|
|
141
|
+
const dir = this.dirs.get(path), { generation } = this.link;
|
|
142
|
+
if (!dir?.next || dir.loading || !this.ready) return;
|
|
143
|
+
const token = ++dir.token;
|
|
144
|
+
dir.loading = true;
|
|
145
|
+
this.onChange();
|
|
146
|
+
const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
|
|
147
|
+
try {
|
|
148
|
+
const reply = await this.link.call('list', { path, cursor: dir.next });
|
|
149
|
+
if (!current()) return;
|
|
150
|
+
dir.entries = dir.entries.concat(reply.entries);
|
|
151
|
+
Object.assign(dir, { next: reply.nextCursor ?? null, error: null, pages: dir.pages + 1 });
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!error.stale && current()) dir.error = { code: error.code, message: error.message };
|
|
154
|
+
} finally {
|
|
155
|
+
if (current()) dir.loading = false;
|
|
156
|
+
this.onChange();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
select(path) { this.selected = path; this.onChange(); }
|
|
161
|
+
setShowHidden(on) { this.showHidden = on; this.onChange(); }
|
|
162
|
+
// loaded:取过不止一页的目录已加载的条数,只存条数不存内容;第一页每次都会重新取,不用存。
|
|
163
|
+
snapshot() {
|
|
164
|
+
const loaded = {};
|
|
165
|
+
for (const [path, dir] of this.dirs) if (dir.pages > 1 && dir.entries.length > 0) loaded[path] = dir.entries.length;
|
|
166
|
+
return { expanded: [...this.expanded], selected: this.selected, loaded };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---- 状态保留:setState 没有会话维度,内部按会话分开 ----
|
|
171
|
+
|
|
172
|
+
export const byteSize = value => new TextEncoder().encode(JSON.stringify(value)).length;
|
|
173
|
+
const depth = path => path.split('/').length;
|
|
174
|
+
const strings = (value, max) => (Array.isArray(value) ? value.filter(s => typeof s === 'string' && s.length <= 1024).slice(0, max) : []);
|
|
175
|
+
|
|
176
|
+
const parseLoaded = raw => Object.fromEntries(Object.entries(raw && typeof raw === 'object' ? raw : {})
|
|
177
|
+
.filter(([path, count]) => path.length <= 1024 && Number.isSafeInteger(count) && count > 0 && count <= MAX_LOADED).slice(0, MAX_LOADED_DIRS));
|
|
178
|
+
|
|
179
|
+
// 读回来的值可能是别的版本或坏的,只认自己的形状。
|
|
180
|
+
export function parseState(raw) {
|
|
181
|
+
const state = { v: 1, seq: 0, hidden: false, sessions: {} };
|
|
182
|
+
if (!raw || typeof raw !== 'object' || raw.v !== 1) return state;
|
|
183
|
+
state.hidden = raw.hidden === true;
|
|
184
|
+
state.seq = Number.isSafeInteger(raw.seq) ? raw.seq : 0;
|
|
185
|
+
for (const [id, item] of Object.entries(raw.sessions ?? {})) {
|
|
186
|
+
if (!item || typeof item !== 'object') continue;
|
|
187
|
+
const scroll = item.scroll ?? {}, num = n => (Number.isFinite(n) && n >= 0 ? n : 0);
|
|
188
|
+
state.sessions[id] = {
|
|
189
|
+
at: Number.isSafeInteger(item.at) ? item.at : 0, expanded: strings(item.expanded, 5000),
|
|
190
|
+
selected: typeof item.selected === 'string' && item.selected.length <= 1024 ? item.selected : null,
|
|
191
|
+
scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left) },
|
|
192
|
+
};
|
|
193
|
+
const loaded = parseLoaded(item.loaded);
|
|
194
|
+
if (Object.keys(loaded).length > 0) state.sessions[id].loaded = loaded;
|
|
195
|
+
}
|
|
196
|
+
return state;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function putSession(state, session, record) {
|
|
200
|
+
state.seq++;
|
|
201
|
+
state.sessions[session] = { ...record, at: state.seq };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// 总量不超过 limit(序列化后的 UTF-8 字节):先淘汰最旧的会话,再从深到浅裁当前会话的展开目录,最后兜底清空。不抛。
|
|
205
|
+
export function trimState(state, keep, limit = STATE_LIMIT) {
|
|
206
|
+
const next = { ...state, sessions: { ...state.sessions } };
|
|
207
|
+
const fits = () => byteSize(next) <= limit;
|
|
208
|
+
const others = Object.keys(next.sessions).filter(id => id !== keep).sort((a, b) => next.sessions[a].at - next.sessions[b].at);
|
|
209
|
+
for (const id of others) { if (fits()) return next; delete next.sessions[id]; }
|
|
210
|
+
let current = next.sessions[keep];
|
|
211
|
+
if (fits() || !current) return fits() ? next : { ...next, sessions: {} };
|
|
212
|
+
// 条数只影响返回后的滚动落点,比展开状态先舍。
|
|
213
|
+
current = next.sessions[keep] = { ...current, loaded: {} };
|
|
214
|
+
if (fits()) return next;
|
|
215
|
+
// 按层级从浅到深排,取最长的、放得下的前缀;前缀仍然满足「上层也展开」。
|
|
216
|
+
const sorted = [...current.expanded].sort((a, b) => depth(a) - depth(b));
|
|
217
|
+
let low = 0, high = sorted.length;
|
|
218
|
+
const withCount = count => { next.sessions[keep] = { ...current, expanded: sorted.slice(0, count) }; return fits(); };
|
|
219
|
+
while (low < high) { const mid = (low + high + 1) >> 1; if (withCount(mid)) low = mid; else high = mid - 1; }
|
|
220
|
+
if (withCount(low)) return next;
|
|
221
|
+
return { ...next, sessions: {} };
|
|
222
|
+
}
|
package/view/notice.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// 说明区:一段文字,或「没连上 + 原因 + 重试」。树页和文件页共用。
|
|
2
|
+
// 重画会换掉正在聚焦的按钮:焦点留在说明区里(有重试按钮就落在它上面),不丢到页面外。
|
|
3
|
+
export function showNotice(el, { text, failure, retry }) {
|
|
4
|
+
const focused = el.contains(document.activeElement);
|
|
5
|
+
let target = el;
|
|
6
|
+
if (failure === undefined) el.textContent = text;
|
|
7
|
+
else {
|
|
8
|
+
const button = document.createElement('button'), title = document.createElement('p'), reason = document.createElement('p');
|
|
9
|
+
title.textContent = '没有连上资源管理器的后台';
|
|
10
|
+
reason.className = 'secondary';
|
|
11
|
+
reason.textContent = failure;
|
|
12
|
+
button.className = 'link';
|
|
13
|
+
button.textContent = '重试';
|
|
14
|
+
button.addEventListener('click', retry);
|
|
15
|
+
el.replaceChildren(title, reason, button);
|
|
16
|
+
target = button;
|
|
17
|
+
}
|
|
18
|
+
if (focused) { el.tabIndex = -1; target.focus(); }
|
|
19
|
+
}
|