Skip to content

Build your personal knowledge base with Trilium Notes

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

import Component from "../../components/component";
import { ParentComponent } from "../react/react_utils";

// i18next is never initialized here, so `t()` returns undefined and a row whose label is only a
// translated string renders without the `<label for>` the tests below look rows up by.
vi.mock("../../services/i18n", async (importOriginal) => ({
    ...(await importOriginal<typeof import("../../services/i18n")>()),
    t: (key: string) => key
}));

// The form fetches the names a definition can complete against and the notes already carrying the
// attribute. Neither is what these tests are about, and an unanswered request rejects into the run.
vi.mock("../../services/server", () => ({
    default: {
        get: vi.fn(async () => []),
        post: vi.fn(async () => ({ results: [], count: 0 }))
    }
}));

import type { AttributeDetailOpts } from "./attribute_detail";

const VIEWPORT = { width: 1200, height: 800 };

// Every popup these tests render counts the notes already carrying the attribute, and reads the
// active context to name their paths. The app is never started here, so it is given one with
// nothing hoisted rather than left to reject into the run. Mocked rather than assigned: the tests
// below reset the module registry, which would hand the popup a fresh, unstarted context.
vi.mock("../../components/app_context", async (importOriginal) => {
    const actual = await importOriginal<typeof import("../../components/app_context")>();
    (actual.default as { tabManager?: unknown }).tabManager =
        { getActiveContext: () => undefined };
    return actual;
});

describe("attribute detail popup positioning", () => {
    beforeEach(() => {
        sizeViewport(VIEWPORT.width, VIEWPORT.height);
    });

    afterEach(() => {
        document.body.replaceChildren();
    });

    it("leaves a popup that has not been laid out where it is", async () => {
        const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
        const popup = sized(document.createElement("div"), 0, 0);

        (await import("./attribute_detail")).positionPopup(popup, opts({ x: 100 }));

        expect(popup.style.left).toBe("");
        expect(warn).toHaveBeenCalledWith(expect.stringContaining("position popup"));
        warn.mockRestore();
    });

    it("puts an anchored popup on whichever side of its anchor has the room for it", async () => {
        const { positionPopup } = await import("./attribute_detail");
        const popup = sized(document.createElement("div"), 300, 400);

        // Room to the left of the anchor: 300 wide plus the gap and the margin fit before it.
        positionPopup(popup, opts({ anchor: anchoredAt({ left: 900, right: 1100, top: 120 }) }));
        expect(popup.style.left).toBe("592px"); // 900 - 300 - 8
        expect(popup.style.top).toBe("120px");
        expect(popup.style.right).toBe("");
        expect(popup.style.maxHeight).toBe("780px"); // the viewport less a margin above and below

        // No room to the left, so it takes the right — and slides up to stay wholly on screen.
        positionPopup(popup, opts({ anchor: anchoredAt({ left: 40, right: 200, top: 700 }) }));
        expect(popup.style.left).toBe("208px"); // 200 + 8
        expect(popup.style.top).toBe("390px"); // 800 - 400 - 10

        // Narrower than the popup on either side: it keeps to the viewport's left margin.
        sizeViewport(305, VIEWPORT.height);
        positionPopup(popup, opts({ anchor: anchoredAt({ left: 10, right: 300, top: 40 }) }));
        expect(popup.style.left).toBe("10px");
    });

    it("sits above the attributes pane, and above the status bar without one", async () => {
        const { positionPopup } = await import("./attribute_detail");
        const popup = sized(document.createElement("div"), 300, 200);
        sizeBody(VIEWPORT.height);

        const pane = document.createElement("div");
        pane.className = "bottom-panel attribute-list";
        pane.getBoundingClientRect = (() => ({ top: 600 })) as Element["getBoundingClientRect"];
        document.body.append(pane);

        positionPopup(popup, opts({ x: 500 }));
        expect(popup.style.top).toBe("unset");
        expect(popup.style.bottom).toBe("200px"); // the body's height down to the pane
        expect(popup.style.maxHeight).toBe("600px");
        expect(popup.style.left).toBe("350px"); // centred on the press

        // With the pane away, the status bar is what the popup docks to instead.
        pane.classList.add("hidden-ext");
        const statusBar = sized(document.createElement("div"), 1200, 40);
        statusBar.className = "component status-bar";
        document.body.append(statusBar);

        // A press near the left edge is held a margin away from it rather than centred.
        positionPopup(popup, opts({ x: 100 }));
        expect(popup.style.bottom).toBe("40px");
        expect(popup.style.maxHeight).toBe("760px");
        expect(popup.style.left).toBe("10px");
    });
});

