@mytools-all/mytools-search 0.1.0 → 0.1.1

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/app.mjs CHANGED
@@ -1,391 +1,476 @@
1
- import {
2
- $,
3
- $$,
4
- action,
5
- copy,
6
- status,
7
- ready,
8
- call,
9
- escapeHtml,
10
- formatBytes,
11
- debounce,
12
- } from "./common.mjs";
13
- import { buildSearchQuery } from "./searchQuery.mjs";
14
- const filters = [
15
- ["all", "全部", ""],
16
- ["folder", "文件夹", "folder:"],
17
- ["doc", "文档", "ext:doc;docx;xls;xlsx;ppt;pptx;txt;md;csv"],
18
- ["pdf", "PDF", "ext:pdf"],
19
- ["image", "图片", "ext:png;jpg;jpeg;gif;bmp;webp;svg"],
20
- ["video", "视频", "ext:mp4;mkv;mov;avi;webm"],
21
- ["audio", "音频", "ext:mp3;wav;flac;aac;ogg"],
22
- ["archive", "压缩文件", "ext:zip;rar;7z;gz;tar"],
23
- ["exe", "程序", "ext:exe;msi;bat;cmd"],
24
- ];
25
- let entries = [],
26
- selected = -1,
27
- total = 0,
28
- offset = 0,
29
- type = "all",
30
- busy = false,
31
- pending = false,
32
- generation = 0,
33
- previewUrl = "",
34
- previewGeneration = 0,
35
- history = [];
36
- const limit = 100;
37
- try {
38
- const saved = JSON.parse(localStorage.getItem("search-custom-filters") || "[]");
39
- if (Array.isArray(saved)) filters.push(...saved.filter(f=>Array.isArray(f) && f.length===3 && f.every(x=>typeof x === "string") && f[0].startsWith("custom-")).slice(0,30));
40
- } catch {}
41
- function renderFilters() {
42
- $("#types").innerHTML = filters
43
- .map(
44
- ([id, label]) =>
45
- '<button data-type="' +
46
- escapeHtml(id) +
47
- '" class="' +
48
- (id === type ? "active" : "") +
49
- '">' +
50
- escapeHtml(label) +
51
- "</button>",
52
- )
53
- .join("");
54
- $("#custom-filter-list").innerHTML = filters.filter(f=>f[0].startsWith("custom-")).map(([id,label])=>'<div>'+escapeHtml(label)+' <button data-remove-filter="'+escapeHtml(id)+'" aria-label="删除过滤项">×</button></div>').join("");
55
- }
56
- renderFilters();
57
- function saveFilters() {
58
- localStorage.setItem("search-custom-filters", JSON.stringify(filters.filter(f=>f[0].startsWith("custom-"))));
59
- renderFilters();
60
- }
61
- $("#save-filter").onclick = action(() => {
62
- const label=$("#filter-name").value.trim(), query=$("#filter-query").value.trim();
63
- if (!label || !query) throw Error("请填写名称和 Everything 条件");
64
- if (filters.length>=39) throw Error("最多保存30个自定义过滤项");
65
- filters.push(["custom-"+crypto.randomUUID(),label.slice(0,30),query.slice(0,1000)]);
66
- saveFilters();$("#filter-name").value="";$("#filter-query").value="";
67
- });
68
- $("#custom-filter-list").onclick = e => {
69
- const id=e.target.closest("[data-remove-filter]")?.dataset.removeFilter;
70
- const at=filters.findIndex(f=>f[0]===id);if(at<0)return;
71
- filters.splice(at,1);if(type===id){type="all";offset=0;void action(search)();}saveFilters();
72
- };
73
- function picked() {
74
- if (!entries[selected]) throw Error("请先选择结果");
75
- return entries[selected];
76
- }
77
- function select(index, focus = false) {
78
- selected = Math.max(0, Math.min(entries.length - 1, index));
79
- $$(".result").forEach((el, i) => {
80
- el.classList.toggle("selected", i === selected);
81
- el.setAttribute("aria-selected", String(i === selected));
82
- });
83
- const row = $$(".result")[selected];
84
- row?.scrollIntoView({ block: "nearest" });
85
- if (focus) $("#results").focus();
86
- if (!$("#preview").classList.contains("hidden")) void preview();
87
- }
88
- function render() {
89
- const q = $("#query").value.trim();
90
- const words = q
91
- .split(/\s+/)
92
- .filter((w) => w && !w.includes(":") && !/[|<>"*?]/.test(w));
93
- const highlight = (name) => {
94
- if (!words.length) return escapeHtml(name);
95
- const regex = new RegExp(
96
- words
97
- .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
98
- .join("|"),
99
- "gi",
100
- );
101
- let output = "",
102
- at = 0;
103
- for (const match of name.matchAll(regex)) {
104
- output +=
105
- escapeHtml(name.slice(at, match.index)) +
106
- "<mark>" +
107
- escapeHtml(match[0]) +
108
- "</mark>";
109
- at = match.index + match[0].length;
110
- }
111
- return output + escapeHtml(name.slice(at));
112
- };
113
- $("#results").innerHTML = entries.length
114
- ? entries
115
- .map(
116
- (e, i) =>
117
- '<div role="option" class="result" data-index="' +
118
- i +
119
- '"><span class="file-icon">' +
120
- (e.directory ? "▱" : "▤") +
121
- '</span><div><div class="file-name">' +
122
- highlight(e.name) +
123
- '</div><div class="file-path" title="' +
124
- escapeHtml(e.path) +
125
- '">' +
126
- escapeHtml(e.path.replace(/[\\/][^\\/]+$/, "")) +
127
- '</div></div><div class="meta">' +
128
- (e.directory ? "文件夹" : formatBytes(e.size)) +
129
- "<br>" +
130
- (e.modified ? new Date(e.modified * 1000).toLocaleString() : "") +
131
- "</div></div>",
132
- )
133
- .join("")
134
- : '<div class="empty">没有匹配的文件</div>';
135
- $$(".result").forEach((el) => {
136
- el.onclick = () => select(Number(el.dataset.index), true);
137
- el.ondblclick = action(() =>
138
- call("shell.open", { path: entries[Number(el.dataset.index)].path }),
139
- );
140
- el.oncontextmenu = (e) => {
141
- e.preventDefault();
142
- select(Number(el.dataset.index), true);
143
- void action(() => call("shell.reveal", { path: picked().path }))();
144
- };
145
- });
146
- $("#count").textContent =
147
- (total ? offset + 1 : 0) + "–" + (offset + entries.length) + " / " + total;
148
- $("#previous").disabled = offset === 0;
149
- $("#next").disabled = offset + entries.length >= total;
150
- select(0);
151
- }
152
- function showConnection(message, title = "未连接到 Everything") {
153
- $("#connection strong").textContent = title;
154
- $("#connection").classList.remove("hidden");
155
- $("#connection-message").textContent = message;
156
- }
157
- async function search() {
158
- if (busy) {
159
- pending = true;
160
- generation++;
161
- return;
162
- }
163
- busy = true;
164
- const token = ++generation;
165
- $("#refresh").disabled = true;
166
- status("正在查询 Everything…");
167
- const q = $("#query").value.trim();
168
- try {
169
- const filter = filters.find((f) => f[0] === type)[2];
170
- const query = buildSearchQuery({query:q,category:filter,extension:$("#extension-filter").value,excluded:$("#exclude-filter").value,period:$("#modified-period").value,from:$("#modified-from").value,to:$("#modified-to").value});
171
- const result = await call("fs.globalsearch", {
172
- query,
173
- offset,
174
- limit,
175
- sort: Number($("#sort").value),
176
- });
177
- if (token !== generation) return;
178
- entries = result.entries;
179
- total = result.total;
180
- $("#connection").classList.add("hidden");
181
- render();
182
- status("Everything · " + total.toLocaleString() + " 个结果");
183
- } catch (e) {
184
- if (token === generation) {
185
- entries = [];
186
- total = 0;
187
- render();
188
- showConnection(
189
- e.message || String(e),
190
- /授权|拒绝|denied|permission/i.test(e.message || "")
191
- ? "搜索权限未获允许"
192
- : "Everything 查询失败",
193
- );
194
- status(e.message || String(e), true);
195
- }
196
- } finally {
197
- busy = false;
198
- $("#refresh").disabled = false;
199
- if (pending) {
200
- pending = false;
201
- void action(search)();
202
- }
203
- }
204
- }
205
- function remember() {
206
- const q = $("#query").value.trim();
207
- if (!q) return;
208
- history = [q, ...history.filter((x) => x !== q)].slice(0, 20);
209
- $("#history").innerHTML =
210
- '<option value="">搜索历史</option>' +
211
- history.map((q) => "<option>" + escapeHtml(q) + "</option>").join("");
212
- localStorage.setItem("search-history", JSON.stringify(history));
213
- }
214
- const schedule = debounce(() => {
215
- offset = 0;
216
- void action(search)();
217
- }, 160);
218
- window.mytools?.onSearch?.(event => {
219
- $("#query").value = event.query;
220
- if (event.key) $("#query").dispatchEvent(new KeyboardEvent("keydown", {key:event.key,bubbles:true}));
221
- else { generation++; schedule(); }
222
- });
223
- $("#query").oninput = () => {
224
- generation++;
225
- schedule();
226
- };
227
- $("#query").onkeydown = (e) => {
228
- if (e.isComposing) return;
229
- if (e.key === "ArrowDown") {
230
- e.preventDefault();
231
- select(0, true);
232
- }
233
- if (e.key === "Enter") {
234
- e.preventDefault();
235
- remember();
236
- offset = 0;
237
- void action(search)();
238
- }
239
- if (e.key === "Escape") $("#query").select();
240
- };
241
- $("#results").onkeydown = action(async (e) => {
242
- if (e.key === "ArrowDown" || e.key === "ArrowUp") {
243
- e.preventDefault();
244
- select(selected + (e.key === "ArrowDown" ? 1 : -1));
245
- } else if (e.key === "Enter") {
246
- e.preventDefault();
247
- await call(e.ctrlKey ? "shell.reveal" : "shell.open", {
248
- path: picked().path,
249
- });
250
- } else if (e.key === " ") {
251
- e.preventDefault();
252
- $("#preview-toggle").click();
253
- } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "c") {
254
- e.preventDefault();
255
- await copy(picked().path);
256
- } else if (e.key === "Escape") {
257
- $("#query").focus();
258
- $("#query").select();
259
- }
260
- });
261
- $("#types").onclick = e => {
262
- const b = e.target.closest("[data-type]");
263
- if (!b) return;
264
- type = b.dataset.type;
265
- $$("#types button").forEach((x) => x.classList.toggle("active", x === b));
266
- offset = 0;
267
- void action(search)();
268
- };
269
- $("#sort").onchange = () => {
270
- offset = 0;
271
- void action(search)();
272
- };
273
- for (const control of $$("#advanced-filters input,#advanced-filters select")) control.onchange = () => {
274
- $("#date-range").classList.toggle("hidden", $("#modified-period").value !== "custom");
275
- offset = 0;
276
- void action(search)();
277
- };
278
- $("#filter-toggle").onclick = () => {
279
- const expanded = $("#advanced-filters").classList.toggle("hidden") === false;
280
- $("#filter-toggle").setAttribute("aria-expanded", String(expanded));
281
- };
282
- $("#reset-filters").onclick = () => {
283
- for (const input of $$("#advanced-filters input")) input.value = "";
284
- $("#modified-period").value = "";
285
- $("#date-range").classList.add("hidden");
286
- offset = 0;
287
- void action(search)();
288
- };
289
- $("#history").onchange = () => {
290
- if ($("#history").value) {
291
- $("#query").value = $("#history").value;
292
- offset = 0;
293
- void action(search)();
294
- }
295
- };
296
- $("#previous").onclick = () => {
297
- offset = Math.max(0, offset - limit);
298
- void action(search)();
299
- };
300
- $("#next").onclick = () => {
301
- offset += limit;
302
- void action(search)();
303
- };
304
- $("#refresh").onclick = action(search);
305
- $("#retry").onclick = action(search);
306
- $("#start").onclick = action(async () => {
307
- const apps = await call("app.list", { query: "Everything" });
308
- const candidates = Array.isArray(apps) ? apps : apps.apps || [];
309
- const app = candidates.find((a) =>
310
- /everything/i.test(a.name || a.title || ""),
311
- );
312
- if (!app)
313
- throw Error(
314
- "没有找到已安装的 Everything。请先安装或手动启动 Everything 后重新连接。",
315
- );
316
- await call("app.launch", { target: app.target || app.id });
317
- status("已启动 Everything,请稍后点击重新连接");
318
- });
319
- $("#open").onclick = action(() => call("shell.open", { path: picked().path }));
320
- $("#reveal").onclick = action(() =>
321
- call("shell.reveal", { path: picked().path }),
322
- );
323
- $("#copy").onclick = action(() => copy(picked().path));
324
- async function preview() {
325
- const token = ++previewGeneration;
326
- try {
327
- if (!entries[selected]) { $("#preview").textContent="选择文件查看预览"; return; }
328
- const file = picked();
329
- $("#preview").textContent = "正在读取预览…";
330
- const result = await call("fs.searchpreview", { path: file.path });
331
- if (token !== previewGeneration) return;
332
- if (previewUrl) {
333
- URL.revokeObjectURL(previewUrl);
334
- previewUrl = "";
335
- }
336
- $("#preview").replaceChildren();
337
- const heading = document.createElement("strong");
338
- heading.textContent = file.name;
339
- $("#preview").append(heading);
340
- const metadata = document.createElement("div");
341
- metadata.className = "preview-meta";
342
- metadata.textContent = [file.path, file.directory ? "文件夹" : formatBytes(file.size),file.modified ? new Date(file.modified * 1000).toLocaleString() : ""].filter(Boolean).join("\n");
343
- $("#preview").append(metadata);
344
- if (["image","pdf","audio","video"].includes(result.kind)) {
345
- previewUrl = URL.createObjectURL(
346
- new Blob([new Uint8Array(result.bytes)], { type: result.mime }),
347
- );
348
- const media = result.kind === "image" ? new Image() : document.createElement(result.kind === "pdf" ? "iframe" : result.kind);
349
- media.src = previewUrl; media.title = file.name;
350
- if (result.kind === "image") media.alt = file.name;
351
- if (["audio","video"].includes(result.kind)) media.controls = true;
352
- $("#preview").append(media);
353
- } else {
354
- const pre = document.createElement("pre");
355
- pre.textContent = result.text;
356
- $("#preview").append(pre);
357
- if (result.truncated)
358
- $("#preview").append(document.createTextNode("\n仅预览前 20 KB"));
359
- }
360
- } catch (e) {
361
- if (token === previewGeneration)
362
- $("#preview").textContent = e.message || String(e);
363
- }
364
- }
365
- $("#preview-toggle").onclick = () => {
366
- $("#preview").classList.toggle("hidden");
367
- if (!$("#preview").classList.contains("hidden")) void preview();
368
- else { previewGeneration++; if (previewUrl) { URL.revokeObjectURL(previewUrl);previewUrl=""; } }
369
- };
370
- try {
371
- history = JSON.parse(localStorage.getItem("search-history") || "[]");
372
- if (!Array.isArray(history)) history = [];
373
- } catch {
374
- history = [];
375
- }
376
- $("#history").innerHTML =
377
- '<option value="">搜索历史</option>' +
378
- history.map((q) => "<option>" + escapeHtml(q) + "</option>").join("");
379
- ready(async (env) => {
380
- if (env?.hostSearch) {
381
- $("#query").style.display = "none";
382
- $("#query").setAttribute("aria-hidden", "true");
383
- }
384
- const s = await call("fs.searchstatus");
385
- if (s.running) await search();
386
- else
387
- showConnection(
388
- "请启动 Everything 1.4 / 1.5a 并等待索引完成。此插件直接使用 Everything 索引,不扫描磁盘目录。",
389
- );
390
- if (!env?.hostSearch) $("#query").focus();
391
- });
1
+ import {
2
+ $,
3
+ $$,
4
+ action,
5
+ copy,
6
+ status,
7
+ ready,
8
+ call,
9
+ escapeHtml,
10
+ formatBytes,
11
+ debounce,
12
+ } from "./common.mjs";
13
+ import { buildSearchQuery } from "./searchQuery.mjs";
14
+ import { resultName, resultParent, placeholderIcon } from "./resultPresentation.mjs";
15
+ const filters = [
16
+ ["all", "全部", ""],
17
+ ["folder", "文件夹", "folder:"],
18
+ ["doc", "文档", "ext:doc;docx;xls;xlsx;ppt;pptx;txt;md;csv"],
19
+ ["pdf", "PDF", "ext:pdf"],
20
+ ["image", "图片", "ext:png;jpg;jpeg;gif;bmp;webp;svg"],
21
+ ["video", "视频", "ext:mp4;mkv;mov;avi;webm"],
22
+ ["audio", "音频", "ext:mp3;wav;flac;aac;ogg"],
23
+ ["archive", "压缩文件", "ext:zip;rar;7z;gz;tar"],
24
+ ["exe", "程序", "ext:exe;msi;bat;cmd"],
25
+ ];
26
+ let entries = [],
27
+ selected = -1,
28
+ total = 0,
29
+ offset = 0,
30
+ type = "all",
31
+ busy = false,
32
+ pending = false,
33
+ generation = 0,
34
+ previewUrl = "",
35
+ previewGeneration = 0,
36
+ history = [];
37
+ const limit = 100;
38
+ const iconCache = new Map();
39
+ let iconObserver;
40
+ let iconGeneration = 0;
41
+ try {
42
+ const saved = JSON.parse(localStorage.getItem("search-custom-filters") || "[]");
43
+ if (Array.isArray(saved)) filters.push(...saved.filter(f=>Array.isArray(f) && f.length===3 && f.every(x=>typeof x === "string") && f[0].startsWith("custom-")).slice(0,30));
44
+ } catch {}
45
+ function renderFilters() {
46
+ $("#types").innerHTML = filters
47
+ .map(
48
+ ([id, label]) =>
49
+ '<button data-type="' +
50
+ escapeHtml(id) +
51
+ '" class="' +
52
+ (id === type ? "active" : "") +
53
+ '">' +
54
+ escapeHtml(label) +
55
+ "</button>",
56
+ )
57
+ .join("");
58
+ const custom = filters.filter(f=>f[0].startsWith("custom-"));
59
+ $("#custom-filter-list").innerHTML = custom.length ? custom.map(([id,label,query])=>'<div class="custom-filter"><div class="custom-filter__text"><strong>'+escapeHtml(label)+'</strong><code title="'+escapeHtml(query)+'">'+escapeHtml(query)+'</code></div><button class="filter-delete" data-remove-filter="'+escapeHtml(id)+'" aria-label="删除过滤项:'+escapeHtml(label)+'" title="删除此过滤项"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v5M14 11v5"/></svg><span>删除</span></button></div>').join("") : '<p class="filter-empty">暂无自定义过滤项</p>';
60
+ }
61
+ renderFilters();
62
+ function saveFilters() {
63
+ localStorage.setItem("search-custom-filters", JSON.stringify(filters.filter(f=>f[0].startsWith("custom-"))));
64
+ renderFilters();
65
+ }
66
+ $("#save-filter").onclick = action(() => {
67
+ const label=$("#filter-name").value.trim(), query=$("#filter-query").value.trim();
68
+ if (!label || !query) throw Error("请填写名称和 Everything 条件");
69
+ if (filters.length>=39) throw Error("最多保存30个自定义过滤项");
70
+ filters.push(["custom-"+crypto.randomUUID(),label.slice(0,30),query.slice(0,1000)]);
71
+ saveFilters();$("#filter-name").value="";$("#filter-query").value="";
72
+ });
73
+ $("#custom-filter-list").onclick = e => {
74
+ const id=e.target.closest("[data-remove-filter]")?.dataset.removeFilter;
75
+ const at=filters.findIndex(f=>f[0]===id);if(at<0)return;
76
+ const label=filters[at][1];
77
+ filters.splice(at,1);if(type===id){type="all";offset=0;void action(search)();}saveFilters();
78
+ status("已删除过滤项:"+label);$("#filter-name").focus();
79
+ };
80
+ function picked() {
81
+ if (!entries[selected]) throw Error("请先选择结果");
82
+ return entries[selected];
83
+ }
84
+ function clearSearch() {
85
+ generation++;
86
+ pending = false;
87
+ entries = [];
88
+ selected = -1;
89
+ total = 0;
90
+ offset = 0;
91
+ iconGeneration++;
92
+ iconObserver?.disconnect();
93
+ previewGeneration++;
94
+ for (const media of $("#preview").querySelectorAll("audio,video")) {
95
+ media.pause();
96
+ media.removeAttribute("src");
97
+ media.load();
98
+ }
99
+ if (previewUrl) { URL.revokeObjectURL(previewUrl); previewUrl = ""; }
100
+ $("#results").replaceChildren();
101
+ $("#preview").replaceChildren();
102
+ $("#preview").classList.add("hidden");
103
+ $("#connection").classList.add("hidden");
104
+ $("#count").textContent = "0 / 0";
105
+ $("#previous").disabled = true;
106
+ $("#next").disabled = true;
107
+ for (const id of ["open","reveal","copy","preview-toggle"]) $("#"+id).disabled = true;
108
+ $("#refresh").disabled = false;
109
+ status("输入关键词开始搜索");
110
+ }
111
+ function select(index, focus = false) {
112
+ if (!entries.length) { selected = -1; return; }
113
+ selected = Math.max(0, Math.min(entries.length - 1, index));
114
+ $$(".result").forEach((el, i) => {
115
+ el.classList.toggle("selected", i === selected);
116
+ el.setAttribute("aria-selected", String(i === selected));
117
+ });
118
+ const row = $$(".result")[selected];
119
+ row?.scrollIntoView({ block: "nearest" });
120
+ if (focus) $("#results").focus();
121
+ if (!$("#preview").classList.contains("hidden")) void preview();
122
+ }
123
+ function render() {
124
+ const q = $("#query").value.trim();
125
+ const words = q
126
+ .split(/\s+/)
127
+ .filter((w) => w && !w.includes(":") && !/[|<>"*?]/.test(w));
128
+ const highlight = (name) => {
129
+ if (!words.length) return escapeHtml(name);
130
+ const regex = new RegExp(
131
+ words
132
+ .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
133
+ .join("|"),
134
+ "gi",
135
+ );
136
+ let output = "",
137
+ at = 0;
138
+ for (const match of name.matchAll(regex)) {
139
+ output +=
140
+ escapeHtml(name.slice(at, match.index)) +
141
+ "<mark>" +
142
+ escapeHtml(match[0]) +
143
+ "</mark>";
144
+ at = match.index + match[0].length;
145
+ }
146
+ return output + escapeHtml(name.slice(at));
147
+ };
148
+ $("#results").innerHTML = entries.length
149
+ ? entries
150
+ .map(
151
+ (e, i) =>
152
+ '<div role="option" class="result" data-index="' +
153
+ i +
154
+ '"><span class="file-icon">' +
155
+ '<img alt="" src="'+(iconCache.get(e.path+"\0"+e.modified) || placeholderIcon(e.directory))+'" />' +
156
+ '</span><div><div class="file-name">' +
157
+ highlight(resultName(e)) +
158
+ '</div><div class="file-path" title="' +
159
+ escapeHtml(e.path) +
160
+ '">' +
161
+ escapeHtml(resultParent(e)) +
162
+ '</div></div><div class="meta">' +
163
+ (e.directory ? "文件夹" : formatBytes(e.size)) +
164
+ "<br>" +
165
+ (e.modified ? new Date(e.modified * 1000).toLocaleString() : "") +
166
+ "</div></div>",
167
+ )
168
+ .join("")
169
+ : '<div class="empty">没有匹配的文件</div>';
170
+ $$(".result").forEach((el) => {
171
+ el.onclick = () => select(Number(el.dataset.index), true);
172
+ el.ondblclick = action(() =>
173
+ call("shell.open", { path: entries[Number(el.dataset.index)].path }),
174
+ );
175
+ el.oncontextmenu = (e) => {
176
+ e.preventDefault();
177
+ select(Number(el.dataset.index), true);
178
+ void action(() => call("shell.reveal", { path: picked().path }))();
179
+ };
180
+ });
181
+ $("#count").textContent =
182
+ (total ? offset + 1 : 0) + "–" + (offset + entries.length) + " / " + total;
183
+ $("#previous").disabled = offset === 0;
184
+ $("#next").disabled = offset + entries.length >= total;
185
+ for (const id of ["open","reveal","copy","preview-toggle"]) $("#"+id).disabled = !entries.length;
186
+ select(0);
187
+ hydrateIcons();
188
+ }
189
+ function hydrateIcons() {
190
+ const token = ++iconGeneration;
191
+ iconObserver?.disconnect();
192
+ const queue = new Map();
193
+ let running = false;
194
+ const applyIcons = () => {
195
+ $$(".result").forEach(row => {
196
+ const entry = entries[Number(row.dataset.index)];
197
+ const image = row.querySelector(".file-icon img");
198
+ if (!entry || !image) return;
199
+ image.src = iconCache.get(entry.path+"\0"+entry.modified) || placeholderIcon(entry.directory);
200
+ image.onerror = () => { image.onerror = null; image.src = placeholderIcon(entry.directory); };
201
+ });
202
+ };
203
+ const load = async () => {
204
+ if (running) return;
205
+ running = true;
206
+ try {
207
+ while (queue.size && token === iconGeneration) {
208
+ const batch = [...queue.values()].slice(0,8);
209
+ batch.forEach(entry => queue.delete(entry.path));
210
+ let icons;
211
+ try { icons = await call("fs.searchicons", {paths:batch.map(entry=>entry.path)}); }
212
+ catch { queue.clear(); return; }
213
+ if (!Array.isArray(icons)) { queue.clear(); return; }
214
+ if (token !== iconGeneration) return;
215
+ for (const entry of batch) {
216
+ const icon = icons.find(item=>item.path===entry.path)?.icon;
217
+ iconCache.set(entry.path+"\0"+entry.modified, typeof icon === "string" && icon.startsWith("data:image/png;base64,") ? icon : null);
218
+ }
219
+ while (iconCache.size > 256) iconCache.delete(iconCache.keys().next().value);
220
+ applyIcons();
221
+ }
222
+ } finally { running = false; }
223
+ };
224
+ const enqueue = row => {
225
+ const entry = entries[Number(row.dataset.index)];
226
+ if (entry && !iconCache.has(entry.path+"\0"+entry.modified)) queue.set(entry.path,entry);
227
+ };
228
+ if (typeof IntersectionObserver === "undefined") {
229
+ $$(".result").slice(0,16).forEach(enqueue);
230
+ void load();
231
+ } else {
232
+ iconObserver = new IntersectionObserver(changes=>{
233
+ for (const change of changes) if(change.isIntersecting) {enqueue(change.target);iconObserver.unobserve(change.target);}
234
+ void load();
235
+ },{root:$("#results"),rootMargin:"48px"});
236
+ $$(".result").forEach(row=>iconObserver.observe(row));
237
+ }
238
+ }
239
+ function showConnection(message, title = "未连接到 Everything") {
240
+ $("#connection strong").textContent = title;
241
+ $("#connection").classList.remove("hidden");
242
+ $("#connection-message").textContent = message;
243
+ }
244
+ async function search() {
245
+ const q = $("#query").value.trim();
246
+ if (!q) { clearSearch(); return; }
247
+ if (busy) {
248
+ pending = true;
249
+ generation++;
250
+ return;
251
+ }
252
+ busy = true;
253
+ const token = ++generation;
254
+ $("#refresh").disabled = true;
255
+ status("正在查询 Everything…");
256
+ try {
257
+ const filter = filters.find((f) => f[0] === type)[2];
258
+ const query = buildSearchQuery({query:q,category:filter,extension:$("#extension-filter").value,excluded:$("#exclude-filter").value,period:$("#modified-period").value,from:$("#modified-from").value,to:$("#modified-to").value});
259
+ const result = await call("fs.globalsearch", {
260
+ query,
261
+ offset,
262
+ limit,
263
+ sort: Number($("#sort").value),
264
+ });
265
+ if (token !== generation) return;
266
+ entries = result.entries;
267
+ total = result.total;
268
+ $("#connection").classList.add("hidden");
269
+ render();
270
+ status("Everything · " + total.toLocaleString() + " 个结果");
271
+ } catch (e) {
272
+ if (token === generation) {
273
+ entries = [];
274
+ total = 0;
275
+ render();
276
+ showConnection(
277
+ e.message || String(e),
278
+ /授权|拒绝|denied|permission/i.test(e.message || "")
279
+ ? "搜索权限未获允许"
280
+ : "Everything 查询失败",
281
+ );
282
+ status(e.message || String(e), true);
283
+ }
284
+ } finally {
285
+ busy = false;
286
+ $("#refresh").disabled = false;
287
+ if (pending) {
288
+ pending = false;
289
+ void action(search)();
290
+ }
291
+ }
292
+ }
293
+ function remember() {
294
+ const q = $("#query").value.trim();
295
+ if (!q) return;
296
+ history = [q, ...history.filter((x) => x !== q)].slice(0, 20);
297
+ $("#history").innerHTML =
298
+ '<option value="">搜索历史</option>' +
299
+ history.map((q) => "<option>" + escapeHtml(q) + "</option>").join("");
300
+ localStorage.setItem("search-history", JSON.stringify(history));
301
+ }
302
+ const schedule = debounce(() => {
303
+ offset = 0;
304
+ void action(search)();
305
+ }, 160);
306
+ window.mytools?.onSearch?.(event => {
307
+ $("#query").value = event.query;
308
+ if (!$("#query").value.trim()) { clearSearch(); return; }
309
+ if (event.key) $("#query").dispatchEvent(new KeyboardEvent("keydown", {key:event.key,bubbles:true}));
310
+ else { generation++; schedule(); }
311
+ });
312
+ $("#query").oninput = () => {
313
+ if (!$("#query").value.trim()) { clearSearch(); return; }
314
+ generation++;
315
+ schedule();
316
+ };
317
+ $("#query").onkeydown = (e) => {
318
+ if (e.isComposing) return;
319
+ if (e.key === "ArrowDown") {
320
+ e.preventDefault();
321
+ select(0, true);
322
+ }
323
+ if (e.key === "Enter") {
324
+ e.preventDefault();
325
+ remember();
326
+ offset = 0;
327
+ void action(search)();
328
+ }
329
+ if (e.key === "Escape") $("#query").select();
330
+ };
331
+ $("#results").onkeydown = action(async (e) => {
332
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
333
+ e.preventDefault();
334
+ select(selected + (e.key === "ArrowDown" ? 1 : -1));
335
+ } else if (e.key === "Enter") {
336
+ e.preventDefault();
337
+ await call(e.ctrlKey ? "shell.reveal" : "shell.open", {
338
+ path: picked().path,
339
+ });
340
+ } else if (e.key === " ") {
341
+ e.preventDefault();
342
+ $("#preview-toggle").click();
343
+ } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "c") {
344
+ e.preventDefault();
345
+ await copy(picked().path);
346
+ } else if (e.key === "Escape") {
347
+ $("#query").focus();
348
+ $("#query").select();
349
+ }
350
+ });
351
+ $("#types").onclick = e => {
352
+ const b = e.target.closest("[data-type]");
353
+ if (!b) return;
354
+ type = b.dataset.type;
355
+ $$("#types button").forEach((x) => x.classList.toggle("active", x === b));
356
+ offset = 0;
357
+ void action(search)();
358
+ };
359
+ $("#sort").onchange = () => {
360
+ offset = 0;
361
+ void action(search)();
362
+ };
363
+ for (const control of $$("#advanced-filters input,#advanced-filters select")) control.onchange = () => {
364
+ $("#date-range").classList.toggle("hidden", $("#modified-period").value !== "custom");
365
+ offset = 0;
366
+ void action(search)();
367
+ };
368
+ $("#filter-toggle").onclick = () => {
369
+ const expanded = $("#advanced-filters").classList.toggle("hidden") === false;
370
+ $("#filter-toggle").setAttribute("aria-expanded", String(expanded));
371
+ };
372
+ $("#reset-filters").onclick = () => {
373
+ for (const input of $$("#advanced-filters input")) input.value = "";
374
+ $("#modified-period").value = "";
375
+ $("#date-range").classList.add("hidden");
376
+ offset = 0;
377
+ void action(search)();
378
+ };
379
+ $("#history").onchange = () => {
380
+ if ($("#history").value) {
381
+ $("#query").value = $("#history").value;
382
+ offset = 0;
383
+ void action(search)();
384
+ }
385
+ };
386
+ $("#previous").onclick = () => {
387
+ offset = Math.max(0, offset - limit);
388
+ void action(search)();
389
+ };
390
+ $("#next").onclick = () => {
391
+ offset += limit;
392
+ void action(search)();
393
+ };
394
+ $("#refresh").onclick = action(search);
395
+ $("#retry").onclick = action(search);
396
+ $("#start").onclick = action(async () => {
397
+ const apps = await call("app.list", { query: "Everything" });
398
+ const candidates = Array.isArray(apps) ? apps : apps.apps || [];
399
+ const app = candidates.find((a) =>
400
+ /everything/i.test(a.name || a.title || ""),
401
+ );
402
+ if (!app)
403
+ throw Error(
404
+ "没有找到已安装的 Everything。请先安装或手动启动 Everything 后重新连接。",
405
+ );
406
+ await call("app.launch", { target: app.target || app.id });
407
+ status("已启动 Everything,请稍后点击重新连接");
408
+ });
409
+ $("#open").onclick = action(() => call("shell.open", { path: picked().path }));
410
+ $("#reveal").onclick = action(() =>
411
+ call("shell.reveal", { path: picked().path }),
412
+ );
413
+ $("#copy").onclick = action(() => copy(picked().path));
414
+ async function preview() {
415
+ const token = ++previewGeneration;
416
+ try {
417
+ if (!entries[selected]) { $("#preview").textContent="选择文件查看预览"; return; }
418
+ const file = picked();
419
+ $("#preview").textContent = "正在读取预览…";
420
+ const result = await call("fs.searchpreview", { path: file.path });
421
+ if (token !== previewGeneration) return;
422
+ if (previewUrl) {
423
+ URL.revokeObjectURL(previewUrl);
424
+ previewUrl = "";
425
+ }
426
+ $("#preview").replaceChildren();
427
+ const heading = document.createElement("strong");
428
+ heading.textContent = resultName(file);
429
+ $("#preview").append(heading);
430
+ const metadata = document.createElement("div");
431
+ metadata.className = "preview-meta";
432
+ metadata.textContent = [file.path, file.directory ? "文件夹" : formatBytes(file.size),file.modified ? new Date(file.modified * 1000).toLocaleString() : ""].filter(Boolean).join("\n");
433
+ $("#preview").append(metadata);
434
+ if (["image","pdf","audio","video"].includes(result.kind)) {
435
+ previewUrl = URL.createObjectURL(
436
+ new Blob([new Uint8Array(result.bytes)], { type: result.mime }),
437
+ );
438
+ const media = result.kind === "image" ? new Image() : document.createElement(result.kind === "pdf" ? "iframe" : result.kind);
439
+ media.src = previewUrl; media.title = file.name;
440
+ if (result.kind === "image") media.alt = file.name;
441
+ if (["audio","video"].includes(result.kind)) media.controls = true;
442
+ $("#preview").append(media);
443
+ } else {
444
+ const pre = document.createElement("pre");
445
+ pre.textContent = result.text;
446
+ $("#preview").append(pre);
447
+ if (result.truncated)
448
+ $("#preview").append(document.createTextNode("\n仅预览前 20 KB"));
449
+ }
450
+ } catch (e) {
451
+ if (token === previewGeneration)
452
+ $("#preview").textContent = e.message || String(e);
453
+ }
454
+ }
455
+ $("#preview-toggle").onclick = () => {
456
+ $("#preview").classList.toggle("hidden");
457
+ if (!$("#preview").classList.contains("hidden")) void preview();
458
+ else { previewGeneration++; if (previewUrl) { URL.revokeObjectURL(previewUrl);previewUrl=""; } }
459
+ };
460
+ try {
461
+ history = JSON.parse(localStorage.getItem("search-history") || "[]");
462
+ if (!Array.isArray(history)) history = [];
463
+ } catch {
464
+ history = [];
465
+ }
466
+ $("#history").innerHTML =
467
+ '<option value="">搜索历史</option>' +
468
+ history.map((q) => "<option>" + escapeHtml(q) + "</option>").join("");
469
+ ready(async (env) => {
470
+ if (env?.hostSearch) {
471
+ $("#query").style.display = "none";
472
+ $("#query").setAttribute("aria-hidden", "true");
473
+ }
474
+ await search();
475
+ if (!env?.hostSearch) $("#query").focus();
476
+ });