UNPKG

mdsvex-enhanced-images

Version:

An MDsveX plugin to preprocess Markdown images using @sveltejs/enhanced-img.

58 lines (56 loc) 2.1 kB
var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; // src/index.ts import { sep } from "path"; import { visit } from "unist-util-visit"; function escapeHtmlAttribute(value) { return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } var defaultResolverFactory = (relativeHandler = (path) => `.${sep}${path}`) => (path) => { if (path.startsWith("http://") || path.startsWith("https://") || path.startsWith("$") || path.startsWith("@") || path.startsWith(`.${sep}`) || path.startsWith(`..${sep}`)) { return path; } else { return relativeHandler(path); } }; var enhancedImages = (config) => { const resolvedConfig = __spreadValues({ resolve: defaultResolverFactory() }, config); return (tree) => { visit(tree, "image", (node, index, parent) => { if (node.url.startsWith("http://") || node.url.startsWith("https://")) { return; } const url = resolvedConfig.resolve(node.url); node.type = "html"; let imgHtml = `<enhanced:img src="${url}"`; if (node.alt !== null) { imgHtml += ` alt="${escapeHtmlAttribute(node.alt)}"`; } if (node.title !== null && node.title !== void 0 && node.title !== "") { imgHtml += ` title="${escapeHtmlAttribute(node.title)}"`; } imgHtml += ` />`; node.value = imgHtml; }); }; }; export { defaultResolverFactory, enhancedImages };