Skip to content

Build your personal knowledge base with Trilium Notes

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

import FNote from "../../entities/fnote";

// What this file is for: the panel draws its runs one way for a pointer and another for a thumb, and
// the device is read once at module load (see `IS_MOBILE`), so the two cannot be told apart within a
// single file. Everything else about the panel is covered against a pointer in AttributeList.spec.
vi.mock("../../services/utils", async (importOriginal) => ({
    ...(await importOriginal<typeof import("../../services/utils")>()),
    isMobile: () => true
}));

const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));
vi.mock("../react/hooks", async (importOriginal) => ({
    ...(await importOriginal<typeof import("../react/hooks")>()),
    useActiveNoteContext: () => ({ note: shownNote.current })
}));

const showContextMenu = vi.hoisted(() => vi.fn(async () => {}));
vi.mock("../../menus/context_menu", () => ({ default: { show: showContextMenu } }));
vi.mock("../../services/dialog", () => ({ default: { confirm: vi.fn(async () => true) } }));
vi.mock("../../services/toast", () => ({ default: { showMessage: vi.fn(), showError: vi.fn() } }));

import FAttribute, { FAttributeRow } from "../../entities/fattribute";
import { holdAttributes } from "../../services/attribute_clipboard";
import froca from "../../services/froca";
import noteAttributeCache from "../../services/note_attribute_cache";
import options from "../../services/options";
import server from "../../services/server";
import { buildNote } from "../../test/easy-froca";
import AttributeList from "./AttributeList";

