From f38707484de2557666a46a20e0dd5a36ac198d64 Mon Sep 17 00:00:00 2001 From: Zach Leatherman Date: Fri, 13 Dec 2024 16:44:48 -0600 Subject: [PATCH] Adds keep and replace options to eleventy:optional attribute. #259 --- src/image-attrs-to-posthtml-node.js | 12 ++++++++++-- src/transform-plugin.js | 24 +++++++++++++++++++----- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/image-attrs-to-posthtml-node.js b/src/image-attrs-to-posthtml-node.js index 7c92110..bd4cfa4 100644 --- a/src/image-attrs-to-posthtml-node.js +++ b/src/image-attrs-to-posthtml-node.js @@ -83,8 +83,16 @@ function isIgnored(node) { return node?.attrs && node?.attrs?.[ATTR.IGNORE] !== undefined; } -function isOptional(node) { - return node?.attrs && node?.attrs?.[ATTR.OPTIONAL] !== undefined; +function isOptional(node, comparisonValue) { + let attrValue = node?.attrs && node?.attrs?.[ATTR.OPTIONAL]; + if(attrValue !== undefined) { + // if comparisonValue is not specified, return true + if(comparisonValue === undefined) { + return true; + } + return attrValue === comparisonValue; + } + return false; } function getOutputDirectory(node) { diff --git a/src/transform-plugin.js b/src/transform-plugin.js index 4c86fcf..83e02a5 100644 --- a/src/transform-plugin.js +++ b/src/transform-plugin.js @@ -58,13 +58,27 @@ function transformTag(context, node, opts) { Object.assign(node, obj); }, (error) => { - if(!isOptional(node) && opts.failOnError) { - return Promise.reject(error); + if(isOptional(node) || !opts.failOnError) { + if(isOptional(node, "keep")) { + // leave as-is, likely 404 when a user visits the page + } else if(isOptional(node, "replace")) { + // transparent png + node.attrs.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="; + } else if(isOptional(node)) { + // delete node + delete node.tag; + delete node.attrs; + + return Promise.resolve(); + } + + // optional or don’t fail on error + cleanTag(node); + + return Promise.resolve(); } - cleanTag(node); - - return Promise.resolve(); + return Promise.reject(error); }); }