@@ -38,57 +38,43 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable<string>)
3838 if ( ! names ) names = attrs . get ( Object . getPrototypeOf ( instance ) ) || [ ]
3939 for ( const key of names ) {
4040 const value = ( < Record < PropertyKey , unknown > > ( < unknown > instance ) ) [ key ]
41+ const name = attrToAttributeName ( key )
4142 let descriptor : PropertyDescriptor
4243 if ( typeof value === 'number' ) {
43- descriptor = numberProperty ( key )
44+ descriptor = {
45+ get ( this : HTMLElement ) : number {
46+ return Number ( this . getAttribute ( name ) || 0 )
47+ } ,
48+ set ( this : HTMLElement , newValue : string ) {
49+ this . setAttribute ( name , newValue )
50+ }
51+ }
4452 } else if ( typeof value === 'boolean' ) {
45- descriptor = booleanProperty ( key )
53+ descriptor = {
54+ get ( this : HTMLElement ) : boolean {
55+ return this . hasAttribute ( name )
56+ } ,
57+ set ( this : HTMLElement , newValue : boolean ) {
58+ this . toggleAttribute ( name , newValue )
59+ }
60+ }
4661 } else {
47- descriptor = stringProperty ( key )
62+ descriptor = {
63+ get ( this : HTMLElement ) : string {
64+ return String ( this . getAttribute ( name ) || '' )
65+ } ,
66+ set ( this : HTMLElement , newValue : string ) {
67+ this . setAttribute ( name , newValue || '' )
68+ }
69+ }
4870 }
4971 Object . defineProperty ( instance , key , descriptor )
50- if ( key in instance && ! instance . hasAttribute ( attrToAttributeName ( key ) ) ) {
72+ if ( key in instance && ! instance . hasAttribute ( name ) ) {
5173 descriptor . set ! . call ( instance , value )
5274 }
5375 }
5476}
5577
56- function booleanProperty ( key : string ) : PropertyDescriptor {
57- const attributeName = attrToAttributeName ( key )
58- return {
59- get ( this : HTMLElement ) : boolean {
60- return this . hasAttribute ( attributeName )
61- } ,
62- set ( this : HTMLElement , value : boolean ) {
63- this . toggleAttribute ( attributeName , value )
64- }
65- }
66- }
67-
68- function stringProperty ( key : string ) : PropertyDescriptor {
69- const attributeName = attrToAttributeName ( key )
70- return {
71- get ( this : HTMLElement ) : string {
72- return String ( this . getAttribute ( attributeName ) || '' )
73- } ,
74- set ( this : HTMLElement , value : string ) {
75- this . setAttribute ( attributeName , value || '' )
76- }
77- }
78- }
79-
80- function numberProperty ( key : string ) : PropertyDescriptor {
81- const attributeName = attrToAttributeName ( key )
82- return {
83- get ( this : HTMLElement ) : number {
84- return Number ( this . getAttribute ( attributeName ) || 0 )
85- } ,
86- set ( this : HTMLElement , value : number ) {
87- this . setAttribute ( attributeName , String ( value ) )
88- }
89- }
90- }
91-
9278function attrToAttributeName ( name : string ) : string {
9379 return `data-${ name . replace ( / ( [ A - Z ] ( $ | [ a - z ] ) ) / g, '-$1' ) } ` . replace ( / - - / g, '-' ) . toLowerCase ( )
9480}
0 commit comments