[CI] pgitBot
·
2026-02-26
search.js
JavaScript
1document.addEventListener('DOMContentLoaded', () => {
2 // Only run search logic on the search page
3 if (document.querySelector('#search-results-container')) {
4 const resultsContainer = document.getElementById('search-results-container');
5 let searchIndex = [];
6
7 async function executeSearch() {
8 try {
9 const response = await fetch('search-index.json');
10 if (!response.ok) {
11 resultsContainer.innerHTML = '<p>Error: Could not load search index.</p>';
12 return;
13 }
14 searchIndex = await response.json();
15
16 const urlParams = new URLSearchParams(window.location.search);
17 const query = urlParams.get('q');
18
19 // Update the search input in the header to reflect the current query
20 const headerSearchInput = document.getElementById('search-input');
21 if (headerSearchInput && query) {
22 headerSearchInput.value = query;
23 }
24
25 if (!query) {
26 resultsContainer.innerHTML = '<p>Please enter a search term.</p>';
27 return;
28 }
29
30 const results = searchIndex.filter(item =>
31 item.name.toLowerCase().includes(query.toLowerCase()) ||
32 item.path.toLowerCase().includes(query.toLowerCase())
33 );
34
35 renderResults(results, query);
36 } catch (error) {
37 console.error('Error during search:', error);
38 resultsContainer.innerHTML = '<p>An error occurred during the search.</p>';
39 }
40 }
41
42 function renderResults(results, query) {
43 if (results.length === 0) {
44 resultsContainer.innerHTML = `<p>No results found for "<strong>${escapeHTML(query)}</strong>".</p>`;
45 return;
46 }
47
48 let html = `<p>${results.length} results found for "<strong>${escapeHTML(query)}</strong>":</p><ul>`;
49 results.forEach(item => {
50 html += `
51 <li class="search-result-item">
52 <a href="${item.url}">${highlight(item.path, query)}</a>
53 <span>${item.language}</span>
54 </li>`;
55 });
56 html += '</ul>';
57 resultsContainer.innerHTML = html;
58 }
59
60 function escapeHTML(str) {
61 return str.replace(/[&<>"']/g, function(match) {
62 return {
63 '&': '&',
64 '<': '<',
65 '>': '>',
66 '"': '"',
67 "'": '''
68 }[match];
69 });
70 }
71
72 function highlight(text, query) {
73 const escapedQuery = escapeHTML(query);
74 const regex = new RegExp(`(${escapedQuery})`, 'gi');
75 return escapeHTML(text).replace(regex, '<mark>$1</mark>');
76 }
77
78 executeSearch();
79 }
80});