import React, { createRef, useCallback, useImperativeHandle, useState, } from 'react'; import ReactDOM from 'react-dom'; import {TRANSPARENT} from '../../helpers/colors'; import {useSyncExternalStore} from '../../helpers/use-sync-external-store'; import { getActiveStudioDialog, subscribeToStudioDialogs, } from '../../state/studio-dialog'; import {useZIndex} from '../../state/z-index'; import {getPortal} from '../Menu/portals'; import {Notification} from './Notification'; const container: React.CSSProperties = { position: 'absolute', zIndex: 1, justifyContent: 'center', alignItems: 'center', display: 'flex', width: '100%', flexDirection: 'column', paddingTop: 40, pointerEvents: 'none', backgroundColor: TRANSPARENT, }; type TNotification = { id: string; content: React.ReactNode; created: number; duration: number | null; }; type CreatedNotification = { dismiss: () => void; replaceContent: ( newContent: React.ReactNode, durationInMs: number | null, ) => void; }; type TNotificationCenter = { addNotification: (notification: TNotification) => CreatedNotification; }; const notificationCenter = createRef(); export const showNotification = ( content: React.ReactNode, durationInMs: number | null, ) => { return (notificationCenter.current as TNotificationCenter).addNotification({ content, duration: durationInMs, created: Date.now(), id: String(Math.random()).replace('0.', ''), }); }; export const NotificationCenter: React.FC = () => { const [notifications, setNotifications] = useState([]); const {currentZIndex} = useZIndex(); const dialog = useSyncExternalStore( subscribeToStudioDialogs, getActiveStudioDialog, ); const onRemove = useCallback((id: string) => { setNotifications((not) => { return not.filter((n) => n.id !== id); }); }, []); const addNotification = useCallback( (notification: TNotification): CreatedNotification => { setNotifications((previousNotifications) => { return [...previousNotifications, notification]; }); return { dismiss: () => { setNotifications((oldNotifications) => { return oldNotifications.filter( (notificationToFilter) => notificationToFilter.id !== notification.id, ); }); }, replaceContent: ( newContent: React.ReactNode, durationInMs: number | null, ) => { setNotifications((oldNotifications) => { return oldNotifications.map((notificationToMap) => { if (notificationToMap.id === notification.id) { return { ...notificationToMap, duration: durationInMs, content: newContent, created: Date.now(), }; } return notificationToMap; }); }); }, }; }, [], ); useImperativeHandle(notificationCenter, () => { return { addNotification, }; }, [addNotification]); if (notifications.length === 0) { return null; } return ReactDOM.createPortal(
{notifications.map((n) => { return ( {n.content} ); })}
, // Notifications must be above overlays opened from the editor, such as the // floating sidebars used in the mobile layout. dialog ?? getPortal(currentZIndex + 1), ); };