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
This commit is contained in:

committed by
Matias Niemelä

parent
64335d3521
commit
ca17d4f639
40
aio/tools/transforms/angular-base-package/post-processors/add-image-dimensions.js
vendored
Normal file
40
aio/tools/transforms/angular-base-package/post-processors/add-image-dimensions.js
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
};
|
Reference in New Issue
Block a user