|
| 1 | +const xmlns = 'http://www.w3.org/2000/svg' |
| 2 | + |
| 3 | +const plainObjectConstructor = {}.constructor |
| 4 | + |
| 5 | +function exists (value) { |
| 6 | + return value !== null && typeof value !== 'undefined' |
| 7 | +} |
| 8 | + |
| 9 | +function isPlainObject (value) { |
| 10 | + return value.constructor === plainObjectConstructor |
| 11 | +} |
| 12 | + |
| 13 | +function isString (value) { |
| 14 | + return typeof value === 'string' |
| 15 | +} |
| 16 | + |
| 17 | +function renderChildren (el, children) { |
| 18 | + for (const child of children) { |
| 19 | + if (isPlainObject(child)) { |
| 20 | + Object.entries(child) |
| 21 | + .filter(([key, value]) => exists(value)) |
| 22 | + .forEach(([key, value]) => el.setAttribute(key, value)) |
| 23 | + } else if (Array.isArray(child)) { |
| 24 | + renderChildren(el, child) |
| 25 | + } else if (isString(child)) { |
| 26 | + el.append(document.createTextNode(child)) |
| 27 | + } else { |
| 28 | + el.append(child) |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +export default function h (tagName, ...children) { |
| 34 | + const el = ['svg', 'path'].includes(tagName) |
| 35 | + ? document.createElementNS(xmlns, tagName) |
| 36 | + : document.createElement(tagName) |
| 37 | + renderChildren(el, children) |
| 38 | + return el |
| 39 | +} |
| 40 | + |
| 41 | +export const tags = Object.fromEntries( |
| 42 | + ['div', 'form', 'a', 'input', 'button', 'ol', 'li', 'em'] |
| 43 | + .map(tagName => [tagName, (...args) => h(tagName, ...args)]) |
| 44 | +) |
0 commit comments