Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion homedocs/src/pages/docs/layout/overlay.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion homedocs/src/pages/docs/layout/window.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
72 changes: 57 additions & 15 deletions packages/cx/src/widgets/overlay/Overlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand All @@ -136,11 +139,23 @@ export interface OverlayOpenOptions {
name?: string;
dismiss?: () => void;
parentEl?: Element;
subscribeToBeforeDismiss?: (callback: () => boolean) => void;
subscribeToBeforeDismiss?: (callback: () => boolean | Promise<boolean>) => void;
destroyDelay?: number;
removeParentDOMElement?: boolean;
}

export type BeforeDismissResult = boolean | void | Promise<boolean | void>;

/** 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<boolean>) | 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;
Expand All @@ -149,7 +164,7 @@ export interface ConfigureOverlayContainerContext {
export class OverlayInstance<WidgetType extends OverlayBase<any, any> = Overlay> extends Instance<WidgetType> {
declare positionChangeSubscribers: SubscriberList;
declare dismiss?: () => void;
onBeforeDismiss?: () => boolean;
onBeforeDismiss?: () => boolean | Promise<boolean>;
declare beaconEl?: HTMLElement | null;
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<boolean>) | null = null;
let stop: any;

options = {
Expand All @@ -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<boolean>) => {
beforeDismiss = cb;
},
};
Expand Down Expand Up @@ -507,7 +522,7 @@ class OverlayContent extends VDOM.Component<OverlayContentProps, {}> {
export interface OverlayComponentProps {
instance: OverlayInstance;
parentEl?: HTMLElement;
subscribeToBeforeDismiss?: (cb: () => boolean) => void;
subscribeToBeforeDismiss?: (cb: () => boolean | Promise<boolean>) => void;
children: any;
beaconEl: HTMLElement | null;
}
Expand All @@ -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;
Expand Down Expand Up @@ -818,11 +834,37 @@ export class OverlayComponent<
}
}

onBeforeDismiss() {
onBeforeDismiss(): boolean | Promise<boolean> {
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;
Expand Down
139 changes: 139 additions & 0 deletions packages/cx/src/widgets/overlay/Window.browser.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<cx>
<Window
visible={m.visible}
controller={WindowController}
onBeforeDismiss={() => {
calls++;
return true;
}}
>
Content
</Window>
</cx>,
{ 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;

Expand Down Expand Up @@ -150,3 +185,107 @@ describe("Window onBeforeDismiss", () => {
await expect.poll(() => document.querySelector(".cxb-window")).toBeNull();
});
});

describe("Window onBeforeDismiss with a promise", () => {
const m = createModel<Model>();

function deferred() {
let resolve!: (value: boolean) => void;
let promise = new Promise<boolean>((r) => (resolve = r));
return { promise, resolve };
}

function closeButton() {
return document.querySelector(".cxb-window button") as HTMLElement;
}

async function setup() {
let checks: ReturnType<typeof deferred>[] = [];
let store = new Store({ data: { visible: true } });
await render(
<cx>
<Window
visible={m.visible}
title="Edit"
closable
closeOnEscape
onBeforeDismiss={() => {
let check = deferred();
checks.push(check);
return check.promise;
}}
>
<input />
</Window>
</cx>,
{ 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<HTMLInputElement>(".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: <cx>Content</cx>,
}).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();
});
});
Loading