Code highlighting fixes:
All checks were successful
continuous-integration/drone/push Build is passing

- Fix pre+code element moving
- Do not highlight if pre is already formatted
This commit is contained in:
Cadence Ember 2020-11-14 17:27:13 +13:00
parent c0c7278279
commit 0960ca7e97
Signed by: cadence
GPG key ID: BC1C2C61CF521B17

View file

@ -5,24 +5,29 @@ class HighlightedCode extends ElemJS {
constructor(element) { constructor(element) {
super(element) super(element)
if (this.element.tagName === "PRE" && this.element.children.length === 1 && this.element.children[0].tagName === "CODE") { if (this.element.tagName === "PRE" && this.element.children.length === 1 && this.element.children[0].tagName === "CODE") {
// we shouldn't nest code inside a pre. put the text in the pre directly. // we shouldn't nest <code> inside <pre>. put the text in <pre> directly.
const code = this.element.children[0] const code = this.element.children[0]
this.clearChildren() this.clearChildren()
for (const child of code.childNodes) { while (code.firstChild) {
this.element.appendChild(child) this.element.appendChild(code.firstChild)
} }
} }
if (this.element.textContent.length > 80) { let shouldHighlight = (
// if there are child _elements_, it's already formatted, we shouldn't mess that up
this.element.children.length === 0
/* /*
no need to highlight very short code blocks: no need to highlight very short code blocks:
- content inside might not be code, some users still use code blocks - content inside might not be code, some users still use code blocks
for plaintext quotes for plaintext quotes
- language detection will almost certainly be incorrect - language detection will almost certainly be incorrect
- even if it's code and the language is detected, the user will - even if it's code and the language is detected, the user will
be able to mentally format small amounts of code themselves be able to mentally format small amounts of code themselves
feel free to change the threshold number feel free to change the threshold number
*/ */
&& this.element.textContent.length > 80
)
if (shouldHighlight) {
lazyLoad("https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10/build/highlight.min.js").then(hljs => hljs.highlightBlock(this.element)) lazyLoad("https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10/build/highlight.min.js").then(hljs => hljs.highlightBlock(this.element))
} }
} }