Customizing Code Blocks on Write.as

I'm loving the experience on Write.as so far. But, there was one thing bothering me – I wanted to make a couple adjustments to the code blocks on my posts. Specifically, I wanted to enable horizontal scrolling and add a copy button.

Luckily, Write.as provides the option to enter custom CSS and JavaScript to add to your blog. I wouldn't want to make an entirely different theme this way (though several people have), but it's perfect for making small modifications like these.

The relevant CSS customizations are below. These enable horizontal scrolling of the code block, and modify the layout and styling of the copy button that will get dynamically added.

#post #post-body pre {
  overflow-x: auto;
  position: relative;
}
#post #post-body pre code {
  white-space: pre;
}
pre button {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0.5;
  border: none;
  font-family: monospace;
}
pre button:hover {
    opacity: 1.0;
}

Here's the JavaScript code to dynamically add a copy button to the code blocks.

if ( navigator.clipboard ) {
  let preBlocks = document.querySelectorAll("pre");
  for ( const preBlock of preBlocks ) {
    let codeBlock = preBlock.querySelector("code");
    if ( ! codeBlock ) { continue }
    let button = document.createElement("button");
    button.innerText = "Copy";
    preBlock.appendChild(button);
    button.addEventListener("click", async () => {
      await navigator.clipboard.writeText(codeBlock.innerText);
      button.innerText = "Copied";
      setTimeout(() => {button.innerText="Copy";}, 3000);
    });
  }
}

Part of what I really like about Write.as is that the limited customization is just enough to let me tweak things as needed. With Jekyll and similar options, I feel compelled to try customizing everything instead of just writing.

#writeas