Skip to content

Build your personal knowledge base with Trilium Notes

15.5 KB
Raw Blame
import { createContext, render } from "preact";
import { useContext, useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const mocks = vi.hoisted(() => {
    // What a dialog did on its way up, in the order it did it (see "suspends the focus-traps ...").
    const raising: string[] = [];

    return {
        raising,
        openDialog: vi.fn(async (dialog: JQuery<HTMLElement>) => {
            raising.push("openDialog");
            return dialog;
        }),
        hide: vi.fn(),
        suspendModalFocusTraps: vi.fn(() => {
            raising.push("suspendModalFocusTraps");
            return () => {};
        })
    };
});

vi.mock("../../services/dialog", () => ({
    openDialog: mocks.openDialog
}));

// Only what is reached while a dialog is raised: its own instance, and the tooltip class the
// shared hooks patch as they load (see hooks.tsx).
vi.mock("bootstrap", () => ({
    Modal: { getOrCreateInstance: () => ({ hide: mocks.hide }) },
    Tooltip: class {
        static getInstance() { return null; }
        dispose() {}
    },
    Dropdown: class {}
}));

vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));

vi.mock("../../components/app_context", () => ({
    default: { triggerCommand: vi.fn() }
}));

vi.mock("./modal_focustrap", () => ({
    suspendModalFocusTraps: mocks.suspendModalFocusTraps
}));

import { handleSystemBack } from "../../services/system_back";
import Modal, { ScriptModal } from "./Modal";

let container: HTMLDivElement;

beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
    mocks.openDialog.mockClear();
    mocks.hide.mockClear();
    mocks.suspendModalFocusTraps.mockClear();
    mocks.raising.length = 0;
});

afterEach(() => {
    act(() => render(null, container));
    container.remove();
});

/**
 * A dialog holding something that changes, so that a test can make it render again without
 * touching the dialog's own props — a keystroke into what it holds, as far as the dialog knows.
 */
function DialogWithTypedInto({ show, onHidden }: { show: boolean; onHidden(): void }) {
    const [ typed, setTyped ] = useState("");

    return (
        <Modal className="test-dialog" size="md" show={show} onHidden={onHidden}>
            {/* Named, the dialog bringing a close button of its own that stands before it. */}
            <button className="typed-into" onClick={() => setTyped(`${typed}x`)}>{typed}</button>
        </Modal>
    );
}

