Skip to content

Commit

Permalink
Adds keep and replace options to eleventy:optional attribute. #259
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Dec 13, 2024
1 parent 06d4fb4 commit f387074
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
12 changes: 10 additions & 2 deletions src/image-attrs-to-posthtml-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
24 changes: 19 additions & 5 deletions src/transform-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
}

Expand Down

0 comments on commit f387074

Please sign in to comment.