1- import computedStyleToInlineStyle from "computed-style-to-inline-style" ;
21import download from "js-file-download" ;
32
43/** Export an `<svg>` element with inlined CSS styles.
54
65Returns the source of an SVG document.
76 */
87export function exportSVG ( svg : SVGSVGElement ) : string {
9- computedStyleToInlineStyle ( svg , { recursive : true } ) ;
10-
118 const serializer = new XMLSerializer ( ) ;
12- let source = serializer . serializeToString ( svg ) ;
9+ const node = computedStyleToInlineStyle ( svg ) ;
10+ let source = serializer . serializeToString ( node ) ;
1311
1412 // Add XML namespaces.
1513 if ( ! source . match ( / ^ < s v g [ ^ > ] * ?\s x m l n s = ( [ ' " ` ] ) h t t p s ? \: \/ \/ w w w \. w 3 \. o r g \/ 2 0 0 0 \/ s v g \1/ ) ) {
@@ -31,3 +29,31 @@ export function downloadSVG(svg: SVGSVGElement, filename: string) {
3129 const source = exportSVG ( svg ) ;
3230 return download ( source , filename , "image/svg+xml" ) ;
3331}
32+
33+ /** Convert an HTML or SVG element's style from computed to inline.
34+
35+ Adapted from <https://github.com/lukehorvat/computed-style-to-inline-style>
36+ but fixed to avoid mutating the original DOM node: see issue 4 on that repo.
37+ */
38+ export function computedStyleToInlineStyle ( element : StylableElement ) : Node {
39+ const cloned = element . cloneNode ( true ) ;
40+ recurseComputedStyleToInlineStyle ( element , cloned as StylableElement ) ;
41+ return cloned ;
42+ }
43+
44+ function recurseComputedStyleToInlineStyle ( element : StylableElement , cloned : StylableElement ) {
45+ for ( let i = 0 ; i < element . children . length ; i ++ ) {
46+ recurseComputedStyleToInlineStyle (
47+ element . children [ i ] as StylableElement ,
48+ cloned . children [ i ] as StylableElement ,
49+ ) ;
50+ }
51+
52+ const computedStyle = getComputedStyle ( element ) ;
53+ for ( const property of computedStyle ) {
54+ // biome-ignore lint/suspicious/noExplicitAny: types are busted?
55+ cloned . style [ property as any ] = computedStyle . getPropertyValue ( property ) ;
56+ }
57+ }
58+
59+ type StylableElement = HTMLElement | SVGElement ;
0 commit comments