import React from 'react' ; import NativeSelect , { NativeSelectProps , } from './NativeSelect' ; import EnhancedSelect , { EnhancedSelectProps , } from './EnhancedSelect' ; import { MDCSelectFoundation } from '@material/select/foundation' ; export type BaseSelectProps < T extends HTMLElement > = T extends HTMLSelectElement ? NativeSelectProps : EnhancedSelectProps ; export interface CommonSelectProps { enhanced : boolean ; className ? : string ; disabled ? : boolean ; foundation ? : MDCSelectFoundation ; value ? : string ; selectClassName ? : string ; } export class BaseSelect < T extends HTMLElement = HTMLSelectElement > extends React . Component < BaseSelectProps < T > > { static defaultProps = { enhanced : false , selectClassName : '' , } ; handleFocus = ( evt ) => { const { foundation , onFocus } = this . props ; if ( foundation ) { foundation . handleFocus ( ) ; } onFocus && onFocus ( evt ) ; } ; handleBlur = ( evt ) => { const { foundation , onBlur } = this . props ; if ( foundation ) { foundation . handleBlur ( ) ; } onBlur && onBlur ( evt ) ; } ; handleTouchStart = ( evt ) => { const { foundation , onTouchStart } = this . props ; if ( foundation ) { foundation . handleClick ( this . getNormalizedXCoordinate ( evt ) ) ; } onTouchStart && onTouchStart ( evt ) ; } ; handleMouseDown = ( evt ) => { const { foundation , onMouseDown } = this . props ; if ( foundation ) { foundation . handleClick ( this . getNormalizedXCoordinate ( evt ) ) ; } onMouseDown && onMouseDown ( evt ) ; } ; handleClick = ( evt ) => { const { foundation , onClick } = this . props ; if ( foundation ) { foundation . handleClick ( this . getNormalizedXCoordinate ( evt ) ) ; } onClick && onClick ( evt ) ; } ; handleKeyDown = ( evt ) => { const { foundation , onKeyDown } = this . props ; if ( foundation ) { foundation . handleKeydown ( evt . nativeEvent ) ; } onKeyDown && onKeyDown ( evt ) ; } ; private isTouchEvent = ( evt ) : evt is TouchEvent => { return Boolean ( ( evt as TouchEvent ) . touches ) ; } ; private getNormalizedXCoordinate = ( evt ) => { const targetClientRect = ( evt . currentTarget as Element ) . getBoundingClientRect ( ) ; const xCoordinate = this . isTouchEvent ( evt . nativeEvent ) ? evt . nativeEvent . touches [ 0 ] . clientX : evt . nativeEvent . clientX ; return xCoordinate - targetClientRect . left ; } ; render ( ) { const { onFocus , onBlur , onClick , onMouseDown , onTouchStart , ref , enhanced , children , onKeyDown , selectClassName , ... otherProps } = this . props ; const props = { onFocus : this . handleFocus , onBlur : this . handleBlur , onMouseDown : this . handleMouseDown , onClick : this . handleClick , onTouchStart : this . handleTouchStart , className : selectClassName , ... otherProps , } ; if ( enhanced ) { return ( < EnhancedSelect onKeyDown = { this . handleKeyDown } { ... props } > { children } < /EnhancedSelect>); } return ( < NativeSelect onKeyDown = { onKeyDown } { ... props } > { children } < /NativeSelect>); } }