Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions frontend/app/context/ToastContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,34 @@ const ToastContext =
const MAX_TOASTS = 4;
const TOAST_DURATION = 4000;

type ToastContextSnapshot = {
activeToastCount: number;
latestToastId: number;
generatedAt: number;
};

function buildToastContextSnapshot(
toasts: Toast[],
latestToastId: number
): ToastContextSnapshot {
return {
activeToastCount: toasts.length,
latestToastId,
generatedAt: Date.now(),
};
}

function validateToastContext(
snapshot: ToastContextSnapshot
) {
return {
isValid:
snapshot.activeToastCount >= 0,
checkedAt: Date.now(),
};
}


export function useToast() {
return useContext(ToastContext);
}
Expand All @@ -47,6 +75,13 @@ export function ToastProvider({

const toastIdRef = useRef(0);

const [contextSnapshot, setContextSnapshot] =
useState<ToastContextSnapshot>({
activeToastCount: 0,
latestToastId: 0,
generatedAt: Date.now(),
});

const toastTimersRef =
useRef<
Map<number, NodeJS.Timeout>
Expand Down Expand Up @@ -223,6 +258,23 @@ export function ToastProvider({
]
);

useEffect(() => {
const snapshot =
buildToastContextSnapshot(
toasts,
toastIdRef.current
);

const validation =
validateToastContext(
snapshot
);

if (validation.isValid) {
setContextSnapshot(snapshot);
}
}, [toasts]);

useEffect(() => {
return () => {
toastTimersRef.current.forEach(
Expand All @@ -238,6 +290,11 @@ export function ToastProvider({
<ToastContext.Provider
value={{ showToast }}
>
<div className="hidden">
{contextSnapshot.activeToastCount}
{contextSnapshot.latestToastId}
</div>

{children}

<div className="fixed top-4 right-4 z-50 flex flex-col gap-3 pointer-events-none">
Expand Down
Loading