nicolodavis.com

Autogenerated Screenshots in Markdown

Sep 8, 2020

I’ve been working on user documentation for Boardgame Lab. As is the case for most product documentation, screenshots are the most time consuming aspect of this process.

Generating them is one half of the picture. Keeping them up to date as the product evolves is another challenge.

Fortunately, there is a way to automate this.

E2E Testing Tools

Turns out that most E2E testing tools for the web have the ability to generate screenshots. I use Playwright with tests written using CodeceptJS (I find the API more readable than using Playwright directly).

Other tools like Puppeteer and Cypress have similar capabilities, so pick one that you’re comfortable with.

The code to generate a screenshot in CodeceptJS looks something like this:

Feature('Test');

Scenario('save screenshot', (I) => {
  I.amOnPage('/');
  I.saveScreenshot('screenshot.png');
});

Hooking it up with your build process

We want to add our screenshot generating code directly to the Markdown file holding the user documentation and have it automagically replace that with an image of the final screenshot.

# Boardgame Lab documentation

Documentation text.

<screenshot>
  I.amOnPage("/")
</screenshot>

The general strategy is to extract the content of <screenshot> tags and copy them over to JavaScript files which are then converted to screenshots via CodeceptJS. The way I’ve set it up, the extraction logic also provides the boilerplate, including the saveScreenshot line.

diagram

This can be done in many ways. My documentation site is written in Svelte and uses MDsveX, which provides a convenient hook to parse HTML tags from Markdown files.

In theory you could use something other than HTML tags to demarcate the JavaScript code, but this format allows passing in additional parameters which are useful. For example, you could specify the size of the screenshot or the actual element you want to screenshot (if you don’t want to capture the entire page).

<screenshot width="640" height="480">
  I.amOnPage("/")
</screenshot>

Concluding Thoughts

I like this approach because not only does it automate the generation of screenshots, the code to generate those screenshots are actual tests that serve to validate the correctness of the application!

Code: link


Nicolo John Davis
Nicolo Davis