signal-desktop/ts/components/Toast.tsx

96 lines
2.3 KiB
TypeScript
Raw Normal View History

2023-01-03 19:55:46 +00:00
// Copyright 2021 Signal Messenger, LLC
2021-09-22 20:59:54 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
import type { KeyboardEvent, MouseEvent, ReactNode } from 'react';
import React, { memo, useEffect } from 'react';
2021-09-22 20:59:54 +00:00
import classNames from 'classnames';
2021-10-06 21:00:51 +00:00
import { useRestoreFocus } from '../hooks/useRestoreFocus';
import { clearTimeoutIfNecessary } from '../util/clearTimeoutIfNecessary';
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;
};
style?: React.CSSProperties;
2021-09-22 20:59:54 +00:00
};
2022-11-18 00:45:19 +00:00
export const Toast = memo(function ToastInner({
autoDismissDisabled = false,
children,
className,
disableCloseOnClick = false,
onClose,
style,
timeout = 8000,
toastAction,
}: PropsType): JSX.Element | null {
const [focusRef] = useRestoreFocus();
2023-06-13 16:40:48 +00:00
useEffect(() => {
if (autoDismissDisabled) {
2022-11-18 00:45:19 +00:00
return;
}
2021-09-22 20:59:54 +00:00
2022-11-18 00:45:19 +00:00
const timeoutId = setTimeout(onClose, timeout);
2021-09-22 20:59:54 +00:00
2022-11-18 00:45:19 +00:00
return () => {
clearTimeoutIfNecessary(timeoutId);
};
}, [autoDismissDisabled, onClose, timeout]);
2021-09-22 20:59:54 +00:00
return (
<div
aria-live="assertive"
className={classNames('Toast', className)}
onClick={() => {
if (!disableCloseOnClick) {
onClose();
}
}}
onKeyDown={(ev: KeyboardEvent<HTMLDivElement>) => {
if (ev.key === 'Enter' || ev.key === ' ') {
if (!disableCloseOnClick) {
onClose();
}
}
}}
role="button"
tabIndex={0}
style={style}
>
<div className="Toast__content">{children}</div>
{toastAction && (
2022-11-18 00:45:19 +00:00
<div
className="Toast__button"
onClick={(ev: MouseEvent<HTMLDivElement>) => {
ev.stopPropagation();
ev.preventDefault();
toastAction.onClick();
onClose();
2022-11-18 00:45:19 +00:00
}}
onKeyDown={(ev: KeyboardEvent<HTMLDivElement>) => {
if (ev.key === 'Enter' || ev.key === ' ') {
ev.stopPropagation();
ev.preventDefault();
toastAction.onClick();
onClose();
2022-11-18 00:45:19 +00:00
}
}}
ref={focusRef}
2022-11-18 00:45:19 +00:00
role="button"
tabIndex={0}
>
{toastAction.label}
</div>
)}
</div>
);
2022-11-18 00:45:19 +00:00
});