describe("attribute detail popup naming", () => {
    it("lists a name behind its kind icon, with the cog on a name Trilium reads for itself", async () => {
        const { AttributeNameSuggestion } = await import("./attribute_detail");
        const row = (type: "label" | "relation", name: string) => {
            const host = document.createElement("div");
            render(<AttributeNameSuggestion type={type} name={name} />, host);
            const kind = host.querySelector(".attr-name-suggestion > .attribute-kind");
            if (!kind) throw new Error("no kind icon rendered");
            return { kind, host };
        };

        const builtin = row("label", "archived");
        expect(builtin.kind.querySelector(".bx-hash")).not.toBeNull();
        expect(builtin.kind.classList.contains("marker-system")).toBe(true);
        expect(builtin.kind.getAttribute("title")).toBe("attribute_list_panel.system_hint");
        expect(builtin.host.querySelector(".attribute-kind + .attr-name-suggestion-name")?.textContent).toBe("archived");
        expect(builtin.host.querySelector(".ext-badge")).toBeNull();

        const invented = row("label", "myOwnLabel");
        expect(invented.kind.classList.contains("marker-system")).toBe(false);
        expect(invented.kind.hasAttribute("title")).toBe(false);

        // A name that is a built-in of the other type is not one here.
        const relation = row("relation", "archived");
        expect(relation.kind.querySelector(".bx-transfer")).not.toBeNull();
        expect(relation.kind.classList.contains("marker-system")).toBe(false);
    });

    it("edits a definition under its bare name and stores it back under its prefix", async () => {
        const { addDefinitionPrefix, stripDefinitionPrefix } = await import("./attribute_detail");

        expect(stripDefinitionPrefix("label:priority", "label-definition")).toBe("priority");
        expect(stripDefinitionPrefix("relation:author", "relation-definition")).toBe("author");
        expect(stripDefinitionPrefix("priority", "label")).toBe("priority");

        expect(addDefinitionPrefix("priority", "label-definition")).toBe("label:priority");
        expect(addDefinitionPrefix("author", "relation-definition")).toBe("relation:author");
        expect(addDefinitionPrefix("priority", "relation")).toBe("priority");
    });

    it("completes a definition against bare names, so that picking one does not prefix it twice", async () => {
        vi.resetModules();
        const server = (await import("../../services/server")).default;
        const { fetchDefinitionNames } = await import("./attribute_detail");
        // The label list holds the definitions of both kinds, definitions being labels themselves.
        const labelNames = [ "priority", "label:priority", "label:due", "relation:author", "label:" ];
        const get = vi.fn(async (url: string) => url.includes("type=label") ? labelNames : [ "template" ]);
        server.get = get as unknown as typeof server.get;

        // A label's definitions come out of the one list it shares with them.
        expect(await fetchDefinitionNames("label", "")).toEqual([ "priority", "due" ]);
        expect(get).toHaveBeenCalledExactlyOnceWith("attribute-names/?type=label&query=");

        // A relation's are only in the label list, which is asked for on top of the relation names —
        // whose plain labels are no names for a relation, and stay out.
        get.mockClear();
        expect(await fetchDefinitionNames("relation", "a b")).toEqual([ "template", "author" ]);
        expect(get.mock.calls.map(([ url ]) => url)).toEqual([
            "attribute-names/?type=relation&query=a%20b",
            "attribute-names/?type=label&query=a%20b"
        ]);
    });

    it("searches for every note carrying the attribute by name alone", async () => {
        const { formatAttributeForSearch } = await import("./attribute_detail");

        expect(formatAttributeForSearch({ type: "label", name: "author" })).toBe("#author");
        expect(formatAttributeForSearch({ type: "relation", name: "template" })).toBe("~template");
    });

    it("counts a show as new by what it would put in the form, not by the objects it arrives in", async () => {
        const { isSameShow } = await import("./attribute_detail");
        const shown = opts({ attribute: { type: "label", name: "author", value: "Tolkien" } });

        // The same row pressed again: a fresh opts object around an equal attribute is the same show,
        // whether or not the attribute object itself survived.
        expect(isSameShow(shown, { ...shown, x: 40 })).toBe(true);
        expect(isSameShow(shown, opts({ attribute: { type: "label", name: "author", value: "Tolkien" } }))).toBe(true);

        // Anything the form would show differently is another show.
        expect(isSameShow(shown, opts({ attribute: { type: "label", name: "author", value: "Lewis" } }))).toBe(false);
        expect(isSameShow(shown, opts({ attribute: { type: "relation", name: "author", value: "Tolkien" } }))).toBe(false);
        expect(isSameShow(shown, opts({ ...shown, isOwned: false }))).toBe(false);
        expect(isSameShow(shown, opts({ ...shown, focus: "name" }))).toBe(false);
        // Which rows the form carries is part of what it would show.
        expect(isSameShow(shown, opts({ ...shown, hideInheritance: true }))).toBe(false);
        expect(isSameShow(shown, opts({ ...shown, hideMultiplicity: true }))).toBe(false);
        expect(isSameShow(shown, opts({ ...shown, hideType: true }))).toBe(false);
        expect(isSameShow(shown, opts({ ...shown, hideTypeOptions: true }))).toBe(false);

        // ...but the very same request handed back is the host re-rendering around an untouched
        // popup, which every keystroke does — rebuilding the form there costs the focus and, with a
        // request that asks for it, re-selects the field so the next character replaces the name.
        const focused = opts({ focus: "name" });
        expect(isSameShow(focused, focused)).toBe(true);

        // Opening and closing are shows of their own, so reopening rebuilds the form.
        expect(isSameShow(null, shown)).toBe(false);
        expect(isSameShow(shown, null)).toBe(false);
        expect(isSameShow(null, null)).toBe(true);
    });

    it("explains only the names Trilium attaches a meaning to, and points at a help page where there is one", async () => {
        const { lookupAttributeHelp } = await import("./attribute_detail");

        expect(lookupAttributeHelp("label", "customRequestHandler")).toMatchObject({ helpPage: "J5Ex1ZrMbyJ6" });
        expect(lookupAttributeHelp("label", "somethingInvented")).toBeUndefined();
        expect(lookupAttributeHelp(undefined, "customRequestHandler")).toBeUndefined();
    });

    it("explains every name Trilium reads for itself, and no name it does not", async () => {
        const { ATTR_HELP } = await import("./attr_help");
        const { default: BUILTIN_ATTRIBUTES } = await import("@triliumnext/commons/src/lib/builtin_attributes");

        // Asserted on the entry being declared rather than on what it reads: `t()` resolves to nothing
        // without the translations loaded, which is why the lookup below is checked by its help page.
        for (const { type, name } of BUILTIN_ATTRIBUTES) {
            expect(Object.hasOwn(ATTR_HELP[type] ?? {}, name), `${type} ${name} has no help`).toBe(true);
        }

        for (const type of [ "label", "relation" ] as const) {
            for (const name of Object.keys(ATTR_HELP[type] ?? {})) {
                expect(BUILTIN_ATTRIBUTES.some((attr) => attr.type === type && attr.name === name),
                    `${type} ${name} is explained but is not a builtin`).toBe(true);
            }
        }
    });

    it("marks the names Trilium reads for itself, a definition named after one excepted", async () => {
        const { isSystemAttribute } = await import("./attribute_detail");

        expect(isSystemAttribute("label", "archived")).toBe(true);
        expect(isSystemAttribute("relation", "template")).toBe(true);
        // Most system attributes have no help entry, which is what the mark is for.
        expect(isSystemAttribute("label", "dateNote")).toBe(true);
        expect(isSystemAttribute("label", "somethingInvented")).toBe(false);

        // A definition sets up a field named after a system attribute without being one, and the popup
        // edits it under the bare name -- so the name alone would wrongly say yes.
        expect(isSystemAttribute("label-definition", "archived")).toBe(false);
        expect(isSystemAttribute("relation-definition", "template")).toBe(false);
        expect(isSystemAttribute(undefined, "archived")).toBe(false);
    });
});

