close all dialogs on navigate

This commit is contained in:
Petar Petrov 2024-12-11 13:35:09 +02:00
parent 142e674020
commit c713106948
2 changed files with 34 additions and 25 deletions

View File

@ -1,3 +1,4 @@
import { closeAllDialogs } from "../dialogs/make-dialog-manager";
import { fireEvent } from "./dom/fire_event"; import { fireEvent } from "./dom/fire_event";
import { mainWindow } from "./dom/get_main_window"; import { mainWindow } from "./dom/get_main_window";
@ -13,16 +14,24 @@ export interface NavigateOptions {
data?: any; data?: any;
} }
export const navigate = (path: string, options?: NavigateOptions) => { export const navigate = async (path: string, options?: NavigateOptions) => {
const replace = options?.replace || false; const { history } = mainWindow;
let replace = options?.replace || false;
if (history.state?.dialog) {
const closed = await closeAllDialogs();
if (!closed) {
// block navigation if dialogs refuse to close
return;
}
// if there were open dialogs, we discard the current state
replace = true;
}
setTimeout(() => {
if (__DEMO__) { if (__DEMO__) {
if (replace) { if (replace) {
mainWindow.history.replaceState( history.replaceState(
mainWindow.history.state?.root history.state?.root ? { root: true } : (options?.data ?? null),
? { root: true }
: (options?.data ?? null),
"", "",
`${mainWindow.location.pathname}#${path}` `${mainWindow.location.pathname}#${path}`
); );
@ -30,18 +39,15 @@ export const navigate = (path: string, options?: NavigateOptions) => {
mainWindow.location.hash = path; mainWindow.location.hash = path;
} }
} else if (replace) { } else if (replace) {
mainWindow.history.replaceState( history.replaceState(
mainWindow.history.state?.root history.state?.root ? { root: true } : (options?.data ?? null),
? { root: true }
: (options?.data ?? null),
"", "",
path path
); );
} else { } else {
mainWindow.history.pushState(options?.data ?? null, "", path); history.pushState(options?.data ?? null, "", path);
} }
fireEvent(mainWindow, "location-changed", { fireEvent(mainWindow, "location-changed", {
replace, replace,
}); });
});
}; };

View File

@ -174,6 +174,9 @@ export const closeLastDialog = async () => {
} }
}; };
export const closeAllDialogs = () =>
Promise.all(OPEN_DIALOG_STACK.map((state) => closeDialog(state.dialogTag)));
const _handleClosed = async (ev: HASSDomEvent<DialogClosedParams>) => { const _handleClosed = async (ev: HASSDomEvent<DialogClosedParams>) => {
// If not closed by navigating back, remove the open state from history // If not closed by navigating back, remove the open state from history
const dialogIndex = OPEN_DIALOG_STACK.findIndex( const dialogIndex = OPEN_DIALOG_STACK.findIndex(