@coda-console/resource-manager 0.5.0 → 0.6.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/grid.mjs ADDED
@@ -0,0 +1,213 @@
1
+ // 图标视图:一次看一层(model.cwd)。visibleCells 把模型压成扁平的单元格(纯逻辑),layoutOf 生成布局映射,mountGrid 只画可见的一段,上万条也不卡。
2
+ // 设计见 docs/design/phase-3.md 第 14 节。进入、返回、恢复滚动在页面(app.mjs)。
3
+ import { h } from './dom.mjs';
4
+ import { infoText } from './format.mjs';
5
+ import { mountGestures } from './gestures.mjs';
6
+ import { icon, iconFor } from './icons.mjs';
7
+ import { isHidden, joinPath } from './model.mjs';
8
+ import { EntryKind } from './protocol.mjs';
9
+ import { TITLES, rootName } from './tree.mjs';
10
+
11
+ const OVERSCAN = 2; // 上下多画几行
12
+
13
+ // 单元格:{ type: 'entry', path, name, kind, link, size, mtimeMs } 是条目;{ type: 'status' | 'more', path, text, retry? } 是说明项,独占一行。
14
+ // 说明的文字和 tree.mjs 的 visibleRows 一致,只是没有层级。
15
+ export function visibleCells(model) {
16
+ const dir = model.cwd, state = model.dirs.get(dir), cells = [];
17
+ const note = (text, retry) => ({ type: 'status', path: dir, text, ...(retry ? { retry } : {}) });
18
+ if (!state || (!state.loaded && !state.error)) return [note('正在读取…')];
19
+ if (!state.loaded) return [note(`读取失败:${state.error.message}`, true)];
20
+ if (state.error) cells.push(note(`更新失败:${state.error.message}`, true)); // 刷新失败:旧条目保留,点它重试
21
+ if (state.sortFallback) cells.push(note('条目太多,只能按名称排列'));
22
+ const before = cells.length;
23
+ for (const entry of state.entries) {
24
+ if (!model.showHidden && isHidden(entry.name)) continue;
25
+ cells.push({ type: 'entry', path: joinPath(dir, entry.name), name: entry.name, kind: entry.kind, link: entry.link === true, size: entry.size, mtimeMs: entry.mtimeMs });
26
+ }
27
+ if (state.next) cells.push({ type: 'more', path: dir, text: state.loading ? '正在读取…' : '再显示' });
28
+ else if (cells.length === before) cells.push(note(state.entries.length ? '只有隐藏项' : '空目录'));
29
+ return cells;
30
+ }
31
+
32
+ // 布局映射:一次生成,总高度、可见窗口、点击都用它。连续的条目各段占 ceil(n / 列数) 行,每个说明项独占一行;列数至少为 1。
33
+ // spans:{ from, count, row, rows, note } 按行从上到下。
34
+ export function layoutOf(cells, columns) {
35
+ const cols = Math.max(1, Math.floor(columns) || 1), spans = [];
36
+ let rows = 0;
37
+ for (let at = 0; at < cells.length;) {
38
+ if (cells[at].type !== 'entry') { spans.push({ from: at, count: 1, row: rows, rows: 1, note: true }); rows++; at++; continue; }
39
+ let end = at;
40
+ while (end < cells.length && cells[end].type === 'entry') end++;
41
+ const span = { from: at, count: end - at, row: rows, rows: Math.ceil((end - at) / cols), note: false };
42
+ spans.push(span);
43
+ rows += span.rows;
44
+ at = end;
45
+ }
46
+ return { cols, rows, spans };
47
+ }
48
+
49
+ const spanAt = (layout, row) => layout.spans.find(span => row >= span.row && row < span.row + span.rows);
50
+ // 这一行第一个单元格的序号。
51
+ export const firstOfRow = (layout, row) => { const span = spanAt(layout, row); return span.note ? span.from : span.from + (row - span.row) * layout.cols; };
52
+ // 这个序号的单元格在第几行。
53
+ export function rowOfCell(layout, index) {
54
+ const span = layout.spans.find(item => index >= item.from && index < item.from + item.count);
55
+ return span.note ? span.row : span.row + Math.floor((index - span.from) / layout.cols);
56
+ }
57
+ // 行高分两种:条目行 cellH,说明行 noteH(说明行不必和单元格一样高)。布局映射按行记,高度在这里换算,总高度、可见窗口、点击都用同一份。
58
+ // 第 row 行顶边的位置;row 等于总行数时是总高度。
59
+ export function rowTop(layout, row, cellH, noteH) {
60
+ let y = 0;
61
+ for (const span of layout.spans) {
62
+ const unit = span.note ? noteH : cellH;
63
+ if (row < span.row + span.rows) return y + Math.max(0, row - span.row) * unit;
64
+ y += span.rows * unit;
65
+ }
66
+ return y;
67
+ }
68
+ // y 落在第几行(向下取整);超出内容是总行数。
69
+ export function rowAt(layout, y, cellH, noteH) {
70
+ let top = 0;
71
+ for (const span of layout.spans) {
72
+ const unit = span.note ? noteH : cellH, height = span.rows * unit;
73
+ if (y < top + height) return span.row + Math.max(0, Math.floor((y - top) / unit));
74
+ top += height;
75
+ }
76
+ return layout.rows;
77
+ }
78
+ // 顶边在 y 之上的行数(向上取整):可见窗口画到这一行之前。
79
+ export function rowsAbove(layout, y, cellH, noteH) {
80
+ let top = 0;
81
+ for (const span of layout.spans) {
82
+ const unit = span.note ? noteH : cellH, height = span.rows * unit;
83
+ if (y <= top) return span.row;
84
+ if (y < top + height) return span.row + Math.ceil((y - top) / unit);
85
+ top += height;
86
+ }
87
+ return layout.rows;
88
+ }
89
+
90
+ // 第 first 行(含)到第 last 行(不含)的单元格序号范围 [from, to)。
91
+ export function windowOf(layout, first, last) {
92
+ if (first >= last) return { from: 0, to: 0 };
93
+ const from = firstOfRow(layout, first), tail = spanAt(layout, last - 1);
94
+ return { from, to: Math.min(tail.from + tail.count, tail.note ? tail.from + 1 : firstOfRow(layout, last - 1) + layout.cols) };
95
+ }
96
+
97
+ // handlers: { open(path), enter(path), more(path), retry(path), menu(event, cell), back? }
98
+ // back 给了就在头部最左边放「返回」(Mac,和没有原生返回的环境);不给就没有头部,iPhone 用原生返回,标题在工具条上。
99
+ // draggable、longPress 同 mountTree。
100
+ export function mountGrid(el, model, handlers, { draggable = true, longPress = false } = {}) {
101
+ const head = h('div', { class: 'ghead' }), body = h('div', { class: 'gbody' }), spacer = h('div', { class: 'gspacer' }), win = h('div', { class: 'gwin' });
102
+ head.hidden = true;
103
+ spacer.append(win);
104
+ body.append(spacer);
105
+ el.replaceChildren(head, body);
106
+ let cells = [], layout = layoutOf([], 1), cellW = 72, cellH = 76, noteH = 32, measuredWidth = -1, headKey = null;
107
+
108
+ // 探针放在 win 里:量到的是单元格和说明行在真实结构里的尺寸,两种行高不同。
109
+ const measure = () => {
110
+ const probe = h('div', { class: 'gi cell' }), note = h('div', { class: 'gi gnote' });
111
+ probe.style.visibility = note.style.visibility = 'hidden';
112
+ win.append(probe, note);
113
+ const box = probe.getBoundingClientRect();
114
+ cellW = box.width || cellW;
115
+ cellH = box.height || cellH;
116
+ noteH = note.getBoundingClientRect().height || noteH;
117
+ probe.remove();
118
+ note.remove();
119
+ };
120
+ const columns = () => Math.max(1, Math.floor(body.clientWidth / cellW));
121
+
122
+ // 头部:返回、当前目录名。在根目录时没有返回键,标题是根目录名。
123
+ function paintHead() {
124
+ const name = model.cwd === '' ? (model.ready ? rootName(model.root.path) : '') : model.cwd.slice(model.cwd.lastIndexOf('/') + 1);
125
+ const key = `${model.cwd}\n${name}`;
126
+ head.hidden = !handlers.back || name === '';
127
+ if (key === headKey) return;
128
+ headKey = key;
129
+ head.replaceChildren(...(handlers.back && model.cwd !== '' ? [h('button', { class: 'icon', 'aria-label': '返回', title: '返回', onclick: handlers.back }, icon('back', 18))] : []),
130
+ h('span', { class: 'ghico', 'aria-hidden': 'true' }, icon('folder', 22)),
131
+ h('div', { class: 'grow' }, h('div', { class: 'gname-head truncate', title: model.cwd || name }, name)));
132
+ }
133
+
134
+ function paint() {
135
+ const top = body.scrollTop - (spacer.offsetTop || 0);
136
+ const first = Math.max(0, rowAt(layout, Math.max(0, top), cellH, noteH) - OVERSCAN);
137
+ const last = Math.min(layout.rows, rowsAbove(layout, top + body.clientHeight, cellH, noteH) + OVERSCAN);
138
+ const { from, to } = windowOf(layout, first, last);
139
+ win.style.transform = `translateY(${from === to ? 0 : rowTop(layout, rowOfCell(layout, from), cellH, noteH)}px)`;
140
+ win.style.gridTemplateColumns = `repeat(${layout.cols}, minmax(0, 1fr))`;
141
+ win.replaceChildren(...cells.slice(from, to).map((cell, i) => cellNode(cell, from + i)));
142
+ }
143
+
144
+ function cellNode(cell, index) {
145
+ const node = h('div', { class: 'gi' });
146
+ node.dataset.i = index;
147
+ if (cell.type !== 'entry') {
148
+ node.className = `gi gnote ${cell.type}`;
149
+ node.textContent = cell.text;
150
+ if (cell.retry) { node.classList.add('retry'); node.title = cell.text; } // 长原因在行里被截断,Mac 悬停看全
151
+ return node;
152
+ }
153
+ const dead = cell.kind === EntryKind.LINK || cell.kind === EntryKind.OTHER;
154
+ node.className = `gi cell ${cell.kind}${dead ? ' dead' : ''}${cell.path === model.selected ? ' sel' : ''}`;
155
+ if (!dead && draggable) node.draggable = true;
156
+ // 扩展名前给一个优先断点:package.json 折成 package / .json,不在字母中间断;没有点(或点在最前面)、太长时 overflow-wrap 才在任意位置断。
157
+ const dot = cell.name.lastIndexOf('.');
158
+ const glyph = h('span', { class: 'gico' }, icon(iconFor(cell), 32)), name = h('span', { class: 'gname' }, ...(dot > 0 ? [cell.name.slice(0, dot), h('wbr'), cell.name.slice(dot)] : [cell.name]));
159
+ const info = TITLES[cell.kind] ? '' : infoText(cell);
160
+ node.title = TITLES[cell.kind] ? `${cell.path}\n${TITLES[cell.kind]}` : info ? `${cell.path}\n${info}` : cell.path;
161
+ node.append(glyph, name);
162
+ return node;
163
+ }
164
+
165
+ // 按现在的单元格和列数重新生成布局映射。列数变了(拖窄、旋转):保持第一个可见的单元格还在顶部,不保持像素。
166
+ function rebuild() {
167
+ const cols = columns(), top = Math.max(0, body.scrollTop - (spacer.offsetTop || 0));
168
+ const anchor = cols !== layout.cols && layout.rows && top > 0 ? firstOfRow(layout, Math.min(layout.rows - 1, rowAt(layout, top, cellH, noteH))) : null;
169
+ layout = layoutOf(cells, cols);
170
+ spacer.style.height = `${rowTop(layout, layout.rows, cellH, noteH)}px`;
171
+ if (anchor !== null && anchor < cells.length) body.scrollTop = (spacer.offsetTop || 0) + rowTop(layout, rowOfCell(layout, anchor), cellH, noteH);
172
+ }
173
+ function relayout() {
174
+ if (columns() !== layout.cols) rebuild();
175
+ paint();
176
+ }
177
+
178
+ const gestures = mountGestures(el, {
179
+ hit: event => cells[event.target.closest?.('.gi')?.dataset.i],
180
+ pressable: cell => cell.type === 'entry',
181
+ activate: cell => {
182
+ if (cell.type === 'more') return handlers.more(cell.path);
183
+ if (cell.type === 'status') return cell.retry ? handlers.retry(cell.path) : undefined;
184
+ if (cell.kind === EntryKind.DIR) handlers.enter(cell.path);
185
+ else if (cell.kind === EntryKind.FILE) handlers.open(cell.path);
186
+ },
187
+ menu: (event, cell) => handlers.menu(event, cell),
188
+ dragText: cell => cell.path,
189
+ longPress,
190
+ scroller: body,
191
+ });
192
+ body.addEventListener('scroll', paint, { passive: true });
193
+ new ResizeObserver(relayout).observe(body);
194
+
195
+ return {
196
+ // 隐藏过的网格显示后宽度变了:重量单元格,再算列数。
197
+ render() {
198
+ if (body.clientWidth !== measuredWidth) { measuredWidth = body.clientWidth; measure(); }
199
+ cells = visibleCells(model);
200
+ rebuild();
201
+ paintHead();
202
+ paint();
203
+ },
204
+ remeasure() { measuredWidth = body.clientWidth; measure(); this.render(); },
205
+ scroll: () => body.scrollTop,
206
+ scrollTo(top) { body.scrollTop = top; paint(); }, // 浏览器的滚动事件随后还会画一次;这里先画,位置才马上对
207
+ onScroll(fn) { body.addEventListener('scroll', fn, { passive: true }); },
208
+ get layout() { return layout; },
209
+ // 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。
210
+ reset() { gestures.reset(); },
211
+ dispose() { gestures.dispose(); },
212
+ };
213
+ }
package/view/index.html CHANGED
@@ -10,11 +10,13 @@
10
10
  <div id="bar" class="bar" hidden></div>