describe("related notes menu", () => {
    it("lists the notes and the search entry as the dropdown does, titles escaped for the menu", async () => {
        const { showRelatedNotesMenu } = await import("./attribute_detail");
        const { default: contextMenu } = await import("../../menus/context_menu");
        const { default: appContext } = await import("../../components/app_context");

        const show = vi.spyOn(contextMenu, "show").mockResolvedValue();
        const triggerCommand = vi.spyOn(appContext, "triggerCommand").mockResolvedValue(undefined);
        // The tab manager only exists once the app has started, so the stub stands it in whole.
        const setNote = vi.fn();
        const previousTabManager = appContext.tabManager;
        appContext.tabManager = { getActiveContext: () => ({ setNote }) } as unknown as typeof appContext.tabManager;

        showRelatedNotesMenu({ pageX: 12, pageY: 34 } as MouseEvent, {
            notes: [{ notePath: "root/abc", icon: "tn-icon bx bx-file", title: "Tolkien & <sons>" }],
            otherCount: 5
        }, { type: "label", name: "author", value: "" });

        expect(show).toHaveBeenCalledOnce();
        const options = show.mock.calls[0][0];
        expect(options).toMatchObject({ x: 12, y: 34 });

        const [ noteItem, separator, searchItem ] = options.items;
        // The menu reads a title as HTML, which the note's own is not.
        expect(noteItem).toMatchObject({
            title: "Tolkien &amp; &lt;sons&gt;",
            uiIcon: "tn-icon bx bx-file"
        });
        expect(separator).toEqual({ kind: "separator" });
        expect(searchItem).toMatchObject({ uiIcon: "bx bx-search-alt" });

        // A note entry navigates to it; the search entry searches for every carrier of the name.
        const pressEvent = new MouseEvent("mousedown");
        if ("handler" in noteItem) {
            noteItem.handler?.(noteItem, pressEvent);
        }
        expect(setNote).toHaveBeenCalledWith("root/abc");

        if ("handler" in searchItem) {
            searchItem.handler?.(searchItem, pressEvent);
        }
        expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "#author" });

        appContext.tabManager = previousTabManager;
        vi.restoreAllMocks();
    });
});

