Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: fix some issues

Adorian Doranb7934db6ff0b
diff --git a/apps/client/src/widgets/collections/board/card.tsx b/apps/client/src/widgets/collections/board/card.tsx
index 876b7a6e2c..d16ce3db4d 100644
--- a/apps/client/src/widgets/collections/board/card.tsx
+++ b/apps/client/src/widgets/collections/board/card.tsx
@@ -121,9 +121,9 @@ function Card({
setTitle(note.title);
}, [ note ]);
- // A new card can be out of sight on a full column. One at either end takes the column to that
- // end, so it lands clear of the fade the scrolling body draws over its edges; one inserted
- // between others is only brought into view.
+ // A new card can be out of sight on a full column. A card at either end scrolls its column to
+ // that end, clear of the fade `useScrollFade` draws over the edges; one between others is only
+ // scrolled into view.
useLayoutEffect(() => {
if (!isNew) {
return;
@@ -146,8 +146,8 @@ function Card({
};
bring();
- // And again once it has opened out: a card asked for while it is still growing is measured
- // against a column shorter than the one it ends up in, which leaves it over the edge.
+ // Again once the growth has finished: a card scrolled to while `useFlip` is still opening
+ // it out is measured against a shorter column, and ends up past the edge.
const settled = window.setTimeout(bring, FLIP_SETTLE_MS);
return () => window.clearTimeout(settled);
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index b778bc233d..9514e7320a 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -22,7 +22,9 @@ import { useStaticTooltip } from "../../react/hooks";
import { FLIP_SETTLE_MS, useFlip } from "../../react/flip";
import { useScrollFade } from "../../react/scroll_fade";
-/** How long a column stays quiet for a card the footer is making, if the write never answers. */
+/**
+ * How long `footerQuietUntil` holds for a card `AddNewItem` is making, if the write never answers.
+ */
const FOOTER_QUIET_MS = 5000;
import NoteLink from "../../react/NoteLink";
import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";
@@ -86,23 +88,24 @@ export default function Column({
} & DragContext) {
const [ isCreatingNewItem, setIsCreatingNewItem ] = useState(false);
const [ created, setCreated ] = useState<{ noteId?: string, takesFocus: boolean }>();
- // The column stays the one just added until another is, so what has already been shown is
- // remembered here rather than played again by every redraw of the board.
+ // `isNew` stays true until another column is added, so the reveal is recorded here rather than
+ // replayed on every redraw of the board.
const [ isRevealed, setIsRevealed ] = useState(false);
/**
- * When a card the footer is making may still arrive.
+ * Until when a card from `AddNewItem` can still arrive, during which `useFlip` does not grow
+ * it.
*
- * Naming the card itself is not enough: the write answers with its id, and the refresh that
- * draws it can land first, so the card is on the board before there is anything to say it came
- * from the footer. The column is quiet from the moment the footer is asked instead.
+ * Testing the id is not enough: `createNewItem()` answers with it after the refresh that draws
+ * the card can already have run, so `created` is set too late. `onCreating` sets this before
+ * the write instead.
*/
const footerQuietUntil = useRef(0);
- // A card inserted next to another one is where the reader is working, so it is left focused; one
- // made in the footer is not, or every card would take focus from the editor still being typed in.
+ // An inserted card is left focused, since that is where the work is; a card from the footer is
+ // not, or it would take focus from the editor being typed in.
const cardInserted = useCallback(
(noteId: string | undefined) => setCreated({ noteId, takesFocus: true }), []);
const addingFromFooter = useCallback(() => {
- // Long enough to cover a write that never answers, and cut short by the one that does.
+ // Long enough for a write that never answers; `cardAdded` shortens it when one does.
footerQuietUntil.current = Date.now() + FOOTER_QUIET_MS;
}, []);
const cardAdded = useCallback((noteId: string | undefined) => {
@@ -116,13 +119,14 @@ export default function Column({
const editorRef = useRef<HTMLInputElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const scrollFade = useScrollFade(contentRef);
- // The gap opening and closing moves the cards below it, which they follow rather than jump to,
- // and a card added to the column opens the room it takes rather than appearing in it. Except
- // the one the footer just made: it is already announced by the fade and by the column running
- // to its end, and opening out on top of those is one movement too many.
+ // Cards slide to follow the drop gap opening and closing. Only the card named by `created`
+ // opens out of nothing: a card moved here from another column mounts as a new element too, and
+ // would collapse and reopen after the drop. The footer's own card is excluded as well, by
+ // `footerQuietUntil`: the scroll to the end and the fade already show it.
useFlip(contentRef, {
selector: ".board-note",
- grow: () => Date.now() > footerQuietUntil.current
+ grow: (card) => card.getAttribute("data-note-id") === created?.noteId
+ && Date.now() > footerQuietUntil.current
});
const { handleDragOver, handleDragLeave, handleDrop } = useDragging({
column, columnIndex, columnItems, isEditing, api, parentNote
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index d24cdb2a79..5bb8641105 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -1313,6 +1313,53 @@ describe("Board column rename", () => {
expect(others.some(other => other.classList.contains("appearing"))).toBe(false);
});
+ /**
+ * A card that arrives from somewhere else, a move between columns above all, mounts as a new
+ * element in the column that draws it. Only the card the column itself made opens out of
+ * nothing; the rest are already where they were put.
+ */
+ it("opens out only the card the column made, not one that merely arrived", async () => {
+ const { note, container } = await setup();
+
+ // happy-dom lays nothing out, and a child with no offset parent is one `useFlip` skips.
+ for (const [ property, read ] of Object.entries({
+ offsetParent(this: HTMLElement) { return this.parentElement; },
+ offsetHeight() { return 34; },
+ offsetTop() { return 0; }
+ })) {
+ Object.defineProperty(HTMLElement.prototype, property,
+ { configurable: true, get: read as () => unknown });
+ }
+
+ try {
+ addCard(note, "Doing");
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={new Component()}>
+ <Harness
+ note={note}
+ noteIds={[ ...note.getChildNoteIds() ]}
+ initialConfig={DEFAULT_CONFIG}
+ />
+ </ParentComponent.Provider>,
+ container
+ );
+ await flush();
+ });
+ await act(async () => { await flush(); });
+
+ const arrived = [ ...container.querySelectorAll<HTMLElement>(".board-note") ]
+ .find(card => card.textContent?.includes("Added"));
+ if (!arrived) throw new Error("expected the card that arrived to be drawn");
+ expect(arrived.style.height).toBe("");
+ expect(arrived.style.overflow).toBe("");
+ } finally {
+ for (const property of [ "offsetParent", "offsetHeight", "offsetTop" ]) {
+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)[property];
+ }
+ }
+ });
+
it("reveals a card inserted next to another one, without leaving its place", async () => {
const { note, container } = await setup();
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index 2b6a9cd2e5..0dbd6b95ae 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -158,7 +158,7 @@ export const BoardDragStateContext = createContext<BoardDragState>({
/** How long a finger stays on the create button before it offers where to put the card. */
const HOLD_TO_PLACE_MS = 500;
-/** How far a finger can wander during that and still be holding rather than scrolling. */
+/** How far the pointer can move during that and still count as a hold rather than a scroll. */
const HOLD_SLACK_PX = 10;
const BOARD_HINTS: ShortcutHintDefinition = [
@@ -311,7 +311,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
[ usableColumns, storedColumns, includeArchived ]);
const containerRef = useRef<HTMLDivElement>(null);
- /** When a column the reader moved may still be settling, which is what a slide is drawn for. */
+ /** Until when a column move can still be settling, which is when `useFlip` slides columns. */
const columnMovedUntil = useRef(0);
const boardDragState = useMemo<BoardDragState>(() => ({
@@ -479,22 +479,19 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
// is left to whatever it belongs to. Suppressed while a card is carried: the gesture owns the
// pointer, and the board must not slide under it.
const { isPannable, isPanning } = useDragPan(containerRef, { disabled: isDraggingItem });
- // The gap a carried column opens moves the columns beside it, which they follow rather than
- // jump to. Two are left out: the copy being carried, whose transform the gesture writes every
- // frame, and the add-column button, which a new column moves at the same moment as the scroll
- // that keeps it in view, so sliding it as well reads as a stumble rather than as movement.
+ // Columns slide to follow the gap a carried column opens. The selector excludes the drag
+ // preview, whose transform `useBoardDrag` writes every frame; `AddNewColumn` is outside the
+ // container, and is moved by the scroll that keeps it in view instead.
//
- // Columns are moved, never opened out. A column is its grouping value, so it is drawn afresh
- // whenever that value changes, and a rename is indistinguishable from an arrival to anything
- // watching the page. The one column that really does arrive is the one just added, and the fade
- // and the board running to its end already say so.
+ // No `grow`: a column is its grouping value, so a rename mounts a new element and is
+ // indistinguishable from an arrival. The column just added is shown by `board-item-appear` and
+ // by the scroll to the board's end.
useFlip(containerRef, {
selector: ".board-column:not(.board-drag-preview)",
axis: "horizontal",
- // Only for a move the reader made. A column is its grouping value, so the board redraws
- // its columns whenever a value changes, and the order churns for a moment as the three
- // places that name a column catch up with one another; following that draws a slide for a
- // rename nobody moved.
+ // Only for a move the reader made, tracked by `columnMovedUntil`. A value change redraws
+ // the columns, and the order churns while the cards, the definition and the stored config
+ // catch up with one another; sliding for that animates a rename as a move.
disabled: !draggedColumn && Date.now() > columnMovedUntil.current
});
@@ -816,47 +813,43 @@ export function TitleEditor({
isNewItem?: boolean;
mode?: "normal" | "multiline" | "relation";
/**
- * Whether Enter saves and clears the editor rather than closing it, so that a run of cards can
- * be typed one after another. Enter is then the only thing that saves: Escape and losing focus
- * both give up what was typed and close the editor, since an editor that stays open between
- * cards is left behind often enough that saving on the way out would make cards nobody asked
- * for.
+ * Whether Enter saves and clears the editor rather than closing it, so a run of cards can be
+ * typed one after another. Enter is then the only thing that saves: Escape and losing focus
+ * discard what was typed and close the editor. An editor left standing between cards is walked
+ * away from often enough that saving on the way out would create cards nobody asked for.
*/
saveAndContinue?: boolean;
- /** What was typed and not saved, handed over so that reopening the editor can carry it back. */
+ /** Reports what was typed and not saved, so reopening the editor can restore it. */
abandon?: (typed: string) => void;
/**
- * What the button stands for while there is nothing to save. The icon is the same wherever it
- * is offered; an editor whose caller has nothing to do yet keeps the button, which then does
- * nothing rather than coming and going as the field is typed into and emptied again.
+ * What the button does while the field is empty, drawn as `bx bx-folder-open`. Without it no
+ * button is drawn at all until something is typed.
*/
whenEmpty?: { title: string, onClick?: () => void };
- /** What the button beside the field makes, for the reader hovering over it. */
+ /** Names what the button creates, shown in its tooltip. */
submitTitle?: string;
/**
- * Opens the menu of which end to make the item at, for a `save` that reads that end. Its
- * presence is what puts the two ends on the button: a right click or a hold opens the menu,
- * and Shift+Enter saves at the start without it.
+ * Opens the menu naming which end to create at, for a `save` that reads `atStart`. Passing it
+ * is what gives the button both ends: a right click or a hold opens the menu, Shift+Enter
+ * saves at the start.
*/
openPlacements?: (x: number, y: number, place: (atStart: boolean) => void) => void;
/**
* Where focus goes when the editor closes, instead of back to whatever held it before. A card
- * whose editor was opened for it rather than by it names itself, so that closing does not light
- * up the card the reader came from on the way.
+ * whose editor was opened by an insert passes its own element, so closing does not focus the
+ * card the insert was made from.
*/
returnFocusTo?: RefObject<HTMLElement>;
/**
- * Whether opening the editor selects what is already in it, which is what a rename wants. An
- * editor opened part-typed puts the caret after the text instead, so the next key carries on
- * rather than replacing it.
+ * Whether opening the editor selects the text already in it, which is what a rename wants. An
+ * editor opened part-typed puts the caret after the text instead, so the next key continues it.
*/
selectOnFocus?: boolean;
}) {
const inputRef = useRef<any>(null);
/**
- * What the field holds, kept here rather than read off the field alone: `FormTextBox` takes its
- * value as a prop, so a render for anything else, the button beside it changing face included,
- * writes that prop back over what has been typed.
+ * What the field holds. Kept in state because `FormTextBox` takes its value as a prop: any
+ * other render, the button changing icon included, would write a stale prop back over it.
*/
const [ typed, setTyped ] = useState(currentValue ?? "");
const isEmpty = !typed.trim();
diff --git a/apps/client/src/widgets/collections/board/keyboard.ts b/apps/client/src/widgets/collections/board/keyboard.ts
index d1dfe55310..b5536e0b13 100644
--- a/apps/client/src/widgets/collections/board/keyboard.ts
+++ b/apps/client/src/widgets/collections/board/keyboard.ts
@@ -473,39 +473,36 @@ function move(
};
}
-/** The reveal waiting to run, so that a newer one takes its place rather than joining it. */
+/** The pending `reveal()` timer, so a newer call replaces it instead of running alongside it. */
let pendingReveal: number | undefined;
/**
- * Focuses an element and brings it into view once it has come to rest.
+ * Focuses an element and scrolls to it once it has stopped moving.
*
- * A moved element is carried back to where it was and let go, which turns the move into a slide,
- * and for as long as that slide runs the element is drawn between the two places. The browser
- * scrolls to where a thing is drawn, so asking any earlier scrolls to where it came from, decides
- * it is in view already, and leaves the column standing where it was.
+ * `useFlip` transforms a moved element back to its old place and releases it, so while that slide
+ * runs the element is painted between the two places. `scrollIntoView` follows what is painted, so
+ * scrolling any earlier targets where the element came from and leaves the column where it was.
*/
function reveal(element: HTMLElement) {
element.focus({ preventScroll: true });
- // Only the last one asked for: keys pressed faster than a slide runs would otherwise each
- // scroll to where the card stood at the time, which is nowhere it is by the time they land.
+ // Only the last call survives: keys pressed faster than a slide runs would otherwise each
+ // scroll to where the card stood when they fired.
window.clearTimeout(pendingReveal);
pendingReveal = window.setTimeout(() => {
if (!element.isConnected) {
return;
}
- // The last card takes the column to its end rather than only into view: what stands under
- // it is the gap it carries and the fade the column draws over its bottom edge, and coming
- // to rest against those leaves it behind them.
+ // 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) {
content.scrollTop = content.scrollHeight;
}
- // And into view either way, which is what carries the board sideways to the column a card
- // has just crossed into. Asked for second, so a column already taken to its end is left
- // where it stands.
+ // Into view either way, which is what scrolls the board sideways to the column a card has
+ // crossed into. Called second, so a column already scrolled to its end stays there.
element.scrollIntoView({ block: "nearest", inline: "nearest" });
}, FLIP_SETTLE_MS);
}
diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.ts
index 173640cc80..12af7ccef7 100644
--- a/apps/client/src/widgets/react/flip.ts
+++ b/apps/client/src/widgets/react/flip.ts
@@ -1,57 +1,55 @@
import { RefObject } from "preact";
import { useCallback, useEffect, useLayoutEffect, useRef } from "preact/hooks";
-/** How long a slide or a growth takes. Matches the transitions the board's own rules carry. */
+/** How long a slide or a growth runs for. Matches the board's own CSS transitions. */
export const FLIP_DURATION_MS = 200;
-/** How long until a slide or a growth has run its course and what it moved stands still. */
+/** How long until a slide or a growth has finished and the element it moved stands still. */
export const FLIP_SETTLE_MS = FLIP_DURATION_MS + 40;
/**
- * How far a child moves before it is taken to have moved at all.
+ * How far a child must move to count as having moved.
*
- * Offsets are whole numbers, so a fraction of a pixel anywhere above a list rounds a share of it
- * one pixel either way. Following that draws a wave across every child for a change nobody can see.
+ * `offsetTop` is a whole number, so sub-pixel layout above the list rounds some children one pixel
+ * either way. Animating that draws a wave across the list for a change no one can see.
*/
const MIN_MOVE_PX = 4;
export interface FlipOptions {
/** Which children to follow. */
selector: string;
- /** Which way they move. Defaults to down the container. */
+ /** The axis the children move along. Defaults to down the container. */
axis?: "vertical" | "horizontal";
/**
- * Whether a child that was not there before opens out of nothing rather than arriving whole.
- * A predicate answers for one child at a time, for arrivals that announce themselves some
- * other way and would only be made restless by opening out as well.
+ * Whether a child that was not there before opens out from zero size instead of appearing at
+ * full size. A predicate decides per child, for arrivals already shown some other way.
*/
grow?: boolean | ((child: HTMLElement) => boolean);
- /** Whether to leave them where the browser puts them. */
+ /** Whether to leave the children where the browser puts them. */
disabled?: boolean;
}
/**
* Slides a container's children from where they stood to where they now stand, and opens out the
- * ones that were not there at all.
+ * ones that were not there before.
*
- * The children are drawn in their new places as usual, then carried back to their old ones for a
- * frame and let go, which the transition they already wear turns into a slide. A new child is
- * measured, collapsed to nothing, and let go the same way, so the room it takes is made rather
- * than found and its neighbours are moved by the growth itself.
+ * The children are drawn in their new places, transformed back to the old ones for one frame and
+ * released, which the CSS transition they already carry turns into a slide. A new child is
+ * measured, collapsed to zero size and released the same way, so its neighbours are moved by the
+ * growth rather than jumping.
*
- * Positions are read as an offset from the page, which neither a scroll nor a transform of a slide
- * still running moves, together with what that offset was measured from: it is taken from whatever
- * is positioned above the child, and a change of that is a different number for the very same
- * place.
+ * A position is read as `offsetTop`/`offsetLeft`, which neither scrolling nor a running slide's
+ * transform changes, together with the `offsetParent` it was measured from: a different
+ * `offsetParent` reports a different number for the same place.
*/
export function useFlip(
ref: RefObject<HTMLElement>, { selector, axis = "vertical", grow, disabled }: FlipOptions
) {
- // Written after every commit, so what it holds is where the children stood before this one.
+ // Written after every commit, so it holds where the children stood at the previous one.
const seen = useRef(new Map<Element, Place>());
- /** Whether the container has been drawn at all: its first children arrive with it, not into it. */
+ /** Whether the container has been drawn once. Children of the first draw are not arrivals. */
const drawn = useRef(false);
- /** Whether a growth is under way, during which the children below it are already in motion. */
+ /** Whether a growth is running, during which the children below it are already moving. */
const settling = useRef(false);
const settled = useRef<number>();
@@ -59,8 +57,8 @@ export function useFlip(
const places = new Map<Element, Place>();
for (const child of ref.current?.querySelectorAll<HTMLElement>(selector) ?? []) {
- // A child out of the flow is remembered as having no place rather than forgotten, so
- // that coming back is a return and not an arrival.
+ // A child out of the flow keeps an entry with `at: null` rather than none, so that
+ // returning to the flow reads as a move and not as an arrival.
const from = child.offsetParent;
places.set(child, from
? { at: axis === "vertical" ? child.offsetTop : child.offsetLeft, from }
@@ -102,9 +100,8 @@ export function useFlip(
});
}
} else if (
- // Not while a growth is running: it moves the children below it over the frames
- // that follow, and each of those reads them somewhere between where they were and
- // where they are going, which is a move only in the sense that it is under way.
+ // Not while `settling` is set: a growth moves the children below it over the
+ // frames that follow, so a commit in that window reads them part-way.
!settling.current && previous.at !== null && previous.from === place.from
&& Math.abs(previous.at - place.at) >= MIN_MOVE_PX
) {
@@ -112,8 +109,8 @@ export function useFlip(
}
}
- // The places as they will settle, so the next commit reads a slide still running as the
- // place it is sliding into rather than as a move of its own.
+ // Stored as the places they settle at, so the next commit reads a running slide as its
+ // destination rather than as a fresh move.
seen.current = now;
drawn.current = true;
@@ -122,10 +119,9 @@ export function useFlip(
}
if (moved.length) {
- // Read once, to make the browser work out the styles just written before the frame that
- // takes them away. Without it a child moved in the page can be set back and let go
- // inside one recalculation, which leaves the transition nothing to start from and the
- // move is drawn where it lands with nothing in between.
+ // Forces a layout so the browser applies the transforms just written, before the
+ // frame that clears them. Without it both writes land in one style recalculation, the
+ // transition has no starting point, and the move is drawn only at its destination.
void container.offsetHeight;
}
@@ -140,8 +136,8 @@ export function useFlip(
void container.offsetHeight;
- // Read again once the growth is over, so what follows is measured against where its
- // neighbours came to rest rather than against wherever it caught them.
+ // Re-read once the growth has finished, so the next commit measures against where the
+ // children came to rest.
window.clearTimeout(settled.current);
settled.current = window.setTimeout(() => {
settling.current = false;
@@ -152,13 +148,13 @@ export function useFlip(
useEffect(() => () => window.clearTimeout(settled.current), []);
}
-/** Where a child stood, `null` while it was out of the flow, and what that was measured from. */
+/** Where a child stood, `null` while out of the flow, and the `offsetParent` it was read from. */
interface Place {
at: number | null;
from: Element | null;
}
-/** Puts a child back where it was, and lets go of it on the next frame. */
+/** Transforms a child back to where it was, and releases it on the next frame. */
function slide(element: HTMLElement, offset: number, axis: Axis) {
if (isStill()) {
return;
@@ -178,10 +174,10 @@ function slide(element: HTMLElement, offset: number, axis: Axis) {
}
/**
- * Takes a child down to nothing and lets it out to the size it was measured at.
+ * Collapses a child to zero and releases it to the size it was measured at.
*
- * The margins go with it: a child of no height still holds the space below it open, which is the
- * part of the jump that would be left.
+ * The margins collapse with it: a child of no height still holds its margins open, which would
+ * leave part of the jump the growth is there to remove.
*/
function open(element: HTMLElement, size: number, axis: Axis) {
if (isStill()) {
@@ -204,8 +200,8 @@ function open(element: HTMLElement, size: number, axis: Axis) {
element.style.transition = `${property} ${FLIP_DURATION_MS}ms ease, `
+ `margin ${FLIP_DURATION_MS}ms ease`;
element.style[property] = `${size}px`;
- // Cleared rather than named: what the margins go back to is the stylesheet's to say, and a
- // change of computed value is what the transition follows either way.
+ // Cleared rather than set to a value: the stylesheet owns what the margins return to, and
+ // the transition follows the computed value either way.
element.style[margin] = "";
window.setTimeout(() => {