describe("Modal", () => {
    it("mounts a script modal above a contained render note while preserving context and cleanup", async () => {
        const Context = createContext("missing");
        const onClick = vi.fn();

        function Content() {
            return <button onClick={onClick}>{useContext(Context)}</button>;
        }

        container.classList.add("note-detail-render-content");
        container.dataset.ntxId = "source-pane";
        container.style.contain = "size";
        container.style.overflow = "auto";
        await act(async () => {
            render(<Context.Provider value="from render note">
                <ScriptModal className="script-dialog" size="md" show onHidden={() => {}}>
                    <Content />
                </ScriptModal>
            </Context.Provider>, container);
        });

        const dialog = document.querySelector<HTMLElement>(".script-dialog");
        expect(dialog?.parentElement?.parentElement).toBe(document.body);
        expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(true);
        expect(container.contains(dialog)).toBe(false);
        expect(mocks.openDialog).toHaveBeenCalledWith(expect.anything(), true, { focus: true }, undefined);

        const button = dialog?.querySelector<HTMLButtonElement>(".modal-body button");
        expect(button?.textContent).toBe("from render note");
        expect(button?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("source-pane");
        await act(async () => button?.click());
        expect(onClick).toHaveBeenCalledOnce();

        await act(async () => render(null, container));
        expect(document.querySelector(".script-dialog")).toBeNull();
        expect(mocks.hide).toHaveBeenCalled();
    });

    it("keeps a script modal's pane without applying render-note styles outside a render note", async () => {
        container.dataset.ntxId = "script-pane";

        await act(async () => {
            render(<ScriptModal className="script-dialog" size="md" show onHidden={() => {}}>body</ScriptModal>, container);
        });

        const dialog = document.querySelector<HTMLElement>(".script-dialog");
        expect(dialog?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("script-pane");
        expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(false);
    });

    it("carries the render-note scope and pane into a nested script modal", async () => {
        container.classList.add("note-detail-render-content");
        container.dataset.ntxId = "nested-source-pane";

        await act(async () => {
            render(<ScriptModal className="outer-script" size="md" show onHidden={() => {}}>
                <ScriptModal className="inner-script" size="sm" show stackable onHidden={() => {}}>nested</ScriptModal>
            </ScriptModal>, container);
        });

        for (const className of [ "outer-script", "inner-script" ]) {
            const dialog = document.querySelector<HTMLElement>(`.${className}`);
            expect(dialog?.parentElement?.classList.contains("render-note-scope")).toBe(true);
            expect(dialog?.closest("[data-ntx-id]")?.getAttribute("data-ntx-id")).toBe("nested-source-pane");
        }
    });

    /**
     * The bug this pins: `modalRef.current` stood among the effect's dependencies, and a ref holds
     * nothing while the render that names them runs and the element by the time the effect does —
     * so the first re-render after mounting read as a change and opened the dialog a second time.
     * Opening closes whichever dialog is active, which by then is this one, and the dialog put
     * itself away on the first keystroke typed into it (the calendar's ghost, where it was found).
     */
    it("opens once, however often what it holds is typed into", async () => {
        const onHidden = vi.fn();

        await act(async () => {
            render(<DialogWithTypedInto show onHidden={onHidden} />, container);
        });
        expect(mocks.openDialog).toHaveBeenCalledTimes(1);

        // Twice over: the first re-render is the one the ref's settling used to spoil, and a second
        // says the dependencies have come to rest rather than merely changed the once.
        for (let press = 0; press < 2; press++) {
            await act(async () => {
                container.querySelector("button.typed-into")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
            });
            // The press must actually have re-rendered the dialog, or the test proves nothing.
            expect(container.querySelector("button.typed-into")?.textContent).toBe("x".repeat(press + 1));
            expect(mocks.openDialog).toHaveBeenCalledTimes(1);
        }

        expect(mocks.hide).not.toHaveBeenCalled();
    });

    /**
     * A dialog taken out of the tree while still up leaves Bootstrap's backdrop on the body, there
     * being nothing left to take it away — a dimmed page that cannot be pressed. The calendar's
     * ghost goes exactly that way once its event is made.
     */
    it("puts itself down when it is taken out of the tree while still up", async () => {
        await act(async () => {
            render(<DialogWithTypedInto show onHidden={() => {}} />, container);
        });
        expect(mocks.hide).not.toHaveBeenCalled();

        await act(async () => { render(null, container); });
        expect(mocks.hide).toHaveBeenCalled();
    });

    /**
     * Bootstrap marks a raised dialog with `show`, and Preact writes `className` in full whenever
     * the prop changes — so a host that says something about its note in the class took its own
     * dialog off the screen. Picking a colour in the geo map's marker sheet did exactly that: the
     * note's colour class arrived, `show` left with the old attribute, and what remained was a
     * backdrop over an empty page.
     */
    it("keeps the classes Bootstrap wrote when the host's own change", async () => {
        await act(async () => {
            render(<Modal className="test-dialog" size="md" show onHidden={() => {}}>body</Modal>, container);
        });

        const dialog = container.querySelector<HTMLElement>(".test-dialog");
        expect(dialog).toBeTruthy();
        // What Bootstrap puts there once it has raised the dialog, it being mocked out here.
        dialog?.classList.add("show");

        await act(async () => {
            render(<Modal className="test-dialog with-hue" size="md" show onHidden={() => {}}>body</Modal>, container);
        });
        expect(dialog?.classList.contains("show")).toBe(true);
        expect(dialog?.classList.contains("with-hue")).toBe(true);
        expect(dialog?.classList.contains("modal")).toBe(true);

        // A class the host has stopped asking for goes, so this is not merely never writing again.
        await act(async () => {
            render(<Modal className="test-dialog" size="md" show onHidden={() => {}}>body</Modal>, container);
        });
        expect(dialog?.classList.contains("with-hue")).toBe(false);
        expect(dialog?.classList.contains("test-dialog")).toBe(true);
        expect(dialog?.classList.contains("show")).toBe(true);
    });

    it("renders without a class of the host's own", async () => {
        await act(async () => {
            render(<Modal size="md" show onHidden={() => {}}>body</Modal>, container);
        });

        expect(container.querySelector(".modal")?.getAttribute("class")).toBe("modal fade mx-auto");
    });

    /**
     * `openDialog` moves focus onto the new backdrop synchronously, and a focus-trap still active on
     * the dialog underneath pulls it straight back in. Over the Options dialog that lands in the
     * settings search field, whose focus handler shows the search results in place of the page being
     * configured — unmounting the dialog just opened and leaving its portaled markup on screen with
     * nothing behind it. Every card in the "Add AI provider" wizard answered a click with nothing.
     */
    it("suspends the underlying focus-traps before opening", async () => {
        await act(async () => {
            render(<DialogWithTypedInto show onHidden={() => {}} />, container);
        });

        expect(mocks.raising).toEqual([ "suspendModalFocusTraps", "openDialog" ]);
    });

    it("marks a dialog taller than half the screen", async () => {
        let onResize = () => {};
        vi.stubGlobal("ResizeObserver", class {
            constructor(callback: () => void) { onResize = callback; }
            observe() {}
            disconnect() {}
        });
        vi.stubGlobal("innerHeight", 800);

        await act(async () => {
            render(<Modal size="md" show onHidden={() => {}}>body</Modal>, container);
        });
        const dialog = container.querySelector<HTMLElement>(".modal-dialog");
        expect(dialog).not.toBeNull();
        let height = 500;
        Object.defineProperty(dialog, "offsetHeight", { get: () => height });

        act(() => onResize());
        expect(dialog?.classList).toContain("modal-dialog-tall");

        // Going tall widens the dialog, which can rewrap it a little shorter.
        height = 380;
        act(() => onResize());
        expect(dialog?.classList).toContain("modal-dialog-tall");

        height = 300;
        act(() => onResize());
        expect(dialog?.classList).not.toContain("modal-dialog-tall");

        // The screen can change height without the dialog changing size.
        height = 380;
        act(() => onResize());
        expect(dialog?.classList).not.toContain("modal-dialog-tall");
        vi.stubGlobal("innerHeight", 700);
        act(() => { window.dispatchEvent(new Event("resize")); });
        expect(dialog?.classList).toContain("modal-dialog-tall");
        vi.unstubAllGlobals();
    });

    it("closes on the system back while it is shown", async () => {
        await act(async () => {
            render(<Modal size="md" show onHidden={() => {}}>body</Modal>, container);
        });
        expect(handleSystemBack()).toBe(true);
        expect(mocks.hide).toHaveBeenCalledOnce();

        await act(async () => {
            render(<Modal size="md" show={false} onHidden={() => {}}>body</Modal>, container);
        });
        mocks.hide.mockClear();
        expect(handleSystemBack()).toBe(false);
        expect(mocks.hide).not.toHaveBeenCalled();
    });

    it("opens a dialog that starts closed only once it is asked to show", async () => {
        const onHidden = vi.fn();

        await act(async () => {
            render(<DialogWithTypedInto show={false} onHidden={onHidden} />, container);
        });
        expect(mocks.openDialog).not.toHaveBeenCalled();

        await act(async () => {
            render(<DialogWithTypedInto show onHidden={onHidden} />, container);
        });
        expect(mocks.openDialog).toHaveBeenCalledTimes(1);
    });
});

/**
 * Bootstrap's modal events are native events, so they bubble, and a modal opened from inside another
 * one is a DOM descendant of it. The listeners must therefore answer only for their own element.
 */
describe("Modal stacking", () => {
    it("does not report a nested modal's closing as its own", () => {
        const { outer, inner, onOuterHidden, onInnerHidden } = renderNested();

        fire(inner, "hidden.bs.modal");

        expect(onInnerHidden).toHaveBeenCalledOnce();
        expect(onOuterHidden).not.toHaveBeenCalled();

        fire(outer, "hidden.bs.modal");
        expect(onOuterHidden).toHaveBeenCalledOnce();
    });

    it("does not report a nested modal's opening as its own", () => {
        const { inner, onOuterShown, onInnerShown } = renderNested();

        fire(inner, "shown.bs.modal");

        expect(onInnerShown).toHaveBeenCalledOnce();
        expect(onOuterShown).not.toHaveBeenCalled();
    });
});

function renderNested() {
    const onOuterHidden = vi.fn();
    const onInnerHidden = vi.fn();
    const onOuterShown = vi.fn();
    const onInnerShown = vi.fn();

    // Kept in the DOM while hidden, so the pair is nested without Bootstrap having to run.
    act(() => render(
        <Modal
            className="outer-modal"
            size="lg"
            title="Outer"
            show={false}
            keepInDom
            onHidden={onOuterHidden}
            onShown={onOuterShown}
        >
            <Modal
                className="inner-modal"
                size="sm"
                title="Inner"
                show={false}
                keepInDom
                stackable
                onHidden={onInnerHidden}
                onShown={onInnerShown}
            >
                inner body
            </Modal>
        </Modal>,
        container
    ));

    const outer = container.querySelector<HTMLElement>(".outer-modal");
    const inner = container.querySelector<HTMLElement>(".inner-modal");
    if (!outer || !inner) {
        throw new Error("both modals should be in the DOM");
    }
    expect(outer.contains(inner)).toBe(true);

    return { outer, inner, onOuterHidden, onInnerHidden, onOuterShown, onInnerShown };
}

function fire(element: HTMLElement, type: string) {
    act(() => {
        element.dispatchEvent(new CustomEvent(type, { bubbles: true }));
    });
}