import * as RMWC from '@rmwc/types' ; import { CheckboxProps , CheckboxHTMLProps } from '.' ; import { useToggleFoundation } from '@rmwc/toggleable' ; import { useFoundation } from '@rmwc/base' ; import { MDCCheckboxFoundation } from '@material/checkbox' ; import React , { useEffect , useCallback } from 'react' ; export const useCheckboxFoundation = ( props ) => { const { renderToggle , toggleRootProps , id } = useToggleFoundation < MDCCheckboxFoundation > ( props ) ; const { foundation , ... elements } = useFoundation ( { props , elements : { rootEl : true , checkboxEl : true } , foundation : ( { rootEl , checkboxEl , getProps } ) => { return new MDCCheckboxFoundation ( { addClass : ( className ) => rootEl . addClass ( className ) , removeClass : ( className ) => rootEl . removeClass ( className ) , setNativeControlAttr : ( attr , value ) => checkboxEl . setProp ( attr as any , value ) , removeNativeControlAttr : ( attr ) => checkboxEl . removeProp ( attr as any ) , isIndeterminate : ( ) => ! ! getProps ( ) . indeterminate , isChecked : ( ) => getProps ( ) . checked !== undefined ? ! ! getProps ( ) . checked : ! ! ( checkboxEl . ref as HTMLInputElement ) ?. checked , hasNativeControl : ( ) => ! ! checkboxEl . ref , setNativeControlDisabled : ( disabled ) => checkboxEl . setProp ( 'disabled' , disabled ) , forceLayout : ( ) => rootEl . ref ?. offsetWidth , isAttachedToDOM : ( ) => true } ) ; } } ) ; const { rootEl , checkboxEl } = elements ; const doSync = useCallback ( ( ) => { if ( checkboxEl . ref ) { ( checkboxEl . ref as HTMLInputElement ) . indeterminate = Boolean ( props . indeterminate ) ; } window . requestAnimationFrame ( ( ) => { foundation . handleChange ( ) ; } ) ; } , [ props . indeterminate , foundation , checkboxEl . ref ] ) ; useEffect ( ( ) => { doSync ( ) ; } , [ doSync ] ) ; const handleAnimationEnd = ( evt ) => { props . onAnimationEnd ?. ( evt ) ; foundation . handleAnimationEnd ( ) ; } ; const handleOnChange = ( evt ) => { props . onChange ?. ( evt ) ; doSync ( ) ; } ; rootEl . setProp ( 'onAnimationEnd' , handleAnimationEnd , true ) ; checkboxEl . setProp ( 'onChange' , handleOnChange , true ) ; return { foundation , renderToggle , toggleRootProps , id , ... elements } ; } ;