@coda-console/resource-manager 0.7.2 → 0.8.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/preview.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // 文件预览:只接收路径和读块的能力,不依赖树的状态。readFile 是纯逻辑;mountPreview 才碰 DOM。
2
2
  import { h } from './dom.mjs';
3
+ import { createFind } from './find.mjs';
3
4
  import { formatSize } from './format.mjs';
4
5
  import { HIGHLIGHT_LIMIT, appendAll, hasLongLine, highlight } from './highlight.mjs';
5
6
  import { icon, iconFor } from './icons.mjs';
@@ -58,19 +59,39 @@ export const lineCount = text => (text === '' ? 1 : text.split('\n').length - (t
58
59
  // back:给了就在头部最左边放「返回」(Mac 侧栏预览:原生工具栏项目只能在右侧);文件页和 iPhone 不传。
59
60
  // open(path, scroll) 带了要恢复的位置时,返回的 Promise 在「位置用上了」时变 true(正文到了、已设好位置;读取失败不算,位置留着等重试),
60
61
  // 在「位置作废」时变 false(预览关了、改看别的文件)。读取被刷新、重载或 changed 作废时位置不丢:接替它的那次读取接着带上,用上才算完。
62
+ // 文件内查找(第 18.6 节)是预览自己的一部分,接在预览已有的生命周期上:open 换了文件、reload、stop、close 关查找;refresh 保留;release 不碰。
63
+ // 页面只负责入口:canFind(有显示着的文本才有)、openFind()(⌘F、iPhone 的「查找」菜单项)。consumed(event):这个按键已经被菜单消费了(菜单开着时的 Esc)。
61
64
  // selectionMenu(event, { path, text, startLine, endLine }):给了就接管正文里选中文字的右键(只有 Mac 传);预览不知道菜单里是什么。
62
65
  // 选区为空、或裁到正文里之后为空时不接管,走系统默认。内容和行号在这里取好,交出去之后和选区无关。
63
- export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null }) {
66
+ export function mountPreview(el, { read, copy, actions = [], copyInHead = true, back = null, selectionMenu = null, consumed = () => false }) {
64
67
  const name = h('div', { class: 'pname truncate' }), meta = h('div', { class: 'pmeta caption secondary truncate' }, ' ');
65
68
  const fileIcon = h('span', { class: 'pico', 'aria-hidden': 'true' });
66
69
  // 图标按钮:可访问名称和 Mac 的悬停提示都是 label;没有图标的退回文字。
67
70
  const action = (label, glyph, run) => h('button', { class: glyph ? 'icon' : 'link', 'aria-label': label, title: label, onclick: run }, glyph ? icon(glyph, 18) : label);
68
71
  const copyPath = () => path !== null && copy(path);
69
72
  const retryButton = h('button', { class: 'link', onclick: () => load(true), hidden: true }, '重试');
70
- const body = h('div', { class: 'pbody' });
73
+ const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
74
+ let gutterEl = null;
75
+ const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
71
76
  const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
72
77
  el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), retryButton,
73
- ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), body);
78
+ ...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), find.el, body);
79
+ find.done.addEventListener('click', () => { find.close(); body.focus(); });
80
+ // 查找条的键盘:Esc 关(从查找条里关,焦点回正文;焦点在正文里,焦点留在正文);⌘G、⇧⌘G 下一个、上一个。输入法组字中的按键不管,菜单消费掉的 Esc 不再处理。
81
+ el.addEventListener('keydown', event => {
82
+ if (!find.isOpen || event.isComposing) return;
83
+ if (event.key === 'Escape' && consumed(event)) { event.preventDefault(); return; } // 菜单关掉的 Esc:查找输入框是 type=search,默认动作会清空它,要拦下
84
+ if (event.key === 'Escape') {
85
+ event.preventDefault();
86
+ const fromBar = find.el.contains(document.activeElement);
87
+ find.close();
88
+ if (fromBar) body.focus();
89
+ } else if (event.key?.toLowerCase() === 'g' && event.metaKey && !event.ctrlKey && !event.altKey) {
90
+ event.preventDefault();
91
+ if (event.shiftKey) find.prev(); else find.next();
92
+ }
93
+ });
94
+ let textShown = false, pendingFind = null, longLine = false; // 现在显示的是不是文本;show() 换好的正文,等滚动位置设好再交给查找
74
95
 
75
96
  let path = null, token = 0, shown = null, objectUrl = null; // shown:当前显示的 { size, mtimeMs }
76
97
  let opens = 0, stoppedAt = -1; // 打开次数和上一次停止时的次数:释放只在停止之后没有再打开过时才做(返回的退场还没结束又打开了)
@@ -93,6 +114,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
93
114
 
