From 9a014dba561e29bc80e1ea3c885b8ff3cfbad0cd Mon Sep 17 00:00:00 2001 From: Atul Varma Date: Sat, 27 Feb 2021 08:43:31 -0500 Subject: [PATCH] Factor out export-svg.tsx. --- lib/export-svg.tsx | 32 ++++++++++++++++++++++++++++++++ lib/pages/creature-page.tsx | 27 +-------------------------- 2 files changed, 33 insertions(+), 26 deletions(-) create mode 100644 lib/export-svg.tsx diff --git a/lib/export-svg.tsx b/lib/export-svg.tsx new file mode 100644 index 0000000..b21df98 --- /dev/null +++ b/lib/export-svg.tsx @@ -0,0 +1,32 @@ +function getSvgMarkup(el: SVGSVGElement): string { + return [ + ``, + "", + '', + el.outerHTML, + ].join("\n"); +} + +/** + * Initiates a download on the user's browser which downloads the given + * SVG element under the given filename. + */ +export function exportSvg( + filename: string, + svgRef: React.RefObject +) { + const svgEl = svgRef.current; + if (!svgEl) { + alert("Oops, an error occurred! Please try again later."); + return; + } + const dataURL = `data:image/svg+xml;utf8,${encodeURIComponent( + getSvgMarkup(svgEl) + )}`; + const anchor = document.createElement("a"); + anchor.href = dataURL; + anchor.download = filename; + document.body.append(anchor); + anchor.click(); + document.body.removeChild(anchor); +} diff --git a/lib/pages/creature-page.tsx b/lib/pages/creature-page.tsx index adb9b12..cddc85e 100644 --- a/lib/pages/creature-page.tsx +++ b/lib/pages/creature-page.tsx @@ -19,6 +19,7 @@ import { SymbolContextWidget } from "../symbol-context-widget"; import { range } from "../util"; import { getBoundingBoxCenter, uniformlyScaleToFit } from "../bounding-box"; import { AutoSizingSvg } from "../auto-sizing-svg"; +import { exportSvg } from "../export-svg"; const DEFAULT_BG_COLOR = "#858585"; @@ -414,32 +415,6 @@ const COMPLEXITY_LEVEL_GENERATORS: CreatureGenerator[] = [ const MAX_COMPLEXITY_LEVEL = COMPLEXITY_LEVEL_GENERATORS.length - 1; -function getSvgMarkup(el: SVGSVGElement): string { - return [ - ``, - "", - '', - el.outerHTML, - ].join("\n"); -} - -function exportSvg(filename: string, svgRef: React.RefObject) { - const svgEl = svgRef.current; - if (!svgEl) { - alert("Oops, an error occurred! Please try again later."); - return; - } - const dataURL = `data:image/svg+xml;utf8,${encodeURIComponent( - getSvgMarkup(svgEl) - )}`; - const anchor = document.createElement("a"); - anchor.href = dataURL; - anchor.download = filename; - document.body.append(anchor); - anchor.click(); - document.body.removeChild(anchor); -} - function getDownloadFilename(randomSeed: number | null) { let downloadBasename = "mystic-symbolic-creature";