wix-style-react
Version:
wix-style-react
62 lines • 2.02 kB
JavaScript
import { useEffect, useRef, useReducer } from 'react';
import { eventManager } from '../core';
export function useToastContainer(props) {
const [, forceUpdate] = useReducer(x => x + 1, 0);
const containerRef = useRef(null);
const toastToRender = useRef(new Map()).current;
const instance = useRef({
toastKey: 1,
props,
}).current;
useEffect(() => {
eventManager
.cancelEmit(3 /* Event.WillUnmount */)
.on(0 /* Event.Show */, buildToast)
.on(1 /* Event.Clear */, toastId => containerRef.current && removeToast(toastId))
.emit(2 /* Event.DidMount */, instance);
return () => {
toastToRender.clear();
eventManager.emit(3 /* Event.WillUnmount */, instance);
};
// TODO: fix ESLint error
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
instance.props = props;
});
const removeToast = (toastId) => {
if (toastId !== undefined && toastToRender.has(toastId)) {
toastToRender.delete(toastId);
forceUpdate();
}
};
const buildToast = (content, options) => {
const toastProps = {
...options,
key: instance.toastKey++,
onClose: event => {
event?.preventDefault();
event?.stopPropagation();
removeToast(options.toastId);
options.onClose?.(event);
},
};
appendToast(content, toastProps);
};
const appendToast = (content, toastProps) => {
if (!containerRef.current)
return;
const { toastId } = toastProps;
const toast = {
content,
props: toastProps,
};
toastToRender.set(toastId, toast);
forceUpdate();
};
return {
toasts: Array.from(toastToRender.values()),
containerRef,
};
}
//# sourceMappingURL=useToastContainer.js.map