1 document.addEventListener('DOMContentLoaded', function () { 2 ////console.log('FuzzySearch original script loaded'); 3 4 const input = document.getElementById('fuzzysearch-input'); 5 const resultsList = document.getElementById('fuzzysearch-results'); 6 7 if (!input || !resultsList) { 8 console.error('Fuzzy search elements not found!'); 9 return; 10 } 11 12 let fuse, currentIndex = -1; 13 14 fetch(DOKU_BASE + 'lib/exe/ajax.php?call=fuzzysearch_pages', { 15 method: 'GET', 16 credentials: 'same-origin' 17 }) 18 .then(response => { 19 if (!response.ok) throw new Error('Fetch failed'); 20 return response.json(); 21 }) 22 .then(data => { 23 fuse = new Fuse(data, { 24 keys: ['title'], 25 threshold: 0.4, 26 includeScore: true 27 }); 28 29 input.addEventListener('input', function () { 30 const query = this.value.trim(); 31 resultsList.innerHTML = ''; 32 currentIndex = -1; 33 34 if (query.length === 0) return; 35 36 const results = fuse.search(query); 37 results.forEach((result, index) => { 38 const page = result.item; 39 const li = document.createElement('li'); 40 li.innerHTML = `<a href="${DOKU_BASE}doku.php?id=${page.id}">${page.title}</a>`; 41 li.dataset.index = index; 42 resultsList.appendChild(li); 43 }); 44 if (results.length === 0) { 45 resultsList.innerHTML = '<li>No matches found</li>'; 46 } 47 }); 48 49 input.addEventListener('keydown', function (e) { 50 const items = resultsList.getElementsByTagName('li'); 51 if (items.length === 0) return; 52 53 if (e.key === 'ArrowDown') { 54 e.preventDefault(); 55 if (currentIndex < items.length - 1) { 56 currentIndex++; 57 updateHighlight(items); 58 } 59 } else if (e.key === 'ArrowUp') { 60 e.preventDefault(); 61 if (currentIndex > 0) { 62 currentIndex--; 63 updateHighlight(items); 64 } else { 65 currentIndex = -1; 66 updateHighlight(items); 67 } 68 } else if (e.key === 'Enter' && currentIndex >= 0) { 69 e.preventDefault(); 70 const selectedLink = items[currentIndex].querySelector('a'); 71 if (selectedLink) window.location.href = selectedLink.href; 72 } 73 }); 74 75 function updateHighlight(items) { 76 for (let i = 0; i < items.length; i++) { 77 items[i].classList.remove('highlighted'); 78 if (i === currentIndex) { 79 items[i].classList.add('highlighted'); 80 items[i].scrollIntoView({ block: 'nearest' }); 81 } 82 } 83 } 84 }) 85 .catch(error => { 86 // console.error('Error fetching page data:', error); 87 resultsList.innerHTML = '<li>Error loading search data</li>'; 88 }); 89 });