PERF: Move highlightjs to a background worker, and add result cache (#10191)

Syntax highlighting is a CPU-intensive process which we run a lot while rendering posts and while using the composer preview. Moving it to a background worker releases the main thread to the browser, which makes the UX much smoother.
This commit is contained in:
David Taylor
2020-07-15 12:48:07 +01:00
committed by GitHub
parent 052178efa7
commit d09f283e91
10 changed files with 277 additions and 46 deletions
@@ -1,11 +1,37 @@
import Component from "@ember/component";
import { on, observes } from "discourse-common/utils/decorators";
import highlightSyntax from "discourse/lib/highlight-syntax";
import { highlightText } from "discourse/lib/highlight-syntax";
import { escapeExpression } from "discourse/lib/utilities";
import discourseComputed from "discourse-common/utils/decorators";
import { htmlSafe } from "@ember/template";
export default Component.extend({
@on("didInsertElement")
@observes("code")
_refresh: function() {
highlightSyntax($(this.element));
didReceiveAttrs() {
this._super(...arguments);
if (this.code === this.previousCode) return;
this.set("previousCode", this.code);
this.set("highlightResult", null);
const toHighlight = this.code;
highlightText(escapeExpression(toHighlight), this.lang).then(
({ result }) => {
if (toHighlight !== this.code) return; // Code has changed since highlight was requested
this.set("highlightResult", result);
}
);
},
@discourseComputed("code", "highlightResult")
displayCode(code, highlightResult) {
if (highlightResult) return htmlSafe(highlightResult);
return code;
},
@discourseComputed("highlightResult", "lang")
codeClasses(highlightResult, lang) {
const classes = [];
if (lang) classes.push(lang);
if (highlightResult) classes.push("hljs");
return classes.join(" ");
}
});