Commit c8426764 authored by Akari Labs's avatar Akari Labs

push new typescript inert

parent 16a4595a
export interface WrappedElement { element: HTMLElement, [x: string]: any }
export type InertAttributes = { [key: string]: string };
export type InertElement = HTMLElement | WrappedElement | ElementArray | string;
interface ElementArray extends Array<InertElement> { }
export type InertTag = ((attributes: InertAttributes, children: InertElement) => HTMLElement | WrappedElement) | string;
export function inert(tag: InertTag, attrs?: InertAttributes, ..._children: InertElement[]): HTMLElement {
var children: InertElement = _children;
function reduceChild(child: InertElement): InertElement[] {
if (Array.isArray(child)) return child.map(reduceChild);
return [child];
}
if (Array.isArray(children[0]) && children.length === 1) children = children[0];
if (Array.isArray(children) && children.length !== 0)
children = children.map(reduceChild).reduce((p, c) => p.concat(c));
var element: HTMLElement;
switch (typeof tag) {
case 'function':
const ielement = tag(attrs || {}, children);
if (ielement instanceof HTMLElement) element = ielement;
else if (ielement.element != null) element = ielement.element;
break;
case 'string':
element = window.document.createElement(tag);
if (attrs != null) for (var k in attrs) {
const a = attrs[k];
switch (typeof a) {
case 'boolean':
if (a) element.setAttribute(k, '');
break;
case 'function':
// a bit of a hack, but it works
if (k.startsWith('on')) {
element[k] = a;
break;
}
default:
element.setAttribute(k, a);
break;
}
}
function addChild(child: InertElement) {
if (child == null) return;
else if (Array.isArray(child)) child.forEach(addChild);
else if (child instanceof HTMLElement) element.appendChild(child);
else if ((typeof child === 'object') && (child.element != null)) element.appendChild(child.element);
else element.append(child.toString());
}
addChild(children);
break;
}
return element;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment