React to theme changes in widget mode

This commit is contained in:
Robin
2024-12-17 19:42:04 -05:00
parent 53fff37d5d
commit 5d8804d7e8
3 changed files with 73 additions and 14 deletions

View File

@@ -15,13 +15,19 @@ import {
test,
vi,
} from "vitest";
import EventEmitter from "events";
import { useTheme } from "./useTheme";
import { useUrlParams } from "./UrlParams";
import { getUrlParams } from "./UrlParams";
import { widget } from "./widget";
import { WidgetApiToWidgetAction } from "matrix-widget-api";
// Mock the useUrlParams hook
vi.mock("./UrlParams", () => ({
useUrlParams: vi.fn(),
vi.mock("./UrlParams", () => ({ getUrlParams: vi.fn() }));
vi.mock("./widget", () => ({
widget: {
api: { transport: { reply: vi.fn() } },
lazyActions: new EventEmitter(),
},
}));
describe("useTheme", () => {
@@ -46,7 +52,7 @@ describe("useTheme", () => {
{ setTheme: "light-high-contrast", add: ["cpd-theme-light-hc"] },
])("apply procedure", ({ setTheme, add }) => {
test(`should apply ${add[0]} theme when ${setTheme} theme is specified`, () => {
(useUrlParams as Mock).mockReturnValue({ theme: setTheme });
(getUrlParams as Mock).mockReturnValue({ theme: setTheme });
renderHook(() => useTheme());
@@ -61,7 +67,7 @@ describe("useTheme", () => {
});
test("should not reapply the same theme if it hasn't changed", () => {
(useUrlParams as Mock).mockReturnValue({ theme: "dark" });
(getUrlParams as Mock).mockReturnValue({ theme: "dark" });
// Simulate a previous theme
originalClassList.item = vi.fn().mockReturnValue("cpd-theme-dark");
@@ -75,4 +81,23 @@ describe("useTheme", () => {
expect(document.body.classList.remove).toHaveBeenCalledWith("no-theme");
expect(originalClassList.add).not.toHaveBeenCalled();
});
test("theme changes in response to widget actions", () => {
renderHook(() => useTheme());
expect(originalClassList.add).toHaveBeenCalledWith("cpd-theme-dark");
widget!.lazyActions.emit(
WidgetApiToWidgetAction.ThemeChange,
new CustomEvent(WidgetApiToWidgetAction.ThemeChange, {
detail: { data: { name: "light" } },
}),
);
expect(originalClassList.remove).toHaveBeenCalledWith(
"cpd-theme-light",
"cpd-theme-dark",
"cpd-theme-light-hc",
"cpd-theme-dark-hc",
);
expect(originalClassList.add).toHaveBeenLastCalledWith("cpd-theme-light");
});
});