UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

54 lines (53 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createSvgPaths = exports.createSvgElements = exports.createSvgElement = exports.ElementNamespace = void 0; var ElementNamespace; (function (ElementNamespace) { ElementNamespace["Html"] = "html"; ElementNamespace["Svg"] = "svg"; })(ElementNamespace || (exports.ElementNamespace = ElementNamespace = {})); /** * Shorthand for creating an element with `document.createElement`, then assigning properties. * * Non-HTML elements (e.g. `svg` elements) should use the `elementType` parameter to select * the element namespace. */ const createElement = (tag, props, elementType = ElementNamespace.Html) => { let elem; if (elementType === ElementNamespace.Html) { elem = document.createElement(tag); } else if (elementType === ElementNamespace.Svg) { elem = document.createElementNS('http://www.w3.org/2000/svg', tag); } else { throw new Error(`Unknown element type ${elementType}`); } for (const [key, value] of Object.entries(props)) { if (key === 'children') continue; if (typeof value !== 'string' && typeof value !== 'number') { throw new Error(`Unsupported value type ${typeof value}`); } elem.setAttribute(key, value.toString()); } if (props.children) { for (const item of props.children) { elem.appendChild(item); } } return elem; }; const createSvgElement = (tag, props) => { return createElement(tag, props, ElementNamespace.Svg); }; exports.createSvgElement = createSvgElement; const createSvgElements = (tag, elements) => { return elements.map((props) => (0, exports.createSvgElement)(tag, props)); }; exports.createSvgElements = createSvgElements; const createSvgPaths = (...paths) => { return (0, exports.createSvgElements)('path', paths); }; exports.createSvgPaths = createSvgPaths; exports.default = createElement;