36 lines
1021 B
TypeScript
36 lines
1021 B
TypeScript
import type {
|
|
SvgNode,
|
|
SvgPlugin,
|
|
SvgPluginOptions,
|
|
} from "../../types/common.js";
|
|
|
|
export const collapseGroups: SvgPlugin = {
|
|
name: "collapseGroups",
|
|
apply(node: SvgNode, _options: SvgPluginOptions): SvgNode | null {
|
|
if (node.type !== "element" || node.name !== "g") return node;
|
|
const children = node.children ?? [];
|
|
if (children.length !== 1) return node;
|
|
|
|
const child = children[0]!;
|
|
if (child.type !== "element") return node;
|
|
|
|
const groupAttrs = node.attributes ?? {};
|
|
|
|
// Never collapse if group has an id (may be referenced)
|
|
if ("id" in groupAttrs) return node;
|
|
|
|
const childAttrs = child.attributes ?? {};
|
|
|
|
// Check for conflicting attributes
|
|
for (const key of Object.keys(groupAttrs)) {
|
|
if (key in childAttrs) return node;
|
|
}
|
|
|
|
// Merge group attrs onto child
|
|
return {
|
|
...child,
|
|
attributes: { ...groupAttrs, ...childAttrs },
|
|
};
|
|
},
|
|
};
|