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, increase test coverage
Adorian Doran129f2a23fd0e
diff --git a/apps/client/src/widgets/collections/board/board_drag.ts b/apps/client/src/widgets/collections/board/board_drag.tsindex 995675bec2..2b5ebceec3 100644--- a/apps/client/src/widgets/collections/board/board_drag.ts+++ b/apps/client/src/widgets/collections/board/board_drag.ts@@ -3,10 +3,13 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { useTrackedElement } from "../../react/hooks";import {- type CardBox, cardInsertionIndex, columnAt, columnCovers, columnInsertionIndex+ type CardBox, cardInsertionIndex, columnAt, type ColumnBox, columnCovers, columnInsertionIndex} from "./drag_geometry";-import { type BoardMeasurement, measureBoard, toAreaY, toBoardX } from "./drag_measure";+import {+ type BoardMeasurement, measureBoard, placeInModel, toAreaY, toBoardX+} from "./drag_measure";import { createEdgeScroller, type ScrollTarget } from "../../react/edge_scroll";+import { getColumnModel } from "./windowing";/** How far a pointer travels before a press with a button held is taken for a drag. */const MOUSE_THRESHOLD = 4;@@ -247,7 +250,7 @@ export function useBoardDrag(? {column: column.value,index: area- ? placeIn(column.cards, toAreaY(area, topY), held.card, column.value)+ ? placeAt(area, toAreaY(area, topY), held.card, column): 0}: null;@@ -541,6 +544,21 @@ function row(held: Gesture & { kind: "column" }) {return { lefts, stride: (boxes[held.index]?.width ?? 0) + gap };}+/**+ * The place a carried card would take in a column.+ *+ * A windowed column is asked what it is drawing with now: the boxes a gesture measures at its start+ * only estimate the cards it was not drawing then, and an auto-scroll draws them for real.+ */+function placeAt(area: HTMLElement, y: number, card: DraggedCard, column: ColumnBox): number {+ const model = getColumnModel(area);+ if (!model) {+ return placeIn(column.cards, y, card, column.value);+ }++ return placeInModel(model, y, column.value === card.fromColumn ? card.index : undefined);+}+/*** The place a carried card would take in a column, counting that column as the board holds it.*diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 8a968ebaaf..94a529360f 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -561,7 +561,7 @@ export default function Column({const reveal = (event: Event) => {const { detail } = event as CustomEvent<RevealCardDetail>;if (detail.column === column) {- scrollToCard(detail.index);+ scrollToCard(detail.index, detail.immediate);}};diff --git a/apps/client/src/widgets/collections/board/drag_measure.spec.ts b/apps/client/src/widgets/collections/board/drag_measure.spec.tsindex 6c730a3367..45e9a08ecd 100644--- a/apps/client/src/widgets/collections/board/drag_measure.spec.ts+++ b/apps/client/src/widgets/collections/board/drag_measure.spec.ts@@ -1,7 +1,9 @@import { afterEach, beforeEach, describe, expect, it } from "vitest";import { cardInsertionIndex, columnAt } from "./drag_geometry";-import { forgetCardHeights, measureBoard, toAreaY, toBoardX } from "./drag_measure";+import {+ forgetCardHeights, measureBoard, placeInModel, toAreaY, toBoardX+} from "./drag_measure";let container: HTMLElement | undefined;@@ -226,3 +228,60 @@ describe("reading a point against a measurement", () => {}});});++describe("placeInModel", () => {+ /** The boxes a column of these heights lays out, for comparing against the geometry. */+ const boxesOf = (heights: number[], spacing: number) => {+ let top = 0;+ return heights.map((height) => {+ const box = { top, height };+ top += height + spacing;+ return box;+ });+ };++ /**+ * The model has to answer exactly what the geometry answers from the boxes: it stands in for+ * reading the page, and a column that drifts between the two puts the gap somewhere the drop+ * does not go.+ */+ it("agrees with the geometry at every point down a column", () => {+ const heights = Array.from({ length: 40 }, (_, i) => 40 + (i % 5) * 20);+ const spacing = 9;+ const boxes = boxesOf(heights, spacing);+ const foot = boxes[boxes.length - 1].top + boxes[boxes.length - 1].height;++ for (let y = -20; y < foot + 40; y += 7) {+ expect(placeInModel({ heights, spacing }, y, undefined))+ .toBe(cardInsertionIndex(boxes, y));+ }+ });++ it("agrees with the geometry for a card carried within the same column", () => {+ const heights = Array.from({ length: 30 }, (_, i) => 50 + (i % 3) * 30);+ const spacing = 9;++ for (const carried of [ 0, 7, 29 ]) {+ // The carried card is out of the flow, so the column lays out without it.+ const rest = heights.filter((_, index) => index !== carried);+ const boxes = boxesOf(rest, spacing);+ const foot = boxes[boxes.length - 1].top + boxes[boxes.length - 1].height;++ for (let y = -20; y < foot + 40; y += 11) {+ const place = cardInsertionIndex(boxes, y);+ const expected = place >= carried ? place + 1 : place;+ expect(placeInModel({ heights, spacing }, y, carried)).toBe(expected);+ }+ }+ });++ it("puts a point above the column at the front and one below it at the back", () => {+ const model = { heights: [ 60, 60, 60 ], spacing: 10 };+ expect(placeInModel(model, -500, undefined)).toBe(0);+ expect(placeInModel(model, 99_999, undefined)).toBe(3);+ });++ it("answers for a column holding nothing", () => {+ expect(placeInModel({ heights: [], spacing: 9 }, 40, undefined)).toBe(0);+ });+});diff --git a/apps/client/src/widgets/collections/board/drag_measure.ts b/apps/client/src/widgets/collections/board/drag_measure.tsindex f07197ae14..f2181d7e17 100644--- a/apps/client/src/widgets/collections/board/drag_measure.ts+++ b/apps/client/src/widgets/collections/board/drag_measure.ts@@ -1,4 +1,5 @@import { type CardBox, type ColumnBox } from "./drag_geometry";+import { type ColumnModel } from "./windowing";/** What a drag measures once at its start, and reads for the rest of the gesture. */export interface BoardMeasurement {@@ -58,6 +59,47 @@ export function toBoardX(container: HTMLElement, clientX: number): number {return clientX - container.getBoundingClientRect().left + container.scrollLeft;}+/**+ * The place a carried card would take in a windowed column, counted from what the column lays its+ * cards out with rather than from the page.+ *+ * The same answer {@link cardInsertionIndex} gives for a column drawn in full, and the same+ * treatment of the carried card: it is out of the flow while it is held, so the cards below it+ * stand one place higher and the index is counted back afterwards.+ *+ * Worked out per move rather than once per gesture. A window that has moved under an auto-scroll+ * draws cards the gesture had only estimated, and an index counted from the estimate drifts further+ * from the gap the longer the scroll runs.+ *+ * @param carrying the place the carried card holds here, or `undefined` if it came from elsewhere.+ */+export function placeInModel(model: ColumnModel, y: number, carrying: number | undefined): number {+ const { heights, spacing } = model;+ let offset = 0;+ /** How many cards have been passed, the carried one not counted among them. */+ let place = 0;++ for (const [ index, height ] of heights.entries()) {+ if (index === carrying) {+ continue;+ }++ const foot = offset + height;+ const isLast = index === heights.length - 1+ || (carrying === heights.length - 1 && index === heights.length - 2);+ // Halfway into the gap below a card is where the next place begins.+ const boundary = isLast ? foot : foot + spacing / 2;+ if (y < boundary) {+ return carrying !== undefined && place >= carrying ? place + 1 : place;+ }++ offset = foot + spacing;+ place++;+ }++ return carrying !== undefined && place >= carrying ? place + 1 : place;+}+/*** A point in a card area's content space, which that column's vertical scrolling does not move its* cards in.diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 2d7e929f8d..e6635951b5 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3548,6 +3548,33 @@ describe("Board filtering", () => {return results;}+ /**+ * The move is drawn at once, into the unfiltered map. Counting the place among the shown cards+ * instead puts the card partway up the column, and it jumps to the end when the write lands.+ */+ it("sends a card to the end of the column, not to the end of what the filter shows", async () => {+ // "To Do" holds three cards and shows one, so the two counts are far enough apart to tell+ // which of them the move used.+ await setup({ matched: [ "filtered3", "filtered4" ] });+ expect(cardTitles(0)).toEqual([ "Third" ]);+ expect(cardTitles(1)).toEqual([ "Fourth" ]);++ const carried = container.querySelectorAll<HTMLElement>(".board-column")[1]+ ?.querySelector<HTMLElement>(".board-note");+ if (!carried) throw new Error("expected a card in the second column");++ carried.focus();+ await act(async () => {+ carried.dispatchEvent(new KeyboardEvent("keydown", {+ key: "ArrowLeft", ctrlKey: true, bubbles: true, cancelable: true+ }));+ await flush();+ });++ // Drawn behind the card already shown, which is where the end of the column is.+ expect(cardTitles(0)).toEqual([ "Third", "Fourth" ]);+ });+it("shows only the matched cards, in their own order, keeping every column", async () => {// The matches arrive in score order; the board must keep branch order regardless.const note = await setup({ matched: [ "filtered3", "filtered1" ] });diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 9aff522c5a..107ed42a7b 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -49,6 +49,7 @@ import Api, { getPendingWrites, PendingColumnWrites, settleColumn } from "./api"import { useBoardDrag } from "./board_drag";import { columnGapStandsAside, columnStandsAside, movesColumn } from "./drag_geometry";import { forgetCardHeights } from "./drag_measure";+import { forgetWindowHeights } from "./windowing";import { BoardDropStateContext, DropStateStore } from "./drop_state";import BoardApi from "./api";import { adoptLegacyColumns, readColumns } from "./column_storage";@@ -658,8 +659,13 @@ export default function BoardView({// measured at. A phone gives a column a share of the window, so a window that changes size// takes the heights with it.useEffect(() => {- window.addEventListener("resize", forgetCardHeights);- return () => window.removeEventListener("resize", forgetCardHeights);+ const forget = () => {+ forgetCardHeights();+ forgetWindowHeights();+ };++ window.addEventListener("resize", forget);+ return () => window.removeEventListener("resize", forget);}, []);// Which columns stand narrow, as a line, so that one opening or closing is read off a single@@ -1107,15 +1113,21 @@ export default function BoardView({const sendCardsToColumn = useCallback((cards: { noteId: string, branchId: string }[], targetColumn: string) => holdMove(- cards, targetColumn, api.getColumnNoteIds(targetColumn).length,+ // The end of the column itself, not of what a filter leaves showing of it: the move is+ // drawn into `allByColumn`, so a place counted among the shown cards would put the card+ // partway up the column and leave it to jump to the end as the write lands.+ cards, targetColumn, allByColumn?.get(targetColumn)?.length ?? 0,api.moveToColumnEnd(cards, targetColumn)),- [ api, holdMove ]);+ [ api, holdMove, allByColumn ]);/** Moves cards to a place among the ones already in a column. */const moveCardsWithin = useCallback((cards: { noteId: string, branchId: string }[], column: string, index: number- ) => holdMove(cards, column, index, api.moveWithinBoard(cards, column, index)),- [ api, holdMove ]);+ ) => holdMove(+ cards, column,+ unfilteredCardIndex(byColumn?.get(column) ?? [], allByColumn?.get(column) ?? [], index),+ api.moveWithinBoard(cards, column, index)),+ [ api, holdMove, byColumn, allByColumn ]);const clearSelectionOutsideCards = useCallback((e: MouseEvent) => {if (!(e.target as HTMLElement | null)?.closest(".board-note")) {diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.tsindex f03bde9bda..b1103695d9 100644--- a/apps/client/src/widgets/collections/board/keyboard.ts+++ b/apps/client/src/widgets/collections/board/keyboard.ts@@ -109,6 +109,8 @@ export function useBoardKeyboard({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);+ /** Where the reader last stood, for a key pressed while focus is between two draws. */+ const lastSpot = useRef<Spot | 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.@@ -197,7 +199,11 @@ export function useBoardKeyboard({// work over a board as over anything else.if (e.altKey && !e.ctrlKey) return;- const spot = spotOf(container, document.activeElement);+ const spot = spotOf(container, document.activeElement)+ // Focus can be left on nothing by a redraw that took the card it was on out of the+ // page. The walk carries on from where it last stood rather than letting the key+ // through, which would scroll the board instead of moving along it.+ ?? (NAVIGATION_KEYS.includes(e.key) ? lastSpot.current : null);if (!spot) return;if (e.ctrlKey) {@@ -274,7 +280,7 @@ export function useBoardKeyboard({if (NAVIGATION_KEYS.includes(e.key)) {// The plain arrows would otherwise scroll the page past the end of a column.take(e);- walk(container, spot, e.key);+ lastSpot.current = walk(container, spot, e.key) ?? spot;return;}@@ -453,14 +459,14 @@ function spotOf(container: HTMLElement, element: Element | null): Spot | null {* right cross to the next column's first card, or to its button where it holds none: its header is* reached by pressing up from there, which is the only way a header is reached at all.*/-function walk(container: HTMLElement, from: Spot, key: string) {+function walk(container: HTMLElement, from: Spot, key: string): Spot | null {const next = destination(container, from, key);- if (!next) return false;+ if (!next) return null;const element = elementAt(container, next);if (element) {reveal(element);- return true;+ return next;}// A windowed column draws a slice of its cards, and the walk has stepped onto one outside it.@@ -468,20 +474,20 @@ function walk(container: HTMLElement, from: Spot, key: string) {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;+ if (!column || value === undefined) return null;++ // Drawn before the ask returns, so the card is focused in this keystroke. Left to a later+ // frame, the scroll can take the card being walked from out of the page first, and focus+ // falls to nothing: the next key then finds nowhere to walk from and the board scrolls.+ askForCard(container, value, next.item, true);+ const arrived = cardAt(column, next.item);+ if (arrived) {+ reveal(arrived);+ return next;+ }}- return false;+ return null;}function destination(container: HTMLElement, from: Spot, key: string): Spot | null {diff --git a/apps/client/src/widgets/collections/board/windowing.spec.tsx b/apps/client/src/widgets/collections/board/windowing.spec.tsxindex 5cc6be8421..49e2eb1caf 100644--- a/apps/client/src/widgets/collections/board/windowing.spec.tsx+++ b/apps/client/src/widgets/collections/board/windowing.spec.tsx@@ -3,8 +3,9 @@ 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+ askForCard, type ColumnWindow, computeWindow, estimateFor, forgetWindowHeights,+ NOMINAL_CARD_HEIGHT, resolveHeights, REVEAL_CARD, type RevealCardDetail, sameWindow,+ useColumnWindow, type WindowInput} from "./windowing";/** A column of uniform cards, which makes every offset in a test arithmetic. */@@ -134,34 +135,61 @@ describe("resolveHeights", () => {});});-describe("estimateFrom", () => {- beforeEach(() => forgetWindowHeights());+describe("estimateFor", () => {+ const ids = (count: number, from = 0) =>+ Array.from({ length: count }, (_, i) => `n${from + i}`);+ const measuredAt = (count: number, height: number, from = 0) =>+ new Map(ids(count, from).map((id) => [ id, height ] as const));- 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("answers nothing until enough of the column's own cards have been measured", () => {+ expect(estimateFor(ids(50), measuredAt(2, 200), undefined)).toBeUndefined();});- 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);+ it("settles on the average of the column's measured cards", () => {+ expect(estimateFor(ids(50), measuredAt(12, 100), undefined)).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.+ * The spacer above the window is counted from this and is what holds the reader's place: a+ * figure that kept being revised would slide the column while 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);+ it("answers back what a column has already settled on", () => {+ const measured = new Map<string, number>(measuredAt(40, 500));+ expect(estimateFor(ids(50), measured, 100)).toBe(100);+ });- for (let i = 0; i < 40; i++) {- measured.set(`tall${i}`, 500);- }+ /**+ * Two boards, or two columns of one board, can carry different attributes and stand at quite+ * different heights. Counting one column's cards at another's average puts its spacers, its+ * scrollbar and its scroll destinations all in the wrong place.+ */+ it("counts only the cards the column holds, not every card measured anywhere", () => {+ const measured = new Map<string, number>([+ // A tall column measured earlier, whose cards this one does not hold.+ ...measuredAt(40, 500, 100),+ ...measuredAt(12, 60)+ ]);++ expect(estimateFor(ids(50), measured, undefined)).toBe(60);+ });+});- expect(estimateFrom(measured)).toBe(100);+describe("askForCard", () => {+ it("raises the ask on the board, naming the column, the card and how soon it is wanted", () => {+ const board = document.createElement("div");+ document.body.appendChild(board);+ const seen: RevealCardDetail[] = [];+ board.addEventListener(REVEAL_CARD, (e) =>+ seen.push((e as CustomEvent<RevealCardDetail>).detail));++ askForCard(board, "To Do", 42);+ askForCard(board, "Done", 7, true);+ board.remove();++ expect(seen).toEqual([+ { column: "To Do", index: 42, immediate: false },+ { column: "Done", index: 7, immediate: true }+ ]);});});@@ -200,7 +228,7 @@ describe("useColumnWindow", () => {/** 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 seen: ReturnType<typeof useColumnWindow>[] = [];const ref = { current: area ?? null };function Probe() {@@ -208,6 +236,7 @@ describe("useColumnWindow", () => {return null;}+await act(async () => {render(<Probe />, host ?? document.body);});@@ -249,6 +278,58 @@ describe("useColumnWindow", () => {expect(last().windowChanged).toBe(true);});+ it("scrolls to a card the column is not drawing, placing it inside the area", async () => {+ const { last } = await probe(ids(2000));++ await act(async () => last().scrollToCard(400));++ // Cards stand at the nominal height until measured, so where card 400 begins is arithmetic.+ const perCard = NOMINAL_CARD_HEIGHT + 9;+ expect(area?.scrollTop).toBe(Math.max(0, 400 * perCard - 300));+ });++ it("leaves the scroll alone for a column it is switched off for", async () => {+ const { last } = await probe(ids(2000), false);+ if (area) area.scrollTop = 42;++ await act(async () => last().scrollToCard(400));++ expect(area?.scrollTop).toBe(42);+ });++ it("draws the card before the ask returns when it is wanted at once", async () => {+ const { last } = await probe(ids(2000));+ const before = last().bounds;++ // No act(): the point is that the window has moved by the time the call returns, which is+ // what lets a keyboard walk focus the card in the same keystroke.+ last().scrollToCard(400, true);++ expect(last().bounds.from).toBeGreaterThan(before.from);+ });++ it("counts a card at what it measures once the column has drawn it", async () => {+ const noteIds = ids(2000);+ const { last } = await probe(noteIds);+ const tall = last().bounds.below;++ // The cards the column drew, standing taller than the nominal height it assumed.+ await act(async () => {+ for (const noteId of noteIds.slice(0, 30)) {+ const card = document.createElement("div");+ card.className = "board-note";+ card.dataset.noteId = noteId;+ Object.defineProperty(card, "offsetHeight", { value: 200, configurable: true });+ area?.appendChild(card);+ }+ if (area) area.scrollTop = 1;+ area?.dispatchEvent(new Event("scroll"));+ });++ // A taller column has more of itself left below the window than it was counted at.+ expect(last().bounds.below).toBeGreaterThan(tall);+ });+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;diff --git a/apps/client/src/widgets/collections/board/windowing.ts b/apps/client/src/widgets/collections/board/windowing.tsindex fccc06e9c5..d474426575 100644--- a/apps/client/src/widgets/collections/board/windowing.ts+++ b/apps/client/src/widgets/collections/board/windowing.ts@@ -9,6 +9,7 @@*/import { RefObject } from "preact";+import { flushSync } from "preact/compat";import {useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from "preact/hooks";@@ -121,31 +122,49 @@ export function resolveHeights(}/**- * What an unmeasured card is counted at, settled once from the first cards drawn and left alone- * after that.+ * What a column counts an unmeasured card at, from the cards of that column already measured.*- * 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.+ * A column's own cards, not every card the page has drawn: two boards, or two columns of one+ * board, can carry different attributes and stand at quite different heights, and counting one+ * column's cards at another's average puts its spacers, its scrollbar and its scroll destinations+ * all in the wrong place.+ *+ * Answers nothing until enough of them have been measured, and the caller then holds what it is+ * given for good. It has to stop moving: the spacer above the window holds the reader's place and+ * is counted from this, so a figure that kept being revised would slide the column as they read.+ *+ * @param held what the column has already settled on, which is answered back unchanged.*/-export function estimateFrom(measured: ReadonlyMap<string, number>) {- if (estimate !== undefined || measured.size < ESTIMATE_SAMPLE) {- return estimate ?? NOMINAL_CARD_HEIGHT;+export function estimateFor(+ noteIds: readonly string[],+ measured: ReadonlyMap<string, number>,+ held: number | undefined+) {+ if (held !== undefined) {+ return held;}let total = 0;- for (const height of measured.values()) {- total += height;+ let seen = 0;+ for (const noteId of noteIds) {+ const height = measured.get(noteId);+ if (height !== undefined) {+ total += height;+ seen++;+ }}- estimate = total / measured.size;- return estimate;+ return seen >= ESTIMATE_SAMPLE ? total / seen : undefined;}-/** How many cards are measured before what the rest are counted at is settled. */+/** How many of a column's cards are measured before what the rest are counted at is settled. */const ESTIMATE_SAMPLE = 12;-let estimate: number | undefined;+/**+ * Bumped when what has been measured is dropped, so every column settles on a fresh estimate+ * rather than holding one taken at a width the board no longer has.+ */+let generation = 0;/*** Whether two windows draw the same cards.@@ -176,11 +195,19 @@ export function useColumnWindow() {const [ revision, setRevision ] = useState(0);const [ scroll, setScroll ] = useState({ top: 0, viewport: 0 });+ /** What this column counts its unmeasured cards at, once its own have settled it. */+ const estimate = useRef<{ at: number, value?: number }>({ at: generation });+ if (estimate.current.at !== generation) {+ estimate.current = { at: generation };+ }+ estimate.current.value = estimateFor(noteIds, cardHeights, estimate.current.value);++ const settled = estimate.current.value;const heights = useMemo(- () => resolveHeights(noteIds, cardHeights, estimateFrom(cardHeights)),+ () => resolveHeights(noteIds, cardHeights, settled ?? NOMINAL_CARD_HEIGHT),// `revision` stands for the measurements, which live outside the render.// eslint-disable-next-line react-hooks/exhaustive-deps- [ noteIds, revision ]);+ [ noteIds, revision, settled ]);const spacing = cardSpacing() || DEFAULT_SPACING;const bounds = useMemo(() => (enabled@@ -259,11 +286,24 @@ export function useColumnWindow(}});+ // Published after each commit, so a gesture reads what the column is drawing with now rather+ // than what it was drawing with when the gesture started.+ useLayoutEffect(() => {+ const area = areaRef.current;+ if (!area) return;++ if (enabled) {+ models.set(area, { heights, spacing });+ } else {+ models.delete(area);+ }+ }, [ areaRef, enabled, heights, spacing ]);+/*** 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 scrollToCard = useCallback((index: number, immediate = false) => {const area = areaRef.current;if (!area || !enabled) return;@@ -275,19 +315,47 @@ export function useColumnWindow(// 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);++ if (immediate) {+ // The scroll event that would move the window arrives a frame later, so the window is+ // moved here instead and the card is in the page before this returns.+ flushSync(() => setScroll({ top: area.scrollTop, viewport: area.clientHeight }));+ }}, [ areaRef, enabled, heights, spacing ]);return { bounds, windowChanged: changed, scrollToCard };}+/**+ * What a column lays its cards out from: the heights the spacers are counted with, and the gap+ * between one card and the next.+ *+ * Published so a drag can work out where a card would land without reading the page. The page is+ * the wrong source mid-gesture: the carried card is out of the flow, the gap stands over the cards,+ * and the ones below it are moved aside by a transform.+ */+export interface ColumnModel {+ heights: readonly number[];+ spacing: number;+}++/** The model a column is drawing with, or nothing where it draws all of its cards. */+export function getColumnModel(area: HTMLElement) {+ return models.get(area);+}++const models = new WeakMap<HTMLElement, ColumnModel>();+/*** 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 } }));+export function askForCard(+ container: HTMLElement, column: string, index: number, immediate = false+) {+ container.dispatchEvent(new CustomEvent(REVEAL_CARD, { detail: { column, index, immediate } }));}/** The event {@link askForCard} raises, which a windowed column listens for. */@@ -296,12 +364,21 @@ export const REVEAL_CARD = "board:reveal-card";export interface RevealCardDetail {column: string;index: number;+ /**+ * Whether the card must be in the page by the time the ask returns.+ *+ * For a keyboard walk, which has to focus it in the same keystroke: focus left on nothing+ * while a frame is waited for makes the next key find no card to walk from, and the browser+ * scrolls the board instead. Not for an ask made while the board is drawing, where drawing+ * again in the middle of a commit is not safe.+ */+ immediate?: boolean;}/** Drops what has been measured, for a window whose size has changed under it. */export function forgetWindowHeights() {cardHeights.clear();- estimate = undefined;+ generation++;}/**