UNPKG

js-draw

Version:

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

48 lines (47 loc) 1.64 kB
export var ElementNamespace; (function (ElementNamespace) { ElementNamespace["Html"] = "html"; ElementNamespace["Svg"] = "svg"; })(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; }; export const createSvgElement = (tag, props) => { return createElement(tag, props, ElementNamespace.Svg); }; export const createSvgElements = (tag, elements) => { return elements.map((props) => createSvgElement(tag, props)); }; export const createSvgPaths = (...paths) => { return createSvgElements('path', paths); }; export default createElement;