Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: implement DOM windowing

Adorian Doran3cdd1a935f28
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.ts
index c573966d88..995675bec2 100644
--- a/apps/client/src/widgets/collections/board/board_drag.ts
+++ b/apps/client/src/widgets/collections/board/board_drag.ts
@@ -583,7 +583,13 @@ function startCard(
const noteId = element?.dataset.noteId;
if (!element || !columnElement || !noteId) return null;
- const cards = [ ...columnElement.querySelectorAll(".board-note") ];
+ // A windowed column draws a slice of its cards, so the card says which place it holds rather
+ // than being counted among the ones on screen.
+ const stated = element.dataset.index;
+ const place = stated === undefined ? Number.NaN : Number(stated);
+ const index = Number.isFinite(place)
+ ? place
+ : [ ...columnElement.querySelectorAll(".board-note") ].indexOf(element);
const noteIds = carriedWith(noteId);
return {
kind: "card",
@@ -593,7 +599,7 @@ function startCard(
noteId,
noteIds,
fromColumn: columnElement.dataset.column ?? "",
- index: cards.indexOf(element),
+ index,
height: carriedHeight(element, noteIds)
},
position: null,
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 0eec3be29e..f3c952098c 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -270,6 +270,7 @@ function Card({
}
}}
data-note-id={note.noteId}
+ data-index={index}
onContextMenu={handleContextMenu}
onDragStart={handleDragStart}
onClick={!isEditing ? handleClick : undefined}
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 939e95359f..8a968ebaaf 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -47,6 +47,9 @@ import { DEFAULT_CARD_ICON, DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns"
import { openColumnContextMenu, openColumnSortMenu, openCreateCardMenu } from "./context_menu";
import type { ColumnSort } from "./data";
import { cardSpacing } from "./drag_measure";
+import {
+ REVEAL_CARD, type RevealCardDetail, useColumnWindow, WINDOW_THRESHOLD
+} from "./windowing";
import { BoardDropStateContext, useDropIndex, useIsDropTarget } from "./drop_state";
interface DragContext {
@@ -210,6 +213,15 @@ export default function Column({
const headerRef = useRef<HTMLHeadingElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const scrollFade = useScrollFade(contentRef);
+ const noteIds = useMemo(
+ () => (columnItems ?? []).map(({ note }) => note.noteId), [ columnItems ]);
+ // A column of thousands draws only what the reader can see. Left off below the threshold, so
+ // an ordinary board keeps the code path it has always had.
+ const isWindowed = noteIds.length > WINDOW_THRESHOLD;
+ const { bounds, windowChanged, scrollToCard } = useColumnWindow(contentRef, noteIds, isWindowed);
+ const shownItems = isWindowed
+ ? (columnItems ?? []).slice(bounds.from, bounds.until)
+ : (columnItems ?? []);
// Cards slide to follow the drop gap opening and closing. Measured only when the column's own
// cards have changed: reading one position costs a layout of the whole board, and anything
// else that redraws it would have every column read one per card.
@@ -221,10 +233,13 @@ export default function Column({
// Paused where nothing has moved the cards, so the places it knows are still good.
paused: !cardsChanged,
// Off for the length of a gesture, so the commit that ends one records where the cards
- // landed rather than sliding them there.
- disabled: !!draggedCard || !!draggedColumn || !!isResizing
+ // landed rather than sliding them there. A window that has just swapped its cards is the
+ // same case: the places recorded before it name cards that are no longer drawn, and
+ // sliding from them would animate a scroll as though the column had been reordered.
+ disabled: !!draggedCard || !!draggedColumn || !!isResizing || windowChanged
});
+ const windowFrom = isWindowed ? bounds.from : 0;
// The gap is a standing element that slides, and the cards beside it are transformed: putting
// one among the cards, or taking one out, restyles every element the board holds.
const gapRef = useRef<HTMLDivElement>(null);
@@ -250,16 +265,24 @@ export default function Column({
// moves, and the ones past its foot are left alone whatever it holds.
const reach = Math.ceil(area.clientHeight / MIN_CARD_HEIGHT) + 1;
+ // A windowed column draws a slice of its cards, so a place in the column has to be read
+ // as a place among the ones drawn before it can name an element.
+ const placeOf = (index: number) => index - windowFrom;
+
// Read before anything is written, and `offsetTop` is no business of a transform anyway.
if (dropIndex !== null) {
- const standing = cards[dropIndex];
+ const standing = cards[placeOf(dropIndex)];
// `lift()` sets `display: none` on the carried card, so a gap past the last one
// measures against the last card still laid out.
const drawn = [ ...cards ].filter(card => card.style.display !== "none");
const last = drawn[drawn.length - 1];
const top = standing
? standing.offsetTop
- : (last ? last.offsetTop + last.offsetHeight + cardSpacing() : 0);
+ // A gap above the window stands at the first drawn card; one below it stands
+ // after the last, which is where the cards run out either way.
+ : (placeOf(dropIndex) < 0
+ ? (cards[0]?.offsetTop ?? 0)
+ : (last ? last.offsetTop + last.offsetHeight + cardSpacing() : 0));
gap.style.transform = `translateY(${top}px)`;
gap.style.height = `${height}px`;
}
@@ -278,7 +301,7 @@ export default function Column({
return;
}
- const from = dropIndex;
+ const from = Math.max(0, placeOf(dropIndex));
const until = Math.min(cards.length, from + reach);
const last = aside.current;
// A step of a drag moves the gap by a card, so only the few cards it passed change what
@@ -298,7 +321,7 @@ export default function Column({
}
}
aside.current = { from, until, room };
- }, [ dropIndex, draggedCard, columnItems ]);
+ }, [ dropIndex, draggedCard, columnItems, windowFrom ]);
const { handleDragOver, handleDragLeave, handleDrop } = useDragging({
column, columnIndex, columnItems, isEditing, api, parentNote, onLanded: setCreatedNoteId
});
@@ -516,6 +539,36 @@ export default function Column({
return () => window.clearTimeout(timer);
}, [ insertedNoteId, columnItems ]);
+ // A card just made at the foot of a long column stands outside the window, and the card's own
+ // effect that scrolls to it cannot run while it is not drawn. The column brings it into view
+ // instead, which is what draws it.
+ const arrived = createdNoteId ?? landedNoteId;
+ useEffect(() => {
+ if (!isWindowed || !arrived) return;
+
+ const index = noteIds.indexOf(arrived);
+ if (index >= 0 && (index < bounds.from || index >= bounds.until)) {
+ scrollToCard(index);
+ }
+ }, [ arrived, isWindowed, noteIds, bounds.from, bounds.until, scrollToCard ]);
+
+ // The keyboard can walk onto a card the window leaves undrawn, which cannot be focused until
+ // it is in the page.
+ useEffect(() => {
+ const board = contentRef.current?.closest<HTMLElement>(".board-view-container");
+ if (!board || !isWindowed) return;
+
+ const reveal = (event: Event) => {
+ const { detail } = event as CustomEvent<RevealCardDetail>;
+ if (detail.column === column) {
+ scrollToCard(detail.index);
+ }
+ };
+
+ board.addEventListener(REVEAL_CARD, reveal);
+ return () => board.removeEventListener(REVEAL_CARD, reveal);
+ }, [ column, isWindowed, scrollToCard ]);
+
// The board raises its backdrop for any open field, and each column holds its own.
useEffect(() => {
setInsertingColumn(column, !!insertBefore);
@@ -550,6 +603,7 @@ export default function Column({
"with-hue": hue !== undefined,
"board-column-archived": archived,
"editing-open": hasEditedCard || !!insertBefore,
+ windowed: isWindowed,
"over-limit": isOverLimit,
collapsed: isCollapsed,
"quick-collapse": isCollapsingByHand,
@@ -674,8 +728,11 @@ export default function Column({
className={clsx("board-column-content", scrollFade.className)}
style={scrollFade.style}
onWheel={handleScroll}
+ data-window-from={isWindowed ? windowFrom : undefined}
+ data-window-count={isWindowed ? noteIds.length : undefined}
>
- {(columnItems ?? []).map(({ note, branch }, index) => (
+ <div className="board-window-spacer" style={{ height: `${bounds.above}px` }} />
+ {shownItems.map(({ note, branch }, offset) => (
<Fragment key={note.noteId}>
{insertBefore?.branchId === branch.branchId && insertField}
<Card
@@ -683,7 +740,7 @@ export default function Column({
note={note}
branch={branch}
column={column}
- index={index}
+ index={bounds.from + offset}
statusAttribute={api.statusAttribute}
isNew={note.noteId === createdNoteId
|| note.noteId === landedNoteId}
@@ -696,6 +753,7 @@ export default function Column({
/>
</Fragment>
))}
+ <div className="board-window-spacer" style={{ height: `${bounds.below}px` }} />
{insertBefore && !insertBefore.branchId && insertField}
{/* 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. */}
diff --git a/apps/client/src/widgets/collections/board/drag_measure.ts b/apps/client/src/widgets/collections/board/drag_measure.ts
index 62825b6f7a..f07197ae14 100644
--- a/apps/client/src/widgets/collections/board/drag_measure.ts
+++ b/apps/client/src/widgets/collections/board/drag_measure.ts
@@ -107,12 +107,13 @@ function measureCards(area: HTMLElement | null): CardBox[] {
const counted = countCards(area, false);
const { cards, elements } = counted;
- const last = cards.length - 1;
+ // The last card the column actually draws, which in a windowed one is not the last it holds.
+ const last = counted.drawnFrom + elements.length - 1;
// A card whose title or attributes changed stands a different height, and nothing says so, so
// where the last card really is settles whether what was remembered still holds.
- if (counted.borrowed && last > 0) {
- const at = elements[last].getBoundingClientRect().top - counted.top;
+ if (counted.borrowed && elements.length > 1 && cards[last]) {
+ const at = elements[elements.length - 1].getBoundingClientRect().top - counted.top;
if (Math.abs(at - cards[last].top) > 1) {
for (const element of elements) {
heights.delete(element.dataset.noteId ?? "");
@@ -133,6 +134,10 @@ function measureCards(area: HTMLElement | null): CardBox[] {
function countCards(area: HTMLElement, readEvery: boolean) {
const top = area.getBoundingClientRect().top - area.scrollTop;
const cards: CardBox[] = [];
+ // A windowed column draws a slice of itself. The cards it leaves undrawn are counted in below
+ // and above the ones it does, so an index here still names a place in the column rather than a
+ // place among what happens to be on screen.
+ const window = readWindow(area);
const elements: HTMLElement[] = [];
/** Where the next card stands if it has to be counted rather than read. */
let next = 0;
@@ -181,5 +186,48 @@ function countCards(area: HTMLElement, readEvery: boolean) {
next = stands + height + (spacing ?? 0);
}
- return { cards, elements, borrowed, top };
+ if (!window) {
+ return { cards, elements, borrowed, top, drawnFrom: 0 };
+ }
+
+ // The undrawn cards are spread evenly over the spacer standing for them: precise enough for a
+ // drop, which can only land where the reader can see, and it keeps every index in the column's
+ // own terms.
+ const above = spread(window.from, 0, window.above);
+ const below = spread(
+ window.total - window.from - cards.length,
+ window.above + (cards.length ? next - window.above : 0),
+ window.below);
+
+ return { cards: [ ...above, ...cards, ...below ], elements, borrowed, top, drawnFrom: window.from };
+}
+
+/** What the column says it is drawing, or nothing where it draws all of itself. */
+function readWindow(area: HTMLElement) {
+ const stated = area.dataset.windowCount;
+ const total = stated === undefined ? Number.NaN : Number(stated);
+ if (!Number.isFinite(total)) {
+ return undefined;
+ }
+
+ const spacers = area.querySelectorAll<HTMLElement>(".board-window-spacer");
+ return {
+ from: Number(area.dataset.windowFrom ?? "0") || 0,
+ total,
+ above: spacers[0]?.offsetHeight ?? 0,
+ below: spacers[1]?.offsetHeight ?? 0
+ };
+}
+
+/** Stands `count` cards evenly across a run of pixels, for the ones a column is not drawing. */
+function spread(count: number, from: number, span: number): CardBox[] {
+ if (count <= 0) {
+ return [];
+ }
+
+ const each = span / count;
+ return Array.from({ length: count }, (_, index) => ({
+ top: from + index * each,
+ height: Math.max(0, each - (spacing ?? 0))
+ }));
}
diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.css
index f8d6062a8a..e7ad197c68 100644
--- a/apps/client/src/widgets/collections/board/index.css
+++ b/apps/client/src/widgets/collections/board/index.css
@@ -625,6 +625,19 @@ body.mobile .board-view-container .board-add-column {
/* A column contains only what it can scroll itself. `contain` on both axes would also hold a
sideways swipe that starts on a card, which the column cannot scroll and the board can: Chrome
stops it at the column instead of passing it on, and the board never moves. */
+/* Stands for the cards a windowed column is not drawing, so the column is the height it would be
+ were it drawing them. */
+.board-view-container .board-window-spacer {
+ margin: 0;
+}
+
+/* A measurement that corrects the spacer above moves everything below it, and the column moves its
+ own scroll position by as much to hold the reader still. The browser must not do so as well: the
+ two chase each other and never settle. */
+.board-view-container .board-column.windowed > .board-column-content {
+ overflow-anchor: none;
+}
+
.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. */
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 456ee10e43..2d7e929f8d 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -4208,3 +4208,100 @@ describe("Board properties from the note menu", () => {
return host;
}
});
+
+describe("a column windowed for its size", () => {
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ saved.length = 0;
+ vi.restoreAllMocks();
+ vi.spyOn(server, "put").mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ it("draws a slice of a big column and stands spacers for the rest", async () => {
+ const board = await renderSized(200, 3);
+ const columns = board.querySelectorAll<HTMLElement>(".board-column");
+ const big = columns[0];
+ const small = columns[1];
+ if (!big || !small) throw new Error("expected two columns");
+
+ const drawn = big.querySelectorAll(".board-note");
+ expect(drawn.length).toBeGreaterThan(0);
+ expect(drawn.length).toBeLessThan(200);
+ expect(big.classList.contains("windowed")).toBe(true);
+
+ const area = big.querySelector<HTMLElement>(".board-column-content");
+ expect(area?.dataset.windowCount).toBe("200");
+ expect(area?.dataset.windowFrom).toBe("0");
+
+ // The cards it is not drawing are held by the spacer below them.
+ const spacers = big.querySelectorAll<HTMLElement>(".board-window-spacer");
+ expect(spacers).toHaveLength(2);
+ expect(spacers[0].style.height).toBe("0px");
+ expect(Number.parseFloat(spacers[1].style.height)).toBeGreaterThan(0);
+
+ // A column that fits keeps the path it has always had.
+ expect(small.classList.contains("windowed")).toBe(false);
+ expect(small.querySelectorAll(".board-note")).toHaveLength(3);
+ expect(small.querySelector<HTMLElement>(".board-column-content")?.dataset.windowCount)
+ .toBeUndefined();
+ });
+
+ /**
+ * The drag and the keyboard both name a card by the place it holds in its column. Counting
+ * drawn elements would name a place among whatever is on screen, which moves as it scrolls.
+ */
+ it("gives each card the place it holds in the column, not among the ones drawn", async () => {
+ const board = await renderSized(200, 3);
+ const drawn = [ ...board.querySelectorAll<HTMLElement>(".board-column-content .board-note") ];
+ const big = drawn.filter((card) => card.closest(".board-column")
+ === board.querySelector(".board-column"));
+
+ expect(big.map((card) => card.dataset.index))
+ .toEqual(big.map((_, index) => String(index)));
+ });
+
+ async function renderSized(big: number, small: number) {
+ const note = buildNote({
+ title: "Board",
+ "#collection": "",
+ "#viewType": "board",
+ children: [
+ ...Array.from({ length: big }, (_, i) => ({
+ title: `Big ${i}`, "#status": "To Do"
+ })),
+ ...Array.from({ length: small }, (_, i) => ({
+ title: `Small ${i}`, "#status": "Done"
+ }))
+ ]
+ });
+
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={{ columns: [ { value: "To Do" }, { value: "Done" } ] }}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await act(async () => { await flush(); });
+
+ return mountPoint;
+ }
+});
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index ff6789a7a0..f03bde9bda 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -1,3 +1,4 @@
+import { askForCard } from "./windowing";
import { cardFollows } from "./columns";
import { RefObject } from "preact";
import { useCallback, useLayoutEffect, useRef } from "preact/hooks";
@@ -106,6 +107,8 @@ export function useBoardKeyboard({
sendCardsToColumn, moveCardsWithin
}: BoardKeyboardOptions) {
const pendingFocus = useRef<PendingFocus | null>(null);
+ /** The card a column has been asked to draw, so it is not asked for again each render. */
+ const asked = useRef<string | null>(null);
// Every render, since a redraw is the only thing that takes focus away here and more than one
// of them follows a move.
@@ -136,7 +139,28 @@ export function useBoardKeyboard({
if (element) {
reveal(element);
+ return;
}
+
+ // The card has landed in a windowed column that is not drawing it, so there is nothing to
+ // focus yet. The column is asked to scroll to it, which draws it.
+ //
+ // Waited for here rather than left to this effect running again: the scroll re-renders the
+ // column alone, and the board this effect belongs to is not drawn again by it.
+ const { noteId } = pending.intent;
+ if (asked.current === noteId) return;
+
+ const place = placeOf(byColumn, noteId);
+ if (!place) return;
+
+ asked.current = noteId;
+ askForCard(container, place.column, place.index);
+ waitForCard(container, noteId, (card) => {
+ asked.current = null;
+ if (pendingFocus.current === pending && document.activeElement === document.body) {
+ reveal(card);
+ }
+ });
});
/**
@@ -419,7 +443,7 @@ function spotOf(container: HTMLElement, element: Element | null): Spot | null {
const card = element.closest(".board-note");
if (!card) return null;
- return { kind: "item", column, item: cardsOf(columnElement).indexOf(card as HTMLElement) };
+ return { kind: "item", column, item: indexOfCard(card as HTMLElement, columnElement) };
}
/**
@@ -434,10 +458,30 @@ function walk(container: HTMLElement, from: Spot, key: string) {
if (!next) return false;
const element = elementAt(container, next);
- if (!element) return false;
+ if (element) {
+ reveal(element);
+ return true;
+ }
+
+ // A windowed column draws a slice of its cards, and the walk has stepped onto one outside it.
+ // The column is asked to bring it into view, which is what puts it in the page to be focused.
+ if (next.kind === "item") {
+ const column = columnsOf(container)[next.column];
+ const value = column?.dataset.column;
+ if (!column || value === undefined) return false;
+
+ askForCard(container, value, next.item);
+ // Focused on the frame after the column has drawn it: the element does not exist yet.
+ requestAnimationFrame(() => {
+ const arrived = cardAt(column, next.item);
+ if (arrived) {
+ reveal(arrived);
+ }
+ });
+ return true;
+ }
- reveal(element);
- return true;
+ return false;
}
function destination(container: HTMLElement, from: Spot, key: string): Spot | null {
@@ -456,7 +500,7 @@ function destination(container: HTMLElement, from: Spot, key: string): Spot | nu
if (from.kind === "add-column") return null;
- const items = cardsOf(columnsOf(container)[from.column]).length;
+ const items = cardCountOf(columnsOf(container)[from.column]);
if (key === "Home") return entryOf(container, from.column);
if (key === "End") {
return items
@@ -483,7 +527,7 @@ function entryOf(container: HTMLElement, column: number): Spot {
return { kind: "header", column };
}
- return cardsOf(element).length
+ return cardCountOf(element)
? { kind: "item", column, item: 0 }
: { kind: "add-item", column };
}
@@ -655,7 +699,41 @@ function elementAt(container: HTMLElement, spot: Spot): HTMLElement | null {
if (spot.kind === "header") return column.querySelector("h3");
if (spot.kind === "add-item") return column.querySelector(".board-new-item");
- return cardsOf(column)[spot.item] ?? null;
+ return cardAt(column, spot.item);
+}
+
+/**
+ * Watches for a card to be drawn, for the few frames a column takes to scroll to it.
+ *
+ * Given up on rather than waited for indefinitely: a card that never arrives means the move did not
+ * land where it was expected, and focus is better left alone than chased.
+ */
+function waitForCard(
+ container: HTMLElement, noteId: string, then: (card: HTMLElement) => void, tries = 8
+) {
+ const card = findCard(container, noteId);
+ if (card) {
+ then(card);
+ return;
+ }
+
+ if (tries > 0) {
+ requestAnimationFrame(() => waitForCard(container, noteId, then, tries - 1));
+ }
+}
+
+/** Which column holds a note and where in it, for a card the board is not drawing. */
+function placeOf(byColumn: ColumnMap | undefined, noteId: string) {
+ if (!byColumn) return undefined;
+
+ for (const [ column, items ] of byColumn) {
+ const index = items.findIndex((item) => item.note.noteId === noteId);
+ if (index >= 0) {
+ return { column, index };
+ }
+ }
+
+ return undefined;
}
/** Found by what it stands for rather than by where it sits, which a move is about to change. */
@@ -681,3 +759,31 @@ function cardsOf(column: Element | undefined) {
return [ ...column.querySelectorAll<HTMLElement>(".board-note") ];
}
+
+/**
+ * How many cards a column holds, which a windowed one draws only part of.
+ *
+ * Read from what the column states rather than counted off the page, or walking one would stop at
+ * the edge of what happens to be drawn.
+ */
+function cardCountOf(column: Element | undefined) {
+ if (!column || column.classList.contains("collapsed")) {
+ return 0;
+ }
+
+ const stated = column.querySelector<HTMLElement>(".board-column-content")?.dataset.windowCount;
+ const count = stated === undefined ? Number.NaN : Number(stated);
+ return Number.isFinite(count) ? count : cardsOf(column).length;
+}
+
+/** The place a card holds in its column, which it states for a windowed one. */
+function indexOfCard(card: HTMLElement, column: Element | undefined) {
+ const stated = card.dataset.index;
+ const index = stated === undefined ? Number.NaN : Number(stated);
+ return Number.isFinite(index) ? index : cardsOf(column).indexOf(card);
+}
+
+/** The card at a place in a column, or nothing where the column is not drawing it. */
+function cardAt(column: Element, index: number) {
+ return column.querySelector<HTMLElement>(`.board-note[data-index="${index}"]`);
+}
diff --git a/apps/client/src/widgets/collections/board/windowing.spec.tsx b/apps/client/src/widgets/collections/board/windowing.spec.tsx
new file mode 100644
index 0000000000..5cc6be8421
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/windowing.spec.tsx
@@ -0,0 +1,264 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ type ColumnWindow, computeWindow, estimateFrom, forgetWindowHeights, NOMINAL_CARD_HEIGHT,
+ resolveHeights, sameWindow, useColumnWindow, type WindowInput
+} from "./windowing";
+
+/** A column of uniform cards, which makes every offset in a test arithmetic. */
+function column(count: number, height = 100, spacing = 10): Omit<WindowInput, "scrollTop"> {
+ return { heights: Array(count).fill(height), spacing, viewport: 500 };
+}
+
+describe("computeWindow", () => {
+ it("draws nothing for a column holding nothing", () => {
+ expect(computeWindow({ heights: [], spacing: 10, scrollTop: 0, viewport: 500 }))
+ .toEqual({ from: 0, until: 0, above: 0, below: 0 });
+ });
+
+ it("draws the whole of a column that fits, with no spacer at either end", () => {
+ const win = computeWindow({ ...column(4), scrollTop: 0, overscan: 0, chunk: 1 });
+ expect(win).toEqual({ from: 0, until: 4, above: 0, below: 0 });
+ });
+
+ it("draws what the area shows plus the overscan, and stands the spacers on the rest", () => {
+ // Cards are 110px apart. At 1000px down, the area covers cards 9 through 13.
+ const win = computeWindow({ ...column(100), scrollTop: 1000, overscan: 0, chunk: 1 });
+
+ expect(win.from).toBe(9);
+ expect(win.until).toBe(14);
+ expect(win.above).toBe(9 * 110);
+ expect(win.below).toBe((100 - 14) * 110);
+ // What the spacers and the drawn cards stand at together is the column's own height.
+ expect(win.above + (win.until - win.from) * 110 + win.below).toBe(100 * 110);
+ });
+
+ it("widens the window by the overscan at both ends", () => {
+ const tight = computeWindow({ ...column(100), scrollTop: 1000, overscan: 0, chunk: 1 });
+ const loose = computeWindow({ ...column(100), scrollTop: 1000, overscan: 220, chunk: 1 });
+
+ expect(loose.from).toBe(tight.from - 2);
+ expect(loose.until).toBe(tight.until + 2);
+ });
+
+ it("rounds the edges outwards to whole chunks, so scrolling by a card redraws nothing", () => {
+ const first = computeWindow({ ...column(500), scrollTop: 1000, overscan: 0, chunk: 25 });
+ const nudged = computeWindow({ ...column(500), scrollTop: 1050, overscan: 0, chunk: 25 });
+
+ expect(first.from % 25).toBe(0);
+ expect(first.until % 25).toBe(0);
+ expect(sameWindow(first, nudged)).toBe(true);
+ });
+
+ it("moves the window on once the reader has passed a chunk", () => {
+ const near = computeWindow({ ...column(500), scrollTop: 1000, overscan: 0, chunk: 25 });
+ const far = computeWindow({ ...column(500), scrollTop: 6000, overscan: 0, chunk: 25 });
+
+ expect(sameWindow(near, far)).toBe(false);
+ expect(far.from).toBeGreaterThan(near.from);
+ });
+
+ it("keeps the top spacer at nothing while the reader is at the top", () => {
+ const win = computeWindow({ ...column(500), scrollTop: 0, overscan: 800, chunk: 25 });
+ expect(win.from).toBe(0);
+ expect(win.above).toBe(0);
+ });
+
+ it("keeps the foot spacer at nothing once the last card is drawn", () => {
+ const heights = Array(500).fill(100);
+ const total = 500 * 110;
+ const win = computeWindow({
+ heights, spacing: 10, viewport: 500, scrollTop: total - 500, overscan: 0, chunk: 25
+ });
+
+ expect(win.until).toBe(500);
+ expect(win.below).toBe(0);
+ });
+
+ it("draws the last cards rather than nothing when scrolled past the end", () => {
+ const win = computeWindow({
+ ...column(300), scrollTop: 999_999, overscan: 0, chunk: 25
+ });
+
+ expect(win.until).toBe(300);
+ expect(win.from).toBeLessThan(300);
+ expect(win.below).toBe(0);
+ });
+
+ it("draws from the top for a scroll position above it", () => {
+ const win = computeWindow({ ...column(300), scrollTop: -200, overscan: 0, chunk: 25 });
+ expect(win.from).toBe(0);
+ expect(win.above).toBe(0);
+ });
+
+ it("counts cards of differing heights rather than assuming one height", () => {
+ const heights = [ 50, 300, 50, 300, 50 ];
+ const win = computeWindow({
+ heights, spacing: 0, viewport: 100, scrollTop: 350, overscan: 0, chunk: 1
+ });
+
+ // 350px down is inside the third card, which begins at 350.
+ expect(win.from).toBe(2);
+ expect(win.above).toBe(350);
+ expect(win.above + heights.slice(win.from, win.until).reduce((a, b) => a + b, 0)
+ + win.below).toBe(750);
+ });
+
+ it("adds up to the column's own height at every scroll position", () => {
+ const heights = Array.from({ length: 200 }, (_, i) => 40 + (i % 7) * 15);
+ const total = heights.reduce((sum, h) => sum + h + 9, 0);
+
+ for (let scrollTop = 0; scrollTop < total; scrollTop += 137) {
+ const win = computeWindow({
+ heights, spacing: 9, viewport: 600, scrollTop, overscan: 300, chunk: 25
+ });
+ const drawn = heights.slice(win.from, win.until)
+ .reduce((sum, h) => sum + h + 9, 0);
+ expect(win.above + drawn + win.below).toBe(total);
+ }
+ });
+});
+
+describe("resolveHeights", () => {
+ it("uses the nominal height while nothing has been measured", () => {
+ expect(resolveHeights([ "a", "b" ], new Map()))
+ .toEqual([ NOMINAL_CARD_HEIGHT, NOMINAL_CARD_HEIGHT ]);
+ });
+
+ it("uses what was measured, and the figure it is given for the rest", () => {
+ const measured = new Map([ [ "a", 80 ], [ "c", 120 ] ]);
+ expect(resolveHeights([ "a", "b", "c", "d" ], measured, 90))
+ .toEqual([ 80, 90, 120, 90 ]);
+ });
+});
+
+describe("estimateFrom", () => {
+ beforeEach(() => forgetWindowHeights());
+
+ it("stands at the nominal height until enough cards have been measured", () => {
+ const measured = new Map([ [ "a", 200 ], [ "b", 200 ] ]);
+ expect(estimateFrom(measured)).toBe(NOMINAL_CARD_HEIGHT);
+ });
+
+ it("settles on the average once there are enough of them", () => {
+ const measured = new Map(
+ Array.from({ length: 12 }, (_, i) => [ `n${i}`, 100 ] as const));
+ expect(estimateFrom(measured)).toBe(100);
+ });
+
+ /**
+ * The spacer above the window is counted from this, and the spacer is what holds the reader's
+ * place: a figure that kept being revised would move the column under them as they read it.
+ */
+ it("never moves again once it has settled", () => {
+ const measured = new Map<string, number>(
+ Array.from({ length: 12 }, (_, i) => [ `n${i}`, 100 ]));
+ expect(estimateFrom(measured)).toBe(100);
+
+ for (let i = 0; i < 40; i++) {
+ measured.set(`tall${i}`, 500);
+ }
+
+ expect(estimateFrom(measured)).toBe(100);
+ });
+});
+
+describe("sameWindow", () => {
+ it("compares the cards drawn and not the spacers around them", () => {
+ const a = { from: 0, until: 25, above: 0, below: 100 };
+ const b = { from: 0, until: 25, above: 0, below: 250 };
+ const c = { from: 25, until: 50, above: 0, below: 100 };
+
+ expect(sameWindow(a, b)).toBe(true);
+ expect(sameWindow(a, c)).toBe(false);
+ });
+});
+
+describe("useColumnWindow", () => {
+ let host: HTMLElement | undefined;
+ let area: HTMLElement | undefined;
+
+ beforeEach(() => {
+ forgetWindowHeights();
+ host = document.createElement("div");
+ area = document.createElement("div");
+ document.body.appendChild(host);
+ document.body.appendChild(area);
+ // happy-dom lays nothing out, so the area is told what it stands at.
+ Object.defineProperty(area, "clientHeight", { value: 600, configurable: true });
+ });
+
+ afterEach(() => {
+ if (host) render(null, host);
+ host?.remove();
+ area?.remove();
+ host = undefined;
+ area = undefined;
+ });
+
+ /** Renders a probe that does nothing but report what the hook hands back. */
+ async function probe(noteIds: string[], enabled = true) {
+ const seen: { bounds: ColumnWindow, windowChanged: boolean }[] = [];
+ const ref = { current: area ?? null };
+
+ function Probe() {
+ seen.push(useColumnWindow(ref, noteIds, enabled));
+ return null;
+ }
+
+ await act(async () => {
+ render(<Probe />, host ?? document.body);
+ });
+ return { seen, last: () => seen[seen.length - 1] };
+ }
+
+ const ids = (count: number) => Array.from({ length: count }, (_, i) => `note${i}`);
+
+ it("draws every card of a column it is switched off for", async () => {
+ const { last } = await probe(ids(500), false);
+ expect(last().bounds).toEqual({ from: 0, until: 500, above: 0, below: 0 });
+ expect(last().windowChanged).toBe(false);
+ });
+
+ it("draws a slice of a column it is switched on for, with the rest in the spacers", async () => {
+ const { last } = await probe(ids(500));
+ const { bounds } = last();
+
+ expect(bounds.from).toBe(0);
+ expect(bounds.until).toBeGreaterThan(0);
+ expect(bounds.until).toBeLessThan(500);
+ expect(bounds.above).toBe(0);
+ expect(bounds.below).toBeGreaterThan(0);
+ });
+
+ it("moves the window when the column is scrolled, and says that it changed", async () => {
+ const { last } = await probe(ids(2000));
+ const first = last().bounds;
+
+ await act(async () => {
+ if (area) area.scrollTop = 20_000;
+ area?.dispatchEvent(new Event("scroll"));
+ });
+
+ const moved = last().bounds;
+ expect(moved.from).toBeGreaterThan(first.from);
+ expect(moved.above).toBeGreaterThan(first.above);
+ // The flip has to be told, or it slides cards from places that named other cards.
+ expect(last().windowChanged).toBe(true);
+ });
+
+ it("leaves the window alone for a scroll that stays inside the chunk it is drawing", async () => {
+ const { last } = await probe(ids(2000));
+ const first = last().bounds;
+
+ await act(async () => {
+ if (area) area.scrollTop = 1;
+ area?.dispatchEvent(new Event("scroll"));
+ });
+
+ expect(last().bounds.from).toBe(first.from);
+ expect(last().windowChanged).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/windowing.ts b/apps/client/src/widgets/collections/board/windowing.ts
new file mode 100644
index 0000000000..fccc06e9c5
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/windowing.ts
@@ -0,0 +1,316 @@
+/**
+ * Which of a column's cards are drawn, for a column holding more of them than the page can carry.
+ *
+ * A board keeps every card of every column in the page, and the cost of that is not the elements
+ * inside a card but the card itself: the style rules the page holds are matched against each one,
+ * so a column of thousands makes scrolling, dragging and hovering it cost hundreds of milliseconds.
+ * Drawing only what the reader can see, with a spacer standing for the rest, takes those back to
+ * the frame budget.
+ */
+
+import { RefObject } from "preact";
+import {
+ useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState
+} from "preact/hooks";
+
+import { cardSpacing } from "./drag_measure";
+
+/** What a card stands at before anything has measured it: one line of title with its padding. */
+export const NOMINAL_CARD_HEIGHT = 64;
+
+/** How far past each edge of the area cards are still drawn, so scrolling has somewhere to go. */
+export const OVERSCAN_PX = 800;
+
+/** The window's edges move in steps of this many cards, so a scroll swaps them in batches. */
+export const WINDOW_CHUNK = 25;
+
+/** What a column holds before it is worth windowing at all. */
+export const WINDOW_THRESHOLD = 120;
+
+export interface ColumnWindow {
+ /** The first card drawn. */
+ from: number;
+ /** One past the last card drawn. */
+ until: number;
+ /** What the spacer above the drawn cards stands at, in pixels. */
+ above: number;
+ /** What the spacer below them stands at, in pixels. */
+ below: number;
+}
+
+export interface WindowInput {
+ /** What each card stands at, in the order the column holds them. */
+ heights: readonly number[];
+ /** What stands between one card and the next. */
+ spacing: number;
+ scrollTop: number;
+ /** What the area drawing the cards stands at. */
+ viewport: number;
+ overscan?: number;
+ /** How many cards the window's edges move by. One card, for a test that wants no batching. */
+ chunk?: number;
+}
+
+/**
+ * The cards to draw at a scroll position, and what the spacers around them stand at.
+ *
+ * The edges are rounded outwards to whole chunks so that scrolling by a card does not redraw the
+ * column: a window only changes once the reader has passed a chunk of them.
+ */
+export function computeWindow({
+ heights, spacing, scrollTop, viewport, overscan = OVERSCAN_PX, chunk = WINDOW_CHUNK
+}: WindowInput): ColumnWindow {
+ const count = heights.length;
+ if (count === 0) {
+ return { from: 0, until: 0, above: 0, below: 0 };
+ }
+
+ const top = scrollTop - overscan;
+ const bottom = scrollTop + viewport + overscan;
+ let first = count;
+ let last = -1;
+ let offset = 0;
+ /** Where each drawn edge stands, kept while walking so neither is measured a second time. */
+ const edges: number[] = [];
+
+ for (const [index, height] of heights.entries()) {
+ edges.push(offset);
+ const foot = offset + height;
+ if (foot > top && first === count) {
+ first = index;
+ }
+ if (offset < bottom) {
+ last = index;
+ }
+ offset += height + spacing;
+ }
+ edges.push(offset);
+
+ // Nothing is in view when the column is scrolled past its own end, which a shrinking column
+ // leaves the reader at. The last chunk is drawn instead, so the column is never blank.
+ if (last < 0 || first > last) {
+ first = Math.max(0, count - 1);
+ last = count - 1;
+ }
+
+ const from = Math.max(0, Math.floor(first / chunk) * chunk);
+ const until = Math.min(count, Math.ceil((last + 1) / chunk) * chunk);
+
+ return {
+ from,
+ until,
+ above: edges[from] ?? 0,
+ // The spacing below the last drawn card is its own margin, so the spacer stands for what
+ // is left after it.
+ below: Math.max(0, (edges[count] ?? 0) - (edges[until] ?? edges[count] ?? 0))
+ };
+}
+
+/**
+ * What each card stands at, measured where it has been drawn and estimated where it has not.
+ *
+ * The estimate is the average of what has been measured, so a column of tall cards is not counted
+ * as a column of short ones once any of them has been seen.
+ */
+export function resolveHeights(
+ noteIds: readonly string[],
+ measured: ReadonlyMap<string, number>,
+ nominal = NOMINAL_CARD_HEIGHT
+): number[] {
+ return noteIds.map((noteId) => measured.get(noteId) ?? nominal);
+}
+
+/**
+ * What an unmeasured card is counted at, settled once from the first cards drawn and left alone
+ * after that.
+ *
+ * It has to stop moving. The spacer above the window is what holds the reader's place, and it is
+ * counted from these: a figure that kept being revised would move every card under them on every
+ * measurement, and the column would creep while they read it.
+ */
+export function estimateFrom(measured: ReadonlyMap<string, number>) {
+ if (estimate !== undefined || measured.size < ESTIMATE_SAMPLE) {
+ return estimate ?? NOMINAL_CARD_HEIGHT;
+ }
+
+ let total = 0;
+ for (const height of measured.values()) {
+ total += height;
+ }
+
+ estimate = total / measured.size;
+ return estimate;
+}
+
+/** How many cards are measured before what the rest are counted at is settled. */
+const ESTIMATE_SAMPLE = 12;
+
+let estimate: number | undefined;
+
+/**
+ * Whether two windows draw the same cards.
+ *
+ * The spacers are left out: they follow from the heights, and a measurement that only corrects
+ * them must not count as a change that redraws the column.
+ */
+export function sameWindow(a: ColumnWindow, b: ColumnWindow) {
+ return a.from === b.from && a.until === b.until;
+}
+
+/**
+ * The window a column draws, kept in step with its scrolling and with what its cards measure.
+ *
+ * Heights are learned as cards are drawn and remembered by note, so a card that has been on screen
+ * once is counted at its own height afterwards rather than at the estimate. Correcting a height
+ * above the reader would slide the column under them, so the scroll position is moved by the same
+ * amount in the frame the correction lands.
+ *
+ * @param areaRef the scrolling element the cards are drawn in.
+ * @param noteIds the column's cards, in the order it holds them.
+ * @param enabled whether this column is windowed at all.
+ */
+export function useColumnWindow(
+ areaRef: RefObject<HTMLElement>,
+ noteIds: readonly string[],
+ enabled: boolean
+) {
+ const [ revision, setRevision ] = useState(0);
+ const [ scroll, setScroll ] = useState({ top: 0, viewport: 0 });
+ const heights = useMemo(
+ () => resolveHeights(noteIds, cardHeights, estimateFrom(cardHeights)),
+ // `revision` stands for the measurements, which live outside the render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [ noteIds, revision ]);
+ const spacing = cardSpacing() || DEFAULT_SPACING;
+
+ const bounds = useMemo(() => (enabled
+ ? computeWindow({
+ heights, spacing, scrollTop: scroll.top, viewport: scroll.viewport
+ })
+ : { from: 0, until: noteIds.length, above: 0, below: 0 }
+ ), [ enabled, heights, spacing, scroll.top, scroll.viewport, noteIds.length ]);
+
+ /** What the last commit drew, so a change of window can be told from a change of spacer. */
+ const drawn = useRef(bounds);
+ const changed = enabled && !sameWindow(drawn.current, bounds);
+ drawn.current = bounds;
+
+ // Follows the column's own scrolling. Read in the event rather than through state, so the
+ // window keeps up with the finger instead of trailing it by a frame.
+ useEffect(() => {
+ const area = areaRef.current;
+ if (!area || !enabled) return;
+
+ const read = () => setScroll((current) => (
+ current.top === area.scrollTop && current.viewport === area.clientHeight
+ ? current
+ : { top: area.scrollTop, viewport: area.clientHeight }));
+
+ read();
+ area.addEventListener("scroll", read, { passive: true });
+ const resize = new ResizeObserver(read);
+ resize.observe(area);
+
+ return () => {
+ area.removeEventListener("scroll", read);
+ resize.disconnect();
+ };
+ }, [ areaRef, enabled ]);
+
+ /** What the spacer above stood at last, and for which first card, so a correction is spotted. */
+ const above = useRef({ from: bounds.from, height: bounds.above });
+ useLayoutEffect(() => {
+ const area = areaRef.current;
+ if (!area || !enabled) {
+ above.current = { from: bounds.from, height: bounds.above };
+ return;
+ }
+
+ // A correction to what the undrawn cards are counted at moves everything below it, so the
+ // column is scrolled by as much to leave what the reader is looking at where it was.
+ //
+ // Only where the same cards are still drawn: a window that moved because the reader
+ // scrolled has a different spacer above it by rights, and the scroll position that moved
+ // it is already the one they asked for.
+ const held = above.current;
+ const shift = held.from === bounds.from ? bounds.above - held.height : 0;
+ above.current = { from: bounds.from, height: bounds.above };
+ if (Math.abs(shift) > 1 && area.scrollTop > 0) {
+ area.scrollTop += shift;
+ }
+
+ let corrected = false;
+ for (const card of area.querySelectorAll<HTMLElement>(".board-note")) {
+ const noteId = card.dataset.noteId;
+ const height = card.offsetHeight;
+ // A card holding the field its title is typed in stands taller than the card does, and
+ // a carried one is out of the flow at no height at all.
+ if (!noteId || !height || card.classList.contains("editing")) continue;
+
+ const known = cardHeights.get(noteId);
+ if (known === undefined || Math.abs(known - height) > 0.5) {
+ cardHeights.set(noteId, height);
+ corrected = true;
+ }
+ }
+
+ if (corrected) {
+ setRevision((r) => r + 1);
+ }
+ });
+
+ /**
+ * Brings a card into the window, for one the column has just made where the reader is not
+ * looking. The scroll is what moves the window: it is worked out from the same heights.
+ */
+ const scrollToCard = useCallback((index: number) => {
+ const area = areaRef.current;
+ if (!area || !enabled) return;
+
+ let offset = 0;
+ for (const [ at, height ] of heights.entries()) {
+ if (at >= index) break;
+ offset += height + spacing;
+ }
+
+ // Placed a little above the foot of the area, so the card is not left under its own edge.
+ area.scrollTop = Math.max(0, offset - area.clientHeight / 2);
+ }, [ areaRef, enabled, heights, spacing ]);
+
+ return { bounds, windowChanged: changed, scrollToCard };
+}
+
+/**
+ * Asks the column drawing `column` to bring a card into view.
+ *
+ * The keyboard walks a column by index and can step onto a card outside the window, which is not
+ * in the page to be focused. The column answers by scrolling to it, which draws it.
+ */
+export function askForCard(container: HTMLElement, column: string, index: number) {
+ container.dispatchEvent(new CustomEvent(REVEAL_CARD, { detail: { column, index } }));
+}
+
+/** The event {@link askForCard} raises, which a windowed column listens for. */
+export const REVEAL_CARD = "board:reveal-card";
+
+export interface RevealCardDetail {
+ column: string;
+ index: number;
+}
+
+/** Drops what has been measured, for a window whose size has changed under it. */
+export function forgetWindowHeights() {
+ cardHeights.clear();
+ estimate = undefined;
+}
+
+/**
+ * What each card measured, by note, kept for as long as the page is open.
+ *
+ * Shared by every board: a card keeps its height wherever it is drawn, and a column that has never
+ * been scrolled still counts its cards at what they stood at somewhere else.
+ */
+const cardHeights = new Map<string, number>();
+
+/** What stands between two cards before a drag has measured it. Matches `.board-note`'s margin. */
+const DEFAULT_SPACING = 9;