diff --git a/src/FocusSensor/index.ts b/src/FocusSensor/index.ts new file mode 100644 index 00000000..5ab84de8 --- /dev/null +++ b/src/FocusSensor/index.ts @@ -0,0 +1,47 @@ +import {Component, cloneElement} from 'react'; +import {h} from '../util'; +import {Value} from '../Value'; +import renderProp from '../util/renderProp'; +import faccToHoc from '../util/faccToHoc'; + +export interface IFocusSensorProps { + bond?: boolean | string; +} + +export const FocusSensor: React.StatelessComponent = (props: IFocusSensorProps) => { + let {bond} = props; + + return Value({ + render: ({value, set}) => { + if (bond) { + if (typeof bond === 'boolean') { + bond = 'bond'; + } + + return renderProp(props, { + isActive: value, + [bond]: { + onFocus: () => set(true), + onBlur: () => set(false), + } + }); + } else { + const element = renderProp(props, { + isActive: value + }); + + return cloneElement(element, { + onFocus: () => set(true), + onBlur: () => set(false), + }); + } + } + }); +}; + +const FocusSensorWithBond = (props) => h(FocusSensor, { + bond: true, + ...props +}); + +export const withFocus = faccToHoc(FocusSensorWithBond, 'focus');