From cc1f364c6e57fa637e530516401adc2f29a567c4 Mon Sep 17 00:00:00 2001 From: Marko Stijak Date: Tue, 24 Nov 2026 20:31:56 +0100 Subject: [PATCH] feat(Overlay): allow onBeforeDismiss to return a promise onBeforeDismiss may return a promise, e.g. from MsgBox.yesNo, to ask before an overlay is dismissed. The overlay closes when the promise resolves to anything other than false. While the promise is pending, other attempts to dismiss the overlay, e.g. pressing Escape again, are ignored. If the overlay is closed in another way in the meantime, the result is ignored. onBeforeDismiss is also no longer called again for an overlay that is already closing, e.g. if dismiss is called twice in a row. --- homedocs/src/pages/docs/layout/overlay.mdx | 2 +- homedocs/src/pages/docs/layout/window.mdx | 2 +- packages/cx/src/widgets/overlay/Overlay.tsx | 72 +++++++-- .../widgets/overlay/Window.browser.spec.tsx | 139 ++++++++++++++++++ 4 files changed, 198 insertions(+), 17 deletions(-) diff --git a/homedocs/src/pages/docs/layout/overlay.mdx b/homedocs/src/pages/docs/layout/overlay.mdx index d894c4107..7f4ec2949 100644 --- a/homedocs/src/pages/docs/layout/overlay.mdx +++ b/homedocs/src/pages/docs/layout/overlay.mdx @@ -56,7 +56,7 @@ The `open` method returns a `close` function that can be called to dismiss the o | `closeOnEscape` | `boolean` | Closes the overlay when Escape key is pressed. | | `dismissOnFocusOut` | `boolean` | Dismisses the overlay when it loses focus. | | `dismissOnPopState` | `boolean` | Dismisses the overlay if the user presses the browser back button. | -| `onBeforeDismiss` | `function` | Called with `(instance, component)` before the overlay is dismissed. Return `false` to keep it open. Setting `visible` to `false` closes the overlay without calling it. | +| `onBeforeDismiss` | `function` | Called with `(instance, component)` before the overlay is dismissed. Return `false`, or a promise that resolves to `false`, to keep it open; other attempts to dismiss the overlay are ignored while the promise is pending. Setting `visible` to `false` closes the overlay without calling it. | | `animate` | `boolean` | Appends the `animate` state after initial render for CSS animations. | | `destroyDelay` | `number` | Milliseconds to wait before removing from DOM (use with `animate`). | | `autoFocus` | `boolean` | Automatically focuses the overlay when shown. | diff --git a/homedocs/src/pages/docs/layout/window.mdx b/homedocs/src/pages/docs/layout/window.mdx index 197dacf8a..ebe504691 100644 --- a/homedocs/src/pages/docs/layout/window.mdx +++ b/homedocs/src/pages/docs/layout/window.mdx @@ -82,6 +82,6 @@ The factory returns a Promise that resolves when the window is closed, making it | `resizable` | `boolean` | Enables window resizing. | | `closable` | `boolean` | Controls close button visibility. Defaults to `true`. | | `closeOnEscape` | `boolean` | Closes the window when Escape key is pressed. | -| `onBeforeDismiss` | `function` | Called with `(instance, component)` before the window is dismissed, e.g. with Escape or the close button. Return `false` to keep it open, e.g. to ask whether unsaved changes should be discarded. | +| `onBeforeDismiss` | `function` | Called with `(instance, component)` before the window is dismissed, e.g. with Escape or the close button. Return `false`, or a promise that resolves to `false`, to keep it open, e.g. to ask whether unsaved changes should be discarded with `MsgBox.yesNo`. | | `fixed` | `boolean` | Disables moving the window by dragging the header. | | `pad` | `boolean` | Adds default padding to the window body. | diff --git a/packages/cx/src/widgets/overlay/Overlay.tsx b/packages/cx/src/widgets/overlay/Overlay.tsx index ef03aa3bc..95f1a9978 100644 --- a/packages/cx/src/widgets/overlay/Overlay.tsx +++ b/packages/cx/src/widgets/overlay/Overlay.tsx @@ -17,6 +17,7 @@ import { getActiveElement } from "../../util/getActiveElement"; import { getTopLevelBoundingClientRect } from "../../util/getTopLevelBoundingClientRect"; import { isDataRecord } from "../../util/isDataRecord"; import { isNumber } from "../../util/isNumber"; +import { isPromise } from "../../util/isPromise"; import { KeyCode } from "../../util/KeyCode"; import { parseStyle } from "../../util/parseStyle"; import { SubscriberList } from "../../util/SubscriberList"; @@ -120,9 +121,11 @@ export interface OverlayConfig extends StyledContainerConfig { /** * Callback invoked before the overlay is dismissed, e.g. with Escape, the close button or the function returned - * by `open`. Return `false` to keep the overlay open. Setting `visible` to `false` closes the overlay without it. + * by `open`. Return `false`, or a promise that resolves to `false`, to keep the overlay open. While the promise is + * pending, further attempts to dismiss the overlay are ignored. Setting `visible` to `false` closes the overlay + * without it. */ - onBeforeDismiss?: string | ((instance: Instance, component: any) => boolean | void); + onBeforeDismiss?: string | ((instance: Instance, component: any) => BeforeDismissResult); /** Callback fired when overlay will dismiss. */ overlayWillDismiss?: (instance: Instance, component: any) => boolean; @@ -136,11 +139,23 @@ export interface OverlayOpenOptions { name?: string; dismiss?: () => void; parentEl?: Element; - subscribeToBeforeDismiss?: (callback: () => boolean) => void; + subscribeToBeforeDismiss?: (callback: () => boolean | Promise) => void; destroyDelay?: number; removeParentDOMElement?: boolean; } +export type BeforeDismissResult = boolean | void | Promise; + +/** Runs the check before an overlay is dismissed, which may be asynchronous, and closes the overlay if it allows it. */ +function dismissIfAllowed(check: (() => boolean | Promise) | null | undefined, close: () => void): void { + let allowed = check ? check() : true; + if (isPromise(allowed)) + allowed.then((allowed) => { + if (allowed) close(); + }); + else if (allowed !== false) close(); +} + export interface ConfigureOverlayContainerContext { relatedElement?: HTMLElement | null; initiatingEvent?: React.SyntheticEvent; @@ -149,7 +164,7 @@ export interface ConfigureOverlayContainerContext { export class OverlayInstance = Overlay> extends Instance { declare positionChangeSubscribers: SubscriberList; declare dismiss?: () => void; - onBeforeDismiss?: () => boolean; + onBeforeDismiss?: () => boolean | Promise; declare beaconEl?: HTMLElement | null; } @@ -189,7 +204,7 @@ export class OverlayBase< declare onClick?: string; declare onMouseDown?: string; declare onBackdropClick?: string; - declare onBeforeDismiss?: string | ((instance: Instance, component: any) => boolean | void); + declare onBeforeDismiss?: string | ((instance: Instance, component: any) => BeforeDismissResult); declare overlayWillDismiss?: (instance: Instance, component: any) => boolean; declare style?: any; declare pad?: boolean; @@ -237,8 +252,7 @@ export class OverlayBase< if (isBinding(this.visible)) { if (!instance.dismiss) { instance.dismiss = () => { - if (instance.onBeforeDismiss && instance.onBeforeDismiss() === false) return; - instance.set("visible", false); + dismissIfAllowed(instance.onBeforeDismiss, () => instance.set("visible", false)); }; } } else if (context.options.dismiss) instance.dismiss = context.options.dismiss; @@ -368,7 +382,7 @@ export class OverlayBase< let el = this.containerFactory(undefined, options?.initiatingEvent); el.style.display = "hidden"; - let beforeDismiss: (() => boolean) | null = null; + let beforeDismiss: (() => boolean | Promise) | null = null; let stop: any; options = { @@ -377,11 +391,12 @@ export class OverlayBase< ...options, parentEl: el, dismiss: () => { - if (beforeDismiss && beforeDismiss() === false) return; - stop(); - beforeDismiss = null; + dismissIfAllowed(beforeDismiss, () => { + stop(); + beforeDismiss = null; + }); }, - subscribeToBeforeDismiss: (cb: () => boolean) => { + subscribeToBeforeDismiss: (cb: () => boolean | Promise) => { beforeDismiss = cb; }, }; @@ -507,7 +522,7 @@ class OverlayContent extends VDOM.Component { export interface OverlayComponentProps { instance: OverlayInstance; parentEl?: HTMLElement; - subscribeToBeforeDismiss?: (cb: () => boolean) => void; + subscribeToBeforeDismiss?: (cb: () => boolean | Promise) => void; children: any; beaconEl: HTMLElement | null; } @@ -529,6 +544,7 @@ export class OverlayComponent< declare shadowEl?: HTMLElement | null; declare dismissed?: boolean; declare unmounting?: boolean; + declare dismissPending?: boolean; onPopState?: () => void; unsubscribeWheelBlock?: () => void; declare customStyle: any; @@ -818,11 +834,37 @@ export class OverlayComponent< } } - onBeforeDismiss() { + onBeforeDismiss(): boolean | Promise { + let { instance } = this.props; + let { widget } = instance; + + // while an asynchronous onBeforeDismiss is pending, e.g. a confirmation, or once dismissing is allowed and the + // overlay is about to close, other attempts to dismiss it are ignored + if (this.dismissPending || this.dismissed) return false; + + let allowed = widget.onBeforeDismiss ? instance.invoke("onBeforeDismiss", instance, this) : true; + if (isPromise(allowed)) { + this.dismissPending = true; + return allowed.then( + (allowed) => { + this.dismissPending = false; + // the overlay may have been closed in the meantime + return allowed !== false && !this.unmounting && this.beginDismiss(); + }, + (error) => { + this.dismissPending = false; + throw error; + }, + ); + } + if (allowed === false) return false; + return this.beginDismiss(); + } + + beginDismiss(): boolean { let { instance } = this.props; let { widget } = instance; - if (widget.onBeforeDismiss && instance.invoke("onBeforeDismiss", instance, this) === false) return false; if (widget.overlayWillDismiss && widget.overlayWillDismiss(instance, this) === false) return false; this.dismissed = true; diff --git a/packages/cx/src/widgets/overlay/Window.browser.spec.tsx b/packages/cx/src/widgets/overlay/Window.browser.spec.tsx index 85111fb3a..ba6deaacd 100644 --- a/packages/cx/src/widgets/overlay/Window.browser.spec.tsx +++ b/packages/cx/src/widgets/overlay/Window.browser.spec.tsx @@ -105,6 +105,41 @@ describe("Window onBeforeDismiss", () => { assert.ok(calls[0].widget instanceof Window); }); + it("is called once if the window is dismissed twice before it closes", async () => { + let calls = 0; + let controller: Controller | undefined; + + class WindowController extends Controller { + onInit() { + controller = this; + } + } + + let store = new Store({ data: { visible: true } }); + await render( + + { + calls++; + return true; + }} + > + Content + + , + { store }, + ); + + await settle(() => { + controller!.instance.parentOptions.dismiss(); + controller!.instance.parentOptions.dismiss(); + }); + assert.equal(calls, 1); + assert.equal(store.get(m.visible), false); + }); + it("calls a controller method given by name", async () => { let calls = 0; @@ -150,3 +185,107 @@ describe("Window onBeforeDismiss", () => { await expect.poll(() => document.querySelector(".cxb-window")).toBeNull(); }); }); + +describe("Window onBeforeDismiss with a promise", () => { + const m = createModel(); + + function deferred() { + let resolve!: (value: boolean) => void; + let promise = new Promise((r) => (resolve = r)); + return { promise, resolve }; + } + + function closeButton() { + return document.querySelector(".cxb-window button") as HTMLElement; + } + + async function setup() { + let checks: ReturnType[] = []; + let store = new Store({ data: { visible: true } }); + await render( + + { + let check = deferred(); + checks.push(check); + return check.promise; + }} + > + + + , + { store }, + ); + return { store, checks }; + } + + it("closes the window when the promise resolves to true", async () => { + let { store, checks } = await setup(); + + await settle(() => userEvent.click(closeButton())); + assert.equal(checks.length, 1); + assert.equal(store.get(m.visible), true); + + await settle(() => checks[0].resolve(true)); + assert.equal(store.get(m.visible), false); + }); + + it("keeps the window open when the promise resolves to false", async () => { + let { store, checks } = await setup(); + + await settle(() => userEvent.click(closeButton())); + await settle(() => checks[0].resolve(false)); + assert.equal(store.get(m.visible), true); + + // the window can be dismissed again afterwards + await settle(() => userEvent.click(closeButton())); + assert.equal(checks.length, 2); + await settle(() => checks[1].resolve(true)); + assert.equal(store.get(m.visible), false); + }); + + it("ignores other attempts to dismiss the window while the promise is pending", async () => { + let { store, checks } = await setup(); + + await settle(() => userEvent.click(closeButton())); + document.querySelector(".cxb-window input")!.focus(); + await settle(() => userEvent.keyboard("{Escape}")); + await settle(() => userEvent.click(closeButton())); + assert.equal(checks.length, 1); + + await settle(() => checks[0].resolve(true)); + assert.equal(store.get(m.visible), false); + }); + + it("does nothing when the promise resolves after the window was closed otherwise", async () => { + let { store, checks } = await setup(); + + await settle(() => userEvent.click(closeButton())); + await settle(() => store.set(m.visible, false)); + await expect.poll(() => document.querySelector(".cxb-window")).toBeNull(); + + await settle(() => checks[0].resolve(true)); + assert.equal(store.get(m.visible), false); + }); + + it("is awaited by the dismiss function of a window opened with open", async () => { + let check = deferred(); + let dismiss = Window.create({ + title: "Opened", + onBeforeDismiss: () => check.promise, + items: Content, + }).open(new Store()); + await expect.poll(() => document.querySelector(".cxb-window")).toBeTruthy(); + + dismiss(); + await settle(); + assert.ok(document.querySelector(".cxb-window"), "the window was closed"); + + check.resolve(true); + await expect.poll(() => document.querySelector(".cxb-window")).toBeNull(); + }); +});