@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.
@@ -0,0 +1,71 @@
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):点击(iPhone);Mac 给了 select 就按 Finder 的规则:单击条目只 select(item),单击空白 select(null),双击条目才 activate(item);
9
+ // 说明行、「再显示」这类不能选的项单击就 activate,direct(event, item) 为真的点击(展开箭头)也直接 activate、不选中,双击它不再重复激活。
10
+ // 双击靠浏览器的 dblclick,要求派发时目标节点还在容器里,所以 select 不能重画。menu(event, item):右键,长按到点时收到 { clientX, clientY };dragText(item):拖动时带的文字(元素是否可拖由调用方设 draggable);
11
+ // longPress:触屏上按住一项打开 menu,不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
12
+ // 返回 { reset, dispose }:reset 在切会话时调用,长按的等待和吞点击的标记都属于上一个会话;dispose 摘掉全部监听。
13
+ export function mountGestures(el, { hit, pressable, activate, select, direct = () => false, menu, dragText, longPress = false, scroller = el }) {
14
+ const listeners = [];
15
+ const on = (target, type, fn, options) => { target.addEventListener(type, fn, options); listeners.push([target, type, fn]); };
16
+
17
+ // 长按:按下只记一个等待;移动超限、抬起、取消、滚动、第二根手指都作废。
18
+ // 触发后吞掉紧接着的那次点击;没有点击跟来时,下一次按下清掉,不会误吞后面真正的点击。
19
+ let hold = null, swallow = false;
20
+ const cancelHold = () => { if (hold) { clearTimeout(hold.timer); hold = null; } };
21
+ if (longPress) {
22
+ on(el, 'pointerdown', event => {
23
+ cancelHold();
24
+ swallow = false;
25
+ const item = hit(event);
26
+ if (event.isPrimary === false || !item || !pressable(item)) return;
27
+ const { clientX: x, clientY: y, pointerId: id } = event;
28
+ hold = { id, x, y, timer: setTimeout(() => {
29
+ hold = null;
30
+ swallow = true;
31
+ menu({ clientX: x, clientY: y }, item);
32
+ }, HOLD_MS) };
33
+ });
34
+ on(el, 'pointermove', event => {
35
+ if (hold && event.pointerId === hold.id && Math.hypot(event.clientX - hold.x, event.clientY - hold.y) > HOLD_SLOP) cancelHold();
36
+ });
37
+ for (const type of ['pointerup', 'pointercancel']) on(el, type, cancelHold);
38
+ on(scroller, 'scroll', cancelHold, { passive: true });
39
+ }
40
+
41
+ on(el, 'click', event => {
42
+ if (swallow) { swallow = false; return; }
43
+ const item = hit(event);
44
+ if (!select) { if (item) activate(item); return; }
45
+ if (!item) select(null);
46
+ else if (!pressable(item) || direct(event, item)) activate(item);
47
+ else select(item);
48
+ });
49
+ if (select) on(el, 'dblclick', event => {
50
+ const item = hit(event);
51
+ if (item && pressable(item) && !direct(event, item)) activate(item);
52
+ });
53
+ on(el, 'contextmenu', event => {
54
+ const item = hit(event);
55
+ if (item && pressable(item)) { event.preventDefault(); menu(event, item); }
56
+ });
57
+ on(el, 'dragstart', event => {
58
+ const item = hit(event);
59
+ if (!item || !pressable(item)) return event.preventDefault();
60
+ event.dataTransfer.setData('text/plain', dragText(item)); // 相对路径
61
+ event.dataTransfer.effectAllowed = 'copy';
62
+ });
63
+
64
+ return {
65
+ reset() { cancelHold(); swallow = false; },
66
+ dispose() {
67
+ cancelHold();
68
+ for (const [target, type, fn] of listeners.splice(0)) target.removeEventListener(type, fn);
69
+ },
70
+ };
71
+ }
package/view/grid.mjs ADDED
@@ -0,0 +1,268 @@
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
+ // 键盘在图标视图里的一步(纯逻辑):action 是 up、down、left、right。返回 { select: 序号 } 或 null。
98
+ // 上下走同一列:跳过说明项独占的行,目标行不满、没有这一列时选那一行的最后一个;左右在条目之间走(行尾接下一行的第一个)。
99
+ // 选中的条目不在 cells 里按没有选中算:↓ 选第一个条目,↑ 选最后一个。
100
+ export function stepCells(cells, layout, selected, action) {
101
+ const at = selected === null ? -1 : cells.findIndex(cell => cell.type === 'entry' && cell.path === selected);
102
+ const first = cells.findIndex(cell => cell.type === 'entry');
103
+ if (first < 0) return null;
104
+ if (at < 0) {
105
+ if (action === 'down') return { select: first };
106
+ if (action === 'up') return { select: cells.map(cell => cell.type).lastIndexOf('entry') };
107
+ return null;
108
+ }
109
+ if (action === 'left' || action === 'right') {
110
+ const next = at + (action === 'right' ? 1 : -1);
111
+ return cells[next]?.type === 'entry' ? { select: next } : null;
112
+ }
113
+ const row = rowOfCell(layout, at), column = at - firstOfRow(layout, row), step = action === 'down' ? 1 : -1;
114
+ for (let r = row + step; r >= 0 && r < layout.rows; r += step) {
115
+ const span = spanAt(layout, r);
116
+ if (span.note) continue;
117
+ return { select: Math.min(firstOfRow(layout, r) + column, span.from + span.count - 1) };
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // handlers: { open(path), enter(path), more(path), retry(path), menu(event, cell), back?, select?(path | null) }
123
+ // select 是 Mac 单击选中,不给就是 iPhone 的轻点打开。
124
+ // back 给了就在头部最左边放「返回」(Mac,和没有原生返回的环境);不给就没有头部,iPhone 用原生返回,标题在工具条上。
125
+ // draggable、longPress 同 mountTree。
126
+ // keyboard:滚动容器(.gbody)可以获得焦点,键盘才接得上(Mac)。
127
+ export function mountGrid(el, model, handlers, { draggable = true, longPress = false, keyboard = false } = {}) {
128
+ const head = h('div', { class: 'ghead' }), body = h('div', { class: 'gbody' }), spacer = h('div', { class: 'gspacer' }), win = h('div', { class: 'gwin' });
129
+ head.hidden = true;
130
+ if (keyboard) body.tabIndex = 0;
131
+ spacer.append(win);
132
+ body.append(spacer);
133
+ el.replaceChildren(head, body);
134
+ let cells = [], layout = layoutOf([], 1), cellW = 72, cellH = 76, noteH = 32, measuredWidth = -1, headKey = null;
135
+
136
+ // 探针放在 win 里:量到的是单元格和说明行在真实结构里的尺寸,两种行高不同。
137
+ const measure = () => {
138
+ const probe = h('div', { class: 'gi cell' }), note = h('div', { class: 'gi gnote' });
139
+ probe.style.visibility = note.style.visibility = 'hidden';
140
+ win.append(probe, note);
141
+ const box = probe.getBoundingClientRect();
142
+ cellW = box.width || cellW;
143
+ cellH = box.height || cellH;
144
+ noteH = note.getBoundingClientRect().height || noteH;
145
+ probe.remove();
146
+ note.remove();
147
+ };
148
+ const columns = () => Math.max(1, Math.floor(body.clientWidth / cellW));
149
+
150
+ // 头部:返回、当前目录名。在根目录时没有返回键,标题是根目录名。
151
+ function paintHead() {
152
+ const name = model.cwd === '' ? (model.ready ? rootName(model.root.path) : '') : model.cwd.slice(model.cwd.lastIndexOf('/') + 1);
153
+ const key = `${model.cwd}\n${name}`;
154
+ head.hidden = !handlers.back || name === '';
155
+ if (key === headKey) return;
156
+ headKey = key;
157
+ head.replaceChildren(...(handlers.back && model.cwd !== '' ? [h('button', { class: 'icon', 'aria-label': '返回', title: '返回', onclick: handlers.back }, icon('back', 18))] : []),
158
+ h('span', { class: 'ghico', 'aria-hidden': 'true' }, icon('folder', 22)),
159
+ h('div', { class: 'grow' }, h('div', { class: 'gname-head truncate', title: model.cwd || name }, name)));
160
+ }
161
+
162
+ function paint() {
163
+ const top = body.scrollTop - (spacer.offsetTop || 0);
164
+ const first = Math.max(0, rowAt(layout, Math.max(0, top), cellH, noteH) - OVERSCAN);
165
+ const last = Math.min(layout.rows, rowsAbove(layout, top + body.clientHeight, cellH, noteH) + OVERSCAN);
166
+ const { from, to } = windowOf(layout, first, last);
167
+ win.style.transform = `translateY(${from === to ? 0 : rowTop(layout, rowOfCell(layout, from), cellH, noteH)}px)`;
168
+ win.style.gridTemplateColumns = `repeat(${layout.cols}, minmax(0, 1fr))`;
169
+ win.replaceChildren(...cells.slice(from, to).map((cell, i) => cellNode(cell, from + i)));
170
+ }
171
+
172
+ function cellNode(cell, index) {
173
+ const node = h('div', { class: 'gi' });
174
+ node.dataset.i = index;
175
+ if (cell.type !== 'entry') {
176
+ node.className = `gi gnote ${cell.type}`;
177
+ node.textContent = cell.text;
178
+ if (cell.retry) { node.classList.add('retry'); node.title = cell.text; } // 长原因在行里被截断,Mac 悬停看全
179
+ return node;
180
+ }
181
+ const dead = cell.kind === EntryKind.LINK || cell.kind === EntryKind.OTHER;
182
+ node.className = `gi cell ${cell.kind}${dead ? ' dead' : ''}${cell.path === model.selected ? ' sel' : ''}`;
183
+ if (!dead && draggable) node.draggable = true;
184
+ // 扩展名前给一个优先断点:package.json 折成 package / .json,不在字母中间断;没有点(或点在最前面)、太长时 overflow-wrap 才在任意位置断。
185
+ const dot = cell.name.lastIndexOf('.');
186
+ 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]));
187
+ const info = TITLES[cell.kind] ? '' : infoText(cell);
188
+ node.title = TITLES[cell.kind] ? `${cell.path}\n${TITLES[cell.kind]}` : info ? `${cell.path}\n${info}` : cell.path;
189
+ node.append(glyph, name);
190
+ return node;
191
+ }
192
+
193
+ // 按现在的单元格和列数重新生成布局映射。列数变了(拖窄、旋转):保持第一个可见的单元格还在顶部,不保持像素。
194
+ function rebuild() {
195
+ const cols = columns(), top = Math.max(0, body.scrollTop - (spacer.offsetTop || 0));
196
+ const anchor = cols !== layout.cols && layout.rows && top > 0 ? firstOfRow(layout, Math.min(layout.rows - 1, rowAt(layout, top, cellH, noteH))) : null;
197
+ layout = layoutOf(cells, cols);
198
+ spacer.style.height = `${rowTop(layout, layout.rows, cellH, noteH)}px`;
199
+ if (anchor !== null && anchor < cells.length) body.scrollTop = (spacer.offsetTop || 0) + rowTop(layout, rowOfCell(layout, anchor), cellH, noteH);
200
+ }
201
+ function relayout() {
202
+ if (columns() !== layout.cols) rebuild();
203
+ paint();
204
+ }
205
+
206
+ // 点击(iPhone)、双击、⌘↓ 和右键「打开」共用这一份。
207
+ const activate = cell => {
208
+ if (cell.type === 'more') return handlers.more(cell.path);
209
+ if (cell.type === 'status') return cell.retry ? handlers.retry(cell.path) : undefined;
210
+ if (cell.kind === EntryKind.DIR) handlers.enter(cell.path);
211
+ else if (cell.kind === EntryKind.FILE) handlers.open(cell.path);
212
+ };
213
+ // 事件挂在 body 上:头部的返回键点击不算「点空白」。
214
+ const gestures = mountGestures(body, {
215
+ hit: event => cells[event.target.closest?.('.gi')?.dataset.i],
216
+ pressable: cell => cell.type === 'entry',
217
+ activate,
218
+ select: handlers.select && (cell => handlers.select(cell ? cell.path : null)),
219
+ menu: (event, cell) => handlers.menu(event, cell),
220
+ dragText: cell => cell.path,
221
+ longPress,
222
+ scroller: body,
223
+ });
224
+ // 选中变了只在现有节点上切 .sel,不重建:双击的 dblclick 要落在还在容器里的节点上。
225
+ const mark = () => { for (const node of win.children) node.classList.toggle('sel', cells[node.dataset.i]?.type === 'entry' && cells[node.dataset.i].path === model.selected); };
226
+ // 滚到这个单元格能看见,只滚最少的距离。
227
+ const reveal = index => {
228
+ const top = (spacer.offsetTop || 0) + rowTop(layout, rowOfCell(layout, index), cellH, noteH);
229
+ if (top < body.scrollTop) body.scrollTop = top;
230
+ else if (top + cellH > body.scrollTop + body.clientHeight) body.scrollTop = top + cellH - body.clientHeight;
231
+ paint();
232
+ };
233
+ body.addEventListener('scroll', paint, { passive: true });
234
+ new ResizeObserver(relayout).observe(body);
235
+
236
+ return {
237
+ // 隐藏过的网格显示后宽度变了:重量单元格,再算列数。
238
+ render() {
239
+ if (body.clientWidth !== measuredWidth) { measuredWidth = body.clientWidth; measure(); }
240
+ cells = visibleCells(model);
241
+ rebuild();
242
+ paintHead();
243
+ paint();
244
+ },
245
+ remeasure() { measuredWidth = body.clientWidth; measure(); this.render(); },
246
+ scroll: () => body.scrollTop,
247
+ scrollTo(top) { body.scrollTop = top; paint(); }, // 浏览器的滚动事件随后还会画一次;这里先画,位置才马上对
248
+ onScroll(fn) { body.addEventListener('scroll', fn, { passive: true }); },
249
+ get layout() { return layout; },
250
+ select: mark,
251
+ activate,
252
+ focus() { body.focus(); },
253
+ onKey(fn) { body.addEventListener('keydown', fn); },
254
+ key(action) {
255
+ const step = stepCells(cells, layout, model.selected, action);
256
+ if (!step) return;
257
+ handlers.select(cells[step.select].path);
258
+ reveal(step.select);
259
+ },
260
+ openSelected() {
261
+ const cell = model.selected === null ? undefined : cells.find(item => item.type === 'entry' && item.path === model.selected);
262
+ if (cell) activate(cell);
263
+ },
264
+ // 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。
265
+ reset() { gestures.reset(); },
266
+ dispose() { gestures.dispose(); },
267
+ };
268
+ }
@@ -0,0 +1,93 @@
1
+ // 语法高亮:调用 highlight.js,把它的输出解析成节点。文件内容不经过 HTML 解析,所以 CR、NUL 和未配对的代理项都原样保留。
2
+ // highlight.js 的输出只有 <span class="…">、</span> 和五种转义;格式之外的任何内容都算失败,调用方显示纯文本。
3
+ import hljs from './vendor/highlight/highlight.min.mjs';
4
+ import dart from './vendor/highlight/languages/dart.min.mjs';
5
+ import dockerfile from './vendor/highlight/languages/dockerfile.min.mjs';
6
+ import scala from './vendor/highlight/languages/scala.min.mjs';
7
+ import { h } from './dom.mjs';
8
+
9
+ hljs.registerLanguage('dart', dart);
10
+ hljs.registerLanguage('dockerfile', dockerfile);
11
+ hljs.registerLanguage('scala', scala);
12
+
13
+ // 超过这个字节数不高亮(实测依据和为什么是 128 KiB 见 docs/design/phase-3.md 第 15.4 节)。
14
+ export const HIGHLIGHT_LIMIT = 128 * 1024;
15
+ // 有一行超过这个字符数(UTF-16 长度)也不高亮:压成一行的文件上色慢,也帮不上阅读(第 15.4 节)。
16
+ export const LINE_LIMIT = 5000;
17
+
18
+ // 有没有一行超过 LINE_LIMIT:按 \n 分行(\r 留在行里),只扫一遍,不建数组。
19
+ export function hasLongLine(text) {
20
+ for (let start = 0; start < text.length;) {
21
+ const end = text.indexOf('\n', start);
22
+ if ((end < 0 ? text.length : end) - start > LINE_LIMIT) return true;
23
+ if (end < 0) break;
24
+ start = end + 1;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ const ENTITIES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#x27;': "'" };
30
+ const ENTITY = /&(?:amp|lt|gt|quot|#x27);/y;
31
+ const OPEN = /<span class="([A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*)">/y;
32
+ const CLOSE = '</span>';
33
+ const NEXT = /[<&]/g;
34
+ const CHUNK = 2000; // append(...nodes) 的参数个数有上限,节点多的时候分批
35
+
36
+ export function appendAll(parent, nodes) {
37
+ for (let at = 0; at < nodes.length; at += CHUNK) parent.append(...nodes.slice(at, at + CHUNK));
38
+ }
39
+
40
+ // 解析 html,返回顶层节点(字符串和 span 元素);格式不对返回 null。expected:原文的长度,文字总长不符也算格式不对。
41
+ export function parse(html, expected) {
42
+ const stack = [{ nodes: [], cls: null }];
43
+ let at = 0, length = 0;
44
+ const push = text => {
45
+ const { nodes } = stack.at(-1);
46
+ length += text.length;
47
+ if (typeof nodes.at(-1) === 'string') nodes[nodes.length - 1] += text; else nodes.push(text);
48
+ };
49
+ while (at < html.length) {
50
+ NEXT.lastIndex = at;
51
+ const found = NEXT.exec(html);
52
+ const next = found ? found.index : html.length;
53
+ if (next > at) push(html.slice(at, next));
54
+ if (!found) break;
55
+ at = next;
56
+ if (html[at] === '&') {
57
+ ENTITY.lastIndex = at;
58
+ const entity = ENTITY.exec(html);
59
+ if (!entity) return null;
60
+ push(ENTITIES[entity[0]]);
61
+ at += entity[0].length;
62
+ } else if (html.startsWith(CLOSE, at)) {
63
+ if (stack.length === 1) return null;
64
+ const { nodes, cls } = stack.pop();
65
+ const span = h('span', { class: cls });
66
+ appendAll(span, nodes);
67
+ stack.at(-1).nodes.push(span);
68
+ at += CLOSE.length;
69
+ } else {
70
+ OPEN.lastIndex = at;
71
+ const open = OPEN.exec(html);
72
+ if (!open) return null;
73
+ stack.push({ nodes: [], cls: open[1] });
74
+ at += open[0].length;
75
+ }
76
+ }
77
+ return stack.length === 1 && length === expected ? stack[0].nodes : null;
78
+ }
79
+
80
+ // text 按 language 上色,返回节点数组;没能高亮(库抛错、库自己吞掉了内部错误、输出格式不对)返回 null。
81
+ // 输出里没有 span 不算失败(空文件、只有普通标识符的文件)。
82
+ export function highlight(text, language) {
83
+ try {
84
+ const result = hljs.highlight(text, { language, ignoreIllegals: true });
85
+ if (result.errorRaised) return null;
86
+ return parse(result.value, text.length);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ // 给测试:打包的库本身。
93
+ export { hljs };
package/view/icons.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // 图标:页面里自己画的 SVG,形状近似 SF Symbol,不打包 Apple 的符号,也不用任何第三方素材。颜色都是 currentColor,由 CSS 定:
2
2
  // 种类图标带 tone-* 类(颜色见 style.css 的 --tone-*),没有色调的(工具条、菜单的图标)跟随所在位置的文字色。
3
+ import { invert, lookupByName } from './lookup.mjs';
3
4
  import { EntryKind } from './protocol.mjs';
4
5
 
5
6
  const SVG_NS = 'http://www.w3.org/2000/svg';
@@ -132,7 +133,6 @@ const EXTENSIONS = {
132
133
  database: ['db', 'sqlite', 'sqlite3'],
133
134
  font: ['ttf', 'otf', 'woff', 'woff2'],
134
135
  };
135
- const invert = table => new Map(Object.entries(table).flatMap(([id, keys]) => keys.map(key => [key, id])));
136
136
  const BY_NAME = invert(NAMES), BY_EXT = invert(EXTENSIONS);
137
137
 
138
138
  // 一个条目的种类:{ glyph, tone, label }。目录、链接、其他按种类;文件先按整个文件名,再按扩展名(点开头的名字没有扩展名)。
@@ -141,8 +141,7 @@ export function kindOf({ kind, name }) {
141
141
  if (kind === EntryKind.DIR) return KINDS.dir;
142
142
  if (kind === EntryKind.LINK) return KINDS.link;
143
143
  if (kind === EntryKind.OTHER) return KINDS.other;
144
- const lower = String(name).toLowerCase(), dot = lower.lastIndexOf('.');
145
- return KINDS[BY_NAME.get(lower) ?? (lower.startsWith('.env.') ? 'env' : undefined) ?? (dot > 0 ? BY_EXT.get(lower.slice(dot + 1)) : undefined) ?? 'file'];
144
+ return KINDS[lookupByName(name, BY_NAME, BY_EXT, lower => (lower.startsWith('.env.') ? 'env' : undefined)) ?? 'file'];
146
145
  }
147
146
 
148
147
  // 图标名:种类表里的 glyph。
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="preview" class="pane preview"></div>
13
+ <div id="grid" class="pane grid"></div>
14
+ <div id="preview" class="pane preview" tabindex="-1"></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/keys.mjs ADDED
@@ -0,0 +1,15 @@
1
+ // Mac 的键盘:只认一组最小的键,不匹配的(含其他修饰键组合)返回 null,页面不拦。设计见 docs/design/phase-3.md 第 15.10 节。
2
+ const ARROWS = { ArrowUp: 'up', ArrowDown: 'down', ArrowLeft: 'left', ArrowRight: 'right' };
3
+ const bare = event => !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
4
+ const command = event => event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
5
+
6
+ // 浏览区:↑ ↓ ← → 移动,⌘↓ 打开(同双击),⌘↑ 回上一层。输入法组字中的按键不管。
7
+ export function browseAction(event) {
8
+ if (event.isComposing) return null;
9
+ if (bare(event)) return ARROWS[event.key] ?? null;
10
+ if (command(event)) return event.key === 'ArrowDown' ? 'open' : event.key === 'ArrowUp' ? 'parent' : null;
11
+ return null;
12
+ }
13
+
14
+ // 侧栏预览:只有 ⌘↑(返回)。
15
+ export const previewAction = event => (!event.isComposing && command(event) && event.key === 'ArrowUp' ? 'back' : null);
@@ -0,0 +1,49 @@
1
+ // 认语言:文件名到 highlight.js 的语言 id,只按文件名和扩展名,不猜内容;不在表里的是 null,显示纯文本。
2
+ import { invert, lookupByName } from './lookup.mjs';
3
+
4
+ const NAMES = {
5
+ ruby: ['gemfile', 'rakefile', 'podfile'],
6
+ makefile: ['makefile', 'gnumakefile'],
7
+ dockerfile: ['dockerfile', 'containerfile'],
8
+ };
9
+ const EXTENSIONS = {
10
+ javascript: ['js', 'mjs', 'cjs', 'jsx'],
11
+ typescript: ['ts', 'tsx', 'mts', 'cts'],
12
+ json: ['json', 'jsonc', 'json5'],
13
+ python: ['py', 'pyw', 'pyi'],
14
+ go: ['go'],
15
+ rust: ['rs'],
16
+ swift: ['swift'],
17
+ java: ['java'],
18
+ kotlin: ['kt', 'kts'],
19
+ c: ['c'],
20
+ cpp: ['h', 'cc', 'cpp', 'cxx', 'hpp', 'hh'], // .h 一律按 C++
21
+ objectivec: ['m', 'mm'], // .m 一律按 Objective-C
22
+ csharp: ['cs'],
23
+ php: ['php'],
24
+ ruby: ['rb'],
25
+ lua: ['lua'],
26
+ sql: ['sql'],
27
+ r: ['r'],
28
+ perl: ['pl', 'pm'],
29
+ dart: ['dart'],
30
+ scala: ['scala'],
31
+ xml: ['html', 'htm', 'xml', 'xhtml', 'plist', 'vue'],
32
+ css: ['css'],
33
+ scss: ['scss'],
34
+ less: ['less'],
35
+ yaml: ['yml', 'yaml'],
36
+ ini: ['toml', 'ini', 'cfg'],
37
+ markdown: ['md', 'markdown', 'mdx'],
38
+ bash: ['sh', 'bash', 'zsh'],
39
+ makefile: ['mk'],
40
+ dockerfile: ['dockerfile'],
41
+ diff: ['diff', 'patch'],
42
+ graphql: ['graphql', 'gql'],
43
+ };
44
+ const BY_NAME = invert(NAMES), BY_EXTENSION = invert(EXTENSIONS);
45
+
46
+ export const languageOf = name => lookupByName(name, BY_NAME, BY_EXTENSION) ?? null;
47
+
48
+ // 给测试:表里出现的所有语言 id。
49
+ export const LANGUAGE_IDS = [...new Set([...Object.keys(NAMES), ...Object.keys(EXTENSIONS)])];
@@ -0,0 +1,8 @@
1
+ // 按文件名查表:图标表和语言表各用一份数据、同一套查找。
2
+ // 整个文件名(小写)优先,再是 special(各表自己的规则,如图标的 .env.*),最后是扩展名(小写);扩展名取最后一个点之后,点在开头的名字没有扩展名。
3
+ export const invert = table => new Map(Object.entries(table).flatMap(([id, keys]) => keys.map(key => [key, id])));
4
+
5
+ export function lookupByName(name, byName, byExtension, special = () => undefined) {
6
+ const lower = String(name).toLowerCase(), dot = lower.lastIndexOf('.');
7
+ return byName.get(lower) ?? special(lower) ?? (dot > 0 ? byExtension.get(lower.slice(dot + 1)) : undefined);
8
+ }