Fix history management failing when updating URL

This commit is contained in:
Nicolas Mowen 2025-11-26 07:03:17 -07:00
parent de2144f158
commit a5ba3f8e3e

View File

@ -17,6 +17,7 @@ export function useHistoryBack({
}: UseHistoryBackOptions): void { }: UseHistoryBackOptions): void {
const historyPushedRef = React.useRef(false); const historyPushedRef = React.useRef(false);
const closedByBackRef = React.useRef(false); const closedByBackRef = React.useRef(false);
const urlWhenOpenedRef = React.useRef<string | null>(null);
// Keep onClose in a ref to avoid effect re-runs that cause multiple history pushes // Keep onClose in a ref to avoid effect re-runs that cause multiple history pushes
const onCloseRef = React.useRef(onClose); const onCloseRef = React.useRef(onClose);
@ -30,6 +31,9 @@ export function useHistoryBack({
if (open) { if (open) {
// Only push history state if we haven't already (prevents duplicates in strict mode) // Only push history state if we haven't already (prevents duplicates in strict mode)
if (!historyPushedRef.current) { if (!historyPushedRef.current) {
// Store the current URL (pathname + search, without hash) before pushing history state
urlWhenOpenedRef.current =
window.location.pathname + window.location.search;
window.history.pushState({ overlayOpen: true }, ""); window.history.pushState({ overlayOpen: true }, "");
historyPushedRef.current = true; historyPushedRef.current = true;
} }
@ -37,6 +41,7 @@ export function useHistoryBack({
const handlePopState = () => { const handlePopState = () => {
closedByBackRef.current = true; closedByBackRef.current = true;
historyPushedRef.current = false; historyPushedRef.current = false;
urlWhenOpenedRef.current = null;
onCloseRef.current(); onCloseRef.current();
}; };
@ -48,10 +53,22 @@ export function useHistoryBack({
} else { } else {
// Overlay is closing - clean up history if we pushed and it wasn't via back button // Overlay is closing - clean up history if we pushed and it wasn't via back button
if (historyPushedRef.current && !closedByBackRef.current) { if (historyPushedRef.current && !closedByBackRef.current) {
window.history.back(); const currentUrl = window.location.pathname + window.location.search;
const urlWhenOpened = urlWhenOpenedRef.current;
// If the URL has changed (e.g., filters were applied via search params),
// don't go back as it would undo the filter update.
// The history entry we pushed will remain, but that's acceptable compared
// to losing the user's filter changes.
if (!urlWhenOpened || currentUrl === urlWhenOpened) {
// URL hasn't changed, safe to go back and remove our history entry
window.history.back();
}
// If URL changed, we skip history.back() to preserve the filter updates
} }
historyPushedRef.current = false; historyPushedRef.current = false;
closedByBackRef.current = false; closedByBackRef.current = false;
urlWhenOpenedRef.current = null;
} }
}, [enabled, open]); }, [enabled, open]);
} }