Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion plugins/removeUnknownsAndDefaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
attrsGroupsDefaults,
elems,
elemsGroups,
inheritableAttrs,
presentationNonInheritableGroupAttrs,
} from './_collections.js';
import { detachNodeFromParent } from '../lib/xast.js';
Expand Down Expand Up @@ -114,6 +115,28 @@ export const fn = (root, params) => {
} = params;
const stylesheet = collectStylesheet(root);

/**
* A referenced subtree may be instantiated by a `use` element, whose
* inherited styles must not replace defaults declared inside the subtree.
*
* @param {import('../lib/types.js').XastNode} node
* @returns {boolean}
*/
const hasReferenceableAncestor = (node) => {
let ancestor = node;
while (ancestor.type === 'element') {
if (ancestor.attributes.id != null) {
return true;
}
const parent = stylesheet.parents.get(ancestor);
if (parent == null) {
return false;
}
ancestor = parent;
}
return false;
};

return {
instruction: {
enter: (node) => {
Expand Down Expand Up @@ -194,7 +217,11 @@ export const fn = (root, params) => {
defaultAttrs &&
node.attributes.id == null &&
attributesDefaults &&
attributesDefaults.get(name) === value
attributesDefaults.get(name) === value &&
// An inheritable default inside a referenceable subtree may keep
// that subtree from inheriting a different value via `use`.
(inheritableAttrs.has(name) === false ||
hasReferenceableAncestor(parentNode) === false)
) {
// keep defaults if parent has own or inherited style
if (
Expand Down
23 changes: 23 additions & 0 deletions test/plugins/removeUnknownsAndDefaults.18.svg.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Keep inheritable default attributes inside a referenceable subtree.

===

<svg xmlns="http://www.w3.org/2000/svg">
<g id="a">
<rect width="10" height="10" fill-opacity="1"/>
</g>
<g fill-opacity=".3">
<use href="#a"/>
</g>
</svg>

@@@

<svg xmlns="http://www.w3.org/2000/svg">
<g id="a">
<rect width="10" height="10" fill-opacity="1"/>
</g>
<g fill-opacity=".3">
<use href="#a"/>
</g>
</svg>