@coda-console/resource-manager 0.2.0 → 0.4.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,11 +1,13 @@
1
1
  // 资源管理器的页面入口:消息收发、状态保留、工具栏。状态在 model.mjs,渲染在 tree.mjs 和 preview.mjs。
2
2
  import { EXIT, paintBar } from './bar.mjs';
3
3
  import { connect } from './connection.mjs';
4
+ import { infoText, sortName } from './format.mjs';
5
+ import { icon } from './icons.mjs';
4
6
  import { Model, STATE_LIMIT, noticeText, parseState, putSession, trimState } from './model.mjs';
5
7
  import { showNotice } from './notice.mjs';
6
8
  import { mountPreview } from './preview.mjs';
7
- import { RootState } from './protocol.mjs';
8
- import { mountTree } from './tree.mjs';
9
+ import { EntryKind, RootState, SortKey } from './protocol.mjs';
10
+ import { mountTree, rootName } from './tree.mjs';
9
11
 
10
12
  const coda = window.coda;
11
13
  const $ = id => document.getElementById(id);
@@ -21,16 +23,18 @@ let pending = { tree: null, preview: null };
21
23
  const conn = connect(coda, { handlers: { session: onSession, root: onRoot, changed: onChanged }, onStatus: () => schedule() });
22
24
  const model = new Model({ link: conn.link, onChange: () => schedule() });
23
25
  model.showHidden = persisted.hidden;
26
+ model.sort = persisted.sort;
24
27
  const tree = mountTree($('tree'), model, {
25
28
  open: openFile,
26
29
  toggle: path => model.toggle(path),
27
30
  more: path => model.loadMore(path),
28
31
  retry: path => model.retry(path),
29
- menu: (event, path) => showMenu(event, path),
32
+ menu: (event, row) => pathMenu(event, row),
30
33
  }, { draggable: !isIOS, longPress: isIOS });
31
34
  const preview = mountPreview($('preview'), {
32
35
  read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text),
33
- actions: isIOS ? [] : [{ label: '窗口', run: openInView }],
36
+ actions: isIOS ? [] : [{ label: '窗口', icon: 'window', run: openInView }], copyInHead: !isIOS,
37
+ back: isIOS ? null : () => { backPressed = true; model.select(null); },
34
38
  });
35
39
 
36
40
  // ---- 在独立视图里打开:iPhone 点文件,Mac 预览头部的「窗口」 ----
@@ -77,6 +81,8 @@ function schedule() {
77
81
  queueMicrotask(() => { queued = false; render(); });
78
82
  }
79
83
 
84
+ // 用户点了预览头部的返回:render 据此决定焦点要不要交给目录树,别的模式变化不动焦点。
85
+ let backPressed = false;
80
86
  const mode = () => (!model.ready ? 'notice' : model.selected !== null && !isIOS ? 'preview' : 'tree');
81
87
 
82
88
  // 说明区只在内容变了才重画,免得重试按钮在点击中途被换掉。
