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: tweak the card toolbar
Adorian Doran1174716067c4
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsxindex 87bebdff6a..f2cf165660 100644--- a/apps/client/src/widgets/collections/board/card.tsx+++ b/apps/client/src/widgets/collections/board/card.tsx@@ -26,9 +26,10 @@ import {} from "../../react/hooks";import { TooltipIcon } from "../../react/Icon";import { HighlightedText } from "../../react/RawHtml";+import { useIsOnScreen, useLingeringTrue } from "../../react/hooks";import { useIsSelected, useSelection } from "../../react/selection";import { type DragData, TREE_CLIPBOARD_TYPE } from "../../note_tree";-import CardToolbar from "./card_toolbar";+import CardToolbar, { RAIL_EXIT_MS } from "./card_toolbar";function Card({api,@@ -111,6 +112,18 @@ function Card({setIsFocused(false);}, []);+ /**+ * Whether the card's rail is wanted. Off the card while its title is edited, since the rename+ * it offers is under way, while it is carried, since the board is being rearranged under the+ * finger, and in selection mode, where the board's own rail acts on the selection instead.+ */+ const isRailWanted = isMobile() && isFocused && !isEditing && !isDragging && !isSelecting;+ // The rail stands for the card, so it goes when the card is scrolled off the screen entirely+ // and comes back with it.+ const isOnScreen = useIsOnScreen(cardRef, isRailWanted);+ const isRailShown = isRailWanted && isOnScreen;+ // Kept drawn while it slides off.+ const isRailDrawn = useLingeringTrue(isRailShown, RAIL_EXIT_MS);const isSelected = useIsSelected(note.noteId);// A card owns its own title: the board does not redraw for a note-row change. Setting the value@@ -342,13 +355,10 @@ function Card({badges={isOutsideFilter && <OutsideFilterBadge />}/></div>- {/* Off the card while its title is edited, since the rename it offers is under way, while- it is carried, since the board is being rearranged under the finger, and in selection- mode, where the board's own rail acts on the selection instead. */}- {isMobile() && isFocused && !isEditing && !isDragging && !isSelecting- && overlayHost.current && (+ {isRailDrawn && overlayHost.current && (<CardToolbarhost={overlayHost.current}+ isLeaving={!isRailShown}isSorted={api.isColumnSorted(column)}removal={api.isInboxEnabled ? "note" : "board"}onRename={() => setBranchIdToEdit(branch.branchId)}diff --git a/apps/client/src/widgets/collections/board/card_toolbar.css b/apps/client/src/widgets/collections/board/card_toolbar.cssindex c1640dea2d..dbed50ecf3 100644--- a/apps/client/src/widgets/collections/board/card_toolbar.css+++ b/apps/client/src/widgets/collections/board/card_toolbar.css@@ -1,12 +1,59 @@+:where(:root) {+ --board-rail-enter-duration: 250ms;+ /* Must match RAIL_EXIT_MS in card_toolbar.tsx, which keeps the rail drawn that long. */+ --board-rail-exit-duration: 400ms;+}+/* Laid out by the group, which pins itself over the board: the wrapper is there for its events. */.board-view-container .board-card-toolbar {display: contents;}+/* In over the edge it stands against, and back out over it when dismissed. */+.board-view-container .board-card-toolbar .tn-overlay-control-group {+ animation: board-rail-enter var(--board-rail-enter-duration) ease-out;+}++/* Standing in for a rail already there, which is dropped as this one arrives. Above the leaving+ rule, which must still win for a rail that later leaves. */+.board-view-container .board-card-toolbar.takes-over .tn-overlay-control-group {+ animation: none;+}++.board-view-container .board-card-toolbar.leaving .tn-overlay-control-group {+ animation: board-rail-leave var(--board-rail-exit-duration) ease-in forwards;+ pointer-events: none;+}++@keyframes board-rail-enter {+ from {+ transform: translateX(100%);+ }+}++@keyframes board-rail-leave {+ to {+ transform: translateX(100%);+ }+}++@media (prefers-reduced-motion: reduce) {+ .board-view-container .board-card-toolbar .tn-overlay-control-group,+ .board-view-container .board-card-toolbar.leaving .tn-overlay-control-group {+ animation: none;+ }++ /* Gone at once rather than standing still for the exit's length. */+ .board-view-container .board-card-toolbar.leaving {+ display: none;+ }+}+/* Hidden while a card is carried, under the class board_drag.ts sets on the container itself: a- class rendered from state changes the attribute mid-drag and drops that one, and its auto-scroll. */+ class rendered from state changes the attribute mid-drag and drops that one, and its auto-scroll.+ Visibility rather than display, which restarts the entrance when the drag ends. */.board-view-container.board-dragging .board-card-toolbar {- display: none;+ visibility: hidden;}.board-view-container .board-card-toolbar .tn-overlay-control-group {diff --git a/apps/client/src/widgets/collections/board/card_toolbar.tsx b/apps/client/src/widgets/collections/board/card_toolbar.tsxindex 31a4084246..d9ceededa9 100644--- a/apps/client/src/widgets/collections/board/card_toolbar.tsx+++ b/apps/client/src/widgets/collections/board/card_toolbar.tsx@@ -1,14 +1,76 @@import "./card_toolbar.css";-import { type ComponentChildren } from "preact";-import { createPortal } from "preact/compat";+import clsx from "clsx";+import { type ComponentChildren, createContext } from "preact";+import { createPortal, useSyncExternalStore } from "preact/compat";+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n";import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";+/**+ * How long the rail takes to slide off, which is how long whoever draws it keeps drawing it once it+ * is dismissed (see `useLingeringTrue`). Matches `--board-rail-exit-duration` in card_toolbar.css.+ */+export const RAIL_EXIT_MS = 400;++/**+ * Which rail stands on a board, one at a time. A rail arriving while another stands takes over in+ * place, neither sliding in over it nor waiting for it to slide off: the one it replaces is dropped+ * at once. A rail keeps its stand while it slides off, so a newcomer takes over from that too.+ */+export class RailStand {+ private owner: object | null = null;+ /** The rails another took over from, which stay dropped even once the stand is free again. */+ private superseded = new WeakSet<object>();+ private listeners = new Set<() => void>();++ /** Whether any rail stands, the one leaving included. */+ get isTaken() {+ return this.owner !== null;+ }++ isSuperseded(token: object) {+ return this.superseded.has(token);+ }++ claim(token: object) {+ if (this.owner === token) return;+ if (this.owner !== null) {+ this.superseded.add(this.owner);+ }+ this.owner = token;+ this.notify();+ }++ /** Gives the stand up, unless another rail has taken it over meanwhile. */+ release(token: object) {+ this.superseded.delete(token);+ if (this.owner !== token) return;+ this.owner = null;+ this.notify();+ }++ subscribe(listener: () => void) {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ }++ private notify() {+ for (const listener of [ ...this.listeners ]) {+ listener();+ }+ }+}++/** The board's stand, provided by the board so that two boards side by side keep their own. */+export const BoardRailContext = createContext(new RailStand());+interface CardToolbarProps {/** The board's element, which the toolbar floats over rather than the card it belongs to. */host: HTMLElement;+ /** Whether the rail is on its way off, sliding back over the edge it came from. */+ isLeaving: boolean;/** Whether the column places its cards itself, which leaves one place to insert at. */isSorted: boolean;/**@@ -35,11 +97,11 @@ interface CardToolbarProps {* follows the focus, and is hidden while a card is carried (see card_toolbar.css).*/export default function CardToolbar({- host, isSorted, removal, onRename, onInsertAbove, onInsertBelow, onInsertNew, onRemove,- onMore, onFocusOut+ host, isLeaving, isSorted, removal, onRename, onInsertAbove, onInsertBelow, onInsertNew,+ onRemove, onMore, onFocusOut}: CardToolbarProps) {return (- <Rail host={host} onFocusOut={onFocusOut}>+ <Rail host={host} isLeaving={isLeaving} onFocusOut={onFocusOut}><OverlayControlButtontitle={t("board_view.edit-title")}icon="bx-rename"@@ -90,6 +152,7 @@ export default function CardToolbar({interface SelectionToolbarProps {host: HTMLElement;+ isLeaving: boolean;/** How many cards are picked out. With none, there is nothing to press. */count: number;onDelete: () => void;@@ -101,9 +164,11 @@ interface SelectionToolbarProps {* What can be done with the cards picked out in selection mode: deleting them, or opening the* menu for all of them. Stands in for the focused card's rail while the mode lasts.*/-export function SelectionToolbar({ host, count, onDelete, onMore }: SelectionToolbarProps) {+export function SelectionToolbar({+ host, isLeaving, count, onDelete, onMore+}: SelectionToolbarProps) {return (- <Rail host={host}>+ <Rail host={host} isLeaving={isLeaving}><OverlayControlButtontitle={t("board_view.delete-note")}icon="bx-trash"@@ -123,15 +188,36 @@ export function SelectionToolbar({ host, count, onDelete, onMore }: SelectionToointerface RailProps {host: HTMLElement;+ isLeaving: boolean;onFocusOut?: (event: FocusEvent) => void;children: ComponentChildren;}-/** The rail itself, flush with the board's trailing edge; what stands on it is the caller's. */-function Rail({ host, onFocusOut, children }: RailProps) {+/**+ * The rail itself, flush with the board's trailing edge; what stands on it is the caller's. It+ * slides in over that edge, and back out over it while `isLeaving` (see card_toolbar.css), unless+ * it takes over from another rail or another takes over from it (see {@link RailStand}).+ */+function Rail({ host, isLeaving, onFocusOut, children }: RailProps) {+ const stand = useContext(BoardRailContext);+ const token = useRef({}).current;+ // Decided as the rail arrives: whether it takes over in place rather than sliding in.+ const [ tookOver ] = useState(() => stand.isTaken);+ useEffect(() => {+ stand.claim(token);+ return () => stand.release(token);+ }, [ stand, token ]);+ const isSuperseded = useSyncExternalStore(+ useCallback((listener: () => void) => stand.subscribe(listener), [ stand ]),+ useCallback(() => stand.isSuperseded(token), [ stand, token ]));++ if (isLeaving && isSuperseded) {+ return null;+ }+return createPortal(<div- className="board-card-toolbar"+ className={clsx("board-card-toolbar", { leaving: isLeaving, "takes-over": tookOver })}// A press must not move the focus off the card, which would close the toolbar under// the finger, nor reach the board, which would take it for the start of a pan. Nor// the click: to the board, a click outside a card gives the selection up.diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 24da10de12..5485811e6a 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -30,6 +30,7 @@ import BoardView, { BoardViewData } from ".";import { getNoteTypeOptions, type NoteTypeOption } from "../../../services/note_types";import { collectShortcutHints } from "../../../services/shortcut_hints";import BoardApi, { getPendingWrites } from "./api";+import { RAIL_EXIT_MS } from "./card_toolbar";import { DEFAULT_COLUMN_ICON } from "./columns";// Stands in for the server: by the time the bulk action resolves, the notes carry the new value,@@ -4790,11 +4791,34 @@ describe("Card toolbar on mobile", () => {let container: HTMLElement;let host: Component;+ /** Stands in for the observer the rail watches its card with, and reports on request. */+ class MockIntersectionObserver {+ static instances: MockIntersectionObserver[] = [];+ observe = vi.fn();+ disconnect = vi.fn();++ constructor(readonly callback: IntersectionObserverCallback) {+ MockIntersectionObserver.instances.push(this);+ }++ report(isIntersecting: boolean) {+ this.callback(+ [ { isIntersecting } as IntersectionObserverEntry ],+ this as unknown as IntersectionObserver);+ }+ }+ let realIntersectionObserver: typeof IntersectionObserver;+beforeEach(() => {layout.onMobile = true;+ MockIntersectionObserver.instances = [];+ realIntersectionObserver = window.IntersectionObserver;+ window.IntersectionObserver =+ MockIntersectionObserver as unknown as typeof IntersectionObserver;});afterEach(() => {+ window.IntersectionObserver = realIntersectionObserver;layout.onMobile = false;vi.useRealTimers();saved.length = 0;@@ -4860,6 +4884,11 @@ describe("Card toolbar on mobile", () => {await act(async () => { card(noteId).focus(); });}+ /** Lets a dismissed rail finish sliding off, after which it is gone. Needs fake timers. */+ async function letRailLeave() {+ await act(async () => { vi.advanceTimersByTime(RAIL_EXIT_MS); });+ }+it("follows the focus onto a card and leaves with it, over the board", async () => {await setup();expect(toolbar()).toBeNull();@@ -4881,10 +4910,65 @@ describe("Card toolbar on mobile", () => {button("bx-rename").dispatchEvent(press);expect(press.defaultPrevented).toBe(true);+ // Dismissed, it slides off before it goes, and takes no press meanwhile.+ vi.useFakeTimers();await act(async () => { card("tool1").blur(); });+ expect(toolbar()?.classList.contains("leaving")).toBe(true);+ await letRailLeave();expect(toolbar()).toBeNull();});+ /**+ * Focus moving from one card to another hands the rail over: the newcomer stands in place+ * without sliding in, and the rail it replaces is dropped rather than left sliding off.+ */+ it("hands over between cards without sliding out and in", async () => {+ await setup();+ await focus("tool1");+ expect(toolbar()?.classList.contains("takes-over")).toBe(false);++ await focus("tool2");+ const rails = container.querySelectorAll(".board-card-toolbar");+ expect(rails).toHaveLength(1);+ expect(rails[0].classList.contains("takes-over")).toBe(true);+ expect(rails[0].classList.contains("leaving")).toBe(false);++ // The one standing slides off on its own once nothing takes over from it.+ vi.useFakeTimers();+ await act(async () => { card("tool2").blur(); });+ expect(toolbar()?.classList.contains("leaving")).toBe(true);+ await letRailLeave();+ expect(toolbar()).toBeNull();+ });++ /**+ * The rail stands for the card, so a card scrolled off the screen entirely takes it along,+ * and brings it back. Watched only while the rail is wanted: the observer goes with the focus.+ */+ it("goes off the screen with its card and comes back with it", async () => {+ await setup();+ expect(MockIntersectionObserver.instances).toHaveLength(0);++ await focus("tool1");+ expect(toolbar()).not.toBeNull();+ const observer = MockIntersectionObserver.instances.at(-1);+ if (!observer) throw new Error("expected the card to be watched");+ expect(observer.observe).toHaveBeenCalledWith(card("tool1"));++ vi.useFakeTimers();+ await act(async () => { observer.report(false); });+ await letRailLeave();+ expect(toolbar()).toBeNull();++ await act(async () => { observer.report(true); });+ expect(toolbar()?.classList.contains("leaving")).toBe(false);++ await act(async () => { card("tool1").blur(); });+ await letRailLeave();+ expect(toolbar()).toBeNull();+ expect(observer.disconnect).toHaveBeenCalled();+ });+it("is left out off mobile, where the card has its menu", async () => {layout.onMobile = false;await setup();@@ -4901,10 +4985,11 @@ describe("Card toolbar on mobile", () => {// Insert below opens the field under the card, which takes the focus and the rail with it.await focus("tool1");+ vi.useFakeTimers();await act(async () => {toolbar()?.querySelectorAll<HTMLElement>("button")[2].click();- await flush();});+ await letRailLeave();const column = container.querySelectorAll(".board-column")[0];const order = [ ...column.querySelectorAll(".board-note, .board-new-item.inserting") ].map(element => element.getAttribute("data-note-id") ?? "field");@@ -4914,6 +4999,7 @@ describe("Card toolbar on mobile", () => {// Rename opens the title editor in the card, and the rail stands aside while it is open.await focus("tool2");await act(async () => { button("bx-rename").click(); });+ await letRailLeave();expect(card("tool2").classList.contains("editing")).toBe(true);expect(toolbar()).toBeNull();diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 09bed9a16f..44d886a0ba 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -33,8 +33,9 @@ import { FormListItem } from "../../react/FormList";import FormTextArea from "../../react/FormTextArea";import FormTextBox from "../../react/FormTextBox";import {- useContextualShortcutHints, useNoteContext, useNoteLabel, useNoteLabelBoolean,- useNoteLabelWithDefault, useNoteTypeOptions, useSetContextData, useTrackedElement, useTriliumEvent+ useContextualShortcutHints, useLingeringTrue, useNoteContext, useNoteLabel,+ useNoteLabelBoolean, useNoteLabelWithDefault, useNoteTypeOptions, useSetContextData,+ useTrackedElement, useTriliumEvent} from "../../react/hooks";import Icon from "../../react/Icon";import NoteAutocomplete from "../../react/NoteAutocomplete";@@ -47,7 +48,7 @@ import { useDragPan } from "../../react/drag_pan";import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";import { SelectionContext, SelectionStore } from "../../react/selection";import { CollectionFilterInput, useCollectionFilter } from "../collection_filter";-import { SelectionToolbar } from "./card_toolbar";+import { BoardRailContext, RAIL_EXIT_MS, RailStand, SelectionToolbar } from "./card_toolbar";import BoardHeaderTools from "./selection_bar";import { ViewModeProps } from "../interface";import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";@@ -400,6 +401,7 @@ export default function BoardView({* card must wake that card and no other.*/const selection = useMemo(() => new SelectionStore(), []);+ const railStand = useMemo(() => new RailStand(), []);/*** Whether a tap picks a card out instead of opening it. Mobile only: a finger has no Ctrl to* pick cards out with. Leaving the mode gives the selection up as well.@@ -417,6 +419,8 @@ export default function BoardView({setIsSelecting(false);selection.clear();}, [ selection ]);+ // The selection's rail is kept drawn while it slides off.+ const isSelectionRailDrawn = useLingeringTrue(isMobile() && isSelecting, RAIL_EXIT_MS);const setDropPosition = useCallback((position: ColumnDrag | null) => {dropState.set({ ...dropState.get(), position });}, [ dropState ]);@@ -1412,6 +1416,7 @@ export default function BoardView({<SelectionContext.Provider value={selection}><BoardOverlayHostContext.Provider value={containerRef}><BoardSelectionModeContext.Provider value={isSelecting}>+ <BoardRailContext.Provider value={railStand}>{byColumn && columns && <divref={containerRef}className={clsx("board-view-container", {@@ -1542,9 +1547,10 @@ export default function BoardView({{/* Acts on the selection in place of the focused card's rail. The menu isasked of the card first picked out, whose own handler carries the wholeselection, the way a tap on a heading asks for a column's. */}- {isMobile() && isSelecting && containerRef.current && (+ {isSelectionRailDrawn && containerRef.current && (<SelectionToolbarhost={containerRef.current}+ isLeaving={!isSelecting}count={selectionCount}onDelete={() => branches.deleteNotes(api.getCards(selection.keys).map((card) => card.branch.branchId),@@ -1560,6 +1566,7 @@ export default function BoardView({}}/>)}+ </BoardRailContext.Provider></BoardSelectionModeContext.Provider></BoardOverlayHostContext.Provider></SelectionContext.Provider>diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex ea152e4171..f38fa4c2df 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -993,6 +993,52 @@ export function useElementSize(ref: RefObject<HTMLElement>) {* screen actually changed — a request the browser refuses (no user gesture behind it, a* policy against it) leaves the view exactly as it was.*/+/**+ * Whether any part of an element is on screen, for something that floats over the page on the+ * element's account and has no business there once the element is scrolled out of sight.+ *+ * Watched only while `enabled`, and true whenever it is not: an element that is not being watched+ * is taken as on screen, and watching starts from that until the observer says otherwise.+ */+export function useIsOnScreen(ref: RefObject<Element>, enabled: boolean) {+ const [ isOnScreen, setIsOnScreen ] = useState(true);++ useEffect(() => {+ const element = ref.current;+ if (!enabled || !element) {+ setIsOnScreen(true);+ return;+ }++ const observer = new IntersectionObserver(+ ([ entry ]) => setIsOnScreen(entry.isIntersecting));+ observer.observe(element);+ return () => observer.disconnect();+ }, [ ref, enabled ]);++ return isOnScreen;+}++/**+ * `value`, held at true for `ms` after it turns false, for something that leaves the page with an+ * animation: what draws it keeps drawing it that long, and tells it that it is leaving.+ */+export function useLingeringTrue(value: boolean, ms: number) {+ const [ isLingering, setIsLingering ] = useState(value);++ useEffect(() => {+ if (value) {+ setIsLingering(true);+ return;+ }++ const timer = window.setTimeout(() => setIsLingering(false), ms);+ return () => window.clearTimeout(timer);+ }, [ value, ms ]);++ return value || isLingering;+}+export function useFullscreen(element: HTMLElement | null | undefined, onChange?: () => void): [ boolean, () => Promise<boolean> ] {const [ isFullscreen, setFullscreen ] = useState(() => !!element && document.fullscreenElement === element);// Read afresh on every change rather than closed over, so that a listener bound once follows a