Skip to content

Commit

Permalink
fix same- page result navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
welpo committed Jan 7, 2024
1 parent a1e253d commit 9382997
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 16 deletions.
38 changes: 24 additions & 14 deletions static/js/searchElasticlunr.js
Original file line number Diff line number Diff line change
Expand Up @@ -2945,32 +2945,40 @@ window.onload = function () {
// Display the results.
let resultIdCounter = 0; // Counter to generate unique IDs.
searchResults.forEach(function (result) {
if (result.doc.body !== '') {
if (result.doc.title || result.doc.path || result.doc.id) {
const resultDiv = document.createElement('div');
resultDiv.setAttribute('role', 'option');
resultDiv.id = 'result-' + resultIdCounter++;
resultDiv.innerHTML = '<a href><span></span><span></span></a>';
const linkElement = resultDiv.querySelector('a');
const titleElement = resultDiv.querySelector('span:first-child');
const snippetElement = resultDiv.querySelector('span:nth-child(2)');
// Return a link with text fragment, scrolling and highlighting the search term.
const encodedSearchTerm = encodeURIComponent(searchTerm);
linkElement.href = `${result.ref}#:~:text=${encodedSearchTerm}`;
titleElement.textContent = result.doc.title;

// Determine the text for the title.
titleElement.textContent =
result.doc.title || result.doc.path || result.doc.id;

// Determine if the body or description is available for the snippet.
let snippetText = result.doc.body
? generateSnippet(result.doc.body, searchTerm.split(/\s+/))
: result.doc.description
? result.doc.description
: '';
snippetElement.innerHTML = snippetText;

// Create the hyperlink.
let href = result.ref;
if (result.doc.body) {
snippetElement.innerHTML = generateSnippet(
result.doc.body,
searchTerm.split(/\s+/)
);
} else {
// Handle the case where body is undefined or empty
console.error('Document body is undefined for result:', result);
snippetElement.innerHTML = ''; // Or set some default message
// Include text fragment if body is available.
const encodedSearchTerm = encodeURIComponent(searchTerm);
href += `#:~:text=${encodedSearchTerm}`;
}
linkElement.href = href;

results.appendChild(resultDiv);
}
});

searchInput.setAttribute(
'aria-expanded',
resultIdCounter > 0 ? 'true' : 'false'
Expand Down Expand Up @@ -3093,11 +3101,13 @@ window.onload = function () {
}

if (event.key === 'Enter' && activeDiv) {
event.preventDefault();
event.stopImmediatePropagation();
const anchorTag = activeDiv.querySelector('a');
if (anchorTag) {
event.preventDefault();
window.location.href = anchorTag.getAttribute('href');
}
closeModal(); // Necessary when linking to the current page.
}
});
};
Loading

0 comments on commit 9382997

Please sign in to comment.