@coda-console/resource-manager 0.5.0 → 0.7.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/menu.mjs CHANGED
@@ -1,71 +1,196 @@
1
1
  // 菜单:Mac 右键、iPhone 长按的行菜单,Mac 选中文字的右键菜单,iPhone 的 ⋯ 和 Mac 原生「更多」弹出的菜单都用它,树页和文件页各挂一个。
2
- // 菜单开着时点菜单外只关菜单、紧接着的那次点击不交给页面;Escape、窗口失焦关闭;页面里别的滚动区域滚动时由页面调 hide。
2
+ // 菜单开着时点菜单外只关菜单、紧接着的那次点击不交给页面;Escape、窗口失焦、旋转(窗口尺寸变化)关闭;页面里别的滚动区域滚动时由页面调 hide。
3
+ // 菜单可以有一层二级菜单(项里写 submenu)。「整次菜单」(current)和「当前层」(layer、fly)分开记:
4
+ // 在面板里切到下一层、退回来,整次菜单还是同一次,但上一层的按钮不再响应。第二个面板(sub)也算菜单里面,点它不是点外面。
3
5
  import { icon } from './icons.mjs';
4
6
 
5
- // el:页面里的 #menu。open 之后的位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
7
+ const CLOSE_MS = 150; // 鼠标移到别的项之后,侧面板收起前等多久:斜着移过去不会误关
8
+ const GAP = 2; // 侧面板和根面板之间留的空隙
9
+
10
+ // el:页面里的 #menu。sub:侧面板(#submenu),没有就不能弹出,二级菜单总是在 el 里切到下一层。
11
+ // flyout:true 时(Mac)鼠标移上去或点击「显示」这类项,侧面板在根面板左边弹出;放不下就退成切到下一层(iPhone 总是这样)。
12
+ // open 之后的位置按安全区夹住(横屏时客户端不替页面留);offsetWidth 在显示后才量得到。
6
13
  // 高度有上限(style.css 的 .menu):内容多时在菜单里滚动,不超出安全区。
