Peter Bacon Darwin ca17d4f639 build(aio): auto-fill width/height to all image tags
Parse all `<img>` tags, during doc-gen, and insert the width and height of
the sourceed image, if neither are already specified.

Warnings are reported if the `<img>` tag has no `src` attribute or the image
cannot be loaded.

The work is done in the `addImageDimensions` post-processor, which must be
configured with a `basePath` so that it knows where to find the images.

Closes #15888
2017-05-01 15:52:51 -07:00

41 lines
1.4 KiB
JavaScript

const visit = require('unist-util-visit');
const is = require('hast-util-is-element');
const source = require('unist-util-source');
/**
* Add the width and height of the image to the `img` tag if they are
* not already provided. This helps prevent jank when the page is
* rendered before the image has downloaded.
*
* If there is no `src` attribute on an image, or it is not possible
* to load the image file indicated by the `src` then a warning is emitted.
*/
module.exports = function addImageDimensions(getImageDimensions) {
return function addImageDimensionsImpl() {
return (ast, file) => {
visit(ast, node => {
if (is(node, 'img')) {
const props = node.properties;
const src = props.src;
if (!src) {
file.message('Missing src in image tag `' + source(node, file) + '`');
} else if (props.width === undefined && props.height === undefined) {
try {
const dimensions = getImageDimensions(addImageDimensionsImpl.basePath, src);
props.width = '' + dimensions.width;
props.height = '' + dimensions.height;
} catch(e) {
if (e.code === 'ENOENT') {
file.message('Unable to load src in image tag `' + source(node, file) + '`');
} else {
file.fail(e.message);
}
}
}
}
});
};
};
};