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: fix some issues
Adorian Doran964a2f6564ec
diff --git a/apps/client/src/components/component.spec.ts b/apps/client/src/components/component.spec.tsindex 13a0b4d27b..4bf040a815 100644--- a/apps/client/src/components/component.spec.ts+++ b/apps/client/src/components/component.spec.ts@@ -39,8 +39,8 @@ describe("Component handlers", () => {const component = new Component();const late = vi.fn();const removed = vi.fn();- // Subscribing and unsubscribing from inside a handler is what a hook does when an event- // makes it re-render, so neither may disturb the round it arrived in.+ // A hook subscribes and unsubscribes from inside a handler when an event makes it+ // re-render, and neither can disturb the round the event arrived in.const first = vi.fn(() => {register(component, late);component.removeHandler("entitiesReloaded" as never, removed);diff --git a/apps/client/src/components/component.ts b/apps/client/src/components/component.tsindex 3b3e11cc38..57c784ed96 100644--- a/apps/client/src/components/component.ts+++ b/apps/client/src/components/component.ts@@ -21,9 +21,9 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {initialized: Promise<void> | null;parent?: TypedComponent<any>;_position!: number;- // A set rather than an array: every froca hook re-subscribes whenever its handler changes- // identity, so a view with thousands of components registers and removes against a list- // thousands of entries long. Scanning it each time made that quadratic.+ // Held in a set so that registering and removing cost the same whatever the list already+ // holds: every froca hook re-subscribes whenever its handler changes identity, and a view of+ // thousands of components keeps thousands of handlers for one event.private listeners: Record<string, Set<EventHandler>> | null = {};constructor() {diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex c0cb1de37c..4cf69a4d82 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -35,6 +35,7 @@ import CardTemplatePill from "./card_template_pill";import { type CardTemplates } from "./card_templates";import { DEFAULT_CARD_ICON, DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";import { openColumnContextMenu, openCreateCardMenu } from "./context_menu";+import { BoardDropStateContext, useDropIndex, useIsDropTarget } from "./drop_state";interface DragContext {column: string;@@ -144,7 +145,11 @@ export default function Column({const [ isRevealed, setIsRevealed ] = useState(false);const { setColumnNameToEdit, setColumnLimitToEdit, setActiveColumn } =useContext(BoardActionsContext);- const { branchIdToEdit, columnNameToEdit, dropTarget, draggedCard, dropPosition } = useContext(BoardDragStateContext);+ const { branchIdToEdit, columnNameToEdit, draggedCard } = useContext(BoardDragStateContext);+ // Asked about this column alone: where the gap stands changes on every step of a drag, and a+ // column that the answer does not concern is left as it is rather than drawn again.+ const dropIndex = useDropIndex(column);+ const isDropTarget = useIsDropTarget(column);const isEditing = (columnNameToEdit === column);const editorRef = useRef<HTMLInputElement>(null);const headerRef = useRef<HTMLHeadingElement>(null);@@ -154,16 +159,19 @@ export default function Column({// made in the footer is shown by the scroll to the end and by its fade, and one made among the// others takes the place its field was standing in.//- // While a card is carried, only the column it came from and the ones the gap can reach next- // measure their cards: every column redraws on every step of the gesture, and measuring one- // forces a layout of the whole board. The neighbours are included because the gap crosses to- // an adjacent column, and a column measured only once the gap is already in it has no earlier- // places to slide its cards from.- const dropColumnIndex = dropPosition ? columns.indexOf(dropPosition.column) : -1;+ // While a card is carried, the cards that move are those of the column it came from and those+ // of any column the gap has stood in. The rest are left unmeasured, measuring one costing a+ // layout of the whole board; paused rather than switched off, so a column the gap reaches in+ // one step still knows where its cards stood and slides them from there.+ const heldGap = useRef(false);+ if (!draggedCard) {+ heldGap.current = false;+ } else if (dropIndex !== null) {+ heldGap.current = true;+ }useFlip(contentRef, {selector: ".board-note",- disabled: !!draggedCard && column !== draggedCard.fromColumn- && !(dropColumnIndex >= 0 && Math.abs(columnIndex - dropColumnIndex) <= 1)+ paused: !!draggedCard && column !== draggedCard.fromColumn && !heldGap.current});const { handleDragOver, handleDragLeave, handleDrop } = useDragging({column, columnIndex, columnItems, isEditing, api, parentNote@@ -180,7 +188,7 @@ export default function Column({const isOverLimit = limit !== undefined && (totalCount ?? columnItems?.length ?? 0) > limit;const isCollapsed = !!collapsed && !isActive && !isPeeked;// A column opened to take a dragged card takes its width at once, and its cards with it.- const opensAtOnce = !!draggedCard || dropTarget === column;+ const opensAtOnce = !!draggedCard || isDropTarget;/*** Whether the column is still widening, during which its cards are left unpainted.@@ -379,7 +387,7 @@ export default function Column({<divdata-column={column}className={clsx("board-column", {- "drag-over": dropTarget === column && draggedCard?.fromColumn !== column,+ "drag-over": isDropTarget && draggedCard?.fromColumn !== column,// The class the themes key a hue off, worn here as anywhere else that carries one."with-hue": hue !== undefined,"board-column-archived": archived,@@ -507,8 +515,7 @@ export default function Column({// The card being carried is out of the flow, so the gap stands in its own// place too: held still, which a touch does before it moves, that is where it// was picked up from.- const showIndicatorBefore = dropPosition?.column === column &&- dropPosition.index === index;+ const showIndicatorBefore = dropIndex === index;return (<Fragment key={note.noteId}>@@ -534,7 +541,7 @@ export default function Column({);})}{insertBefore && !insertBefore.branchId && insertField}- {dropPosition?.column === column && dropPosition.index === (columnItems?.length ?? 0) && (+ {dropIndex === (columnItems?.length ?? 0) && (<div className="board-drop-placeholder show" style={gapStyle} />)}</div>}@@ -730,7 +737,10 @@ ${warning}` : counts}function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNote }: DragContext & { isEditing: boolean, api: BoardApi, parentNote: FNote }) {const { setDraggedColumn, setDropTarget, setDropPosition, setActiveColumn } =useContext(BoardActionsContext);- const { draggedColumn, dropPosition } = useContext(BoardDragStateContext);+ const { draggedColumn } = useContext(BoardDragStateContext);+ // Read when a drop happens rather than watched: these callbacks answer for a drag from the+ // note tree, and where the gap stands is of no interest to the column until one lands.+ const dropState = useContext(BoardDropStateContext);/** Needed to track if current column is dragged in real-time, since {@link draggedColumn} is populated one render cycle later. */const isDraggingRef = useRef(false);@@ -784,10 +794,11 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentN}}- if (!(dropPosition?.column === column && dropPosition.index === newIndex)) {+ const standing = dropState.get().position;+ if (!(standing?.column === column && standing.index === newIndex)) {setDropPosition({ column, index: newIndex });}- }, [column, setDropTarget, setActiveColumn, dropPosition, setDropPosition, isEditing]);+ }, [column, setDropTarget, setActiveColumn, dropState, setDropPosition, isEditing]);const handleDragLeave = useCallback((e: DragEvent) => {const relatedTarget = e.relatedTarget as HTMLElement;@@ -802,6 +813,8 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNconst handleDrop = useCallback(async (e: DragEvent) => {if (draggedColumn) return; // Don't handle card drops when dragging columnse.preventDefault();+ // Taken before the gap is closed, which is what says where the note goes.+ const standing = dropState.get().position;setDropTarget(null);setDropPosition(null);@@ -819,9 +832,9 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNconst { noteId, branchId } = dropped[0];const targetNote = await froca.getNote(noteId, true);const parentNoteId = parentNote.noteId;- if (!dropPosition) return;+ if (!standing) return;- const targetIndex = dropPosition.index - 1;+ const targetIndex = standing.index - 1;const targetItems = columnItems || [];const targetBranch = targetIndex >= 0 ? targetItems[targetIndex].branch : null;@@ -839,7 +852,7 @@ function useDragging({ column, columnIndex, columnItems, isEditing, api, parentNawait branches.moveAfterBranch([ branchId ], targetBranch.branchId);}}- }, [ api, draggedColumn, dropPosition, columnItems, column, setDropTarget, setDropPosition ]);+ }, [ api, draggedColumn, dropState, columnItems, column, setDropTarget, setDropPosition ]);return { handleColumnDragStart, handleColumnDragEnd, handleDragOver, handleDragLeave, handleDrop };}diff --git a/apps/client/src/widgets/collections/board/drop_state.spec.tsx b/apps/client/src/widgets/collections/board/drop_state.spec.tsxnew file mode 100644index 0000000000..201f6c6e8e--- /dev/null+++ b/apps/client/src/widgets/collections/board/drop_state.spec.tsx@@ -0,0 +1,87 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { BoardDropStateContext, DropStateStore, useDropIndex, useIsDropTarget } from "./drop_state";++const COLUMNS = [ "a", "b", "c", "d", "e" ];++describe("where the gap stands", () => {+ let container: HTMLElement;+ let store: DropStateStore;+ let renders: Record<string, number>;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ store = new DropStateStore();+ renders = {};+ draw();+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("answers each column about itself alone", () => {+ expect(read("b")).toBe("- -");++ set({ column: "b", index: 2 });+ expect(read("a")).toBe("- -");+ expect(read("b")).toBe("2 target");+ expect(read("c")).toBe("- -");++ set(null);+ expect(read("b")).toBe("- -");+ });++ it("wakes the column the gap left and the one it arrived in, and no others", () => {+ set({ column: "b", index: 0 });+ const afterFirst = { ...renders };++ // Across the board in one step, which a fast pointer does: only the two columns whose own+ // answer changed are drawn again, however far apart they stand.+ set({ column: "e", index: 0 });+ expect(drawnSince(afterFirst)).toEqual([ "b", "e" ]);++ // A place in the same column moves the gap without changing any other column's answer.+ const afterSecond = { ...renders };+ set({ column: "e", index: 1 });+ expect(drawnSince(afterSecond)).toEqual([ "e" ]);+ });++ /** What one column holds, as a line, so a single assertion covers both answers. */+ function read(column: string) {+ return container.querySelector(`[data-column="${column}"]`)?.textContent;+ }++ function drawnSince(before: Record<string, number>) {+ return COLUMNS.filter(column => renders[column] !== before[column]);+ }++ function set(position: { column: string, index: number } | null) {+ act(() => { store.set({ position, target: position?.column ?? null }); });+ }++ function draw() {+ act(() => {+ render(+ <BoardDropStateContext.Provider value={store}>+ {COLUMNS.map(column => <Watcher key={column} column={column} />)}+ </BoardDropStateContext.Provider>,+ container);+ });+ }++ function Watcher({ column }: { column: string }) {+ renders[column] = (renders[column] ?? 0) + 1;+ const index = useDropIndex(column);+ const isTarget = useIsDropTarget(column);+ return (+ <div data-column={column}>+ {`${index ?? "-"} ${isTarget ? "target" : "-"}`}+ </div>+ );+ }+});diff --git a/apps/client/src/widgets/collections/board/drop_state.ts b/apps/client/src/widgets/collections/board/drop_state.tsnew file mode 100644index 0000000000..b06153cec6--- /dev/null+++ b/apps/client/src/widgets/collections/board/drop_state.ts@@ -0,0 +1,68 @@+import { createContext } from "preact";+import { useSyncExternalStore } from "preact/compat";+import { useCallback, useContext } from "preact/hooks";++/** Where the gap held open for a carried card stands. */+export interface DropState {+ /** The column the gap is in and the place it takes, or nothing while the card is over none. */+ position: { column: string, index: number } | null;+ /** The column the card is over, which is drawn as the one it would land in. */+ target: string | null;+}++/**+ * Where the gap stands, held outside the board's own state.+ *+ * Read as board state this moved on every step of a drag, and with it the whole board: 23 columns+ * and every card on them redrawn to move one gap. Held here, a step wakes only the columns whose+ * own answer changed, which is the one the gap left, the one it arrived in, and their neighbours.+ */+export class DropStateStore {+ private state: DropState = { position: null, target: null };+ private listeners = new Set<() => void>();++ get() {+ return this.state;+ }++ set(state: DropState) {+ this.state = state;+ for (const listener of [ ...this.listeners ]) {+ listener();+ }+ }++ subscribe(listener: () => void) {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ }+}++/* v8 ignore next -- the board always provides its own; this is what lets a consumer read it with a+ plain useContext(), with no guard for a provider that is structurally always there. */+export const BoardDropStateContext = createContext(new DropStateStore());++/** Which place the gap holds open in this column, or nothing while it is standing elsewhere. */+export function useDropIndex(column: string) {+ return useDropState(useCallback((state: DropState) =>+ state.position?.column === column ? state.position.index : null, [ column ]));+}++/** Whether a carried card is over this column, which draws it as the one it would land in. */+export function useIsDropTarget(column: string) {+ return useDropState(useCallback((state: DropState) => state.target === column, [ column ]));+}++/**+ * Follows one thing about where the gap stands, redrawing only when that thing changes.+ *+ * @param select what to read, which has to answer with a value comparable by identity: every+ * column asks on every step of a drag, and an answer built afresh each time would redraw them all.+ */+function useDropState<T>(select: (state: DropState) => T): T {+ const store = useContext(BoardDropStateContext);+ return useSyncExternalStore(+ useCallback((listener: () => void) => store.subscribe(listener), [ store ]),+ useCallback(() => select(store.get()), [ store, select ])+ );+}diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 0c8307ebef..f2fa2d8b05 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -41,6 +41,7 @@ import { ViewModeProps } from "../interface";import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";import { useBoardDrag } from "./board_drag";import { movesColumn } from "./drag_geometry";+import { BoardDropStateContext, DropStateStore } from "./drop_state";import BoardApi from "./api";import { DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";import Column from "./column";@@ -159,14 +160,18 @@ interface BoardActions {setDropTarget: (target: string | null) => void;}-/** The half that changes repeatedly while a card or column is dragged, or a title is being edited. */+/**+ * The half that changes when a card or column is taken hold of and let go of, or a title is edited.+ *+ * Where the gap stands is not here: it changes on every step of a drag, and a context does that to+ * every column at once. It is held in a {@link DropStateStore} instead, which each column asks+ * about itself.+ */interface BoardDragState {branchIdToEdit?: string;columnNameToEdit?: string;draggedCard: CardDrag | null;draggedColumn: ColumnDrag | null;- dropPosition: ColumnDrag | null;- dropTarget: string | null;}// Both defaults are the honest identity value rather than a stand-in, which is what lets consumers@@ -195,9 +200,7 @@ export const BoardPromotedAttributesContext = createContext<string[] | undefinedexport const BoardDragStateContext = createContext<BoardDragState>({draggedCard: null,- draggedColumn: null,- dropPosition: null,- dropTarget: null+ draggedColumn: null});/**@@ -278,8 +281,17 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ draggedCard, setDraggedCard ] = useState<CardDrag | null>(null);/** The column just added, which is revealed once the board has drawn it. */const [ createdColumn, setCreatedColumn ] = useState<string>();- const [ dropTarget, setDropTarget ] = useState<string | null>(null);- const [ dropPosition, setDropPosition ] = useState<{ column: string, index: number } | null>(null);+ /**+ * Where the gap stands, kept out of the board's state so that a step of a drag draws no column+ * the gap is not near.+ */+ const dropState = useMemo(() => new DropStateStore(), []);+ const setDropPosition = useCallback((position: ColumnDrag | null) => {+ dropState.set({ ...dropState.get(), position });+ }, [ dropState ]);+ const setDropTarget = useCallback((target: string | null) => {+ dropState.set({ ...dropState.get(), target });+ }, [ dropState ]);const [ draggedColumn, setDraggedColumn ] = useState<ColumnDrag | null>(null);const [ columnDropPosition, setColumnDropPosition ] = useState<number | null>(null);const [ branchIdToEdit, setBranchIdToEdit ] = useState<string>();@@ -462,10 +474,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCbranchIdToEdit,columnNameToEdit,draggedCard,- draggedColumn,- dropPosition,- dropTarget- }), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn, dropPosition, dropTarget ]);+ draggedColumn+ }), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn ]);function refresh() {// A move under way has already been drawn where it will land. Held here rather than at each@@ -561,8 +571,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCheight: card.height}),onCardMove: (position, inside) => {- setDropTarget(position?.column ?? null);- setDropPosition(position);+ // Written together: two writes would wake every column watching the gap twice over.+ dropState.set({ position, target: position?.column ?? null });// Answers for what a `dragover` did, for a collapsed column the card is actually over:// one merely passed near keeps to itself, and one already opened stays open, since// closing it under a drag would move every column after it.@@ -595,8 +605,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC.finally(() => { movesInFlight.current--; });}setDraggedCard(null);- setDropTarget(null);- setDropPosition(null);+ dropState.set({ position: null, target: null });// Asked for by name: the card is drawn again where it landed, and a card that crossed// columns is drawn as a new element, so the one that was focused is gone.focusCard(card.noteId);@@ -760,6 +769,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<BoardPromotedAttributesContext.Provider value={shownAttributes}><BoardHighlightTokensContext.Provider value={filter.highlightedTokens}><BoardKeptCardsContext.Provider value={filter.keptNoteIds}>+ <BoardDropStateContext.Provider value={dropState}><BoardDragStateContext.Provider value={boardDragState}>{byColumn && columns && <divref={containerRef}@@ -859,6 +869,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC)}</div>}</BoardDragStateContext.Provider>+ </BoardDropStateContext.Provider></BoardKeptCardsContext.Provider></BoardHighlightTokensContext.Provider></BoardPromotedAttributesContext.Provider>diff --git a/apps/client/src/widgets/react/flip.spec.tsx b/apps/client/src/widgets/react/flip.spec.tsxindex 7f5379c740..f8f20196ae 100644--- a/apps/client/src/widgets/react/flip.spec.tsx+++ b/apps/client/src/widgets/react/flip.spec.tsx@@ -138,6 +138,62 @@ describe("useFlip", () => {expect(items()[1].style.transform).toBe("translateY(-50px)");});+ it("keeps the places it knows while it is paused, and slides from them when it resumes", async () => {+ let reads = 0;+ Object.defineProperty(HTMLElement.prototype, "offsetParent", {+ configurable: true,+ get(this: HTMLElement) { reads++; return this.parentElement; }+ });++ const options: Partial<FlipOptions> = {};+ const items = await draw([ "a", "b" ], options);++ options.paused = true;+ await settle();+ reads = 0;++ // Moved while nobody is measuring, then followed again: the place recorded before the+ // pause is where the child came from, so the move it made is the one that is drawn.+ place(items(), [ 0, 90 ]);+ await settle();+ expect(reads).toBe(0);+ expect(items()[1].style.transform).toBe("");++ options.paused = false;+ await settle();+ expect(items()[1].style.transform).toBe("translateY(-90px)");+ });++ it("calls off a growth it can no longer follow", async () => {+ vi.useFakeTimers();+ const options: Partial<FlipOptions> = { grow: true };+ const items = await draw([ "a" ], options);++ keys.push("b");+ await settle();+ expect(items()[1].style.height).toBe("0px");++ // Switched off part-way through: the frame the growth ends on would otherwise measure the+ // children, which is what being switched off is there to stop.+ options.disabled = true;+ await settle();+ let reads = 0;+ Object.defineProperty(HTMLElement.prototype, "offsetParent", {+ configurable: true,+ get(this: HTMLElement) { reads++; return this.parentElement; }+ });+ vi.advanceTimersByTime(SETTLE_AFTER_MS);+ expect(reads).toBe(0);++ // The growth is over as far as the hook is concerned, so a move made once it is followed+ // again is drawn rather than held back as part of a settling that never ends.+ options.disabled = false;+ await settle();+ place(items(), [ 0, 60 ]);+ await settle();+ expect(items()[1].style.transform).toBe("translateY(-60px)");+ });+describe("opening out what was not there", () => {it("takes a new child down to nothing and lets it out to its own size", async () => {const items = await draw([ "a" ], { grow: true });diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.tsindex a9e38026b8..131a54d7fd 100644--- a/apps/client/src/widgets/react/flip.ts+++ b/apps/client/src/widgets/react/flip.ts@@ -25,8 +25,22 @@ export interface FlipOptions {* full size. A predicate decides per child, for arrivals already shown some other way.*/grow?: boolean | ((child: HTMLElement) => boolean);- /** Whether to leave the children where the browser puts them, and stop measuring them. */+ /**+ * Whether to leave the children where the browser puts them, stop measuring them, and forget+ * where they stood.+ *+ * For a container whose children are being rebuilt for reasons that are not moves: sliding+ * from a place recorded before such a rebuild animates it as a move.+ */disabled?: boolean;+ /**+ * Whether to stop measuring the children while keeping the places they were last measured at.+ *+ * For a container that is not taking part yet: its children still stand where they were+ * measured, so it slides them from there the moment it does take part. Takes precedence over+ * {@link disabled}.+ */+ paused?: boolean;}/**@@ -43,7 +57,8 @@ export interface FlipOptions {* `offsetParent` reports a different number for the same place.*/export function useFlip(- ref: RefObject<HTMLElement>, { selector, axis = "vertical", grow, disabled }: FlipOptions+ ref: RefObject<HTMLElement>,+ { selector, axis = "vertical", grow, disabled, paused }: FlipOptions) {// Written after every commit, so it holds where the children stood at the previous one.const seen = useRef(new Map<Element, Place>());@@ -77,12 +92,15 @@ export function useFlip(}// Measured only when a slide can come of it: reading one position forces a layout of the- // whole document, which on a list of thousands is what this hook costs. The remembered- // places are dropped with it, since the children can move while they are not being- // followed and a stale place slides a child that never went anywhere.- if (disabled) {- seen.current.clear();- drawn.current = false;+ // whole document, which on a list of thousands is what this hook costs. A growth already+ // running is called off either way, since the frame it ends on reads the children again.+ if (paused || disabled) {+ window.clearTimeout(settled.current);+ settling.current = false;+ if (disabled) {+ seen.current.clear();+ drawn.current = false;+ }return;}