|
| 1 | +<li class="menu-item" id="search-menu-item"> |
| 2 | + <div class="search-container"> |
| 3 | + <input |
| 4 | + type="text" |
| 5 | + id="search-input" |
| 6 | + placeholder="Search..." |
| 7 | + autocomplete="off" |
| 8 | + > |
| 9 | + <div id="search-results" class="search-results"></div> |
| 10 | + </div> |
| 11 | +</li> |
| 12 | + |
| 13 | +<script> |
| 14 | +document.addEventListener('DOMContentLoaded', function() { |
| 15 | + const searchInput = document.getElementById('search-input'); |
| 16 | + const searchResults = document.getElementById('search-results'); |
| 17 | + |
| 18 | + function createSearchResultHTML(item) { |
| 19 | + const summary = item.summary || ''; |
| 20 | + const truncatedSummary = summary.length > 100 ? |
| 21 | + `${summary.substring(0, 100)}...` : |
| 22 | + summary; |
| 23 | + |
| 24 | + return ` |
| 25 | + <a href="${item.url}" class="search-result-item"> |
| 26 | + <div class="search-result-title">${item.title || ''}</div> |
| 27 | + <div class="search-result-summary">${truncatedSummary}</div> |
| 28 | + </a> |
| 29 | + `; |
| 30 | + } |
| 31 | + |
| 32 | + function handleSearch() { |
| 33 | + const searchQuery = searchInput.value.trim(); |
| 34 | + |
| 35 | + if (searchQuery.length < 2) { |
| 36 | + searchResults.style.display = 'none'; |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + fetch('/index.json') |
| 41 | + .then(response => response.json()) |
| 42 | + .then(response => { |
| 43 | + const data = Object.values(response.data || {}); |
| 44 | + const currentLang = document.documentElement.lang || 'en'; |
| 45 | + |
| 46 | + const results = data.filter(item => { |
| 47 | + if (item.lang !== currentLang) return false; |
| 48 | + |
| 49 | + const regex = new RegExp(searchQuery, 'i'); |
| 50 | + return (item.title && item.title.match(regex)) || |
| 51 | + (item.content && item.content.match(regex)); |
| 52 | + }); |
| 53 | + |
| 54 | + searchResults.innerHTML = results.length ? |
| 55 | + results.map(createSearchResultHTML).join('') : |
| 56 | + '<div class="no-results">No results found</div>'; |
| 57 | + |
| 58 | + searchResults.style.display = 'block'; |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + searchInput.addEventListener('input', handleSearch); |
| 63 | + |
| 64 | + document.addEventListener('click', function(e) { |
| 65 | + if (!e.target.closest('.search-container')) { |
| 66 | + searchResults.style.display = 'none'; |
| 67 | + } |
| 68 | + }); |
| 69 | +}); |
| 70 | +</script> |
0 commit comments