7
- export function mountMenu(el) {
14
+ export function mountMenu(el, sub = null, { flyout = false } = {}) {
8
15
  let opener = null; // 打开菜单的按钮;用点打开的没有
9
16
  let current = null; // 这一次打开的标记:关闭之后留在手里的按钮不再响应
17
+ let layer = 0; // el 里现在是哪一层:每次换层(进下一层、退回、重新打开、关闭)加一,旧层的按钮据此作废
18
+ let fly = 0; // 侧面板的第几次展开:收起、重开都加一
19
+ let spec = null, anchor = null; // 根层的内容和锚点:退回根层、换层后重新定位要用
20
+ let flyButton = null; // 展开着侧面板的那个项
21
+ let closeTimer = null;
10
22
 
11
- // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(菜单贴在它下面、右对齐)或 { clientX, clientY } 的点。
12
- // items:[{ label, run, checked?, radio? } | { separator: true } | { heading }],checked 不是 undefined 的带对勾(radio 的是单选,其余是开关);
13
- // 分隔线和小标题不是菜单项,不可点。title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全;detail 是它下面的一行小字。
14
- function open(anchor, { title, detail, items }) {
15
- hide();
16
- const mine = current = {};
17
- const head = [];
18
- if (title !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title }));
19
- if (detail !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-info secondary caption', textContent: detail }));
23
+ // items:[{ label, run, checked?, radio? } | { label, submenu: { items } } | { separator: true } | { heading }],checked 不是 undefined 的带对勾(radio 的是单选,其余是开关);
24
+ // 分隔线和小标题不是菜单项,不可点。hover:这一层的项在鼠标移上去时管侧面板(只有根层,且 flyout)。
25
+ // alive:这一层还有没有效,点击时先问它。
26
+ function build(items, alive, hover) {
20
27
  const checkable = items.some(item => item.checked !== undefined); // 有开关项时,每一项都留出对勾的位置,文字才对齐
21
- el.replaceChildren(...head, ...items.map(({ label, run, checked, radio, separator, heading }) => {
28
+ return items.map(item => {
29
+ const { label, run, checked, radio, separator, heading, submenu } = item;
22
30
  if (separator) return Object.assign(document.createElement('hr'), { className: 'menu-sep' });
23
- if (heading !== undefined) return Object.assign(document.createElement('p'), { className: 'menu-head secondary caption', textContent: heading });
31
+ if (heading !== undefined) {
32
+ // 小标题和选项走同一套布局:这一层有对勾列时,小标题前也放一个同宽的空位,文字才和选项的文字左边对齐。
33
+ const head = Object.assign(document.createElement('p'), { className: 'menu-head secondary caption' });
34
+ if (checkable) head.append(Object.assign(document.createElement('span'), { className: 'check' }));
35
+ head.append(Object.assign(document.createElement('span'), { textContent: heading }));
36
+ return head;
37
+ }
24
38
  const button = document.createElement('button'), name = document.createElement('span');
25
39
  name.textContent = label;
26
40
  if (checkable) {
27
41
  const mark = document.createElement('span');
28
42
  mark.className = 'check';
29
- if (checked) mark.append(icon('check', 16));
43
+ if (checked) mark.append(icon('check', 14));
30
44
  button.append(mark);
31
45
  }
32
46
  button.append(name);
33
- button.setAttribute('role', checked === undefined ? 'menuitem' : radio ? 'menuitemradio' : 'menuitemcheckbox');
34
- if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
35
- button.addEventListener('click', () => {
36
- if (current !== mine) return; // 菜单已经关了(或换成了别的):留在手里的按钮不再响应
37
- hide();
38
- run();
47
+ if (submenu) {
48
+ const arrow = document.createElement('span');
49
+ arrow.className = 'sub-arrow';
50
+ arrow.append(icon('chevron', 14));
51
+ button.append(arrow);
52
+ button.setAttribute('role', 'menuitem');
53
+ button.setAttribute('aria-haspopup', 'menu');
54
+ button.setAttribute('aria-expanded', 'false');
55
+ // 进下一层不是叶子项:不关菜单,也不执行什么。
56
+ button.addEventListener('click', () => { if (alive()) show(button, item, true); });
57
+ } else {
58
+ button.setAttribute('role', checked === undefined ? 'menuitem' : radio ? 'menuitemradio' : 'menuitemcheckbox');
59
+ if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
60
+ button.addEventListener('click', () => {
61
+ if (!alive()) return; // 菜单已经关了(换成了别的、退回了上一层):留在手里的按钮不再响应
62
+ hide();
63
+ run();
64
+ });
65
+ }
66
+ if (hover) button.addEventListener('pointerenter', event => {
67
+ if (!alive() || event.pointerType === 'touch') return;
68
+ if (submenu) show(button, item, false); else later();
39
69
  });
40
70
  return button;
41
- }));
42
- el.hidden = false;
71
+ });
72
+ }
73
+
74
+ // 根层:路径标题、信息行,和项。
75
+ function paintRoot() {
76
+ const { title, detail, items } = spec, mine = current, mineLayer = ++layer;
77
+ const head = [];
78
+ if (title !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title }));
79
+ if (detail !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-info secondary caption', textContent: detail }));
80
+ el.replaceChildren(...head, ...build(items, () => current === mine && layer === mineLayer, flyout && sub !== null));
43
81
  el.scrollTop = 0;
82
+ }
83
+
84
+ // 贴在锚点下面、右对齐(锚点是按钮元素或同样有 getBoundingClientRect 的假锚点),或放在点上;每次换层内容宽度变了都要重来。
85
+ function place() {
44
86
  const box = anchor.getBoundingClientRect?.();
45
87
  const x = box ? box.right - el.offsetWidth : anchor.clientX, y = box ? box.bottom + 4 : anchor.clientY;
46
88
  el.style.left = `max(var(--safe-left), min(${x}px, calc(100vw - var(--safe-right) - ${el.offsetWidth + 4}px)))`;
47
89
  el.style.top = `max(var(--safe-top), min(${y}px, calc(100vh - var(--safe-bottom) - ${el.offsetHeight + 4}px)))`;
48
- if (box) { opener = anchor; opener.setAttribute?.('aria-expanded', 'true'); }
49
90
  }
50
91
 
92
+ // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(原生按钮:只代表根层,子菜单贴的是真实的项)或 { clientX, clientY } 的点。
93
+ // title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全;detail 是它下面的一行小字。
94
+ function open(at, content) {
95
+ hide();
96
+ current = {};
97
+ spec = content;
98
+ anchor = at;
99
+ paintRoot();
100
+ el.hidden = false;
101
+ place();
102
+ if (at.getBoundingClientRect) { opener = at; opener.setAttribute?.('aria-expanded', 'true'); }
103
+ }
104
+
105
+ // 二级菜单:click 是点击(键盘激活也是);鼠标移上去只在放得下时弹出,放不下什么都不做,免得内容在鼠标底下突然换掉。
106
+ function show(button, item, click) {
107
+ keep();
108
+ if (flyout && sub !== null) {
109
+ if (flyButton === button) return; // 已经开着
110
+ collapse();
111
+ const mine = current, mineFly = ++fly;
112
+ const nodes = build(item.submenu.items, () => current === mine && fly === mineFly, false);
113
+ sub.replaceChildren(...nodes);
114
+ sub.hidden = false;
115
+ sub.style.visibility = 'hidden'; // 先量尺寸再决定放不放得下,量的时候别让人看到
116
+ sub.scrollTop = 0;
117
+ const { offsetWidth, offsetHeight } = sub, root = el.getBoundingClientRect(), at = button.getBoundingClientRect();
118
+ const x = root.left - offsetWidth - GAP;
119
+ if (x >= safeLeft()) {
120
+ sub.style.left = `${x}px`;
121
+ sub.style.top = `max(var(--safe-top), min(${at.top - 5}px, calc(100vh - var(--safe-bottom) - ${offsetHeight + 4}px)))`; // 第一项和「显示」对齐:减去面板的边框和内边距
122
+ sub.style.visibility = '';
123
+ flyButton = button;
124
+ button.setAttribute('aria-expanded', 'true');
125
+ if (click) nodes.find(node => node.tagName === 'BUTTON')?.focus?.(); // 键盘激活:焦点进侧面板
126
+ return;
127
+ }
128
+ collapse(); // 放不下:和 iPhone 一样切到下一层
129
+ }
130
+ if (click) enter(item);
131
+ }
132
+
133
+ // 在 el 里切到下一层:顶上一行返回;点返回回到根层,下一层的按钮此后不再响应。
134
+ function enter(item) {
135
+ const mine = current, mineLayer = ++layer, alive = () => current === mine && layer === mineLayer;
136
+ const back = document.createElement('button'), mark = document.createElement('span'), name = document.createElement('span');
137
+ mark.className = 'check back';
138
+ mark.append(icon('back', 14));
139
+ name.textContent = '返回';
140
+ back.className = 'menu-back';
141
+ back.append(mark, name);
142
+ back.setAttribute('role', 'menuitem');
143
+ back.addEventListener('click', () => {
144
+ if (!alive()) return;
145
+ paintRoot();
146
+ place();
147
+ });
148
+ el.replaceChildren(back, Object.assign(document.createElement('hr'), { className: 'menu-sep' }), ...build(item.submenu.items, alive, false));
149
+ el.scrollTop = 0;
150
+ place();
151
+ }
152
+
153
+ // 鼠标回到「显示」或侧面板:取消正在等的收起。
154
+ function keep() { clearTimeout(closeTimer); closeTimer = null; }
155
+ // 鼠标移到别的项:等一会儿再收起侧面板。
156
+ function later() {
157
+ if (flyButton === null || closeTimer !== null) return;
158
+ const mine = current;
159
+ closeTimer = setTimeout(() => { closeTimer = null; if (current === mine) collapse(); }, CLOSE_MS);
160
+ }
161
+ function collapse() {
162
+ keep();
163
+ fly++; // 侧面板里的旧按钮不再响应
164
+ if (sub) sub.hidden = true;
165
+ flyButton?.setAttribute('aria-expanded', 'false');
166
+ flyButton = null;
167
+ }
168
+ // 安全区的左边:body 的左内边距就是它(style.css),算出来的是像素。读不到按 0。
169
+ const safeLeft = () => { const px = parseFloat(globalThis.getComputedStyle?.(document.body)?.paddingLeft); return Number.isFinite(px) ? px : 0; };
170
+
51
171
  function hide() {
52
172
  current = null;
173
+ layer++;
174
+ collapse();
53
175
  el.hidden = true;
54
176
  opener?.setAttribute?.('aria-expanded', 'false');
55
177
  opener = null;
56
178
  }
57
179
 
58
- // 菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
180
+ // 两个面板都算菜单里面。菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
181
+ const inside = target => el.contains(target) || (sub !== null && sub.contains(target));
59
182
  let dismissed = false;
60
183
  document.addEventListener('pointerdown', event => {
61
- dismissed = !el.hidden && !el.contains(event.target);
62
- if (!el.contains(event.target)) hide();
184
+ dismissed = !el.hidden && !inside(event.target);
185
+ if (!inside(event.target)) hide();
63
186
  }, true);
64
187
  document.addEventListener('click', event => {
65
188
  if (dismissed) { dismissed = false; event.stopPropagation(); }
66
189
  }, true);
67
190
  document.addEventListener('keydown', event => { if (event.key === 'Escape') hide(); });
68
191
  window.addEventListener('blur', hide);
192
+ window.addEventListener('resize', hide); // 旋转、拖窄侧栏:位置对不上了
193
+ sub?.addEventListener('pointerenter', keep);
69
194
 
70
195
  return {
71
196
  open, hide,
package/view/model.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // 页面的纯状态:目录树、状态保留。不碰 DOM,请求与代次在 connection.mjs,设计见 docs/design/phase-1.md 第 6、7 节。
2
- import { DEFAULT_SORT, ErrorCode, RootState, Type, parseSort } from './protocol.mjs';
2
+ import { DEFAULT_SORT, ErrorCode, RootState, Type, parseSort, splitRelative } from './protocol.mjs';
3
3
 
4
4
  export const STATE_LIMIT = 96 * 1024;
5
5
  export const MAX_PARALLEL = 8;
@@ -11,8 +11,13 @@ const MAX_LOADED_DIRS = 500;
11
11
  const HIDDEN = new Set(['.git', '.DS_Store']);
12
12
  export const isHidden = name => HIDDEN.has(name);
13
13
  export const joinPath = (dir, name) => (dir ? `${dir}/${name}` : name);
14
+ export const parentOf = path => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
14
15
  const inside = (path, dir) => path === dir || path.startsWith(`${dir}/`);
15
16
 
17
+ // 两种视图:列表(目录树,可以展开多层)和图标(一次看一层,看的那一层是 cwd)。全局一份,和排序一样。
18
+ export const View = Object.freeze({ LIST: 'list', ICONS: 'icons' });
19
+ export const parseView = raw => (raw === View.ICONS ? View.ICONS : View.LIST);
20
+
16
21
  async function pool(items, limit, fn) {
17
22
  let index = 0;
18
23
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -37,12 +42,23 @@ export class Model {
37
42
  dirs = new Map(); // path → { entries, next, loaded, loading, error, token }
38
43
  expanded = new Set(); // 不变量:展开的目录,它的每一级上层也展开
39
44
  wanted = new Map(); // 恢复状态时各目录要取够的条数,第一次取用后删掉
40
- selected = null;
45
+ selected = null; // 选中的条目(高亮和键盘移动用,文件夹、不能打开的条目都可以)
46
+ opened = null; // Mac 侧栏预览中的文件;iPhone 一直是 null
41
47
  showHidden = false;
42
48
  sort = DEFAULT_SORT; // 全局一份,由页面存进 persisted
49
+ view = View.LIST; // 全局一份,由页面存进 persisted
50
+ cwd = ''; // 图标视图正在看的目录,'' 是根目录;每个会话一份,连同当时的根目录存进会话状态
51
+ scope = 0; // 根目录的身份:这个会话认定「换了根目录」时加一,依赖根目录的东西(待恢复的滚动)据此作废
43
52
  #round = 0; // refresh 的轮次:新一轮开始后,旧一轮不再派发排队的目录
53
+ #nav = 0; // 导航上下文:进入、返回、换会话、回到根目录、回退各加一;一次请求只有发出时的上下文还在,才能改 cwd
54
+ #savedRoot = null; // 会话状态里存的根目录;收到这个会话第一条就绪的 root 之前,是否「同一个根目录」靠它比
55
+ #resolved = false; // 这个会话已经收到过就绪的 root
56
+ #rootPath = null; // 就绪的根目录路径,之后的变化靠它比
57
+ #quiet = false; // cwd 是从保存的状态里恢复的,还没确认过:它没了不提示
58
+ #noticed = -1; // 提示过「文件夹已不存在」的轮次,一轮只提示一次
44
59
 
45
- constructor({ link, onChange = () => {} }) { Object.assign(this, { link, onChange }); }
60
+ // onLost(path):cwd 没了、已经退到上一层时调用一次(恢复时不调用)。
61
+ constructor({ link, onChange = () => {}, onLost = () => {} }) { Object.assign(this, { link, onChange, onLost }); }
46
62
 
47
63
  get ready() { return this.root?.state === RootState.READY; }
48
64
 
@@ -63,21 +79,44 @@ export class Model {
63
79
  this.session = session ?? null;
64
80
  this.root = null;
65
81
  this.dirs = new Map();
82
+ this.#nav++;
83
+ this.#resolved = false;
84
+ this.#rootPath = null;
85
+ this.#savedRoot = typeof saved?.root === 'string' ? saved.root : null;
86
+ this.cwd = typeof saved?.cwd === 'string' ? saved.cwd : '';
87
+ this.#quiet = this.cwd !== '';
66
88
  this.wanted = new Map(Object.entries(saved?.loaded ?? {}).map(([path, count]) => [path, Math.min(count, RESTORE_LIMIT)]));
67
89
  const paths = (saved?.expanded ?? []).filter(path => path !== '');
68
90
  this.expanded = new Set(paths.filter(path => !path.includes('/') || paths.includes(path.slice(0, path.lastIndexOf('/')))));
69
91
  this.selected = saved?.selected ?? null;
92
+ this.opened = saved?.opened ?? null;
70
93
  this.onChange();
71
94
  }
72
95
 
73
96
  // 只换根目录状态,不动会话状态;ready 时重新取全部。
74
97
  onRoot({ generation, state, path }) {
75
98
  if (generation !== this.link.generation) return null;
99
+ if (state === RootState.READY) this.#identify(path);
76
100
  this.root = { state, path };
77
101
  this.onChange();
78
102
  return state === RootState.READY ? this.refresh() : Promise.resolve();
79
103
  }
80
104
 
105
+ // 根目录有没有换:重建页面后 model.root 是 null,不能靠「路径变了」,否则每次重建都算换了。
106
+ // 这个会话第一条就绪的 root 和保存的根目录比(没存根目录的旧状态当作没换),之后的 root 和上一次比。换了就全部回到根目录。
107
+ #identify(path) {
108
+ const changed = this.#resolved ? this.#rootPath !== path : this.#savedRoot !== null && this.#savedRoot !== path;
109
+ this.#resolved = true;
110
+ this.#rootPath = path;
111
+ if (!changed) return;
112
+ this.scope++;
113
+ this.#nav++;
114
+ this.cwd = '';
115
+ this.selected = this.opened = null;
116
+ this.#quiet = false;
117
+ this.wanted = new Map();
118
+ }
119
+
81
120
  onChanged({ generation }) {
82
121
  return generation === this.link.generation && this.ready ? this.refresh() : null;
83
122
  }
@@ -87,7 +126,40 @@ export class Model {
87
126
  refresh({ cap = Infinity } = {}) {
88
127
  if (!this.ready) return Promise.resolve();
89
128
  const { generation } = this.link, round = ++this.#round;
90
- return pool(['', ...this.expanded], MAX_PARALLEL, path => (round === this.#round ? this.#reload(path, generation, { cap }) : undefined));
129
+ return pool(this.requested(), MAX_PARALLEL, path => (round === this.#round ? this.#reload(path, generation, { cap }) : undefined));
130
+ }
131
+
132
+ // 一轮要取的目录:列表是根和展开的,图标是根和 cwd;同一路径只取一次。
133
+ requested() { return this.view === View.ICONS ? [...new Set(['', this.cwd])] : ['', ...this.expanded]; }
134
+
135
+ // 换视图:马上按新的集合刷新,作废旧的排队轮次;回来之前显示已有的内容,没有就显示读取中。展开状态不动。
136
+ setView(view) {
137
+ const next = parseView(view);
138
+ if (next === this.view) return Promise.resolve();
139
+ this.view = next;
140
+ this.onChange();
141
+ return this.refresh();
142
+ }
143
+
144
+ // 图标视图进入一层:cwd 换成它并加载。返回 levels 层(缺省一层,到根为止)。
145
+ enter(path) {
146
+ this.cwd = path;
147
+ return this.#go();
148
+ }
149
+
150
+ leave(levels = 1) {
151
+ let next = this.cwd;
152
+ for (let i = 0; i < levels && next !== ''; i++) next = parentOf(next);
153
+ if (next === this.cwd) return Promise.resolve();
154
+ this.cwd = next;
155
+ return this.#go();
156
+ }
157
+
158
+ #go() {
159
+ this.#nav++;
160
+ this.#quiet = false;
161
+ this.onChange();
162
+ return this.retry(this.cwd);
91
163
  }
92
164
 
93
165
  // 换排序:已加载的目录按新顺序重新取,取够现在的条数,这次最多 RESTORE_LIMIT 条;每个目录一次替换。
@@ -105,7 +177,7 @@ export class Model {
105
177
  if (this.link.generation !== generation) return; // 排队时会话已换,旧任务不碰新会话
106
178
  let dir = this.dirs.get(path);
107
179
  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;
180
+ const token = ++dir.token, { sort } = this, nav = this.#nav;
109
181
  const want = more ? dir.entries.length + 1 : Math.min(Math.max(dir.entries.length, this.wanted.get(path) ?? 0), cap);
110
182
  dir.loading = true;
111
183
  this.onChange();
@@ -130,27 +202,50 @@ export class Model {
130
202
  pages++;
131
203
  } while (pages === 0 || (next && entries.length < want));
132
204
  if (!current()) return;
133
- Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback });
205
+ Object.assign(dir, { entries, next, loaded: true, error: null, pages, sortFallback, sort });
134
206
  this.wanted.delete(path); // 成功后才删:取页失败后重试还要取够保存的条数
207
+ if (path === this.cwd) this.#quiet = false;
135
208
  } catch (error) {
136
209
  if (error.stale || !current()) return;
137
- if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#drop(path);
138
- else if (error.code !== ErrorCode.NO_ROOT) dir.error = { code: error.code, message: error.message };
210
+ if (error.code === ErrorCode.NOT_FOUND && path !== '') this.#lost(path, nav);
211
+ else if (error.code !== ErrorCode.NO_ROOT) {
212
+ dir.error = { code: error.code, message: error.message };
213
+ if (path === this.cwd) this.#quiet = false;
214
+ }
139
215
  } finally {
140
216
  if (current()) dir.loading = false;
141
217
  this.onChange();
142
218
  }
143
219
  }
144
220
 
145
- #drop(path) {
146
- for (const key of [...this.dirs.keys()]) if (inside(key, path)) this.dirs.delete(key);
221
+ // 目录没了(not_found):所有列目录入口都走这里。先清掉失效的子树;cwd 在里面、而且发出请求以来没有导航过,就退到上一层。
222
+ // 退到哪一层靠新发的请求:它再 not_found 又走到这里,所以每级只试一次;别的错误停在那一级,显示失败行和重试。
223
+ // 清掉子树后原目录对象没了,原请求的检查必然为假,但回退不靠它:回退看的是导航上下文,每一级有自己的请求。
224
+ #lost(path, nav) {
225
+ const covers = nav === this.#nav && inside(this.cwd, path);
226
+ // 迟到的上层失败(发出后用户已经进了别处):清它的子树,但正在加载的 cwd 的条目留着,不然它的回答提交不上。
227
+ this.#drop(path, covers ? null : this.cwd);
228
+ if (!covers) return;
229
+ this.#nav++;
230
+ this.cwd = parentOf(path);
231
+ if (!this.#quiet && this.#noticed !== this.#round && this.view === View.ICONS) {
232
+ this.#noticed = this.#round;
233
+ this.onLost(path);
234
+ }
235
+ this.onChange();
236
+ this.retry(this.cwd);
237
+ }
238
+
239
+ #drop(path, keep = null) {
240
+ for (const key of [...this.dirs.keys()]) if (key !== keep && inside(key, path)) this.dirs.delete(key);
147
241
  for (const key of [...this.expanded]) if (inside(key, path)) this.expanded.delete(key);
148
242
  }
149
243
 
150
244
  toggle(path) {
151
245
  if (this.expanded.has(path)) {
152
246
  for (const key of [...this.expanded]) if (inside(key, path)) this.expanded.delete(key);
153
- for (const key of [...this.dirs.keys()]) if (key !== '' && inside(key, path)) this.dirs.delete(key);
247
+ // cwd 的条目留着:图标视图还在看它
248
+ for (const key of [...this.dirs.keys()]) if (key !== '' && key !== this.cwd && inside(key, path)) this.dirs.delete(key);
154
249
  this.onChange();
155
250
  } else {
156
251
  this.expanded.add(path);
@@ -164,7 +259,9 @@ export class Model {
164
259
  async loadMore(path) {
165
260
  const dir = this.dirs.get(path), { generation } = this.link;
166
261
  if (!dir?.next || dir.loading || !this.ready) return;
167
- const token = ++dir.token;
262
+ // 游标是按另一种排序取的(换排序时这个目录没重建过):不用它,从第一页重取,条数比现在多一条。
263
+ if (dir.sort !== this.sort) return this.#reload(path, generation, { more: true, expired: true });
264
+ const token = ++dir.token, nav = this.#nav;
168
265
  dir.loading = true;
169
266
  this.onChange();
170
267
  const current = () => this.link.generation === generation && this.dirs.get(path) === dir && dir.token === token;
@@ -177,6 +274,7 @@ export class Model {
177
274
  if (error.stale || !current()) return;
178
275
  // 游标过期:从第一页重取,条数比现在多一条,所以还会接着往下取。重取自己管 loading。
179
276
  if (error.code === ErrorCode.CURSOR_EXPIRED) return this.#reload(path, generation, { more: true, expired: true });
277
+ if (error.code === ErrorCode.NOT_FOUND && path !== '') return this.#lost(path, nav);
180
278
  dir.error = { code: error.code, message: error.message };
181
279
  } finally {
182
280
  if (current()) dir.loading = false;
@@ -184,13 +282,23 @@ export class Model {
184
282
  }
185
283
  }
186
284
 
187
- select(path) { this.selected = path; this.onChange(); }
285
+ // 选中只影响高亮,不发 onChange:重画会换掉全部行节点,双击的第二下点击之后 dblclick 就丢了。页面的 selectEntry 负责切高亮和保存。返回是不是变了。
286
+ select(path) {
287
+ if (this.selected === path) return false;
288
+ this.selected = path;
289
+ return true;
290
+ }
291
+ // Mac 打开文件:选中它并切到预览。返回(closeFile)只清 opened,选中留着。
292
+ openFile(path) { this.selected = this.opened = path; this.onChange(); }
293
+ closeFile() { this.opened = null; this.onChange(); }
188
294
  setShowHidden(on) { this.showHidden = on; this.onChange(); }
189
295
  // loaded:取过不止一页的目录已加载的条数,只存条数不存内容;第一页每次都会重新取,不用存。
190
296
  snapshot() {
191
297
  const loaded = {};
192
298
  for (const [path, dir] of this.dirs) if (dir.pages > 1 && dir.entries.length > 0) loaded[path] = dir.entries.length;
193
- return { expanded: [...this.expanded], selected: this.selected, loaded };
299
+ // 还没收到这个会话就绪的 root 时,cwd 和根目录还是保存的那一份,原样存回去,不能被重建途中的一次保存冲掉。
300
+ const root = this.#resolved ? this.#rootPath : this.#savedRoot;
301
+ return { expanded: [...this.expanded], selected: this.selected, opened: this.opened, loaded, cwd: this.cwd, ...(root === null ? {} : { root }) };
194
302
  }
195
303
  }
196
304
 
@@ -203,12 +311,16 @@ const strings = (value, max) => (Array.isArray(value) ? value.filter(s => typeof
203
311
  const parseLoaded = raw => Object.fromEntries(Object.entries(raw && typeof raw === 'object' ? raw : {})
204
312
  .filter(([path, count]) => path.length <= 1024 && Number.isSafeInteger(count) && count > 0 && count <= MAX_LOADED).slice(0, MAX_LOADED_DIRS));
205
313
 
314
+ // cwd 要是后端认的相对路径(规则同 lib/paths.mjs),而且写法规整:model 里的路径都是 joinPath 拼出来的,不带空段和 `.`。
315
+ const cleanRelative = path => { const { segments } = splitRelative(path); return segments !== undefined && segments.join('/') === path; };
316
+
206
317
  // 读回来的值可能是别的版本或坏的,只认自己的形状。
207
318
  export function parseState(raw) {
208
- const state = { v: 1, seq: 0, hidden: false, sort: DEFAULT_SORT, sessions: {} };
319
+ const state = { v: 1, seq: 0, hidden: false, sort: DEFAULT_SORT, view: View.LIST, sessions: {} };
209
320
  if (!raw || typeof raw !== 'object' || raw.v !== 1) return state;
210
321
  state.hidden = raw.hidden === true;
211
322
  state.sort = parseSort(raw.sort) ?? DEFAULT_SORT;
323
+ state.view = parseView(raw.view);
212
324
  state.seq = Number.isSafeInteger(raw.seq) ? raw.seq : 0;
213
325
  for (const [id, item] of Object.entries(raw.sessions ?? {})) {
214
326
  if (!item || typeof item !== 'object') continue;
@@ -216,9 +328,16 @@ export function parseState(raw) {
216
328
  state.sessions[id] = {
217
329
  at: Number.isSafeInteger(item.at) ? item.at : 0, expanded: strings(item.expanded, 5000),
218
330
  selected: typeof item.selected === 'string' && item.selected.length <= 1024 ? item.selected : null,
331
+ // 0.6.0 的状态没有 opened:selected 只当选中,不打开预览。
332
+ opened: typeof item.opened === 'string' && item.opened.length <= 1024 ? item.opened : null,
219
333
  // 滚动位置是按当时的排序存的;旧版本没有这个字段,那时一定是默认排序。
220
- scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left), sort: parseSort(scroll.sort) ?? DEFAULT_SORT },
334
+ // 两种视图各存各的位置和当时的排序:tree 和 sort 是列表的,grid 和 gridSort 是图标的(旧版本没有后两个)。
335
+ scroll: { tree: num(scroll.tree), top: num(scroll.top), left: num(scroll.left), sort: parseSort(scroll.sort) ?? DEFAULT_SORT,
336
+ grid: num(scroll.grid), gridSort: parseSort(scroll.gridSort) ?? DEFAULT_SORT },
221
337
  };
338
+ // cwd 和存它时的根目录:超长或形状不对当作没有,回到根目录。旧版本没有这两个字段。
339
+ const path = value => (typeof value === 'string' && value.length <= 1024 ? value : undefined);
340
+ if (path(item.cwd) !== undefined && path(item.root) !== undefined && cleanRelative(item.cwd)) Object.assign(state.sessions[id], { cwd: item.cwd, root: item.root });
222
341
  const loaded = parseLoaded(item.loaded);
223
342
  if (Object.keys(loaded).length > 0) state.sessions[id].loaded = loaded;
224
343
  }
package/view/preview.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  // 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
2
2
  import { h } from './dom.mjs';
3
3
  import { formatSize } from './format.mjs';
4
+ import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
4
5
  import { icon, iconFor } from './icons.mjs';
6
+ import { languageOf } from './languages.mjs';
5
7
  import { ContentKind, EntryKind, ErrorCode, IMAGE_LIMIT, TEXT_LIMIT, imageType } from './protocol.mjs';
6
8
  import { clippedSelection, linesOf } from './selection.mjs';
7
9
 
@@ -88,13 +90,20 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
88
90
  revoke();
89
91
  shown = { size: result.size, mtimeMs: result.mtimeMs };
90
92
  // 元信息:目录 · 行数 · 大小;根目录下的文件没有目录,非文本没有行数。修改时间放进 title。
93
+ // 高亮:认得出语言才试;超过上限不试,库或解析出错就退回纯文本,都在元信息里注明。认不出语言的不加说明。
91
94
  const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
92
95
  const lines = result.kind === ContentKind.TEXT ? `${lineCount(result.text)} 行` : '';
93
- const note = result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '';
96
+ const language = result.kind === ContentKind.TEXT ? languageOf(path.split('/').pop()) : null;
97
+ // 先判大小,超过只写「不高亮」;没超再判行长。
98
+ const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : hasLongLine(result.text) ? '行太长,不高亮' : '';
99
+ const colored = language && !skip ? highlight(result.text, language) : null;
100
+ const plain = !language ? '' : skip || (colored ? '' : '没能高亮');
101
+ const note = [result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '', plain].filter(Boolean).join(',');
94
102
  setMeta([dir, lines, formatSize(result.size), note].filter(Boolean).join(' · '), `修改于 ${formatTime(result.mtimeMs)}`);
95
103
  if (result.kind === ContentKind.TEXT) {
96
104
  const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
97
- const text = h('pre', { class: 'text selectable' }, result.text);
105
+ const text = h('pre', { class: 'text selectable' }, ...(colored ? [] : [result.text]));
106
+ if (colored) appendAll(text, colored);
98
107
  if (selectionMenu) text.addEventListener('contextmenu', event => onSelect(event, text));
99
108
  body.replaceChildren(h('div', { class: 'code' }, gutter, text));
100
109
  } else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
package/view/protocol.mjs CHANGED
@@ -60,6 +60,20 @@ export function imageType(name) {
60
60
  return dot < 0 ? null : IMAGE_TYPES[name.slice(dot + 1).toLowerCase()] ?? null;
61
61
  }
62
62
 
63
+ // 相对路径的规则只在这一处:模块(lib/paths.mjs)校验请求,页面恢复保存的 cwd 时用同一个函数。
64
+ // 空串是根目录;拒绝过长、控制字符、绝对路径和 `..`。返回 { segments }(去掉空段和 `.`)或 { problem }(给人看的原因)。
65
+ export const MAX_PATH = 4096;
66
+ const CONTROL = /[\u0000-\u001f\u007f]/;
67
+ export const hasControl = text => CONTROL.test(text);
68
+ export function splitRelative(path) {
69
+ if (typeof path !== 'string' || path.length > MAX_PATH) return { problem: '路径无效' };
70
+ if (hasControl(path)) return { problem: '路径含控制字符' };
71
+ if (path.startsWith('/')) return { problem: '只接受相对路径' };
72
+ const segments = path.split('/').filter(part => part !== '' && part !== '.');
73
+ if (segments.includes('..')) return { problem: '路径不能含 ..' };
74
+ return { segments };
75
+ }
76
+
63
77
  export const messageSize = message => JSON.stringify({ message }).length;
64
78
 
65
79
  // 带 code 的错误,模块里到处抛,主模块转成回答里的 error。
@@ -0,0 +1,57 @@
1
+ // 滚动位置的两样记录:待恢复的位置(页面重建、换会话、返回上一层之后,等内容到了才用)和上层的位置(图标视图进入子目录前的位置,只在内存里)。
2
+ // 不碰 DOM:滚动的元素由页面通过 panes 给。设计见 docs/design/phase-3.md 第 14.5 节。
3
+ import { View } from './model.mjs';
4
+
5
+ export const TRAIL_LIMIT = 32;
6
+
7
+ // 图标视图进入子目录之前,上层的滚动位置:按目录存,最多 limit 层,满了丢最久没用的。不存进 setState:页面卸载后就没了。
8
+ export function createTrail(limit = TRAIL_LIMIT) {
9
+ const tops = new Map();
10
+ return {
11
+ remember(dir, top) { tops.delete(dir); tops.set(dir, top); while (tops.size > limit) tops.delete(tops.keys().next().value); },
12
+ // 取出并删掉:回到上一层时用一次。
13
+ take(dir) { const top = tops.get(dir); tops.delete(dir); return top; },
14
+ clear() { tops.clear(); },
15
+ get size() { return tops.size; },
16
+ };
17
+ }
18
+
19
+ const VIEW = { tree: View.LIST, grid: View.ICONS };
20
+
21
+ // 待恢复的滚动:每个视图(tree、grid)最多一份。不能只等一次 refresh() 完成:旧的一轮完成不等于内容到了,太早设置会被夹回顶部。
22
+ // 一份恢复绑定会话、根目录的身份(model.scope)、排序和目录(图标视图是 cwd),任何一个对不上就作废;
23
+ // 绑定的视图不是正在看的视图时等着,切过去才用。目标目录的内容到了才用,条数不够时浏览器夹到能到的最大值;加载失败就结束;用户自己滚动了就放弃。
24
+ // panes:{ tree, grid },各有 scroll() 和 scrollTo(top)。
25
+ export function createRestore(model, panes) {
26
+ const plans = { tree: null, grid: null };
27
+ // 内容到了:列表是根和展开的目录,图标是 cwd;每个都已经加载(或失败了,失败也算有结果),空着的、没发出的不算。
28
+ const dirsOf = key => (key === 'grid' ? [model.cwd] : ['', ...model.expanded]);
29
+ const bound = (key, plan) => plan.session === model.session && plan.scope === model.scope && plan.sort === model.sort && (key === 'tree' || plan.dir === model.cwd);
30
+
31
+ return {
32
+ // 现在的滚动位置就是用户没动过的基准:调用前页面先把滚动元素滚到顶部。
33
+ plan(key, top) {
34
+ plans[key] = { session: model.session, scope: model.scope, sort: model.sort, dir: key === 'grid' ? model.cwd : '', top, at: panes[key].scroll() };
35
+ },
36
+ drop(key) { plans[key] = null; },
37
+ clear() { plans.tree = plans.grid = null; },
38
+ // 还在等的位置(保存状态时用它,别存成还没恢复的 0);对不上的不算。
39
+ top(key) { return plans[key] && bound(key, plans[key]) ? plans[key].top : null; },
40
+ // 滚动事件:位置不是计划时的基准,就是用户自己滚的,不再跳回去。
41
+ scrolled(key) { if (plans[key] && panes[key].scroll() !== plans[key].at) plans[key] = null; },
42
+ // 每次重画之后调用。
43
+ settle() {
44
+ for (const key of Object.keys(plans)) {
45
+ const plan = plans[key];
46
+ if (!plan) continue;
47
+ if (!bound(key, plan)) { plans[key] = null; continue; }
48
+ if (model.view !== VIEW[key]) continue;
49
+ const states = dirsOf(key).map(dir => model.dirs.get(dir));
50
+ if (key === 'grid' && states[0] && !states[0].loaded && states[0].error) { plans[key] = null; continue; }
51
+ if (!states.every(state => state && (state.loaded || state.error))) continue;
52
+ plans[key] = null;
53
+ panes[key].scrollTo(plan.top);
54
+ }
55
+ },
56
+ };
57
+ }
@@ -1,7 +1,7 @@
1
1
  // 预览里选中的文字:裁到正文元素里面,算出覆盖的行。DOM 的部分只用 Range 的标准方法,行号是纯函数。
2
2
  const START_TO_START = 0, END_TO_END = 2; // Range.START_TO_START、Range.END_TO_END
3
3
 
4
- // el 是正文(一个 pre 加一个文本节点)。选区为空或和 el 不相交返回 null;
4
+ // el 是正文(一个 pre,里面是文本节点,上色后还有嵌套的 span)。选区为空或和 el 不相交返回 null;
5
5
  // 否则把选区裁到 el 里,返回 { text, start }:裁剪后的文字和它在 el 文字里的起点(UTF-16 偏移)。裁剪后为空也返回 null。
6
6
  // 选区的起点或终点落在 el 外面(跨出正文、从行号列开始拖)时,裁掉外面的部分。
7
7
  export function clippedSelection(el, selection = globalThis.getSelection?.()) {