/
useClearButton.ts
42 lines (35 loc) · 1.09 KB
/
useClearButton.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { RefObject, useCallback } from 'react'
import { focusWithoutScrolling } from '../../libs/dom-utils'
import type { ButtonBaseProps } from '../button'
import type { CommonTextFieldProps } from './types'
export interface UseClearButtonResult {
isActive: boolean
buttonProps: ButtonBaseProps
}
export function useClearButton(
props: CommonTextFieldProps,
inputRef: RefObject<HTMLInputElement | HTMLTextAreaElement>,
): UseClearButtonResult {
const { onChange, value, disabled, readOnly } = props
const isInteractive = !(readOnly || disabled)
const isActive = isInteractive && Boolean(value)
const onPress = useCallback(() => {
if (inputRef.current) {
focusWithoutScrolling(inputRef.current)
const syntheticEvent = Object.create({})
syntheticEvent.target = inputRef.current
syntheticEvent.currentTarget = inputRef.current
inputRef.current.value = ''
onChange?.(syntheticEvent)
}
}, [inputRef, onChange])
return {
isActive,
buttonProps: {
disabled,
onPress,
preventFocusOnPress: true,
tabIndex: -1,
},
}
}