signal-desktop/ts/components/Toast.tsx

117 lines
2.9 KiB
TypeScript
Raw Normal View History

2021-09-22 20:59:54 +00:00
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import React, {
KeyboardEvent,
MouseEvent,
ReactNode,
memo,
useEffect,
} from 'react';
2021-09-22 20:59:54 +00:00
import classNames from 'classnames';
import { createPortal } from 'react-dom';
2021-10-06 21:00:51 +00:00
import { useRestoreFocus } from '../hooks/useRestoreFocus';
2021-09-22 20:59:54 +00:00
export type PropsType = {
autoDismissDisabled?: boolean;
children: ReactNode;
className?: string;
2021-09-24 02:08:01 +00:00
disableCloseOnClick?: boolean;
2021-09-22 20:59:54 +00:00
onClose: () => unknown;
timeout?: number;
2021-10-06 21:00:51 +00:00
toastAction?: {
label: string;
onClick: () => unknown;
};
2021-09-22 20:59:54 +00:00
};
export const Toast = memo(
({
autoDismissDisabled = false,
children,
className,
disableCloseOnClick = false,
onClose,
timeout = 8000,
toastAction,
}: PropsType): JSX.Element | null => {
const [root, setRoot] = React.useState<HTMLElement | null>(null);
const [focusRef] = useRestoreFocus();
2021-09-22 20:59:54 +00:00
useEffect(() => {
const div = document.createElement('div');
document.body.appendChild(div);
setRoot(div);
2021-09-22 20:59:54 +00:00
return () => {
document.body.removeChild(div);
setRoot(null);
};
}, []);
2021-09-22 20:59:54 +00:00
useEffect(() => {
if (!root || autoDismissDisabled) {
return;
}
2021-09-22 20:59:54 +00:00
const timeoutId = setTimeout(onClose, timeout);
2021-09-22 20:59:54 +00:00
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [autoDismissDisabled, onClose, root, timeout]);
2021-09-22 20:59:54 +00:00
return root
? createPortal(
<div
aria-live="assertive"
className={classNames('Toast', className)}
onClick={() => {
2021-10-06 21:00:51 +00:00
if (!disableCloseOnClick) {
onClose();
}
}}
onKeyDown={(ev: KeyboardEvent<HTMLDivElement>) => {
if (ev.key === 'Enter' || ev.key === ' ') {
if (!disableCloseOnClick) {
onClose();
}
}
}}
role="button"
tabIndex={0}
>
<div className="Toast__content">{children}</div>
{toastAction && (
<div
className="Toast__button"
onClick={(ev: MouseEvent<HTMLDivElement>) => {
2021-10-06 21:00:51 +00:00
ev.stopPropagation();
ev.preventDefault();
toastAction.onClick();
2021-10-21 20:14:26 +00:00
onClose();
}}
onKeyDown={(ev: KeyboardEvent<HTMLDivElement>) => {
if (ev.key === 'Enter' || ev.key === ' ') {
ev.stopPropagation();
ev.preventDefault();
toastAction.onClick();
2021-10-21 20:14:26 +00:00
onClose();
}
}}
ref={focusRef}
role="button"
tabIndex={0}
>
{toastAction.label}
</div>
)}
</div>,
root
)
: null;
}
);