From 0dd6c307055a00ccc73c2ad5028ff8d997ad697d Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Fri, 11 Jun 2021 16:50:57 +0200 Subject: [PATCH] Re-factor the `DOMSVGFactory` to extend an abstract base class This is first of all consistent with all of the other (similar) factories, and secondly it will also simplify a future addition of a corresponding `NodeSVGFactory` (if that's ever deemed necessary). --- src/display/base_factory.js | 37 ++++++++++++++++++++++++++++++++++++ src/display/display_utils.js | 22 +++------------------ 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/display/base_factory.js b/src/display/base_factory.js index 69d0954a9a162..23c381e2310d8 100644 --- a/src/display/base_factory.js +++ b/src/display/base_factory.js @@ -136,8 +136,45 @@ class BaseStandardFontDataFactory { } } +class BaseSVGFactory { + constructor() { + if (this.constructor === BaseSVGFactory) { + unreachable("Cannot initialize BaseSVGFactory."); + } + } + + create(width, height) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid SVG dimensions"); + } + const svg = this._createSVG("svg:svg"); + svg.setAttribute("version", "1.1"); + svg.setAttribute("width", `${width}px`); + svg.setAttribute("height", `${height}px`); + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + + return svg; + } + + createElement(type) { + if (typeof type !== "string") { + throw new Error("Invalid SVG element type"); + } + return this._createSVG(type); + } + + /** + * @private + */ + _createSVG(type) { + unreachable("Abstract method `_createSVG` called."); + } +} + export { BaseCanvasFactory, BaseCMapReaderFactory, BaseStandardFontDataFactory, + BaseSVGFactory, }; diff --git a/src/display/display_utils.js b/src/display/display_utils.js index 7021c6fd4a332..98b7424b259bc 100644 --- a/src/display/display_utils.js +++ b/src/display/display_utils.js @@ -26,6 +26,7 @@ import { BaseCanvasFactory, BaseCMapReaderFactory, BaseStandardFontDataFactory, + BaseSVGFactory, } from "./base_factory.js"; const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; @@ -109,25 +110,8 @@ class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { } } -class DOMSVGFactory { - create(width, height) { - if (width <= 0 || height <= 0) { - throw new Error("Invalid SVG dimensions"); - } - const svg = document.createElementNS(SVG_NS, "svg:svg"); - svg.setAttribute("version", "1.1"); - svg.setAttribute("width", width + "px"); - svg.setAttribute("height", height + "px"); - svg.setAttribute("preserveAspectRatio", "none"); - svg.setAttribute("viewBox", "0 0 " + width + " " + height); - - return svg; - } - - createElement(type) { - if (typeof type !== "string") { - throw new Error("Invalid SVG element type"); - } +class DOMSVGFactory extends BaseSVGFactory { + _createSVG(type) { return document.createElementNS(SVG_NS, type); } }