1
Fork 0

Render Markdown in search results

Previously Markdown documentation was not rendered to HTML for search results,
which led to the output not being very readable, particularly for inline code.
This PR fixes that by rendering Markdown to HTML with the help of pulldown-cmark
(the library rustdoc uses to parse Markdown for the main text of documentation).
However, the text for the title attribute (the text shown when you hover over an
element) still uses the plain-text rendering since it is displayed in browsers
as plain-text.

Only these styles will be rendered; everything else is stripped away:

* *italics*
* **bold**
* `inline code`
This commit is contained in:
Camelid 2020-10-04 20:42:34 -07:00
parent b4def89d76
commit 5d4a7128d9
8 changed files with 166 additions and 50 deletions

View file

@ -1611,7 +1611,7 @@ function defocusSearchBar() {
item.displayPath + "<span class=\"" + type + "\">" +
name + "</span></a></td><td>" +
"<a href=\"" + item.href + "\">" +
"<span class=\"desc\">" + escape(item.desc) +
"<span class=\"desc\">" + item.desc +
"&nbsp;</span></a></td></tr>";
});
output += "</table>";
@ -2013,7 +2013,9 @@ function defocusSearchBar() {
}
var link = document.createElement("a");
link.href = rootPath + crates[i] + "/index.html";
link.title = rawSearchIndex[crates[i]].doc;
// The summary in the search index has HTML, so we need to
// dynamically render it as plaintext.
link.title = convertHTMLToPlaintext(rawSearchIndex[crates[i]].doc);
link.className = klass;
link.textContent = crates[i];
@ -2026,6 +2028,25 @@ function defocusSearchBar() {
}
};
/**
* Convert HTML to plaintext:
*
* * Replace "<code>foo</code>" with "`foo`"
* * Strip all other HTML tags
*
* Used by the dynamic sidebar crate list renderer.
*
* @param {[string]} html [The HTML to convert]
* @return {[string]} [The resulting plaintext]
*/
function convertHTMLToPlaintext(html) {
var dom = new DOMParser().parseFromString(
html.replace('<code>', '`').replace('</code>', '`'),
'text/html',
);
return dom.body.innerText;
}
// delayed sidebar rendering.
window.initSidebarItems = function(items) {