( options: string | Partial<InfographicOptions>, init?: Partial<InfographicOptions>, )
| 6 | import { setupDOM } from './dom-shim'; |
| 7 | |
| 8 | export async function renderToString( |
| 9 | options: string | Partial<InfographicOptions>, |
| 10 | init?: Partial<InfographicOptions>, |
| 11 | ): Promise<string> { |
| 12 | const { document } = setupDOM(); |
| 13 | const container = document.getElementById('container') as HTMLElement; |
| 14 | let infographic: Infographic | undefined; |
| 15 | let timeoutId: NodeJS.Timeout; |
| 16 | |
| 17 | try { |
| 18 | infographic = new Infographic({ |
| 19 | ...init, |
| 20 | container, |
| 21 | editable: false, |
| 22 | }); |
| 23 | |
| 24 | const renderPromise = new Promise<string>((resolve, reject) => { |
| 25 | infographic!.on('loaded', async ({ node }) => { |
| 26 | try { |
| 27 | const svg = await exportToSVG(node, { embedResources: true }); |
| 28 | resolve(svg.outerHTML); |
| 29 | } catch (e) { |
| 30 | reject(e); |
| 31 | } |
| 32 | }); |
| 33 | }); |
| 34 | |
| 35 | const timeoutPromise = new Promise<string>((_, reject) => { |
| 36 | timeoutId = setTimeout(() => { |
| 37 | reject(new Error('SSR render timeout')); |
| 38 | }, 10000); |
| 39 | }); |
| 40 | |
| 41 | infographic.render(options); |
| 42 | |
| 43 | const svg = await Promise.race([renderPromise, timeoutPromise]); |
| 44 | return injectXMLStylesheet(svg); |
| 45 | } finally { |
| 46 | clearTimeout(timeoutId!); |
| 47 | if (infographic) { |
| 48 | infographic.destroy(); |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | function injectXMLStylesheet(svg: string): string { |
| 54 | const matched = svg.matchAll(/font-family="([\S ]+?)"/g); |
no test coverage detected