Skip to content

Commit

Permalink
style(pre-commit): auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
pre-commit-ci[bot] committed Aug 12, 2024
1 parent dd9b65e commit c5cf5cc
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 70 deletions.
142 changes: 73 additions & 69 deletions docs/_static/searchtools.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,18 @@ if (typeof Scorer === "undefined") {

// Global search result kind enum, used by themes to style search results.
class SearchResultContext {
static get index() { return "index"; }
static get object() { return "object"; }
static get text() { return "text"; }
static get title() { return "title"; }
static get index() {
return "index";
}
static get object() {
return "object";
}
static get text() {
return "text";
}
static get title() {
return "title";
}
}

const _removeChildren = (element) => {
Expand All @@ -62,8 +70,7 @@ const _removeChildren = (element) => {
/**
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
*/
const _escapeRegExp = (string) =>
string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
const _escapeRegExp = (string) => string.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string

const _displayItem = (item, searchTerms, highlightTerms) => {
const docBuilder = DOCUMENTATION_OPTIONS.BUILDER;
Expand All @@ -84,8 +91,7 @@ const _displayItem = (item, searchTerms, highlightTerms) => {
if (docBuilder === "dirhtml") {
// dirhtml builder
let dirname = docName + "/";
if (dirname.match(/\/index\/$/))
dirname = dirname.substring(0, dirname.length - 6);
if (dirname.match(/\/index\/$/)) dirname = dirname.substring(0, dirname.length - 6);
else if (dirname === "index/") dirname = "";
requestUrl = contentRoot + dirname;
linkUrl = requestUrl;
Expand All @@ -99,23 +105,23 @@ const _displayItem = (item, searchTerms, highlightTerms) => {
linkEl.dataset.score = score;
linkEl.innerHTML = title;
if (descr) {
listItem.appendChild(document.createElement("span")).innerHTML =
" (" + descr + ")";
listItem.appendChild(document.createElement("span")).innerHTML = " (" + descr + ")";
// highlight search terms in the description
if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js
if (SPHINX_HIGHLIGHT_ENABLED)
// set in sphinx_highlight.js
highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted"));
}
else if (showSearchSummary)
} else if (showSearchSummary)
fetch(requestUrl)
.then((responseData) => responseData.text())
.then((data) => {
if (data)
listItem.appendChild(
Search.makeSearchSummary(data, searchTerms, anchor)
);
listItem.appendChild(Search.makeSearchSummary(data, searchTerms, anchor));
// highlight search terms in the summary
if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js
highlightTerms.forEach((term) => _highlightText(listItem, term, "highlighted"));
if (SPHINX_HIGHLIGHT_ENABLED)
// set in sphinx_highlight.js
highlightTerms.forEach((term) =>
_highlightText(listItem, term, "highlighted"),
);
});
Search.output.appendChild(listItem);
};
Expand All @@ -124,28 +130,23 @@ const _finishSearch = (resultCount) => {
Search.title.innerText = _("Search Results");
if (!resultCount)
Search.status.innerText = Documentation.gettext(
"Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories."
"Your search did not match any documents. Please make sure that all words are spelled correctly and that you've selected enough categories.",
);
else
Search.status.innerText = Documentation.ngettext(
"Search finished, found one page matching the search query.",
"Search finished, found ${resultCount} pages matching the search query.",
resultCount,
).replace('${resultCount}', resultCount);
).replace("${resultCount}", resultCount);
};
const _displayNextItem = (
results,
resultCount,
searchTerms,
highlightTerms,
) => {
const _displayNextItem = (results, resultCount, searchTerms, highlightTerms) => {
// results left, load the summary and display it
// this is intended to be dynamic (don't sub resultsCount)
if (results.length) {
_displayItem(results.pop(), searchTerms, highlightTerms);
setTimeout(
() => _displayNextItem(results, resultCount, searchTerms, highlightTerms),
5
5,
);
}
// search finished, update title and status message
Expand Down Expand Up @@ -177,9 +178,10 @@ const _orderResultsByScoreThenName = (a, b) => {
* This is the same as ``\W+`` in Python, preserving the surrogate pair area.
*/
if (typeof splitQuery === "undefined") {
var splitQuery = (query) => query
var splitQuery = (query) =>
query
.split(/[^\p{Letter}\p{Number}_\p{Emoji_Presentation}]+/gu)
.filter(term => term) // remove remaining empty strings
.filter((term) => term); // remove remaining empty strings
}

/**
Expand All @@ -191,16 +193,18 @@ const Search = {
_pulse_status: -1,

htmlToText: (htmlString, anchor) => {
const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html');
const htmlElement = new DOMParser().parseFromString(htmlString, "text/html");
for (const removalQuery of [".headerlink", "script", "style"]) {
htmlElement.querySelectorAll(removalQuery).forEach((el) => { el.remove() });
htmlElement.querySelectorAll(removalQuery).forEach((el) => {
el.remove();
});
}
if (anchor) {
const anchorContent = htmlElement.querySelector(`[role="main"] ${anchor}`);
if (anchorContent) return anchorContent.textContent;

console.warn(
`Anchored content block not found. Sphinx search tries to obtain it via DOM query '[role=main] ${anchor}'. Check your theme or template.`
`Anchored content block not found. Sphinx search tries to obtain it via DOM query '[role=main] ${anchor}'. Check your theme or template.`,
);
}

Expand All @@ -209,16 +213,14 @@ const Search = {
if (docContent) return docContent.textContent;

console.warn(
"Content block not found. Sphinx search tries to obtain it via DOM query '[role=main]'. Check your theme or template."
"Content block not found. Sphinx search tries to obtain it via DOM query '[role=main]'. Check your theme or template.",
);
return "";
},

init: () => {
const query = new URLSearchParams(window.location.search).get("q");
document
.querySelectorAll('input[name="q"]')
.forEach((el) => (el.value = query));
document.querySelectorAll('input[name="q"]').forEach((el) => (el.value = query));
if (query) Search.performSearch(query);
},

Expand Down Expand Up @@ -295,11 +297,7 @@ const Search = {

// maybe skip this "word"
// stopwords array is from language_data.js
if (
stopwords.indexOf(queryTermLower) !== -1 ||
queryTerm.match(/^\d+$/)
)
return;
if (stopwords.indexOf(queryTermLower) !== -1 || queryTerm.match(/^\d+$/)) return;

// stem the word
let word = stemmer.stemWord(queryTermLower);
Expand All @@ -311,8 +309,9 @@ const Search = {
}
});

if (SPHINX_HIGHLIGHT_ENABLED) { // set in sphinx_highlight.js
localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" "))
if (SPHINX_HIGHLIGHT_ENABLED) {
// set in sphinx_highlight.js
localStorage.setItem("sphinx_highlight_terms", [...highlightTerms].join(" "));
}

// console.debug("SEARCH: searching for:");
Expand Down Expand Up @@ -341,10 +340,13 @@ const Search = {

const queryLower = query.toLowerCase().trim();
for (const [title, foundTitles] of Object.entries(allTitles)) {
if (title.toLowerCase().trim().includes(queryLower) && (queryLower.length >= title.length/2)) {
if (
title.toLowerCase().trim().includes(queryLower) &&
queryLower.length >= title.length / 2
) {
for (const [file, id] of foundTitles) {
const score = Math.round(Scorer.title * queryLower.length / title.length);
const boost = titles[file] === title ? 1 : 0; // add a boost for document titles
const score = Math.round((Scorer.title * queryLower.length) / title.length);
const boost = titles[file] === title ? 1 : 0; // add a boost for document titles
normalResults.push([
docNames[file],
titles[file] !== title ? `${titles[file]} > ${title}` : title,
Expand All @@ -360,9 +362,9 @@ const Search = {

// search for explicit entries in index directives
for (const [entry, foundEntries] of Object.entries(indexEntries)) {
if (entry.includes(queryLower) && (queryLower.length >= entry.length/2)) {
if (entry.includes(queryLower) && queryLower.length >= entry.length / 2) {
for (const [file, id, isMain] of foundEntries) {
const score = Math.round(100 * queryLower.length / entry.length);
const score = Math.round((100 * queryLower.length) / entry.length);
const result = [
docNames[file],
titles[file],
Expand All @@ -383,7 +385,7 @@ const Search = {

// lookup as object
objectTerms.forEach((term) =>
normalResults.push(...Search.performObjectSearch(term, objectTerms))
normalResults.push(...Search.performObjectSearch(term, objectTerms)),
);

// lookup as search terms in fulltext
Expand All @@ -408,7 +410,11 @@ const Search = {
// note the reversing of results, so that in the case of duplicates, the highest-scoring entry is kept
let seen = new Set();
results = results.reverse().reduce((acc, result) => {
let resultStr = result.slice(0, 4).concat([result[5]]).map(v => String(v)).join(',');
let resultStr = result
.slice(0, 4)
.concat([result[5]])
.map((v) => String(v))
.join(",");
if (!seen.has(resultStr)) {
acc.push(result);
seen.add(resultStr);
Expand All @@ -420,8 +426,15 @@ const Search = {
},

query: (query) => {
const [searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms] = Search._parseQuery(query);
const results = Search._performSearch(searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms);
const [searchQuery, searchTerms, excludedTerms, highlightTerms, objectTerms] =
Search._parseQuery(query);
const results = Search._performSearch(
searchQuery,
searchTerms,
excludedTerms,
highlightTerms,
objectTerms,
);

// for debugging
//Search.lastresults = results.slice(); // a copy
Expand All @@ -444,7 +457,7 @@ const Search = {
const results = [];

const objectSearchCallback = (prefix, match) => {
const name = match[4]
const name = match[4];
const fullname = (prefix ? prefix + "." : "") + name;
const fullnameLower = fullname.toLowerCase();
if (fullnameLower.indexOf(object) < 0) return;
Expand All @@ -456,8 +469,7 @@ const Search = {
// "last name" (i.e. last dotted part)
if (fullnameLower === object || parts.slice(-1)[0] === object)
score += Scorer.objNameMatch;
else if (parts.slice(-1)[0].indexOf(object) > -1)
score += Scorer.objPartialMatch; // matches in last name
else if (parts.slice(-1)[0].indexOf(object) > -1) score += Scorer.objPartialMatch; // matches in last name

const objName = objNames[match[1]][2];
const title = titles[match[0]];
Expand All @@ -468,9 +480,7 @@ const Search = {
otherTerms.delete(object);
if (otherTerms.size > 0) {
const haystack = `${prefix} ${name} ${objName} ${title}`.toLowerCase();
if (
[...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0)
)
if ([...otherTerms].some((otherTerm) => haystack.indexOf(otherTerm) < 0))
return;
}

Expand All @@ -481,8 +491,7 @@ const Search = {
const descr = objName + _(", in ") + title;

// add custom score for some objects according to scorer
if (Scorer.objPrio.hasOwnProperty(match[2]))
score += Scorer.objPrio[match[2]];
if (Scorer.objPrio.hasOwnProperty(match[2])) score += Scorer.objPrio[match[2]];
else score += Scorer.objPrioDefault;

results.push([
Expand All @@ -496,9 +505,7 @@ const Search = {
]);
};
Object.keys(objects).forEach((prefix) =>
objects[prefix].forEach((array) =>
objectSearchCallback(prefix, array)
)
objects[prefix].forEach((array) => objectSearchCallback(prefix, array)),
);
return results;
},
Expand Down Expand Up @@ -573,12 +580,9 @@ const Search = {

// as search terms with length < 3 are discarded
const filteredTermCount = [...searchTerms].filter(
(term) => term.length > 2
(term) => term.length > 2,
).length;
if (
wordList.length !== searchTerms.size &&
wordList.length !== filteredTermCount
)
if (wordList.length !== searchTerms.size && wordList.length !== filteredTermCount)
continue;

// ensure that none of the excluded terms is in the search result
Expand All @@ -588,7 +592,7 @@ const Search = {
terms[term] === file ||
titleTerms[term] === file ||
(terms[term] || []).includes(file) ||
(titleTerms[term] || []).includes(file)
(titleTerms[term] || []).includes(file),
)
)
break;
Expand Down
2 changes: 1 addition & 1 deletion requirements/docs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ sphinx-copybutton==0.5.2
furo==2024.8.6
sphinx-autodoc-typehints==2.2.3
sphinx-intl==2.2.0
typing_extensions==4.12.2
typing_extensions==4.12.2

0 comments on commit c5cf5cc

Please sign in to comment.