|
1 | 1 | import Base from "../../core/base"; |
2 | | -import utils from "../../core/utils"; |
| 2 | +import Parser from "../../core/parser"; |
| 3 | + |
| 4 | +export const parser = new Parser("syntax-highlight"); |
| 5 | +parser.addArgument("language", "html"); |
| 6 | +parser.addArgument("theme", "dark", ["dark", "light"]); |
| 7 | +parser.addArgument("features", null, ["line-highlight", "line-numbers"], true); |
3 | 8 |
|
4 | 9 | export default Base.extend({ |
5 | 10 | name: "syntax-highlight", |
6 | 11 | trigger: ".pat-syntax-highlight", |
7 | 12 |
|
8 | 13 | async init() { |
9 | | - const Prettify = (await import("google-code-prettify/src/prettify")).default; // prettier-ignore |
10 | | - this.$el.addClass("prettyprint"); |
11 | | - utils.debounce(Prettify.prettyPrint, 50)(); |
| 14 | + this.options = parser.parse(this.el, this.options); |
| 15 | + |
| 16 | + let theme; |
| 17 | + if (this.options.theme === "light") { |
| 18 | + theme = ""; |
| 19 | + } else if (this.options.theme === "dark") { |
| 20 | + theme = "okaidia"; |
| 21 | + } else { |
| 22 | + theme = this.options.theme; |
| 23 | + } |
| 24 | + |
| 25 | + import(`prismjs/themes/prism${theme ? "-" + theme : ""}.css`); |
| 26 | + const Prism = (await import("prismjs")).default; |
| 27 | + |
| 28 | + if (this.options.features.includes("line-highlight")) { |
| 29 | + import("prismjs/plugins/line-highlight/prism-line-highlight.css"); |
| 30 | + await import("prismjs/plugins/line-highlight/prism-line-highlight.js"); |
| 31 | + } |
| 32 | + |
| 33 | + if (this.options.features.includes("line-numbers")) { |
| 34 | + import("prismjs/plugins/line-numbers/prism-line-numbers.css"); |
| 35 | + await import("prismjs/plugins/line-numbers/prism-line-numbers.js"); |
| 36 | + this.el.classList.add("line-numbers"); |
| 37 | + } |
| 38 | + |
| 39 | + Prism.manual = true; |
| 40 | + |
| 41 | + let _el = this.el; |
| 42 | + const code_el = [...this.el.children].filter((it) => it.tagName === "CODE")?.[0]; |
| 43 | + if (code_el) { |
| 44 | + _el = code_el; |
| 45 | + } |
| 46 | + |
| 47 | + // Get the language |
| 48 | + let language = [..._el.classList, ...this.el.classList] |
| 49 | + .filter((it) => { |
| 50 | + return it.startsWith("language-") || it.startsWith("lang-"); |
| 51 | + })?.[0] |
| 52 | + ?.replace("language-", "") |
| 53 | + ?.replace("lang-", ""); |
| 54 | + // CSS class language always win. |
| 55 | + language = language || this.options.language || "html"; |
| 56 | + // Set the language on the code element (ignored if already set) |
| 57 | + this.el.classList.add(`language-${language}`); |
| 58 | + _el.classList.add(`language-${language}`); |
| 59 | + |
| 60 | + Prism.highlightElement(_el); |
12 | 61 | }, |
13 | 62 | }); |
0 commit comments