Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/crank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,41 @@ export function createElement<TTag extends Tag>(
return new Element(tag, props as TagProps<TTag>);
}

/**
* Provides dynamic tag functions for creating elements.
*
* Accessing a property returns a function that calls `createElement`
* with the property name as the tag name.
*
* @example
* tags.div({ class: "foo" }, "Hello");
*/
export const tags = new Proxy(
Object.create(null) as Record<
string,
(
props?: Record<string, unknown> | null | undefined,
...children: Array<unknown>
) => Element<string>
>,
{
get(target, tag: string | symbol) {
if (typeof tag === "symbol" || tag === "then") {
return undefined;
}

if (!(tag in target)) {
target[tag] = (
props?: Record<string, unknown> | null | undefined,
...children: Array<unknown>
) => createElement(tag, props, ...children);
}

return target[tag];
}
}
);

/** Clones a given element, shallowly copying the props object. */
export function cloneElement<TTag extends Tag>(
el: Element<TTag>,
Expand Down