-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathModal.tsx
More file actions
95 lines (81 loc) · 2.69 KB
/
Modal.tsx
File metadata and controls
95 lines (81 loc) · 2.69 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import clsx from 'clsx';
import { type PropsWithChildren, useCallback } from 'react';
import React, { useEffect, useRef } from 'react';
import { FocusScope } from '@react-aria/focus';
import { CloseIconRound } from './icons';
import { useTranslationContext } from '../../context';
type CloseEvent =
| KeyboardEvent
| React.KeyboardEvent
| React.MouseEvent<HTMLButtonElement | HTMLDivElement>;
export type ModalCloseSource = 'overlay' | 'button' | 'escape';
export type ModalProps = {
/** If true, modal is opened or visible. */
open: boolean;
/** Custom class to be applied to the modal root div */
className?: string;
/** Callback handler for closing of modal. */
onClose?: (event: CloseEvent) => void;
/** Optional handler to intercept closing logic. Return false to prevent onClose. */
onCloseAttempt?: (source: ModalCloseSource, event: CloseEvent) => boolean;
};
export const Modal = ({
children,
className,
onClose,
onCloseAttempt,
open,
}: PropsWithChildren<ModalProps>) => {
const { t } = useTranslationContext('Modal');
const innerRef = useRef<HTMLDivElement | null>(null);
const closeButtonRef = useRef<HTMLButtonElement | null>(null);
const maybeClose = useCallback(
(source: ModalCloseSource, event: CloseEvent) => {
const allow = onCloseAttempt?.(source, event);
if (allow !== false) {
onClose?.(event);
}
},
[onClose, onCloseAttempt],
);
const handleClick = (event: React.MouseEvent<HTMLButtonElement | HTMLDivElement>) => {
const target = event.target as HTMLButtonElement | HTMLDivElement;
if (!innerRef.current || !closeButtonRef.current) return;
if (closeButtonRef.current.contains(target)) {
maybeClose('button', event);
} else if (!innerRef.current.contains(target)) {
maybeClose('overlay', event);
}
};
useEffect(() => {
if (!open) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') maybeClose('escape', event);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [maybeClose, open]);
if (!open) return null;
return (
<div
className={clsx('str-chat__modal str-chat__modal--open', className)}
onClick={handleClick}
>
<FocusScope autoFocus contain>
<button
className='str-chat__modal__close-button'
ref={closeButtonRef}
title={t('Close')}
>
<CloseIconRound />
</button>
<div
className='str-chat__modal__inner str-chat-react__modal__inner'
ref={innerRef}
>
{children}
</div>
</FocusScope>
</div>
);
};