diff --git a/.prettierrc.json b/.prettierrc.json
new file mode 100644
index 0000000..6f356b6
--- /dev/null
+++ b/.prettierrc.json
@@ -0,0 +1,11 @@
+{
+ "plugins": ["prettier-plugin-astro"],
+ "singleQuote": true,
+ "printWidth": 100,
+ "overrides": [
+ {
+ "files": "*.astro",
+ "options": { "parser": "astro" }
+ }
+ ]
+}
diff --git a/package-lock.json b/package-lock.json
index b32240e..6a4179c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15,8 +15,19 @@
"rehype-mathjax": "^7.1.0",
"remark-math": "^6.0.0",
"typesense": "^3.3.0"
+ },
+ "devDependencies": {
+ "prettier": "3.10.1",
+ "prettier-plugin-astro": "0.14.1"
}
},
+ "node_modules/@astrojs/compiler": {
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/@astrojs/compiler/-/compiler-2.13.1.tgz",
+ "integrity": "sha512-f3FN83d2G/v32ipNClRKgYv30onQlMZX1vCeZMjPsMMPl1mDpmbl0+N5BYo4S/ofzqJyS5hvwacEo0CCVDn/Qg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@astrojs/compiler-binding": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@astrojs/compiler-binding/-/compiler-binding-0.5.3.tgz",
@@ -5517,6 +5528,37 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/prettier": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.10.1.tgz",
+ "integrity": "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "prettier": "bin/prettier.cjs"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/prettier/prettier?sponsor=1"
+ }
+ },
+ "node_modules/prettier-plugin-astro": {
+ "version": "0.14.1",
+ "resolved": "https://registry.npmjs.org/prettier-plugin-astro/-/prettier-plugin-astro-0.14.1.tgz",
+ "integrity": "sha512-RiBETaaP9veVstE4vUwSIcdATj6dKmXljouXc/DDNwBSPTp8FRkLGDSGFClKsAFeeg+13SB0Z1JZvbD76bigJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@astrojs/compiler": "^2.9.1",
+ "prettier": "^3.0.0",
+ "sass-formatter": "^0.7.6"
+ },
+ "engines": {
+ "node": "^14.15.0 || >=16.0.0"
+ }
+ },
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
@@ -5943,6 +5985,23 @@
"@rolldown/binding-win32-x64-msvc": "1.2.16"
}
},
+ "node_modules/s.color": {
+ "version": "0.0.15",
+ "resolved": "https://registry.npmjs.org/s.color/-/s.color-0.0.15.tgz",
+ "integrity": "sha512-AUNrbEUHeKY8XsYr/DYpl+qk5+aM+DChopnWOPEzn8YKzOhv4l2zH6LzZms3tOZP3wwdOyc0RmTciyi46HLIuA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/sass-formatter": {
+ "version": "0.7.9",
+ "resolved": "https://registry.npmjs.org/sass-formatter/-/sass-formatter-0.7.9.tgz",
+ "integrity": "sha512-CWZ8XiSim+fJVG0cFLStwDvft1VI7uvXdCNJYXhDvowiv+DsbD1nXLiQ4zrE5UBvj5DWZJ93cwN0NX5PMsr1Pw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "suf-log": "^2.5.3"
+ }
+ },
"node_modules/satteri": {
"version": "0.11.7",
"resolved": "https://registry.npmjs.org/satteri/-/satteri-0.11.7.tgz",
@@ -6202,6 +6261,16 @@
"inline-style-parser": "0.2.7"
}
},
+ "node_modules/suf-log": {
+ "version": "2.5.3",
+ "resolved": "https://registry.npmjs.org/suf-log/-/suf-log-2.5.3.tgz",
+ "integrity": "sha512-KvC8OPjzdNOe+xQ4XWJV2whQA0aM1kGVczMQ8+dStAO6KfEB140JEVQ9dE76ONZ0/Ylf67ni4tILPJB41U0eow==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "s.color": "0.0.15"
+ }
+ },
"node_modules/svgo": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/svgo/-/svgo-4.1.0.tgz",
diff --git a/package.json b/package.json
index 020f508..7da8dc5 100644
--- a/package.json
+++ b/package.json
@@ -3,6 +3,8 @@
"version": "3.1.1",
"private": true,
"scripts": {
+ "format": "prettier --write \"*.mjs\" \"{public,scripts,src,workers}/**/*.{astro,css,js,mjs,ts}\"",
+ "format:check": "prettier --check \"*.mjs\" \"{public,scripts,src,workers}/**/*.{astro,css,js,mjs,ts}\"",
"prebuild": "node scripts/generate-abbrlinks.mjs",
"build": "astro build",
"postbuild": "node scripts/version-service-worker.mjs",
@@ -19,5 +21,9 @@
"rehype-mathjax": "^7.1.0",
"remark-math": "^6.0.0",
"typesense": "^3.3.0"
+ },
+ "devDependencies": {
+ "prettier": "3.10.1",
+ "prettier-plugin-astro": "0.14.1"
}
}
diff --git a/public/js/external-links.js b/public/js/external-links.js
index 4c9ad82..acb5842 100644
--- a/public/js/external-links.js
+++ b/public/js/external-links.js
@@ -25,7 +25,15 @@
document.addEventListener('click', (event) => {
const anchor = event.target.closest?.('a[href]');
if (!anchor) return;
- if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ if (
+ event.defaultPrevented ||
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ )
+ return;
const externalUrl = getExternalUrl(anchor);
if (!externalUrl) return;
diff --git a/public/js/pwa.js b/public/js/pwa.js
index 465f9cc..24bf90d 100644
--- a/public/js/pwa.js
+++ b/public/js/pwa.js
@@ -39,7 +39,13 @@
installPrompt = event;
if (!installDismissedRecently()) {
window.setTimeout(() => {
- if (installPrompt) showToast('install', '安装 Bi\'s Blog', '添加到桌面,像应用一样打开并阅读缓存过的文章。', '立即安装');
+ if (installPrompt)
+ showToast(
+ 'install',
+ "安装 Bi's Blog",
+ '添加到桌面,像应用一样打开并阅读缓存过的文章。',
+ '立即安装',
+ );
}, 2500);
}
});
@@ -69,7 +75,9 @@
close?.addEventListener('click', () => {
if (toastMode === 'install') {
- try { localStorage.setItem('pwa-install-dismissed-at', String(Date.now())); } catch {}
+ try {
+ localStorage.setItem('pwa-install-dismissed-at', String(Date.now()));
+ } catch {}
}
hideToast();
});
@@ -78,24 +86,27 @@
if (refreshing) window.location.reload();
});
- navigator.serviceWorker.register('/sw.js', { scope: '/' }).then((registration) => {
- if (registration.waiting && navigator.serviceWorker.controller) {
- waitingWorker = registration.waiting;
- showToast('update', '发现新版本', '刷新后即可使用博客的最新内容和功能。', '立即更新');
- }
+ navigator.serviceWorker
+ .register('/sw.js', { scope: '/' })
+ .then((registration) => {
+ if (registration.waiting && navigator.serviceWorker.controller) {
+ waitingWorker = registration.waiting;
+ showToast('update', '发现新版本', '刷新后即可使用博客的最新内容和功能。', '立即更新');
+ }
- registration.addEventListener('updatefound', () => {
- const worker = registration.installing;
- worker?.addEventListener('statechange', () => {
- if (worker.state === 'installed' && navigator.serviceWorker.controller) {
- waitingWorker = worker;
- showToast('update', '发现新版本', '刷新后即可使用博客的最新内容和功能。', '立即更新');
- }
+ registration.addEventListener('updatefound', () => {
+ const worker = registration.installing;
+ worker?.addEventListener('statechange', () => {
+ if (worker.state === 'installed' && navigator.serviceWorker.controller) {
+ waitingWorker = worker;
+ showToast('update', '发现新版本', '刷新后即可使用博客的最新内容和功能。', '立即更新');
+ }
+ });
});
+ })
+ .catch((error) => {
+ console.warn('PWA registration failed:', error);
});
- }).catch((error) => {
- console.warn('PWA registration failed:', error);
- });
const params = new URLSearchParams(window.location.search);
if (params.get('action') === 'search') {
diff --git a/public/js/random.js b/public/js/random.js
index 91d37b5..af0074f 100644
--- a/public/js/random.js
+++ b/public/js/random.js
@@ -1,14 +1,15 @@
function randomPost(trigger) {
- const source = trigger instanceof Element
- ? trigger
- : document.activeElement?.closest?.('.nav-random, [onclick*="randomPost"]');
- const overlay = document.createElement('div');
- const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ const source =
+ trigger instanceof Element
+ ? trigger
+ : document.activeElement?.closest?.('.nav-random, [onclick*="randomPost"]');
+ const overlay = document.createElement('div');
+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
- overlay.className = 'random-post-transition';
- overlay.setAttribute('role', 'status');
- overlay.setAttribute('aria-live', 'polite');
- overlay.innerHTML = `
+ overlay.className = 'random-post-transition';
+ overlay.setAttribute('role', 'status');
+ overlay.setAttribute('aria-live', 'polite');
+ overlay.innerHTML = `
@@ -16,78 +17,86 @@ function randomPost(trigger) {
`;
- source?.classList.add('is-randomizing');
- source?.setAttribute('aria-busy', 'true');
- document.body.appendChild(overlay);
- requestAnimationFrame(() => overlay.classList.add('is-visible'));
+ source?.classList.add('is-randomizing');
+ source?.setAttribute('aria-busy', 'true');
+ document.body.appendChild(overlay);
+ requestAnimationFrame(() => overlay.classList.add('is-visible'));
- const finish = href => {
- const delay = reduceMotion ? 80 : 1250;
- window.setTimeout(() => {
- location.href = href;
- }, delay);
- };
+ const finish = (href) => {
+ const delay = reduceMotion ? 80 : 1250;
+ window.setTimeout(() => {
+ location.href = href;
+ }, delay);
+ };
- const startCardFlight = posts => {
- if (reduceMotion) return;
+ const startCardFlight = (posts) => {
+ if (reduceMotion) return;
- const flight = overlay.querySelector('.random-post-flight');
- if (!flight) return;
+ const flight = overlay.querySelector('.random-post-flight');
+ if (!flight) return;
- const candidates = posts
- .filter(post => post && typeof post.href === 'string' && post.href.startsWith('/posts/'))
- .map(post => ({
- title: typeof post.title === 'string' && post.title.trim() ? post.title.trim() : '\u672a\u547d\u540d\u6587\u7ae0',
- meta: typeof post.category === 'string' && post.category.trim() ? post.category.trim() : '\u968f\u673a\u6587\u7ae0',
- }));
+ const candidates = posts
+ .filter((post) => post && typeof post.href === 'string' && post.href.startsWith('/posts/'))
+ .map((post) => ({
+ title:
+ typeof post.title === 'string' && post.title.trim()
+ ? post.title.trim()
+ : '\u672a\u547d\u540d\u6587\u7ae0',
+ meta:
+ typeof post.category === 'string' && post.category.trim()
+ ? post.category.trim()
+ : '\u968f\u673a\u6587\u7ae0',
+ }));
- const pool = candidates.length ? candidates : [{ title: '\u968f\u673a\u6587\u7ae0', meta: '\u6b63\u5728\u62bd\u53d6' }];
- const count = Math.min(9, Math.max(5, pool.length));
+ const pool = candidates.length
+ ? candidates
+ : [{ title: '\u968f\u673a\u6587\u7ae0', meta: '\u6b63\u5728\u62bd\u53d6' }];
+ const count = Math.min(9, Math.max(5, pool.length));
- for (let index = 0; index < count; index += 1) {
- const post = pool[Math.floor(Math.random() * pool.length)];
- const card = document.createElement('div');
- card.className = 'random-post-flying-card';
- card.style.setProperty('--flight-delay', `${index * 0.11}s`);
- card.style.setProperty('--flight-y', `${-42 + Math.random() * 84}px`);
- card.style.setProperty('--flight-rotate', `${-8 + Math.random() * 16}deg`);
- const meta = document.createElement('small');
- const title = document.createElement('strong');
- meta.textContent = post.meta;
- title.textContent = post.title;
- card.append(meta, title);
- flight.appendChild(card);
- }
- };
+ for (let index = 0; index < count; index += 1) {
+ const post = pool[Math.floor(Math.random() * pool.length)];
+ const card = document.createElement('div');
+ card.className = 'random-post-flying-card';
+ card.style.setProperty('--flight-delay', `${index * 0.11}s`);
+ card.style.setProperty('--flight-y', `${-42 + Math.random() * 84}px`);
+ card.style.setProperty('--flight-rotate', `${-8 + Math.random() * 16}deg`);
+ const meta = document.createElement('small');
+ const title = document.createElement('strong');
+ meta.textContent = post.meta;
+ title.textContent = post.title;
+ card.append(meta, title);
+ flight.appendChild(card);
+ }
+ };
- const reset = () => {
- source?.classList.remove('is-randomizing');
- source?.removeAttribute('aria-busy');
- overlay.classList.remove('is-visible');
- window.setTimeout(() => overlay.remove(), reduceMotion ? 0 : 180);
- };
+ const reset = () => {
+ source?.classList.remove('is-randomizing');
+ source?.removeAttribute('aria-busy');
+ overlay.classList.remove('is-visible');
+ window.setTimeout(() => overlay.remove(), reduceMotion ? 0 : 180);
+ };
- fetch('/api/posts.json')
- .then(res => {
- if (!res.ok) throw new Error(`Failed to load posts: ${res.status}`);
- return res.json();
- })
- .then(posts => {
- const postLinks = posts
- .map(post => post && post.href)
- .filter(href => typeof href === 'string' && href.startsWith('/posts/'));
+ fetch('/api/posts.json')
+ .then((res) => {
+ if (!res.ok) throw new Error(`Failed to load posts: ${res.status}`);
+ return res.json();
+ })
+ .then((posts) => {
+ const postLinks = posts
+ .map((post) => post && post.href)
+ .filter((href) => typeof href === 'string' && href.startsWith('/posts/'));
- if (postLinks.length === 0) {
- console.warn('No posts available for random navigation.');
- reset();
- return;
- }
+ if (postLinks.length === 0) {
+ console.warn('No posts available for random navigation.');
+ reset();
+ return;
+ }
- startCardFlight(posts);
- finish(postLinks[Math.floor(Math.random() * postLinks.length)]);
- })
- .catch(error => {
- console.error('Random post navigation failed:', error);
- reset();
- });
+ startCardFlight(posts);
+ finish(postLinks[Math.floor(Math.random() * postLinks.length)]);
+ })
+ .catch((error) => {
+ console.error('Random post navigation failed:', error);
+ reset();
+ });
}
diff --git a/public/js/search/typesense-search.js b/public/js/search/typesense-search.js
index 94f9436..20aed5e 100644
--- a/public/js/search/typesense-search.js
+++ b/public/js/search/typesense-search.js
@@ -7,14 +7,25 @@
const CONFIG = window.SITE_CONFIG?.search;
const assets = document.currentScript?.dataset || {};
let dependenciesPromise;
- const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
- const safeHighlight = (value) => String(value ?? '').split(/(<\/?mark>)/i)
- .map((part) => /^<\/?mark>$/i.test(part) ? part.toLowerCase() : escapeHtml(part)).join('');
+ const escapeHtml = (value) =>
+ String(value ?? '').replace(
+ /[&<>"']/g,
+ (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char],
+ );
+ const safeHighlight = (value) =>
+ String(value ?? '')
+ .split(/(<\/?mark>)/i)
+ .map((part) => (/^<\/?mark>$/i.test(part) ? part.toLowerCase() : escapeHtml(part)))
+ .join('');
function safeResultUrl(value) {
try {
const url = new URL(value, location.origin);
- return url.origin === location.origin && /^\/posts\//.test(url.pathname) ? url.pathname + url.search + url.hash : '';
- } catch { return ''; }
+ return url.origin === location.origin && /^\/posts\//.test(url.pathname)
+ ? url.pathname + url.search + url.hash
+ : '';
+ } catch {
+ return '';
+ }
}
function loadDependencies() {
if (dependenciesPromise) return dependenciesPromise;
@@ -22,14 +33,18 @@
css.rel = 'stylesheet';
css.href = assets.searchCss;
document.head.appendChild(css);
- const loadScript = (src) => new Promise((resolve, reject) => {
- const script = document.createElement('script');
- script.src = src;
- script.onload = resolve;
- script.onerror = () => reject(new Error('搜索依赖加载失败'));
- document.head.appendChild(script);
- });
- dependenciesPromise = Promise.all([loadScript(assets.searchJs), loadScript(assets.adapterJs)]).catch((error) => {
+ const loadScript = (src) =>
+ new Promise((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = src;
+ script.onload = resolve;
+ script.onerror = () => reject(new Error('搜索依赖加载失败'));
+ document.head.appendChild(script);
+ });
+ dependenciesPromise = Promise.all([
+ loadScript(assets.searchJs),
+ loadScript(assets.adapterJs),
+ ]).catch((error) => {
dependenciesPromise = null;
css.remove();
throw error;
@@ -59,15 +74,15 @@
function showErrorMessage() {
const hitsContainer = document.getElementById('hits');
if (!hitsContainer) return;
-
- hitsContainer.innerHTML =
+
+ hitsContainer.innerHTML =
'' +
- '
' +
- '
搜索服务加载失败
' +
- '
请检查网络连接后重试。
' +
- '
' +
- '' +
- '
' +
+ '
' +
+ '
搜索服务加载失败
' +
+ '
请检查网络连接后重试。
' +
+ '
' +
+ '' +
+ '
' +
'
';
}
@@ -330,13 +345,15 @@
container.focus();
if (!isInitialized) {
- loadDependencies().then(() => {
- initTypesense();
- if (isSearchOpen) focusSearchInput();
- }).catch((error) => {
- console.error(error);
- showErrorMessage();
- });
+ loadDependencies()
+ .then(() => {
+ initTypesense();
+ if (isSearchOpen) focusSearchInput();
+ })
+ .catch((error) => {
+ console.error(error);
+ showErrorMessage();
+ });
}
focusSearchInput();
}
@@ -347,7 +364,7 @@
mask.classList.remove('active');
document.body.style.overflow = previousOverflow;
if (previousFocus instanceof HTMLElement) previousFocus.focus();
- closeTimer = setTimeout(function() {
+ closeTimer = setTimeout(function () {
if (isSearchOpen) return;
mask.style.display = 'none';
closeTimer = null;
@@ -362,7 +379,7 @@
input.focus();
input.select();
} else if (!input && retryCount < (CONFIG.ui.maxRetries || 10)) {
- setTimeout(function() {
+ setTimeout(function () {
focusSearchInput(retryCount + 1);
}, CONFIG.ui.retryDelay || 100);
}
@@ -371,7 +388,7 @@
// ============================================================================
// 事件监听
// ============================================================================
- document.addEventListener('click', function(e) {
+ document.addEventListener('click', function (e) {
if (e.target.closest('.search-typesense-trigger')) {
e.preventDefault();
openSearch();
@@ -379,13 +396,13 @@
});
closeBtn.addEventListener('click', closeSearch);
- mask.addEventListener('click', function(e) {
+ mask.addEventListener('click', function (e) {
if (e.target === mask) closeSearch();
});
- container.addEventListener('click', function(e) {
+ container.addEventListener('click', function (e) {
e.stopPropagation();
});
- window.addEventListener('keydown', function(e) {
+ window.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && isSearchOpen) {
closeSearch();
}
@@ -394,15 +411,27 @@
openSearch();
}
if (e.key === 'Tab' && isSearchOpen) {
- const focusable = [...container.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])')]
- .filter((element) => element.getClientRects().length);
- if (!focusable.length) { e.preventDefault(); container.focus(); return; }
+ const focusable = [
+ ...container.querySelectorAll(
+ 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ ),
+ ].filter((element) => element.getClientRects().length);
+ if (!focusable.length) {
+ e.preventDefault();
+ container.focus();
+ return;
+ }
const first = focusable[0];
const last = focusable[focusable.length - 1];
- if (e.shiftKey && (document.activeElement === first || document.activeElement === container)) {
- e.preventDefault(); last.focus();
+ if (
+ e.shiftKey &&
+ (document.activeElement === first || document.activeElement === container)
+ ) {
+ e.preventDefault();
+ last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
- e.preventDefault(); first.focus();
+ e.preventDefault();
+ first.focus();
}
}
});
@@ -417,16 +446,17 @@
}
var instantsearchLoaded = typeof instantsearch !== 'undefined';
- var adapterLoaded = typeof TypesenseInstantSearchAdapter !== 'undefined' ||
- typeof window.TypesenseInstantSearchAdapter !== 'undefined';
-
+ var adapterLoaded =
+ typeof TypesenseInstantSearchAdapter !== 'undefined' ||
+ typeof window.TypesenseInstantSearchAdapter !== 'undefined';
+
console.log('📦 依赖库检查 (' + (initRetryCount + 1) + '/' + MAX_INIT_RETRIES + '):');
console.log(' instantsearch.js:', instantsearchLoaded ? '✅ 已加载' : '❌ 未加载');
console.log(' TypesenseAdapter:', adapterLoaded ? '✅ 已加载' : '❌ 未加载');
-
+
if (!instantsearchLoaded || !adapterLoaded) {
initRetryCount++;
-
+
if (initRetryCount >= MAX_INIT_RETRIES) {
console.error('');
console.error('❌ Typesense 依赖库加载失败!');
@@ -436,8 +466,12 @@
console.error('');
console.error('inject:');
console.error(' bottom: # ⚠️ 使用 bottom 而不是 head');
- console.error(' - ');
- console.error(' - ');
+ console.error(
+ ' - ',
+ );
+ console.error(
+ ' - ',
+ );
console.error(' - ');
console.error('');
console.error('💡 或在控制台手动检查:');
@@ -445,16 +479,16 @@
console.error(' typeof TypesenseInstantSearchAdapter');
console.error('');
console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
-
+
showErrorMessage();
return;
}
-
+
console.warn('⏳ 100ms 后重试...');
setTimeout(initTypesense, 100);
return;
}
-
+
initRetryCount = 0;
console.log('🚀 开始初始化 Typesense...');
@@ -462,20 +496,22 @@
const typesenseAdapter = new TypesenseInstantSearchAdapter({
server: {
apiKey: CONFIG.apiKey,
- nodes: [{
- host: CONFIG.server.host,
- port: CONFIG.server.port,
- protocol: CONFIG.server.protocol
- }],
- cacheSearchResultsForSeconds: 120
+ nodes: [
+ {
+ host: CONFIG.server.host,
+ port: CONFIG.server.port,
+ protocol: CONFIG.server.protocol,
+ },
+ ],
+ cacheSearchResultsForSeconds: 120,
},
- additionalSearchParameters: CONFIG.searchParams
+ additionalSearchParameters: CONFIG.searchParams,
});
searchInstance = instantsearch({
searchClient: typesenseAdapter.searchClient,
indexName: CONFIG.indexName,
- routing: false
+ routing: false,
});
searchInstance.addWidgets([
@@ -485,64 +521,79 @@
autofocus: false,
showReset: true,
showSubmit: false,
- showLoadingIndicator: true
+ showLoadingIndicator: true,
}),
instantsearch.widgets.stats({
container: '#stats',
templates: {
- text: function(data) {
+ text: function (data) {
if (!data.query) return '';
- return '找到 ' + data.nbHits + ' 条结果 (' + data.processingTimeMS + 'ms)';
- }
- }
+ return (
+ '找到 ' + data.nbHits + ' 条结果 (' + data.processingTimeMS + 'ms)'
+ );
+ },
+ },
}),
instantsearch.widgets.hits({
container: '#hits',
templates: {
- empty: function(results) {
- return '' +
+ empty: function (results) {
+ return (
+ '
' +
'
' +
- '
找不到与 "' + escapeHtml(results.query) + '" 相关的内容
' +
+ '
找不到与 "' +
+ escapeHtml(results.query) +
+ '" 相关的内容
' +
'
试试其他关键词吧 (´·ω·`)
' +
- '
';
+ '
'
+ );
},
- item: function(hit) {
+ item: function (hit) {
// 使用 _highlightResult 获取高亮文本
- var titleHighlight = hit._highlightResult && hit._highlightResult.title
- ? hit._highlightResult.title.value
- : (hit.title || '');
-
- var contentHighlight = hit._highlightResult && hit._highlightResult.content
- ? hit._highlightResult.content.value
- : (hit.content || '');
-
+ var titleHighlight =
+ hit._highlightResult && hit._highlightResult.title
+ ? hit._highlightResult.title.value
+ : hit.title || '';
+
+ var contentHighlight =
+ hit._highlightResult && hit._highlightResult.content
+ ? hit._highlightResult.content.value
+ : hit.content || '';
+
// 截取内容长度
if (contentHighlight.length > 200) {
contentHighlight = contentHighlight.substring(0, 200) + '...';
}
-
+
const url = safeResultUrl(hit.url);
if (!url) return '';
- return '' +
- '' + safeHighlight(titleHighlight) + '
' +
- '' + safeHighlight(contentHighlight) + '
' +
- '';
- }
- }
+ return (
+ '' +
+ '' +
+ safeHighlight(titleHighlight) +
+ '
' +
+ '' +
+ safeHighlight(contentHighlight) +
+ '
' +
+ ''
+ );
+ },
+ },
}),
instantsearch.widgets.pagination({
container: '#pagination',
padding: 2,
showFirst: false,
- showLast: false
- })
+ showLast: false,
+ }),
]);
searchInstance.start();
isInitialized = true;
-
- console.log('✅ Typesense 初始化成功!');
+ console.log('✅ Typesense 初始化成功!');
} catch (error) {
console.error('❌ 初始化失败:', error);
showErrorMessage();
@@ -569,8 +620,11 @@
window.TypesenseSearch = {
open: openSearch,
close: closeSearch,
- isOpen: function() { return isSearchOpen; },
- getInstance: function() { return searchInstance; }
+ isOpen: function () {
+ return isSearchOpen;
+ },
+ getInstance: function () {
+ return searchInstance;
+ },
};
-
})();
diff --git a/public/js/shuoshuo.js b/public/js/shuoshuo.js
index 32b3983..4f91671 100644
--- a/public/js/shuoshuo.js
+++ b/public/js/shuoshuo.js
@@ -1,243 +1,258 @@
function renderTalks() {
- const talkContainer = document.querySelector('#talk');
- if (!talkContainer) return;
- const config = window.SITE_CONFIG?.talks || {};
- const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
- const safeUrl = (value) => {
- try {
- const url = new URL(value, window.location.origin);
- return ['http:', 'https:'].includes(url.protocol) ? url.href : '';
- } catch { return ''; }
- };
- talkContainer.innerHTML = '';
- const generateIconSVG = () => {
- return ``;
+ const talkContainer = document.querySelector('#talk');
+ if (!talkContainer) return;
+ const config = window.SITE_CONFIG?.talks || {};
+ const escapeHtml = (value) =>
+ String(value ?? '').replace(
+ /[&<>"']/g,
+ (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char],
+ );
+ const safeUrl = (value) => {
+ try {
+ const url = new URL(value, window.location.origin);
+ return ['http:', 'https:'].includes(url.protocol) ? url.href : '';
+ } catch {
+ return '';
+ }
+ };
+ talkContainer.innerHTML = '';
+ const generateIconSVG = () => {
+ return ``;
+ };
+ const waterfall = (a) => {
+ function b(a, b) {
+ var c = window.getComputedStyle(b);
+ return parseFloat(c['margin' + a]) || 0;
}
- const waterfall = (a) => {
- function b(a, b) {
- var c = window.getComputedStyle(b);
- return parseFloat(c["margin" + a]) || 0
- }
- function c(a) {
- return a + "px"
- }
+ function c(a) {
+ return a + 'px';
+ }
- function d(a) {
- return parseFloat(a.style.top)
- }
+ function d(a) {
+ return parseFloat(a.style.top);
+ }
- function e(a) {
- return parseFloat(a.style.left)
- }
+ function e(a) {
+ return parseFloat(a.style.left);
+ }
- function f(a) {
- return a.clientWidth
- }
+ function f(a) {
+ return a.clientWidth;
+ }
- function g(a) {
- return a.clientHeight
- }
+ function g(a) {
+ return a.clientHeight;
+ }
- function h(a) {
- return d(a) + g(a) + b("Bottom", a)
- }
+ function h(a) {
+ return d(a) + g(a) + b('Bottom', a);
+ }
- function i(a) {
- return e(a) + f(a) + b("Right", a)
- }
+ function i(a) {
+ return e(a) + f(a) + b('Right', a);
+ }
- function j(a) {
- a = a.sort(function (a, b) {
- return h(a) === h(b) ? e(b) - e(a) : h(b) - h(a)
- })
- }
+ function j(a) {
+ a = a.sort(function (a, b) {
+ return h(a) === h(b) ? e(b) - e(a) : h(b) - h(a);
+ });
+ }
- function k(b) {
- f(a) != t && (b.target.removeEventListener(b.type, arguments.callee), waterfall(a))
- }
- "string" == typeof a && (a = document.querySelector(a));
- var l = [].map.call(a.children, function (a) {
- return a.style.position = "absolute", a
- });
- a.style.position = "relative";
- var m = [];
- l.length && (l[0].style.top = "0px", l[0].style.left = c(b("Left", l[0])), m.push(l[0]));
- for (var n = 1; n < l.length; n++) {
- var o = l[n - 1],
- p = l[n],
- q = i(o) + f(p) <= f(a);
- if (!q) break;
- p.style.top = o.style.top, p.style.left = c(i(o) + b("Left", p)), m.push(p)
- }
- for (; n < l.length; n++) {
- j(m);
- var p = l[n],
- r = m.pop();
- p.style.top = c(h(r) + b("Top", p)), p.style.left = c(e(r)), m.push(p)
- }
- j(m);
- var s = m[0];
- a.style.height = c(h(s) + b("Bottom", s));
- var t = f(a);
- window.addEventListener ? window.addEventListener("resize", k) : document.body.onresize = k
- };
+ function k(b) {
+ f(a) != t && (b.target.removeEventListener(b.type, arguments.callee), waterfall(a));
+ }
+ 'string' == typeof a && (a = document.querySelector(a));
+ var l = [].map.call(a.children, function (a) {
+ return ((a.style.position = 'absolute'), a);
+ });
+ a.style.position = 'relative';
+ var m = [];
+ l.length && ((l[0].style.top = '0px'), (l[0].style.left = c(b('Left', l[0]))), m.push(l[0]));
+ for (var n = 1; n < l.length; n++) {
+ var o = l[n - 1],
+ p = l[n],
+ q = i(o) + f(p) <= f(a);
+ if (!q) break;
+ ((p.style.top = o.style.top), (p.style.left = c(i(o) + b('Left', p))), m.push(p));
+ }
+ for (; n < l.length; n++) {
+ j(m);
+ var p = l[n],
+ r = m.pop();
+ ((p.style.top = c(h(r) + b('Top', p))), (p.style.left = c(e(r))), m.push(p));
+ }
+ j(m);
+ var s = m[0];
+ a.style.height = c(h(s) + b('Bottom', s));
+ var t = f(a);
+ window.addEventListener ? window.addEventListener('resize', k) : (document.body.onresize = k);
+ };
- const fetchAndRenderTalks = () => {
- const url = config.apiUrl;
- if (!url) return;
- const cacheKey = config.cacheKey || 'talksCache';
- const cacheTimeKey = config.cacheTimeKey || 'talksCacheTime';
- const cacheDuration = config.cacheDurationMs || 30 * 60 * 1000;
- let cachedData = null;
- let cachedTime = 0;
- try {
- const parsed = JSON.parse(localStorage.getItem(cacheKey) || 'null');
- if (Array.isArray(parsed)) cachedData = parsed;
- cachedTime = Number(localStorage.getItem(cacheTimeKey)) || 0;
- } catch { /* Cache is optional. */ }
- const now = Date.now();
+ const fetchAndRenderTalks = () => {
+ const url = config.apiUrl;
+ if (!url) return;
+ const cacheKey = config.cacheKey || 'talksCache';
+ const cacheTimeKey = config.cacheTimeKey || 'talksCacheTime';
+ const cacheDuration = config.cacheDurationMs || 30 * 60 * 1000;
+ let cachedData = null;
+ let cachedTime = 0;
+ try {
+ const parsed = JSON.parse(localStorage.getItem(cacheKey) || 'null');
+ if (Array.isArray(parsed)) cachedData = parsed;
+ cachedTime = Number(localStorage.getItem(cacheTimeKey)) || 0;
+ } catch {
+ /* Cache is optional. */
+ }
+ const now = Date.now();
- if (cachedData && cachedTime && (now - cachedTime < cacheDuration)) {
- renderTalksList(cachedData);
- } else {
- fetch(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ page: 1, pageSize: config.pageSize || 30 })
- })
- .then(res => {
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
- })
- .then(data => {
- if (data.code === 1 && data.data && Array.isArray(data.data.items)) {
- try {
- localStorage.setItem(cacheKey, JSON.stringify(data.data.items));
- localStorage.setItem(cacheTimeKey, now.toString());
- } catch { /* Rendering does not depend on cache availability. */ }
- renderTalksList(data.data.items);
- } else throw new Error('Unexpected API response format');
- })
- .catch(err => {
- console.warn('说说加载失败:', err);
- if (cachedData) renderTalksList(cachedData);
- else talkContainer.textContent = '说说暂时无法加载,请稍后再试。';
- });
- }
- };
-
- const renderTalksList = (list) => {
- list.map(formatTalk).forEach(item => talkContainer.appendChild(generateTalkElement(item)));
- if (list.length) waterfall('#talk');
- else talkContainer.textContent = '暂无说说。';
- };
-
- const withImageParams = (url) => {
- if (!url) return '';
- try {
- const parsedUrl = new URL(url, window.location.origin);
- if (!parsedUrl.searchParams.has('fmt')) parsedUrl.searchParams.set('fmt', 'webp');
- if (!parsedUrl.searchParams.has('q')) parsedUrl.searchParams.set('q', '75');
- return safeUrl(parsedUrl.toString());
- } catch {
- return '';
- }
- };
-
- const getImageUrl = (image) => {
- if (!image) return '';
- if (typeof image === 'string') return image;
- return image.image_url || image.url || image.src || image.file?.url || '';
- };
-
- const getTalkImages = (item) => {
- if (Array.isArray(item.images) && item.images.length > 0) {
- return item.images.map(getImageUrl).filter(Boolean);
- }
-
- if (Array.isArray(item.echo_files) && item.echo_files.length > 0) {
- return item.echo_files
- .map((echoFile) => getImageUrl(echoFile.file || echoFile))
- .filter(Boolean);
- }
-
- return [];
- };
-
- const formatTalk = (item) => {
- const date = formatTime(item.created_at);
- let content = escapeHtml(item.content || '');
- content = content.replace(/\[(.*?)\]\((.*?)\)/g, (match, label, href) => {
- const url = safeUrl(href);
- return url ? `@${label}` : label;
+ if (cachedData && cachedTime && now - cachedTime < cacheDuration) {
+ renderTalksList(cachedData);
+ } else {
+ fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ page: 1, pageSize: config.pageSize || 30 }),
+ })
+ .then((res) => {
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
})
- .replace(/- \[ \]/g, '⚪')
- .replace(/- \[x\]/g, '⚫')
- .replace(/\n/g, '
');
- content = `${content}
`;
-
- // 图片
- const images = getTalkImages(item);
- if (images.length > 0) {
- const imgDiv = document.createElement('div');
- imgDiv.className = 'zone_imgbox';
- images.forEach(url => {
- const imageUrl = withImageParams(url);
- if (!imageUrl) return;
- const link = document.createElement('a');
- link.href = imageUrl;
- link.setAttribute('data-fancybox', 'gallery');
- link.className = 'fancybox';
- const imgTag = document.createElement('img');
- imgTag.src = imageUrl;
- imgTag.loading = 'lazy';
- imgTag.alt = '';
- link.appendChild(imgTag);
- imgDiv.appendChild(link);
- });
- content += imgDiv.outerHTML;
- }
-
- // 外链 / GitHub 项目
- // 外链 / GitHub 项目
- if (['WEBSITE', 'GITHUBPROJ'].includes(item.extension_type)) {
- let siteUrl = '', title = '';
- let extensionBack = "https://pic.biss.click/image/1971bdc1-4349-4bb9-b683-20404f5da7d7.webp";
-
- // 解析 extension 字段
+ .then((data) => {
+ if (data.code === 1 && data.data && Array.isArray(data.data.items)) {
try {
- const extObj = typeof item.extension === 'string' ? JSON.parse(item.extension) : item.extension;
- siteUrl = extObj.site || extObj.url || item.extension;
- title = extObj.title || siteUrl;
+ localStorage.setItem(cacheKey, JSON.stringify(data.data.items));
+ localStorage.setItem(cacheTimeKey, now.toString());
} catch {
- siteUrl = item.extension;
- title = siteUrl;
+ /* Rendering does not depend on cache availability. */
}
+ renderTalksList(data.data.items);
+ } else throw new Error('Unexpected API response format');
+ })
+ .catch((err) => {
+ console.warn('说说加载失败:', err);
+ if (cachedData) renderTalksList(cachedData);
+ else talkContainer.textContent = '说说暂时无法加载,请稍后再试。';
+ });
+ }
+ };
- // 特殊处理 GitHub 项目
- if (item.extension_type === 'GITHUBPROJ') {
- extensionBack = "https://pic.biss.click/image/ed410d4e-d3f8-4b26-8840-50dd58f7dc4e.webp";
+ const renderTalksList = (list) => {
+ list.map(formatTalk).forEach((item) => talkContainer.appendChild(generateTalkElement(item)));
+ if (list.length) waterfall('#talk');
+ else talkContainer.textContent = '暂无说说。';
+ };
- // 提取 GitHub 项目名
- const match = siteUrl.match(/^https?:\/\/github\.com\/[^/]+\/([^/?#]+)/i);
- if (match) {
- title = match[1]; // 获取仓库名
- } else {
- // fallback:从最后一个路径段提取
- try {
- const parts = new URL(siteUrl).pathname.split('/').filter(Boolean);
- title = parts.pop() || siteUrl;
- } catch {
- // 如果 URL 无效则保留原始
- }
- }
- }
+ const withImageParams = (url) => {
+ if (!url) return '';
+ try {
+ const parsedUrl = new URL(url, window.location.origin);
+ if (!parsedUrl.searchParams.has('fmt')) parsedUrl.searchParams.set('fmt', 'webp');
+ if (!parsedUrl.searchParams.has('q')) parsedUrl.searchParams.set('q', '75');
+ return safeUrl(parsedUrl.toString());
+ } catch {
+ return '';
+ }
+ };
- siteUrl = safeUrl(siteUrl);
- // 输出 HTML 结构
- if (siteUrl) {
- content += `
+ const getImageUrl = (image) => {
+ if (!image) return '';
+ if (typeof image === 'string') return image;
+ return image.image_url || image.url || image.src || image.file?.url || '';
+ };
+
+ const getTalkImages = (item) => {
+ if (Array.isArray(item.images) && item.images.length > 0) {
+ return item.images.map(getImageUrl).filter(Boolean);
+ }
+
+ if (Array.isArray(item.echo_files) && item.echo_files.length > 0) {
+ return item.echo_files
+ .map((echoFile) => getImageUrl(echoFile.file || echoFile))
+ .filter(Boolean);
+ }
+
+ return [];
+ };
+
+ const formatTalk = (item) => {
+ const date = formatTime(item.created_at);
+ let content = escapeHtml(item.content || '');
+ content = content
+ .replace(/\[(.*?)\]\((.*?)\)/g, (match, label, href) => {
+ const url = safeUrl(href);
+ return url
+ ? `@${label}`
+ : label;
+ })
+ .replace(/- \[ \]/g, '⚪')
+ .replace(/- \[x\]/g, '⚫')
+ .replace(/\n/g, '
');
+ content = `${content}
`;
+
+ // 图片
+ const images = getTalkImages(item);
+ if (images.length > 0) {
+ const imgDiv = document.createElement('div');
+ imgDiv.className = 'zone_imgbox';
+ images.forEach((url) => {
+ const imageUrl = withImageParams(url);
+ if (!imageUrl) return;
+ const link = document.createElement('a');
+ link.href = imageUrl;
+ link.setAttribute('data-fancybox', 'gallery');
+ link.className = 'fancybox';
+ const imgTag = document.createElement('img');
+ imgTag.src = imageUrl;
+ imgTag.loading = 'lazy';
+ imgTag.alt = '';
+ link.appendChild(imgTag);
+ imgDiv.appendChild(link);
+ });
+ content += imgDiv.outerHTML;
+ }
+
+ // 外链 / GitHub 项目
+ // 外链 / GitHub 项目
+ if (['WEBSITE', 'GITHUBPROJ'].includes(item.extension_type)) {
+ let siteUrl = '',
+ title = '';
+ let extensionBack = 'https://pic.biss.click/image/1971bdc1-4349-4bb9-b683-20404f5da7d7.webp';
+
+ // 解析 extension 字段
+ try {
+ const extObj =
+ typeof item.extension === 'string' ? JSON.parse(item.extension) : item.extension;
+ siteUrl = extObj.site || extObj.url || item.extension;
+ title = extObj.title || siteUrl;
+ } catch {
+ siteUrl = item.extension;
+ title = siteUrl;
+ }
+
+ // 特殊处理 GitHub 项目
+ if (item.extension_type === 'GITHUBPROJ') {
+ extensionBack = 'https://pic.biss.click/image/ed410d4e-d3f8-4b26-8840-50dd58f7dc4e.webp';
+
+ // 提取 GitHub 项目名
+ const match = siteUrl.match(/^https?:\/\/github\.com\/[^/]+\/([^/?#]+)/i);
+ if (match) {
+ title = match[1]; // 获取仓库名
+ } else {
+ // fallback:从最后一个路径段提取
+ try {
+ const parts = new URL(siteUrl).pathname.split('/').filter(Boolean);
+ title = parts.pop() || siteUrl;
+ } catch {
+ // 如果 URL 无效则保留原始
+ }
+ }
+ }
+
+ siteUrl = safeUrl(siteUrl);
+ // 输出 HTML 结构
+ if (siteUrl) {
+ content += `
`;
- }
- }
+ }
+ }
+ // 音乐
+ if (item.extension_type === 'MUSIC' && item.extension) {
+ const link = item.extension;
+ let server = '';
+ if (link.includes('music.163.com')) server = 'netease';
+ else if (link.includes('y.qq.com')) server = 'tencent';
+ const idMatch = link.match(/id=(\d+)/);
+ const id = idMatch ? idMatch[1] : '';
+ if (server && id) {
+ content += ``;
+ }
+ }
- // 音乐
- if (item.extension_type === 'MUSIC' && item.extension) {
- const link = item.extension;
- let server = '';
- if (link.includes('music.163.com')) server = 'netease';
- else if (link.includes('y.qq.com')) server = 'tencent';
- const idMatch = link.match(/id=(\d+)/);
- const id = idMatch ? idMatch[1] : '';
- if (server && id) {
- content += ``;
- }
- }
-
- // 视频
- if (item.extension_type === 'VIDEO' && item.extension) {
- const video = item.extension;
- if (/^BV[a-zA-Z0-9]+$/.test(video)) {
- const bilibiliUrl = `https://www.bilibili.com/blackboard/html5mobileplayer.html?bvid=${video}&as_wide=1&high_quality=1&danmaku=0`;
- content += `
+ // 视频
+ if (item.extension_type === 'VIDEO' && item.extension) {
+ const video = item.extension;
+ if (/^BV[a-zA-Z0-9]+$/.test(video)) {
+ const bilibiliUrl = `https://www.bilibili.com/blackboard/html5mobileplayer.html?bvid=${video}&as_wide=1&high_quality=1&danmaku=0`;
+ content += `
`;
- } else if (/^[a-zA-Z0-9_-]{11}$/.test(video)) {
- const youtubeUrl = `https://www.youtube.com/embed/${video}`;
- content += `
+ } else if (/^[a-zA-Z0-9_-]{11}$/.test(video)) {
+ const youtubeUrl = `https://www.youtube.com/embed/${video}`;
+ content += `
`;
- }
- }
+ }
+ }
- return {
- content,
- user: item.username || '匿名',
- avatar: config.fallbackAvatar || window.SITE_CONFIG?.author?.avatar || '',
- date,
- location: '',
- tags: Array.isArray(item.tags) && item.tags.length ? item.tags.map(t => t.name) : ['无标签'],
- text: String(item.content || '').replace(/\[(.*?)\]\((.*?)\)/g, '$1')
- };
+ return {
+ content,
+ user: item.username || '匿名',
+ avatar: config.fallbackAvatar || window.SITE_CONFIG?.author?.avatar || '',
+ date,
+ location: '',
+ tags:
+ Array.isArray(item.tags) && item.tags.length ? item.tags.map((t) => t.name) : ['无标签'],
+ text: String(item.content || '').replace(/\[(.*?)\]\((.*?)\)/g, '$1'),
};
+ };
- const generateTalkElement = (item) => {
- const talkItem = document.createElement('div');
- talkItem.className = 'talk_item';
+ const generateTalkElement = (item) => {
+ const talkItem = document.createElement('div');
+ talkItem.className = 'talk_item';
- const talkMeta = document.createElement('div');
- talkMeta.className = 'talk_meta';
- const avatar = document.createElement('img');
- avatar.className = 'no-lightbox avatar';
- avatar.src = item.avatar;
+ const talkMeta = document.createElement('div');
+ talkMeta.className = 'talk_meta';
+ const avatar = document.createElement('img');
+ avatar.className = 'no-lightbox avatar';
+ avatar.src = item.avatar;
- const info = document.createElement('div');
- info.className = 'info';
- const nick = document.createElement('span');
- nick.className = 'talk_nick';
- nick.textContent = `${item.user} `;
- nick.insertAdjacentHTML('beforeend', generateIconSVG());
- const date = document.createElement('span');
- date.className = 'talk_date';
- date.textContent = item.date;
- info.appendChild(nick);
- info.appendChild(date);
- talkMeta.appendChild(avatar);
- talkMeta.appendChild(info);
+ const info = document.createElement('div');
+ info.className = 'info';
+ const nick = document.createElement('span');
+ nick.className = 'talk_nick';
+ nick.textContent = `${item.user} `;
+ nick.insertAdjacentHTML('beforeend', generateIconSVG());
+ const date = document.createElement('span');
+ date.className = 'talk_date';
+ date.textContent = item.date;
+ info.appendChild(nick);
+ info.appendChild(date);
+ talkMeta.appendChild(avatar);
+ talkMeta.appendChild(info);
- const talkContent = document.createElement('div');
- talkContent.className = 'talk_content';
- talkContent.innerHTML = item.content;
+ const talkContent = document.createElement('div');
+ talkContent.className = 'talk_content';
+ talkContent.innerHTML = item.content;
- const talkBottom = document.createElement('div');
- talkBottom.className = 'talk_bottom';
- const tags = document.createElement('div');
- const tag = document.createElement('span');
- tag.className = 'talk_tag';
- tag.textContent = `🏷️${item.tags}`;
- //const loc = document.createElement('span');
- //loc.className = 'location_tag';
- //loc.textContent = `🌍${item.location}`;
- tags.appendChild(tag);
- //tags.appendChild(loc);
+ const talkBottom = document.createElement('div');
+ talkBottom.className = 'talk_bottom';
+ const tags = document.createElement('div');
+ const tag = document.createElement('span');
+ tag.className = 'talk_tag';
+ tag.textContent = `🏷️${item.tags}`;
+ //const loc = document.createElement('span');
+ //loc.className = 'location_tag';
+ //loc.textContent = `🌍${item.location}`;
+ tags.appendChild(tag);
+ //tags.appendChild(loc);
- const commentLink = document.createElement('a');
- commentLink.href = '#post-comment';
- commentLink.setAttribute('aria-label', '引用这条说说到评论区');
- commentLink.onclick = (event) => { event.preventDefault(); goComment(item.text); };
- const icon = document.createElement('span');
- icon.className = 'icon';
- icon.innerHTML = '';
- commentLink.appendChild(icon);
-
- talkBottom.appendChild(tags);
- talkBottom.appendChild(commentLink);
-
- talkItem.appendChild(talkMeta);
- talkItem.appendChild(talkContent);
- talkItem.appendChild(talkBottom);
-
- return talkItem;
+ const commentLink = document.createElement('a');
+ commentLink.href = '#post-comment';
+ commentLink.setAttribute('aria-label', '引用这条说说到评论区');
+ commentLink.onclick = (event) => {
+ event.preventDefault();
+ goComment(item.text);
};
+ const icon = document.createElement('span');
+ icon.className = 'icon';
+ icon.innerHTML = '';
+ commentLink.appendChild(icon);
- const goComment = (text) => {
- const textarea = document.querySelector('#twikoo-wrap textarea');
- if (!textarea) {
- document.getElementById('post-comment')?.scrollIntoView({ behavior: 'smooth' });
- btf.snackbarShow('评论区尚未加载完成,请稍后再试');
- return;
- }
- textarea.value = `${text.split(/\r?\n/).map(line => `> ${line}`).join('\n')}\n\n`;
- textarea.dispatchEvent(new Event('input', { bubbles: true }));
- textarea.focus();
- btf.snackbarShow("已为您引用该说说,不删除空格效果更佳");
- };
+ talkBottom.appendChild(tags);
+ talkBottom.appendChild(commentLink);
- const formatTime = (time) => {
- const timestamp = Number(time);
- const d = Number.isFinite(timestamp)
- ? new Date(timestamp < 100000000000 ? timestamp * 1000 : timestamp)
- : new Date(time);
- const pad = (n) => n.toString().padStart(2, '0');
- if (Number.isNaN(d.getTime())) return '';
- return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
- };
+ talkItem.appendChild(talkMeta);
+ talkItem.appendChild(talkContent);
+ talkItem.appendChild(talkBottom);
- fetchAndRenderTalks();
+ return talkItem;
+ };
+
+ const goComment = (text) => {
+ const textarea = document.querySelector('#twikoo-wrap textarea');
+ if (!textarea) {
+ document.getElementById('post-comment')?.scrollIntoView({ behavior: 'smooth' });
+ btf.snackbarShow('评论区尚未加载完成,请稍后再试');
+ return;
+ }
+ textarea.value = `${text
+ .split(/\r?\n/)
+ .map((line) => `> ${line}`)
+ .join('\n')}\n\n`;
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
+ textarea.focus();
+ btf.snackbarShow('已为您引用该说说,不删除空格效果更佳');
+ };
+
+ const formatTime = (time) => {
+ const timestamp = Number(time);
+ const d = Number.isFinite(timestamp)
+ ? new Date(timestamp < 100000000000 ? timestamp * 1000 : timestamp)
+ : new Date(time);
+ const pad = (n) => n.toString().padStart(2, '0');
+ if (Number.isNaN(d.getTime())) return '';
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ };
+
+ fetchAndRenderTalks();
}
renderTalks();
diff --git a/public/js/shuoshuoshouye.js b/public/js/shuoshuoshouye.js
index f61015b..9405284 100644
--- a/public/js/shuoshuoshouye.js
+++ b/public/js/shuoshuoshouye.js
@@ -5,116 +5,126 @@ const cacheTimeKey = 'talksCacheTime';
const cacheDuration = 30 * 60 * 1000; // 缓存有效期 30分钟
function indexTalk() {
- if (talkTimer) {
- clearInterval(talkTimer);
- talkTimer = null;
+ if (talkTimer) {
+ clearInterval(talkTimer);
+ talkTimer = null;
+ }
+
+ if (!document.getElementById('bber-talk')) return;
+ const config = window.SITE_CONFIG?.talks || {};
+ const talksCacheKey = config.cacheKey || cacheKey;
+ const talksCacheTimeKey = config.cacheTimeKey || cacheTimeKey;
+ const talksCacheDuration = config.cacheDurationMs || cacheDuration;
+
+ function toText(ls) {
+ return ls.map((item) => {
+ let c = String(item.content || '').replace(
+ /[&<>"']/g,
+ (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char],
+ );
+
+ const hasImg = /\!\[.*?\]\(.*?\)/.test(c);
+ const hasLink = /\[.*?\]\(.*?\)/.test(c);
+
+ c = c
+ .replace(/#(.*?)\s/g, '')
+ .replace(/\{.*?\}/g, '')
+ .replace(/\!\[.*?\]\(.*?\)/g, '')
+ .replace(/\[.*?\]\(.*?\)/g, '');
+
+ const icons = [];
+
+ if (item.images?.length && !hasImg) icons.push('fa-solid fa-image');
+ if (item.extension_type === 'VIDEO') icons.push('fa-solid fa-video');
+ if (item.extension_type === 'MUSIC') icons.push('fa-solid fa-music');
+ if (item.extension_type === 'WEBSITE' && !hasLink) icons.push('fa-solid fa-link');
+ if (item.extension_type === 'GITHUBPROJ' && !hasLink) icons.push('fab fa-github');
+
+ if (icons.length) c += ' ' + icons.map((i) => ``).join(' ');
+ return c;
+ });
+ }
+
+ // 渲染与轮播
+ function talk(ls) {
+ let html = '';
+ ls.forEach((item, i) => {
+ html += `${item}`;
+ });
+
+ let box = document.querySelector('#bber-talk .talk-list');
+ if (!box) return;
+
+ box.innerHTML = html || '暂无说说';
+
+ talkTimer = setInterval(() => {
+ if (box.children.length > 0) {
+ box.appendChild(box.children[0]);
+ }
+ }, 3000);
+ }
+
+ let cachedData = null;
+ let cachedTime = 0;
+ try {
+ const parsed = JSON.parse(localStorage.getItem(talksCacheKey) || 'null');
+ if (Array.isArray(parsed)) cachedData = parsed;
+ cachedTime = Number(localStorage.getItem(talksCacheTimeKey)) || 0;
+ } catch {
+ /* Cache is optional. */
+ }
+ const currentTime = new Date().getTime();
+
+ // 判断缓存是否有效
+ if (cachedData && cachedTime && currentTime - cachedTime < talksCacheDuration) {
+ const data = toText(cachedData);
+ talk(data.slice(0, config.homeLimit || 6)); // 使用缓存渲染数据
+ } else {
+ if (!config.apiUrl) {
+ talk([]);
+ return;
}
- if (!document.getElementById('bber-talk')) return;
- const config = window.SITE_CONFIG?.talks || {};
- const talksCacheKey = config.cacheKey || cacheKey;
- const talksCacheTimeKey = config.cacheTimeKey || cacheTimeKey;
- const talksCacheDuration = config.cacheDurationMs || cacheDuration;
+ fetch(config.apiUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ page: 1, pageSize: config.pageSize || 30 }),
+ })
+ .then((res) => {
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return res.json();
+ })
+ .then((data) => {
+ // 适配新版结构:code=1 且 data.items 存在
+ if (data.code === 1 && data.data && Array.isArray(data.data.items)) {
+ try {
+ localStorage.setItem(talksCacheKey, JSON.stringify(data.data.items));
+ localStorage.setItem(talksCacheTimeKey, currentTime.toString());
+ } catch {
+ /* Rendering does not depend on cache availability. */
+ }
- function toText(ls) {
- return ls.map(item => {
- let c = String(item.content || '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
-
- const hasImg = /\!\[.*?\]\(.*?\)/.test(c);
- const hasLink = /\[.*?\]\(.*?\)/.test(c);
-
- c = c
- .replace(/#(.*?)\s/g, '')
- .replace(/\{.*?\}/g, '')
- .replace(/\!\[.*?\]\(.*?\)/g, '')
- .replace(/\[.*?\]\(.*?\)/g, '');
-
- const icons = [];
-
- if (item.images?.length && !hasImg) icons.push('fa-solid fa-image');
- if (item.extension_type === 'VIDEO') icons.push('fa-solid fa-video');
- if (item.extension_type === 'MUSIC') icons.push('fa-solid fa-music');
- if (item.extension_type === 'WEBSITE' && !hasLink) icons.push('fa-solid fa-link');
- if (item.extension_type === 'GITHUBPROJ' && !hasLink) icons.push('fab fa-github');
-
- if (icons.length) c += ' ' + icons.map(i => ``).join(' ');
- return c;
- });
- }
-
- // 渲染与轮播
- function talk(ls) {
- let html = '';
- ls.forEach((item, i) => {
- html += `${item}`;
- });
-
- let box = document.querySelector("#bber-talk .talk-list");
- if (!box) return;
-
- box.innerHTML = html || '暂无说说';
-
- talkTimer = setInterval(() => {
- if (box.children.length > 0) {
- box.appendChild(box.children[0]);
- }
- }, 3000);
- }
-
- let cachedData = null;
- let cachedTime = 0;
- try {
- const parsed = JSON.parse(localStorage.getItem(talksCacheKey) || 'null');
- if (Array.isArray(parsed)) cachedData = parsed;
- cachedTime = Number(localStorage.getItem(talksCacheTimeKey)) || 0;
- } catch { /* Cache is optional. */ }
- const currentTime = new Date().getTime();
-
- // 判断缓存是否有效
- if (cachedData && cachedTime && (currentTime - cachedTime < talksCacheDuration)) {
- const data = toText(cachedData);
- talk(data.slice(0, config.homeLimit || 6)); // 使用缓存渲染数据
- } else {
- if (!config.apiUrl) { talk([]); return; }
-
- fetch(config.apiUrl, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ page: 1, pageSize: config.pageSize || 30 })
- })
- .then(res => {
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json();
- })
- .then(data => {
- // 适配新版结构:code=1 且 data.items 存在
- if (data.code === 1 && data.data && Array.isArray(data.data.items)) {
- try {
- localStorage.setItem(talksCacheKey, JSON.stringify(data.data.items));
- localStorage.setItem(talksCacheTimeKey, currentTime.toString());
- } catch { /* Rendering does not depend on cache availability. */ }
-
- const formattedData = toText(data.data.items);
- talk(formattedData.slice(0, config.homeLimit || 6));
- } else {
- throw new Error('Unexpected API response format');
- }
- })
- .catch(error => {
- console.warn('说说加载失败:', error);
- if (cachedData) talk(toText(cachedData).slice(0, config.homeLimit || 6));
- else {
- const box = document.querySelector('#bber-talk .talk-list');
- if (box) box.innerHTML = '说说暂时无法加载';
- }
- });
- }
+ const formattedData = toText(data.data.items);
+ talk(formattedData.slice(0, config.homeLimit || 6));
+ } else {
+ throw new Error('Unexpected API response format');
+ }
+ })
+ .catch((error) => {
+ console.warn('说说加载失败:', error);
+ if (cachedData) talk(toText(cachedData).slice(0, config.homeLimit || 6));
+ else {
+ const box = document.querySelector('#bber-talk .talk-list');
+ if (box) box.innerHTML = '说说暂时无法加载';
+ }
+ });
+ }
}
// pjax 支持
function whenDOMReady() {
- indexTalk();
+ indexTalk();
}
whenDOMReady();
-document.addEventListener("pjax:complete", whenDOMReady);
+document.addEventListener('pjax:complete', whenDOMReady);
diff --git a/scripts/generate-abbrlinks.mjs b/scripts/generate-abbrlinks.mjs
index 8437380..1314986 100644
--- a/scripts/generate-abbrlinks.mjs
+++ b/scripts/generate-abbrlinks.mjs
@@ -99,7 +99,9 @@ async function main() {
if (existing) {
if (existingFiles.has(existing)) {
- throw new Error(`Duplicate abbrlink "${existing}" in ${relative(process.cwd(), existingFiles.get(existing))} and ${relative(process.cwd(), file)}`);
+ throw new Error(
+ `Duplicate abbrlink "${existing}" in ${relative(process.cwd(), existingFiles.get(existing))} and ${relative(process.cwd(), file)}`,
+ );
}
existingFiles.set(existing, file);
usedAbbrlinks.add(existing);
diff --git a/scripts/version-service-worker.mjs b/scripts/version-service-worker.mjs
index 5aaef4a..c1ea38b 100644
--- a/scripts/version-service-worker.mjs
+++ b/scripts/version-service-worker.mjs
@@ -11,10 +11,12 @@ hash.update('\0');
async function collect(directory) {
const entries = await readdir(directory, { withFileTypes: true });
- const files = await Promise.all(entries.map((entry) => {
- const path = join(directory, entry.name);
- return entry.isDirectory() ? collect(path) : [path];
- }));
+ const files = await Promise.all(
+ entries.map((entry) => {
+ const path = join(directory, entry.name);
+ return entry.isDirectory() ? collect(path) : [path];
+ }),
+ );
return files.flat();
}
@@ -26,6 +28,9 @@ for (const path of files) {
hash.update('\0');
}
-const versioned = source.replace(/^const CACHE_VERSION = '[^']+';/m, `const CACHE_VERSION = '${hash.digest('hex').slice(0, 16)}';`);
+const versioned = source.replace(
+ /^const CACHE_VERSION = '[^']+';/m,
+ `const CACHE_VERSION = '${hash.digest('hex').slice(0, 16)}';`,
+);
if (versioned === source) throw new Error('Service worker cache version was not found');
await writeFile(worker, versioned);
diff --git a/site.config.mjs b/site.config.mjs
index d781ced..04e42d3 100644
--- a/site.config.mjs
+++ b/site.config.mjs
@@ -42,7 +42,12 @@ export const siteConfig = {
social: [
{ label: '发送邮件', href: 'mailto:bishsh2006@gmail.com', icon: 'fa-solid fa-envelope' },
{ label: '订阅 RSS', href: '/rss/', icon: 'fa-solid fa-rss' },
- { label: 'GitHub', href: 'https://github.com/bishshi', icon: 'fa-brands fa-github', external: true },
+ {
+ label: 'GitHub',
+ href: 'https://github.com/bishshi',
+ icon: 'fa-brands fa-github',
+ external: true,
+ },
],
pagination: {
postsPerPage: 16,
@@ -68,13 +73,7 @@ export const siteConfig = {
},
externalLinks: {
waitSeconds: 10,
- whitelist: [
- 'blog.biss.click',
- 'biss.click',
- 'github.com',
- 'localhost',
- '127.0.0.1',
- ],
+ whitelist: ['blog.biss.click', 'biss.click', 'github.com', 'localhost', '127.0.0.1'],
},
talks: {
apiUrl: 'https://mm.biss.click/api/echo/page',
@@ -112,9 +111,11 @@ export const siteConfig = {
cdn: {
instantsearchCss: 'https://cdn.jsdmirror.com/npm/instantsearch.css/themes/reset-min.css',
fancyboxCss: 'https://cdn.jsdmirror.com/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.css',
- fontawesomeCss: 'https://cdn.jsdmirror.com/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css',
+ fontawesomeCss:
+ 'https://cdn.jsdmirror.com/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css',
instantsearchJs: 'https://cdn.jsdmirror.com/npm/instantsearch.js@4.56.0',
- typesenseAdapterJs: 'https://cdn.jsdmirror.com/npm/typesense-instantsearch-adapter@2.7.0/dist/typesense-instantsearch-adapter.min.js',
+ typesenseAdapterJs:
+ 'https://cdn.jsdmirror.com/npm/typesense-instantsearch-adapter@2.7.0/dist/typesense-instantsearch-adapter.min.js',
fancyboxJs: 'https://cdn.jsdmirror.com/npm/@fancyapps/ui@5.0/dist/fancybox/fancybox.umd.js',
jqueryJs: 'https://code.jquery.com/jquery-4.0.0.min.js',
welcomeMessageJs: 'https://cdn.jsdmirror.com/gh/bishshi/welcomemessage/txmap.js',
diff --git a/src/components/ArchiveTimeline.astro b/src/components/ArchiveTimeline.astro
index 3c07667..545997e 100644
--- a/src/components/ArchiveTimeline.astro
+++ b/src/components/ArchiveTimeline.astro
@@ -49,31 +49,33 @@ const archiveYears = posts.reduce((years, post) => {
---
- {archiveYears.map((yearGroup) => (
-
-
-
- {yearGroup.year}
- {yearGroup.count} 篇
-
-
- {yearGroup.months.map((monthGroup) => (
-
-
- {monthGroup.label}
- {monthGroup.posts.length} 篇
-
-
-
- ))}
-
-
- ))}
+ {
+ archiveYears.map((yearGroup) => (
+
+
+
+ {yearGroup.year}
+ {yearGroup.count} 篇
+
+
+ {yearGroup.months.map((monthGroup) => (
+
+
+ {monthGroup.label}
+ {monthGroup.posts.length} 篇
+
+
+
+ ))}
+
+
+ ))
+ }
diff --git a/src/components/ArticleSidebar.astro b/src/components/ArticleSidebar.astro
index 8e2885c..98ed3f0 100644
--- a/src/components/ArticleSidebar.astro
+++ b/src/components/ArticleSidebar.astro
@@ -45,50 +45,67 @@ const tocSections = toc.reduce((sections, item) => {
- {post.tags.length > 0 && (
-
-
- #
- 文章标签
- {post.tags.length}
-
-
- {post.tags.map((tag) => (
-
#{tag}
- ))}
-
-
- )}
+ {
+ post.tags.length > 0 && (
+
+
+ #
+ 文章标签
+ {post.tags.length}
+
+
+ {post.tags.map((tag) => (
+
#{tag}
+ ))}
+
+
+ )
+ }
- {toc.length > 0 && (
-
- )}
+ {
+ toc.length > 0 && (
+
+ )
+ }
diff --git a/src/components/CustomContextMenu.astro b/src/components/CustomContextMenu.astro
index 6f43094..1b00e11 100644
--- a/src/components/CustomContextMenu.astro
+++ b/src/components/CustomContextMenu.astro
@@ -23,7 +23,12 @@
用 Bing 搜索
-
-
{currentPage < totalPages ? (
-
) : (
diff --git a/src/components/PostCard.astro b/src/components/PostCard.astro
index f975c14..c42bd8d 100644
--- a/src/components/PostCard.astro
+++ b/src/components/PostCard.astro
@@ -7,9 +7,10 @@ interface Props {
}
const { post, index } = Astro.props;
-const logNumber = index === undefined
- ? post.date.toISOString().slice(5, 10).replace('-', '.')
- : String(index + 1).padStart(2, '0');
+const logNumber =
+ index === undefined
+ ? post.date.toISOString().slice(5, 10).replace('-', '.')
+ : String(index + 1).padStart(2, '0');
---
diff --git a/src/components/PostChangelog.astro b/src/components/PostChangelog.astro
index db7e510..8889cd6 100644
--- a/src/components/PostChangelog.astro
+++ b/src/components/PostChangelog.astro
@@ -10,7 +10,9 @@ const { entries } = Astro.props;
-
+
+
+
REVISION HISTORY
文章修订记录
@@ -18,17 +20,19 @@ const { entries } = Astro.props;
{entries.length} 次
- {entries.map((entry) => (
- -
-
-
-
-
{entry.title}
- {entry.date &&
}
+ {
+ entries.map((entry) => (
+
-
+
+
+
+
{entry.title}
+ {entry.date && }
+
+ {entry.description &&
{entry.description}
}
- {entry.description && {entry.description}
}
-
-
- ))}
+
+ ))
+ }
diff --git a/src/components/PostCopyrightCard.astro b/src/components/PostCopyrightCard.astro
index 2c4f909..f787c8e 100644
--- a/src/components/PostCopyrightCard.astro
+++ b/src/components/PostCopyrightCard.astro
@@ -40,11 +40,15 @@ const tags = post.tags;
- {type === 'pie' ? (
-
-
+ {
+ type === 'pie' ? (
+
+
-
- {pieItems.map((item, index) => {
- const content = (
- <>
-
-
{item.label}
-
{item.value}
-
{item.percentText}
- >
- );
+
+ {pieItems.map((item, index) => {
+ const content = (
+ <>
+
+
{item.label}
+
{item.value}
+
{item.percentText}
+ >
+ );
- return item.href ? (
-
- {content}
-
- ) : (
-
- {content}
-
- );
- })}
+ return item.href ? (
+
+ {content}
+
+ ) : (
+
+ {content}
+
+ );
+ })}
+
-
- ) : (
-
-
+
+ )
+ }
diff --git a/src/components/TwikooComments.astro b/src/components/TwikooComments.astro
index 7da4215..1a2f79d 100644
--- a/src/components/TwikooComments.astro
+++ b/src/components/TwikooComments.astro
@@ -23,7 +23,7 @@ const { envId, path, title, region = '' } = Astro.props;
第三方服务
- 本站可能使用 CDN、评论、头像、搜索或统计分析服务。第三方服务会根据其自身政策处理数据,建议你阅读对应服务的隐私说明。 + 本站可能使用 + CDN、评论、头像、搜索或统计分析服务。第三方服务会根据其自身政策处理数据,建议你阅读对应服务的隐私说明。
Cookie 与本地存储
- 关于 Cookie 和 LocalStorage 的更多说明,请查看 Cookies 页面。你可以在浏览器中清除这些数据。 + 关于 Cookie 和 LocalStorage 的更多说明,请查看 Cookies 页面。你可以在浏览器中清除这些数据。
联系
-如果你希望删除评论或询问隐私相关问题,可以发送邮件至 {siteConfig.author.email}。
++ 如果你希望删除评论或询问隐私相关问题,可以发送邮件至 {siteConfig.author.email}。 +
复制地址,添加到你的 RSS 阅读器
支持 Feedly、Inoreader、Fluent Reader、NetNewsWire 等常见阅读器。
{post.title}
-{post.summary}
-+ {post.title} +
+{post.summary}
+