describe("the rows the form carries", () => {
    let mounted: HTMLElement | undefined;

    afterEach(() => {
        if (mounted) {
            render(null, mounted);
            mounted.remove();
            mounted = undefined;
        }
    });

    /** Renders the form on a definition, which is where the kind and multiplicity rows live. */
    async function renderForm(overrides: Partial<AttributeDetailOpts> = {}) {
        const { AttributeForm } = await import("./attribute_detail");
        const host = document.createElement("div");
        mounted = host;
        document.body.appendChild(host);

        await act(async () => {
            render(
                <ParentComponent.Provider value={new Component()}>
                    <AttributeForm
                        opts={opts({
                            attribute: {
                                type: "label",
                                name: "label:severity",
                                value: "promoted,single,select"
                            },
                            ...overrides
                        })}
                        attrType="label-definition"
                        onCancel={() => {}}
                    />
                </ParentComponent.Provider>,
                host
            );
        });

        // `OptionsRow` names the control it wraps, labelling it by a unique id built from that
        // name.
        return (name: string) =>
            !!host.querySelector(`[name="${name}"], [id^="${name}"], [for^="${name}"]`);
    }

    it("carries the kind, kind options, multiplicity and inheritance rows by default", async () => {
        const has = await renderForm();

        expect(has("attr-label-type")).toBe(true);
        expect(has("attr-select-options")).toBe(true);
        expect(has("attr-multiplicity")).toBe(true);
        expect(has("attr-inheritable")).toBe(true);
    });

    /** A host that can only use one kind, such as a board grouping by a select, leaves it out. */
    it("leaves out the kind row alone for `hideType`", async () => {
        const has = await renderForm({ hideType: true });

        expect(has("attr-label-type")).toBe(false);
        // Only that row: the rest of the form is untouched.
        expect(has("attr-name")).toBe(true);
        expect(has("attr-multiplicity")).toBe(true);
        expect(has("attr-inheritable")).toBe(true);
    });

    /** A host that fills the kind's own rows in itself, such as a board making the columns. */
    it("leaves out the select options alone for `hideTypeOptions`", async () => {
        const has = await renderForm({ hideTypeOptions: true });

        expect(has("attr-select-options")).toBe(false);
        // Only that row: the rest of the form is untouched.
        expect(has("attr-name")).toBe(true);
        expect(has("attr-label-type")).toBe(true);
        expect(has("attr-multiplicity")).toBe(true);
        expect(has("attr-inheritable")).toBe(true);
    });
});

