Harden search and improve talks fallback
自动部署 / deploy (push) Failing after 41s

This commit is contained in:
biss committed 2026-11-30 20:26:00 +08:00
1 parent 351bc8a226
commit 19f1f4c458
3 files changed
+67 -32

No files matched your search

+16 -13
View File
@@ -7,6 +7,15 @@
const CONFIG = window.SITE_CONFIG?.search;
const assets = document.currentScript?.dataset || {};
let dependenciesPromise;
const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[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 ''; }
}
function loadDependencies() {
if (dependenciesPromise) return dependenciesPromise;
const css = document.createElement('link');
@@ -52,15 +61,7 @@
'<div class="ts-empty">' +
'<div style="color: #f44336;"><i class="fas fa-exclamation-triangle" style="font-size: 3rem;"></i></div>' +
'<div style="font-size: 1.1rem; font-weight: bold; margin: 15px 0;">搜索服务加载失败</div>' +
'<div style="font-size: 0.9rem; color: #666; line-height: 1.8;">' +
'<p>依赖库未能正确加载,请检查以下配置:</p>' +
'<ol style="text-align: left; max-width: 500px; margin: 15px auto;">' +
'<li>确认已在 <code>_config.butterfly.yml</code> 中正确引入依赖</li>' +
'<li>检查 JS 文件加载顺序(先 instantsearch.js,再 adapter)</li>' +
'<li>尝试更换 CDN 或使用本地文件</li>' +
'<li>打开浏览器控制台查看详细错误信息</li>' +
'</ol>' +
'</div>' +
'<div style="font-size: 0.9rem; color: #666; line-height: 1.8;">请检查网络连接后重试。</div>' +
'<div style="margin-top: 20px;">' +
'<button onclick="location.reload()" style="padding: 10px 20px; background: #49b1f5; color: white; border: none; border-radius: 5px; cursor: pointer;">重新加载页面</button>' +
'</div>' +
@@ -475,7 +476,7 @@
empty: function(results) {
return '<div class="ts-empty">' +
'<div><i class="fas fa-search"></i></div>' +
'<div>找不到与 "<strong>' + results.query + '</strong>" 相关的内容</div>' +
'<div>找不到与 "<strong>' + escapeHtml(results.query) + '</strong>" 相关的内容</div>' +
'<div style="margin-top: 10px;">试试其他关键词吧 (´·ω·`)</div>' +
'</div>';
},
@@ -494,9 +495,11 @@
contentHighlight = contentHighlight.substring(0, 200) + '...';
}
return '<a href="' + hit.url + '" class="ts-result-item">' +
'<div class="ts-result-title">' + titleHighlight + '</div>' +
'<div class="ts-result-content">' + contentHighlight + '</div>' +
const url = safeResultUrl(hit.url);
if (!url) return '';
return '<a href="' + escapeHtml(url) + '" class="ts-result-item">' +
'<div class="ts-result-title">' + safeHighlight(titleHighlight) + '</div>' +
'<div class="ts-result-content">' + safeHighlight(contentHighlight) + '</div>' +
'</a>';
}
}
+24 -9
View File
@@ -89,33 +89,48 @@ function renderTalks() {
const cacheKey = config.cacheKey || 'talksCache';
const cacheTimeKey = config.cacheTimeKey || 'talksCacheTime';
const cacheDuration = config.cacheDurationMs || 30 * 60 * 1000;
const cachedData = localStorage.getItem(cacheKey);
const cachedTime = localStorage.getItem(cacheTimeKey);
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(JSON.parse(cachedData));
renderTalksList(cachedData);
} else {
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ page: 1, pageSize: config.pageSize || 30 })
})
.then(res => res.json())
.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)) {
localStorage.setItem(cacheKey, JSON.stringify(data.data.items));
localStorage.setItem(cacheTimeKey, now.toString());
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.error('Error fetching:', err));
.catch(err => {
console.warn('说说加载失败:', err);
if (cachedData) renderTalksList(cachedData);
else talkContainer.textContent = '说说暂时无法加载,请稍后再试。';
});
}
};
const renderTalksList = (list) => {
list.map(formatTalk).forEach(item => talkContainer.appendChild(generateTalkElement(item)));
waterfall('#talk');
if (list.length) waterfall('#talk');
else talkContainer.textContent = '暂无说说。';
};
const withImageParams = (url) => {
+27 -10
View File
@@ -52,7 +52,7 @@ function indexTalk() {
let box = document.querySelector("#bber-talk .talk-list");
if (!box) return;
box.innerHTML = html;
box.innerHTML = html || '<li class="item">暂无说说</li>';
talkTimer = setInterval(() => {
if (box.children.length > 0) {
@@ -61,36 +61,53 @@ function indexTalk() {
}, 3000);
}
const cachedData = localStorage.getItem(talksCacheKey);
const cachedTime = localStorage.getItem(talksCacheTimeKey);
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(JSON.parse(cachedData));
const data = toText(cachedData);
talk(data.slice(0, config.homeLimit || 6)); // 使用缓存渲染数据
} else {
if (!config.apiUrl) return;
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 => res.json())
.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)) {
localStorage.setItem(talksCacheKey, JSON.stringify(data.data.items));
localStorage.setItem(talksCacheTimeKey, currentTime.toString());
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 {
console.warn('Unexpected API response format:', data);
throw new Error('Unexpected API response format');
}
})
.catch(error => console.error('Error fetching data:', error));
.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 = '<li class="item">说说暂时无法加载</li>';
}
});
}
}