|
| 1 | +import { HTMLProps } from 'web-utility/source/DOM-type'; |
| 2 | +import { clearList } from './utility'; |
| 3 | +import { AsyncComponent } from './AsyncComponent'; |
| 4 | + |
| 5 | +export interface VElement { |
| 6 | + tagName: string; |
| 7 | + childNodes: VChildNode[]; |
| 8 | + [key: string]: any; |
| 9 | +} |
| 10 | +export type VChild = string | number | boolean | VElement; |
| 11 | +export type VChildNode = VChild | AsyncComponent; |
| 12 | +export type VChildren = VChildNode | VChildNode[]; |
| 13 | + |
| 14 | +export type GeneratorNode = Generator<VChildren, any, Node | Node[]>; |
| 15 | +export type AsyncGeneratorNode = AsyncGenerator<VChildren, any, Node | Node[]>; |
| 16 | + |
| 17 | +export type AsyncNode = Promise<VChildren> | GeneratorNode | AsyncGeneratorNode; |
| 18 | + |
| 19 | +export type RenderNode = VChildren | AsyncNode; |
| 20 | + |
| 21 | +export interface Props extends HTMLProps { |
| 22 | + children?: VChildren; |
| 23 | + [key: string]: any; |
| 24 | +} |
| 25 | + |
| 26 | +export type FunctionComponent = (props: Props) => RenderNode; |
| 27 | + |
| 28 | +export type Component = string | FunctionComponent; |
| 29 | + |
| 30 | +declare global { |
| 31 | + namespace JSX { |
| 32 | + interface IntrinsicElements { |
| 33 | + [tagName: string]: Props; |
| 34 | + } |
| 35 | + interface ElementChildrenAttribute { |
| 36 | + children: VChildren; |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +export function createElement( |
| 42 | + tagName: Component, |
| 43 | + props: Props | null, |
| 44 | + ...childNodes: VChildNode[] |
| 45 | +) { |
| 46 | + childNodes = clearList(childNodes); |
| 47 | + |
| 48 | + if (typeof tagName === 'string') |
| 49 | + return { |
| 50 | + ...props, |
| 51 | + tagName: tagName as string, |
| 52 | + childNodes |
| 53 | + }; |
| 54 | + |
| 55 | + props = { ...props, children: childNodes }; |
| 56 | + |
| 57 | + const result = tagName(props); |
| 58 | + |
| 59 | + if (typeof (result as Promise<any>).then === 'function') |
| 60 | + return new AsyncComponent(async function* () { |
| 61 | + yield await (result as Promise<any>); |
| 62 | + }, props); |
| 63 | + |
| 64 | + if (typeof (result as Generator).next === 'function') |
| 65 | + return new AsyncComponent(tagName, props); |
| 66 | + |
| 67 | + return result; |
| 68 | +} |
| 69 | + |
| 70 | +export function Fragment({ children }: Props) { |
| 71 | + return children; |
| 72 | +} |
0 commit comments