Skip to content

Commit

Permalink
Add some site search enhancement syslog-ng#15 (syslog-ng#20)
Browse files Browse the repository at this point in the history
- restored original lunr search algorithm
- added search help tooltip and page
- search string is now preserved between page reloads
- excluded not wanted pages from search results
- tooltip is getting hidden automatically now on window focus lost as
well

Solves: syslog-ng#15 

Signed-off-by: Hofi <hofione@gmail.com>
  • Loading branch information
mrgarris0n authored May 9, 2024
2 parents a953b79 + c3cf7d7 commit ce2ef70
Show file tree
Hide file tree
Showing 16 changed files with 447 additions and 202 deletions.
7 changes: 4 additions & 3 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,14 @@ defaults:

# Search settings
search: true
# Setting search_full_content to true could impact page load performance!
search_full_content: true

search_provider: lunr
lunr:
search_within_pages: true
# Setting search_full_content to true could impact page load performance!
search_full_content: true
# No we have all the valuable content in collections
# Standalone pages like, sitemap.xml, 404, etc. should not be searched
search_within_pages: false

# search_provider: algolia
# algolia:
Expand Down
10 changes: 10 additions & 0 deletions _data/external_links.yml
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,13 @@ ietf-syslog-proto:
id: ietf-syslog-proto
url: https://tools.ietf.org/html/rfc5424
title: [ "new syslog (IETF-syslog) protocol" ]

lunr-site:
id: lunr-site
url: https://lunrjs.com
title: [ "Lunar site" ]

lunr-search-help:
id: lunr-search-help
url: https://lunrjs.com/guides/searching.html
title: [ "Lunar search help" ]
10 changes: 8 additions & 2 deletions _includes/search/lunr-search-scripts.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
{% assign lang = site.locale | slice: 0,2 | default: "en" %}
{% comment %}
<!-- {% assign lang = site.locale | slice: 0,2 | default: "en" %}
NOTE: currently only EN is supported
{% case lang %}
{% when "gr" %}
{% assign lang = "gr" %}
{% else %}
{% assign lang = "en" %}
{% endcase %}
{% endcase %} -->
{% endcomment %}
{% assign lang = "en" %}
<script src="{{ '/assets/js/lunr/lunr.min.js' | relative_url }}"></script>
<script src="{{ '/assets/js/lunr/lunr-store.js' | relative_url }}"></script>
<script src="{{ '/assets/js/lunr/lunr-' | append: lang | append: '.js' | relative_url }}"></script>
1 change: 1 addition & 0 deletions _includes/search/search_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
{{ site.data.ui-text[site.locale].search_label_text | default: 'Enter your search term...' }}
</label>
<input type="search" id="search" class="search-input" tabindex="-1" placeholder="{{ site.data.ui-text[site.locale].search_placeholder_text | default: 'Enter your search term...' }}" />
<a class="search-help content-tooltip full-content-tooltip nav-link" href="/lunr_search_help.html">[ Hover or click for search help ]</a>
</form>
<div id="results" class="results"></div>
{%- when "google" -%}
Expand Down
13 changes: 7 additions & 6 deletions _js/custom/custom-init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
Custom js init stuff
========================================================================== */

$(function () {

// Override the default lunr tokenizer options, as a quick fix added _ to the list to get ignored the differences like option-1 and option_1
lunr.tokenizer.separator = /[\s\-_]+/

});
// $(function () {
//
// // Override the default lunr tokenizer options, as a quick fix added _ to the list to get ignored the differences like option-1 and option_1
// //lunr.tokenizer.separator = /[\s\-_]+/
// lunr.tokenizer.separator = /[\s]+/
//
// });
133 changes: 91 additions & 42 deletions _js/custom/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,35 @@

$(function () {
// FIXME: How to get the real base URL (without using Liquid and Front Matter) ?!?!
const docRootName = 'doc';
const docRoot = '';
const notFoundPageName = '404.html';
const contentID = 'article';

function trimCharFromString(str, char) {
// Create a regular expression to match the given character at the beginning or end of the string
const regex = new RegExp(`^${char}|${char}$`, 'g');

// Use replace() to trim the character from the string
return str.replace(regex, '');
}

function hideTocIfNotNeeded(docObject, forceHide) {
var shouldHide = forceHide;
var tocElement = docObject.querySelector('.toc');

if (tocElement) {
var tocMenuElement = tocElement.querySelector('.toc__menu');
if (null == tocMenuElement || false == tocMenuElement.hasChildNodes)
shouldHide = true;
}
if (shouldHide) {
// TOC is autogenerated via 'include toc.html' so its size is not known prior the call of toc.html
// Signal emptiness, css will hide if needed based on it and config settings
// NOTE: Not hiding directly here to behave the same way like the left sidebar does
tocElement.classList.add('empty');
}
}

function adjustSidebars() {
// Identify the URL of the loaded page
var loadedPageUrl = window.location.pathname;
Expand Down Expand Up @@ -56,15 +81,7 @@ $(function () {
matchingNavItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// TOC is autogenerated via 'include toc.html' so its size is not known prior the call of toc.html
// Signal emptiness, css will hide if needed based on it and config settings
// NOTE: Not hiding directly here to behave the same way like the left sidebar does
var tocElement = document.querySelector('.toc');
if (tocElement) {
var tocMenuElement = tocElement.querySelector('.toc__menu');
if (null == tocMenuElement || false == tocMenuElement.hasChildNodes)
tocElement.classList.add('empty');
}
hideTocIfNotNeeded(document, false);
}
}

Expand Down Expand Up @@ -158,7 +175,7 @@ $(function () {
error => {
if (error == "Error: 404") {
var baseURL = window.location.origin;
var notFoundURL = baseURL + '/' + docRoot + '/' + notFoundPageName;
var notFoundURL = baseURL + '/' + (docRoot != '' ? docRoot + '/' : '') + notFoundPageName;

updateContentFromUrl(notFoundURL);
}
Expand All @@ -174,15 +191,20 @@ $(function () {
// Functions to handle link clicks
// -------------
function getCollectionFromDocPath(url) {
var parts = url.href.split('/');
var docIndex = parts.indexOf(docRootName);
var collection = '';
var parts = trimCharFromString(url.pathname, '/').split('/');

// If 'doc' is not found or it's the last segment, return an empty string
if (docIndex === -1 || docIndex === parts.length - 1) {
return '';
if (docRoot == '') {
collection = parts[0];
}
else {
var docIndex = parts.indexOf(docRoot);

return parts[docIndex + 1];
// If 'docRoot' is found or it is not the last segment, return the next part after it as the collection name
if (docIndex !== -1 && docIndex !== parts.length - 1)
collection = parts[docIndex + 1];
}
return collection;
}

function sameCollection(url1, url2) {
Expand All @@ -194,6 +216,9 @@ $(function () {

function handleNavLinkClick(event) {
if (!event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) {
if (tooltipTarget)
hideTooltip(true);

var updated = false;
// Get the relative URL value and update the browser URL
// Use originalTarget or explicitTarget to get the correct one even for clicks from the tooltips
Expand All @@ -205,7 +230,7 @@ $(function () {
// Try to load into the inner content frame only if the collection has not changed
// Otherwise let the original click flow take effect, as the nav bar must be reloaded too
// for a different collection
if (url.origin == window.location.origin && sameCollection(url, window.location)) {
if (url.origin === window.location.origin && anchorElement.target !== '_blank' && sameCollection(url, window.location)) {
// Prevent default navigation behavior, we will use our content load method
event.preventDefault();

Expand All @@ -224,7 +249,7 @@ $(function () {
event.target.blur();
}
if (false == updated)
console.debug("Different collection item requested, loading full page...")
console.debug("Different collection item or new tab/page requested, loading full page...")
}
}

Expand Down Expand Up @@ -287,10 +312,13 @@ $(function () {
});
}

function alterPageTitle(content) {
function alterPageForTooltip(content, fullPageContent) {
let tempContainer = document.createElement('div');
tempContainer.innerHTML = content;

if (fullPageContent)
hideTocIfNotNeeded(tempContainer, true);

// Remove/Override some default title style formatting to look better in the tooltip
const pageTitle = tempContainer.querySelector('#page-title');
if (pageTitle)
Expand All @@ -300,7 +328,11 @@ $(function () {
if (pageSubtitle)
pageSubtitle.style.borderBottom = '0px';

return tempContainer.innerHTML;
var newContent = tempContainer.innerHTML
// remove unnecessary, reqursive inner content tooltips
newContent = newContent.replace(/\bcontent-tooltip\b/g, '');

return newContent;
}

function loadContentPartFrom(url, onSuccess, onError) {
Expand All @@ -319,17 +351,14 @@ $(function () {
var startHeading = newContent.querySelector('#' + startHeadingId);
if (startHeading) {
var content = startHeading.outerHTML; // Include the starting <h> element itself

var nextSibling = startHeading.nextElementSibling;

// Collect all siblings until the next heading or the end of the document
// FIXME: This magic 6 must be maintained together now with generate_links.rb (and other places ?!)
while (nextSibling && nextSibling.tagName !== 'H1' && nextSibling.tagName !== 'H2' && nextSibling.tagName !== 'H3' && nextSibling.tagName !== 'H4' && nextSibling.tagName !== 'H5' && nextSibling.tagName !== 'H6') {
content += nextSibling.outerHTML;
nextSibling = nextSibling.nextElementSibling;
}
if (false == hasAnchor)
content = alterPageTitle(content);

onSuccess(content);
}
else
Expand Down Expand Up @@ -373,9 +402,14 @@ $(function () {
tooltip.style.setProperty(posName, newPosition);
}

function showTooltip(event, tooltipText) {
function showTooltip(event, tooltipText, fullPageContent) {
tooltip.innerHTML = tooltipText.innerHTML;

if (fullPageContent)
tooltip.classList.add("full-content-tooltip");
else
tooltip.classList.remove("full-content-tooltip");

var tooltipPos = getTooltipPos(event, tooltipTarget)
var tooltipArrowLeftShift = 2 * toolTipArrowSize;

Expand Down Expand Up @@ -436,31 +470,41 @@ $(function () {
element.appendChild(tooltipText);

element.addEventListener('mouseover', function (event) {
var fullPageContent = element.classList.contains('full-content-tooltip');

tooltipTarget = element;

// Load only once per page load
if (tooltipText.innerHTML === '') {
var url = element.href;
loadContentPartFrom(
url,
newContent => {
// remove unnecessary inner content tooltips
newContent = newContent.replace(/\bcontent-tooltip\b/g, '');
// cache for reuse
tooltipText.innerHTML = newContent;
showTooltip(event, tooltipText);
},
error => {
console.error('Error loading the tooltip content!' + error);
}
);

function onSuccess(newContent) {
if (typeof (newContent) === 'object' && 'innerHTML' in newContent)
newContent = newContent.innerHTML;
newContent = alterPageForTooltip(newContent, fullPageContent);

// cache for reuse
tooltipText.innerHTML = newContent;
showTooltip(event, tooltipText, fullPageContent);
}

function onError(error) {
console.error('Error loading the tooltip content!' + error);
}

if (fullPageContent) {
loadContentFromUrl(url, newContent => onSuccess(newContent), error => onError(error));
}
else {
loadContentPartFrom(url, newContent => onSuccess(newContent), error => onError(error));
}
}
else
showTooltip(event, tooltipText);
showTooltip(event, tooltipText, fullPageContent);
});
});

document.addEventListener('mousemove', (event) => {
document.addEventListener('mousemove', function (event) {
if (shouldHideTooltip(event.target)) {
if (tooltipTarget)
hideTooltip(true);
Expand All @@ -471,7 +515,7 @@ $(function () {
}
});

document.addEventListener('scroll', (event) => {
document.addEventListener('scroll', function (event) {
if (elementUnderCursor == null || shouldHideTooltip(elementUnderCursor)) {
if (tooltipTarget)
hideTooltip(true);
Expand All @@ -481,6 +525,11 @@ $(function () {
document.addEventListener("mouseover", function (event) {
elementUnderCursor = event.target;
});

window.addEventListener('blur', function () {
if (tooltipTarget)
hideTooltip(true);
});
}

// -------------
Expand Down
Loading

0 comments on commit ce2ef70

Please sign in to comment.