Getting Started
+Some text
+Other Section
+Other text
+Yet Another Section
+More text
+diff --git a/CHANGES.rst b/CHANGES.rst index f52b9e3d16b..16253c72c59 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -33,6 +33,8 @@ Features added Bugs fixed ---------- +* #11944: Use anchor in search preview. + Patch by Will Lachance. * #11668: Raise a useful error when ``theme.conf`` is missing. Patch by Vinay Sajip. * #11622: Ensure that the order of keys in ``searchindex.js`` is deterministic. diff --git a/sphinx/themes/basic/static/searchtools.js b/sphinx/themes/basic/static/searchtools.js index 8bb1af5a448..e9a43fa5d3e 100644 --- a/sphinx/themes/basic/static/searchtools.js +++ b/sphinx/themes/basic/static/searchtools.js @@ -99,7 +99,7 @@ const _displayItem = (item, searchTerms, highlightTerms) => { .then((data) => { if (data) listItem.appendChild( - Search.makeSearchSummary(data, searchTerms) + Search.makeSearchSummary(data, searchTerms, anchor) ); // highlight search terms in the summary if (SPHINX_HIGHLIGHT_ENABLED) // set in sphinx_highlight.js @@ -160,11 +160,22 @@ const Search = { _queued_query: null, _pulse_status: -1, - htmlToText: (htmlString) => { + htmlToText: (htmlString, anchor) => { const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html'); htmlElement.querySelectorAll(".headerlink").forEach((el) => { el.remove() }); + if (anchor) { + const anchorContent = htmlElement.querySelector(anchor); + if (anchorContent) return anchorContent.textContent; + + console.warn( + `Anchor block not found. Sphinx search tries to obtain it via '${anchor}'. Check your theme or template.` + ); + } + + // if anchor not specified or not found, fall back to main content const docContent = htmlElement.querySelector('[role="main"]'); if (docContent) return docContent.textContent; + console.warn( "Content block not found. Sphinx search tries to obtain it via '[role=main]'. Could you check your theme or template." ); @@ -549,8 +560,8 @@ const Search = { * search summary for a given text. keywords is a list * of stemmed words. */ - makeSearchSummary: (htmlText, keywords) => { - const text = Search.htmlToText(htmlText); + makeSearchSummary: (htmlText, keywords, anchor) => { + const text = Search.htmlToText(htmlText, anchor); if (text === "") return null; const textLower = text.toLowerCase(); diff --git a/tests/js/searchtools.js b/tests/js/searchtools.js index c9e0c43d3b2..b70c2d32528 100644 --- a/tests/js/searchtools.js +++ b/tests/js/searchtools.js @@ -31,6 +31,38 @@ describe('Basic html theme search', function() { }); +describe("htmlToText", function() { + + const testHTML = ` +
Some text
+Other text
+More text
+