Skip to content

Commit

Permalink
Merge text/tspan with style attributes. (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
johnkenny54 authored Nov 13, 2024
1 parent 3384e1d commit 9a38290
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
17 changes: 17 additions & 0 deletions plugins/cleanupTextElements.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { getStyleDeclarations } from '../lib/css-tools.js';
import { writeStyleAttribute } from '../lib/css.js';

export const name = 'cleanupTextElements';
export const description = 'simplify <text> elements and content';

Expand Down Expand Up @@ -62,6 +65,19 @@ export const fn = (root, params, info) => {
hoistableChild.attributes[attributeName];
}
}
// Update style attribute.
const childDeclarations = getStyleDeclarations(hoistableChild);
if (childDeclarations) {
const parentDeclarations = getStyleDeclarations(element);
if (parentDeclarations) {
for (const [k, v] of childDeclarations) {
parentDeclarations.set(k, v);
}
writeStyleAttribute(element, parentDeclarations);
} else {
writeStyleAttribute(element, childDeclarations);
}
}
}

// If the <text> element has x/y, and so do all children, remove x/y from <text>.
Expand Down Expand Up @@ -238,6 +254,7 @@ function isHoistable(child) {
}
for (const attributeName of Object.keys(child.attributes)) {
switch (attributeName) {
case 'style':
case 'x':
case 'y':
break;
Expand Down
15 changes: 15 additions & 0 deletions test/plugins/cleanupTextElements.04.svg.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Hoist children with style attributes.

===

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<text>
<tspan y="20" style="font-weight:bold">This is a test</tspan>
</text>
</svg>

@@@

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<text y="20" style="font-weight:bold">This is a test</text>
</svg>
15 changes: 15 additions & 0 deletions test/plugins/cleanupTextElements.05.svg.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Hoist children with style attributes.

===

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<text style="fill:red">
<tspan y="20" style="font-weight:bold">This is a test</tspan>
</text>
</svg>

@@@

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<text style="fill:red;font-weight:bold" y="20">This is a test</text>
</svg>

0 comments on commit 9a38290

Please sign in to comment.