upsetjs import { extractStyleId , extractTitle } from './utils' ; import { getDefaultTheme } from '../fillDefaults' ; import type { UpSetThemes } from '../interfaces' ; export function createSVG ( node , toRemove ? ) { const clone = node . cloneNode ( true ) as SVGSVGElement ; clone . style . backgroundColor = getDefaultTheme ( node . dataset . theme as UpSetThemes ) . backgroundColor ; if ( toRemove ) { Array . from ( clone . querySelectorAll ( toRemove ) ) . forEach ( ( d ) => d . remove ( ) ) ; } return new XMLSerializer ( ) . serializeToString ( clone ) ; } param node param options export function exportSVG ( node , { type = 'png' , title , toRemove } ) { const b = new Blob ( [ createSVG ( node , toRemove ) ] , { type : 'image/svg+xml;charset=utf-8' , } ) ; const styleId = extractStyleId ( node ) ; const chartTitle = title ?? extractTitle ( node , styleId ) ; const url = URL . createObjectURL ( b ) ; if ( type === 'svg' ) { downloadUrl ( url , `${ chartTitle }.${ type }` , node . ownerDocument ! ) ; URL . revokeObjectURL ( url ) ; return Promise . resolve ( ) ; } return toPNG ( url , node ) . then ( ( purl ) => { downloadUrl ( purl , `${ chartTitle }.${ type }` , node . ownerDocument ! ) ; URL . revokeObjectURL ( url ) ; } ) ; } function toPNG ( url , node ) { const canvas = node . ownerDocument ! . createElement ( 'canvas' ) ; const bb = node . getBoundingClientRect ( ) ; canvas . width = bb . width ; canvas . height = bb . height ; const ctx = canvas . getContext ( '2d' ) ! ; const img = new Image ( canvas . width , canvas . height ) ; return new Promise < string > ( ( resolve ) => { img . onload = ( ) => { ctx . drawImage ( img , 0 , 0 ) ; const png = canvas . toDataURL ( 'image/png' ) ; resolve ( png ) ; } ; img . src = url ; } ) ; } param url param title param doc export function downloadUrl ( url , title , doc ) { const a = doc . createElement ( 'a' ) ; a . href = url ; a . style . position = 'absolute' ; a . style . left = '-10000px' ; a . style . top = '-10000px' ; a . download = title ; doc . body . appendChild ( a ) ; a . click ( ) ; a . remove ( ) ; }