Skip to content

Commit 420044b

Browse files
committed
HTML Search: Use anchor for search previews
1 parent 4ef8752 commit 420044b

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

sphinx/themes/basic/static/searchtools.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const _displayItem = (item, searchTerms, highlightTerms) => {
9999
.then((data) => {
100100
if (data)
101101
listItem.appendChild(
102-
Search.makeSearchSummary(data, searchTerms)
102+
Search.makeSearchSummary(data, searchTerms, anchor)
103103
);
104104
// highlight search terms in the summary
105105
if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js
@@ -160,10 +160,15 @@ const Search = {
160160
_queued_query: null,
161161
_pulse_status: -1,
162162

163-
htmlToText: (htmlString) => {
163+
htmlToText: (htmlString, anchor) => {
164164
const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html');
165165
htmlElement.querySelectorAll(".headerlink").forEach((el) => { el.remove() });
166-
const docContent = htmlElement.querySelector('[role="main"]');
166+
let docContent = undefined;
167+
if (anchor && htmlElement.querySelector(anchor)) {
168+
docContent = htmlElement.querySelector(anchor);
169+
} else {
170+
docContent = htmlElement.querySelector('[role="main"]');
171+
}
167172
if (docContent) return docContent.textContent;
168173
console.warn(
169174
"Content block not found. Sphinx search tries to obtain it via '[role=main]'. Could you check your theme or template."
@@ -549,8 +554,8 @@ const Search = {
549554
* search summary for a given text. keywords is a list
550555
* of stemmed words.
551556
*/
552-
makeSearchSummary: (htmlText, keywords) => {
553-
const text = Search.htmlToText(htmlText);
557+
makeSearchSummary: (htmlText, keywords, anchor) => {
558+
const text = Search.htmlToText(htmlText, anchor);
554559
if (text === "") return null;
555560

556561
const textLower = text.toLowerCase();

0 commit comments

Comments
 (0)