One line
let a = 1
Two lines
let a = 1
let b = 2
CodeSample.js rendering itself:
let toLineSpans = code => {
code = code
.replace(/^\n+/g, '') // remove blank leading newlines, but not spaces on the first line
.trimEnd() // remove trailing whitespace
let lines = code
.split('\n')
lines[0] = lines[0].trim()
lines = lines
.slice(lines.findIndex(line => line.trim().length > 0))
return lines.map((line,i) =>
`${line}`
)
.join('')
}
export class CodeSample extends HTMLElement {
constructor(){
super()
this.code = this.textContent
console.log(JSON.stringify(this.code))
}
connectedCallback(){
this.render()
}
render(){
this.innerHTML = ``
let codeLinesWithSpansHTML = toLineSpans(this.code)
let pre = document.createElement('pre')
let code = document.createElement('code')
pre.append(code)
code.innerHTML = codeLinesWithSpansHTML
this.append(pre)
}
listen(){
}
}
customElements.define('code-sample', CodeSample)
CodeSample.js
fetching and rendering itself: