SillyTavern/public/scripts/setting-search.js

55 lines
2.0 KiB
JavaScript
Raw Normal View History

/**
* Search for settings that match the search string and highlight them.
*/
2023-09-19 07:19:22 +02:00
async function searchSettings() {
removeHighlighting(); // Remove previous highlights
2023-12-02 19:04:51 +01:00
const searchString = String($('#settingsSearch').val());
const searchableText = $('#user-settings-block-content'); // Get the HTML block
if (searchString.trim() !== '') {
2023-09-19 07:19:22 +02:00
highlightMatchingElements(searchableText[0], searchString); // Highlight matching elements
}
}
/**
* Check if the element is a child of a header element
* @param {HTMLElement | Text | Document | Comment} element Settings block HTML element
* @returns {boolean} True if the element is a child of a header element, false otherwise
*/
2023-09-19 07:19:22 +02:00
function isParentHeader(element) {
return $(element).closest('h4, h3').length > 0;
}
/**
* Recursively highlight elements that match the search string
* @param {HTMLElement | Text | Document | Comment} element Settings block HTML element
* @param {string} searchString Search string
*/
2023-09-19 07:19:22 +02:00
function highlightMatchingElements(element, searchString) {
$(element).contents().each(function () {
const isTextNode = this.nodeType === Node.TEXT_NODE;
const isElementNode = this.nodeType === Node.ELEMENT_NODE;
2023-12-02 19:04:51 +01:00
if (isTextNode && this.nodeValue.trim() !== '' && !isParentHeader(this)) {
2023-09-19 07:19:22 +02:00
const parentElement = $(this).parent();
const elementText = this.nodeValue;
if (elementText.toLowerCase().includes(searchString.toLowerCase())) {
parentElement.addClass('highlighted'); // Add CSS class to highlight matched elements
}
2023-12-02 19:04:51 +01:00
} else if (isElementNode && !$(this).is('h4')) {
2023-09-19 07:19:22 +02:00
highlightMatchingElements(this, searchString);
}
});
}
/**
* Remove highlighting from previously highlighted elements.
*/
2023-09-19 07:19:22 +02:00
function removeHighlighting() {
2023-12-02 19:04:51 +01:00
$('.highlighted').removeClass('highlighted'); // Remove CSS class from previously highlighted elements
2023-09-19 07:19:22 +02:00
}
2023-09-19 07:19:22 +02:00
jQuery(() => {
$('#settingsSearch').on('input change', searchSettings);
});