~cytrogen/blog-public

ref: 88eebf3dfdd8ab819fa1a84e1976a8a75d5af2b6 blog-public/js/search.js -rw-r--r-- 9.7 KiB
88eebf3dCytrogen Deploy 2026-02-19 08:34:27 3 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/**
 * Modern Local Search Implementation
 * Compatible with hexo-generator-search
 * Separated from UI control logic for better maintainability
 */

class ModernSearch {
  constructor(options = {}) {
    this.options = {
      path: options.path || 'search.xml',
      inputSelector: options.inputSelector || '#search-input',
      resultsSelector: options.resultsSelector || '#search-results .search-results__list',
      loadingSelector: options.loadingSelector || '.search-results__loading',
      emptySelector: options.emptySelector || '.search-results__empty',
      maxResults: options.maxResults || 50,
      excerptLength: options.excerptLength || 200,
      debounceDelay: options.debounceDelay || 300,
      ...options
    };
    
    this.searchData = [];
    this.searchInput = null;
    this.resultsContainer = null;
    this.loadingElement = null;
    this.emptyElement = null;
    this.debounceTimer = null;
    
    this.init();
  }
  
  async init() {
    // Find DOM elements
    this.searchInput = document.querySelector(this.options.inputSelector);
    this.resultsContainer = document.querySelector(this.options.resultsSelector);
    this.loadingElement = document.querySelector(this.options.loadingSelector);
    this.emptyElement = document.querySelector(this.options.emptySelector);
    
    if (!this.searchInput || !this.resultsContainer) {
      console.warn('Search elements not found');
      return;
    }
    
    // Load search data
    await this.loadSearchData();
    
    // Set up event listeners
    this.setupEventListeners();
  }
  
  async loadSearchData() {
    try {
      this.showLoading();
      
      const response = await fetch(this.options.path);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      
      const xmlText = await response.text();
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
      
      // Check for parsing errors
      const parseError = xmlDoc.querySelector('parsererror');
      if (parseError) {
        throw new Error('XML parsing failed');
      }
      
      // Extract search data
      const entries = xmlDoc.querySelectorAll('entry');
      this.searchData = Array.from(entries).map(entry => ({
        title: this.getTextContent(entry, 'title'),
        content: this.getTextContent(entry, 'content'),
        url: this.getTextContent(entry, 'url')
      })).filter(item => item.title && item.content); // Filter out empty entries
      
      this.hideLoading();
      console.log(`Loaded ${this.searchData.length} search entries`);
      
    } catch (error) {
      console.error('Failed to load search data:', error);
      this.hideLoading();
      this.showError('Failed to load search data');
    }
  }
  
  getTextContent(parent, tagName) {
    const element = parent.querySelector(tagName);
    return element ? element.textContent.trim() : '';
  }
  
