1 2(function() { 3 4 class CodeBlockComponent extends HTMLElement { 5 6 constructor() { 7 super(); 8 this.attachShadow({ mode: "open" }); 9 } 10 11 bindEvents() { 12 const { shadowRoot } = this; 13 const copyButton = shadowRoot.querySelector('#copy-button'); 14 copyButton.addEventListener("click", () => { 15 this.copyCode(); 16 }); 17 } 18 19 copyCode() { 20 const { shadowRoot } = this; 21 const codeNode = shadowRoot.querySelector('#code'); 22 const range = document.createRange(); 23 range.selectNode(codeNode); 24 window.getSelection().addRange(range); 25 try { 26 document.execCommand('copy'); 27 } catch(err) { 28 console.warn('Oops, unable to copy'); 29 } 30 } 31 32 connectedCallback() { 33 const { shadowRoot } = this; 34 35 const styles = document.querySelector("#code-block-template").innerHTML; 36 37 let lang = this.classList.value; 38 lang = lang.replace("language-", ""); 39 40 const trimmed = this.innerHTML.trim(); 41 42 let lineNumbersClass = ""; 43 if (this.classList.contains("line-numbers")) { 44 lineNumbersClass = "line-numbers"; 45 } 46 47 // Line Highlighting would be something like this. 48 49 // let lineHighlights = ""; 50 // if (this.dataset.line) { 51 // lineHighlights = this.dataset.line; 52 // } 53 54 // Plus data-line="${lineHighlights} on the <pre> 55 if (this.classList.contains("has-copy")) { 56 var template = ` 57 <div> 58 ${styles} 59 <pre class="${lineNumbersClass} ${this.classList}" id="pre"><code id="code">${trimmed}</code><button id="copy-button">Copy</button></pre> 60 </div> 61 `; 62 } else { 63 var template = ` 64 <div> 65 ${styles} 66 <pre class="${lineNumbersClass} ${this.classList}" id="pre"><code id="code">${trimmed}</code></pre> 67 </div> 68 `; 69 } 70 71 const placeholder = document.createElement('div'); 72 placeholder.insertAdjacentHTML('afterbegin', template); 73 74 const node = placeholder.firstElementChild; 75 76 shadowRoot.appendChild(node); 77 78 // We could highlight it _before_ injecting with a different Prism function, but I'm not sure it does plugins then, like line numbers. Should check. 79 Prism.highlightAllUnder(shadowRoot); 80 if (this.classList.contains("has-copy")) { 81 this.bindEvents(); 82 } 83 } 84 } 85 86 customElements.define('code-block', CodeBlockComponent); 87 88 })();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.