1- import hljs from 'highlight.js' ;
2- import typescript from 'highlight.js/lib/languages/typescript' ;
31import {
42 type CSSResultGroup ,
53 LitElement ,
@@ -17,32 +15,41 @@ import { syntaxStyles } from './syntax-style-light';
1715export class SyntaxHighlighter extends LitElement {
1816 @property ( { type : String } ) code = '' ;
1917
20- @state ( ) private highlightedCode = '' ;
18+ /**
19+ * The language to use for syntax highlighting, or 'auto' to automatically detect
20+ *
21+ * See https://highlightjs.readthedocs.io/en/latest/supported-languages.html for supported languages.
22+ */
23+ @property ( { type : String } ) language = 'auto' ;
2124
22- connectedCallback ( ) : void {
23- super . connectedCallback ( ) ;
24- hljs . registerLanguage ( 'typescript' , typescript ) ;
25- }
25+ @state ( ) private highlightedCode : string = '' ;
2626
2727 protected willUpdate ( _changedProperties : PropertyValues ) : void {
28- if ( _changedProperties . has ( 'code' ) ) {
28+ if ( _changedProperties . has ( 'code' ) || _changedProperties . has ( 'language' ) ) {
2929 this . highlightCode ( ) ;
3030 }
3131 }
3232
3333 render ( ) {
3434 return html `
35- < pre > < code class ="hljs language-typescript "> ${ unsafeHTML (
36- this . highlightedCode ,
37- ) } </ code > </ pre >
35+ < pre > < code class ="hljs "> ${ unsafeHTML ( this . highlightedCode ) } </ code > </ pre >
3836 ` ;
3937 }
4038
41- private highlightCode ( ) {
39+ private async highlightCode ( ) {
40+ const hljsModule = await import ( 'highlight.js' ) ;
41+ const hljs = hljsModule . default ;
4242 const code = this . code . trim ( ) ;
43- const highlighted = hljs . highlight ( code , {
44- language : 'typescript' ,
45- } ) . value ;
43+
44+ let highlighted : string ;
45+ if ( this . language === 'auto' ) {
46+ highlighted = hljs . highlightAuto ( code ) . value ;
47+ } else {
48+ highlighted = hljs . highlight ( code , {
49+ language : this . language ,
50+ } ) . value ;
51+ }
52+
4653 this . highlightedCode = highlighted ;
4754 }
4855
0 commit comments