Skip to content

Commit

Permalink
Re-factor the DOMSVGFactory to extend an abstract base class
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
Snuffleupagus authored and bh213 committed Jun 3, 2022
1 parent 78c3fa5 commit 0dd6c30
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 19 deletions.
37 changes: 37 additions & 0 deletions src/display/base_factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
22 changes: 3 additions & 19 deletions src/display/display_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
BaseCanvasFactory,
BaseCMapReaderFactory,
BaseStandardFontDataFactory,
BaseSVGFactory,
} from "./base_factory.js";

const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
Expand Down Expand Up @@ -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);
}
}
Expand Down

0 comments on commit 0dd6c30

Please sign in to comment.