11ty Syntax Highlighting Quirk

I'm using the 11ty Syntax Highlighting Plugin to style code blocks on this blog. For the most part this has worked great, but I've noticed one thing which was irritating me — comments were not appearing on Mobile Safari on iOS devices.

This doesn't occur in desktop Safari, so is "obviously" a quirk with the iOS version. A little searching turned up that the problem is that Prism adds a class comment which is then ignored in the mobile version of Safari.

How to fix?

The Prism docs suggest using a plugin that allows for renaming of classes in config, but I don't think there's an (easy) way to get that working inside the 11ty plugin.

So that leaves two tasks:

  • within 11ty, automate the changing of class="comment" within HTML files for some other, custom class name that mobile Safari won't mess with
  • within 11ty, change the styling so that the new class name gets styled appropriately

HTML first

Changing the HTML is pretty easy. First, in my utils folder, add a file transforms.js that exports the following function:

// utils/transforms.js
const changeCommentClass = (content, outputPath) => {
    if (outputPath.endsWith(".html")) {
    // have to use a regex here, otherwise this new function also changes this code block!
        return content.replace(/token\scomment/g, "token prism-comment");
    }
    return content;
};

module.exports = {
    changeCommentClass
}

In the above code block for this post, I have to use the \s within the regex, otherwise this function will also change the occurrence of token<space>comment in the post ...

I'd checked the original output and found that comments were being wrapped in a span with a class of token<space>comment, so that function runs through every HTML file and replaces all instances of token<space>comment with token prism-comment.

Then to actually use that transform, we need to add it to the config file:

// .eleventy.js

// import the function
const { changeCommentClass } = require('./utils/transforms.js');

// add it to the config
module.exports = function(eleventyConfig) {

    ...

    eleventyConfig.addTransform("changeCommentClass", changeCommentClass);

    ...
}

Styling second

I'm using the a11y-dark theme for Prism, and I have a copy of the stylesheet in my src/css folder which is imported in my <head> when required.

Rather than any additional automation, I can therefore simply change all the appropriate selectors in my local copy of the stylesheet — so every instance of token.comment is changed to token.prism-comment.

And voila, comments are now appearing in mobile Safari.