@coda-console/resource-manager 0.4.0 → 0.5.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 CHANGED
@@ -1,12 +1,15 @@
1
- // 资源管理器的页面入口:消息收发、状态保留、工具栏。状态在 model.mjs,渲染在 tree.mjs 和 preview.mjs。
1
+ // 资源管理器的页面入口:消息收发、状态保留、工具栏。状态在 model.mjs,渲染在 tree.mjs、preview.mjs 和 info.mjs,菜单和提示在 menu.mjs 和 hint.mjs。
2
2
  import { EXIT, paintBar } from './bar.mjs';
3
+ import { createChat } from './chat.mjs';
3
4
  import { connect } from './connection.mjs';
4
5
  import { infoText, sortName } from './format.mjs';
5
- import { icon } from './icons.mjs';
6
+ import { mountHint } from './hint.mjs';
7
+ import { mountInfo } from './info.mjs';
8
+ import { mountMenu } from './menu.mjs';
6
9
  import { Model, STATE_LIMIT, noticeText, parseState, putSession, trimState } from './model.mjs';
7
10
  import { showNotice } from './notice.mjs';
8
11
  import { mountPreview } from './preview.mjs';
9
- import { EntryKind, RootState, SortKey } from './protocol.mjs';
12
+ import { EntryKind, RootState, SortKey, Type } from './protocol.mjs';
10
13
  import { mountTree, rootName } from './tree.mjs';
11
14
 
12
15
  const coda = window.coda;
