@coda-console/resource-manager 0.4.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.
@@ -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
+ }
@@ -0,0 +1,62 @@
1
+ // 条目上的事件规则:Mac 右键和拖动、iPhone 长按、点击。目录树和图标视图共用,各自注入「点到哪一项」和激活动作。
2
+ // 长按:按住这么久、移动不超过这个距离才算。
3
+ export const HOLD_MS = 500;
4
+ export const HOLD_SLOP = 10;
5
+
6
+ // el:接事件的元素;scroller:滚动的元素(滚动事件不冒泡),缺省同 el。选项:
7
+ // hit(event) → 点到的那一项或 undefined;pressable(item):能不能弹菜单、拖动、长按(目录树的说明行、「再显示」不能);
8
+ // activate(item):点击;menu(event, item):右键,长按到点时收到 { clientX, clientY };dragText(item):拖动时带的文字(元素是否可拖由调用方设 draggable);
9
+ // longPress:触屏上按住一项打开 menu,不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
10
+ // 返回 { reset, dispose }:reset 在切会话时调用,长按的等待和吞点击的标记都属于上一个会话;dispose 摘掉全部监听。
11
+ export function mountGestures(el, { hit, pressable, activate, menu, dragText, longPress = false, scroller = el }) {
12
+ const listeners = [];
13
+ const on = (target, type, fn, options) => { target.addEventListener(type, fn, options); listeners.push([target, type, fn]); };
14
+
15
+ // 长按:按下只记一个等待;移动超限、抬起、取消、滚动、第二根手指都作废。
16
+ // 触发后吞掉紧接着的那次点击;没有点击跟来时,下一次按下清掉,不会误吞后面真正的点击。
17
+ let hold = null, swallow = false;
18
+ const cancelHold = () => { if (hold) { clearTimeout(hold.timer); hold = null; } };
19
+ if (longPress) {
20
+ on(el, 'pointerdown', event => {
21
+ cancelHold();
22
+ swallow = false;
23
+ const item = hit(event);
24
+ if (event.isPrimary === false || !item || !pressable(item)) return;
25
+ const { clientX: x, clientY: y, pointerId: id } = event;
26
+ hold = { id, x, y, timer: setTimeout(() => {
27
+ hold = null;
28
+ swallow = true;
29
+ menu({ clientX: x, clientY: y }, item);
30
+ }, HOLD_MS) };
31
+ });
32
+ on(el, 'pointermove', event => {
33
+ if (hold && event.pointerId === hold.id && Math.hypot(event.clientX - hold.x, event.clientY - hold.y) > HOLD_SLOP) cancelHold();
34
+ });
35
+ for (const type of ['pointerup', 'pointercancel']) on(el, type, cancelHold);
36
+ on(scroller, 'scroll', cancelHold, { passive: true });
37
+ }
38
+
39
+ on(el, 'click', event => {
40
+ if (swallow) { swallow = false; return; }
41
+ const item = hit(event);
42
+ if (item) activate(item);
43
+ });
44
+ on(el, 'contextmenu', event => {
45
+ const item = hit(event);
46
+ if (item && pressable(item)) { event.preventDefault(); menu(event, item); }
47
+ });
48
+ on(el, 'dragstart', event => {
49
+ const item = hit(event);
50
+ if (!item || !pressable(item)) return event.preventDefault();
51
+ event.dataTransfer.setData('text/plain', dragText(item)); // 相对路径
52
+ event.dataTransfer.effectAllowed = 'copy';
53
+ });
54
+
55
+ return {
56
+ reset() { cancelHold(); swallow = false; },
57
+ dispose() {
58
+ cancelHold();
59
+ for (const [target, type, fn] of listeners.splice(0)) target.removeEventListener(type, fn);
60
+ },
61
+ };
62
+ }
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/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
+ }