@ -1,11 +1,11 @@
type Attributes = {
type DataAttributes = {
[ key : string ] : string | number ;
data : {
} & {
data ? : {
[ key : string ] : string | number ;
[ key : string ] : string | number ;
}
}
} ;
} ;
type Attributes < Type > = Partial < Type & DataAttributes > ;
/ * *
/ * *
* example usage :
* example usage :
*
*
@ -15,31 +15,43 @@ type Attributes = {
*
*
* @param { string } name
* @param { string } name
* @param { HTMLElement . prototype } props
* @param { HTMLElement . prototype } props
* @param { Array < HTMLElement| string > } children
* @param { Array < Node> | string | number } children
* @return HTMLElement
* @return HTMLElement
* /
* /
export const elem = < Name extends keyof HTMLElementTagNameMap > (
export const elem = < Name extends keyof HTMLElementTagNameMap > (
name : Extract < Name , keyof HTMLElementTagNameMap > ,
name : Extract < Name , keyof HTMLElementTagNameMap > ,
attrs : Attributes = { } , // TODO optional
attrs ?: Attributes < HTMLElementTagNameMap [ Name ] > ,
children : Array < Node > | string = [ ] , // TODO optional
children ?: Array < HTMLElement | string > | string | number ,
) : HTMLElementTagNameMap [ Name ] = > {
) : HTMLElementTagNameMap [ Name ] = > {
const { data , . . . props } = attrs ;
const el = document . createElement ( name ) ;
const el = document . createElement ( name ) ;
Object . assign ( el , props ) ;
if ( attrs ) {
if ( Array . isArray ( children ) ) {
const { data , . . . props } = attrs ;
el . append ( . . . children ) ;
Object . assign ( el , props ) ;
} else {
if ( data ) {
const childType = typeof children ;
Object . entries ( data ) . forEach ( ( [ key , value ] ) = > {
if ( childType === 'number' || childType === 'string' ) {
el . dataset [ key ] = value as string ;
el . append ( children ) ;
} ) ;
} else {
console . error ( 'call me' ) ;
}
}
}
}
if ( data ) {
if ( children != null ) {
Object . entries ( data ) . forEach ( ( [ key , value ] ) = > {
if ( Array . isArray ( children ) ) {
el . dataset [ key ] = value as string ;
el . append ( . . . children ) ;
} ) ;
} else {
switch ( typeof children ) {
case 'number' :
el . append ( ` ${ children } ` ) ;
break ;
case 'string' :
el . append ( children ) ;
break ;
default :
if ( children instanceof Element ) {
el . append ( children ) ;
break ;
}
console . error ( ` expected element, string or number but got ${ typeof children } ` , children ) ;
}
}
}
}
return el ;
return el ;
} ;
} ;