  setupEventListeners() {
    // Debounced input handler
    this.searchInput.addEventListener('input', (e) => {
      clearTimeout(this.debounceTimer);
      const query = e.target.value.trim();
      
      this.debounceTimer = setTimeout(() => {
        if (query.length === 0) {
          this.clearResults();
        } else if (query.length >= 2) { // Only search for 2+ characters
          this.performSearch(query);
        }
      }, this.options.debounceDelay);
    });
    
    // Handle Enter key
    this.searchInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        const query = e.target.value.trim();
        if (query.length >= 2) {
          clearTimeout(this.debounceTimer);
          this.performSearch(query);
        }
      }
    });
  }
  
  performSearch(query) {
    if (!query || this.searchData.length === 0) {
      this.clearResults();
      return;
    }
    
    this.showLoading();
    
    // Use requestAnimationFrame for better performance with large datasets
    requestAnimationFrame(() => {
      const results = this.search(query);
      this.displayResults(results, query);
      this.hideLoading();
    });
  }
  
  search(query) {
    const keywords = query.toLowerCase()
      .split(/[\s\-\+\(\)]+/)
      .filter(word => word.length > 0);
    
    if (keywords.length === 0) return [];
    
    const results = [];
    
    for (const item of this.searchData) {
      const titleLower = item.title.toLowerCase();
      const contentLower = this.stripHtml(item.content).toLowerCase();
      
      let score = 0;
      let matchedKeywords = 0;
      const titleMatches = [];
      const contentMatches = [];
      
      for (const keyword of keywords) {
        const titleIndex = titleLower.indexOf(keyword);
        const contentIndex = contentLower.indexOf(keyword);
        
        if (titleIndex >= 0 || contentIndex >= 0) {
          matchedKeywords++;
          
          // Higher score for title matches
          if (titleIndex >= 0) {
            score += titleIndex === 0 ? 10 : 5; // Boost for exact start matches
            titleMatches.push({ keyword, index: titleIndex });
          }
          
          // Lower score for content matches
          if (contentIndex >= 0) {
            score += 1;
            contentMatches.push({ keyword, index: contentIndex });
          }
        }
      }
      
      // Only include results that match all keywords
      if (matchedKeywords === keywords.length) {
        results.push({
          ...item,
          score,
          titleMatches,
          contentMatches,
          excerpt: this.generateExcerpt(contentLower, keywords)
        });
      }
    }
    
    // Sort by score (descending) and limit results
    return results
      .sort((a, b) => b.score - a.score)
      .slice(0, this.options.maxResults);
  }
  
  stripHtml(html) {
    const div = document.createElement('div');
    div.innerHTML = html;
    return div.textContent || div.innerText || '';
  }
  
  generateExcerpt(content, keywords) {
    // Find the first keyword occurrence
    let firstIndex = Infinity;
    for (const keyword of keywords) {
      const index = content.indexOf(keyword);
      if (index >= 0 && index < firstIndex) {
        firstIndex = index;
      }
    }
    
    if (firstIndex === Infinity) return content.substring(0, this.options.excerptLength);
    
    // Generate excerpt around the first match
    const start = Math.max(0, firstIndex - 50);
    const end = Math.min(content.length, start + this.options.excerptLength);
    
    let excerpt = content.substring(start, end);
    if (start > 0) excerpt = '...' + excerpt;
    if (end < content.length) excerpt = excerpt + '...';
    
    return excerpt;
  }
  
  highlightKeywords(text, keywords) {
    let highlighted = text;
    
    for (const keyword of keywords) {
      const regex = new RegExp(`(${this.escapeRegex(keyword)})`, 'gi');
      highlighted = highlighted.replace(regex, '<mark class="search-keyword">$1</mark>');
    }
    
    return highlighted;
  }
  
  escapeRegex(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }
  
  displayResults(results, query) {
    if (results.length === 0) {
      this.showEmpty();
      return;
    }
    
    this.hideEmpty();
    
    const keywords = query.toLowerCase().split(/[\s\-\+\(\)]+/).filter(word => word.length > 0);
    
    const resultsHtml = results.map(result => `
      <article class="search-result-item">
        <h3 class="search-result-item__title">
          <a href="${this.escapeHtml(result.url)}" title="${this.escapeHtml(result.title)}">
            ${this.highlightKeywords(this.escapeHtml(result.title), keywords)}
          </a>
        </h3>
        <p class="search-result-item__excerpt">
          ${this.highlightKeywords(this.escapeHtml(result.excerpt), keywords)}
        </p>
        <div class="search-result-item__meta">
          ${result.url}
        </div>
      </article>
    `).join('');
    
    this.resultsContainer.innerHTML = resultsHtml;
    
    // Add click tracking (optional)
    this.trackSearchResults(query, results.length);
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
  
  clearResults() {
    if (this.resultsContainer) {
      this.resultsContainer.innerHTML = '';
    }
    this.hideLoading();
    this.hideEmpty();
  }
  
  showLoading() {
    if (this.loadingElement) {
      this.loadingElement.hidden = false;
    }
    this.hideEmpty();
  }
  
  hideLoading() {
    if (this.loadingElement) {
      this.loadingElement.hidden = true;
    }
  }
  
  showEmpty() {
    if (this.emptyElement) {
      this.emptyElement.hidden = false;
    }
  }
  
  hideEmpty() {
    if (this.emptyElement) {
      this.emptyElement.hidden = true;
    }
  }
  
  showError(message) {
    if (this.resultsContainer) {
      this.resultsContainer.innerHTML = `
        <div class="search-error" style="text-align: center; color: var(--color-danger); padding: 2rem;">
          <p>${this.escapeHtml(message)}</p>
        </div>
      `;
    }
  }
  
  trackSearchResults(query, resultCount) {
    // Optional: Track search analytics
    if (typeof gtag === 'function') {
      gtag('event', 'search', {
        search_term: query,
        custom_parameter: resultCount
      });
    }
  }
}

// Initialize search when DOM is ready and search is enabled
document.addEventListener('DOMContentLoaded', () => {
  // Check if search elements exist (indicating search is enabled)
  if (document.querySelector('#search-dialog') && document.querySelector('#search-input')) {
    // Initialize with default options - can be customized via theme config
    window.modernSearch = new ModernSearch({
      path: '/search.xml', // Default path - should be configurable
      maxResults: 50,
      excerptLength: 200,
      debounceDelay: 300
    });
  }
});