11import { BaseControl } from "@wordpress/components" ;
22import { useInstanceId } from "@wordpress/compose" ;
3- import { forwardRef } from "@wordpress/element" ;
4- import type { ChangeEvent , ForwardedRef } from 'react' ;
3+ import { forwardRef , useState } from "@wordpress/element" ;
4+ import type { ChangeEvent , FormEvent , ForwardedRef } from 'react' ;
55
66interface Props {
77 value : number
88 unit : string
9- onChange : any
9+ onChange : ( value : number , unit : string ) => any
1010 label : string
1111 help ?: string
1212}
1313
14+ interface State {
15+ value : number ;
16+ unit : string ;
17+ }
18+
1419export const TextControlWithUnit = forwardRef ( UnforwardedTextControlWithUnit ) ;
1520export default TextControlWithUnit ;
1621
1722function UnforwardedTextControlWithUnit ( props : Props , ref : ForwardedRef < HTMLInputElement > ) {
1823 const instanceId = useInstanceId ( TextControlWithUnit ) ;
1924 const id = `inspector-text-control-${ instanceId } ` ;
20- const onChangeValue = ( event : ChangeEvent < HTMLInputElement > ) => props . onChange ( event . target . value ) ;
25+ const units = [ "px" ] ;
26+
27+ const [ state , setState ] = useState < State > ( {
28+ value : props . value ,
29+ unit : props . unit ,
30+ } ) ;
31+
32+ const onChangeValue = ( event : ChangeEvent < HTMLInputElement > ) => {
33+ const target = event . target as HTMLInputElement ;
34+ const value = + target . value ;
35+ setState ( {
36+ ...state ,
37+ value : value ,
38+ } ) ;
39+ props . onChange ( value , state . unit ) ;
40+ } ;
41+
42+ const onChangeUnit = ( event : FormEvent < HTMLSelectElement > ) => {
43+ const target = event . target as HTMLSelectElement ;
44+ const unit = target . value ;
45+ setState ( {
46+ ...state ,
47+ unit : unit ,
48+ } ) ;
49+ props . onChange ( state . value , unit ) ;
50+ } ;
2151
2252 return (
2353 < div className = { "chatrix-text-control-with-unit" } >
@@ -31,12 +61,14 @@ function UnforwardedTextControlWithUnit(props: Props, ref: ForwardedRef<HTMLInpu
3161 className = "components-text-control__input"
3262 type = { "text" }
3363 id = { id }
34- value = { props . value }
64+ value = { state . value }
3565 onChange = { onChangeValue }
3666 aria-describedby = { ! ! props . help ? id + '__help' : undefined }
3767 ref = { ref }
3868 />
39- < span > { props . unit } </ span >
69+ < select value = { state . unit } onChange = { onChangeUnit } >
70+ { units . map ( unit => < option value = { unit } key = { unit } > { unit } </ option > ) }
71+ </ select >
4072 </ span >
4173 </ BaseControl >
4274 </ div >
0 commit comments