Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active December 24, 2023 06:32
Show Gist options
  • Save fsubal/e7f61ec465bd2a09221cc5753367fb67 to your computer and use it in GitHub Desktop.
Save fsubal/e7f61ec465bd2a09221cc5753367fb67 to your computer and use it in GitHub Desktop.
import hljs from 'highlight.js'
import typescript from 'highlight.js/lib/languages/typescript'
const css = new CSSStyleSheet()
css.replaceSync(`
@import 'highlight.js/styles/github-dark.css';
overflow-x: auto;
font-size: 12px;
border-radius: 8px;
font-family: 'SF Mono', SFMono-Regular, ui-monospace, 'DejaVu Sans Mono',
Menlo, Consolas, monospace;
`)
export class CodeBlock extends HTMLPreElement {
shadowRoot!: ShadowRoot
content = this.innerText
static {
customElements.define('code-block', this)
hljs.registerLanguage('typescript', typescript)
}
static get observedAttributes() {
return ['language']
}
get language() {
return this.getAttribute('language') ?? 'typescript'
}
constructor() {
super()
this.attachShadow({ mode: 'closed' })
this.shadowRoot.adoptedStyleSheets = [css]
}
connectedCallback() {
this.render()
}
attributeChangedCallback() {
this.render()
}
render() {
const { value } = hljs.highlight(this.content, {
language: this.language
})
const code = document.createElement('code')
code.innerHTML = value
code.classList.add('hljs')
this.shadowRoot.appendChild(code)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment