@namewta/skills-hub 0.1.47 → 0.1.49
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/README.md +1 -1
- package/THIRD_PARTY_NOTICES.md +3 -3
- package/package.json +1 -1
- package/scripts/persistence/home.md +1 -0
- package/skills/dev/dev-archive/references/change-closure.md +4 -0
- package/skills/home/home-project-changelog/SKILL.md +5 -5
- package/skills/home/home-project-changelog/assets/project-changelog.md +7 -7
- package/skills/home/home-project-changelog/assets/worker-brief.md +1 -1
- package/skills/home/home-project-changelog/references/git-ranges.md +3 -0
- package/skills/home/home-project-changelog/references/tools.md +20 -2
- package/skills/home/home-project-changelog/references/workflow.md +5 -2
- package/skills/home/home-project-changelog/references/writing.md +20 -2
- package/skills/home/home-project-changelog/scripts/changelog.mjs +47 -5
- package/skills/home/home-project-changelog/scripts/contract.mjs +46 -2
- package/skills/home/home-project-changelog/scripts/git.mjs +15 -0
- package/skills/home/home-project-changelog/scripts/revision.mjs +231 -0
- package/skills/home/home-project-changelog/scripts/storage.mjs +32 -8
- package/skills/home/home-project-changelog/scripts/summary.mjs +17 -3
- package/skills/home/home-project-changelog/scripts/tasks.mjs +40 -0
- package/skills/home/home-setup/SKILL.md +1 -1
- package/skills/home/home-setup/references/registry.md +4 -0
- package/skills/home/home-setup/scripts/git.mjs +2 -0
- package/skills/home/home-website/SKILL.md +20 -0
- package/skills/home/home-website/assets/website/gitignore.tmpl +4 -0
- package/skills/home/home-website/assets/website/package-lock.json +2376 -0
- package/skills/home/home-website/assets/website/package.json +11 -0
- package/skills/home/home-website/assets/website/scripts/artifact.mjs +84 -0
- package/skills/home/home-website/assets/website/scripts/inputs.mjs +251 -0
- package/skills/home/home-website/assets/website/scripts/preview.mjs +50 -0
- package/skills/home/home-website/assets/website/scripts/render.mjs +97 -0
- package/skills/home/home-website/assets/website/scripts/site.mjs +173 -0
- package/skills/home/home-website/assets/website/site/.vitepress/theme/index.js +3 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/app.js +262 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/site.css +330 -0
- package/skills/home/home-website/assets/website/site/public/home-assets/start.js +7 -0
- package/skills/home/home-website/assets/website/site/templates/layout.mjs +93 -0
- package/skills/home/home-website/assets/website/site/templates/ledger.mjs +69 -0
- package/skills/home/home-website/assets/website/site/templates/model.mjs +104 -0
- package/skills/home/home-website/assets/website/site/templates/pages.mjs +75 -0
- package/skills/home/home-website/assets/website/site/templates/project-logs.mjs +130 -0
- package/skills/home/home-website/assets/website/site.config.json +6 -0
- package/skills/home/home-website/references/website.md +82 -0
- package/skills/home/home-website/scripts/init.mjs +57 -0
- package/skills/home/home-workflow/SKILL.md +1 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { directory, inputs, read } from './inputs.mjs';
|
|
8
|
+
import { fingerprint, manifest, validateArtifact } from './artifact.mjs';
|
|
9
|
+
import { render } from './render.mjs';
|
|
10
|
+
import { preview } from './preview.mjs';
|
|
11
|
+
import { statistics } from '../site/templates/model.mjs';
|
|
12
|
+
|
|
13
|
+
const website = fileURLToPath(new URL('../', import.meta.url));
|
|
14
|
+
const cache = path.join(website,'.cache');
|
|
15
|
+
const dist = path.join(website,'dist');
|
|
16
|
+
const previous = path.join(cache,'previous-dist');
|
|
17
|
+
const previousMeta = path.join(cache,'previous.json');
|
|
18
|
+
const lock = path.join(website,'.refresh.lock');
|
|
19
|
+
const meta = path.join(cache,'current.json');
|
|
20
|
+
const retry = 'node .agents/home/website/scripts/site.mjs refresh';
|
|
21
|
+
|
|
22
|
+
function mkdir(target) {
|
|
23
|
+
if (!directory(target)) fs.mkdirSync(target);
|
|
24
|
+
}
|
|
25
|
+
function pidState() {
|
|
26
|
+
const bytes = read(path.join(lock,'owner.json'));
|
|
27
|
+
const owner = bytes && JSON.parse(bytes);
|
|
28
|
+
if (owner?.host !== os.hostname() || !Number.isInteger(owner.pid) || owner.pid <= 0) return 'unknown';
|
|
29
|
+
try { process.kill(owner.pid,0); return 'running'; }
|
|
30
|
+
catch (error) { return error.code === 'ESRCH' ? 'stopped' : 'unknown'; }
|
|
31
|
+
}
|
|
32
|
+
function acquire(wait) {
|
|
33
|
+
const deadline = Date.now() + wait;
|
|
34
|
+
for (;;) {
|
|
35
|
+
try { fs.mkdirSync(lock); break; }
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== 'EEXIST') throw error;
|
|
38
|
+
if (!directory(lock)) continue;
|
|
39
|
+
if (Date.now() >= deadline) throw Error('另有刷新在运行或上次异常退出。确认旧进程已结束后可运行 recover。');
|
|
40
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try { fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({host:os.hostname(),pid:process.pid}),{flag:'wx'}); }
|
|
44
|
+
catch (error) { fs.rmdirSync(lock); throw error; }
|
|
45
|
+
}
|
|
46
|
+
function release() {
|
|
47
|
+
fs.unlinkSync(path.join(lock,'owner.json'));
|
|
48
|
+
fs.rmdirSync(lock);
|
|
49
|
+
}
|
|
50
|
+
function restoreDist() {
|
|
51
|
+
if (!directory(previous) || directory(dist)) return;
|
|
52
|
+
const record = read(previousMeta);
|
|
53
|
+
if (record) fs.renameSync(previousMeta,meta);
|
|
54
|
+
fs.renameSync(previous,dist);
|
|
55
|
+
}
|
|
56
|
+
function current() {
|
|
57
|
+
const bytes = read(meta);
|
|
58
|
+
if (!bytes) return null;
|
|
59
|
+
try { return JSON.parse(bytes); } catch { return null; }
|
|
60
|
+
}
|
|
61
|
+
function artifactMatches(fingerprintValue, record) {
|
|
62
|
+
if (record?.fingerprint !== fingerprintValue || !Array.isArray(record.files) || !directory(dist)) return false;
|
|
63
|
+
return JSON.stringify(manifest(dist)) === JSON.stringify(record.files);
|
|
64
|
+
}
|
|
65
|
+
function hadSavedLogs(record) {
|
|
66
|
+
if (record?.hasState !== undefined) return record.hasState;
|
|
67
|
+
if (!directory(dist)) return false;
|
|
68
|
+
const catalog = read(path.join(dist,'data','catalog.json'));
|
|
69
|
+
return catalog && JSON.parse(catalog).projects.some(project => project.ranges > 0);
|
|
70
|
+
}
|
|
71
|
+
function publish(candidate, record, run) {
|
|
72
|
+
const tempMeta = path.join(run,'current.json');
|
|
73
|
+
fs.writeFileSync(tempMeta,JSON.stringify(record)+'\n');
|
|
74
|
+
if (directory(previous)) fs.rmSync(previous,{recursive:true});
|
|
75
|
+
const displaced = directory(dist);
|
|
76
|
+
if (displaced) {
|
|
77
|
+
const metadata = read(meta);
|
|
78
|
+
if (metadata) {
|
|
79
|
+
const tempPrevious = path.join(run,'previous.json');
|
|
80
|
+
fs.writeFileSync(tempPrevious,metadata);
|
|
81
|
+
fs.renameSync(tempPrevious,previousMeta);
|
|
82
|
+
} else if (read(previousMeta)) fs.unlinkSync(previousMeta);
|
|
83
|
+
fs.renameSync(dist,previous);
|
|
84
|
+
}
|
|
85
|
+
let swapped = false;
|
|
86
|
+
try {
|
|
87
|
+
fs.renameSync(candidate,dist);
|
|
88
|
+
swapped = true;
|
|
89
|
+
fs.renameSync(tempMeta,meta);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (swapped) fs.renameSync(dist,candidate);
|
|
92
|
+
if (displaced) fs.renameSync(previous,dist);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function refresh(force) {
|
|
98
|
+
mkdir(cache);
|
|
99
|
+
// Acquire before reading sources so a waiting refresh always builds from the newest Home state.
|
|
100
|
+
acquire(60_000);
|
|
101
|
+
let run;
|
|
102
|
+
try {
|
|
103
|
+
restoreDist();
|
|
104
|
+
const snapshot = inputs(website);
|
|
105
|
+
const {model,warnings,excluded} = snapshot;
|
|
106
|
+
const before = current();
|
|
107
|
+
if (!snapshot.hasState && hadSavedLogs(before)) throw Error('已构建的网站缺少 changelogs/state.json,请先核对 Home 或恢复状态文件。');
|
|
108
|
+
const key = fingerprint(website,model);
|
|
109
|
+
const projectIds = model.projects.map(project=>project.id);
|
|
110
|
+
const stats = statistics(model.projects.flatMap(project=>project.periods));
|
|
111
|
+
const summary = {base:model.base,projects:projectIds.length,entries:stats.changes,stats,warnings,excluded,dist};
|
|
112
|
+
if (!force && artifactMatches(key,before)) return {status:'unchanged', ...summary};
|
|
113
|
+
const cli = path.join(website,'node_modules','vitepress','bin','vitepress.js');
|
|
114
|
+
if (!fs.existsSync(cli)) throw Error('网站尚未安装依赖,请在网站目录运行 npm ci,再重试。');
|
|
115
|
+
run = fs.mkdtempSync(path.join(cache,'build-'));
|
|
116
|
+
const candidate = render(website,run,model);
|
|
117
|
+
const result = spawnSync(process.execPath,[cli,'build',candidate.source],{
|
|
118
|
+
cwd:website,env:{...process.env,FORCE_COLOR:'0'},encoding:'utf8',maxBuffer:8*1024*1024,windowsHide:true,
|
|
119
|
+
});
|
|
120
|
+
if (result.error || result.status !== 0) throw Error('VitePress 构建失败:'+(result.error?.message ?? result.stderr.trim() ?? '未知错误')+'\n'+(result.stdout ?? '').trim());
|
|
121
|
+
// VitePress MPA builds leave a Node ESM marker in their output directory.
|
|
122
|
+
const marker = path.join(candidate.dist,'package.json');
|
|
123
|
+
const markerBytes = read(marker);
|
|
124
|
+
if (markerBytes && JSON.stringify(JSON.parse(markerBytes)) === '{"private":true,"type":"module"}') fs.unlinkSync(marker);
|
|
125
|
+
const publishedFiles = manifest(candidate.dist,validateArtifact(candidate,model.base));
|
|
126
|
+
const after = inputs(website);
|
|
127
|
+
if (after.inputRevision !== snapshot.inputRevision || fingerprint(website,after.model) !== key) {
|
|
128
|
+
throw Error('构建时 Home 或网站源文件已变化,保留上次版本,请重试。');
|
|
129
|
+
}
|
|
130
|
+
publish(candidate.dist,{fingerprint:key,base:model.base,projects:projectIds,hasState:snapshot.hasState,files:publishedFiles},run);
|
|
131
|
+
return {status:'built', ...summary,
|
|
132
|
+
added:projectIds.filter(id=>!before?.projects?.includes(id)),
|
|
133
|
+
removed:(before?.projects ?? []).filter(id=>!projectIds.includes(id)),
|
|
134
|
+
};
|
|
135
|
+
} finally {
|
|
136
|
+
try { if (run) fs.rmSync(run,{recursive:true}); }
|
|
137
|
+
finally { release(); }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function recover() {
|
|
142
|
+
const guard = path.join(cache,'recover.lock');
|
|
143
|
+
fs.mkdirSync(guard);
|
|
144
|
+
try {
|
|
145
|
+
if (directory(lock)) {
|
|
146
|
+
if (pidState() !== 'stopped') throw Error('刷新锁的原进程未证实已结束。请核对锁中的主机和 PID。');
|
|
147
|
+
fs.renameSync(lock,path.join(guard,'owner'));
|
|
148
|
+
}
|
|
149
|
+
acquire(0);
|
|
150
|
+
try { restoreDist(); return {status:'ready',dist,refresh:retry}; }
|
|
151
|
+
finally { release(); }
|
|
152
|
+
} finally {
|
|
153
|
+
fs.rmSync(guard,{recursive:true});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const [command = 'refresh', ...args] = process.argv.slice(2);
|
|
158
|
+
try {
|
|
159
|
+
const {values} = parseArgs({args,options:{force:{type:'boolean'},port:{type:'string'},help:{type:'boolean'}}});
|
|
160
|
+
if (values.help) console.log('用法:node scripts/site.mjs refresh [--force] | preview [--port 4173] | recover');
|
|
161
|
+
else if (command === 'refresh' && values.port === undefined) console.log(JSON.stringify(refresh(values.force),null,2));
|
|
162
|
+
else if (command === 'recover' && values.port === undefined && !values.force) {
|
|
163
|
+
mkdir(cache);
|
|
164
|
+
console.log(JSON.stringify(recover(),null,2));
|
|
165
|
+
} else if (command === 'preview' && !values.force) {
|
|
166
|
+
const record = current();
|
|
167
|
+
if (!record || !directory(dist)) throw Error('还没有可预览的构建,请先运行 refresh。');
|
|
168
|
+
preview(dist,record.base,values.port ?? '4173');
|
|
169
|
+
} else throw Error('未知操作,请查看 --help。');
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.error(JSON.stringify({status:'failed',message:error.message,retry}));
|
|
172
|
+
process.exitCode = 1;
|
|
173
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
'use strict';
|
|
3
|
+
const one = selector => document.querySelector(selector);
|
|
4
|
+
const all = selector => [...document.querySelectorAll(selector)];
|
|
5
|
+
const root = one('.home-site')?.dataset.root;
|
|
6
|
+
const normalize = value => (value ?? '').normalize('NFKC').toLocaleLowerCase('zh-CN').trim();
|
|
7
|
+
if (!root) return;
|
|
8
|
+
const fileRoot = location.protocol === 'file:' ? new URL('../', document.currentScript.src) : null;
|
|
9
|
+
|
|
10
|
+
function routeHref(href) {
|
|
11
|
+
if (!fileRoot || !href.startsWith(root) || href.startsWith('//')) return href;
|
|
12
|
+
const target = new URL(href.slice(root.length), fileRoot);
|
|
13
|
+
if (target.pathname.endsWith('/')) target.pathname += 'index.html';
|
|
14
|
+
return target.href;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (fileRoot) {
|
|
18
|
+
for (const link of all('.home-site a[href^="/"]')) link.href = routeHref(link.getAttribute('href'));
|
|
19
|
+
}
|
|
20
|
+
document.documentElement.classList.add('enhanced');
|
|
21
|
+
const searchIndex = window.homeSearchIndex ?? [];
|
|
22
|
+
|
|
23
|
+
function setQueryParam(name, value) {
|
|
24
|
+
const url = new URL(location.href);
|
|
25
|
+
if (value) url.searchParams.set(name, value);
|
|
26
|
+
else url.searchParams.delete(name);
|
|
27
|
+
try { history.replaceState(null, '', url.href); } catch { /* Filtering also works when a local browser restricts history. */ }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function initTheme() {
|
|
31
|
+
const toggle = one('[data-theme-toggle]');
|
|
32
|
+
const key = 'skills-hub.home-website.theme';
|
|
33
|
+
function updateLabel() {
|
|
34
|
+
const dark = document.documentElement.dataset.theme === 'dark';
|
|
35
|
+
const label = dark ? '切换浅色模式' : '切换深色模式';
|
|
36
|
+
toggle.setAttribute('aria-label', label);
|
|
37
|
+
toggle.title = label;
|
|
38
|
+
}
|
|
39
|
+
updateLabel();
|
|
40
|
+
toggle.addEventListener('click', () => {
|
|
41
|
+
const choice = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
|
|
42
|
+
document.documentElement.dataset.theme = choice;
|
|
43
|
+
try { localStorage.setItem(key,choice); } catch {}
|
|
44
|
+
updateLabel();
|
|
45
|
+
});
|
|
46
|
+
window.addEventListener('pageshow', updateLabel);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function initCatalog() {
|
|
50
|
+
const input = one('#catalog-query');
|
|
51
|
+
if (!input) return;
|
|
52
|
+
const cards = all('#project-grid .project-card');
|
|
53
|
+
const buttons = all('[data-group-filter]');
|
|
54
|
+
const params = new URL(location.href).searchParams;
|
|
55
|
+
let group = buttons.find(button => button.dataset.groupFilter === params.get('group'))?.dataset.groupFilter ?? '';
|
|
56
|
+
input.value = params.get('q') ?? '';
|
|
57
|
+
function filter(updateUrl = true) {
|
|
58
|
+
const q = normalize(input.value);
|
|
59
|
+
let count = 0;
|
|
60
|
+
for (const card of cards) {
|
|
61
|
+
const visible = (!group || JSON.parse(card.dataset.groups).includes(group)) && normalize(card.innerText || card.textContent).includes(q);
|
|
62
|
+
card.hidden = !visible;
|
|
63
|
+
if (visible) count++;
|
|
64
|
+
}
|
|
65
|
+
buttons.forEach(button => button.setAttribute('aria-pressed', String(button.dataset.groupFilter === group)));
|
|
66
|
+
one('#catalog-count').textContent = '显示 ' + count + ' 个项目';
|
|
67
|
+
one('#catalog-empty').hidden = count !== 0;
|
|
68
|
+
if (updateUrl) { setQueryParam('group', group); setQueryParam('q', input.value.trim()); }
|
|
69
|
+
}
|
|
70
|
+
buttons.forEach(button => button.addEventListener('click', () => { group = button.dataset.groupFilter; filter(); }));
|
|
71
|
+
input.addEventListener('input', () => filter());
|
|
72
|
+
one('#reset-catalog').addEventListener('click', () => { group = ''; input.value = ''; filter(); input.focus(); });
|
|
73
|
+
filter(false);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function initTimeline() {
|
|
77
|
+
const input = one('#timeline-query');
|
|
78
|
+
if (!input) return;
|
|
79
|
+
const project = one('#timeline-project');
|
|
80
|
+
const month = one('#timeline-month');
|
|
81
|
+
const category = one('#timeline-category');
|
|
82
|
+
const fields = [['repo', project], ['month', month], ['category', category], ['q', input]].filter(([, field]) => field);
|
|
83
|
+
const number = value => value.toLocaleString('zh-CN');
|
|
84
|
+
const months = all('.ledger-window').map(section => ({
|
|
85
|
+
section,
|
|
86
|
+
key: section.dataset.month,
|
|
87
|
+
count: section.querySelector('.window-count'),
|
|
88
|
+
groups: [...section.querySelectorAll('.ledger-group')].map(group => ({
|
|
89
|
+
group,
|
|
90
|
+
id: group.dataset.ledgerRepo,
|
|
91
|
+
projectText: normalize(group.dataset.ledgerRepo + ' ' + group.dataset.repoName),
|
|
92
|
+
commits: Number(group.dataset.commits),
|
|
93
|
+
rows: [...group.querySelectorAll('[data-kind]')].map(row => ({
|
|
94
|
+
row,
|
|
95
|
+
category: row.dataset.kind,
|
|
96
|
+
text: normalize(row.textContent),
|
|
97
|
+
task: row.hasAttribute('data-entry'),
|
|
98
|
+
})),
|
|
99
|
+
})),
|
|
100
|
+
}));
|
|
101
|
+
|
|
102
|
+
function restore() {
|
|
103
|
+
const params = new URL(location.href).searchParams;
|
|
104
|
+
for (const [key, field] of fields) {
|
|
105
|
+
field.value = params.get(key) ?? '';
|
|
106
|
+
if (field.tagName === 'SELECT' && field.selectedIndex < 0) field.value = '';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function render() {
|
|
111
|
+
const tokens = normalize(input.value).split(/\s+/u).filter(Boolean);
|
|
112
|
+
const projects = new Set();
|
|
113
|
+
let dated = 0, undated = false, tasks = 0;
|
|
114
|
+
for (const entry of months) {
|
|
115
|
+
let groups = 0, entries = 0, commits = 0;
|
|
116
|
+
for (const group of entry.groups) {
|
|
117
|
+
const matchesScope = (!project?.value || project.value === group.id) && (!month.value || month.value === entry.key);
|
|
118
|
+
const visible = group.rows.filter(item => {
|
|
119
|
+
item.row.hidden = !matchesScope || (category.value !== '' && category.value !== item.category)
|
|
120
|
+
|| !tokens.every(token => item.text.includes(token) || group.projectText.includes(token));
|
|
121
|
+
return !item.row.hidden;
|
|
122
|
+
});
|
|
123
|
+
const commitOnly = !group.rows.length && !category.value && tokens.every(token => group.projectText.includes(token));
|
|
124
|
+
group.group.hidden = !matchesScope || (!visible.length && !commitOnly);
|
|
125
|
+
if (group.group.hidden) continue;
|
|
126
|
+
groups++;
|
|
127
|
+
projects.add(group.id);
|
|
128
|
+
entries += visible.filter(item => item.task).length;
|
|
129
|
+
commits += group.commits;
|
|
130
|
+
}
|
|
131
|
+
entry.section.hidden = groups === 0;
|
|
132
|
+
if (!groups) continue;
|
|
133
|
+
if (entry.key === 'undated') undated = true;
|
|
134
|
+
else dated++;
|
|
135
|
+
tasks += entries;
|
|
136
|
+
const commitLabel = category.value || tokens.length
|
|
137
|
+
? `所示项目共 ${number(commits)} 次 Git 提交`
|
|
138
|
+
: `${number(commits)} 次 Git 提交`;
|
|
139
|
+
entry.count.textContent = `${number(entries)} 项任务 · ${commitLabel}`;
|
|
140
|
+
}
|
|
141
|
+
const monthCount = dated ? `${dated} 个月${undated ? '及日期未记录条目' : ''}` : undated ? '日期未记录条目' : '0 个月';
|
|
142
|
+
const projectCount = project ? ` · ${projects.size} 个项目` : '';
|
|
143
|
+
one('#timeline-count').textContent = `${monthCount}${projectCount} · ${number(tasks)} 项任务`;
|
|
144
|
+
one('#timeline-empty').hidden = dated > 0 || undated;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
for (const [key, field] of fields) field.addEventListener(field === input ? 'input' : 'change', () => {
|
|
148
|
+
setQueryParam(key, field.value);
|
|
149
|
+
render();
|
|
150
|
+
});
|
|
151
|
+
one('#reset-timeline').addEventListener('click', () => {
|
|
152
|
+
for (const [key, field] of fields) {
|
|
153
|
+
field.value = '';
|
|
154
|
+
setQueryParam(key, '');
|
|
155
|
+
}
|
|
156
|
+
render();
|
|
157
|
+
input.focus();
|
|
158
|
+
});
|
|
159
|
+
window.addEventListener('pageshow', event => {
|
|
160
|
+
if (event.persisted) {
|
|
161
|
+
restore();
|
|
162
|
+
render();
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
restore();
|
|
166
|
+
render();
|
|
167
|
+
}
|
|
168
|
+
function addHighlighted(parent, value, needle) {
|
|
169
|
+
// The source index is text. Insert text nodes even when a phrase looks like markup.
|
|
170
|
+
const position = needle ? value.toLocaleLowerCase('zh-CN').indexOf(needle) : -1;
|
|
171
|
+
if (position < 0) { parent.textContent = value; return; }
|
|
172
|
+
parent.append(value.slice(0,position));
|
|
173
|
+
const highlight = document.createElement('mark');
|
|
174
|
+
highlight.textContent = value.slice(position,position + needle.length);
|
|
175
|
+
parent.append(highlight,value.slice(position + needle.length));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function initSearch() {
|
|
179
|
+
const dialog = one('#search-dialog'), input = one('#global-query'), results = one('#search-results');
|
|
180
|
+
const opener = one('[data-open-search]');
|
|
181
|
+
let restoreFocus = opener, selected = -1;
|
|
182
|
+
function showResults() {
|
|
183
|
+
selected = -1;
|
|
184
|
+
const query = normalize(input.value);
|
|
185
|
+
const tokens = query.split(/\s+/u).filter(Boolean);
|
|
186
|
+
const found = searchIndex.filter(item => {
|
|
187
|
+
if (!tokens.length) return item.kind === '项目';
|
|
188
|
+
const haystack = normalize([item.name,item.id,item.title,item.text,item.group,item.date].filter(Boolean).join(' '));
|
|
189
|
+
return tokens.every(token => haystack.includes(token));
|
|
190
|
+
});
|
|
191
|
+
results.replaceChildren();
|
|
192
|
+
one('#search-summary').textContent = query
|
|
193
|
+
? (found.length ? '找到 ' + found.length + ' 个结果' : '没有匹配的结果,试试其他项目名或变更关键词。')
|
|
194
|
+
: '直接前往项目';
|
|
195
|
+
for (const item of found) {
|
|
196
|
+
const link = document.createElement('a');
|
|
197
|
+
link.className = 'search-result';
|
|
198
|
+
link.href = routeHref(root + item.url);
|
|
199
|
+
link.target = '_self';
|
|
200
|
+
const label = document.createElement('small');
|
|
201
|
+
label.textContent = item.kind + ' · ' + item.id + (item.date ? ' · ' + item.date : '');
|
|
202
|
+
const title = document.createElement('strong');
|
|
203
|
+
addHighlighted(title,item.title,tokens[0]);
|
|
204
|
+
const desc = document.createElement('span');
|
|
205
|
+
const excerpt = item.text.split(' · ').find(text => tokens.length && tokens.some(token => normalize(text).includes(token))) ?? item.text.split(' · ')[0];
|
|
206
|
+
addHighlighted(desc,excerpt,tokens[0]);
|
|
207
|
+
link.append(label,title,desc);
|
|
208
|
+
results.append(link);
|
|
209
|
+
}
|
|
210
|
+
results.scrollTop = 0;
|
|
211
|
+
}
|
|
212
|
+
function open(trigger) {
|
|
213
|
+
if (dialog.open) return;
|
|
214
|
+
restoreFocus = trigger instanceof HTMLElement ? trigger : opener;
|
|
215
|
+
input.value = '';
|
|
216
|
+
showResults();
|
|
217
|
+
dialog.showModal();
|
|
218
|
+
input.focus();
|
|
219
|
+
}
|
|
220
|
+
opener.addEventListener('click', () => open(opener));
|
|
221
|
+
one('[data-close-search]').addEventListener('click', () => dialog.close());
|
|
222
|
+
dialog.addEventListener('close', () => restoreFocus?.focus({ preventScroll:true }));
|
|
223
|
+
dialog.addEventListener('click', event => {
|
|
224
|
+
if (event.target !== dialog) return;
|
|
225
|
+
const box = dialog.getBoundingClientRect();
|
|
226
|
+
if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) dialog.close();
|
|
227
|
+
});
|
|
228
|
+
document.addEventListener('keydown', event => {
|
|
229
|
+
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
|
|
230
|
+
event.preventDefault();
|
|
231
|
+
if (dialog.open) dialog.close(); else open(document.activeElement === document.body ? opener : document.activeElement);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
input.addEventListener('input',showResults);
|
|
235
|
+
dialog.addEventListener('keydown', event => {
|
|
236
|
+
if (event.key === 'Escape') {
|
|
237
|
+
event.preventDefault();
|
|
238
|
+
dialog.close();
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const links = [...results.querySelectorAll('a')];
|
|
242
|
+
if (!links.length) return;
|
|
243
|
+
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
244
|
+
event.preventDefault();
|
|
245
|
+
const start = links.indexOf(document.activeElement);
|
|
246
|
+
if (start >= 0) selected = start;
|
|
247
|
+
selected = event.key === 'ArrowDown' ? (selected + 1) % links.length : (selected <= 0 ? links.length - 1 : selected - 1);
|
|
248
|
+
links.forEach((link,index) => link.classList.toggle('is-selected',index === selected));
|
|
249
|
+
links[selected].focus({preventScroll:true});
|
|
250
|
+
links[selected].scrollIntoView({block:'nearest'});
|
|
251
|
+
} else if (event.key === 'Enter' && event.target === input) {
|
|
252
|
+
event.preventDefault(); links[0].click();
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
results.addEventListener('click', event => { if (event.target.closest('a')) dialog.close(); });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
initTheme();
|
|
259
|
+
initCatalog();
|
|
260
|
+
initTimeline();
|
|
261
|
+
initSearch();
|
|
262
|
+
})();
|