-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
83 lines (73 loc) · 1.81 KB
/
index.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { useCallback, useMemo, useRef, useState } from 'react'
function useHtmlDialog(options: {
resetStyles?: boolean
closeOnOutsideClick?: boolean
}): ReturnShape {
const ref = useRef<HTMLDialogElement>(null)
const [isOpen, setIsOpen] = useState(false)
const show = useCallback(() => {
ref.current?.show()
setIsOpen(true)
}, [])
const showModal = useCallback(() => {
ref.current?.showModal()
setIsOpen(true)
}, [])
const close = useCallback(() => {
ref.current?.close()
setIsOpen(false)
}, [])
const dialogElementProps = useMemo(() => {
const onClick: DialogElementProps['onClick'] = (
e: React.MouseEvent<HTMLDialogElement, MouseEvent>,
) => {
if (options?.closeOnOutsideClick === false) {
return
}
if (e.target === ref.current) {
close()
}
}
const onKeyDown: DialogElementProps['onKeyDown'] = (
e: React.KeyboardEvent<HTMLDialogElement>,
) => {
if (e.key === 'Escape') {
close()
}
}
const style: React.CSSProperties | undefined =
options?.resetStyles === false
? undefined
: {
padding: 0,
border: 'none',
background: 'transparent',
}
return { ref, style, onClick, onKeyDown } satisfies DialogElementProps
}, [options, close])
return {
ref,
show,
showModal,
close,
props: dialogElementProps,
isOpen,
}
}
type DialogElementProps = React.HTMLAttributes<HTMLDialogElement> & {
ref: React.RefObject<HTMLDialogElement>
}
type ReturnShape = {
ref: React.RefObject<HTMLDialogElement>
show: () => void
showModal: () => void
close: () => void
props: {
ref: React.RefObject<HTMLDialogElement>
style: React.CSSProperties | undefined
onClick: (e: React.MouseEvent<HTMLDialogElement, MouseEvent>) => void
onKeyDown: (e: React.KeyboardEvent<HTMLDialogElement>) => void
}
isOpen: boolean
}
export { useHtmlDialog }