customElements.define('code-block-example',
class extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
}
addClickListener() {
const el = this.shadowRoot.querySelector('button')
el.addEventListener('click', () => this.copyCode())
}
connectedCallback() {
const sr = this.shadowRoot
const template = this.makeTemplate()
sr.appendChild(template.content.cloneNode(true))
sr.querySelector('#code-output').innerHTML =
this.querySelector('code').innerHTML
this.addClickListener()
}
async copyCode() {
const button = this.shadowRoot.querySelector('button')
try {
await navigator.clipboard.writeText(
this.querySelector('code').innerText
)
button.innerHTML = "Copied!"
} catch (err) {
button.innerHTML = "Error copying"
}
}
makeTemplate() {
const t = this.ownerDocument.createElement('template')
t.innerHTML = `
<style>
.code-wrapper {
position: relative;
}
.copy-button {
position: absolute;
right: 0;
}
</style>
<div class="code-wrapper">
<button class="copy-button">Copy</button>
<pre><code id="code-output"></code></pre>
</div>`
return t
}
}
)