Skip to content

Commit

Permalink
Switch ModalManager to the React 18 createRoot API (#28336)
Browse files Browse the repository at this point in the history
* Remove boilerplate around dispatcher and settings watchers

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Move state update listeners from constructor to componentDidMount

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Switch ModalManager to the React 18 createRoot API

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Iterate

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

---------

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
  • Loading branch information
t3chguy authored Nov 4, 2024
1 parent 38e5eee commit 502cc91
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 60 deletions.
61 changes: 30 additions & 31 deletions src/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ Please see LICENSE files in the repository root for full details.
*/

import React, { StrictMode } from "react";
import ReactDOM from "react-dom";
import { createRoot, Root } from "react-dom/client";
import classNames from "classnames";
import { IDeferred, defer, sleep } from "matrix-js-sdk/src/utils";
import { IDeferred, defer } from "matrix-js-sdk/src/utils";
import { TypedEventEmitter } from "matrix-js-sdk/src/matrix";
import { Glass, TooltipProvider } from "@vector-im/compound-web";

Expand Down Expand Up @@ -69,6 +69,16 @@ type HandlerMap = {

type ModalCloseReason = "backgroundClick";

function getOrCreateContainer(id: string): HTMLDivElement {
let container = document.getElementById(id) as HTMLDivElement | null;
if (!container) {
container = document.createElement("div");
container.id = id;
document.body.appendChild(container);
}
return container;
}

export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMap> {
private counter = 0;
// The modal to prioritise over all others. If this is set, only show
Expand All @@ -83,28 +93,22 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
// Neither the static nor priority modal will be in this list.
private modals: IModal<any>[] = [];

private static getOrCreateContainer(): HTMLElement {
let container = document.getElementById(DIALOG_CONTAINER_ID);

if (!container) {
container = document.createElement("div");
container.id = DIALOG_CONTAINER_ID;
document.body.appendChild(container);
private static root?: Root;
private static getOrCreateRoot(): Root {
if (!ModalManager.root) {
const container = getOrCreateContainer(DIALOG_CONTAINER_ID);
ModalManager.root = createRoot(container);
}

return container;
return ModalManager.root;
}

private static getOrCreateStaticContainer(): HTMLElement {
let container = document.getElementById(STATIC_DIALOG_CONTAINER_ID);

if (!container) {
container = document.createElement("div");
container.id = STATIC_DIALOG_CONTAINER_ID;
document.body.appendChild(container);
private static staticRoot?: Root;
private static getOrCreateStaticRoot(): Root {
if (!ModalManager.staticRoot) {
const container = getOrCreateContainer(STATIC_DIALOG_CONTAINER_ID);
ModalManager.staticRoot = createRoot(container);
}

return container;
return ModalManager.staticRoot;
}

public constructor() {
Expand Down Expand Up @@ -389,19 +393,14 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
}

private async reRender(): Promise<void> {
// TODO: We should figure out how to remove this weird sleep. It also makes testing harder
//
// await next tick because sometimes ReactDOM can race with itself and cause the modal to wrongly stick around
await sleep(0);

if (this.modals.length === 0 && !this.priorityModal && !this.staticModal) {
// If there is no modal to render, make all of Element available
// to screen reader users again
dis.dispatch({
action: "aria_unhide_main_app",
});
ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateContainer());
ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateStaticContainer());
ModalManager.getOrCreateRoot().render(<></>);
ModalManager.getOrCreateStaticRoot().render(<></>);
return;
}

Expand Down Expand Up @@ -432,10 +431,10 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
</StrictMode>
);

ReactDOM.render(staticDialog, ModalManager.getOrCreateStaticContainer());
ModalManager.getOrCreateStaticRoot().render(staticDialog);
} else {
// This is safe to call repeatedly if we happen to do that
ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateStaticContainer());
ModalManager.getOrCreateStaticRoot().render(<></>);
}

const modal = this.getCurrentModal();
Expand All @@ -461,10 +460,10 @@ export class ModalManager extends TypedEventEmitter<ModalManagerEvent, HandlerMa
</StrictMode>
);

setTimeout(() => ReactDOM.render(dialog, ModalManager.getOrCreateContainer()), 0);
ModalManager.getOrCreateRoot().render(dialog);
} else {
// This is safe to call repeatedly if we happen to do that
ReactDOM.unmountComponentAtNode(ModalManager.getOrCreateContainer());
ModalManager.getOrCreateRoot().render(<></>);
}
}
}
Expand Down
6 changes: 5 additions & 1 deletion test/unit-tests/components/structures/MatrixChat-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import { DRAFT_LAST_CLEANUP_KEY } from "../../../../src/DraftCleaner";
import { UIFeature } from "../../../../src/settings/UIFeature";
import AutoDiscoveryUtils from "../../../../src/utils/AutoDiscoveryUtils";
import { ValidatedServerConfig } from "../../../../src/utils/ValidatedServerConfig";
import Modal from "../../../../src/Modal.tsx";

jest.mock("matrix-js-sdk/src/oidc/authorize", () => ({
completeAuthorizationCodeGrant: jest.fn(),
Expand Down Expand Up @@ -1514,7 +1515,9 @@ describe("<MatrixChat />", () => {

describe("when key backup failed", () => {
it("should show the new recovery method dialog", async () => {
const spy = jest.spyOn(Modal, "createDialogAsync");
jest.mock("../../../../src/async-components/views/dialogs/security/NewRecoveryMethodDialog", () => ({
__test: true,
__esModule: true,
default: () => <span>mocked dialog</span>,
}));
Expand All @@ -1526,7 +1529,8 @@ describe("<MatrixChat />", () => {
});
await flushPromises();
mockClient.emit(CryptoEvent.KeyBackupFailed, "error code");
await waitFor(() => expect(screen.getByText("mocked dialog")).toBeInTheDocument());
await waitFor(() => expect(spy).toHaveBeenCalledTimes(1));
expect(await spy.mock.lastCall![0]).toEqual(expect.objectContaining({ __test: true }));
});
});
});
36 changes: 18 additions & 18 deletions test/unit-tests/components/structures/auth/ForgotPassword-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.

import React from "react";
import { mocked } from "jest-mock";
import { act, render, RenderResult, screen } from "jest-matrix-react";
import { act, render, RenderResult, screen, waitFor } from "jest-matrix-react";
import userEvent from "@testing-library/user-event";
import { MatrixClient, createClient } from "matrix-js-sdk/src/matrix";

Expand Down Expand Up @@ -47,14 +47,12 @@ describe("<ForgotPassword>", () => {
};

const click = async (element: Element): Promise<void> => {
await act(async () => {
await userEvent.click(element, { delay: null });
});
await userEvent.click(element, { delay: null });
};

const itShouldCloseTheDialogAndShowThePasswordInput = (): void => {
it("should close the dialog and show the password input", () => {
expect(screen.queryByText("Verify your email to continue")).not.toBeInTheDocument();
it("should close the dialog and show the password input", async () => {
await waitFor(() => expect(screen.queryByText("Verify your email to continue")).not.toBeInTheDocument());
expect(screen.getByText("Reset your password")).toBeInTheDocument();
});
};
Expand Down Expand Up @@ -314,7 +312,7 @@ describe("<ForgotPassword>", () => {
});
});

it("should send the new password and show the click validation link dialog", () => {
it("should send the new password and show the click validation link dialog", async () => {
expect(client.setPassword).toHaveBeenCalledWith(
{
type: "m.login.email.identity",
Expand All @@ -326,15 +324,15 @@ describe("<ForgotPassword>", () => {
testPassword,
false,
);
expect(screen.getByText("Verify your email to continue")).toBeInTheDocument();
await expect(
screen.findByText("Verify your email to continue"),
).resolves.toBeInTheDocument();
expect(screen.getByText(testEmail)).toBeInTheDocument();
});

describe("and dismissing the dialog by clicking the background", () => {
beforeEach(async () => {
await act(async () => {
await userEvent.click(screen.getByTestId("dialog-background"), { delay: null });
});
await userEvent.click(await screen.findByTestId("dialog-background"), { delay: null });
await waitEnoughCyclesForModal({
useFakeTimers: true,
});
Expand All @@ -345,7 +343,7 @@ describe("<ForgotPassword>", () => {

describe("and dismissing the dialog", () => {
beforeEach(async () => {
await click(screen.getByLabelText("Close dialog"));
await click(await screen.findByLabelText("Close dialog"));
await waitEnoughCyclesForModal({
useFakeTimers: true,
});
Expand All @@ -356,14 +354,16 @@ describe("<ForgotPassword>", () => {

describe("and clicking »Re-enter email address«", () => {
beforeEach(async () => {
await click(screen.getByText("Re-enter email address"));
await click(await screen.findByText("Re-enter email address"));
await waitEnoughCyclesForModal({
useFakeTimers: true,
});
});

it("should close the dialog and go back to the email input", () => {
expect(screen.queryByText("Verify your email to continue")).not.toBeInTheDocument();
it("should close the dialog and go back to the email input", async () => {
await waitFor(() =>
expect(screen.queryByText("Verify your email to continue")).not.toBeInTheDocument(),
);
expect(screen.queryByText("Enter your email to reset password")).toBeInTheDocument();
});
});
Expand Down Expand Up @@ -397,11 +397,11 @@ describe("<ForgotPassword>", () => {
});

it("should show the sign out warning dialog", async () => {
expect(
screen.getByText(
await expect(
screen.findByText(
"Signing out your devices will delete the message encryption keys stored on them, making encrypted chat history unreadable.",
),
).toBeInTheDocument();
).resolves.toBeInTheDocument();

// confirm dialog
await click(screen.getByText("Continue"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.

import { Feature, ServerSupport } from "matrix-js-sdk/src/feature";
import { MatrixClient, MatrixEvent, RelationType } from "matrix-js-sdk/src/matrix";
import { screen } from "jest-matrix-react";
import { screen, act } from "jest-matrix-react";
import userEvent from "@testing-library/user-event";

import { flushPromises, mkEvent, stubClient } from "../../../../test-utils";
Expand All @@ -31,12 +31,12 @@ describe("ConfirmRedactDialog", () => {
};

const confirmDeleteVoiceBroadcastStartedEvent = async () => {
createRedactEventDialog({ mxEvent });
act(() => createRedactEventDialog({ mxEvent }));
// double-flush promises required for the dialog to show up
await flushPromises();
await flushPromises();

await userEvent.click(screen.getByTestId("dialog-primary-button"));
await userEvent.click(await screen.findByTestId("dialog-primary-button"));
};

beforeEach(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.

import React from "react";
import { mocked } from "jest-mock";
import { fireEvent, render, screen } from "jest-matrix-react";
import { fireEvent, render, screen, waitFor } from "jest-matrix-react";
import { TimestampToEventResponse, ConnectionError, HTTPError, MatrixError } from "matrix-js-sdk/src/matrix";

import dispatcher from "../../../../../src/dispatcher/dispatcher";
Expand Down Expand Up @@ -291,7 +291,9 @@ describe("DateSeparator", () => {
// The submit debug logs option should *NOT* be shown for network errors.
//
// We have to use `queryBy` so that it can return `null` for something that does not exist.
expect(screen.queryByTestId("jump-to-date-error-submit-debug-logs-button")).not.toBeInTheDocument();
await waitFor(() =>
expect(screen.queryByTestId("jump-to-date-error-submit-debug-logs-button")).not.toBeInTheDocument(),
);
});
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ describe("message", () => {
expect(mockClient.sendMessage).toHaveBeenCalledTimes(0);
expect(mockClient.cancelPendingEvent).toHaveBeenCalledTimes(1);
expect(mockCreateRedactEventDialog).toHaveBeenCalledTimes(1);
expect(spyDispatcher).toHaveBeenCalledTimes(0);
expect(spyDispatcher).toHaveBeenCalledTimes(1);
});

it("Should do nothing if the content is unmodified", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ describe("<JoinRuleSettings />", () => {

await flushPromises();

expect(within(dialog).getByText("Loading new room")).toBeInTheDocument();
await expect(within(dialog).findByText("Loading new room")).resolves.toBeInTheDocument();

// "create" our new room, have it come thru sync
client.getRoom.mockImplementation((id) => {
Expand Down Expand Up @@ -250,7 +250,7 @@ describe("<JoinRuleSettings />", () => {

await flushPromises();

expect(within(dialog).getByText("Loading new room")).toBeInTheDocument();
await expect(within(dialog).findByText("Loading new room")).resolves.toBeInTheDocument();

// "create" our new room, have it come thru sync
client.getRoom.mockImplementation((id) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ describe("<SessionManagerTab />", () => {
const mockVerificationRequest = {
cancel: jest.fn(),
on: jest.fn(),
off: jest.fn(),
} as unknown as VerificationRequest;

const mockCrypto = mocked({
Expand Down
4 changes: 2 additions & 2 deletions test/unit-tests/utils/media/requestMediaPermissions-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ describe("requestMediaPermissions", () => {
const audioStream = {} as MediaStream;

const itShouldLogTheErrorAndShowTheNoMediaPermissionsModal = () => {
it("should log the error and show the »No media permissions« modal", () => {
it("should log the error and show the »No media permissions« modal", async () => {
expect(logger.log).toHaveBeenCalledWith("Failed to list userMedia devices", error);
screen.getByText("No media permissions");
await screen.findByText("No media permissions");
});
};

Expand Down

0 comments on commit 502cc91

Please sign in to comment.