<code-block class="language-css line-numbers" data-line="2">
<pre>
html {
--brandColor: red;
background: var(--brandColor);
}
body {
text-rendering: optimizeSpeed;
height: 100vh;
margin: 0;
font-family: "Georgia", serif;
}
</pre>
</code-block>
<code-block class="language-html line-numbers" data-line="2">
<pre>
<div class="card">
<h2>Cool.</h2>
</div>
</pre>
</code-block>
<code-block class="language-javascript line-numbers" data-line="2">
<pre>
const name = "Chris Coyier";
console.log(name);
</pre>
</code-block>
<template id="code-block-template">
<style>
pre[class*="language-"] {
background: #111;
color: white;
font-family: monospace;
font-size: 120%;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.6;
-moz-tab-size: 2;
-o-tab-size: 2;
tab-size: 2;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
border-radius: .5em;
margin: .5em 0;
overflow: auto;
padding: 1em;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: hsl(0, 0%, 47%);
}
.token.punctuation {
opacity: .7;
}
.token.namespace {
opacity: .7;
}
.token.tag,
.token.boolean,
.token.number,
.token.deleted {
color: hsl(14, 58%, 55%); /* #CF6A4C */
}
.token.keyword,
.token.property,
.token.selector,
.token.constant,
.token.symbol,
.token.builtin {
color: hsl(53, 89%, 79%); /* #F9EE98 */
}
.token.attr-name,
.token.attr-value,
.token.string,
.token.char,
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable,
.token.inserted {
color: hsl(76, 21%, 52%); /* #8F9D6A */
}
.token.atrule {
color: hsl(218, 22%, 55%); /* #7587A6 */
}
.token.regex,
.token.important {
color: hsl(42, 75%, 65%); /* #E9C062 */
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
/* Markup */
.language-markup .token.tag,
.language-markup .token.attr-name,
.language-markup .token.punctuation {
color: hsl(33, 33%, 52%); /* #AC885B */
}
/* Make the tokens sit above the line highlight so the colours don't look faded. */
.token {
position: relative;
z-index: 1;
}
.line-highlight {
background: hsla(0, 0%, 33%, 0.25); /* #545454 */
background: linear-gradient(to right, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */
border-bottom: 1px dashed hsl(0, 0%, 33%); /* #545454 */
border-top: 1px dashed hsl(0, 0%, 33%); /* #545454 */
left: 0;
line-height: inherit;
margin-top: 0.75em; /* Same as .prism’s padding-top */
padding: inherit 0;
pointer-events: none;
position: absolute;
right: 0;
white-space: pre;
z-index: 0;
}
.line-highlight:before,
.line-highlight[data-end]:after {
background-color: hsl(215, 15%, 59%); /* #8794A6 */
border-radius: 999px;
box-shadow: 0 1px white;
color: hsl(24, 20%, 95%); /* #F5F2F0 */
content: attr(data-start);
font: bold 65%/1.5 sans-serif;
left: .6em;
min-width: 1em;
padding: 0 .5em;
position: absolute;
text-align: center;
text-shadow: none;
top: .4em;
vertical-align: .3em;
}
.line-highlight[data-end]:after {
bottom: .4em;
content: attr(data-end);
top: auto;
}
pre[data-line] {
position: relative;
padding: 1em 0 1em 3em;
}
.line-highlight {
position: absolute;
left: 0;
right: 0;
padding: inherit 0;
margin-top: 1em; /* Same as .prism’s padding-top */
background: hsla(24, 20%, 50%,.08);
background: linear-gradient(to right, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
pointer-events: none;
line-height: inherit;
white-space: pre;
}
.line-highlight:before,
.line-highlight[data-end]:after {
content: attr(data-start);
position: absolute;
top: .4em;
left: .6em;
min-width: 1em;
padding: 0 .5em;
background-color: hsla(24, 20%, 50%,.4);
color: hsl(24, 20%, 95%);
font: bold 65%/1.5 sans-serif;
text-align: center;
vertical-align: .3em;
border-radius: 999px;
text-shadow: none;
box-shadow: 0 1px white;
}
.line-highlight[data-end]:after {
content: attr(data-end);
top: auto;
bottom: .4em;
}
.line-numbers .line-highlight:before,
.line-numbers .line-highlight:after {
content: none;
}
pre[class*="language-"].line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre[class*="language-"].line-numbers > code {
position: relative;
white-space: inherit;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: -0.13em; /* wtf */
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span::before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}
#copy-button {
position: absolute;
top: 5px;
right: 5px;
}
</style>
</template>
/*
Code Block Web Component
1) ✅ Basic styles (pulls `styles` global from another Pen)
2) ✅ Syntax Highlight (assumes global `Prism`)
3) ✅ Click to copy (Native JavaScript)
4) ✅ Optional Line numbers (Prism feature)
6) ✅ whitespace top/bottom trimming
TODO
[ ] Is there a way to avoid the <pre> in the custom element but still handle whitespace OK? Or is <pre> super magical and it's the only practial way to handle whitespace? Justin's doesn't seem to need it https://github.com/justinribeiro/code-block
[ ] Implement line highlighting feature from Prism (had trouble with styles).
[ ] Could this do entity escaping for you, so you didn't have to bother with that in the HTML? Or is that too weird because you wouldn't want the raw HTML sitting in the HTML to start with, in case the JS doesn't load? Maybe put HTML in <!-- comments
--> or is that too weird because what if you want to show comments?
*/
(function() {
class CodeBlockComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
bindEvents() {
const { shadowRoot } = this;
const copyButton = shadowRoot.querySelector('#copy-button');
copyButton.addEventListener("click", () => {
this.copyCode();
});
}
copyCode() {
const { shadowRoot } = this;
const codeNode = shadowRoot.querySelector('#code');
const range = document.createRange();
range.selectNode(codeNode);
window.getSelection().addRange(range);
try {
document.execCommand('copy');
} catch(err) {
console.warn('Oops, unable to copy');
}
}
connectedCallback() {
const { shadowRoot } = this;
const styles = document.querySelector("#code-block-template").innerHTML;
let lang = this.classList.value;
lang = lang.replace("language-", "");
const trimmed = this.innerHTML.trim();
let lineNumbersClass = "";
if (this.classList.contains("line-numbers")) {
lineNumbersClass = "line-numbers";
}
// Line Highlighting would be something like this.
// let lineHighlights = "";
// if (this.dataset.line) {
// lineHighlights = this.dataset.line;
// }
// Plus data-line="${lineHighlights} on the <pre>
const template = `
<div>
${styles}
<pre class="${lineNumbersClass} ${this.classList}" id="pre"><code id="code">${trimmed}</code><button id="copy-button">Copy</button></pre>
</div>
`;
const placeholder = document.createElement('div');
placeholder.insertAdjacentHTML('afterbegin', template);
const node = placeholder.firstElementChild;
shadowRoot.appendChild(node);
// 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.
Prism.highlightAllUnder(shadowRoot);
this.bindEvents();
}
}
customElements.define('code-block', CodeBlockComponent);
})();
This Pen doesn't use any external CSS resources.