/** * 增强搜索功能 * 支持搜索历史、自动建议和智能搜索 */ class EnhancedSearch { constructor() { this.searchHistoryKey = 'search-history'; this.maxHistoryItems = 10; this.searchHistory = this.loadSearchHistory(); this.suggestionsCache = {}; this.searchData = []; this.init(); } /** * 初始化 */ init() { this.loadSearchData(); this.setupSearchUI(); this.setupKeyboardShortcuts(); } /** * 加载搜索数据 */ async loadSearchData() { try { // 从 JSON 数据加载 const response = await fetch('./data/search-index.json'); if (response.ok) { this.searchData = await response.json(); console.log(`加载了 ${this.searchData.length} 条搜索数据`); } else { // 如果没有搜索索引,使用导航数据 const navResponse = await fetch('./data/nav.json'); const navData = await navResponse.json(); this.searchData = this.extractSearchData(navData); console.log(`从导航数据提取了 ${this.searchData.length} 条搜索数据`); } } catch (error) { console.error('加载搜索数据失败:', error); } } /** * 从导航数据提取搜索数据 */ extractSearchData(navData) { const results = []; if (navData.categories) { navData.categories.forEach(category => { if (category.links) { category.links.forEach(link => { results.push({ title: link.name, url: link.url, category: category.name, description: link.description || `来自 ${category.name}`, keywords: [link.name, category.name].join(' '), type: 'link' }); }); } }); } return results; } /** * 加载搜索历史 */ loadSearchHistory() { try { const history = localStorage.getItem(this.searchHistoryKey); return history ? JSON.parse(history) : []; } catch (error) { console.error('加载搜索历史失败:', error); return []; } } /** * 保存搜索历史 */ saveSearchHistory() { try { localStorage.setItem(this.searchHistoryKey, JSON.stringify(this.searchHistory)); } catch (error) { console.error('保存搜索历史失败:', error); } } /** * 添加搜索历史 */ addSearchHistory(query) { const trimmedQuery = query.trim(); if (!trimmedQuery) return; // 移除重复项 this.searchHistory = this.searchHistory.filter(item => item !== trimmedQuery); // 添加到开头 this.searchHistory.unshift(trimmedQuery); // 限制数量 if (this.searchHistory.length > this.maxHistoryItems) { this.searchHistory = this.searchHistory.slice(0, this.maxHistoryItems); } this.saveSearchHistory(); } /** * 清除搜索历史 */ clearSearchHistory() { this.searchHistory = []; this.saveSearchHistory(); } /** * 设置搜索 UI */ setupSearchUI() { // 查找或创建搜索框 const searchInput = document.getElementById('search-input') || document.querySelector('.search-input'); if (searchInput) { this.setupSearchInput(searchInput); } // 创建搜索建议容器 this.createSuggestionsContainer(); } /** * 设置搜索输入框 */ setupSearchInput(input) { this.searchInput = input; // 输入事件 input.addEventListener('input', (e) => { this.handleInput(e.target.value); }); // 焦点事件 input.addEventListener('focus', () => { this.showSuggestions(); }); // 失去焦点事件(延迟隐藏) input.addEventListener('blur', () => { setTimeout(() => this.hideSuggestions(), 200); }); // 键盘事件 input.addEventListener('keydown', (e) => { this.handleKeydown(e); }); } /** * 创建建议容器 */ createSuggestionsContainer() { const container = document.createElement('div'); container.className = 'search-suggestions-container'; container.id = 'search-suggestions'; document.body.appendChild(container); this.suggestionsContainer = container; } /** * 处理输入 */ handleInput(value) { if (value.trim()) { this.showSuggestions(value); } else { this.showSuggestions(); } } /** * 显示建议 */ showSuggestions(query = '') { if (!this.suggestionsContainer) return; let suggestionsHTML = ''; // 搜索建议 if (query.trim()) { const suggestions = this.getSuggestions(query); if (suggestions.length > 0) { suggestionsHTML += `