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: improve column dragging performance
Adorian Doranda814030040d
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.tsindex 457ec56369..f93df7108f 100644--- a/apps/client/src/widgets/collections/board/board_drag.ts+++ b/apps/client/src/widgets/collections/board/board_drag.ts@@ -66,8 +66,13 @@ export interface BoardDragCallbacks {* A column has been taken hold of by its heading.** @param size what it measures, so the gap held open for it is the size it will land in.+ * @param row where the columns stood before it was taken out of the row, and how much room it+ * takes out of one, which is what the board moves the gap and the other columns against.*/- onColumnStart(column: string, index: number, size: { width: number, height: number }): void;+ onColumnStart(+ column: string, index: number, size: { width: number, height: number },+ row: { lefts: number[], stride: number }+ ): void;/** Which place among the columns it would take, counting them as they stand. */onColumnMove(index: number | null): void;/** As {@link onCardEnd}, for a column: a place means let go, nothing means called off. */@@ -175,7 +180,7 @@ export function useBoardDrag(if (held.kind === "card") {latest.current.onCardStart(held.card);} else {- latest.current.onColumnStart(held.column, held.index, lifted.size);+ latest.current.onColumnStart(held.column, held.index, lifted.size, row(held));}resolve(held);};@@ -357,7 +362,25 @@ export function useBoardDrag(}};- /** Set between a tap and the `touchend` the browser would make mouse events from. */+ /**+ * Where the columns stood before the carried one was taken out of the row, which is what the board+ * places the gap and the columns that step aside for it against.+ */+function row(held: Gesture & { kind: "column" }) {+ const boxes = held.measurement?.columns ?? [];+ const last = boxes[boxes.length - 1];+ // Read off the row rather than from the stylesheet: what stands between two columns is the+ // same everywhere, and one pair is enough to say how much.+ const gap = boxes.length > 1 ? boxes[1].left - (boxes[0].left + boxes[0].width) : 0;+ const lefts = boxes.map(({ left }) => left);+ if (last) {+ lefts.push(last.left + last.width + gap);+ }++ return { lefts, stride: (boxes[held.index]?.width ?? 0) + gap };+}++/** Set between a tap and the `touchend` the browser would make mouse events from. */let justTapped = false;const onTouchEnd = (event: TouchEvent) => {diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 2f35a86adb..89d1617fdf 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -60,6 +60,7 @@ export default function Column({isActive,isPeeked,isResizing,+ standsAside,nested,limit,columnItems,@@ -87,6 +88,14 @@ export default function Column({isPeeked?: boolean,/** Whether a column is still taking its new width, during which no column's cards move. */isResizing?: boolean,+ /**+ * How far the column stands aside for one being carried, in pixels.+ *+ * Written as a transform rather than drawn by putting the carried column's place among the+ * others: the row is left as it stands for the length of the gesture, so a step of it costs+ * the browser a transform apiece instead of laying out every card on the board again.+ */+ standsAside?: number,/** What a new card is made from, and how the reader picks something else. */cardTemplates: CardTemplates,/** Whether the inbox also collects notes deeper than the board's direct children. */@@ -421,7 +430,10 @@ export default function Column({onDragOver={handleDragOver}onDragLeave={handleDragLeave}onDrop={handleDrop}- style={{ "--board-column-custom-hue": hue }}+ style={{+ "--board-column-custom-hue": hue,+ transform: standsAside ? `translateX(${standsAside}px)` : undefined+ }}><h3ref={headerRef}diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsxindex 994e0a9071..7d8b16bcda 100644--- a/apps/client/src/widgets/collections/board/drag.spec.tsx+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx@@ -487,6 +487,61 @@ describe("Board column reordering", () => {expect(placeholder?.style.width).toBe("");});+ /**+ * The row is left as it stands for the length of the gesture: the carried column's place is+ * held open where it was lifted from, and the columns it is carried past step aside by a+ * transform. Reordering the elements per step would lay out every card on the board again.+ */+ it("holds the gap where the column was lifted from and steps the others aside", async () => {+ const { columns, board } = await renderColumns();++ // Carried over the third column, which spans 200 to 300, past its middle.+ await carryColumn(columns[0], 280, { release: false });++ // The copy being carried is a column too, and it follows the pointer rather than the row.+ const drawn = [ ...board.querySelectorAll<HTMLElement>(+ ".board-column:not(.board-drag-preview)") ];+ const placeholder = board.querySelector<HTMLElement>(".column-drop-placeholder");+ // Still the first thing in the row, where the column it stands for was picked up.+ expect(placeholder?.previousElementSibling).toBeNull();+ // The two it passes close up by what it takes out of the row, which is its own 100px:+ // happy-dom computes no styles, so the gap between columns reads as nothing here.+ expect(drawn.map(column => column.style.transform))+ .toEqual([ "", "translateX(-100px)", "translateX(-100px)" ]);+ });++ /**+ * The transforms come off in the same frame the row is drawn in its new order, where every+ * column already stands where that order puts it. Eased to nothing they would each carry a+ * column's width from a place it never stood in, which reads as the row sliding after the drop.+ */+ it("takes the transforms off without a transition once a column has landed", async () => {+ const { columns, board } = await renderColumns();++ // Watched rather than read afterwards: the frame that puts the transition back has run by+ // the time the gesture returns.+ expect(await classesWhile(board, () => carryColumn(columns[0], 280)))+ .toContain("board-columns-landing");+ });++ it("eases the columns back where the drag is called off, having moved nothing", async () => {+ const { columns, board } = await renderColumns();++ // Let go where it started, which places the column back where it came from: the columns+ // that stepped aside slide back, so the transition has to stay on.+ expect(await classesWhile(board, () => carryColumn(columns[0], 20)))+ .not.toContain("board-columns-landing");+ });++ it("puts the columns back once the gesture is over", async () => {+ const { columns, board } = await renderColumns();++ await carryColumn(columns[0], 280);++ expect([ ...board.querySelectorAll<HTMLElement>(".board-column") ]+ .map(column => column.style.transform)).toEqual([ "", "", "" ]);+ });+/** A copy of it is carried, capped so a tall column does not cover the board it is placed on. */it("carries a copy, hiding the column until it is let go", async () => {const { columns, board } = await renderColumns();@@ -596,6 +651,20 @@ describe("Board column reordering", () => {});/** Takes hold of a column by its heading, carries it to `clientX` and lets it go there. */+ /** Every class the element wears at any point while `run` is going on. */+ async function classesWhile(element: HTMLElement, run: () => Promise<void>) {+ const seen = new Set<string>();+ const watch = new MutationObserver(() => {+ for (const name of element.classList) {+ seen.add(name);+ }+ });+ watch.observe(element, { attributes: true, attributeFilter: [ "class" ] });+ await run();+ watch.disconnect();+ return [ ...seen ];+ }+async function carryColumn(column: HTMLElement,clientX: number,diff --git a/apps/client/src/widgets/collections/board/drag_geometry.spec.ts b/apps/client/src/widgets/collections/board/drag_geometry.spec.tsindex 6d8fcdab79..90e54a9ec7 100644--- a/apps/client/src/widgets/collections/board/drag_geometry.spec.ts+++ b/apps/client/src/widgets/collections/board/drag_geometry.spec.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import {type CardBox, cardInsertionIndex, columnAt, type ColumnBox, columnCovers,- columnInsertionIndex, movesColumn+ columnInsertionIndex, columnStandsAside, movesColumn} from "./drag_geometry";/** Three 100px columns with a 20px gap, standing 400 tall from the top of the page. */@@ -172,3 +172,33 @@ describe("movesColumn", () => {expect(movesColumn(0, 2)).toBe(true);});});++describe("columnStandsAside", () => {+ // Six columns, the third one carried, each standing 266px wide with the gap after it.+ const aside = (index: number, to: number | null) => columnStandsAside(index, 2, to, 266);++ it("moves the columns between where it left and where it lands, and no others", () => {+ // Carried to the right: the ones it passes close up behind it.+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, 5)))+ .toEqual([ 0, 0, 0, -266, -266, 0 ]);++ // Carried to the left: the ones it passes stand aside for it.+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, 0)))+ .toEqual([ 266, 266, 0, 0, 0, 0 ]);+ });++ it("holds everything still where the column would land back in its own place", () => {+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, 2))).toEqual([ 0, 0, 0, 0, 0, 0 ]);+ // The place just after its own is the same place: it is the only column out of the row.+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, 3))).toEqual([ 0, 0, 0, 0, 0, 0 ]);+ });++ it("holds everything still while the column is over nowhere it could land", () => {+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, null))).toEqual([ 0, 0, 0, 0, 0, 0 ]);+ });++ it("counts the place past the last column as the end of the row", () => {+ expect([ 0, 1, 2, 3, 4, 5 ].map(index => aside(index, 6)))+ .toEqual([ 0, 0, 0, -266, -266, -266 ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/drag_geometry.ts b/apps/client/src/widgets/collections/board/drag_geometry.tsindex 3dca6e4315..e50fcb9781 100644--- a/apps/client/src/widgets/collections/board/drag_geometry.ts+++ b/apps/client/src/widgets/collections/board/drag_geometry.ts@@ -132,3 +132,55 @@ export function columnInsertionIndex(columns: ColumnBox[], x: number): number {export function movesColumn(from: number, to: number): boolean {return to !== from && to !== from + 1;}++/**+ * How far a column stands aside while another is carried past it, in pixels.+ *+ * The board is not reordered as the reader drags: the carried column's place is held open where it+ * was lifted from, and the columns between there and where it would land step aside by its width+ * instead. A step of the gesture then costs each of them a transform, where reordering the elements+ * costs a fresh layout of every card on the board.+ *+ * @param index which column is being asked about.+ * @param from where the carried column was lifted from.+ * @param to the place it would take, counting the columns as they stand, or nothing while it is+ * over nowhere it could land.+ * @param width what it takes up, its own width and the gap after it.+ */+export function columnStandsAside(+ index: number, from: number, to: number | null, width: number+): number {+ if (to === null || index === from) {+ return 0;+ }++ // Landing further along: everything between the place it left and the place it takes closes up+ // behind it. Landing at the place just after its own leaves it where it is.+ if (to > from) {+ return index > from && index < to ? -width : 0;+ }++ return index >= to && index < from ? width : 0;+}++/**+ * How far the gap held open for a carried column stands from where that column was lifted, in+ * pixels.+ *+ * The gap is drawn where the column was picked up and carried to where it would land, the columns+ * it passes having stepped aside to leave the room. Read against `lefts`, which holds where each+ * column stood before the drag began and, last of all, where a column added at the end would.+ */+export function columnGapStandsAside(+ from: number, to: number | null, lefts: number[], stride: number+): number {+ const origin = lefts[from];+ if (to === null || origin === undefined) {+ return 0;+ }++ const at = lefts[Math.min(to, lefts.length - 1)];+ // Landing further along, the gap opens after the column it is carried past rather than before+ // it, which is that column's own place less the room the gap takes.+ return (to > from ? at - stride : at) - origin;+}diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex eab01e18dd..ca64222cfe 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -769,7 +769,8 @@ body.mobile .board-view-container .board-add-column {border-radius: 8px;background-color: rgba(0, 0, 0, 0.1);opacity: 0;- transition: opacity 0.15s ease;+ /* Carried to where the column would land, the same way the columns it passes step aside. */+ transition: opacity 0.15s ease, transform 0.2s ease;}body.mobile .column-drop-placeholder {@@ -922,6 +923,16 @@ body.mobile .column-drop-placeholder {width var(--board-expand-duration) ease;}+/* The one frame the row is drawn in after a column is dropped. Each column already stands where+ that order puts it, carried there by the transform the drag wrote, so taking the transform off+ has nothing left to ease: given a transition it would carry the column a full width from a place+ it never stood in. Written against the selectors above, which it has to outweigh. */+.board-view-container.board-columns-landing .board-column,+.board-view-container.board-columns-landing .board-column.collapsed:not(.board-drag-preview),+.board-view-container.board-columns-landing .board-column.quick-expand:not(.board-drag-preview) {+ transition: none;+}+/** The column's contents are pinned at the width it is opening to, and clipped until it gets there.*diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex b2e8986b91..a077884ecb 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -40,7 +40,7 @@ import { CollectionFilterInput, useCollectionFilter } from "../collection_filterimport { ViewModeProps } from "../interface";import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api";import { useBoardDrag } from "./board_drag";-import { movesColumn } from "./drag_geometry";+import { columnGapStandsAside, columnStandsAside, 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";@@ -130,6 +130,10 @@ interface ColumnDrag {index: number;/** What the column measures, so the gap held open for it is the size it will land in. */size?: { width: number, height: number };+ /** How much room it takes out of the row, its width and the gap after it. */+ stride?: number;+ /** Where each column stood before it was taken out, and where one added at the end would. */+ lefts?: number[];}/**@@ -628,11 +632,30 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCrevealColumn(position.column);}},- onColumnStart: (column, index, size) => setDraggedColumn({ column, index, size }),+ onColumnStart: (column, index, size, row) => setDraggedColumn({+ column, index, size, stride: row.stride, lefts: row.lefts+ }),onColumnMove: setColumnDropPosition,onColumnEnd: (from, to) => {+ // The row is drawn again as the gesture lets go, and the columns land where their+ // transforms already had them. No card moves inside a column for that, so the same+ // window that covers a column changing width covers this too.+ columnResizingUntil.current = Date.now() + EXPAND_MS;if (to !== null && movesColumn(from, to)) {- handleColumnDrop(from, to);+ // The transforms come off in the same frame the row is drawn in its new order,+ // where each column already stands where that order puts it. Eased to zero they+ // would carry it a column's width from a place it never stood in, so the frame+ // that takes them off runs without a transition.+ const container = containerRef.current;+ container?.classList.add("board-columns-landing");++ // Taken off a frame after the one that draws the row, not on it: a frame's+ // callbacks run before the styles it paints are worked out, so putting the+ // transition back in the first of them puts it back in time to be used.+ requestAnimationFrame(() => requestAnimationFrame(+ () => container?.classList.remove("board-columns-landing")));+ // Not animated either: the row puts the columns exactly where they already are.+ handleColumnDrop(from, to, false);}setDraggedColumn(null);setColumnDropPosition(null);@@ -665,8 +688,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCaxis: "horizontal",// Only for a move the reader made, tracked by `columnMovedUntil`. A value change redraws// the columns, and the order churns while the cards, the definition and the stored config- // catch up with one another; sliding for that animates a rename as a move.- disabled: !draggedColumn && Date.now() > columnMovedUntil.current+ // catch up with one another; sliding for that animates a rename as a move. A carried+ // column is left out as well: the columns beside it are moved by their own transforms,+ // which this would measure and then slide back from.+ disabled: !!draggedColumn || Date.now() > columnMovedUntil.current});/**@@ -723,8 +748,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// The drag reports where the column landed among the ones on screen, which is not where it// landed among them all once some are archived and hidden. Translated here so a reorder leaves// every hidden column where it was rather than herding them to the end.- const handleColumnDrop = useCallback((fromIndex: number, toIndex: number) => {- columnMovedUntil.current = Date.now() + FLIP_SETTLE_MS;+ const handleColumnDrop = useCallback((fromIndex: number, toIndex: number, animate = true) => {+ if (animate) {+ columnMovedUntil.current = Date.now() + FLIP_SETTLE_MS;+ }// The list the api holds, which is also the one it reorders. A column the board is not// showing is in neither, so indexing into `columns` would be off by one.const allColumns = api.columns;@@ -809,10 +836,16 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<div className="board-columns">{shownColumns.map((column, index) => (<Fragment key={column}>- {columnDropPosition === index && (+ {draggedColumn?.index === index && (<divclassName="column-drop-placeholder show"- style={placeholderSize}+ style={{+ ...placeholderSize,+ transform: `translateX(${columnGapStandsAside(+ draggedColumn.index, columnDropPosition,+ draggedColumn.lefts ?? [],+ draggedColumn.stride ?? 0)}px)`+ }}/>)}<Column@@ -828,6 +861,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCisActive={activeColumn === column}isPeeked={isPeekingAll}isResizing={isResizingColumns}+ standsAside={draggedColumn+ ? columnStandsAside(index, draggedColumn.index,+ columnDropPosition, draggedColumn.stride ?? 0)+ : 0}cardTemplates={cardTemplates}nested={storedColumns.get(column)?.nested}limit={storedColumns.get(column)?.limit}@@ -842,9 +879,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC/></Fragment>))}- {columnDropPosition === shownColumns.length && draggedColumn && (- <div className="column-drop-placeholder show" style={placeholderSize} />- )}+</div><AddNewColumn