An awesome code block component
For journey-to-fullstack I created a code block that I'm quite proud of. Since I'm using MDX with Gatsby, I can easily tell the renderer to use this custom component in place of the usual bare <pre>
and <code>
tags.
I want to make it a bit better, so I thought I'd use this week's post to think it through and get the upgrade started. This is how it currently looks---the following code in Markdown:
Will produce this code block on render:
It's quite cool already---it has nice styling, highlighting provided by Prism.js and it automatically parses the language
attribute to produce a small coloured tag on the top right corner. The color adjusts to the language, for a small set of languages that I can grow as I add code blocks in new languages.
Some of the things that I'd like to add:
I want to be able to add a title to the code block. I can see myself wanting this feature when building a tutorial where I want to convey that a given code block represents a file with a specific path.
I want to look into using the
<figure>
and<figcaption>
HTML tags to make it more semantic. I'm not entirely sure that will always be the right approach, since:Usually a
<figure>
is an image, illustration, diagram, code snippet, etc., that is referenced in the main flow of a document, but that can be moved to another part of the document or to an appendix without affecting the main flow.I want to have customizable line numbers. Being able to activate or deactivate line numbering and to provide an offset to be able to start numbering at an arbitrary number.
Being able to visually emphasize lines to draw attention to them. Whether using an array of line numbers or number ranges. Being able to customize what styles are applied for the emphasis.
A copy to clipboard button. Also really cool to be able to select certain lines and copy those only, although that might be over-engineering it a bit, since a user can already select and copy with their mouse.
A full-screen button, possibly switching to a lightbox-type display of the code block.
That's a healthy set of features. I'm sure someone has already coded this. I like javascript.info's code blocks, I also got some inspiration---namely, the colored tag---from Gatsby's docs.
What do you say, does this sound like an awesome code block component? Did I miss a killer feature? Let me know on Twitter.