forked from use-platform/use-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseButton.ts
More file actions
63 lines (54 loc) · 1.88 KB
/
useButton.ts
File metadata and controls
63 lines (54 loc) · 1.88 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { AllHTMLAttributes, ElementType, HTMLAttributes, RefObject } from 'react'
import { useFocusable } from '../../interactions/focusable'
import { usePress } from '../../interactions/press'
import { mergeProps } from '../../libs/merge-props'
import { isFirefox } from '../../libs/platform'
import type { SharedButtonProps } from '../../shared/types'
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface UseButtonProps<T extends HTMLElement = HTMLElement> extends SharedButtonProps<T> {}
export interface UseButtonResult<T> {
isPressed: boolean
buttonProps: HTMLAttributes<T>
ElementType: ElementType
}
export function useButton<T extends HTMLElement = HTMLElement>(
props: UseButtonProps<T>,
ref: RefObject<T>,
): UseButtonResult<T> {
const {
as: elementType = 'button',
disabled,
href,
target,
rel,
type = 'button',
tabIndex,
...restProps
} = props
let additionalProps: AllHTMLAttributes<T>
if (elementType === 'button') {
additionalProps = { type, disabled }
if (isFirefox()) {
// https://bugzilla.mozilla.org/show_bug.cgi?id=654072
additionalProps.autoComplete = 'off'
}
} else {
additionalProps = {
role: 'button',
tabIndex: disabled ? undefined : 0,
href: elementType === 'a' && disabled ? undefined : href,
target: elementType === 'a' ? target : undefined,
type: elementType === 'input' ? type : undefined,
disabled: elementType === 'input' ? disabled : undefined,
'aria-disabled': !disabled || elementType === 'input' ? undefined : disabled,
rel: elementType === 'a' ? rel : undefined,
}
}
const { focusableProps } = useFocusable(props, ref)
const { isPressed, pressProps } = usePress(props)
return {
buttonProps: mergeProps(restProps, additionalProps, focusableProps, pressProps),
ElementType: elementType,
isPressed,
}
}