@@ -91,6 +97,8 @@ function paintNotice() {
91
97
 
92
98
  function render() {
93
99
  const current = mode();
100
+ const refocus = backPressed && document.hasFocus();
101
+ backPressed = false;
94
102
  for (const [id, name] of [['tree', 'tree'], ['preview', 'preview'], ['notice', 'notice']]) {
95
103
  $(id).classList.toggle('off', current !== name);
96
104
  $(id).inert = current !== name;
@@ -101,27 +109,62 @@ function render() {
101
109
  preview.open(model.selected, pending.preview);
102
110
  pending.preview = null;
103
111
  } else if (current !== 'preview' && preview.path !== null) preview.close();
104
- syncToolbar(current);
112
+ // 返回按钮随预览一起 inert,焦点会掉到页面外:用户刚点了返回、页面又持有焦点时交给目录树。
113
+ // 后台刷新、切会话、root 变化造成的切换不动焦点,免得抢走客户端输入框的焦点。
114
+ if (refocus && current === 'tree') { $('tree').tabIndex = -1; $('tree').focus(); }
115
+ syncToolbar();
105
116
  }
106
117
 
107
- // ---- 工具栏:Mac 用 coda.toolbar,没有的(iOS)退成页内一条 ----
108
- const toolbarItems = current => [
109
- ...(current === 'preview' ? [{ id: 'back', label: '返回', icon: 'chevron.left', kind: 'button' }] : []),
110
- { id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' },
111
- { id: 'hidden', label: '显示隐藏文件', icon: 'eye', kind: 'toggle', on: model.showHidden },
112
- ];
118
+ // ---- 工具栏:Mac 用 coda.toolbar,没有的(iOS、harness)退成页内一条 ----
119
+ // Mac 只有一个原生按钮「更多」:原生菜单带向下的箭头,关不掉,所以按下后由页面弹菜单。返回键在预览头部,不在这里。
120
+ const toolbarItems = () => hasToolbar
121
+ ? [{ id: 'more', label: '更多', icon: 'ellipsis', kind: 'button' }]
122
+ : [
123
+ { id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' },
124
+ { id: 'hidden', label: '显示隐藏文件', icon: 'eye', kind: 'toggle', on: model.showHidden },
125
+ ];
126
+ // iPhone 树页顶部:返回(仅横屏)、根目录名、⋯。刷新、显示隐藏文件和排序都在 ⋯ 的菜单里。
127
+ 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];
129
+ // 比较键就是要画的项:根目录名变了(换会话)工具条跟着重画。
113
130
  let lastItems = '';
114
- function syncToolbar(current) {
115
- const items = toolbarItems(current), key = JSON.stringify(items);
131
+ function syncToolbar() {
132
+ const items = isIOS ? phoneItems() : toolbarItems(), key = JSON.stringify(items);
116
133
  if (key === lastItems) return;
117
134
  lastItems = key;
118
135
  if (hasToolbar) return quiet(() => coda.toolbar(items));
119
- paintBar($('bar'), isIOS ? [EXIT, ...items] : items, act);
136
+ hideMenu(); // 重画会换掉 ⋯ 按钮,开着的菜单认不得新按钮
137
+ paintBar($('bar'), items, act);
120
138
  }
121
139
 
122
- function act(id) {
140
+ // 原生按钮没有 DOM 元素可以当锚点:用一个固定在页面右上角的假锚点,同时也是「谁打开的菜单」的标记。
141
+ const TOOLBAR = { getBoundingClientRect: () => ({ right: window.innerWidth, bottom: 0 }) };
142
+ // 「更多」菜单的内容只写这一处,iPhone 的 ⋯ 和 Mac 的原生按钮共用:刷新、显示隐藏文件,分隔线,小标题和平铺的四个排序项。
143
+ const moreMenu = () => ({ items: [
144
+ { label: '刷新', run: () => act('refresh') },
145
+ { label: '显示隐藏文件', checked: model.showHidden, run: () => act('hidden') },
146
+ { separator: true },
147
+ { heading: '排序' },
148
+ ...Object.values(SortKey).map(key => ({ label: sortName(key), checked: key === model.sort, radio: true, run: () => changeSort(key) })),
149
+ ] });
150
+
151
+ // 换排序:旧的滚动位置对新顺序没有意义,待恢复的作废,回到顶部;排序是全局的,存进 persisted。选当前项什么都不做。
152
+ function changeSort(sort) {
153
+ const before = model.sort;
154
+ model.setSort(sort);
155
+ if (model.sort === before) return; // 同值:什么都没换
156
+ persisted.sort = model.sort;
157
+ pending.tree = null;
158
+ tree.scrollTo(0);
159
+ }
160
+
161
+ function act(id, button) {
123
162
  if (id === EXIT.id) quiet(() => coda.close());
124
- else if (id === 'back') model.select(null);
163
+ else if (id === 'more') {
164
+ // 键盘激活没有 pointerdown,菜单外点击那条规则不管用:同一个按钮再次激活就关闭。
165
+ if (!menu.hidden && opener === button) hideMenu();
166
+ else openMenu(button, moreMenu());
167
+ }
125
168
  else if (id === 'hidden') { model.setShowHidden(!model.showHidden); persisted.hidden = model.showHidden; }
126
169
  else if (id === 'refresh') {
127
170
  conn.refresh();
@@ -129,7 +172,8 @@ function act(id) {
129
172
  preview.refresh();
130
173
  }
131
174
  }
132
- quiet(() => coda.on('toolbar', ({ id }) => act(id)));
175
+ // 原生按钮的事件是 { id }:只认 more,别的什么都不做。
176
+ quiet(() => coda.on('toolbar', event => { if (event?.id === 'more') act('more', TOOLBAR); }));
133
177
 
134
178
  // ---- 状态保留 ----
135
179
  let saveTimer = null;
@@ -144,7 +188,7 @@ function saveNow() {
144
188
  const top = preview.scroll();
145
189
  putSession(persisted, session, {
146
190
  ...model.snapshot(),
147
- scroll: { tree: pending.tree ?? tree.scroll(), top: pending.preview?.top ?? top.top, left: pending.preview?.left ?? top.left },
191
+ scroll: { tree: pending.tree ?? tree.scroll(), top: pending.preview?.top ?? top.top, left: pending.preview?.left ?? top.left, sort: model.sort },
148
192
  });
149
193
  persisted = trimState(persisted, session);
150
194
  // setState 超限会同步抛错:再收紧一次,仍失败就放弃这次,不影响界面。
@@ -154,26 +198,53 @@ quiet(() => coda.on('visibility', visible => { if (!visible) saveNow(); }));
154
198
  $('tree').addEventListener('scroll', queueSave, { passive: true });
155
199
  preview.onScroll(queueSave);
156
200
 
157
- // ---- 复制路径的菜单:Mac 右键、iPhone 长按 ----
158
- // 菜单顶上写完整的相对路径:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全。
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 是它下面的一行小字。
159
205
  // 位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
160
206
  const menu = $('menu');
161
- function showMenu(event, path) {
162
- const entries = [['复制相对路径', path], ['复制绝对路径', `${model.root.path}/${path}`]];
163
- const title = document.createElement('p');
164
- title.className = 'menu-path secondary';
165
- title.textContent = path;
166
- menu.replaceChildren(title, ...entries.map(([label, text]) => {
167
- const button = document.createElement('button');
168
- button.textContent = label;
169
- button.addEventListener('click', () => { coda.copy(text); hideMenu(); });
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(); });
170
229
  return button;
171
230
  }));
172
231
  menu.hidden = false;
173
- menu.style.left = `max(var(--safe-left), min(${event.clientX}px, calc(100vw - var(--safe-right) - ${menu.offsetWidth + 4}px)))`;
174
- menu.style.top = `max(var(--safe-top), min(${event.clientY}px, calc(100vh - var(--safe-bottom) - ${menu.offsetHeight + 4}px)))`;
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'); }
237
+ }
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;
175
247
  }
176
- const hideMenu = () => { menu.hidden = true; };
177
248
  // 菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给树。
178
249
  let menuDismissed = false;
179
250
  document.addEventListener('pointerdown', event => {
@@ -199,7 +270,8 @@ function onSession(data) {
199
270
  clearTimeout(hintTimer);
200
271
  $('hint').hidden = true;
201
272
  const saved = persisted.sessions[data.session] ?? null;
202
- pending = saved ? { tree: saved.scroll.tree, preview: { top: saved.scroll.top, left: saved.scroll.left } } : { tree: null, preview: null };
273
+ // 目录树的滚动位置是按当时的排序存的;排序是全局的,在别的会话换过就对不上,等内容到了回到顶部。
274
+ 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 };
203
275
  model.receive(data, saved);
204
276
  }
205
277
 
package/view/bar.mjs CHANGED
@@ -1,16 +1,26 @@
1
- // 页内工具条:没有 coda.toolbar 的平台(iPhone)用。两个页面共用,按钮由页面给。
1
+ // 页内工具条:没有 coda.toolbar 的平台(iPhone)用,两个页面共用,按钮由页面给。
2
2
  // 「返回」只在横屏出现(导航栏隐藏时),显示与否由 style.css 的媒体查询决定,这里一律画出来。
3
- export const EXIT = { id: 'exit', label: '返回', kind: 'button' };
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';
4
6
 
7
+ export const EXIT = { id: 'exit', label: '返回', kind: 'button', glyph: 'back' };
8
+
9
+ // act(id, button):button 是被点的元素,菜单要用它定位。
5
10
  export function paintBar(el, items, act) {
6
11
  el.hidden = false;
7
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 });
8
14
  const button = document.createElement('button');
9
- button.textContent = item.label;
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 }));
10
18
  if (item.id === EXIT.id) button.classList.add('exit');
11
- button.setAttribute('aria-pressed', item.kind === 'toggle' ? String(item.on) : 'false');
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'); }
12
22
  if (item.on) button.classList.add('on');
13
- button.addEventListener('click', () => act(item.id));
23
+ button.addEventListener('click', () => act(item.id, button));
14
24
  return button;
15
25
  }));
