Merge pull request #458 from ericcornelissen/check-hljs-once

Check if hljs is not null only once
This commit is contained in:
Rodrigo Fernandes 2022-11-04 23:46:45 +00:00 committed by GitHub
commit 7b6ee267af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -137,16 +137,14 @@ export class Diff2HtmlUI {
} }
highlightCode(): void { highlightCode(): void {
if (this.hljs === null) { const hljs = this.hljs;
if (hljs === null) {
throw new Error('Missing a `highlight.js` implementation. Please provide one when instantiating Diff2HtmlUI.'); throw new Error('Missing a `highlight.js` implementation. Please provide one when instantiating Diff2HtmlUI.');
} }
// Collect all the diff files and execute the highlight on their lines // Collect all the diff files and execute the highlight on their lines
const files = this.targetElement.querySelectorAll('.d2h-file-wrapper'); const files = this.targetElement.querySelectorAll('.d2h-file-wrapper');
files.forEach(file => { files.forEach(file => {
// HACK: help Typescript know that `this.hljs` is defined since we already checked it
if (this.hljs === null) return;
const language = file.getAttribute('data-lang'); const language = file.getAttribute('data-lang');
if (!(this.config.highlightLanguages instanceof Map)) { if (!(this.config.highlightLanguages instanceof Map)) {
@ -164,16 +162,13 @@ export class Diff2HtmlUI {
// Collect all the code lines and execute the highlight on them // Collect all the code lines and execute the highlight on them
const codeLines = file.querySelectorAll('.d2h-code-line-ctn'); const codeLines = file.querySelectorAll('.d2h-code-line-ctn');
codeLines.forEach(line => { codeLines.forEach(line => {
// HACK: help Typescript know that `this.hljs` is defined since we already checked it
if (this.hljs === null) return;
const text = line.textContent; const text = line.textContent;
const lineParent = line.parentNode; const lineParent = line.parentNode;
if (text === null || lineParent === null || !this.isElement(lineParent)) return; if (text === null || lineParent === null || !this.isElement(lineParent)) return;
const result: HighlightResult = closeTags( const result: HighlightResult = closeTags(
this.hljs.highlight(text, { hljs.highlight(text, {
language: hljsLanguage, language: hljsLanguage,
ignoreIllegals: true, ignoreIllegals: true,
}), }),