Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: performance improvements

Adorian Doranfb22e980bd1b
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index b0172c0ac6..c77f320c21 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -11,6 +11,7 @@ import {
BoardPromotedAttributesContext, TitleEditor
} from ".";
import { ContextMenuEvent } from "../../../menus/context_menu";
+import { cardFollows } from "./columns";
import { openNoteContextMenu } from "./context_menu";
import { t } from "../../../services/i18n";
import UserAttributesDisplay from "../../attribute_widgets/UserAttributesList";
@@ -164,7 +165,7 @@ function Card({
}
const bring = () => {
- if (!card.nextElementSibling) {
+ if (!cardFollows(card)) {
content.scrollTop = content.scrollHeight;
} else if (!card.previousElementSibling) {
content.scrollTop = 0;
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 246bd401b3..cab436480d 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -2,7 +2,7 @@ import clsx from "clsx";
import { Fragment } from "preact";
import { flushSync } from "preact/compat";
import {
- useCallback, useContext, useEffect, useMemo, useRef, useState
+ useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState
} from "preact/hooks";
import { JSX } from "preact/jsx-runtime";
@@ -25,6 +25,17 @@ import { useScrollFade } from "../../react/scroll_fade";
/** How long a field waits for the card it made, after which it is taken down regardless. */
const HAND_OVER_MS = 2000;
+/** What a gap stands at when nothing carried says otherwise. Matches `.board-drop-placeholder`. */
+const STOCK_GAP_HEIGHT = 40;
+
+/**
+ * How many cards below the gap are told to stand aside for it.
+ *
+ * Only the ones the reader can see have to move, and a column shows a handful at a time. Telling
+ * every card below the gap instead is thousands of them on a long column, and each one costs.
+ */
+const CARDS_ASIDE = 30;
+
/** 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";
@@ -35,6 +46,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 { cardSpacing } from "./drag_measure";
import { BoardDropStateContext, useDropIndex, useIsDropTarget } from "./drop_state";
interface DragContext {
@@ -184,27 +196,89 @@ export default function Column({
//
// A column being carried, and a column changing width, move no card inside any column, so
// every column is left unmeasured for the length of either.
- const heldGap = useRef(false);
- const holdsGap = dropIndex !== null;
- const justLeftGap = heldGap.current && !holdsGap;
- heldGap.current = holdsGap;
+ // Measured only when the column's own cards have changed, which is the only thing that moves
+ // them. Anything else that redraws the board, scrolling it sideways above all, would otherwise
+ // have every column read a position for every card it holds.
+ const measured = useRef<unknown>();
+ const cardsChanged = measured.current !== columnItems;
+ measured.current = columnItems;
useFlip(contentRef, {
selector: ".board-note",
- paused: draggedCard
- ? column !== draggedCard.fromColumn && !holdsGap && !justLeftGap
- : !!draggedColumn || !!isResizing
+ // Paused where nothing has moved the cards, so the places it knows are still good.
+ paused: !cardsChanged,
+ // Switched off outright for the length of a gesture, which is what makes the commit that
+ // ends one record where the cards landed rather than slide them there: the places it knew
+ // are from before the drag, and a card let go has already been carried to its own.
+ disabled: !!draggedCard || !!draggedColumn || !!isResizing
});
+
+ // The gap is opened without touching what the column holds. Putting an element among the
+ // cards, taking one out, or carrying one to another place all cost the same: the board
+ // restyles every element it holds, which on a large one is most of a second. Changing the
+ // size of an element that stays put, and moving one that stands outside the flow, cost
+ // nothing, so the gap is a standing element that slides and the cards beside it are
+ // transformed. The cards carry a transform transition already, so the sliding is the
+ // browser's to do.
+ const gapRef = useRef<HTMLDivElement>(null);
+ const roomRef = useRef<HTMLDivElement>(null);
+ /** Which cards were last told to stand aside, so only what changed is written. */
+ const aside = useRef({ from: 0, until: 0, room: 0 });
+ useLayoutEffect(() => {
+ const area = contentRef.current;
+ const gap = gapRef.current;
+ if (!area || !gap) return;
+
+ const cards = area.querySelectorAll<HTMLElement>(".board-note");
+ const height = draggedCard?.height ?? STOCK_GAP_HEIGHT;
+ const room = dropIndex === null ? 0 : height + cardSpacing();
+
+ // Read before anything is written, and `offsetTop` is no business of a transform anyway.
+ if (dropIndex !== null) {
+ const standing = cards[dropIndex];
+ const last = cards[cards.length - 1];
+ const top = standing
+ ? standing.offsetTop
+ : (last ? last.offsetTop + last.offsetHeight + cardSpacing() : 0);
+ gap.style.transform = `translateY(${top}px)`;
+ gap.style.height = `${height}px`;
+ }
+ gap.classList.toggle("show", dropIndex !== null);
+ roomRef.current?.style.setProperty("height", `${room}px`);
+
+ // Once the gap is gone, every card is put back, whichever ones they now are: a drop
+ // reorders the column, so the places that stood aside no longer name the same cards.
+ if (dropIndex === null) {
+ for (const card of cards) {
+ if (card.style.transform) {
+ card.style.removeProperty("transform");
+ }
+ }
+ aside.current = { from: 0, until: 0, room: 0 };
+ return;
+ }
+
+ const from = dropIndex;
+ const until = Math.min(cards.length, from + CARDS_ASIDE);
+ const last = aside.current;
+ // A step of a drag moves the gap by a card, so only the few cards it passed change what
+ // they are told; the rest of the window is already standing where it should.
+ const afresh = last.room !== room;
+ for (let index = last.from; index < last.until; index++) {
+ if (afresh || index < from || index >= until) {
+ cards[index]?.style.removeProperty("transform");
+ }
+ }
+ for (let index = from; index < until; index++) {
+ if (afresh || index < last.from || index >= last.until) {
+ cards[index].style.transform = `translateY(${room}px)`;
+ }
+ }
+ aside.current = { from, until, room };
+ }, [ dropIndex, draggedCard?.height, columnItems ]);
const { handleDragOver, handleDragLeave, handleDrop } = useDragging({
column, columnIndex, columnItems, isEditing, api, parentNote
});
- // Measured rather than styled: the gap stands for the card being carried, which is whatever
- // height its own content gave it. A drag from the note tree carries no card, so the stock
- // height stands.
- const gapStyle = draggedCard?.height
- ? { height: `${draggedCard.height}px` }
- : undefined;
-
// Read here rather than in the badge: the column body shows an outline as well.
const isOverLimit = limit !== undefined && (totalCount ?? columnItems?.length ?? 0) > limit;
const isCollapsed = !!collapsed && !isActive && !isPeeked;
@@ -537,9 +611,6 @@ export default function Column({
>
{(columnItems ?? []).map(({ note, branch }, index) => (
<Fragment key={note.noteId}>
- {dropIndex === index && (
- <div className="board-drop-placeholder show" style={gapStyle} />
- )}
{insertBefore?.branchId === branch.branchId && insertField}
<Card
api={api}
@@ -558,9 +629,10 @@ export default function Column({
</Fragment>
))}
{insertBefore && !insertBefore.branchId && insertField}
- {dropIndex === (columnItems?.length ?? 0) && (
- <div className="board-drop-placeholder show" style={gapStyle} />
- )}
+ {/* Both stand here for the length of the board's life: an element appearing
+ among the cards, or leaving them, is what a drag cannot afford. */}
+ <div ref={gapRef} className="board-drop-placeholder" />
+ <div ref={roomRef} className="board-drop-room" />
</div>}
{!isCollapsed && <AddNewItem
diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.ts
index fccfdc92ef..f42b744fb7 100644
--- a/apps/client/src/widgets/collections/board/columns.ts
+++ b/apps/client/src/widgets/collections/board/columns.ts
@@ -171,3 +171,20 @@ export function resolveBoardColumns(
function named(value: string) {
return value.trim() !== INBOX_COLUMN;
}
+
+/**
+ * Whether the column holds another card below this one.
+ *
+ * Asked rather than read off `nextElementSibling`: the gap a drag opens, and the room it takes,
+ * stand below the cards for the length of the board's life, so the last card is never the last
+ * thing in its column.
+ */
+export function cardFollows(card: Element) {
+ for (let next = card.nextElementSibling; next; next = next.nextElementSibling) {
+ if (next.classList.contains("board-note")) {
+ return true;
+ }
+ }
+
+ return false;
+}
diff --git a/apps/client/src/widgets/collections/board/drag.spec.tsx b/apps/client/src/widgets/collections/board/drag.spec.tsx
index c5e90fd7a3..56d4095a13 100644
--- a/apps/client/src/widgets/collections/board/drag.spec.tsx
+++ b/apps/client/src/widgets/collections/board/drag.spec.tsx
@@ -61,25 +61,33 @@ describe("Board drag and drop", () => {
}
});
+ /**
+ * The gap stands outside the column's flow and the cards below it stand aside for it. Carried
+ * among them instead, it changes what the column holds, and the board restyles every element
+ * it holds for that, on every step of a drag.
+ */
it("marks the card a drop would land before, from where the pointer is", async () => {
const { columns } = await renderBoard();
// Above the middle of the second card, so the drop lands between the two.
await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);
- const placeholders = [ ...columns[0].querySelectorAll(".board-column-content > *") ]
- .map(child => child.className);
- expect(placeholders[1]).toContain("board-drop-placeholder");
+ expect(columns[0].querySelector(".board-drop-placeholder.show")).toBeTruthy();
+ expect([ ...columns[0].querySelectorAll<HTMLElement>(".board-note") ]
+ .map(card => card.style.transform !== "")).toEqual([ false, true ]);
});
it("clears the mark once the pointer leaves the column altogether", async () => {
const { columns } = await renderBoard();
await drag(columns[0], "dragover", { types: [ TREE_CLIPBOARD_TYPE ] }, 120);
- expect(columns[0].querySelector(".board-drop-placeholder")).toBeTruthy();
+ expect(columns[0].querySelector(".board-drop-placeholder.show")).toBeTruthy();
+ // The gap itself stays where it stands; it is shown and hidden rather than made and
+ // unmade, which is what keeps a drag off the board's own contents.
await drag(columns[0], "dragleave", { types: [] });
- expect(columns[0].querySelector(".board-drop-placeholder")).toBeNull();
+ expect(columns[0].querySelector(".board-drop-placeholder.show")).toBeNull();
+ expect(columns[0].querySelector(".board-drop-placeholder")).toBeTruthy();
});
it("ignores a drag carrying something the board has no use for", async () => {
@@ -87,7 +95,7 @@ describe("Board drag and drop", () => {
await drag(columns[0], "dragover", { types: [ "text/uri-list" ] }, 120);
- expect(columns[0].querySelector(".board-drop-placeholder")).toBeNull();
+ expect(columns[0].querySelector(".board-drop-placeholder.show")).toBeNull();
});
it("clones a note dragged in from the tree, which the board does not hold", async () => {
diff --git a/apps/client/src/widgets/collections/board/drag_measure.ts b/apps/client/src/widgets/collections/board/drag_measure.ts
index c58f8e9be5..91eaafab52 100644
--- a/apps/client/src/widgets/collections/board/drag_measure.ts
+++ b/apps/client/src/widgets/collections/board/drag_measure.ts
@@ -75,6 +75,14 @@ const heights = new Map<string, number>();
/** What stands between two cards, which is one rule the board over and so is read once. */
let spacing: number | undefined;
+/**
+ * What stands between two cards, which is what a gap takes up on top of the card it stands for.
+ * Nothing until a column has been measured, which a drag does before it opens any gap.
+ */
+export function cardSpacing() {
+ return spacing ?? 0;
+}
+
/** Drops what has been measured, for a window whose size has changed under it. */
export function forgetCardHeights() {
heights.clear();
@@ -90,9 +98,8 @@ export function forgetCardHeights() {
* this leads to names a place in the list the board holds, which is the list a move is expressed
* against.
*
- * The gap standing open for the carried card holds the cards under it a place lower than they are
- * measured to be. What a place is counted against is the column without the drag's own doing in
- * it, so the room the gap takes is given back to everything below it.
+ * The gap the carried card leaves room for stands outside the column's flow, so it displaces no
+ * card and none of its room has to be given back: what is measured is the column as it stands.
*/
function measureCards(area: HTMLElement | null) {
if (!area) {
@@ -101,7 +108,6 @@ function measureCards(area: HTMLElement | null) {
const top = area.getBoundingClientRect().top - area.scrollTop;
const cards: CardBox[] = [];
- let gap = 0;
/** Where the next card stands if it has to be counted rather than read. */
let next = 0;
/** The foot of the last card read, which the next one read settles the spacing against. */
@@ -114,12 +120,6 @@ function measureCards(area: HTMLElement | null) {
continue;
}
- if (child.classList.contains("board-drop-placeholder")) {
- const box = child.getBoundingClientRect();
- gap += box.height + Number.parseFloat(getComputedStyle(child).marginBottom || "0");
- continue;
- }
-
if (!child.classList.contains("board-note")) {
continue;
}
@@ -134,7 +134,7 @@ function measureCards(area: HTMLElement | null) {
if (height === undefined || !anchored) {
const box = child.getBoundingClientRect();
height ??= box.height;
- at = box.top - top - gap;
+ at = box.top - top;
anchored = true;
if (noteId && box.height) {
heights.set(noteId, box.height);
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index bd03bad546..4bc2aaf677 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -522,6 +522,8 @@ body.mobile .board-view-container .board-add-column {
stops it at the column instead of passing it on, and the board never moves. */
.board-view-container .board-column-content {
overscroll-behavior-y: contain;
+ /* What the gap is placed against, and what a card's `offsetTop` is then counted from. */
+ position: relative;
}
/* And while something is carried, the end does not spring back either: the copy is positioned
@@ -741,7 +743,19 @@ body.mobile .board-view-container .board-add-column {
}
}
+/* Outside the column's flow and standing there for good. Carrying it into the cards, or out of
+ them, is a change to what the column holds, and the board restyles every element it holds for
+ that; sliding it instead costs nothing. */
.board-drop-placeholder {
+ position: absolute;
+ /* It stands over the cards whether it is showing or not, and a press belongs to the card under
+ it, not to the space being held open. */
+ pointer-events: none;
+ /* Anchored at the top of the column's content, which the transform then counts down from. Left
+ to its own place in the flow it would start below every card. */
+ top: 0;
+ left: 0;
+ right: 0;
height: 40px;
/* The gap below is the card's, in em, so it has to be read at the card's own font size. */
font-size: var(--card-font-size);
@@ -751,11 +765,20 @@ body.mobile .board-view-container .board-add-column {
background-color: rgba(0, 0, 0, 0.15);
opacity: 0;
/* Opacity only: the height is the carried card's, so any change in it is a mismatch to see
- rather than a movement to smooth over. */
+ rather than a movement to smooth over, and it slides to follow the pointer rather than easing
+ after it. */
transition: opacity 0.15s ease;
box-sizing: border-box;
}
+/* The room the gap takes out of the column, so it still scrolls past its last card while one is
+ held there. It stands in the flow at no height, and is given one for as long as the gap needs
+ it: growing an element that stays put costs nothing, where adding one does not. */
+.board-drop-room {
+ height: 0;
+ flex-shrink: 0;
+}
+
.board-drop-placeholder.show {
opacity: 0.6;
}
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 5696b99154..f0a126f25e 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -609,6 +609,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
}
},
onCardEnd: (card, position) => {
+ // Put back here rather than left to the columns to draw: the board is about to move a
+ // card, hide the gap and close the room it took, and if those reach the screen in
+ // separate frames the reader sees a gap open where nothing is being carried any more.
+ closeGaps(containerRef.current);
const branchId = byColumn?.get(card.fromColumn)?.[card.index]?.branch.branchId;
if (position && branchId && byColumn && allByColumn) {
// Drawn at once, into `allByColumn` since that is what `byColumn` derives from, at
@@ -958,6 +962,35 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
* Naming the winning check, rather than returning a boolean, is what lets the profiler attribute a
* redraw to a cause.
*/
+/**
+ * Puts every card back where the column draws it, closes every gap and gives back the room they
+ * took.
+ *
+ * The columns do this for themselves as they are drawn, but a drop moves a card, hides a gap and
+ * closes its room in one go, and those reaching the screen in separate frames is a gap the reader
+ * sees open where nothing is being carried. Done here first, the board is already tidy whichever
+ * way the drawing falls.
+ */
+function closeGaps(container: HTMLElement | null) {
+ if (!container) {
+ return;
+ }
+
+ for (const card of container.querySelectorAll<HTMLElement>(".board-note")) {
+ if (card.style.transform) {
+ card.style.removeProperty("transform");
+ }
+ }
+
+ for (const gap of container.querySelectorAll(".board-drop-placeholder")) {
+ gap.classList.remove("show");
+ }
+
+ for (const room of container.querySelectorAll<HTMLElement>(".board-drop-room")) {
+ room.style.height = "0px";
+ }
+}
+
export function findRefreshReason(loadResults: LoadResults, statusAttribute: string, noteIds: string[], parentNoteId: string): string | null {
// A card moved between columns.
if (loadResults.getAttributeRows().some(attr => attr.name === statusAttribute && noteIds.includes(attr.noteId ?? ""))) {
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index 641b2c3b70..019f6a75ec 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -1,3 +1,4 @@
+import { cardFollows } from "./columns";
import { RefObject } from "preact";
import { useCallback, useLayoutEffect, useRef } from "preact/hooks";
@@ -502,7 +503,7 @@ function reveal(element: HTMLElement) {
// The last card scrolls its column to the end rather than just into view: its own bottom
// margin and the fade over the column's bottom edge would otherwise cover it.
const content = element.closest<HTMLElement>(".board-column-content");
- if (content && !element.nextElementSibling) {
+ if (content && !cardFollows(element)) {
content.scrollTop = content.scrollHeight;
}
diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.ts
index 131a54d7fd..57a596dd14 100644
--- a/apps/client/src/widgets/react/flip.ts
+++ b/apps/client/src/widgets/react/flip.ts
@@ -37,8 +37,8 @@ export interface FlipOptions {
* 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}.
+ * measured, so it slides them from there the moment it does take part. Where {@link disabled}
+ * is set as well, the places are dropped: forgetting outranks remembering.
*/
paused?: boolean;
}