forked from solution-loisir/markdown-it-eleventy-img
/
index.js
executable file
·63 lines (48 loc) · 2.37 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const Image = require("@11ty/eleventy-img");
const logWarningFor = require("./utilities/warnings");
const { remove } = require("./utilities/remove-key-from");
const generateAttrsObject = require("./utilities/generate-attrs-object");
const { typeObjectError, typeFunctionError } = require("./utilities/errors");
const { propertiesFrom } = require("./utilities/lower-case-trim-object");
/**
*
* @param {MarkdownIt} md The markdown-it object
* @param {*} imgOptions Overrides eleventy-img specific options.
* @param {*} globalAttributes Adds attributes to the image output.
* @param {Function} renderImage Lets you render custom markup and do almost everything you like with your markdown images.
* @param {Function} resolvePath Function that will be used to resolve paths for images in markdown. Receives image path string and env as parameters. Default resolves to CWD.
*/
module.exports = function markdownItEleventyImg(md, {
imgOptions = {},
globalAttributes = {},
renderImage,
resolvePath
} = {}) {
typeObjectError(imgOptions, "imgOptions");
typeObjectError(globalAttributes, "globalAttributes");
typeFunctionError(renderImage, "renderImage");
const normalizedGlobalAttributes = propertiesFrom(globalAttributes).lowerCased().trimmed().object();
logWarningFor(normalizedGlobalAttributes);
md.renderer.rules.image = (tokens, index, rendererOptions, env, renderer) => {
const token = tokens[index];
const normalizedTokenAttributes = generateAttrsObject(token).addContentTo("alt").attrs;
const src = (resolvePath) ? resolvePath(normalizedTokenAttributes.src, env) : normalizedTokenAttributes.src;
const normalizedTokenAttributesWithoutSrc = remove("src").from(normalizedTokenAttributes);
const imageAttributes = { ...normalizedGlobalAttributes, ...normalizedTokenAttributesWithoutSrc };
if(renderImage) {
const image = [ Image, imgOptions ];
const attributes = [ src, imageAttributes ];
return renderImage(image, attributes);
}
if(Image.Util.isRemoteUrl(src)) {
token.attrs[token.attrIndex("alt")][1] = token.content;
return renderer.renderToken(tokens, index, rendererOptions);
}
Image(src, imgOptions);
const metadata = Image.statsSync(src, imgOptions);
const imageMarkup = Image.generateHTML(metadata, imageAttributes, {
whitespaceMode: "inline"
});
return imageMarkup;
};
};