describe("dismissing the attribute detail popup", () => {
    afterEach(() => {
        document.body.replaceChildren();
    });

    it("stays open for a press in the note list of its target field, and closes for one elsewhere", async () => {
        const { AttributeDetail } = await import("./attribute_detail");
        const onDismiss = vi.fn();
        const host = document.createElement("div");
        document.body.appendChild(host);
        await act(async () => {
            render(
                <ParentComponent.Provider value={new Component()}>
                    <AttributeDetail
                        opts={opts({ attribute: { type: "relation", name: "author", value: "" } })}
                        onDismiss={onDismiss}
                        onCancel={() => {}}
                    />
                </ParentComponent.Provider>,
                host
            );
        });

        // `NoteAutocomplete` portals its list to the body, outside the popup.
        const noteList = document.createElement("div");
        noteList.className = "dropdown-menu note-autocomplete-menu";
        const row = document.createElement("div");
        noteList.appendChild(row);
        document.body.appendChild(noteList);

        row.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
        expect(onDismiss).not.toHaveBeenCalled();

        document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
        expect(onDismiss).toHaveBeenCalledOnce();

        render(null, host);
    });
});


function opts(overrides: Partial<AttributeDetailOpts>): AttributeDetailOpts {
    return {
        attribute: { type: "label", name: "author", value: "" },
        isOwned: true,
        x: 0,
        ...overrides
    };
}

/** happy-dom lays nothing out, so the sizes the positioning reads are given to it directly. */
function sized(el: HTMLElement, width: number, height: number) {
    Object.defineProperty(el, "offsetWidth", { value: width, configurable: true });
    Object.defineProperty(el, "offsetHeight", { value: height, configurable: true });
    return el;
}

function anchoredAt({ left, right, top }: { left: number; right: number; top: number }) {
    const anchor = document.createElement("div");
    anchor.getBoundingClientRect = (() => ({ left, right, top })) as Element["getBoundingClientRect"];
    return anchor;
}

function sizeViewport(width: number, height: number) {
    Object.defineProperty(document.documentElement, "clientWidth", { value: width, configurable: true });
    Object.defineProperty(document.documentElement, "clientHeight", { value: height, configurable: true });
}

function sizeBody(height: number) {
    Object.defineProperty(document.body, "clientHeight", { value: height, configurable: true });
}