94
115
  function show(result) {
95
116
  revoke();
117
+ textShown = result.kind === ContentKind.TEXT;
118
+ pendingFind = null;
119
+ if (!textShown) find.close(); // 图片、二进制没有查找
96
120
  shown = { size: result.size, mtimeMs: result.mtimeMs };
97
121
  // 元信息:目录 · 行数 · 大小;根目录下的文件没有目录,非文本没有行数。修改时间放进 title。
98
122
  // 高亮:认得出语言才试;超过上限不试,库或解析出错就退回纯文本,都在元信息里注明。认不出语言的不加说明。
@@ -100,7 +124,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
100
124
  const lines = result.kind === ContentKind.TEXT ? `${lineCount(result.text)} 行` : '';
101
125
  const language = result.kind === ContentKind.TEXT ? languageOf(path.split('/').pop()) : null;
102
126
  // 先判大小,超过只写「不高亮」;没超再判行长。
103
- const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : hasLongLine(result.text) ? '行太长,不高亮' : '';
127
+ // 有长行:上色已经按它判断,查找也用同一个结果(不再扫一遍正文):长行里注册高亮会让浏览器同步重画整行,所以只计数、导航、滚动。
128
+ longLine = result.kind === ContentKind.TEXT && hasLongLine(result.text);
129
+ const skip = !language ? '' : result.bytes.length > HIGHLIGHT_LIMIT ? '不高亮' : longLine ? '行太长,不高亮' : '';
104
130
  const colored = language && !skip ? highlight(result.text, language) : null;
105
131
  const plain = !language ? '' : skip || (colored ? '' : '没能高亮');
106
132
  const note = [result.truncated ? `只显示前 ${formatSize(TEXT_LIMIT)}` : '', plain].filter(Boolean).join(',');
@@ -109,6 +135,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
109
135
  const gutter = h('pre', { class: 'gutter', 'aria-hidden': 'true' }, Array.from({ length: lineCount(result.text) }, (_, i) => i + 1).join('\n'));
110
136
  const text = h('pre', { class: 'text selectable' }, ...(colored ? [] : [result.text]));
111
137
  if (colored) appendAll(text, colored);
138
+ gutterEl = gutter;
139
+ pendingFind = { el: text, text: result.text, highlight: !longLine };
112
140
  if (selectionMenu) text.addEventListener('contextmenu', event => onSelect(event, text));
113
141
  body.replaceChildren(h('div', { class: 'code' }, gutter, text));
114
142
  } else if (result.kind === ContentKind.IMAGE && result.bytes.length > 0) {
@@ -129,15 +157,17 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
129
157
 
130
158
  function failure(error, silent, retry) {
131
159
  if (error.stale) return;
132
- if (error.code === ErrorCode.NOT_FOUND) { shown = null; setMeta(' '); return notice('文件已不存在', path); }
160
+ if (error.code === ErrorCode.NOT_FOUND) { shown = null; textShown = false; find.clearContent(); setMeta(' '); return notice('文件已不存在', path); }
133
161
  if (silent && shown) return setStale(error.message); // 后台刷新失败:保留正文,提示原因
162
+ textShown = false;
163
+ find.clearContent(); // 整页重读失败:标记清掉,计数写「—」,之后再读成功就重新找
134
164
  notice('读不到这个文件', error.message, { label: '重试', run: retry });
135
165
  }
136
166
 
137
167
  // silent:刷新。没变化不重画;变了就换内容,并尽量留在原来的滚动位置;有待恢复的位置时用它。
138
168
  async function load(silent) {
139
169
  const mine = ++token, mark = () => mine === token;
140
- if (!silent) { shown = null; setMeta('读取中…'); revoke(); body.replaceChildren(); }
170
+ if (!silent) { shown = null; textShown = false; find.clearContent(); setMeta('读取中…'); revoke(); body.replaceChildren(); }
141
171
  try {
142
172
  const result = await readFile(offset => read(path, offset), {
143
173
  prev: silent ? shown : null, cancelled: () => !mark(),
@@ -149,6 +179,8 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
149
179
  const keep = carry?.scroll ?? (silent ? { top: body.scrollTop, left: body.scrollLeft } : { top: 0, left: 0 });
150
180
  show(result);
151
181
  body.scrollTop = keep.top; body.scrollLeft = keep.left;
182
+ // 顺序:换正文 → 设好滚动位置 → 重建查找(刷新和换正文时查找不滚动,不盖掉恢复)
183
+ if (pendingFind) find.setContent(pendingFind.el, pendingFind.text, { highlight: pendingFind.highlight });
152
184
  settle(true);
153
185
  } catch (error) {
154
186
  if (mark()) failure(error, silent, () => load(false)); // 失败不算用上:待恢复的位置留着,重试或之后的刷新成功才用、才清
@@ -158,6 +190,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
158
190
  return {
159
191
  open(next, scroll = null) {
160
192
  settle(false);
193
+ if (next !== path) find.close(); // 换了文件就关查找,不靠调用方先 stop()
161
194
  opens++;
162
195
  path = next;
163
196
  const base = next.split('/').pop();
@@ -171,9 +204,9 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
171
204
  copyPath,
172
205
  refresh() { return path === null ? undefined : load(true); },
173
206
  // 内容的来源变了(根目录换了位置):旧正文不能留,也不能按元数据判断「没变」。
174
- reload() { return path === null ? undefined : load(false); },
207
+ reload() { find.close(); return path === null ? undefined : load(false); }, // 来源变了:查找也关
175
208
  // 停止(逻辑关闭,立即):不再读、不再刷新,待恢复的位置结算;画面(正文、图片的 URL)留着,由 release 在退场结束时清掉。
176
- stop() { settle(false); token++; path = null; shown = null; stoppedAt = opens; },
209
+ stop() { settle(false); token++; path = null; shown = null; textShown = false; find.close(); stoppedAt = opens; },
177
210
  // 释放(画面):停止之后又打开过就什么都不做。
178
211
  release() {
179
212
  if (stoppedAt !== opens) return; // 停止之后又打开过(打开次数变了):这一屏是新的,不是退场的旧页
@@ -187,5 +220,11 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
187
220
  scroll: () => (path === null ? { top: 0, left: 0 } : { top: body.scrollTop, left: body.scrollLeft }),
188
221
  onScroll: fn => body.addEventListener('scroll', fn, { passive: true }),
189
222
  get path() { return path; },
223
+ // 文件内查找的入口:有显示着的文本(或查找条已经开着)才有。
224
+ get canFind() { return path !== null && (textShown || find.isOpen); },
225
+ get findOpen() { return find.isOpen; },
226
+ openFind() { if (this.canFind) find.open(); return this.canFind; },
227
+ closeFind() { find.close(); },
228
+ find,
190
229
  };
191
230
  }
package/view/protocol.mjs CHANGED
@@ -13,18 +13,22 @@ export const SNIFF_BYTES = 8000;
13
13
  export const REQUEST_ID_MAX = 64;
14
14
  // 输入框草稿的文字上限(UTF-16 单元);拼完超过就不写。
15
15
  export const DRAFT_LIMIT = 100_000;
16
+ // 文件名搜索(设计见 docs/design/phase-3.md 第 18 节):搜索词去掉首尾空白后的长度上限(UTF-16 单元)、结果条数上限。
17
+ export const QUERY_MAX = 256;
18
+ export const SEARCH_RESULTS = 500;
16
19
 
17
20
  export const Type = Object.freeze({
18
21
  HELLO: 'hello', REFRESH: 'refresh', LIST: 'list', READ: 'read', STAT: 'stat', DIR_SIZE: 'dir_size', ADD_TEXT: 'add_text',
19
- DIR_SIZE_CANCEL: 'dir_size_cancel', // 没有回答
22
+ SEARCH: 'search',
23
+ DIR_SIZE_CANCEL: 'dir_size_cancel', SEARCH_CANCEL: 'search_cancel', // 没有回答
20
24
  SESSION: 'session', ROOT: 'root', CHANGED: 'changed',
21
- LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added',
25
+ LISTED: 'listed', CHUNK: 'chunk', STATTED: 'statted', SIZED: 'sized', ADDED: 'added', SEARCHED: 'searched',
22
26
  });
23
27
 
24
28
  // 请求 → 回答的类型。模块回答、页面分发都查这一张。
25
29
  export const ReplyOf = Object.freeze({
26
30
  [Type.LIST]: Type.LISTED, [Type.READ]: Type.CHUNK, [Type.STAT]: Type.STATTED,
27
- [Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED,
31
+ [Type.DIR_SIZE]: Type.SIZED, [Type.ADD_TEXT]: Type.ADDED, [Type.SEARCH]: Type.SEARCHED,
28
32
  });
29
33
  export const isReply = type => Object.values(ReplyOf).includes(type);
30
34
 
@@ -34,7 +38,7 @@ export const ErrorCode = Object.freeze({
34
38
  NO_ROOT: 'no_root', INVALID_PATH: 'invalid_path', OUTSIDE_ROOT: 'outside_root', NOT_FOUND: 'not_found',
35
39
  NOT_DIR: 'not_dir', NOT_FILE: 'not_file', DENIED: 'denied', CURSOR_EXPIRED: 'cursor_expired',
36
40
  INVALID_OFFSET: 'invalid_offset', INVALID_SORT: 'invalid_sort', TOO_LARGE: 'too_large', IO: 'io_error',
37
- DRAFT_FAILED: 'draft_failed', DRAFT_TOO_LONG: 'draft_too_long',
41
+ DRAFT_FAILED: 'draft_failed', DRAFT_TOO_LONG: 'draft_too_long', INVALID_QUERY: 'invalid_query',
38
42
  });
39
43
 
40
44
  // 目录排序:值是下面四种之一,缺省(请求不带 sort)是名称。方向由排序键决定,只在 lib/tree.mjs 里定义一处。
@@ -74,6 +78,34 @@ export function splitRelative(path) {
74
78
  return { segments };
75
79
  }
76
80
 
81
+ // 隐藏名单:按全名比。目录树、图标视图的「显示隐藏文件」和文件名搜索(模块和页面)共用这一处。
82
+ const HIDDEN = new Set(['.git', '.DS_Store']);
83
+ export const isHidden = name => HIDDEN.has(name);
84
+
85
+ // 文件名搜索的比较:名字和搜索词都先 NFC 规范化再 toLowerCase,包含就算。模块判断匹配、页面加粗用同一个函数。
86
+ export const foldName = text => text.normalize('NFC').toLowerCase();
87
+
88
+ // 页面加粗:搜索词(已 foldName)在名字里第一次出现的位置,返回原名字里的 [起点, 终点)(UTF-16 下标),没有或映射不出来返回 null。
89
+ // 比较是在规范化后的串上做的:把原名字切成「一个基字符加它的组合符号」,每段各自规范化、变小写,拼起来要等于整串的结果,
90
+ // 这样才能建「规范化后的位置 → 原名字的位置」的对照;拼不起来(如谚文字母的组合)、命中段的两端落在一段中间(一个字符变小写后变成两个)都不加粗。
91
+ const CLUSTER = /\P{M}\p{M}*|\p{M}+/gu;
92
+ export function matchSpan(name, folded) {
93
+ const whole = foldName(name), at = whole.indexOf(folded);
94
+ if (at < 0 || folded === '') return null;
95
+ const starts = new Map(), ends = new Map(); // 规范化后的位置 → 原名字的位置
96
+ let from = 0, to = 0, out = '';
97
+ for (const [piece] of name.matchAll(CLUSTER)) {
98
+ const folding = foldName(piece);
99
+ starts.set(from, to);
100
+ from += folding.length;
101
+ to += piece.length;
102
+ ends.set(from, to);
103
+ out += folding;
104
+ }
105
+ if (out !== whole || !starts.has(at) || !ends.has(at + folded.length)) return null;
106
+ return [starts.get(at), ends.get(at + folded.length)];
107
+ }
108
+
77
109
  export const messageSize = message => JSON.stringify({ message }).length;
78
110
 
79
111
  // 带 code 的错误,模块里到处抛,主模块转成回答里的 error。
@@ -0,0 +1,144 @@
1
+ // 文件名搜索在页面这一侧的状态(设计见 docs/design/phase-3.md 第 18.3 节):搜索词、搜索轮次、防抖、在途的请求、结果和它所属的搜索词、结果的选中。
2
+ // 不碰 DOM,请求由 call 发。
3
+ //
4
+ // 每个异步机制的五样:
5
+ // - 搜索轮次 round:由这里持有。输入、清空、隐藏开关切换、changed 和手动刷新的重搜、换会话、换根目录、根目录不可用都立刻加一(bump),
6
+ // 同时取消防抖计时器和在途的请求(link 在请求已发出时发 search_cancel)。只有当前轮次的回答能提交,旧轮次迟到的成功和失败都作废。
7
+ // - 防抖计时器:输入或重搜时开始,停顿 DEBOUNCE_MS 才发;到点先核对轮次,不是这一轮就不发;发出时、轮次变了时结束;换会话后不会用新会话发旧词。
8
+ // - 在途的请求:发出时开始,回答、失败、被 bump 取消时结束;超时由 link 的 30 秒兜底(算失败,显示原因和重试);回答回来时还核对会话和根目录的身份。
9
+ // - 结果 shown:和它所属的搜索词存在一起;新结果到来之前旧结果留着,状态写「正在搜索…」;加粗用旧结果自己的词。
10
+ import { ErrorCode, SEARCH_RESULTS, foldName, matchSpan } from './protocol.mjs';
11
+
12
+ export const DEBOUNCE_MS = 300;
13
+
14
+ const dirOf = path => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
15
+ const baseOf = path => path.slice(path.lastIndexOf('/') + 1);
16
+
17
+ const STOPS = {
18
+ count: `结果太多,只显示先找到的 ${SEARCH_RESULTS} 个`,
19
+ bytes: '结果太多,只显示一部分',
20
+ items: '没搜完(超过 20 万项),只显示已找到的',
21
+ time: '没搜完(超过 5 秒),只显示已找到的',
22
+ queue: '没搜完(目录太多),只显示已找到的',
23
+ };
24
+
25
+ // 状态行(结果上面一行):{ text, retry? }。
26
+ export function statusOf({ status, error, shown }) {
27
+ if (status === 'error') return { text: `搜索失败:${error}`, retry: true };
28
+ if (status === 'searching') return { text: '正在搜索…' };
29
+ if (!shown) return { text: '' };
30
+ const base = shown.stop === 'done' ? (shown.items.length === 0 ? '没有找到' : `共 ${shown.items.length} 个`) : STOPS[shown.stop] ?? '';
31
+ return { text: shown.unreadable > 0 ? `${base} · ${shown.unreadable} 项读不到` : base };
32
+ }
33
+
34
+ // call(fields, signal) → Promise<searched 回答>;hidden():现在是不是显示隐藏文件;identity():会话和根目录的身份串;
35
+ // onChange():状态变了,页面据此重画。
36
+ export function createSearch({ call, hidden, identity, onChange, timers = globalThis }) {
37
+ let text = '', round = 0, timer = null, inflight = null;
38
+ let shown = null; // { term, folded, items, stop, scanned, unreadable }:结果和它所属的搜索词
39
+ let status = 'idle', error = '', selected = null, suspended = false;
40
+ let cache = null; // rows() 的缓存:同一份结果只算一次行
41
+
42
+ const bump = () => {
43
+ round++;
44
+ timers.clearTimeout(timer);
45
+ timer = null;
46
+ inflight?.abort();
47
+ inflight = null;
48
+ };
49
+
50
+ function send(mine) {
51
+ const term = text.trim(), controller = new AbortController(), id = identity();
52
+ inflight = controller;
53
+ status = 'searching';
54
+ onChange();
55
+ const current = () => round === mine && identity() === id;
56
+ call({ query: term, hidden: hidden() }, controller.signal).then(reply => {
57
+ if (!current()) return;
58
+ inflight = null;
59
+ shown = { term, folded: foldName(term), items: reply.results, stop: reply.stop, scanned: reply.scanned, unreadable: reply.unreadable };
60
+ cache = null;
61
+ status = 'idle';
62
+ if (selected !== null && !reply.results.some(item => item.path === selected)) selected = null;
63
+ onChange();
64
+ }, failure => {
65
+ if (failure?.stale || !current()) return;
66
+ inflight = null;
67
+ status = 'error';
68
+ error = failure?.code === ErrorCode.INVALID_QUERY ? '搜索词无效' : failure?.message ?? '未知原因';
69
+ onChange();
70
+ });
71
+ }
72
+
73
+ // 防抖:停顿才发。回调里核对轮次,不是这一轮就不发。
74
+ function schedule() {
75
+ const mine = round;
76
+ status = 'searching';
77
+ timer = timers.setTimeout(() => { timer = null; if (round === mine) send(mine); }, DEBOUNCE_MS);
78
+ }
79
+
80
+ return {
81
+ get text() { return text; },
82
+ get active() { return text.trim() !== ''; },
83
+ get status() { return status; },
84
+ get error() { return error; },
85
+ get shown() { return shown; },
86
+ get round() { return round; },
87
+ get selected() { return selected; },
88
+ get suspended() { return suspended; },
89
+ statusLine: () => statusOf({ status, error, shown }),
90
+
91
+ // 用户输入(含清空):换了词,旧结果留到新结果来;空词立刻回到浏览。
92
+ input(value) {
93
+ text = value;
94
+ bump();
95
+ if (text.trim() === '') { shown = null; cache = null; selected = null; status = 'idle'; }
96
+ else schedule();
97
+ onChange();
98
+ },
99
+ // changed、手动刷新、隐藏开关切换:有搜索词就重搜,旧结果留到新结果来。
100
+ research() {
101
+ if (text.trim() === '') return;
102
+ bump();
103
+ schedule();
104
+ onChange();
105
+ },
106
+ // 根目录暂不可用(scope 没变):取消,丢结果,留搜索词;再就绪时 resume。
107
+ suspend() {
108
+ bump();
109
+ shown = null; cache = null; selected = null; status = 'idle';
110
+ suspended = true;
111
+ onChange();
112
+ },
113
+ resume() {
114
+ if (!suspended) return;
115
+ suspended = false;
116
+ this.research();
117
+ },
118
+ // 换会话、换根目录、定位开始、用户清空:搜索词、结果、选中都清掉。
119
+ reset() {
120
+ bump();
121
+ text = ''; shown = null; cache = null; selected = null; status = 'idle'; error = ''; suspended = false;
122
+ onChange();
123
+ },
124
+ // 结果的选中:只改这里,不重画;返回是不是变了。
125
+ select(path) {
126
+ if (selected === path) return false;
127
+ selected = path;
128
+ return true;
129
+ },
130
+ // 结果列表的行(mountTree 复用的行格式):加粗用结果自己的词。
131
+ rows() {
132
+ if (!shown) return [];
133
+ if (cache?.shown !== shown) {
134
+ cache = { shown, rows: shown.items.map(item => {
135
+ const name = baseOf(item.path);
136
+ return { type: 'entry', path: item.path, name, depth: 0, kind: item.kind, link: item.link === true, open: false,
137
+ bold: matchSpan(name, shown.folded), place: dirOf(item.path) || '工作目录', chevron: false };
138
+ }) };
139
+ }
140
+ return cache.rows;
141
+ },
142
+ dispose() { bump(); },
143
+ };
144
+ }
@@ -0,0 +1,27 @@
1
+ // 搜索框:目录树和图标视图顶上常驻的一行(设计见 docs/design/phase-3.md 第 18.3 节)。只管这一个输入框和它的清除按钮,搜索词归 view/search.mjs。
2
+ import { h } from './dom.mjs';
3
+ import { icon } from './icons.mjs';
4
+ import { QUERY_MAX } from './protocol.mjs';
5
+
6
+ // onInput(text):用户输入;onClear():点清除按钮;onKey(event):输入框里的按键(Esc、↓ 由页面按分派表处理);
7
+ // onEnter():回车或 iPhone 键盘的「搜索」键。字号不小于 16 点(style.css):iPhone 上小于 16 点聚焦时页面会放大。
8
+ export function mountSearchbar(el, { onInput, onClear, onKey, onEnter }) {
9
+ const input = h('input', {
10
+ id: 'q', type: 'search', placeholder: '搜索文件名', enterkeyhint: 'search', autocomplete: 'off', autocorrect: 'off', autocapitalize: 'off', spellcheck: 'false',
11
+ maxlength: QUERY_MAX, 'aria-label': '搜索文件名',
12
+ oninput: () => onInput(input.value), onkeydown: event => { if (event.key === 'Enter' && !event.isComposing) onEnter(); else onKey(event); },
13
+ });
14
+ const clear = h('button', { class: 'icon sclear', 'aria-label': '清除', title: '清除', onclick: onClear }, icon('clear', 16));
15
+ clear.hidden = true;
16
+ el.replaceChildren(h('div', { class: 'sfield' }, h('span', { class: 'sico', 'aria-hidden': 'true' }, icon('search', 16)), input, clear));
17
+ return {
18
+ input,
19
+ // 页面把搜索词写回输入框(清空、换会话);有字时显示清除按钮。
20
+ set(text) { if (input.value !== text) input.value = text; clear.hidden = text === ''; },
21
+ focus() { input.focus(); },
22
+ // 聚焦并选中里面的字。
23
+ select() { input.focus(); input.select?.(); },
24
+ blur() { input.blur?.(); },
25
+ get focused() { return document.activeElement === input; },
26
+ };
27
+ }
package/view/style.css CHANGED
@@ -54,13 +54,42 @@ p { margin: 0; }
54
54
  .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
55
55
  [hidden] { display: none !important; }
56
56
 
57
- /* 面板(目录树、图标、预览、说明、属性页)叠在同一处,只切可见性:隐藏的树保留滚动位置,切换不改变布局。 */
57
+ /* 面板(目录树、图标、预览、说明、属性页)叠在同一处,只切可见性:隐藏的树保留滚动位置,切换不改变布局。
58
+ 两级:外层是层(#browse、#preview、#notice、#info),#browse 里再叠三个面板(目录树、图标、搜索结果),搜索框在它们上面。 */
58
59
  #stage { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; } /* 裁掉层级过渡时横向溢出的那一层;菜单、提示是它的兄弟节点,不受裁切 */
59
60
  .pane { position: absolute; inset: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: var(--safe-bottom); }
60
61
  .pane.off { visibility: hidden; pointer-events: none; }
61
62
  /* iPhone 层级切换(第 17.6 节):深的一层(预览、属性页)永远在上,打开时它滑入盖住浅层,返回时它滑出露出浅层。
62
63
  .layer 只在过渡期间加:两层都要不透明,否则透出对面;.leaving 是离开的那一层,不接指针,点在它上面等于点在下面的目标页。 */
63
64
  #preview, #info { z-index: 1; }
65
+ .browse { display: flex; flex-direction: column; overflow: hidden; padding-bottom: 0; } /* 底部的安全区归里面的三个面板 */
66
+ #panes { position: relative; flex: 1 1 auto; min-height: 0; }
67
+ /* 搜索框(第 18.3 节):常驻在 #browse 顶上,不随列表滚动。字号不小于 16 点:iPhone 上小于 16 点聚焦时页面会放大。颜色只用 --coda-*。 */
68
+ .searchbar { flex: none; padding: 6px 8px; }
69
+ /* 胶囊形(第 18.3 节,仿 Codex 的搜索栏):底色 --coda-fill,平时留 1px 透明边(聚焦时换色不跳动);放大镜和 placeholder 用三级文字色。
70
+ 聚焦:卡片色底、强调色约 55% 的边、3 点强调色约 18% 的光晕,没有 outline。Mac 的字跟正文,iPhone 不小于 16 点(小于 16 点聚焦时页面会放大)。 */
71
+ .sfield { display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; border: 1px solid transparent; border-radius: 999px; background: var(--coda-fill, var(--hover));
72
+ transition: border-color .12s, box-shadow .12s, background-color .12s; }
73
+ .sico { flex: none; display: grid; place-items: center; color: var(--coda-tertiary, #a1a1a6); }
74
+ .sico svg { display: block; width: 14px; height: 14px; }
75
+ .sfield input { flex: 1 1 auto; min-width: 0; height: 100%; padding: 0; border: 0; outline: 0; background: transparent; color: inherit; font: inherit; font-size: 1em; -webkit-user-select: text; user-select: text; -webkit-appearance: none; appearance: none; }
76
+ .sfield input::placeholder { color: var(--coda-tertiary, #a1a1a6); }
77
+ .sfield input::-webkit-search-cancel-button, .sfield input::-webkit-search-decoration { -webkit-appearance: none; display: none; }
78
+ .sfield:focus-within { background: var(--coda-card, var(--coda-background, #fff)); border-color: color-mix(in srgb, var(--coda-accent, #0a84ff) 55%, transparent);
79
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--coda-accent, #0a84ff) 18%, transparent); }
80
+ .sfield button.sclear { width: 22px; height: 22px; color: var(--coda-tertiary, #a1a1a6); } /* 比 button.icon 的灰色优先 */
81
+ .coda-ios .sfield { height: 36px; padding: 0 12px; gap: 8px; }
82
+ .coda-ios .sfield input { font-size: max(16px, 1em); }
83
+ .coda-ios .sico svg { width: 16px; height: 16px; }
84
+ .coda-ios .searchbar { padding: 8px 16px 4px; }
85
+ @media (prefers-reduced-motion: reduce) { .sfield { transition: none; } }
86
+ /* 结果面板:状态行一行,下面是结果列表(复用目录树的行和虚拟列表)。结果行的名字里匹配的部分加粗。 */
87
+ .search { display: flex; flex-direction: column; overflow: hidden; padding-bottom: 0; }
88
+ .sstatus { flex: none; display: flex; align-items: center; gap: 8px; min-height: calc(var(--row-h) * .7); padding: 2px 16px; font-size: .85em; }
89
+ .shits { flex: 1 1 auto; min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: var(--safe-bottom); container: tree / inline-size; }
90
+ .shits:focus { outline: none; }
91
+ .shits:focus-visible { outline: 1px solid var(--coda-accent, #0a84ff); outline-offset: -2px; }
92
+ .row .name b { font-weight: 700; }
64
93
  .pane.layer { background: var(--coda-background, #fff); }
65
94
  .pane.leaving { pointer-events: none; }
66
95
  /* 滑动期间(约 280 毫秒)整页不响应点按;app.mjs 在过渡开始和结束(含强制结束)时加上和去掉。 */
@@ -256,3 +285,23 @@ button.icon svg { display: block; }
256
285
  /* 横屏:客户端隐藏导航栏,页面自己给返回。近似 verticalSizeClass 的判断,不等价(iPad、Duo 不单独适配)。 */
257
286
  .bar .exit, .bar.exit-only { display: none; } /* 只有返回的工具条(属性页):返回不显示,整条也不占高度 */
258
287
  @media (orientation: landscape) and (max-height: 500px) { .coda-ios .bar .exit { display: inline-flex; } .coda-ios .bar.exit-only { display: flex; } }
288
+
289
+ /* 文件内查找(第 18.6 节):查找条在预览头部下面、正文上面,不随正文滚动。输入框字号不小于 16 点,按钮至少 44 点(iPhone 的最小触摸尺寸在 .coda-ios button 里)。
290
+ 高亮全部匹配和当前这处:颜色从 --coda-accent 用 color-mix 派生(第 9 节),不改文字颜色。 */
291
+ .fbar { flex: none; display: flex; align-items: center; gap: 4px; padding: 4px 12px; border-bottom: 1px solid var(--line); }
292
+ .finput { flex: 1 1 auto; min-width: 0; height: 28px; padding: 0 8px; border: 0; outline: 0; border-radius: var(--coda-radius, 6px); background: var(--coda-fill, var(--hover)); color: inherit; font: inherit; font-size: 1em;
293
+ -webkit-user-select: text; user-select: text; -webkit-appearance: none; appearance: none; }
294
+ .finput::-webkit-search-cancel-button, .finput::-webkit-search-decoration { -webkit-appearance: none; display: none; }
295
+ .finput:focus { outline: 2px solid var(--coda-accent, #0a84ff); outline-offset: -1px; }
296
+ .fcount { flex: none; min-width: 3.2em; text-align: center; white-space: nowrap; font-variant-numeric: tabular-nums; }
297
+ .fbar button { flex: none; white-space: nowrap; }
298
+ .fbar button:disabled { opacity: .35; }
299
+ .fprev svg { transform: rotate(-90deg); } .fnext svg { transform: rotate(90deg); }
300
+ .coda-ios .fbar button { min-height: 44px; min-width: 44px; }
301
+ .coda-ios .finput { height: 36px; font-size: max(16px, 1em); }
302
+ .pbody:focus { outline: none; }
303
+ /* 只在查找开着时生效(.pbody.finding,find.mjs 随查找条的开关加去):这两条规则只要存在,浏览器就要给页面里每个文本节点算高亮样式,
304
+ 实测让打开 128 KiB 的密集上色文件慢了约 27 毫秒(119 → 147),不管规则里写的是背景还是文字色。 */
305
+ .pbody.finding ::highlight(find) { background-color: color-mix(in srgb, var(--coda-accent, #0a84ff) 25%, transparent); }
306
+ /* 当前这处:底色 50%,文字改成正文色(--coda-foreground,和 :root 一样),不显示代码着色,同系统浏览器的查找。全部匹配不改文字颜色。 */
307
+ .pbody.finding ::highlight(find-current) { background-color: color-mix(in srgb, var(--coda-accent, #0a84ff) 50%, transparent); color: var(--coda-foreground, #1d1d1f); }
package/view/tree.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // 目录树:visibleRows 把模型压成扁平行(纯逻辑);mountTree 只画可见的那一段,上万条也不卡。
2
- import { EntryKind, SortKey } from './protocol.mjs';
2
+ import { EntryKind, SortKey, isHidden } from './protocol.mjs';
3
3
  import { dateText, infoText, sizeText, subText } from './format.mjs';
4
4
  import { mountGestures } from './gestures.mjs';
5
5
  import { icon, iconFor } from './icons.mjs';
6
- import { isHidden, joinPath, parentOf } from './model.mjs';
6
+ import { joinPath, parentOf } from './model.mjs';
7
7
 
8
8
  const OVERSCAN = 8;
9
9
 
@@ -62,12 +62,18 @@ export const rootName = path => path.split('/').filter(Boolean).pop() ?? path;
62
62
  export const TITLES = { [EntryKind.LINK]: '指向工作目录外的链接,不能打开', [EntryKind.OTHER]: '不能打开的文件' };
63
63
 
64
64
  // handlers: { open(path), toggle(path), more(path), retry(path), menu(event, row), select(path | null) };select 是 Mac 单击选中,不给就是 iPhone 的轻点打开
65
+ // 搜索结果复用这份画行和虚拟列表(设计见 docs/design/phase-3.md 第 18.3 节):rows() 给行(缺省是目录树的 visibleRows),selected() 给选中的路径(缺省 model.selected),
66
+ // view 是按下反馈里的画面名('tree' 或 'search',search 的行带 .hit),title 为假时没有根目录名的分区标题。
67
+ // 结果行多三个字段:place(所在目录,Mac 在右侧、iPhone 在第二行)、bold(名字里要加粗的 [起点, 终点))、chevron: false(没有展开箭头的位置)。
65
68
  // menu 收到整行(路径、种类、大小、修改时间)。
66
69
  // draggable:触屏上拖行没有用处,还会抢滚动,关掉。now:当前时间,日期的相对格式用,测试可注入。
67
70
  // longPress:触屏上按住一行打开 handlers.menu(Mac 用右键)。不设 touch-action,滚动照旧,滚动接管时收到 pointercancel 作废。
68
71
  // keyboard:滚动容器可以获得焦点,键盘才接得上(Mac)。
69
72
  // press:按下反馈(press.mjs),画行时问它这一行是不是正在按下的;consumed(event):菜单消费掉的按下(gestures.mjs)。
70
- export function mountTree(el, model, handlers, { draggable = true, longPress = false, keyboard = false, now = Date.now, press = null, consumed = () => false } = {}) {
73
+ export function mountTree(el, model, handlers, {
74
+ draggable = true, longPress = false, keyboard = false, now = Date.now, press = null, consumed = () => false,
75
+ rows: rowsOf = () => visibleRows(model), selected = () => model.selected, view = 'tree', title: showTitle = true,
76
+ } = {}) {
71
77
  const title = document.createElement('div'), spacer = document.createElement('div'), win = document.createElement('div');
72
78
  title.className = 'section truncate'; spacer.className = 'spacer'; win.className = 'win';
73
79
  title.hidden = true;
@@ -88,7 +94,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
88
94
 
89
95
  // 分区标题:根目录的名字(root.path 的最后一段),不是 ready 时不显示。iPhone 上由 CSS 隐藏。
90
96
  const paintTitle = () => {
91
- const text = model.ready ? rootName(model.root.path) : '';
97
+ const text = showTitle && model.ready ? rootName(model.root.path) : '';
92
98
  if (title.textContent !== text) title.textContent = text;
93
99
  title.hidden = text === '';
94
100
  };
@@ -112,32 +118,35 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
112
118
  if (row.type !== 'entry') {
113
119
  node.textContent = row.text;
114
120
  if (row.retry) { node.classList.add('retry'); node.title = row.text; } // 长原因在行里被截断,Mac 悬停看全
115
- if (row.retry || row.type === 'more') press?.paint(node, 'tree', row.retry ? 'retry' : 'more', row.path);
121
+ if (row.retry || row.type === 'more') press?.paint(node, view, row.retry ? 'retry' : 'more', row.path);
116
122
  return node;
117
123
  }
118
- press?.paint(node, 'tree', 'entry', row.path);
124
+ press?.paint(node, view, 'entry', row.path);
125
+ if (view === 'search') node.classList.add('hit');
119
126
  const dead = row.kind === EntryKind.LINK || row.kind === EntryKind.OTHER;
120
127
  node.classList.add(row.kind);
121
128
  if (dead) node.classList.add('dead');
122
- if (row.path === model.selected) node.classList.add('sel');
129
+ if (row.path === selected()) node.classList.add('sel');
123
130
  if (row.kind === EntryKind.DIR) node.setAttribute('aria-expanded', row.open);
124
131
  if (!dead && draggable) node.draggable = true;
125
132
  // 一份 DOM:箭头、图标、名字(iPhone 下面跟日期 · 大小)、Mac 的 meta、尾标;iPhone 的箭头用 CSS order 排到最后,两端各用 CSS 藏起另一端的那段。
126
133
  const chevron = document.createElement('span'), glyph = document.createElement('span'), main = document.createElement('span'), label = document.createElement('span'), tail = document.createElement('span');
127
134
  chevron.className = 'chev';
128
135
  if (row.busy) chevron.textContent = '…';
129
- else if (!dead) chevron.append(icon('chevron', 12)); // 文件的箭头 Mac 上由 CSS 藏起来,只占位
136
+ else if (!dead && row.chevron !== false) chevron.append(icon('chevron', 12)); // 文件的箭头 Mac 上由 CSS 藏起来,只占位
130
137
  if (row.open) node.classList.add('open');
131
138
  glyph.className = 'ico';
132
139
  glyph.append(icon(iconFor(row)));
133
140
  main.className = 'main';
134
141
  label.className = 'name truncate';
135
- label.textContent = row.name;
142
+ if (row.bold) label.append(row.name.slice(0, row.bold[0]), Object.assign(document.createElement('b'), { textContent: row.name.slice(...row.bold) }), row.name.slice(row.bold[1]));
143
+ else label.textContent = row.name;
136
144
  main.append(label);
137
- const parts = [chevron, glyph, main];
138
- if (!dead) {
145
+ const parts = row.chevron === false ? [glyph, main] : [chevron, glyph, main];
146
+ {
139
147
  // 能打开的条目带信息;link、other 没有。文件夹没有的部分整个不画:iPhone 名字垂直居中,Mac 右侧不留空位。
140
- const subContent = subText(row, time), metaContent = model.sort === SortKey.DATE ? dateText(row, time) : sizeText(row);
148
+ // 搜索结果的所在目录(row.place)不受 dead 影响:失效的链接和 other 也要看得出在哪。
149
+ const subContent = row.place ?? (dead ? '' : subText(row, time)), metaContent = row.place ?? (dead ? '' : model.sort === SortKey.DATE ? dateText(row, time) : sizeText(row));
141
150
  if (subContent) {
142
151
  const sub = document.createElement('span');
143
152
  sub.className = 'sub caption secondary truncate';
@@ -154,7 +163,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
154
163
  tail.className = row.failed ? 'tail warn' : 'tail';
155
164
  if (row.failed) tail.append(icon('warning', 14));
156
165
  else if (row.link) tail.append(icon('turn', 14));
157
- const info = row.failed || TITLES[row.kind] ? '' : infoText(row);
166
+ const info = row.failed || TITLES[row.kind] || row.place !== undefined ? '' : infoText(row);
158
167
  node.title = row.failed ? `${row.path}\n读取失败:${row.failed}` : TITLES[row.kind] ? `${row.path}\n${TITLES[row.kind]}` : info ? `${row.path}\n${info}` : row.path;
159
168
  node.append(...parts, tail);
160
169
  return node;
@@ -179,7 +188,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
179
188
  consumed,
180
189
  });
181
190
  // 选中变了只在现有节点上切 .sel,不重建:双击的 dblclick 要落在还在容器里的节点上。
182
- const mark = () => { for (const node of win.children) node.classList.toggle('sel', rows[node.dataset.i]?.path === model.selected && rows[node.dataset.i]?.type === 'entry'); };
191
+ const mark = () => { for (const node of win.children) node.classList.toggle('sel', rows[node.dataset.i]?.path === selected() && rows[node.dataset.i]?.type === 'entry'); };
183
192
  // 滚到这一行能看见,只滚最少的距离;按行号算位置,不找节点(没画出来的行也行)。
184
193
  const reveal = index => {
185
194
  const top = (spacer.offsetTop || 0) + index * rowH;
@@ -187,21 +196,30 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
187
196
  else if (top + rowH > el.scrollTop + el.clientHeight) el.scrollTop = top + rowH - el.clientHeight;
188
197
  paint();
189
198
  };
199
+ // 滚到这一行在可见区中间(定位操作的最后一步);找不到返回 false。rows 要是最新的:调用前先 render()。
200
+ const center = path => {
201
+ const index = rows.findIndex(row => row.type === 'entry' && row.path === path);
202
+ if (index < 0) return false;
203
+ el.scrollTop = Math.max(0, (spacer.offsetTop || 0) + index * rowH - (el.clientHeight - rowH) / 2);
204
+ paint();
205
+ return true;
206
+ };
190
207
  el.addEventListener('scroll', paint, { passive: true });
191
208
  new ResizeObserver(paint).observe(el);
192
209
 
193
210
  return {
194
- render() { rows = visibleRows(model); spacer.style.height = `${rows.length * rowH}px`; paintTitle(); paint(); },
211
+ render() { rows = rowsOf(); spacer.style.height = `${rows.length * rowH}px`; paintTitle(); paint(); },
195
212
  remeasure() { measure(); this.render(); },
196
213
  scroll: () => el.scrollTop,
197
- scrollTo(top) { el.scrollTop = top; },
214
+ scrollTo(top) { el.scrollTop = top; paint(); },
198
215
  select: mark,
216
+ center,
199
217
  activate,
200
218
  focus() { el.focus(); },
201
219
  onKey(fn) { el.addEventListener('keydown', fn); },
202
220
  // 键盘一步:选中移动并滚到能看见,→ ← 展开收起。
203
221
  key(action) {
204
- const step = stepRows(rows, model.selected, action);
222
+ const step = stepRows(rows, selected(), action);
205
223
  if (!step) return;
206
224
  if (step.toggle !== undefined) return handlers.toggle(rows[step.toggle].path);
207
225
  handlers.select(rows[step.select].path);
@@ -209,7 +227,7 @@ export function mountTree(el, model, handlers, { draggable = true, longPress = f
209
227
  },
210
228
  // ⌘↓:和双击同一个动作;没有选中或选中的不在了什么都不做。
211
229
  openSelected() {
212
- const row = model.selected === null ? undefined : rows.find(item => item.type === 'entry' && item.path === model.selected);
230
+ const row = selected() === null ? undefined : rows.find(item => item.type === 'entry' && item.path === selected());
213
231
  if (row) activate(row);
214
232
  },
215
233
  // 切会话时调用:长按的等待和吞点击的标记都属于上一个会话。