Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/collections/board: show a toolbar when tapping a column header on mobile
Adorian Doranb9e935a6b6c3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex e95ac4d688..9dcafbecdb 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3575,7 +3575,8 @@"cards-selected_one": "{{count}} card selected","cards-selected_other": "{{count}} cards selected","select-column-cards": "Select every card in the column",- "reset-selection": "Reset the selection"+ "reset-selection": "Reset the selection",+ "expand-column": "Expand column"},"dashboard_view": {"refresh-widget": "Refresh",diff --git a/apps/client/src/widgets/collections/board/board_drag.spec.tsx b/apps/client/src/widgets/collections/board/board_drag.spec.tsxindex 7f4a316c60..7f7e9d2bc4 100644--- a/apps/client/src/widgets/collections/board/board_drag.spec.tsx+++ b/apps/client/src/widgets/collections/board/board_drag.spec.tsx@@ -415,18 +415,28 @@ describe("useBoardDrag, carrying a card", () => {expect(followed.defaultPrevented).toBe(false);});- /** The heading answers for a column's menu, the column itself holding no handler. */- it("asks a column's heading for its menu when it is tapped", () => {+ /** A tap on a heading is a click on it, which focuses the heading; its menu is on a button. */+ it("leaves a tap on a heading to the click it lands", () => {setup();const heading = board.querySelector<HTMLElement>(".board-column h3");if (!heading) throw new Error("expected a heading");const menus: string[] = [];+ const clicks: boolean[] = [];heading.addEventListener("contextmenu", () => menus.push("heading"));+ board.addEventListener("click", (event) => clicks.push(event.defaultPrevented));press(heading, 10, 10, "touch");release(11, 11, "touch");+ act(() => {+ heading.dispatchEvent(new Event("click", { bubbles: true, cancelable: true }));+ });- expect(menus).toEqual([ "heading" ]);+ expect(menus).toEqual([]);+ expect(clicks).toEqual([ false ]);++ const followed = new Event("touchend", { bubbles: true, cancelable: true });+ act(() => { document.dispatchEvent(followed); });+ expect(followed.defaultPrevented).toBe(false);});/**@@ -454,45 +464,6 @@ describe("useBoardDrag, carrying a card", () => {expect(clicks).toEqual([ "click" ]);});- it("leaves the click a tap on a heading also lands unanswered", () => {- setup();- const heading = board.querySelector<HTMLElement>(".board-column h3");- if (!heading) throw new Error("expected a heading");- const clicks: boolean[] = [];- board.addEventListener("click", (event) => clicks.push(event.defaultPrevented));-- press(heading, 10, 10, "touch");- release(11, 11, "touch");- act(() => {- heading.dispatchEvent(new Event("click", { bubbles: true, cancelable: true }));- });-- expect(clicks).toEqual([]);- });-- /**- * A browser follows a tap with mouse events for pages that know nothing of touch. They land on- * the menu the tap just opened, right under the finger, and the first of them takes it back off- * again. They are made from `touchend`, so that is where they are refused.- */- it("refuses the mouse events a browser would make from a tap", () => {- setup();- const heading = board.querySelector<HTMLElement>(".board-column h3");- if (!heading) throw new Error("expected a heading");-- press(heading, 10, 10, "touch");- release(11, 11, "touch");-- const followed = new Event("touchend", { bubbles: true, cancelable: true });- act(() => { document.dispatchEvent(followed); });- expect(followed.defaultPrevented).toBe(true);-- // Once only: the next touch of the reader's own is theirs to have.- const later = new Event("touchend", { bubbles: true, cancelable: true });- act(() => { document.dispatchEvent(later); });- expect(later.defaultPrevented).toBe(false);- });-/** A press that became a drag is not a tap, and its `touchend` is the browser's to answer. */it("leaves the touch that carried a card alone", () => {setup();diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.tsindex 2e0ee4b14b..e439db5a71 100644--- a/apps/client/src/widgets/collections/board/board_drag.ts+++ b/apps/client/src/widgets/collections/board/board_drag.ts@@ -484,33 +484,13 @@ export function useBoardDrag(const held = gesture.current;if (!held || event.pointerId !== held.pointerId) return;- // A tap is a press that never became a drag: it asks for the menu, the long press that- // would have opened one being how a finger picks a card up instead.- const tapped = held.touch && !held.active && event.type === "pointerup"- && Math.hypot(event.clientX - held.startX, event.clientY - held.startY)- <= TOUCH_TOLERANCE;+ // A tap is a press that never became a drag, and is left to the click it lands: a+ // card opens, a strip opens its column, a heading takes the focus. Each carries its+ // menu on a button, the long press being how a finger picks something up.const dragged = held.active && event.type === "pointerup";- const target = held.menuTarget;- // A tap on a card is left to the click it lands, which opens the card, and a tap on a- // collapsed column opens it: that is what the strip is for, and its menu is on the- // button it carries. A column's heading answers a tap with its menu, the long press- // that would otherwise open one being how a finger picks something up.- const isLeftToClick = held.kind === "card"- || target.closest(".board-column")?.classList.contains("collapsed");close(event.type === "pointercancel");- if (tapped && !isLeftToClick) {- // The browser follows a tap with mouse events for pages that know nothing of touch,- // and they land on the menu this is about to open, right under the finger: the- // first of them takes the menu straight back off again. Refused at `touchend`,- // which is what the browser makes them from, and which has yet to be sent.- justTapped = true;- // The click is left out as well, for a browser that sends one regardless.- swallowNextClick();- askForMenu(target, event.clientX, event.clientY);- }-// A mouse drag is followed by a click on whatever the press and the release have in// common, which for a card carried anywhere is the board itself. Taken here, so that// what a click on the board means is not also what letting go of a card means.@@ -531,16 +511,6 @@ export function useBoardDrag(COMPATIBILITY_WINDOW_MS);};- /** Set between a tap and the `touchend` the browser would make mouse events from. */- let justTapped = false;-- const onTouchEnd = (event: TouchEvent) => {- if (justTapped) {- justTapped = false;- event.preventDefault();- }- };-const swallow = (event: Event) => {event.preventDefault();event.stopPropagation();@@ -578,7 +548,6 @@ export function useBoardDrag(container.addEventListener("pointercancel", onPointerUp);document.addEventListener("keydown", onKeyDown);document.addEventListener("touchmove", onTouchMove, { passive: false });- document.addEventListener("touchend", onTouchEnd, { passive: false });return () => {close(true);@@ -591,7 +560,6 @@ export function useBoardDrag(container.removeEventListener("pointercancel", onPointerUp);document.removeEventListener("keydown", onKeyDown);document.removeEventListener("touchmove", onTouchMove);- document.removeEventListener("touchend", onTouchEnd);container.removeEventListener("click", swallow, { capture: true });};}, [ container, disabled ]);@@ -727,7 +695,6 @@ function startCard(return {kind: "card",element,- menuTarget: element,card: {noteId,noteIds,@@ -771,7 +738,6 @@ function startColumn(target: HTMLElement, container: HTMLElement): ColumnSubjectreturn {kind: "column",element,- menuTarget: heading,column: element.dataset.column ?? "",index: columns.indexOf(element),target: null@@ -881,8 +847,6 @@ function countPreview(count: number) {interface CardSubject {kind: "card";element: HTMLElement;- /** What a tap asks for the menu, which for a column is its heading rather than the column. */- menuTarget: HTMLElement;card: DraggedCard;position: DropPosition | null;/** The column the card stands on, if any, which resting there opens. */@@ -896,7 +860,6 @@ interface CardSubject {interface ColumnSubject {kind: "column";element: HTMLElement;- menuTarget: HTMLElement;column: string;/** Where it stands among the columns, counting them as they are drawn. */index: number;diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex f2cf165660..7b2c560a70 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -310,8 +310,9 @@ function Card({onDragStart={handleDragStart}onClick={!isEditing ? handleClick : undefined}onKeyDown={handleKeyDown}- onFocusIn={() => setIsFocused(true)}- onFocusOut={handleFocusOut}+ // Only where the rail follows the focus, so a desktop card is not redrawn for it.+ onFocusIn={isMobile() ? () => setIsFocused(true) : undefined}+ onFocusOut={isMobile() ? handleFocusOut : undefined}tabIndex={300}>{!isEditing ? (diff --git a/apps/client/src/widgets/collections/board/card_toolbar.tsx b/apps/client/src/widgets/collections/board/card_toolbar.tsxindex d9ceededa9..efdaa6fe25 100644--- a/apps/client/src/widgets/collections/board/card_toolbar.tsx+++ b/apps/client/src/widgets/collections/board/card_toolbar.tsx@@ -186,6 +186,49 @@ export function SelectionToolbar({);}+interface ColumnToolbarProps {+ host: HTMLElement;+ isLeaving: boolean;+ /** Whether the column is drawn as a strip, which offers nothing but to open it. */+ isCollapsed: boolean;+ onRename: () => void;+ onToggleCollapse: () => void;+ /** Opens the sort menu, which on mobile is a sheet at the foot of the screen. */+ onSort: (event: MouseEvent) => void;+ onFocusOut: (event: FocusEvent) => void;+}++/** What can be done with the focused column, on the same rail. The icons are the column menu's. */+export function ColumnToolbar({+ host, isLeaving, isCollapsed, onRename, onToggleCollapse, onSort, onFocusOut+}: ColumnToolbarProps) {+ return (+ <Rail host={host} isLeaving={isLeaving} onFocusOut={onFocusOut}>+ {!isCollapsed && (+ <OverlayControlButton+ title={t("board_view.rename-column")}+ icon="bx-edit-alt"+ onClick={onRename}+ />+ )}+ <OverlayControlButton+ title={isCollapsed+ ? t("board_view.expand-column")+ : t("board_view.collapse-column")}+ icon={isCollapsed ? "bx-expand-horizontal" : "bx-collapse-horizontal"}+ onClick={onToggleCollapse}+ />+ {!isCollapsed && (+ <OverlayControlButton+ title={t("board_view.sort")}+ icon="bx-sort-alt-2"+ onClick={onSort}+ />+ )}+ </Rail>+ );+}+interface RailProps {host: HTMLElement;isLeaving: boolean;diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 6229b431f6..37efb505da 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -14,11 +14,12 @@ import dialog from "../../../services/dialog";import { getHue, parseColor } from "../../../services/css_class_manager";import froca from "../../../services/froca";import { t } from "../../../services/i18n";+import { isMobile } from "../../../services/utils";import { DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";import ActionButton from "../../react/ActionButton";import Icon from "../../react/Icon";import { IconPickerButton } from "../../react/IconPicker";-import { useStaticTooltip } from "../../react/hooks";+import { useIsOnScreen, useLingeringTrue, useStaticTooltip } from "../../react/hooks";import { useFlip } from "../../react/flip";import { useScrollFade } from "../../react/scroll_fade";@@ -38,12 +39,15 @@ const MIN_CARD_HEIGHT = 32;/** How long an open takes. Matches `--board-expand-duration` in the board's own rules. */export const EXPAND_MS = 200;import NoteLink from "../../react/NoteLink";-import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";+import {+ BoardActionsContext, BoardDragStateContext, BoardOverlayHostContext, TitleEditor+} from ".";import BoardApi from "./api";import Card from "./card";import CardTemplatePill from "./card_template_pill";import { cardTemplateIcon, type CardTemplates } from "./card_templates";import { DEFAULT_CARD_ICON, DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";+import { ColumnToolbar, RAIL_EXIT_MS } from "./card_toolbar";import { openColumnContextMenu, openColumnSortMenu, openCreateCardMenu } from "./context_menu";import type { ColumnSort } from "./data";import { cardSpacing } from "./drag_measure";@@ -514,6 +518,25 @@ export default function Column({}}, [ column, isCollapsed ]);+ const overlayHost = useContext(BoardOverlayHostContext);+ /** Whether the heading holds the focus, which on mobile floats the column's rail. */+ const [ isHeaderFocused, setIsHeaderFocused ] = useState(false);+ // Focus moving within the heading or onto the rail keeps the rail; anywhere else takes it.+ const handleHeaderFocusOut = useCallback((e: FocusEvent) => {+ const next = e.relatedTarget instanceof Element ? e.relatedTarget : null;+ if (next && (headerRef.current?.contains(next) || next.closest(".board-card-toolbar"))) {+ return;+ }++ setIsHeaderFocused(false);+ }, []);+ // Off the heading while its title is edited, since the rename it offers is under way.+ const isRailWanted = isMobile() && isHeaderFocused && !isEditing;+ const isHeaderOnScreen = useIsOnScreen(headerRef, isRailWanted);+ const isRailShown = isRailWanted && isHeaderOnScreen;+ // Kept drawn while it slides off.+ const isRailDrawn = useLingeringTrue(isRailShown, RAIL_EXIT_MS);+/** Allow using mouse wheel to scroll inside card, while also maintaining column horizontal scrolling. */const handleScroll = useCallback((event: JSX.TargetedWheelEvent<HTMLDivElement>) => {const el = event.currentTarget;@@ -674,6 +697,12 @@ export default function Column({}}}onKeyDown={handleTitleKeyDown}+ // Only where the rail follows the focus: elsewhere a redraw on every focus+ // change buys nothing, and would write a controlled editor's value back mid-edit.+ onFocusIn={isMobile() ? () => setIsHeaderFocused(true) : undefined}+ onFocusOut={isMobile() ? handleHeaderFocusOut : undefined}+ // A tap takes the focus, which not every touch browser gives a heading on its own.+ onClick={isMobile() ? () => headerRef.current?.focus() : undefined}tabIndex={300}>{isCollapsed ? (@@ -793,6 +822,17 @@ export default function Column({<div ref={roomRef} className="board-drop-room" /></div>}+ {isRailDrawn && overlayHost.current && (+ <ColumnToolbar+ host={overlayHost.current}+ isLeaving={!isRailShown}+ isCollapsed={isCollapsed}+ onRename={() => setColumnNameToEdit(column)}+ onToggleCollapse={isCollapsed ? select : collapse}+ onSort={(e) => openColumnSortMenu(api, e.pageX, e.pageY, column)}+ onFocusOut={handleHeaderFocusOut}+ />+ )}{!isCollapsed && <AddNewItemapi={api}cardTemplates={cardTemplates}diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 5485811e6a..d929c7c36f 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -5274,3 +5274,119 @@ describe("Selection mode on mobile", () => {expect(bar()).toBeNull();});});++describe("Column toolbar on mobile", () => {+ let container: HTMLElement;+ let host: Component;++ beforeEach(() => {+ layout.onMobile = true;+ });++ afterEach(() => {+ layout.onMobile = false;+ vi.useRealTimers();+ saved.length = 0;+ render(null, container);+ container.remove();+ });++ async function setup() {+ disposeShownModals();++ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { id: "head1", title: "First", "#status": "To Do" },+ { id: "head2", title: "Second", "#status": "Done" }+ ]+ });++ host = new Component();+ container = document.body.appendChild(document.createElement("div"));+ await act(async () => {+ render(+ <ParentComponent.Provider value={host}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={{ columns: [ { value: "To Do" }, { value: "Done" } ] }}+ />+ </ParentComponent.Provider>,+ container+ );+ });+ await act(async () => { await flush(); });++ return note;+ }++ function heading(index: number) {+ const element = container.querySelectorAll<HTMLElement>(".board-column h3")[index];+ if (!element) throw new Error(`expected the heading of column ${index}`);+ return element;+ }++ const column = (index: number) => container.querySelectorAll(".board-column")[index];+ const toolbar = () => container.querySelector<HTMLElement>(".board-card-toolbar");+ const buttons = () => [ ...toolbar()?.querySelectorAll("button") ?? [] ]+ .map(button => [ ...button.classList ].find(name => name.startsWith("bx-")));++ function button(icon: string) {+ const element = toolbar()?.querySelector<HTMLElement>(`button.${icon}`);+ if (!element) throw new Error(`expected a ${icon} button`);+ return element;+ }++ async function letRailLeave() {+ await act(async () => { vi.advanceTimersByTime(RAIL_EXIT_MS); });+ }++ it("follows the focus onto a heading, which a tap gives it", async () => {+ await setup();+ expect(toolbar()).toBeNull();++ // A tap is a click, and on mobile the heading takes the focus from it.+ await act(async () => { heading(0).click(); });+ expect(document.activeElement).toBe(heading(0));+ expect(buttons()).toEqual([ "bx-edit-alt", "bx-collapse-horizontal", "bx-sort-alt-2" ]);++ vi.useFakeTimers();+ await act(async () => { heading(0).blur(); });+ await letRailLeave();+ expect(toolbar()).toBeNull();+ });++ it("collapses and opens the column, offering only the open on a strip", async () => {+ await setup();+ await act(async () => { heading(0).focus(); });++ await act(async () => { button("bx-collapse-horizontal").click(); });+ expect(column(0).classList.contains("collapsed")).toBe(true);+ expect(buttons()).toEqual([ "bx-expand-horizontal" ]);++ await act(async () => { button("bx-expand-horizontal").click(); });+ expect(column(0).classList.contains("collapsed")).toBe(false);+ expect(buttons()).toEqual([ "bx-edit-alt", "bx-collapse-horizontal", "bx-sort-alt-2" ]);+ });++ it("opens the sort menu and the title editor", async () => {+ await setup();+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});+ await act(async () => { heading(0).focus(); });++ await act(async () => { button("bx-sort-alt-2").click(); });+ expect(show).toHaveBeenCalledTimes(1);++ // The rename opens the editor in the heading, and the rail stands aside while it is open.+ vi.useFakeTimers();+ await act(async () => { button("bx-edit-alt").click(); });+ await letRailLeave();+ expect(heading(0).querySelector("input, textarea")).toBeTruthy();+ expect(toolbar()).toBeNull();++ show.mockRestore();+ });+});