16
26
  }
package/view/file-app.mjs CHANGED
@@ -11,6 +11,7 @@ const coda = window.coda;
11
11
  const $ = id => document.getElementById(id);
12
12
  const quiet = fn => { try { return fn(); } catch { return undefined; } };
13
13
  const hasToolbar = typeof coda.toolbar === 'function' && coda.platform === 'mac';
14
+ const isIOS = coda.platform === 'ios'; // iPhone:复制路径在底部工具条,不在预览头部
14
15
 
15
16
  // 参数里的会话和路径,形状不对按没有处理。
16
17
  const argsOf = args => ({
@@ -28,7 +29,7 @@ let root = null;
28
29
  let restore = parseScroll(quiet(() => coda.getState()));
29
30
 
30
31
  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
+ const preview = mountPreview($('preview'), { read: (path, offset) => conn.link.call('read', { path, offset }), copy: text => coda.copy(text), copyInHead: !isIOS });
32
33
 
33
34
  // 模块跟随的会话和启动参数里的不是同一个时(换会话的两条消息没有先后保证),不能读,等对上。
34
35
  const ready = () => want.path !== null && session === want.session && root?.state === RootState.READY;
@@ -76,7 +77,7 @@ function paintNotice() {
76
77
  : noticeText(session === want.session ? root : null, session);
77
78
  if (key === noticeKey) return;
78
79
  noticeKey = key;
79
- showNotice($('notice'), failed && want.path !== null ? { failure: conn.failure, retry: conn.hello } : { text: key });
80
+ showNotice($('notice'), failed && want.path !== null ? { failure: conn.failure, retry: conn.hello } : { text: key, glyph: 'doc' });
80
81
  }
81
82
 
82
83
  // ---- 模块的消息(代次和握手由 connection 处理)----
@@ -109,15 +110,17 @@ quiet(() => coda.on('context', ({ args }) => {
109
110
  schedule();
110
111
  }));
111
112
 
112
- // ---- 工具条:Mac 用 coda.toolbar,没有的(iOS)退成页内一条 ----
113
+ // ---- 工具条:Mac 用 coda.toolbar;iPhone 在底部放返回(仅横屏)、刷新、复制路径;其他(harness)退成页内一条 ----
113
114
  const refresh = () => { conn.refresh(); preview.refresh(); };
115
+ // 说明区下预览是关着的,复制的是启动值里的路径:模块不可用时也能把路径交给对话。
116
+ const copyPath = () => (preview.path !== null ? preview.copyPath() : want.path !== null && coda.copy(want.path));
114
117
  const items = [{ id: 'refresh', label: '刷新', icon: 'arrow.clockwise', kind: 'button' }];
115
118
  if (hasToolbar) {
116
119
  quiet(() => coda.toolbar(items));
117
120
  quiet(() => coda.on('toolbar', ({ id }) => { if (id === 'refresh') refresh(); }));
118
121
  } else {
119
- const exit = coda.platform === 'ios';
120
- paintBar($('bar'), exit ? [EXIT, ...items] : items, id => (id === EXIT.id ? quiet(() => coda.close()) : refresh()));
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()));
121
124
  }