@@ -24,6 +27,9 @@ const conn = connect(coda, { handlers: { session: onSession, root: onRoot, chang
24
27
  const model = new Model({ link: conn.link, onChange: () => schedule() });
25
28
  model.showHidden = persisted.hidden;
26
29
  model.sort = persisted.sort;
30
+ const hint = mountHint($('hint'));
31
+ const menu = mountMenu($('menu'));
32
+ const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint });
27
33
  const tree = mountTree($('tree'), model, {
28
34
  open: openFile,
29
35
  toggle: path => model.toggle(path),
@@ -35,17 +41,24 @@ const preview = mountPreview($('preview'), {
35
41
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
36
42
  actions: isIOS ? [] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
37
43
  back: isIOS ? null : () => { backPressed = true; model.select(null); },
44
+ // 选中文字的右键菜单只有 Mac:iPhone 用系统的选区菜单。
45
+ selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
46
+ });
47
+ // 属性页:页内一层。iPhone 用原生返回(coda.back);Mac 的客户端会替声明了返回的页面画一个带小箭头的导航,
48
+ // 和侧栏标题重复,所以 Mac 和没有 coda.back 的环境一样,头部最左边自己放返回。
49
+ const nativeBack = isIOS && typeof coda.back === 'function';
50
+ let infoOpen = false;
51
+ let dataRound = 0; // 数据轮次:每收到一次 changed 加一,属性页用它判断文件夹的统计结果是不是上一轮的
52
+ const info = mountInfo($('info'), {
53
+ stat: path => conn.link.call(Type.STAT, { path }),
54
+ size: (path, signal) => conn.link.call(Type.DIR_SIZE, { path }, { signal, cancel: Type.DIR_SIZE_CANCEL }),
55
+ rootPath: () => model.root?.path ?? '',
56
+ round: () => dataRound,
57
+ back: nativeBack ? null : () => { backPressed = true; closeInfo(); },
38
58
  });
39
59
 
40
60
  // ---- 在独立视图里打开:iPhone 点文件,Mac 预览头部的「窗口」 ----
41
61
  // 会话 ID 放进 args:被打开的视图 context.session 是 null。失败(含同步抛出)在原地提示。
42
- let hintTimer = null;
43
- function showHint(text) {
44
- $('hint').textContent = text;
45
- $('hint').hidden = false;
46
- clearTimeout(hintTimer);
47
- hintTimer = setTimeout(() => { $('hint').hidden = true; }, 5000);
48
- }
49
62
  // iPhone 防连点:open 进行中、成功后推入动画的这一小段都忽略重复点击;失败立刻放开。
50
63
  // epoch 每换一次会话加一:旧会话的 open 结果回来时已经作废,不碰新会话的提示和防连点。
51
64
  let opening = false, unlockTimer = null, epoch = 0;
@@ -56,12 +69,12 @@ function openInView(path) {
56
69
  return Promise.resolve().then(() => coda.open({ view: 'file', args: { session: model.session, path } }))
57
70
  .then(() => {
58
71
  if (mine !== epoch) return;
59
- $('hint').hidden = true;
72
+ hint.hide();
60
73
  if (isIOS) { clearTimeout(unlockTimer); unlockTimer = setTimeout(() => { opening = false; }, REOPEN_MS); }
61
74
  }, error => {
62
75
  if (mine !== epoch) return;
63
76
  opening = false;
64
- showHint(`打不开文件:${error?.message ?? '未知原因'}`);
77
+ hint.show(`打不开文件:${error?.message ?? '未知原因'}`);
65
78
  });
66
79
  }
67
80
  function openFile(path) {
@@ -83,7 +96,7 @@ function schedule() {
83
96
 
84
97
  // 用户点了预览头部的返回:render 据此决定焦点要不要交给目录树,别的模式变化不动焦点。
85
98
  let backPressed = false;
86
- const mode = () => (!model.ready ? 'notice' : model.selected !== null && !isIOS ? 'preview' : 'tree');
99
+ const mode = () => (infoOpen ? 'info' : !model.ready ? 'notice' : model.selected !== null && !isIOS ? 'preview' : 'tree');
87
100
 
88
101
  // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
89
102
  let noticeKey = null;
@@ -99,7 +112,7 @@ function render() {
99
112
  const current = mode();
100
113
  const refocus = backPressed && document.hasFocus();
101
114
  backPressed = false;
102
- for (const [id, name] of [['tree', 'tree'], ['preview', 'preview'], ['notice', 'notice']]) {
115
+ for (const [id, name] of [['tree', 'tree'], ['preview', 'preview'], ['notice', 'notice'], ['info', 'info']]) {
103
116
  $(id).classList.toggle('off', current !== name);
104
117
  $(id).inert = current !== name;
105
118
  }
@@ -108,7 +121,7 @@ function render() {
108
121
  if (current === 'preview' && preview.path !== model.selected) {
109
122
  preview.open(model.selected, pending.preview);
110
123
  pending.preview = null;
111
- } else if (current !== 'preview' && preview.path !== null) preview.close();
124
+ } else if ((current === 'tree' || current === 'notice') && preview.path !== null) preview.close(); // 属性页和预览一样只切可见性,不动别的面板的内容
112
125
  // 返回按钮随预览一起 inert,焦点会掉到页面外:用户刚点了返回、页面又持有焦点时交给目录树。
113
126
  // 后台刷新、切会话、root 变化造成的切换不动焦点,免得抢走客户端输入框的焦点。
114
127
  if (refocus && current === 'tree') { $('tree').tabIndex = -1; $('tree').focus(); }
@@ -117,15 +130,17 @@ function render() {
117
130
 
118
131
  // ---- 工具栏:Mac 用 coda.toolbar,没有的(iOS、harness)退成页内一条 ----
119
132
  // Mac 只有一个原生按钮「更多」:原生菜单带向下的箭头,关不掉,所以按下后由页面弹菜单。返回键在预览头部,不在这里。
120
- const toolbarItems = () => hasToolbar
133
+ // 属性页上排序、刷新、显示隐藏文件都没有意义:工具栏不放任何项,退出属性页后恢复。
134
+ const toolbarItems = () => infoOpen ? [] : hasToolbar
121
135
  ? [{ id: 'more', label: '更多', icon: 'ellipsis', kind: 'button' }]
122
136
  : [
123
137
  { id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' },
124
138
  { id: 'hidden', label: '显示隐藏文件', icon: 'eye', kind: 'toggle', on: model.showHidden },
125
139
  ];
126
140
  // iPhone 树页顶部:返回(仅横屏)、根目录名、⋯。刷新、显示隐藏文件和排序都在 ⋯ 的菜单里。
141
+ // 属性页上只留返回:竖屏有原生导航栏,整条工具条不显示;横屏导航栏隐藏,页面自己给返回(显示与否都由 style.css 的横屏媒体查询决定)。
127
142
  const MORE = { id: 'more', label: '更多', kind: 'button', glyph: 'ellipsis', iconOnly: true, menu: true };
128
- const phoneItems = () => [EXIT, { kind: 'title', label: model.ready ? rootName(model.root.path) : '' }, MORE];
143
+ const phoneItems = () => infoOpen ? [EXIT] : [EXIT, { kind: 'title', label: model.ready ? rootName(model.root.path) : '' }, MORE];
129
144
  // 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
130
145
  let lastItems = '';
131
146
  function syncToolbar() {
@@ -133,8 +148,10 @@ function syncToolbar() {
133
148
  if (key === lastItems) return;
134
149
  lastItems = key;
135
150
  if (hasToolbar) return quiet(() => coda.toolbar(items));
136
- hideMenu(); // 重画会换掉 ⋯ 按钮,开着的菜单认不得新按钮
151
+ menu.hide(); // 重画会换掉 ⋯ 按钮,开着的菜单认不得新按钮
137
152
  paintBar($('bar'), items, act);
153
+ $('bar').hidden = items.length === 0; // 没有项(Mac 属性页上的页内工具条)就整条不显示
154
+ $('bar').classList.toggle('exit-only', items.length === 1 && items[0].id === EXIT.id); // 只有返回的工具条跟着返回走:竖屏整条不显示
138
155
  }
139
156
 
140
157
  // 原生按钮没有 DOM 元素可以当锚点:用一个固定在页面右上角的假锚点,同时也是「谁打开的菜单」的标记。
@@ -159,11 +176,12 @@ function changeSort(sort) {
159
176
  }
160
177
 
161
178
  function act(id, button) {
162
- if (id === EXIT.id) quiet(() => coda.close());
179
+ // 横屏时导航栏隐藏,属性页的原生返回看不到:这里的「返回」先关属性页,在根层才关视图。
180
+ if (id === EXIT.id) { if (infoOpen) { backPressed = true; closeInfo(); } else quiet(() => coda.close()); }
163
181
  else if (id === 'more') {
164
182
  // 键盘激活没有 pointerdown,菜单外点击那条规则不管用:同一个按钮再次激活就关闭。
165
- if (!menu.hidden && opener === button) hideMenu();
166
- else openMenu(button, moreMenu());
183
+ if (!menu.hidden && menu.opener === button) menu.hide();
184
+ else menu.open(button, moreMenu());
167
185
  }
168
186
  else if (id === 'hidden') { model.setShowHidden(!model.showHidden); persisted.hidden = model.showHidden; }
169
187
  else if (id === 'refresh') {
@@ -173,7 +191,7 @@ function act(id, button) {
173
191
  }
174
192
  }
175
193
  // 原生按钮的事件是 { id }:只认 more,别的什么都不做。
176
- quiet(() => coda.on('toolbar', event => { if (event?.id === 'more') act('more', TOOLBAR); }));
194
+ quiet(() => coda.on('toolbar', event => { if (event?.id === 'more' && !infoOpen) act('more', TOOLBAR); })); // 属性页上原生按钮已撤掉,迟到的事件不弹菜单
177
195
 
178
196
  // ---- 状态保留 ----
179
197
  let saveTimer = null;
@@ -197,78 +215,54 @@ function saveNow() {
197
215
  quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
198
216
  $('tree').addEventListener('scroll', queueSave, { passive: true });
199
217
  preview.onScroll(queueSave);
218
+ preview.onScroll(menu.hide);
200
219
 
201
- // ---- 菜单:Mac 右键、iPhone 长按出复制路径,iPhone 的 ⋯ 和 Mac 的原生「更多」出刷新、显示隐藏文件和排序 ----
202
- // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(菜单贴在它下面、右对齐)或 { clientX, clientY } 的点。
203
- // items:[{ label, run, checked?, radio? } | { separator: true } | { heading }],checked 不是 undefined 的带对勾(radio 的是单选,其余是开关);
204
- // 分隔线和小标题不是菜单项,不可点。title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全;detail 是它下面的一行小字。
205
- // 位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
206
- const menu = $('menu');
207
- let opener = null; // 打开菜单的按钮;用点打开的没有
208
- function openMenu(anchor, { title, detail, items }) {
209
- hideMenu();
210
- const head = [];
211
- if (title !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title }));
212
- if (detail !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-info secondary caption', textContent: detail }));
213
- const checkable = items.some(item => item.checked !== undefined); // 有开关项时,每一项都留出对勾的位置,文字才对齐
214
- menu.replaceChildren(...head, ...items.map(({ label, run, checked, radio, separator, heading }) => {
215
- if (separator) return Object.assign(document.createElement('hr'), { className: 'menu-sep' });
216
- if (heading !== undefined) return Object.assign(document.createElement('p'), { className: 'menu-head secondary caption', textContent: heading });
217
- const button = document.createElement('button'), name = document.createElement('span');
218
- name.textContent = label;
219
- if (checkable) {
220
- const mark = document.createElement('span');
221
- mark.className = 'check';
222
- if (checked) mark.append(icon('check', 16));
223
- button.append(mark);
224
- }
225
- button.append(name);
226
- button.setAttribute('role', checked === undefined ? 'menuitem' : radio ? 'menuitemradio' : 'menuitemcheckbox');
227
- if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
228
- button.addEventListener('click', () => { run(); hideMenu(); });
229
- return button;
230
- }));
231
- menu.hidden = false;
232
- const box = anchor.getBoundingClientRect?.();
233
- const x = box ? box.right - menu.offsetWidth : anchor.clientX, y = box ? box.bottom + 4 : anchor.clientY;
234
- menu.style.left = `max(var(--safe-left), min(${x}px, calc(100vw - var(--safe-right) - ${menu.offsetWidth + 4}px)))`;
235
- menu.style.top = `max(var(--safe-top), min(${y}px, calc(100vh - var(--safe-bottom) - ${menu.offsetHeight + 4}px)))`;
236
- if (box) { opener = anchor; opener.setAttribute?.('aria-expanded', 'true'); }
220
+ // ---- 行菜单:Mac 右键、iPhone 长按;iPhone 的 ⋯ 和 Mac 的原生「更多」出刷新、显示隐藏文件和排序(菜单本身在 menu.mjs)----
221
+ // 行菜单顶上是路径,下面一行 大小 · 完整修改时间(文件夹只有修改时间,读不到就没有这一行);指向外面的链接和不能打开的条目没有元数据,不显示这一行。
222
+ // 不能打开的条目(指向外面或失效的链接、other)没有「添加到聊天」,和不能拖动一致;它们仍有复制路径和属性。
223
+ function pathMenu(event, row) {
224
+ const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER;
225
+ menu.open(event, { title: row.path, detail: dead ? undefined : infoText(row) || undefined, items: [
226
+ ...(dead ? [] : [{ label: '添加到聊天', run: () => chat.add(row.path) }]),
227
+ { label: '复制相对路径', run: () => coda.copy(row.path) },
228
+ { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${row.path}`) },
229
+ { separator: true },
230
+ { label: '属性', run: () => openInfo(row) },
231
+ ] });
237
232
  }
238
- // 行菜单:路径下面一行 大小 · 完整修改时间(文件夹只有修改时间,读不到就没有这一行);指向外面的链接和不能打开的条目没有元数据,不显示这一行。
239
- const pathMenu = (event, row) => openMenu(event, { title: row.path, detail: row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER ? undefined : infoText(row) || undefined, items: [
240
- { label: '复制相对路径', run: () => coda.copy(row.path) },
241
- { label: '复制绝对路径', run: () => coda.copy(`${model.root.path}/${row.path}`) },
242
- ] });
243
- function hideMenu() {
244
- menu.hidden = true;
245
- opener?.setAttribute?.('aria-expanded', 'false');
246
- opener = null;
233
+ $('tree').addEventListener('scroll', menu.hide, { passive: true });
234
+
235
+ // ---- 属性页:iPhone 进入时声明原生返回一层,所有关闭的路径(原生返回、横屏的返回、换会话、根目录变化)都重新声明回根层 ----
236
+ function openInfo(row) {
237
+ infoOpen = true;
238
+ info.open(row.path, row);
239
+ if (nativeBack) quiet(() => coda.back(['资源管理器']));
240
+ schedule();
241
+ }
242
+ function closeInfo() {
243
+ if (!infoOpen) return;
244
+ infoOpen = false;
245
+ info.close(); // 在统计的一并取消
246
+ if (nativeBack) quiet(() => coda.back([]));
247
+ schedule();
247
248
  }
248
- // 菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给树。
249
- let menuDismissed = false;
250
- document.addEventListener('pointerdown', event => {
251
- menuDismissed = !menu.hidden && !menu.contains(event.target);
252
- if (!menu.contains(event.target)) hideMenu();
253
- }, true);
254
- document.addEventListener('click', event => {
255
- if (menuDismissed) { menuDismissed = false; event.stopPropagation(); }
256
- }, true);
257
- document.addEventListener('keydown', event => { if (event.key === 'Escape') hideMenu(); });
258
- window.addEventListener('blur', hideMenu);
259
- $('tree').addEventListener('scroll', hideMenu, { passive: true });
249
+ // steps 是退几级,属性页只有一级,不论几都回到目录树;已经不在属性页时也重新声明一次根层。
250
+ if (nativeBack) quiet(() => coda.on('back', () => {
251
+ if (infoOpen) closeInfo();
252
+ else quiet(() => coda.back([]));
253
+ }));
260
254
 
261
255
  // ---- 模块的消息(代次和握手由 connection 处理)----
262
256
  function onSession(data) {
263
257
  saveNow(); // 先存旧会话
264
258
  preview.close();
265
- hideMenu();
259
+ closeInfo();
260
+ menu.hide();
266
261
  tree.reset();
267
262
  epoch++;
268
263
  opening = false;
269
264
  clearTimeout(unlockTimer);
270
- clearTimeout(hintTimer);
271
- $('hint').hidden = true;
265
+ hint.hide();
272
266
  const saved = persisted.sessions[data.session] ?? null;
273
267
  // 目录树的滚动位置是按当时的排序存的;排序是全局的,在别的会话换过就对不上,等内容到了回到顶部。
274
268
  pending = saved ? { tree: saved.scroll.sort === model.sort ? saved.scroll.tree : 0, preview: { top: saved.scroll.top, left: saved.scroll.left } } : { tree: null, preview: null };
@@ -277,6 +271,8 @@ function onSession(data) {
277
271
 
278
272
  function onRoot(data) {
279
273
  const before = model.root;
274
+ if (data.state !== before?.state || data.path !== before?.path) menu.hide(); // 开着的菜单里的路径是旧根目录下的
275
+ if (data.state !== RootState.READY || before?.path !== data.path) closeInfo(); // 属性页看的是旧根目录下的路径
280
276
  const done = model.receive(data);
281
277
  if (done && data.state === RootState.READY) {
282
278
  if (before?.path !== data.path) preview.reload(); else preview.refresh();
@@ -290,7 +286,11 @@ function onRoot(data) {
290
286
  }
291
287
 
292
288
  function onChanged(data) {
293
- if (model.receive(data)) preview.refresh();
289
+ if (!model.receive(data)) return;
290
+ menu.hide(); // 开着的菜单可能指着已经删除的路径
291
+ dataRound++;
292
+ preview.refresh();
293
+ info.refresh();
294
294
  }
295
295
 
296
296
  tree.remeasure();
package/view/chat.mjs ADDED
@@ -0,0 +1,45 @@
1
+ // 把文字交给对话(页面这一侧):写进输入框;写不进去、放不下就改成复制并提示。树页和文件页共用。
2
+ // 写草稿本身在模块里(lib/draft.mjs),页面只发 add_text 并看回答。
3
+ import { MESSAGE_LIMIT, Type } from './protocol.mjs';
4
+
5
+ // 选区的位置文字:src/app.ts:12-18,只有一行时是 src/app.ts:12。
6
+ export const positionText = (path, startLine, endLine) => (endLine > startLine ? `${path}:${startLine}-${endLine}` : `${path}:${startLine}`);
7
+
8
+ export const MESSAGES = {
9
+ added: '已添加到输入框',
10
+ failed: '没能写入输入框,已复制',
11
+ tooLong: '选中内容太长,已复制',
12
+ };
13
+
14
+ // link:连接层的 Link;copy(text):复制到剪贴板;hint:view/hint.mjs 的提示。
15
+ export function createChat({ link, copy, hint }) {
16
+ const copied = (text, message) => {
17
+ try { Promise.resolve(copy(text)).catch(() => {}); } catch { /* 剪贴板不可用 */ }
18
+ hint.show(message);
19
+ };
20
+
21
+ // block:true 是内容(另起一行),false 是路径和位置(接在后面)。
22
+ // 会话换了、视图关了(Stale、Cancelled)静默:不提示、不复制。别的失败(含 draft_too_long、超时)都改成复制。
23
+ async function add(text, { block = false } = {}) {
24
+ const fields = { text, block };
25
+ // 按完整信封算:超过消息上限的发了会被宿主丢掉,页面只能等到超时。
26
+ if (link.size(Type.ADD_TEXT, fields) > MESSAGE_LIMIT) return copied(text, MESSAGES.tooLong);
27
+ try {
28
+ await link.call(Type.ADD_TEXT, fields);
29
+ hint.show(MESSAGES.added, { warn: false });
30
+ } catch (error) {
31
+ if (error?.stale) return;
32
+ copied(text, MESSAGES.failed);
33
+ }
34
+ }
35
+
36
+ return {
37
+ add,
38
+ // 选中文字的菜单项。内容和位置在打开菜单前就取好了(selection),点菜单时不再读选区。
39
+ selectionItems: ({ path, text, startLine, endLine }) => [
40
+ { label: '添加到聊天(内容)', run: () => add(text, { block: true }) },
41
+ { label: '添加到聊天(位置)', run: () => add(positionText(path, startLine, endLine)) },
42
+ { label: '复制', run: () => copy(text) },
43
+ ],
44
+ };
45
+ }
@@ -1,14 +1,17 @@
1
1
  // 页面到模块的连接:请求与回答(Link)、hello 握手与超时、按代次分发协议消息。
2
2
  // 树页和文件页共用。只管连接:树的 Model、状态保存、提示文案和 DOM 都在各自的页面里。
3
- import { ErrorCode, Type } from './protocol.mjs';
3
+ import { ErrorCode, Type, isReply, messageSize } from './protocol.mjs';
4
4
 
5
5
  export const TIMEOUT_MS = 30_000;
6
6
 
7
7
  // 会话已经换了,请求作废。调用方一律吞掉,不显示。
8
8
  export class Stale extends Error { constructor() { super('已过期'); this.stale = true; } }
9
+ // 页面自己取消了请求:和 Stale 一样静默,调用方吞掉。
10
+ export class Cancelled extends Stale { constructor() { super(); this.cancelled = true; } }
9
11
  export class RequestError extends Error { constructor(code, message) { super(message); this.code = code; } }
10
12
 
11
13
  // 请求与回答按 requestId 对应。回答要代次相同、请求号还在等待才算;换会话时 reset 作废所有等待并停掉超时。
14
+ // 一个请求只在 #finish 里结算:回答、发送失败、超时、代次失效、取消都走它,只结算一次,同时清掉定时器和取消监听。
12
15
  export class Link {
13
16
  generation = null;
14
17
  pending = new Map();
@@ -18,45 +21,68 @@ export class Link {
18
21
  Object.assign(this, { post, timers, timeoutMs });
19
22
  }
20
23
 
24
+ // 结算 requestId 对应的等待:还在等才算,返回是否结算了。
25
+ #finish(requestId, settle) {
26
+ const entry = this.pending.get(requestId);
27
+ if (!entry) return false;
28
+ this.pending.delete(requestId);
29
+ this.timers.clearTimeout(entry.timer);
30
+ entry.signal?.removeEventListener('abort', entry.onAbort);
31
+ settle(entry);
32
+ return true;
33
+ }
34
+
21
35
  reset(generation) {
22
36
  this.generation = generation;
23
- for (const entry of this.pending.values()) { this.timers.clearTimeout(entry.timer); entry.reject(new Stale()); }
24
- this.pending.clear();
37
+ for (const requestId of [...this.pending.keys()]) this.#finish(requestId, entry => entry.reject(new Stale()));
38
+ }
39
+
40
+ // 这条请求发出去的消息有多大(含信封):用下一个请求号算,和 call 真正发出的一致。页面用它在发之前判断会不会超过消息上限。
41
+ size(type, fields) {
42
+ return messageSize({ type, generation: this.generation, requestId: `q${this.#next}`, ...fields });
25
43
  }
26
44
 
27
- call(type, fields) {
45
+ // options.signal:中止后请求静默作废(Cancelled)。options.cancel:中止时还要告诉模块的消息类型,带 generation 和 requestId;
46
+ // 请求还没发出就中止的,两条都不发。
47
+ call(type, fields, { signal, cancel } = {}) {
28
48
  if (this.generation === null) return Promise.reject(new Stale());
49
+ if (signal?.aborted) return Promise.reject(new Cancelled());
29
50
  const { generation } = this, requestId = `q${this.#next++}`;
30
51
  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);
52
+ const fire = error => this.#finish(requestId, entry => entry.reject(error));
53
+ const timer = this.timers.setTimeout(() => fire(new RequestError('timeout', '30 秒没有回答')), this.timeoutMs);
54
+ const entry = { resolve, reject, timer, signal, posted: false };
55
+ entry.onAbort = () => {
56
+ const { posted } = entry;
57
+ if (fire(new Cancelled()) && cancel && posted) this.#notify({ type: cancel, generation, requestId });
37
58
  };
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, '消息发不出去')));
59
+ signal?.addEventListener('abort', entry.onAbort, { once: true });
60
+ this.pending.set(requestId, entry);
61
+ Promise.resolve().then(() => {
62
+ if (signal?.aborted) return; // 发出之前就中止了:不发,也不用告诉模块
63
+ entry.posted = true;
64
+ return this.post({ type, generation, requestId, ...fields });
65
+ }).catch(() => fire(new RequestError(ErrorCode.IO, '消息发不出去')));
42
66
  });
43
67
  }
44
68
 
69
+ // 没有回答的消息,发不出去也不影响页面。
70
+ #notify(message) {
71
+ try { Promise.resolve(this.post(message)).catch(() => {}); } catch { /* 宿主不可用 */ }
72
+ }
73
+
45
74
  receive(message) {
46
75
  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;
76
+ return this.#finish(message.requestId, entry => {
77
+ if (message.error) entry.reject(new RequestError(message.error.code, message.error.message));
78
+ else entry.resolve(message);
79
+ });
54
80
  }
55
81
  }
56
82
 
57
83
  // 建立连接并开始监听模块的消息;调用 hello() 才发出握手。
58
84
  // handlers:session、root、changed。session 先作废旧代次的请求再交给页面;
59
- // root、changed 只在代次等于当前时才交出;listed、chunk 直接对应请求,页面不用管。
85
+ // root、changed 只在代次等于当前时才交出;各种回答(见 protocol 的 ReplyOf)直接对应请求,页面不用管。
60
86
  // 握手的结束条件是收到首个 root;之后不再提示超时。
61
87
  // onStatus:握手状态变了(开始、失败、重试)时调用,页面据此重画说明。
62
88
  export function connect(coda, { handlers, onStatus = () => {} }) {
@@ -84,8 +110,8 @@ export function connect(coda, { handlers, onStatus = () => {} }) {
84
110
  failure = null;
85
111
  }
86
112
  return handlers[data.type](data);
87
- case Type.LISTED: case Type.CHUNK:
88
- link.receive(data);
113
+ default:
114
+ if (isReply(data.type)) link.receive(data);
89
115
  }
90
116
  });
91
117
 
package/view/dom.mjs ADDED
@@ -0,0 +1,9 @@
1
+ // 小工具:造元素。on 开头的属性是事件监听,值为 null、undefined、false 的属性不设。
2
+ export const h = (tag, attributes = {}, ...children) => {
3
+ const node = document.createElement(tag);
4
+ for (const [key, value] of Object.entries(attributes)) {
5
+ if (key.startsWith('on')) node.addEventListener(key.slice(2), value); else if (value != null && value !== false) node.setAttribute(key, value);
6
+ }
7
+ node.append(...children.flat().filter(child => child != null));
8
+ return node;
9
+ };
package/view/file-app.mjs CHANGED
@@ -1,7 +1,11 @@
1
1
  // 文件视图的页面入口:读一个文件。会话和路径来自 coda.args(启动值),之后的变化走 context 事件;
2
2
  // 连接在 connection.mjs,预览在 preview.mjs,这里不创建目录树。设计见 docs/design/phase-2.md 第 7 节。
3
+ // Mac 的独立窗口里选中文字右键可以添加到聊天(第 13.7 节);iPhone 不接,用系统的选区菜单。
3
4
  import { EXIT, paintBar } from './bar.mjs';
5
+ import { createChat } from './chat.mjs';
4
6
  import { connect } from './connection.mjs';
7
+ import { mountHint } from './hint.mjs';
8
+ import { mountMenu } from './menu.mjs';
5
9
  import { noticeText } from './model.mjs';
6
10
  import { showNotice } from './notice.mjs';
7
11
  import { mountPreview } from './preview.mjs';
@@ -29,7 +33,13 @@ let root = null;
29
33
  let restore = parseScroll(quiet(() => coda.getState()));
30
34
 
31
35
  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 });
36
+ const hint = mountHint($('hint'));
37
+ const menu = mountMenu($('menu'));
38
+ const chat = createChat({ link: conn.link, copy: text => coda.copy(text), hint });
39
+ const preview = mountPreview($('preview'), {
40
+ read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text), copyInHead: !isIOS,
41
+ selectionMenu: isIOS ? null : (event, selection) => menu.open(event, { items: chat.selectionItems(selection) }),
42
+ });
33
43
 
34
44
  // 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
35
45
  const ready = () => want.path !== null && session === want.session && root?.state === RootState.READY;
@@ -84,6 +94,8 @@ function paintNotice() {
84
94
  function onSession(data) {
85
95
  park();
86
96
  preview.close();
97
+ menu.hide();
98
+ hint.hide();
87
99
  session = data.session ?? null;
88
100
  root = null;
89
101
  schedule();
@@ -91,6 +103,7 @@ function onSession(data) {
91
103
 
92
104
  function onRoot(data) {
93
105
  const before = root;
106
+ if (data.state !== before?.state || data.path !== before?.path) menu.hide(); // 选区和行号是旧内容上的
94
107
  root = { state: data.state, path: data.path };
95
108
  if (data.state === RootState.READY) {
96
109
  if (before?.path !== data.path) preview.reload(); else preview.refresh();
@@ -99,13 +112,15 @@ function onRoot(data) {
99
112
  }
100
113
 
101
114
  function onChanged() {
102
- if (root?.state === RootState.READY) preview.refresh();
115
+ if (root?.state !== RootState.READY) return;
116
+ menu.hide(); // 内容可能变了,开着的选区菜单里的选区和行号作废
117
+ preview.refresh();
103
118
  }
104
119
 
105
120
  // ---- 参数变了:换文件或换会话,旧文件的滚动位置不带过去 ----
106
121
  quiet(() => coda.on('context', ({ args }) => {
107
122
  const next = argsOf(args);
108
- if (next.path !== want.path || next.session !== want.session) { restore = null; preview.close(); }
123
+ if (next.path !== want.path || next.session !== want.session) { restore = null; preview.close(); menu.hide(); hint.hide(); }
109
124
  want = next;
110
125
  schedule();
111
126
  }));
@@ -137,6 +152,7 @@ function saveNow() {
137
152
  // visibility: false 之后只保证同步事件处理完,所以同步保存。
138
153
  quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
139
154
  preview.onScroll(queueSave);
155
+ preview.onScroll(menu.hide);
140
156
 
141
157
  render();
142
158
  conn.hello();
package/view/file.html CHANGED
@@ -12,6 +12,8 @@
12
12
  <div id="notice" class="pane empty secondary"></div>
13
13
  </main>
14
14
  <div id="bar" class="bar bottom" hidden></div>
15
+ <div id="menu" class="menu" role="menu" hidden></div>
16
+ <div id="hint" class="hint" role="status" hidden></div>
15
17
  <script type="module" src="file-app.mjs"></script>
16
18
  </body>
17
19
  </html>
package/view/format.mjs CHANGED
@@ -38,3 +38,30 @@ export const infoText = entry => joined([sizeText(entry), Number.isInteger(entry
38
38
 
39
39
  const NAMES = { [SortKey.NAME]: '名称', [SortKey.KIND]: '种类', [SortKey.DATE]: '日期', [SortKey.SIZE]: '大小' };
40
40
  export const sortName = key => NAMES[key];
41
+
42
+ // ---- 属性页 ----
43
+ // 千分位:1204 → 1,204。
44
+ export const thousands = n => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
45
+ // 项数:整万的写成 20 万项,别的千分位 1,204 项。
46
+ export const countText = n => (n >= 10000 && n % 10000 === 0 ? `${n / 10000} 万项` : `${thousands(n)} 项`);
47
+ // 文件大小:2.5 KiB(2,560 字节);不到 1 KiB 只写字节数。
48
+ export const fileSizeText = bytes => (bytes < 1024 ? `${bytes} 字节` : `${formatSize(bytes)}(${thousands(bytes)} 字节)`);
49
+
50
+ // 文件夹大小,{ size, items, complete, unreadable } 是 dir_size 的回答。
51
+ // 统计完:3.2 GiB(1,204 项);有读不到的:至少 3.2 GiB(3 项读不到);没统计完:超过 3.2 GiB(已统计 20 万项);
52
+ // 一项都没读到就到时间(目录正忙):不写「超过 0 B」。
53
+ export function dirSizeText({ size, items, complete, unreadable = 0 }) {
54
+ if (!complete && items === 0) return '目录正忙,没统计完';
55
+ const bytes = formatSize(size);
56
+ if (!complete) return `超过 ${bytes}(${[`已统计 ${countText(items)}`, unreadable > 0 ? `${unreadable} 项读不到` : ''].filter(Boolean).join(',')})`;
57
+ return unreadable > 0 ? `至少 ${bytes}(${unreadable} 项读不到)` : `${bytes}(${countText(items)})`;
58
+ }
59
+
60
+ // 权限:rw-r--r--;setuid、setgid、sticky 照 ls 的写法。
61
+ export function modeText(mode) {
62
+ const chars = Array.from('rwxrwxrwx', (char, i) => (mode & (0o400 >> i) ? char : '-'));
63
+ for (const [bit, at, on] of [[0o4000, 2, 's'], [0o2000, 5, 's'], [0o1000, 8, 't']]) {
64
+ if (mode & bit) chars[at] = chars[at] === 'x' ? on : on.toUpperCase();
65
+ }
66
+ return chars.join('');
67
+ }
package/view/hint.mjs ADDED
@@ -0,0 +1,20 @@
1
+ // 页面底部的一条短提示:失败(橙色)停 5 秒,成功(普通)停 2 秒,新的提示替换旧的。树页和文件页共用。
2
+ export const HINT_MS = { warn: 5000, ok: 2000 };
3
+
4
+ export function mountHint(el) {
5
+ let timer = null;
6
+ return {
7
+ // warn:失败的提示。ms 缺省按 warn 取 HINT_MS。
8
+ show(text, { warn = true, ms = warn ? HINT_MS.warn : HINT_MS.ok } = {}) {
9
+ el.textContent = text;
10
+ el.classList.toggle('warn', warn);
11
+ el.hidden = false;
12
+ clearTimeout(timer);
13
+ timer = setTimeout(() => { el.hidden = true; }, ms);
14
+ },
15
+ hide() {
16
+ clearTimeout(timer);
17
+ el.hidden = true;
18
+ },
19
+ };
20
+ }