describe("AttributeList on a phone", () => {
    let container: HTMLElement;
    let put: ReturnType<typeof vi.fn>;

    beforeEach(() => {
        vi.clearAllMocks();
        options.set("rightPaneCollapsedItems", "[]");
        // What Trilium last copied outlives a render, so each test says for itself whether there is
        // anything to paste.
        holdAttributes([]);
        put = vi.fn(async () => ({}));
        server.put = put as unknown as typeof server.put;
        server.post = (async () => ({ results: [], count: 0 })) as unknown as typeof server.post;
        container = document.createElement("div");
        document.body.appendChild(container);
    });

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

    it("draws a card per run", () => {
        renderPanel(noteWithRuns());

        expect(sectionIds()).toEqual([ "attributes", "attributes-inherited", "attributes-definitions" ]);

        // Each card counts its rows in its title.
        expect(section("attributes").querySelector(".attribute-run-count")?.textContent).toBe("2");
        expect(section("attributes-definitions").querySelector(".attribute-run-count")?.textContent).toBe("2");

        // The rows themselves are unchanged — menu items, which is what a phone's lists are made of.
        expect(namesIn(section("attributes"))).toEqual([ "author", "template" ]);
        expect(section("attributes").querySelector(".attribute-row")?.className).toContain("dropdown-item");
    });

    it("adds from the toolbar and the cards' own headers, there being no row to hover for one", () => {
        renderPanel(noteWithRuns());

        // The toolbar's menu adds any kind; it is also the only way to a relation here, whose creation
        // editor is a pointer's.
        expect(iconsIn(toolbar())).toEqual([ "bx bx-plus" ]);
        expect(iconsIn(header("attributes"))).toEqual([ "bx bx-help-circle" ]);
        // Each card has its own help. A run that can be added to also has an add button, definitions
        // included; the inherited run, whose attributes belong to another note, has none.
        expect(iconsIn(header("attributes-definitions"))).toEqual([ "bx bx-help-circle", "bx bx-plus" ]);
        expect(iconsIn(header("attributes-inherited"))).toEqual([ "bx bx-help-circle" ]);

        // The ghost row at the foot of a run is a hover affordance, so it stays on the desktop.
        expect(container.querySelector(".attribute-add-row")).toBeNull();
    });

    it("says a run holds nothing, which a pointer's runs leave to the add row beneath them", () => {
        renderPanel(buildNote({ id: "phone-bare-run", title: "Bare" }));

        // The card would otherwise stand empty and say nothing: a phone keeps what is done to a run
        // in the card's header, so there is no add row inside it to imply the run is waiting to be
        // filled. AttributeList.spec asserts the other half — that a pointer gets no such notice.
        expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);
        expect(section("attributes").querySelector(".no-items")).not.toBeNull();
        // Only the note's own run is ever shown empty; the rest are left out when they hold nothing.
        expect(sectionIds()).toEqual([ "attributes" ]);
    });

    it("offers pasting from the toolbar, which is a phone's only way to it", async () => {
        // Nothing copied, nothing offered, as in the row menu.
        renderPanel(noteWithRuns());
        expect(iconsIn(toolbar())).not.toContain("bx bx-paste");

        // A note with no attributes has no row to hold down or press beside, so the toolbar is the
        // only way to paste onto it.
        render(null, container);
        holdAttributes([ { type: "label", name: "author", value: "Elian", isInheritable: false } ]);
        renderPanel(buildNote({ id: "phone-bare", title: "Bare" }));

        expect(container.querySelectorAll(".attribute-row")).toHaveLength(0);
        expect(iconsIn(toolbar())).toEqual([ "bx bx-paste", "bx bx-plus" ]);

        // The button opens the clipboard menu, whose Paste row pastes.
        const toggle = toolbar()?.querySelector<HTMLElement>(".attribute-clipboard > button");
        expect(toggle).not.toBeNull();
        act(() => toggle?.click());
        const paste = document.querySelector(".tn-dropdown-portal .bx-paste")?.closest<HTMLElement>("[role=menuitem]");
        expect(paste).toBeTruthy();
        await act(async () => paste?.click());

        const [ url, saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];
        expect(url).toBe("notes/phone-bare/attributes");
        expect(saved).toEqual([ { type: "label", name: "author", value: "Elian", isInheritable: false } ]);

        // A note that cannot be edited has nothing to paste or add, so the toolbar says it is read-only.
        render(null, container);
        const locked = buildNote({ id: "phone-locked", title: "Locked" });
        locked.isContentWritable = false;
        renderPanel(locked);
        expect(iconsIn(toolbar())).toEqual([ "bx bx-lock-alt" ]);
        expect(toolbar()?.querySelector(".attribute-toolbar-read-only")).not.toBeNull();
    });

    it("still picks rows out, by the press held down, and says what can be done with them", () => {
        vi.useFakeTimers();
        renderPanel(noteWithRuns());

        const row = section("attributes").querySelector(".attribute-row");
        act(() => {
            row?.dispatchEvent(new Event("touchstart", { bubbles: true }));
        });
        // Held long enough, the press picks the row out rather than opening it.
        act(() => void vi.advanceTimersByTime(600));

        expect(row?.className).toContain("selected");
        // The checkbox in the kind icon's slot, as on a desktop, ticked; nothing is added at the
        // row's end, so its layout stays as it was.
        expect(row?.querySelector<HTMLInputElement>(".attribute-kind-check input")?.checked).toBe(true);
        expect(row?.querySelector(".menu-trailing-icon")).toBeNull();
        expect(container.querySelector(".attribute-list-panel")?.className).toContain("selecting");

        // Once rows are being picked out, a tap anywhere on another row picks it too.
        const next = section("attributes").querySelectorAll<HTMLElement>(".attribute-row")[1];
        act(() => next.click());
        expect(next.className).toContain("selected");
        expect(next.querySelector<HTMLInputElement>(".attribute-kind-check input")?.checked).toBe(true);

        // The toolbar above the cards turns over to the selection.
        expect(iconsIn(toolbar())).toEqual([ "bx bx-copy", "bx bx-trash", "bx bx-plus" ]);
        expect(toolbar()?.compareDocumentPosition(section("attributes")))
            .toBe(Node.DOCUMENT_POSITION_FOLLOWING);
    });

    function renderPanel(note: FNote) {
        shownNote.current = note;
        act(() => render(<AttributeList />, container));
    }

    function sectionIds() {
        return [ ...container.querySelectorAll(".options-section") ]
            .map((el) => [ ...el.classList ].find((name) => /^attributes(-|$)/.test(name)));
    }

    function toolbar() {
        return container.querySelector<HTMLElement>(".attribute-toolbar");
    }

    function section(id: string) {
        const el = container.querySelector<HTMLElement>(`.options-section.${id}`);
        expect(el, id).not.toBeNull();
        return el as HTMLElement;
    }

    function header(id: string) {
        return section(id).querySelector<HTMLElement>(".options-section-header");
    }
});

function namesIn(root: Element) {
    return [ ...root.querySelectorAll(".attribute-name") ].map((name) => name.textContent);
}

/** The icons a header (or the selection bar) offers, which is what its buttons are known by: the
 *  titles are translated, and translations stay unloaded in these tests. */
function iconsIn(root: Element | null) {
    return [ ...(root?.querySelectorAll(".bx") ?? []) ]
        .map((icon) => [ ...icon.classList ].filter((name) => name.startsWith("bx")).join(" "));
}

/** A note with all three of the runs a phone can be shown, each holding more than one row. */
function noteWithRuns() {
    buildNote({ id: "tpl", title: "Template" });
    const note = buildNote({
        id: "phone-subject",
        title: "Subject",
        "#author": "Elian",
        "~template": "tpl",
        "#label:priority": "promoted,single,date"
    });

    noteAttributeCache.attributes[note.noteId] = [
        ...note.getOwnedAttributes(),
        inherited({ name: "inheritedLabel", value: "x" }),
        inherited({ name: "archived", value: "" }),
        inherited({ name: "label:status", value: "promoted,multi" })
    ];

    return note;
}

function inherited(row: Partial<FAttributeRow>) {
    return new FAttribute(froca, {
        attributeId: `inh-${row.name}`,
        noteId: "tpl",
        type: "label",
        name: "",
        value: "",
        position: 0,
        isInheritable: true,
        ...row
    } as FAttributeRow);
}