11
11
  <main id="stage">
12
12
  <div id="tree" class="pane tree" role="tree"></div>
13
+ <div id="grid" class="pane grid"></div>
13
14
  <div id="preview" class="pane preview"></div>
14
15
  <div id="notice" class="pane empty secondary"></div>
15
16
  <div id="info" class="pane preview info"></div>
16
17
  </main>
17
18
  <div id="menu" class="menu" role="menu" hidden></div>
19
+ <div id="submenu" class="menu" role="menu" hidden></div>
18
20
  <div id="hint" class="hint" role="status" hidden></div>
19
21
  <script type="module" src="app.mjs"></script>
20
22
  </body>
package/view/menu.mjs CHANGED
@@ -1,24 +1,32 @@
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
31
  if (heading !== undefined) return Object.assign(document.createElement('p'), { className: 'menu-head secondary caption', textContent: heading });
24
32
  const button = document.createElement('button'), name = document.createElement('span');
@@ -26,46 +34,157 @@ export function mountMenu(el) {
26
34
  if (checkable) {
27
35
  const mark = document.createElement('span');
28
36
  mark.className = 'check';
29
- if (checked) mark.append(icon('check', 16));
37
+ if (checked) mark.append(icon('check', 14));
30
38
  button.append(mark);
31
39
  }
32
40
  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();
41
+ if (submenu) {
42
+ const arrow = document.createElement('span');
43
+ arrow.className = 'sub-arrow';
44
+ arrow.append(icon('chevron', 14));
45
+ button.append(arrow);
46
+ button.setAttribute('role', 'menuitem');
47
+ button.setAttribute('aria-haspopup', 'menu');
48
+ button.setAttribute('aria-expanded', 'false');
49
+ // 进下一层不是叶子项:不关菜单,也不执行什么。
50
+ button.addEventListener('click', () => { if (alive()) show(button, item, true); });
51
+ } else {
52
+ button.setAttribute('role', checked === undefined ? 'menuitem' : radio ? 'menuitemradio' : 'menuitemcheckbox');
53
+ if (checked !== undefined) button.setAttribute('aria-checked', String(checked));
54
+ button.addEventListener('click', () => {
55
+ if (!alive()) return; // 菜单已经关了(换成了别的、退回了上一层):留在手里的按钮不再响应
56
+ hide();
57
+ run();
58
+ });
59
+ }
60
+ if (hover) button.addEventListener('pointerenter', event => {
61
+ if (!alive() || event.pointerType === 'touch') return;
62
+ if (submenu) show(button, item, false); else later();
39
63
  });
40
64
  return button;
41
- }));
42
- el.hidden = false;
65
+ });
66
+ }
67
+
68
+ // 根层:路径标题、信息行,和项。
69
+ function paintRoot() {
70
+ const { title, detail, items } = spec, mine = current, mineLayer = ++layer;
71
+ const head = [];
72
+ if (title !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-path secondary', textContent: title }));
73
+ if (detail !== undefined) head.push(Object.assign(document.createElement('p'), { className: 'menu-info secondary caption', textContent: detail }));
74
+ el.replaceChildren(...head, ...build(items, () => current === mine && layer === mineLayer, flyout && sub !== null));
43
75
  el.scrollTop = 0;
76
+ }
77
+
78
+ // 贴在锚点下面、右对齐(锚点是按钮元素或同样有 getBoundingClientRect 的假锚点),或放在点上;每次换层内容宽度变了都要重来。
79
+ function place() {
44
80
  const box = anchor.getBoundingClientRect?.();
45
81
  const x = box ? box.right - el.offsetWidth : anchor.clientX, y = box ? box.bottom + 4 : anchor.clientY;
46
82
  el.style.left = `max(var(--safe-left), min(${x}px, calc(100vw - var(--safe-right) - ${el.offsetWidth + 4}px)))`;
47
83
  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
84
  }
50
85
 
86
+ // anchor:按钮元素或同样有 getBoundingClientRect 的假锚点(原生按钮:只代表根层,子菜单贴的是真实的项)或 { clientX, clientY } 的点。
87
+ // title 写在菜单顶上:iPhone 没有 title 悬停,长文件名在行里被截断,这里看全;detail 是它下面的一行小字。
88
+ function open(at, content) {
89
+ hide();
90
+ current = {};
91
+ spec = content;
92
+ anchor = at;
93
+ paintRoot();
94
+ el.hidden = false;
95
+ place();
96
+ if (at.getBoundingClientRect) { opener = at; opener.setAttribute?.('aria-expanded', 'true'); }
97
+ }
98
+
99
+ // 二级菜单:click 是点击(键盘激活也是);鼠标移上去只在放得下时弹出,放不下什么都不做,免得内容在鼠标底下突然换掉。
100
+ function show(button, item, click) {
101
+ keep();
102
+ if (flyout && sub !== null) {
103
+ if (flyButton === button) return; // 已经开着
104
+ collapse();
105
+ const mine = current, mineFly = ++fly;
106
+ const nodes = build(item.submenu.items, () => current === mine && fly === mineFly, false);
107
+ sub.replaceChildren(...nodes);
108
+ sub.hidden = false;
109
+ sub.style.visibility = 'hidden'; // 先量尺寸再决定放不放得下,量的时候别让人看到
110
+ sub.scrollTop = 0;
111
+ const { offsetWidth, offsetHeight } = sub, root = el.getBoundingClientRect(), at = button.getBoundingClientRect();
112
+ const x = root.left - offsetWidth - GAP;
113
+ if (x >= safeLeft()) {
114
+ sub.style.left = `${x}px`;
115
+ sub.style.top = `max(var(--safe-top), min(${at.top - 5}px, calc(100vh - var(--safe-bottom) - ${offsetHeight + 4}px)))`; // 第一项和「显示」对齐:减去面板的边框和内边距
116
+ sub.style.visibility = '';
117
+ flyButton = button;
118
+ button.setAttribute('aria-expanded', 'true');
119
+ if (click) nodes.find(node => node.tagName === 'BUTTON')?.focus?.(); // 键盘激活:焦点进侧面板
120
+ return;
121
+ }
122
+ collapse(); // 放不下:和 iPhone 一样切到下一层
123
+ }
124
+ if (click) enter(item);
125
+ }
126
+
127
+ // 在 el 里切到下一层:顶上一行返回;点返回回到根层,下一层的按钮此后不再响应。
128
+ function enter(item) {
129
+ const mine = current, mineLayer = ++layer, alive = () => current === mine && layer === mineLayer;
130
+ const back = document.createElement('button'), mark = document.createElement('span'), name = document.createElement('span');
131
+ mark.className = 'check back';
132
+ mark.append(icon('back', 14));
133
+ name.textContent = '返回';
134
+ back.className = 'menu-back';
135
+ back.append(mark, name);
136
+ back.setAttribute('role', 'menuitem');
137
+ back.addEventListener('click', () => {
138
+ if (!alive()) return;
139
+ paintRoot();
140
+ place();
141
+ });
142
+ el.replaceChildren(back, Object.assign(document.createElement('hr'), { className: 'menu-sep' }), ...build(item.submenu.items, alive, false));
143
+ el.scrollTop = 0;
144
+ place();
145
+ }
146
+
147
+ // 鼠标回到「显示」或侧面板:取消正在等的收起。
148
+ function keep() { clearTimeout(closeTimer); closeTimer = null; }
149
+ // 鼠标移到别的项:等一会儿再收起侧面板。
150
+ function later() {
151
+ if (flyButton === null || closeTimer !== null) return;
152
+ const mine = current;
153
+ closeTimer = setTimeout(() => { closeTimer = null; if (current === mine) collapse(); }, CLOSE_MS);
154
+ }
155
+ function collapse() {
156
+ keep();
157
+ fly++; // 侧面板里的旧按钮不再响应
158
+ if (sub) sub.hidden = true;
159
+ flyButton?.setAttribute('aria-expanded', 'false');
160
+ flyButton = null;
161
+ }
162
+ // 安全区的左边:body 的左内边距就是它(style.css),算出来的是像素。读不到按 0。
163
+ const safeLeft = () => { const px = parseFloat(globalThis.getComputedStyle?.(document.body)?.paddingLeft); return Number.isFinite(px) ? px : 0; };
164
+
51
165
  function hide() {
52
166
  current = null;
167
+ layer++;
168
+ collapse();
53
169
  el.hidden = true;
54
170
  opener?.setAttribute?.('aria-expanded', 'false');
55
171
  opener = null;
56
172
  }
57
173
 
58
- // 菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
174
+ // 两个面板都算菜单里面。菜单开着时点菜单外:只关菜单,紧接着的那次点击不交给页面。
175
+ const inside = target => el.contains(target) || (sub !== null && sub.contains(target));
59
176
  let dismissed = false;
60
177
  document.addEventListener('pointerdown', event => {
61
- dismissed = !el.hidden && !el.contains(event.target);
62
- if (!el.contains(event.target)) hide();
178
+ dismissed = !el.hidden && !inside(event.target);
179
+ if (!inside(event.target)) hide();
63
180
  }, true);
64
181
  document.addEventListener('click', event => {
65
182
  if (dismissed) { dismissed = false; event.stopPropagation(); }
66
183
  }, true);
67
184
  document.addEventListener('keydown', event => { if (event.key === 'Escape') hide(); });
68
185
  window.addEventListener('blur', hide);
186
+ window.addEventListener('resize', hide); // 旋转、拖窄侧栏:位置对不上了
187
+ sub?.addEventListener('pointerenter', keep);
69
188
 
70
189
  return {
71
190
  open, hide,