122
125
 
123
126
  // ---- 阅读位置:setState 按视图和 args 隔离,每个文件自然分开 ----
package/view/file.html CHANGED
@@ -7,11 +7,11 @@
7
7
  <link rel="stylesheet" href="style.css">
8
8
  </head>
9
9
  <body>
10
- <div id="bar" class="bar" hidden></div>
11
10
  <main id="stage">
12
11
  <div id="preview" class="pane preview"></div>
13
12
  <div id="notice" class="pane empty secondary"></div>
14
13
  </main>
14
+ <div id="bar" class="bar bottom" hidden></div>
15
15
  <script type="module" src="file-app.mjs"></script>
16
16
  </body>
17
17
  </html>
@@ -0,0 +1,40 @@
1
+ // 目录树和菜单里的文字格式:大小、修改日期。纯函数,不依赖运行环境的语言设置;now 由调用方给。
2
+ import { EntryKind, SortKey } from './protocol.mjs';
3
+
4
+ export function formatSize(bytes) {
5
+ if (bytes < 1024) return `${bytes} B`;
6
+ const units = ['KiB', 'MiB', 'GiB'];
7
+ let value = bytes / 1024, unit = 0;
8
+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }
9
+ return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
10
+ }
11
+
12
+ const two = n => String(n).padStart(2, '0');
13
+
14
+ // 相对格式,按本地时间:今天 14:05,今年 11月4日,往年 2025年3月。
15
+ export function formatDate(ms, now) {
16
+ const date = new Date(ms), current = new Date(now);
17
+ if (date.getFullYear() !== current.getFullYear()) return `${date.getFullYear()}年${date.getMonth() + 1}月`;
18
+ if (date.getMonth() !== current.getMonth() || date.getDate() !== current.getDate()) return `${date.getMonth() + 1}月${date.getDate()}日`;
19
+ return `${two(date.getHours())}:${two(date.getMinutes())}`;
20
+ }
21
+
22
+ // 完整的修改时间:2025-03-04 14:05:09。
23
+ export function formatFullDate(ms) {
24
+ const d = new Date(ms);
25
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}`;
26
+ }
27
+
28
+ const MISSING = '—';
29
+ const isDir = entry => entry.kind === EntryKind.DIR;
30
+ // 条目的大小和日期:文件读不到的部分是 —;文件夹不显示大小,读不到修改时间也不显示 —,返回空串。
31
+ export const sizeText = entry => (isDir(entry) ? '' : Number.isInteger(entry.size) ? formatSize(entry.size) : MISSING);
32
+ export const dateText = (entry, now) => (Number.isInteger(entry.mtimeMs) ? formatDate(entry.mtimeMs, now) : isDir(entry) ? '' : MISSING);
33
+ const joined = parts => parts.filter(Boolean).join(' · ');
34
+ // iPhone 第二行:日期 · 大小;文件夹只有日期。
35
+ export const subText = (entry, now) => joined([dateText(entry, now), sizeText(entry)]);
36
+ // 菜单信息行和 Mac 的 title:大小 · 完整修改时间;文件夹只有完整修改时间。没有内容时是空串。
37
+ export const infoText = entry => joined([sizeText(entry), Number.isInteger(entry.mtimeMs) ? formatFullDate(entry.mtimeMs) : isDir(entry) ? '' : MISSING]);
38
+
39
+ const NAMES = { [SortKey.NAME]: '名称', [SortKey.KIND]: '种类', [SortKey.DATE]: '日期', [SortKey.SIZE]: '大小' };
40
+ export const sortName = key => NAMES[key];
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
+ }
package/view/model.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // 页面的纯状态:目录树、状态保留。不碰 DOM,请求与代次在 connection.mjs,设计见 docs/design/phase-1.md 第 6、7 节。
2
- import { ErrorCode, RootState, Type } from './protocol.mjs';
2
+ import { DEFAULT_SORT, ErrorCode, RootState, Type, parseSort } from './protocol.mjs';
3
3
 
4
4
  export const STATE_LIMIT = 96 * 1024;
5
5
  export const MAX_PARALLEL = 8;
@@ -39,6 +39,8 @@ export class Model {
39
39
  wanted = new Map(); // 恢复状态时各目录要取够的条数,第一次取用后删掉
40
40
  selected = null;
41
41
  showHidden = false;
42
+ sort = DEFAULT_SORT; // 全局一份,由页面存进 persisted
43
+ #round = 0; // refresh 的轮次:新一轮开始后,旧一轮不再派发排队的目录
42
44
 
43
45
  constructor({ link, onChange = () => {} }) { Object.assign(this, { link, onChange }); }
44
46
 
@@ -57,6 +59,7 @@ export class Model {
57
59
  // 换会话:清空一切,展开状态换成这个会话保存的。
58
60
  onSession({ generation, session }, saved = null) {
59
61
  this.link.reset(generation);
62
+ this.#round++;
60
63
  this.session = session ?? null;
61
64
  this.root = null;
62
65
  this.dirs = new Map();
@@ -79,34 +82,55 @@ export class Model {
79
82
  return generation === this.link.generation && this.ready ? this.refresh() : null;
80
83
  }
81
84
 
82
- // 重新取根和全部已展开的目录,并行不超过 8 个。
83
- refresh() {
85
+ // 重新取根和全部已展开的目录,并行不超过 8 个。cap:这一轮每个目录最多取够这么多条(换排序时用)。
86
+ // 每一轮带递增的轮次:只查 current() 不够,旧一轮的池子还会启动排队中的目录,递增它们的 token,作废较新的加载。
87
+ refresh({ cap = Infinity } = {}) {
84
88
  if (!this.ready) return Promise.resolve();
85
- const { generation } = this.link;
86
- return pool(['', ...this.expanded], MAX_PARALLEL, path => this.#reload(path, generation));
89
+ const { generation } = this.link, round = ++this.#round;
90
+ return pool(['', ...this.expanded], MAX_PARALLEL, path => (round === this.#round ? this.#reload(path, generation, { cap }) : undefined));
87
91
  }
88
92
 
89
- // 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。
90
- async #reload(path, generation) {
93
+ // 换排序:已加载的目录按新顺序重新取,取够现在的条数,这次最多 RESTORE_LIMIT 条;每个目录一次替换。
94
+ setSort(sort) {
95
+ const next = parseSort(sort);
96
+ if (!next || next === this.sort) return Promise.resolve();
97
+ this.sort = next;
98
+ this.onChange();
99
+ return this.refresh({ cap: RESTORE_LIMIT });
100
+ }
101
+
102
+ // 取够已加载的条数,一次替换;同目录有更新的请求就作废这一个。一次加载固定一种排序。
103
+ // more、expired:「再显示」遇到游标过期转过来时,条数要比现在多一条,而且已经算重取过一次,不再重取。
104
+ async #reload(path, generation, { cap = Infinity, more = false, expired = false } = {}) {
91
105
  if (this.link.generation !== generation) return; // 排队时会话已换,旧任务不碰新会话
92
106
  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);
107
+ if (!dir) this.dirs.set(path, dir = { entries: [], next: null, loaded: false, loading: false, error: null, token: 0, pages: 0, sortFallback: false });
108
+ const token = ++dir.token, { sort } = this;
109
+ const want = more ? dir.entries.length + 1 : Math.min(Math.max(dir.entries.length, this.wanted.get(path) ?? 0), cap);
95
110
  dir.loading = true;
96
111
  this.onChange();
97
112
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
98
113
  try {
99
- const entries = [];
100
- let next = null, pages = 0;
114
+ let entries = [], next = null, pages = 0, sortFallback = false;
101
115
  do {
102
- const reply = await this.link.call('list', { path, cursor: next });
103
- if (this.link.generation !== generation) return; // 回答到了、继续前会话换了,不再取下一页
116
+ let reply;
117
+ try {
118
+ reply = await this.link.call('list', { path, cursor: next, sort });
119
+ } catch (error) {
120
+ // 游标过期(快照被淘汰、释放,或根目录变了):丢掉这一轮累积的,从第一页重取一次,再失败走失败行。
121
+ if (error.code !== ErrorCode.CURSOR_EXPIRED || expired || !current()) throw error;
122
+ expired = true;
123
+ entries = []; next = null; pages = 0; sortFallback = false;
124
+ continue;
125
+ }
126
+ if (!current()) return; // 回答到了、继续前会话换了或有更新的加载,不再取下一页
127
+ if (pages === 0) sortFallback = reply.sortFallback === true;
104
128
  entries.push(...reply.entries);
105
129
  next = reply.nextCursor ?? null;
106
130
  pages++;
107
- } while (next && entries.length < want);
131
+ } while (pages === 0 || (next && entries.length < want));
108
132
  if (!current()) return;
109
- Object.assign(dir, { entries, next, loaded: true, error: null, pages });
133
+ Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback });
110
134
  this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
111
135
  } catch (error) {
112
136
  if (error.stale || !current()) return;
@@ -145,12 +169,15 @@ export class Model {
145
169
  this.onChange();
146
170
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
147
171
  try {
148
- const reply = await this.link.call('list', { path, cursor: dir.next });
172
+ const reply = await this.link.call('list', { path, cursor: dir.next, sort: this.sort });
149
173
  if (!current()) return;
150
174
  dir.entries = dir.entries.concat(reply.entries);
151
175
  Object.assign(dir, { next: reply.nextCursor ?? null, error: null, pages: dir.pages + 1 });
152
176
  } catch (error) {
153
- if (!error.stale && current()) dir.error = { code: error.code, message: error.message };
177
+ if (error.stale || !current()) return;
178
+ // 游标过期:从第一页重取,条数比现在多一条,所以还会接着往下取。重取自己管 loading。
179
+ if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#reload(path, generation, { more: true, expired: true });
180
+ dir.error = { code: error.code, message: error.message };
154
181
  } finally {
155
182
  if (current()) dir.loading = false;
156
183
  this.onChange();
@@ -178,9 +205,10 @@ const parseLoaded = raw => Object.fromEntries(Object.entries(raw && typeof raw =
178
205
 
179
206
  // 读回来的值可能是别的版本或坏的,只认自己的形状。
180
207
  export function parseState(raw) {
181
- const state = { v: 1, seq: 0, hidden: false, sessions: {} };
208
+ const state = { v: 1, seq: 0, hidden: false, sort: DEFAULT_SORT, sessions: {} };
182
209
  if (!raw || typeof raw !== 'object' || raw.v !== 1) return state;
183
210
  state.hidden = raw.hidden === true;
211
+ state.sort = parseSort(raw.sort) ?? DEFAULT_SORT;
184
212
  state.seq = Number.isSafeInteger(raw.seq) ? raw.seq : 0;
185
213
  for (const [id, item] of Object.entries(raw.sessions ?? {})) {
186
214
  if (!item || typeof item !== 'object') continue;
@@ -188,7 +216,8 @@ export function parseState(raw) {
188
216
  state.sessions[id] = {
189
217
  at: Number.isSafeInteger(item.at) ? item.at : 0, expanded: strings(item.expanded, 5000),
190
218
  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) },
219
+ // 滚动位置是按当时的排序存的;旧版本没有这个字段,那时一定是默认排序。
220
+ scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left), sort: parseSort(scroll.sort) ?? DEFAULT_SORT },
192
221
  };
193
222
  const loaded = parseLoaded(item.loaded);
194
223
  if (Object.keys(loaded).length > 0) state.sessions[id].loaded = loaded;
package/view/notice.mjs CHANGED
@@ -1,18 +1,25 @@
1
- // 说明区:一段文字,或「没连上 + 原因 + 重试」。树页和文件页共用。
1
+ // 说明区:大号图标加一段文字,或「没连上 + 原因 + 重试」。树页和文件页共用。
2
2
  // 重画会换掉正在聚焦的按钮:焦点留在说明区里(有重试按钮就落在它上面),不丢到页面外。
3
- export function showNotice(el, { text, failure, retry }) {
3
+ import { icon } from './icons.mjs';
4
+
5
+ const text = content => Object.assign(document.createElement('p'), { textContent: content });
6
+
7
+ export function showNotice(el, { text: message, failure, retry, glyph = 'folder' }) {
4
8
  const focused = el.contains(document.activeElement);
5
9
  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
+ const mark = document.createElement('span');
11
+ mark.className = 'notice-icon';
12
+ if (failure === undefined) {
13
+ mark.append(icon(glyph, 44));
14
+ el.replaceChildren(mark, text(message));
15
+ } else {
16
+ const button = document.createElement('button'), reason = text(failure);
17
+ mark.append(icon('warning', 44));
10
18
  reason.className = 'secondary';
11
- reason.textContent = failure;
12
19
  button.className = 'link';
13
20
  button.textContent = '重试';
14
21
  button.addEventListener('click', retry);
15
- el.replaceChildren(title, reason, button);
22
+ el.replaceChildren(mark, text('没有连上资源管理器的后台'), reason, button);
16
23
  target = button;
17
24
  }
18
25
  if (focused) { el.tabIndex = -1; target.focus(); }