@coda-console/resource-manager 0.0.0-stage → 0.3.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/view/app.mjs ADDED
@@ -0,0 +1,277 @@
1
+ // 资源管理器的页面入口:消息收发、状态保留、工具栏。状态在 model.mjs,渲染在 tree.mjs 和 preview.mjs。
2
+ import { EXIT, paintBar } from './bar.mjs';
3
+ import { connect } from './connection.mjs';
4
+ import { icon } from './icons.mjs';
5
+ import { Model, STATE_LIMIT, noticeText, parseState, putSession, trimState } from './model.mjs';
6
+ import { showNotice } from './notice.mjs';
7
+ import { mountPreview } from './preview.mjs';
8
+ import { RootState } from './protocol.mjs';
9
+ import { mountTree, rootName } from './tree.mjs';
10
+
11
+ const coda = window.coda;
12
+ const $ = id => document.getElementById(id);
13
+ const quiet = fn => { try { return fn(); } catch { return undefined; } };
14
+ const hasToolbar = typeof coda.toolbar === 'function' && coda.platform === 'mac';
15
+ // iPhone 上打开文件推入新视图,树页不进预览模式;selected 只用来高亮,从保存的状态恢复出来也一样。
16
+ const isIOS = coda.platform === 'ios';
17
+
18
+ let persisted = parseState(quiet(() => coda.getState()));
19
+ // 恢复出来的滚动位置,等内容到了再用一次。
20
+ let pending = { tree: null, preview: null };
21
+
22
+ const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
23
+ const model = new Model({ link: conn.link, onChange: () => schedule() });
24
+ model.showHidden = persisted.hidden;
25
+ const tree = mountTree($('tree'), model, {
26
+ open: openFile,
27
+ toggle: path => model.toggle(path),
28
+ more: path => model.loadMore(path),
29
+ retry: path => model.retry(path),
30
+ menu: (event, path) => pathMenu(event, path),
31
+ }, { draggable: !isIOS, longPress: isIOS });
32
+ const preview = mountPreview($('preview'), {
33
+ read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
34
+ actions: isIOS ? [] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
35
+ back: isIOS ? null : () => { backPressed = true; model.select(null); },
36
+ });
37
+
38
+ // ---- 在独立视图里打开:iPhone 点文件,Mac 预览头部的「窗口」 ----
39
+ // 会话 ID 放进 args:被打开的视图 context.session 是 null。失败(含同步抛出)在原地提示。
40
+ let hintTimer = null;
41
+ function showHint(text) {
42
+ $('hint').textContent = text;
43
+ $('hint').hidden = false;
44
+ clearTimeout(hintTimer);
45
+ hintTimer = setTimeout(() => { $('hint').hidden = true; }, 5000);
46
+ }
47
+ // iPhone 防连点:open 进行中、成功后推入动画的这一小段都忽略重复点击;失败立刻放开。
48
+ // epoch 每换一次会话加一:旧会话的 open 结果回来时已经作废,不碰新会话的提示和防连点。
49
+ let opening = false, unlockTimer = null, epoch = 0;
50
+ const REOPEN_MS = 1000;
51
+ function openInView(path) {
52
+ if (isIOS) opening = true;
53
+ const mine = epoch;
54
+ return Promise.resolve().then(() => coda.open({ view: 'file', args: { session: model.session, path } }))
55
+ .then(() => {
56
+ if (mine !== epoch) return;
57
+ $('hint').hidden = true;
58
+ if (isIOS) { clearTimeout(unlockTimer); unlockTimer = setTimeout(() => { opening = false; }, REOPEN_MS); }
59
+ }, error => {
60
+ if (mine !== epoch) return;
61
+ opening = false;
62
+ showHint(`打不开文件:${error?.message ?? '未知原因'}`);
63
+ });
64
+ }
65
+ function openFile(path) {
66
+ if (isIOS && opening) return; // 先于 select 和保存:被忽略的点击什么都不改
67
+ model.select(path);
68
+ if (!isIOS) return;
69
+ saveNow(); // 视图随即卸载,这一刻的展开状态、条数和滚动位置先存下
70
+ openInView(path);
71
+ }
72
+
73
+ // ---- 渲染:同一批变化合并成一次 ----
74
+ let queued = false;
75
+ function schedule() {
76
+ queueSave();
77
+ if (queued) return;
78
+ queued = true;
79
+ queueMicrotask(() => { queued = false; render(); });
80
+ }
81
+
82
+ // 用户点了预览头部的返回:render 据此决定焦点要不要交给目录树,别的模式变化不动焦点。
83
+ let backPressed = false;
84
+ const mode = () => (!model.ready ? 'notice' : model.selected !== null && !isIOS ? 'preview' : 'tree');
85
+
86
+ // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
87
+ let noticeKey = null;
88
+ function paintNotice() {
89
+ const failed = conn.failure !== null && !model.root;
90
+ const key = failed ? `hello:${conn.failure}` : noticeText(model.root, model.session);
91
+ if (key === noticeKey) return;
92
+ noticeKey = key;
93
+ showNotice($('notice'), failed ? { failure: conn.failure, retry: conn.hello } : { text: key });
94
+ }
95
+
96
+ function render() {
97
+ const current = mode();
98
+ const refocus = backPressed && document.hasFocus();
99
+ backPressed = false;
100
+ for (const [id, name] of [['tree', 'tree'], ['preview', 'preview'], ['notice', 'notice']]) {
101
+ $(id).classList.toggle('off', current !== name);
102
+ $(id).inert = current !== name;
103
+ }
104
+ if (current === 'notice') paintNotice();
105
+ tree.render();
106
+ if (current === 'preview' && preview.path !== model.selected) {
107
+ preview.open(model.selected, pending.preview);
108
+ pending.preview = null;
109
+ } else if (current !== 'preview' && preview.path !== null) preview.close();
110
+ // 返回按钮随预览一起 inert,焦点会掉到页面外:用户刚点了返回、页面又持有焦点时交给目录树。
111
+ // 后台刷新、切会话、root 变化造成的切换不动焦点,免得抢走客户端输入框的焦点。
112
+ if (refocus && current === 'tree') { $('tree').tabIndex = -1; $('tree').focus(); }
113
+ syncToolbar();
114
+ }
115
+
116
+ // ---- 工具栏:Mac 用 coda.toolbar,没有的(iOS、harness)退成页内一条 ----
117
+ // Mac 只有一个原生按钮「更多」:原生菜单带向下的箭头,关不掉,所以按下后由页面弹菜单。返回键在预览头部,不在这里。
118
+ const toolbarItems = () => hasToolbar
119
+ ? [{ id: 'more', label: '更多', icon: 'ellipsis', kind: 'button' }]
120
+ : [
121
+ { id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' },
122
+ { id: 'hidden', label: '显示隐藏文件', icon: 'eye', kind: 'toggle', on: model.showHidden },
123
+ ];
124
+ // iPhone 树页顶部:返回(仅横屏)、根目录名、⋯。刷新和显示隐藏文件在 ⋯ 的菜单里。
125
+ const MORE = { id: 'more', label: '更多', kind: 'button', glyph: 'ellipsis', iconOnly: true, menu: true };
126
+ const phoneItems = () => [EXIT, { kind: 'title', label: model.ready ? rootName(model.root.path) : '' }, MORE];
127
+ // 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
128
+ let lastItems = '';
129
+ function syncToolbar() {
130
+ const items = isIOS ? phoneItems() : toolbarItems(), key = JSON.stringify(items);
131
+ if (key === lastItems) return;
132
+ lastItems = key;
133
+ if (hasToolbar) return quiet(() => coda.toolbar(items));
134
+ hideMenu(); // 重画会换掉 ⋯ 按钮,开着的菜单认不得新按钮
135
+ paintBar($('bar'), items, act);
136
+ }
137
+
138
+ // 原生按钮没有 DOM 元素可以当锚点:用一个固定在页面右上角的假锚点,同时也是「谁打开的菜单」的标记。
139
+ const TOOLBAR = { getBoundingClientRect: () => ({ right: window.innerWidth, bottom: 0 }) };
140
+ // 「更多」菜单的内容只写这一处,iPhone 的 ⋯ 和 Mac 的原生按钮共用。
141
+ const moreMenu = () => ({ items: [
142
+ { label: '刷新', run: () => act('refresh') },
143
+ { label: '显示隐藏文件', checked: model.showHidden, run: () => act('hidden') },
144
+ ] });
145
+
146
+ function act(id, button) {
147
+ if (id === EXIT.id) quiet(() => coda.close());
148
+ else if (id === 'more') {
149
+ // 键盘激活没有 pointerdown,菜单外点击那条规则不管用:同一个按钮再次激活就关闭。
150
+ if (!menu.hidden && opener === button) hideMenu();
151
+ else openMenu(button, moreMenu());
152
+ }
153
+ else if (id === 'hidden') { model.setShowHidden(!model.showHidden); persisted.hidden = model.showHidden; }
154
+ else if (id === 'refresh') {
155
+ conn.refresh();
156
+ model.refresh();
157
+ preview.refresh();
158
+ }
159
+ }
160
+ // 原生按钮的事件是 { id }:只认 more,别的什么都不做。
161
+ quiet(() => coda.on('toolbar', event => { if (event?.id === 'more') act('more', TOOLBAR); }));
162
+
163
+ // ---- 状态保留 ----
164
+ let saveTimer = null;
165
+ function queueSave() {
166
+ if (model.session && saveTimer === null) saveTimer = setTimeout(saveNow, 300);
167
+ }
168
+ function saveNow() {
169
+ clearTimeout(saveTimer);
170
+ saveTimer = null;
171
+ const { session } = model;
172
+ if (!session) return;
173
+ const top = preview.scroll();
174
+ putSession(persisted, session, {
175
+ ...model.snapshot(),
176
+ scroll: { tree: pending.tree ?? tree.scroll(), top: pending.preview?.top ?? top.top, left: pending.preview?.left ?? top.left },
177
+ });
178
+ persisted = trimState(persisted, session);
179
+ // setState 超限会同步抛错:再收紧一次,仍失败就放弃这次,不影响界面。
180
+ if (quiet(() => (coda.setState(persisted), true)) === undefined) quiet(() => coda.setState(trimState(persisted, session, STATE_LIMIT / 4)));
181
+ }
182
+ quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
183
+ $('tree').addEventListener('scroll', queueSave, { passive: true });
184
+ preview.onScroll(queueSave);
185
+
186
+ // ---- 菜单:Mac 右键、iPhone 长按出复制路径,iPhone 的 ⋯ 和 Mac 的原生「更多」出刷新和显示隐藏文件 ----
187
+ // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(菜单贴在它下面、右对齐)或 { clientX, clientY } 的点。items:[{ label, run, checked? }],
188
+ // checked 不是 undefined 的是带对勾的开关项。title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全。
189
+ // 位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
190
+ const menu = $('menu');
191
+ let opener = null; // 打开菜单的按钮;用点打开的没有
192
+ function openMenu(anchor, { title, items }) {
193
+ hideMenu();
194
+ const head = title === undefined ? [] : [Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title })];
195
+ const checkable = items.some(item => item.checked !== undefined); // 有开关项时,每一项都留出对勾的位置,文字才对齐
196
+ menu.replaceChildren(...head, ...items.map(({ label, run, checked }) => {
197
+ const button = document.createElement('button'), name = document.createElement('span');
198
+ name.textContent = label;
199
+ if (checkable) {
200
+ const mark = document.createElement('span');
201
+ mark.className = 'check';
202
+ if (checked) mark.append(icon('check', 16));
203
+ button.append(mark);
204
+ }
205
+ button.append(name);
206
+ button.setAttribute('role', checked === undefined ? 'menuitem' : 'menuitemcheckbox');
207
+ if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
208
+ button.addEventListener('click', () => { run(); hideMenu(); });
209
+ return button;
210
+ }));
211
+ menu.hidden = false;
212
+ const box = anchor.getBoundingClientRect?.();
213
+ const x = box ? box.right - menu.offsetWidth : anchor.clientX, y = box ? box.bottom + 4 : anchor.clientY;
214
+ menu.style.left = `max(var(--safe-left), min(${x}px, calc(100vw - var(--safe-right) - ${menu.offsetWidth + 4}px)))`;
215
+ menu.style.top = `max(var(--safe-top), min(${y}px, calc(100vh - var(--safe-bottom) - ${menu.offsetHeight + 4}px)))`;
216
+ if (box) { opener = anchor; opener.setAttribute?.('aria-expanded', 'true'); }
217
+ }
218
+ const pathMenu = (event, path) => openMenu(event, { title: path, items: [
219
+ { label: '复制相对路径', run: () => coda.copy(path) },
220
+ { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${path}`) },
221
+ ] });
222
+ function hideMenu() {
223
+ menu.hidden = true;
224
+ opener?.setAttribute?.('aria-expanded', 'false');
225
+ opener = null;
226
+ }
227
+ // 菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给树。
228
+ let menuDismissed = false;
229
+ document.addEventListener('pointerdown', event => {
230
+ menuDismissed = !menu.hidden && !menu.contains(event.target);
231
+ if (!menu.contains(event.target)) hideMenu();
232
+ }, true);
233
+ document.addEventListener('click', event => {
234
+ if (menuDismissed) { menuDismissed = false; event.stopPropagation(); }
235
+ }, true);
236
+ document.addEventListener('keydown', event => { if (event.key === 'Escape') hideMenu(); });
237
+ window.addEventListener('blur', hideMenu);
238
+ $('tree').addEventListener('scroll', hideMenu, { passive: true });
239
+
240
+ // ---- 模块的消息(代次和握手由 connection 处理)----
241
+ function onSession(data) {
242
+ saveNow(); // 先存旧会话
243
+ preview.close();
244
+ hideMenu();
245
+ tree.reset();
246
+ epoch++;
247
+ opening = false;
248
+ clearTimeout(unlockTimer);
249
+ clearTimeout(hintTimer);
250
+ $('hint').hidden = true;
251
+ const saved = persisted.sessions[data.session] ?? null;
252
+ pending = saved ? { tree: saved.scroll.tree, preview: { top: saved.scroll.top, left: saved.scroll.left } } : { tree: null, preview: null };
253
+ model.receive(data, saved);
254
+ }
255
+
256
+ function onRoot(data) {
257
+ const before = model.root;
258
+ const done = model.receive(data);
259
+ if (done && data.state === RootState.READY) {
260
+ if (before?.path !== data.path) preview.reload(); else preview.refresh();
261
+ const { generation } = conn.link;
262
+ done.then(() => {
263
+ if (conn.link.generation !== generation || pending.tree === null) return;
264
+ tree.scrollTo(pending.tree);
265
+ pending.tree = null;
266
+ });
267
+ }
268
+ }
269
+
270
+ function onChanged(data) {
271
+ if (model.receive(data)) preview.refresh();
272
+ }
273
+
274
+ tree.remeasure();
275
+ quiet(() => coda.on('theme', () => tree.remeasure()));
276
+ render();
277
+ conn.hello();
package/view/bar.mjs ADDED
@@ -0,0 +1,26 @@
1
+ // 页内工具条:没有 coda.toolbar 的平台(iPhone)用,两个页面共用,按钮由页面给。
2
+ // 「返回」只在横屏出现(导航栏隐藏时),显示与否由 style.css 的媒体查询决定,这里一律画出来。
3
+ // 项:{ id, label, kind: 'button' | 'toggle' | 'title', glyph?, iconOnly?, on?, menu? };menu 的按钮打开菜单。title 不是按钮,只显示 label。
4
+ // 有 glyph 画图标;iconOnly 的只留图标,label 当可访问名称;否则图标后面跟文字(没有 glyph 就只有文字)。
5
+ import { icon } from './icons.mjs';
6
+
7
+ export const EXIT = { id: 'exit', label: '返回', kind: 'button', glyph: 'back' };
8
+
9
+ // act(id, button):button 是被点的元素,菜单要用它定位。
10
+ export function paintBar(el, items, act) {
11
+ el.hidden = false;
12
+ el.replaceChildren(...items.map(item => {
13
+ if (item.kind === 'title') return Object.assign(document.createElement('span'), { className: 'bar-title grow truncate', textContent: item.label });
14
+ const button = document.createElement('button');
15
+ if (item.glyph) button.append(icon(item.glyph, 20));
16
+ if (item.iconOnly) button.setAttribute('aria-label', item.label);
17
+ else button.append(Object.assign(document.createElement('span'), { textContent: item.label }));
18
+ if (item.id === EXIT.id) button.classList.add('exit');
19
+ if (item.iconOnly) button.classList.add('icon');
20
+ if (item.kind === 'toggle') button.setAttribute('aria-pressed', String(item.on));
21
+ if (item.menu) { button.setAttribute('aria-haspopup', 'menu'); button.setAttribute('aria-expanded', 'false'); }
22
+ if (item.on) button.classList.add('on');
23
+ button.addEventListener('click', () => act(item.id, button));
24
+ return button;
25
+ }));
26
+ }
@@ -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,142 @@
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
+ const isIOS = coda.platform === 'ios'; // iPhone:复制路径在底部工具条,不在预览头部
15
+
16
+ // 参数里的会话和路径,形状不对按没有处理。
17
+ const argsOf = args => ({
18
+ session: typeof args?.session === 'string' && args.session !== '' ? args.session : null,
19
+ path: typeof args?.path === 'string' && args.path !== '' ? args.path : null,
20
+ });
21
+ const num = n => (Number.isFinite(n) && n >= 0 ? n : 0);
22
+ // 读回来的值可能是别的版本或坏的,只认自己的形状。
23
+ const parseScroll = raw => (raw?.v === 1 ? { top: num(raw.top), left: num(raw.left) } : null);
24
+
25
+ let want = argsOf(coda.args); // 这个视图要看的会话和文件
26
+ let session; // 模块现在跟随的会话;undefined 表示还没收到 session
27
+ let root = null;
28
+ // 等内容到了再用一次的滚动位置。预览收起时也存在这里,恢复后接着用。
29
+ let restore = parseScroll(quiet(() => coda.getState()));
30
+
31
+ const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
32
+ const preview = mountPreview($('preview'), { read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text), copyInHead: !isIOS });
33
+
34
+ // 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
35
+ const ready = () => want.path !== null && session === want.session && root?.state === RootState.READY;
36
+
37
+ // ---- 渲染:同一批变化合并成一次 ----
38
+ let queued = false;
39
+ function schedule() {
40
+ if (queued) return;
41
+ queued = true;
42
+ queueMicrotask(() => { queued = false; render(); });
43
+ }
44
+
45
+ function render() {
46
+ const open = ready();
47
+ $('preview').classList.toggle('off', !open);
48
+ $('preview').inert = !open;
49
+ $('notice').classList.toggle('off', open);
50
+ $('notice').inert = open;
51
+ if (open) {
52
+ if (preview.path !== want.path) openPreview();
53
+ } else {
54
+ park();
55
+ preview.close();
56
+ paintNotice();
57
+ }
58
+ }
59
+
60
+ function openPreview() {
61
+ const { path } = want, scroll = restore;
62
+ // 没有要恢复的位置就明确从头开始,不靠清空正文后滚动条自己归零。
63
+ preview.open(path, scroll ?? { top: 0, left: 0 }).then(() => { if (preview.path === path && restore === scroll) restore = null; });
64
+ }
65
+
66
+ // 预览收起前记下滚动位置,恢复后接着用;内容还没到时 restore 还没用掉,不覆盖。
67
+ function park() {
68
+ if (preview.path !== null && restore === null) restore = preview.scroll();
69
+ }
70
+
71
+ // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
72
+ let noticeKey = null;
73
+ function paintNotice() {
74
+ const failed = conn.failure !== null && !root;
75
+ const key = want.path === null ? '没有指定要打开的文件。'
76
+ : failed ? `hello:${conn.failure}`
77
+ : noticeText(session === want.session ? root : null, session);
78
+ if (key === noticeKey) return;
79
+ noticeKey = key;
80
+ showNotice($('notice'), failed && want.path !== null ? { failure: conn.failure, retry: conn.hello } : { text: key, glyph: 'doc' });
81
+ }
82
+
83
+ // ---- 模块的消息(代次和握手由 connection 处理)----
84
+ function onSession(data) {
85
+ park();
86
+ preview.close();
87
+ session = data.session ?? null;
88
+ root = null;
89
+ schedule();
90
+ }
91
+
92
+ function onRoot(data) {
93
+ const before = root;
94
+ root = { state: data.state, path: data.path };
95
+ if (data.state === RootState.READY) {
96
+ if (before?.path !== data.path) preview.reload(); else preview.refresh();
97
+ }
98
+ schedule();
99
+ }
100
+
101
+ function onChanged() {
102
+ if (root?.state === RootState.READY) preview.refresh();
103
+ }
104
+
105
+ // ---- 参数变了:换文件或换会话,旧文件的滚动位置不带过去 ----
106
+ quiet(() => coda.on('context', ({ args }) => {
107
+ const next = argsOf(args);
108
+ if (next.path !== want.path || next.session !== want.session) { restore = null; preview.close(); }
109
+ want = next;
110
+ schedule();
111
+ }));
112
+
113
+ // ---- 工具条:Mac 用 coda.toolbar;iPhone 在底部放返回(仅横屏)、刷新、复制路径;其他(harness)退成页内一条 ----
114
+ const refresh = () => { conn.refresh(); preview.refresh(); };
115
+ // 说明区下预览是关着的,复制的是启动值里的路径:模块不可用时也能把路径交给对话。
116
+ const copyPath = () => (preview.path !== null ? preview.copyPath() : want.path !== null && coda.copy(want.path));
117
+ const items = [{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }];
118
+ if (hasToolbar) {
119
+ quiet(() => coda.toolbar(items));
120
+ quiet(() => coda.on('toolbar', ({ id }) => { if (id === 'refresh') refresh(); }));
121
+ } else {
122
+ const shown = isIOS ? [EXIT, { ...items[0], glyph: 'refresh' }, { id: 'copy', label: '复制路径', kind: 'button', glyph: 'copy' }] : items;
123
+ paintBar($('bar'), shown, id => (id === EXIT.id ? quiet(() => coda.close()) : id === 'copy' ? copyPath() : refresh()));
124
+ }
125
+
126
+ // ---- 阅读位置:setState 按视图和 args 隔离,每个文件自然分开 ----
127
+ let saveTimer = null;
128
+ function queueSave() {
129
+ if (saveTimer === null) saveTimer = setTimeout(saveNow, 300);
130
+ }
131
+ function saveNow() {
132
+ clearTimeout(saveTimer);
133
+ saveTimer = null;
134
+ const at = restore ?? (preview.path !== null ? preview.scroll() : null);
135
+ if (at) quiet(() => coda.setState({ v: 1, top: at.top, left: at.left }));
136
+ }
137
+ // visibility: false 之后只保证同步事件处理完,所以同步保存。
138
+ quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
139
+ preview.onScroll(queueSave);
140
+
141
+ render();
142
+ 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
+ <main id="stage">
11
+ <div id="preview" class="pane preview"></div>
12
+ <div id="notice" class="pane empty secondary"></div>
13
+ </main>
14
+ <div id="bar" class="bar bottom" hidden></div>
15
+ <script type="module" src="file-app.mjs"></script>
16
+ </body>
17
+ </html>
package/view/icons.mjs ADDED
@@ -0,0 +1,56 @@
1
+ // 图标:页面里自己画的 SVG,形状近似 SF Symbol,不打包 Apple 的符号。颜色都是 currentColor,由 CSS 定。
2
+ import { EntryKind } from './protocol.mjs';
3
+
4
+ const SVG_NS = 'http://www.w3.org/2000/svg';
5
+
6
+ // 描边图标的 24×24 画法;folder 是填充的,单独标。
7
+ const SHAPES = {
8
+ folder: { fill: true, shapes: [['path', { d: 'M3 7.2C3 5.98 3.98 5 5.2 5h4.05c.6 0 1.17.24 1.59.66L12 6.8h6.8C20.02 6.8 21 7.78 21 9v8.8c0 1.22-.98 2.2-2.2 2.2H5.2C3.98 20 3 19.02 3 17.8V7.2z' }]] },
9
+ doc: { shapes: [['path', { d: 'M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z' }], ['path', { d: 'M14 3v5h5' }], ['path', { d: 'M9 13h6M9 17h4' }]] },
10
+ code: { shapes: [['path', { d: 'M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z' }], ['path', { d: 'M14 3v5h5' }], ['path', { d: 'M10.5 12.5 8.5 15l2 2.5M13.5 12.5l2 2.5-2 2.5' }]] },
11
+ image: { shapes: [['rect', { x: 3.5, y: 4.5, width: 17, height: 15, rx: 2.5 }], ['circle', { cx: 9, cy: 10, r: 1.6 }], ['path', { d: 'm4 17 4.5-4.5 3.5 3.5 3-3 5 5' }]] },
12
+ link: { shapes: [['path', { d: 'M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1' }], ['path', { d: 'M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1' }]] },
13
+ other: { shapes: [['path', { d: 'M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z' }], ['path', { d: 'M14 3v5h5' }], ['path', { d: 'M9.5 14.5h5' }]] },
14
+ chevron: { shapes: [['path', { d: 'm9 5 7 7-7 7' }]] },
15
+ warning: { shapes: [['path', { d: 'M12 4 2.8 19.5h18.4L12 4z' }], ['path', { d: 'M12 10v4.5M12 17.2v.1' }]] },
16
+ back: { shapes: [['path', { d: 'm15 5-7 7 7 7' }]] },
17
+ check: { shapes: [['path', { d: 'm5 12.5 4.5 4.5L19 7.5' }]] },
18
+ ellipsis: { fill: true, shapes: [['circle', { cx: 5.5, cy: 12, r: 1.7 }], ['circle', { cx: 12, cy: 12, r: 1.7 }], ['circle', { cx: 18.5, cy: 12, r: 1.7 }]] },
19
+ refresh: { shapes: [['path', { d: 'M19 12a7 7 0 1 1-2.05-4.95' }], ['path', { d: 'M19 4.5v3.8h-3.8' }]] },
20
+ copy: { shapes: [['rect', { x: 8.5, y: 8.5, width: 11, height: 11, rx: 2.2 }], ['path', { d: 'M15.5 8.5V6.7a2.2 2.2 0 0 0-2.2-2.2H6.7a2.2 2.2 0 0 0-2.2 2.2v6.6a2.2 2.2 0 0 0 2.2 2.2h1.8' }]] },
21
+ window: { shapes: [['rect', { x: 3.5, y: 5, width: 17, height: 14, rx: 2.5 }], ['path', { d: 'M3.5 9.5h17' }]] },
22
+ turn: { shapes: [['path', { d: 'M5 18v-4a4 4 0 0 1 4-4h10' }], ['path', { d: 'm15 6 4 4-4 4' }]] },
23
+ };
24
+
25
+ // 扩展名表:不在表里的文件都是文档。
26
+ const BY_EXT = {
27
+ code: ['js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'json', 'yml', 'yaml', 'toml', 'html', 'css', 'scss', 'vue', 'py', 'rb', 'go', 'rs', 'java', 'kt', 'swift',
28
+ 'c', 'h', 'cpp', 'hpp', 'cs', 'php', 'lua', 'sh', 'bash', 'zsh', 'sql', 'xml'],
29
+ image: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'ico', 'bmp', 'heic', 'avif'],
30
+ };
31
+ const EXT_ICON = new Map(Object.entries(BY_EXT).flatMap(([name, exts]) => exts.map(ext => [ext, name])));
32
+
33
+ // 图标名:目录、链接、其他按种类;文件按扩展名(不分大小写;.gitignore 这类点开头的没有扩展名),没有匹配的是文档。
34
+ export function iconFor({ kind, name }) {
35
+ if (kind === EntryKind.DIR) return 'folder';
36
+ if (kind === EntryKind.LINK) return 'link';
37
+ if (kind === EntryKind.OTHER) return 'other';
38
+ const dot = name.lastIndexOf('.');
39
+ return (dot > 0 && EXT_ICON.get(name.slice(dot + 1).toLowerCase())) || 'doc';
40
+ }
41
+
42
+ // 造一个 SVG 元素;size 是点数,CSS 可以按平台覆盖。
43
+ export function icon(name, size = 16) {
44
+ const { fill = false, shapes } = SHAPES[name];
45
+ const svg = document.createElementNS(SVG_NS, 'svg');
46
+ const attrs = { width: size, height: size, viewBox: '0 0 24 24', 'aria-hidden': 'true', ...(fill
47
+ ? { fill: 'currentColor' }
48
+ : { fill: 'none', stroke: 'currentColor', 'stroke-width': 1.8, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }) };
49
+ for (const [key, value] of Object.entries(attrs)) svg.setAttribute(key, value);
50
+ for (const [tag, shape] of shapes) {
51
+ const node = document.createElementNS(SVG_NS, tag);
52
+ for (const [key, value] of Object.entries(shape)) node.setAttribute(key, value);
53
+ svg.append(node);
54
+ }
55
+ return svg;
56
+ }
@@ -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>