kjelsrud.dev/node_modules/@astrojs/mdx/dist/remark-images-to-component.js

85 lines
2.7 KiB
JavaScript
Raw Normal View History

2023-07-19 21:31:30 +02:00
import { visit } from "unist-util-visit";
import { jsToTreeNode } from "./utils.js";
function remarkImageToComponent() {
return function(tree, file) {
if (!file.data.imagePaths)
return;
const importsStatements = [];
const importedImages = /* @__PURE__ */ new Map();
visit(tree, "image", (node, index, parent) => {
var _a;
if ((_a = file.data.imagePaths) == null ? void 0 : _a.has(node.url)) {
let importName = importedImages.get(node.url);
if (!importName) {
importName = `__${importedImages.size}_${node.url.replace(/\W/g, "_")}__`;
importsStatements.push({
type: "mdxjsEsm",
value: "",
data: {
estree: {
type: "Program",
sourceType: "module",
body: [
{
type: "ImportDeclaration",
source: { type: "Literal", value: node.url, raw: JSON.stringify(node.url) },
specifiers: [
{
type: "ImportDefaultSpecifier",
local: { type: "Identifier", name: importName }
}
]
}
]
}
}
});
importedImages.set(node.url, importName);
}
const componentElement = {
name: "__AstroImage__",
type: "mdxJsxFlowElement",
attributes: [
{
name: "src",
type: "mdxJsxAttribute",
value: {
type: "mdxJsxAttributeValueExpression",
value: importName,
data: {
estree: {
type: "Program",
sourceType: "module",
comments: [],
body: [
{
type: "ExpressionStatement",
expression: { type: "Identifier", name: importName }
}
]
}
}
}
},
{ name: "alt", type: "mdxJsxAttribute", value: node.alt || "" }
],
children: []
};
if (node.title) {
componentElement.attributes.push({
type: "mdxJsxAttribute",
name: "title",
value: node.title
});
}
parent.children.splice(index, 1, componentElement);
}
});
tree.children.unshift(...importsStatements);
tree.children.unshift(jsToTreeNode(`import { Image as __AstroImage__ } from "astro:assets";`));
};
}
export {
remarkImageToComponent
};