-
Notifications
You must be signed in to change notification settings - Fork 15
/
usePasswordField.ts
45 lines (38 loc) · 1.05 KB
/
usePasswordField.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
43
44
45
import { RefObject, useState } from 'react'
import { focusWithoutScrolling, setCursorToEnd } from '../../libs/dom-utils'
import type { ButtonBaseProps } from '../button'
import type { TextFieldBaseProps } from './types'
export interface UsePasswordFieldResult {
isShown: boolean
buttonProps: ButtonBaseProps
inputProps: TextFieldBaseProps
}
export function usePasswordField(
props: TextFieldBaseProps,
inputRef: RefObject<HTMLInputElement | HTMLTextAreaElement>,
): UsePasswordFieldResult {
const { disabled } = props
const [isShown, setShown] = useState(false)
const onPress = () => {
setShown(!isShown)
if (inputRef.current) {
focusWithoutScrolling(inputRef.current)
}
// Use raf for set cursor at the end after layout changed.
requestAnimationFrame(() => {
setCursorToEnd(inputRef.current)
})
}
return {
isShown: isShown,
buttonProps: {
disabled,
onPress,
preventFocusOnPress: true,
tabIndex: -1,
},
inputProps: {
type: isShown ? 'text' : 'password',
},
}
}