Add a Sphinx extension for working with srcsets for images.

Review Request #12737 — Created Nov. 23, 2022 and submitted — Latest diff uploaded

Information

beanbag-docutils
master

Reviewers

Sphinx and docutils lack any ability to work with modern <img srcset>
attributes, making it difficult to work with responsive/high-DPI images.
We've historically provided a retina_images extension that made use
of a legacy JavaScript library for swapping images at runtime based on
data attributes, but we don't even ship this anymore on our sites.

This change introduces a new extension that gives us a nice way of using
modern srcsets.

It extends the existing image directive to take an optional
sources option. If provided, this will determine the images that
will be collected in the resulting documentation and provided as a
srcset=. This looks like:

.. image:: path/to/file.png
   :sources: 2x path/to/file@2x.png
             3x path/to/file@3x.png
             ...

The structure is a bit different from the native value for
<img srcset>. Descriptors (e.g., 2x) go first, commas aren't
required if splitting across multiple lines, and 1x is inferred from
the main image.

This is actually entirely optional. If any suitable files exist
alongside the main referenced file, they'll be found and used to build
up the srcset. So the above file@2x.png and file@3x.png don't
even need to be specified. They'll be directly scanned and added.

This makes this extension a drop-in option for codebases without needing
to rely on the custom option.

The reason we're modifying image to begin with, rather than adding a
new directive, is in part to faciliate a drop-in solution that can still
render images without the use of the extension (such as when viewed on
GitHub), but also because the image machinery in both docutils and
Sphinx is baked in and complicated. It's far more error-prone to
introduce something new that replicates all that logic than to
monkeypatch with an optional option that doesn't even need to be
specified for the common case.

This extension does not depend on anything else within this package, and
requires no configuration, so it can be used directly in any Sphinx
documentation packages.

Unit tests pass.

Manually tested with our Review Board documentation, both with manual
sources and source scanning, and saw that the resulting docs looked correct
on standard and high DPIs, with srcset propery filled in.

Commits

Files

    Loading...