Skip to content

Build your personal knowledge base with Trilium Notes

35.2 KB
Raw Blame
import { _setModelData as setModelData, ClassicEditor, FindAndReplace, FindAndReplaceEditing, keyCodes, List, Paragraph, TodoList, Typing, Undo, type ModelElement } from "ckeditor5";
import { beforeEach, describe, expect, it } from "vitest";

import { createTestEditor, getEditorElement } from "../../test/editor-kit.js";
import CollapsibleListItems, { LIST_COLLAPSED_ATTRIBUTE, ToggleListCollapseCommand } from "./collapsible_list_items.js";
import FindReveal from "./find_reveal.js";

// Lists are flat in the model: sibling blocks related by listIndent/listItemId.
const LIST_FIXTURE =
    '<paragraph listIndent="0" listItemId="i-a" listType="bulleted">Parent[]</paragraph>' +
    '<paragraph listIndent="1" listItemId="i-b" listType="bulleted">Child</paragraph>' +
    '<paragraph listIndent="1" listItemId="i-c" listType="bulleted">Other child</paragraph>' +
    '<paragraph listIndent="0" listItemId="i-d" listType="bulleted">Sibling</paragraph>' +
    "<paragraph>Outside of the list</paragraph>";

describe("CollapsibleListItems", () => {
    let editor: ClassicEditor;

    beforeEach(async () => {
        editor = await createTestEditor([CollapsibleListItems, List, TodoList, Paragraph, Typing, Undo]);

        setModelData(editor.model, LIST_FIXTURE);
    });

    it("collapses and expands via the command and persists the state into the data", () => {
        const dataBefore = editor.getData();
        const command = editor.commands.get("toggleListCollapse");
        expect(command?.isEnabled).toBe(true);

        editor.execute("toggleListCollapse");

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(command?.value).toBe(true);

        const domRoot = editor.editing.view.getDomRoot();
        const collapsedItem = domRoot?.querySelector('li[data-trilium-collapsed="true"]');
        expect(collapsedItem).not.toBeNull();
        const nestedList = collapsedItem?.querySelector("ul");
        expect(nestedList).not.toBeNull();
        if (nestedList) {
            expect(getComputedStyle(nestedList).display).toBe("none");
        }

        expect(editor.getData()).toContain('data-trilium-collapsed="true"');

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(command?.value).toBe(false);
        expect(domRoot?.querySelector("li[data-trilium-collapsed]")).toBeNull();
        expect(editor.getData()).toBe(dataBefore);
    });

    it("round-trips the collapsed state through the data without expanding it on load", () => {
        editor.setData(
            '<ul><li data-trilium-collapsed="true">Parent<ul><li>Child</li></ul></li><li>Sibling</li></ul>');

        // Loading a collapsed subtree must not trigger the "content placed under a
        // collapsed parent" auto-expansion: the children arrive together with the parent.
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        const domRoot = editor.editing.view.getDomRoot();
        const nestedList = domRoot?.querySelector('li[data-trilium-collapsed="true"] ul');
        expect(nestedList).not.toBeNull();
        if (nestedList) {
            expect(getComputedStyle(nestedList).display).toBe("none");
        }

        expect(editor.getData()).toContain('data-trilium-collapsed="true"');
    });

    it("normalizes away persisted state that has nothing to collapse", () => {
        editor.setData('<ul><li data-trilium-collapsed="true">No children</li></ul>');

        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(editor.getData()).not.toContain("data-trilium-collapsed");
    });

    it("collapse toggles are undoable", () => {
        const dataBefore = editor.getData();

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        editor.execute("undo");
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(editor.getData()).toBe(dataBefore);
    });

    it("is only enabled on list items that have nested items", () => {
        const command = editor.commands.get("toggleListCollapse");

        setSelectionIn(editor, 1); // leaf child
        expect(command?.isEnabled).toBe(false);

        setSelectionIn(editor, 4); // outside of the list
        expect(command?.isEnabled).toBe(false);
    });

    it("applies to every block of a multi-block list item", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="i-a" listType="bulleted">First[]</paragraph>' +
            '<paragraph listIndent="0" listItemId="i-a" listType="bulleted">Second</paragraph>' +
            '<paragraph listIndent="1" listItemId="i-b" listType="bulleted">Child</paragraph>');

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(getBlock(editor, 1).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(getBlock(editor, 1).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("expands automatically when the selection moves into a hidden item", () => {
        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        setSelectionIn(editor, 1);

        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(editor.getData()).not.toContain("data-trilium-collapsed");
    });

    it("moves the selection to the parent when collapsing hides it (#11256)", () => {
        setSelectionIn(editor, 1);
        const parentItem = editor.editing.view.getDomRoot()?.querySelector("li");
        expect(parentItem).toBeTruthy();
        if (!parentItem) {
            return;
        }

        mouseDownAt(parentItem, -10);

        const parentBlock = getBlock(editor, 0);
        const position = editor.model.document.selection.getFirstPosition();
        expect(parentBlock.getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(position?.parent).toBe(parentBlock);
        expect(position?.offset).toBe(parentBlock.maxOffset);
    });

    it("moves a selection that ends in a hidden child when collapsing (#11256)", () => {
        editor.model.change((writer) => {
            writer.setSelection(writer.createRange(
                writer.createPositionAt(getBlock(editor, 0), 2),
                writer.createPositionAt(getBlock(editor, 1), 3)
            ));
        });

        editor.execute("toggleListCollapse");

        const parentBlock = getBlock(editor, 0);
        const selection = editor.model.document.selection;
        expect(parentBlock.getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(selection.isCollapsed).toBe(true);
        expect(selection.getFirstPosition()?.parent).toBe(parentBlock);
        expect(selection.getFirstPosition()?.offset).toBe(parentBlock.maxOffset);
    });

    it("expands automatically when an item is indented under a collapsed parent", () => {
        editor.execute("toggleListCollapse");
        setSelectionIn(editor, 3); // "Sibling", still visible at indent 0

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        editor.execute("indentList");

        expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(1);
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("drops the collapsed attribute from new items that have nothing to collapse", () => {
        // Simulates e.g. an Enter split copying the attribute onto the new block.
        editor.model.change((writer) => {
            const root = editor.model.document.getRoot();
            if (!root) {
                throw new Error("The editor has no root.");
            }
            const block = writer.createElement("paragraph", {
                listIndent: 0,
                listItemId: "i-z",
                listType: "bulleted",
                [LIST_COLLAPSED_ATTRIBUTE]: true
            });
            writer.insert(block, root, "end");
        });

        expect(getBlock(editor, 5).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("leaves Enter behavior unchanged outside collapsed list items", () => {
        setModelData(editor.model, "<paragraph>paragraph[]</paragraph>");
        editor.execute("enter");
        expect(editor.model.document.getRoot()?.childCount).toBe(2);

        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="u-a" listType="bulleted">item[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="u-b" listType="bulleted">child</paragraph>');
        editor.execute("enter");
        expect(getBlock(editor, 1).isEmpty).toBe(true);
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("u-b");
    });

    it("moves a sibling past hidden children when Enter exits a collapsed multi-block item", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">first</paragraph>' +
            '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">second[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="m-b" listType="bulleted">child</paragraph>');

        editor.execute("toggleListCollapse");
        pressEnter(editor);

        expect(getBlock(editor, 0).getAttribute("listItemId")).toBe("m-a");
        expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("m-a");
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");
        expect(getBlock(editor, 2).isEmpty).toBe(true);

        pressEnter(editor, true);
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");

        pressEnter(editor);

        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-b");
        expect(getBlock(editor, 3).getAttribute("listItemId")).not.toBe("m-a");
        expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);
        expect(getBlock(editor, 3).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(editor.model.document.selection.getFirstPosition()?.parent)
            .toBe(getBlock(editor, 3));

        editor.execute("undo");
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("m-a");
        expect(getBlock(editor, 2).isEmpty).toBe(true);
        expect(getBlock(editor, 3).getAttribute("listItemId")).toBe("m-b");
    });

    it("inserts after the hidden children when Enter splits a collapsed item (#11256)", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="t-a" listType="todo">todo1[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="t-b" listType="todo">a</paragraph>' +
            '<paragraph listIndent="1" listItemId="t-c" listType="todo">b</paragraph>');

        editor.execute("toggleListCollapse");
        editor.execute("enter");

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("t-b");
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("t-c");
        expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);
        expect(getBlock(editor, 3).isEmpty).toBe(true);
        expect(editor.model.document.selection.getFirstPosition()?.parent)
            .toBe(getBlock(editor, 3));

        editor.execute("undo");
        expect(editor.model.document.getRoot()?.childCount).toBe(3);
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("inserts after the entire hidden subtree when Enter splits a collapsed item", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="d-a" listType="bulleted">parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="d-b" listType="bulleted">mid</paragraph>' +
            '<paragraph listIndent="2" listItemId="d-c" listType="bulleted">leaf</paragraph>');

        editor.execute("toggleListCollapse");
        editor.execute("enter");

        expect(getBlock(editor, 0).getAttribute("listItemId")).toBe("d-a");
        expect(getBlock(editor, 1).getAttribute("listItemId")).toBe("d-b");
        expect(getBlock(editor, 2).getAttribute("listItemId")).toBe("d-c");
        expect(getBlock(editor, 3).getAttribute("listIndent")).toBe(0);
        expect(getBlock(editor, 3).isEmpty).toBe(true);
    });

    it("does not crash when Enter follows a collapsed item with no remaining children", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="s-a" listType="bulleted">parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="s-b" listType="bulleted">kid</paragraph>');

        editor.execute("toggleListCollapse");
        for (let i = 0; i < 4; i++) {
            editor.execute("forwardDelete");
        }

        expect(editor.model.document.getRoot()?.childCount).toBe(1);
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(() => editor.execute("enter")).not.toThrow();
        expect(editor.model.document.getRoot()?.childCount).toBe(2);
    });

    it("toggles when clicking the arrow in the gutter and ignores other clicks", () => {
        const domRoot = editor.editing.view.getDomRoot();
        const items = domRoot ? Array.from(domRoot.querySelectorAll("li")) : [];
        const parentItem = items.at(0);
        const leafItem = items.at(1);
        expect(parentItem).toBeDefined();
        expect(leafItem).toBeDefined();
        if (!parentItem || !leafItem) {
            return;
        }

        mouseDownAt(parentItem, -10); // on the gutter arrow
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        mouseDownAt(parentItem, -10); // toggles back
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);

        mouseDownAt(parentItem, 5); // inside the item box: not a gutter click
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);

        mouseDownAt(leafItem, -10); // leaf items have nothing to collapse
        expect(getBlock(editor, 1).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("toggles when the rendered arrow is clicked at its real on-screen position", () => {
        // Unlike the test above (which dispatches straight onto the <li>), this reproduces a
        // genuine user click: it asks the browser what element actually sits at the arrow's
        // pixel coordinates and dispatches there — so it catches a mismatch between where the
        // arrow paints and what the mousedown handler receives as its target.

        // Shift the editor away from the viewport's left edge so the negative-inset gutter
        // (where the arrow lives) is actually on-screen and hit-testable.
        const editorElement = getEditorElement(editor);
        editorElement.style.marginLeft = "160px";
        editorElement.style.marginTop = "60px";

        const parentLi = editor.editing.view.getDomRoot()?.querySelector("li");
        expect(parentLi).toBeTruthy();
        if (!parentLi) {
            return;
        }

        const { x, y } = arrowCentre(parentLi);

        // Click whatever element actually sits at the arrow's coordinates — the real target,
        // not a forced <li> — so a mismatch between where the arrow paints and what the
        // handler receives would be caught.
        const hit = document.elementFromPoint(x, y);
        hit?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, clientX: x, clientY: y }));

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("fills the arrow into a circle while the pointer is on it", async () => {
        const editorElement = getEditorElement(editor);
        editorElement.style.marginLeft = "160px";
        editorElement.style.marginTop = "60px";

        const parentLi = editor.editing.view.getDomRoot()?.querySelector("li");
        expect(parentLi).toBeTruthy();
        if (!parentLi) {
            return;
        }

        const arrow = arrowCentre(parentLi);
        const rect = parentLi.getBoundingClientRect();

        mouseMoveAt(arrow.x, arrow.y);
        expect(parentLi.classList.contains("trilium-list-arrow-hovered")).toBe(true);
        // The arrow is a boxicons glyph, not a hand-drawn shape.
        expect(getComputedStyle(parentLi, "::before").fontFamily).toBe("boxicons");
        // Polled: the circle fades in, so its colour only settles once the transition ends.
        await expect.poll(() => getComputedStyle(parentLi, "::before").backgroundColor)
            .toBe("rgba(128, 128, 128, 0.25)");

        // Over the item's own text the pointer is no longer on the arrow.
        mouseMoveAt(Math.round(rect.left + 5), arrow.y);
        expect(parentLi.classList.contains("trilium-list-arrow-hovered")).toBe(false);
        await expect.poll(() => getComputedStyle(parentLi, "::before").backgroundColor)
            .toBe("rgba(0, 0, 0, 0)");

        // A held button is a drag (selecting text), not a hover.
        mouseMoveAt(arrow.x, arrow.y, 1);
        expect(parentLi.classList.contains("trilium-list-arrow-hovered")).toBe(false);

        // Leaving the editable ends the mouse moves, so the arrow is unlit on the way out —
        // but moving on to another element inside it is left to the mousemove handler.
        mouseMoveAt(arrow.x, arrow.y);
        const otherItem = editor.editing.view.getDomRoot()?.querySelectorAll("li")[1];
        parentLi.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: otherItem }));
        expect(parentLi.classList.contains("trilium-list-arrow-hovered")).toBe(true);

        parentLi.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body }));
        expect(parentLi.classList.contains("trilium-list-arrow-hovered")).toBe(false);
    });

    it("toggles a to-do list item when its gutter arrow is clicked", () => {
        // To-do <li>s wrap content in <span class="todo-list__label">, which shifts the
        // view->model mapping; regression guard for that resolution (the click works for
        // bulleted lists but used to silently no-op on to-do lists).
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="td-a" listType="todo">Parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="td-b" listType="todo">Child</paragraph>' +
            '<paragraph listIndent="1" listItemId="td-c" listType="todo">Other child</paragraph>');

        const parentLi = editor.editing.view.getDomRoot()?.querySelector("li");
        expect(parentLi).toBeTruthy();
        if (!parentLi) {
            return;
        }

        const { x, y } = arrowCentre(parentLi);

        const hit = document.elementFromPoint(x, y);
        hit?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, clientX: x, clientY: y }));

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("resolves the model item from a to-do <li> via the command", () => {
        // Selection-independent of the click path: the command's getSelectedListBlock must
        // also work for to-do items (it does, via the selection), proving end to end.
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="tc-a" listType="todo">Parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="tc-b" listType="todo">Child</paragraph>');

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("toggles via Ctrl+Alt+Enter on a collapsible item and ignores leaves", () => {
        pressCtrlAltEnter(editor); // selection starts in the parent
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);

        pressCtrlAltEnter(editor);
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);

        setSelectionIn(editor, 1); // leaf child: nothing to collapse
        pressCtrlAltEnter(editor);
        expect(getBlock(editor, 1).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("collapses to-do items via Ctrl+Alt+Enter without checking them", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="ta-a" listType="todo">Parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="ta-b" listType="todo">Child</paragraph>');

        pressCtrlAltEnter(editor);

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(getBlock(editor, 0).hasAttribute("todoListChecked")).toBe(false);
    });

    it("leaves Ctrl+Enter to the native to-do check (no longer bound to collapse)", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="t-a" listType="todo">Parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="t-b" listType="todo">Child</paragraph>');

        pressCtrlEnter(editor);

        // Collapse no longer touches Ctrl+Enter, so the native checkTodoList handles it.
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(getBlock(editor, 0).getAttribute("todoListChecked")).toBe(true);
    });

    it("removes the data attribute in the view when the model attribute is set to false", () => {
        // The downcast strategy's setAttributeOnDowncast runs with a falsy value when the model
        // attribute is present but false (rather than removed), exercising its removeAttribute
        // branch directly.
        editor.execute("toggleListCollapse");
        const domRoot = editor.editing.view.getDomRoot();
        expect(domRoot?.querySelector("li[data-trilium-collapsed]")).not.toBeNull();

        editor.model.change((writer) => {
            writer.setAttribute(LIST_COLLAPSED_ATTRIBUTE, false, getBlock(editor, 0));
        });

        expect(domRoot?.querySelector("li[data-trilium-collapsed]")).toBeNull();
    });

    it("ignores a persisted data attribute whose value is not exactly \"true\"", () => {
        editor.setData(
            '<ul><li data-trilium-collapsed="false">Parent<ul><li>Child</li></ul></li></ul>');

        // The upcast converter maps anything other than "true" to null (no model attribute).
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
        expect(editor.getData()).not.toContain("data-trilium-collapsed");
    });

    it("ignores a mousedown that does not target a list item", () => {
        // Click in the paragraph outside the list: data.target is not an <li>, so the handler
        // bails before resolving any block and nothing collapses.
        const domRoot = editor.editing.view.getDomRoot();
        const paragraph = domRoot?.querySelector("p");
        expect(paragraph).toBeTruthy();
        if (!paragraph) {
            return;
        }

        const rect = paragraph.getBoundingClientRect();
        paragraph.dispatchEvent(new MouseEvent("mousedown", {
            bubbles: true,
            cancelable: true,
            clientX: rect.left - 10,
            clientY: rect.top + 5
        }));

        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("treats a click past the right edge as a gutter click in RTL", () => {
        const domRoot = editor.editing.view.getDomRoot();
        if (domRoot) {
            domRoot.setAttribute("dir", "rtl");
            domRoot.style.direction = "rtl";
        }

        const parentLi = domRoot?.querySelector("li");
        expect(parentLi).toBeTruthy();
        if (!parentLi) {
            return;
        }
        parentLi.style.direction = "rtl";

        const rect = parentLi.getBoundingClientRect();
        // In RTL the gutter sits to the right of the box; a click past rect.right is a gutter click.
        parentLi.dispatchEvent(new MouseEvent("mousedown", {
            bubbles: true,
            cancelable: true,
            clientX: rect.right + 10,
            clientY: rect.top + 5
        }));

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("is a no-op when execute runs with no list item selected", () => {
        setSelectionIn(editor, 4); // the paragraph outside the list

        const command = editor.commands.get("toggleListCollapse");
        expect(command).toBeInstanceOf(ToggleListCollapseCommand);
        if (!(command instanceof ToggleListCollapseCommand)) {
            return;
        }
        // editor.execute() (and the decorated command.execute()) short-circuit a disabled
        // command before its body runs, so invoke the raw method to exercise its null-block
        // guard with a non-list selection active.
        expect(() => ToggleListCollapseCommand.prototype.execute.call(command)).not.toThrow();
        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("ignores list attribute changes whose target is not a list block", () => {
        // A listIndent change on the trailing range covers the postfixer branch where the
        // changed range's nodeAfter is not a resolvable list element.
        expect(() => editor.model.change((writer) => {
            const last = getBlock(editor, 4); // "Outside of the list" paragraph
            writer.setAttribute("listIndent", 0, last);
            writer.removeAttribute("listIndent", last);
        })).not.toThrow();

        expect(getBlock(editor, 0).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("does nothing when execute runs on a leaf list item", () => {
        setSelectionIn(editor, 1); // leaf child, no nested items

        const command = editor.commands.get("toggleListCollapse");
        expect(command?.isEnabled).toBe(false);
        expect(command).toBeInstanceOf(ToggleListCollapseCommand);
        if (!(command instanceof ToggleListCollapseCommand)) {
            return;
        }
        // Block exists but has nothing to collapse: the hasNestedItems guard short-circuits.
        expect(() => ToggleListCollapseCommand.prototype.execute.call(command)).not.toThrow();
        expect(getBlock(editor, 1).hasAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(false);
    });

    it("collapses from a selection in a later block of a multi-block item", () => {
        setModelData(editor.model,
            '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">First</paragraph>' +
            '<paragraph listIndent="0" listItemId="m-a" listType="bulleted">Second[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="m-b" listType="bulleted">Child</paragraph>');

        // Selection is in the second block, so getItemBlocks must walk back to the first one.
        editor.execute("toggleListCollapse");

        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        expect(getBlock(editor, 1).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    it("treats a list block without a numeric indent as indent 0", () => {
        // listItemId present but no listIndent: getIndent falls back to 0, so a deeper sibling
        // still counts as nested and the item is collapsible.
        setModelData(editor.model,
            '<paragraph listItemId="n-a" listType="bulleted">Parent[]</paragraph>' +
            '<paragraph listIndent="1" listItemId="n-b" listType="bulleted">Child</paragraph>');

        const command = editor.commands.get("toggleListCollapse");
        expect(command?.isEnabled).toBe(true);

        editor.execute("toggleListCollapse");
        expect(getBlock(editor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
    });

    describe("find-in-note reveal", () => {
        // A fresh editor *with* the find plugin (the default one above deliberately has none, so
        // the "no find plugin" early-return stays exercised). The parent is collapsed, hiding
        // "Child" and "Other child".
        async function createCollapsedFindEditor(): Promise<ClassicEditor> {
            const findEditor = await createTestEditor([CollapsibleListItems, List, TodoList, Paragraph, Typing, Undo, FindAndReplace]);
            setModelData(findEditor.model, LIST_FIXTURE);
            findEditor.execute("toggleListCollapse");
            return findEditor;
        }

        function collapsedItem(findEditor: ClassicEditor): { li: HTMLElement; nested: HTMLElement } {
            const li = findEditor.editing.view.getDomRoot()?.querySelector<HTMLElement>('li[data-trilium-collapsed="true"]');
            const nested = li?.querySelector<HTMLElement>("ul");
            if (!li || !nested) {
                throw new Error("Expected a collapsed list item with a hidden nested list.");
            }
            return { li, nested };
        }

        it("reveals a collapsed item to show a match inside it and follows the highlight, without persisting", async () => {
            const findEditor = await createCollapsedFindEditor();
            const { li, nested } = collapsedItem(findEditor);
            expect(getComputedStyle(nested).display).toBe("none");

            findEditor.execute("find", "child"); // first match: "Child", hidden under the collapsed parent

            expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);
            expect(getComputedStyle(nested).display).not.toBe("none");

            // Advancing to the sibling match keeps the same ancestor revealed (no churn, no error).
            findEditor.execute("findNext"); // "Other child", still under the same collapsed parent
            expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);

            // The persisted collapsed state is never touched — search must not rewrite the layout.
            expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
            expect(findEditor.getData()).toContain('data-trilium-collapsed="true"');
        });

        it("re-collapses once the search is cleared", async () => {
            const findEditor = await createCollapsedFindEditor();
            const { li, nested } = collapsedItem(findEditor);

            findEditor.execute("find", "child");
            expect(getComputedStyle(nested).display).not.toBe("none");

            findEditor.plugins.get(FindAndReplaceEditing).state?.clear(findEditor.model);

            expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(false);
            expect(getComputedStyle(nested).display).toBe("none");
        });

        it("reveals a collapsed item around a position that FindReveal shows", async () => {
            const findEditor = await createTestEditor([
                CollapsibleListItems, List, TodoList, Paragraph, Typing, Undo, FindAndReplace,
                FindReveal
            ]);
            setModelData(findEditor.model, LIST_FIXTURE);
            findEditor.execute("toggleListCollapse");
            const { li } = collapsedItem(findEditor);
            const findReveal = findEditor.plugins.get(FindReveal);

            findReveal.show(findEditor.model.createPositionAt(getBlock(findEditor, 1), 0));
            expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);

            findReveal.show(null);
            expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(false);
            expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
        });

        it("does not permanently expand when the search closes with the highlight inside the item", async () => {
            const findEditor = await createCollapsedFindEditor();
            const { nested } = collapsedItem(findEditor);

            findEditor.execute("find", "Other child");
            expect(getComputedStyle(nested).display).not.toBe("none");

            // Reproduce find_in_text.findBoxClosed: clear the highlight, then drop the caret on the
            // match. Both are synchronous, so the "find is closing" window is still open here.
            const state = findEditor.plugins.get(FindAndReplaceEditing).state;
            const range = state?.highlightedResult?.marker?.getRange();
            expect(range).toBeTruthy();
            state?.clear(findEditor.model);
            if (range) {
                findEditor.model.change((writer) => writer.setSelection(range));
            }

            // The item stays collapsed (saved layout intact) instead of expanding...
            expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
            expect(getComputedStyle(nested).display).toBe("none");
            // ...and the caret sits on the collapsed item's own line, not stranded in the hidden child.
            expect(findEditor.model.document.selection.getFirstPosition()?.parent).toBe(getBlock(findEditor, 0));
        });
    });
});

function getBlock(editor: ClassicEditor, index: number): ModelElement {
    const child = editor.model.document.getRoot()?.getChild(index);
    if (!child || !child.is("element")) {
        throw new Error(`No element block at index ${index}.`);
    }
    return child;
}

function setSelectionIn(editor: ClassicEditor, blockIndex: number): void {
    editor.model.change((writer) => {
        writer.setSelection(writer.createPositionAt(getBlock(editor, blockIndex), 0));
    });
}

function pressCtrlAltEnter(editor: ClassicEditor): void {
    editor.editing.view.document.fire("keydown", {
        keyCode: keyCodes.enter,
        ctrlKey: true,
        altKey: true,
        preventDefault: () => {},
        stopPropagation: () => {}
    });
}

function pressCtrlEnter(editor: ClassicEditor): void {
    editor.editing.view.document.fire("keydown", {
        keyCode: keyCodes.enter,
        ctrlKey: true,
        preventDefault: () => {}
    });
}

function pressEnter(editor: ClassicEditor, isSoft = false): void {
    editor.editing.view.document.fire("enter", { preventDefault: () => {}, isSoft });
}

/**
 * On-screen centre of the arrow drawn next to a list item, read back from the stylesheet rather
 * than restated here: the arrow is a pseudo-element (so it has no rect of its own), but its
 * resolved box is offset from the item, and `translateY(-50%)` puts its centre exactly at `top`.
 * Insets differ per list type — to-do items have no marker to clear — so hardcoding one would
 * make these tests aim at the wrong spot as soon as the CSS moves.
 */
function arrowCentre(item: HTMLElement): { x: number; y: number } {
    const rect = item.getBoundingClientRect();
    const arrow = getComputedStyle(item, "::before");

    return {
        x: Math.round(rect.left + parseFloat(arrow.left) + parseFloat(arrow.width) / 2),
        y: Math.round(rect.top + parseFloat(arrow.top))
    };
}

function mouseMoveAt(clientX: number, clientY: number, buttons = 0): void {
    document.elementFromPoint(clientX, clientY)
        ?.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX, clientY, buttons }));
}

function mouseDownAt(item: HTMLElement, offsetX: number): void {
    const rect = item.getBoundingClientRect();
    item.dispatchEvent(new MouseEvent("mousedown", {
        bubbles: true,
        cancelable: true,
        clientX: rect.left + offsetX,
        clientY: rect.top + 5
    }));
}