Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: extend the entrance animation for cards / columns

Adorian Doran205fd85084dd
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 679f8540b2..410f37a853 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -85,6 +85,8 @@ export default function Column({
// 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.
const [ isRevealed, setIsRevealed ] = useState(false);
+ /** The card the footer made, which arrives without opening out. */
+ const quietlyAdded = created?.takesFocus === false ? created.noteId : undefined;
// 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.
const cardInserted = useCallback(
@@ -98,8 +100,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.
- useFlip(contentRef, { selector: ".board-note" });
+ // 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.
+ useFlip(contentRef, {
+ selector: ".board-note",
+ grow: (card) => card.dataset.noteId !== quietlyAdded
+ });
const { handleDragOver, handleDragLeave, handleDrop } = useDragging({
column, columnIndex, columnItems, isEditing, api, parentNote
});
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index aed19bee9f..726d9afa15 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -457,7 +457,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC
// that keeps it in view, so sliding it as well reads as a stumble rather than as movement.
useFlip(containerRef, {
selector: ".board-column:not(.board-drag-preview)",
- axis: "horizontal"
+ axis: "horizontal",
+ // Except the one just added: it is already announced by the fade and by the board running
+ // to its end, and opening out on top of those is one movement too many.
+ grow: (column) => column.dataset.column !== createdColumn
});
/**
@@ -710,9 +713,11 @@ function AddNewColumn({ api, isInRelationMode, columnCount, onCreated }: {
}
const board = slotRef.current?.closest<HTMLElement>(".board-view-container");
- if (board) {
- board.scrollLeft = board.scrollWidth;
+ if (!board) {
+ return;
}
+
+ board.scrollLeft = board.scrollWidth;
}, [ columnCount, isCreatingNewColumn ]);
const addColumnCallback = useCallback(() => {
diff --git a/apps/client/src/widgets/react/flip.spec.tsx b/apps/client/src/widgets/react/flip.spec.tsx
index 68e5b4b250..58abc072ca 100644
--- a/apps/client/src/widgets/react/flip.spec.tsx
+++ b/apps/client/src/widgets/react/flip.spec.tsx
@@ -1,29 +1,51 @@
/**
- * happy-dom lays nothing out, so every child's place is declared and moved by hand: what these
- * check is that a change of place becomes a slide, and that nothing else does.
+ * happy-dom lays nothing out, so every child's box is declared and moved by hand: what these check
+ * is that a change of place becomes a slide, that an arrival opens out, and that nothing else does.
*/
import { render } from "preact";
-import { act } from "preact/test-utils";
import { useRef } from "preact/hooks";
+import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useFlip } from "./flip";
+import { FLIP_DURATION_MS, type FlipOptions, useFlip } from "./flip";
+
+/** Past the window a growth holds open, which is the duration and a little. */
+const SETTLE_AFTER_MS = FLIP_DURATION_MS + 100;
describe("useFlip", () => {
let container: HTMLElement | undefined;
let frames: (() => void)[] = [];
+ let keys: string[] = [];
+ let rerender: () => Promise<void>;
+
+ const boxes = {
+ offsetParent(this: HTMLElement) { return this.parentElement; },
+ offsetHeight() { return 34; },
+ offsetWidth() { return 180; },
+ offsetTop() { return 0; },
+ offsetLeft() { return 0; }
+ };
beforeEach(() => {
frames = [];
- vi.stubGlobal("requestAnimationFrame", (callback: () => void) => {
- frames.push(callback);
- return frames.length;
- });
+ vi.stubGlobal("requestAnimationFrame", (callback: () => void) => frames.push(callback));
vi.stubGlobal("matchMedia", () => ({ matches: false }));
+
+ // A child has to have a box on the commit that inserts it, before a test can reach it, so
+ // the defaults belong to every element and a test overrides the ones it cares about.
+ for (const [ property, read ] of Object.entries(boxes)) {
+ Object.defineProperty(HTMLElement.prototype, property, {
+ configurable: true, get: read as () => unknown
+ });
+ }
});
afterEach(() => {
+ vi.useRealTimers();
vi.unstubAllGlobals();
+ for (const property of Object.keys(boxes)) {
+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)[property];
+ }
if (container) {
render(null, container);
container.remove();
@@ -32,48 +54,36 @@ describe("useFlip", () => {
});
it("carries a child back to where it was, and lets go on the next frame", async () => {
- const { items } = await draw([ "a", "b" ]);
- place(items(), [ 0, 40 ]);
- await redraw();
+ const items = await draw([ "a", "b" ]);
// The second one is pushed down by something appearing above it.
- place(items(), [ 0, 90 ]);
- await redraw();
+ place(items(), [ 0, 50 ]);
+ await settle();
const [ first, second ] = items();
expect(first.style.transform).toBe("");
expect(second.style.transform).toBe("translateY(-50px)");
expect(second.style.transition).toBe("none");
- act(() => { for (const frame of frames.splice(0)) frame(); });
-
+ run();
expect(second.style.transform).toBe("");
expect(second.style.transition).toBe("");
});
- it("leaves alone a child that has not moved, and one with no place at all", async () => {
- const { items } = await draw([ "a", "b" ]);
- place(items(), [ 0, 40 ]);
- await redraw();
+ it("leaves alone a child that has not moved", async () => {
+ const items = await draw([ "a", "b" ]);
- // The first keeps its place; the second is taken out of the flow and put back elsewhere.
- place(items(), [ 0, 40 ]);
- Object.defineProperty(items()[1], "offsetParent", { value: null, configurable: true });
- await redraw();
- expect(items().every(item => item.style.transform === "")).toBe(true);
+ place(items(), [ 0, 0 ]);
+ await settle();
- place(items(), [ 0, 200 ]);
- await redraw();
- expect(items()[1].style.transform).toBe("");
+ expect(items().every(item => item.style.transform === "")).toBe(true);
});
it("carries a child sideways where that is the way they move", async () => {
- const { items } = await draw([ "a", "b" ], false, "horizontal");
- place(items(), [ 0, 180 ], "offsetLeft");
- await redraw();
+ const items = await draw([ "a", "b" ], { axis: "horizontal" });
- place(items(), [ 0, 360 ], "offsetLeft");
- await redraw();
+ place(items(), [ 0, 180 ], "offsetLeft");
+ await settle();
expect(items()[1].style.transform).toBe("translateX(-180px)");
});
@@ -84,51 +94,128 @@ describe("useFlip", () => {
* and another against the box holding them, and the difference is a header's height.
*/
it("leaves alone a child whose offsets are measured from somewhere else", async () => {
- const { items } = await draw([ "a", "b" ]);
- place(items(), [ 0, 40 ]);
- await redraw();
+ const items = await draw([ "a", "b" ]);
+ const second = items()[1];
- const [ , second ] = items();
Object.defineProperty(second, "offsetParent", {
- value: document.createElement("div"), configurable: true, writable: true
- });
- Object.defineProperty(second, "offsetTop", {
- value: 115, configurable: true, writable: true
+ value: document.createElement("div"), configurable: true
});
- await redraw();
-
+ place(items(), [ 0, 75 ]);
+ await settle();
expect(second.style.transform).toBe("");
// Read against the same thing twice over, it moves as any other child does.
- Object.defineProperty(second, "offsetTop", {
- value: 160, configurable: true, writable: true
- });
- await redraw();
+ place(items(), [ 0, 120 ]);
+ await settle();
expect(second.style.transform).toBe("translateY(-45px)");
});
it("says nothing while it is switched off", async () => {
- const { items } = await draw([ "a", "b" ], true);
- place(items(), [ 0, 40 ]);
- await redraw();
+ const items = await draw([ "a", "b" ], { disabled: true });
+
place(items(), [ 0, 90 ]);
- await redraw();
+ await settle();
expect(items()[1].style.transform).toBe("");
});
- let rerender: () => Promise<void>;
+ describe("opening out what was not there", () => {
+ it("takes a new child down to nothing and lets it out to its own size", async () => {
+ const items = await draw([ "a" ], { grow: true });
- async function draw(
- keys: string[], disabled = false, axis: "vertical" | "horizontal" = "vertical"
- ) {
+ keys.push("b");
+ await settle();
+
+ const arrived = items()[1];
+ expect(arrived.style.height).toBe("0px");
+ expect(arrived.style.marginBlock).toBe("0px");
+ expect(arrived.style.overflow).toBe("hidden");
+
+ run();
+ expect(arrived.style.height).toBe("34px");
+ expect(arrived.style.marginBlock).toBe("");
+ expect(arrived.style.transition).toContain("height");
+ });
+
+ it("opens a new child out sideways where that is the way they move", async () => {
+ const items = await draw([ "a" ], { grow: true, axis: "horizontal" });
+
+ keys.push("b");
+ await settle();
+ run();
+
+ expect(items()[1].style.width).toBe("180px");
+ });
+
+ /**
+ * A growth moves the children below it over the frames that follow, so a commit landing in
+ * that window reads them somewhere on their way. Following that fights the growth: one
+ * insertion used to draw five slides against it.
+ */
+ it("leaves the children a growth is moving alone until it has settled", async () => {
+ vi.useFakeTimers();
+ const items = await draw([ "a", "b" ], { grow: true });
+
+ keys.push("c");
+ await settle();
+ run();
+
+ // Caught on its way by a commit while the growth is still running.
+ place(items(), [ 0, 20 ]);
+ await settle();
+ expect(items()[1].style.transform).toBe("");
+
+ // Once it is over, the places are read again and a move is a move.
+ await act(async () => { vi.advanceTimersByTime(SETTLE_AFTER_MS); });
+ place(items(), [ 0, 60 ]);
+ await settle();
+ expect(items()[1].style.transform).toBe("translateY(-40px)");
+ });
+
+ it("leaves an arrival alone where the caller answers for it", async () => {
+ const items = await draw([ "a" ], { grow: (child) => child.textContent !== "b" });
+
+ keys.push("b");
+ await settle();
+ run();
+
+ expect(items()[1].style.height).toBe("");
+ expect(items()[1].style.overflow).toBe("");
+ });
+
+ it("leaves the children the container was drawn with alone", async () => {
+ const items = await draw([ "a", "b" ], { grow: true });
+
+ expect(items().every(item => item.style.height === "")).toBe(true);
+ });
+
+ it("treats a child coming back into the flow as a return, not an arrival", async () => {
+ const items = await draw([ "a", "b" ], { grow: true });
+ const carried = items()[1];
+
+ // Taken out of the flow, the way a card is while it is carried.
+ Object.defineProperty(carried, "offsetParent", { value: null, configurable: true });
+ await settle();
+
+ Object.defineProperty(carried, "offsetParent", {
+ value: carried.parentElement, configurable: true
+ });
+ await settle();
+
+ expect(carried.style.height).toBe("");
+ expect(carried.style.transform).toBe("");
+ });
+ });
+
+ async function draw(initial: string[], options: Partial<FlipOptions> = {}) {
+ keys = [ ...initial ];
const mountPoint = document.createElement("div");
container = mountPoint;
document.body.appendChild(mountPoint);
function Harness() {
const ref = useRef<HTMLDivElement>(null);
- useFlip(ref, { selector: ".item", axis, disabled });
+ useFlip(ref, { selector: ".item", ...options });
return (
<div ref={ref}>
{keys.map(key => <div key={key} className="item">{key}</div>)}
@@ -141,26 +228,27 @@ describe("useFlip", () => {
};
await rerender();
- return { items: () => [ ...mountPoint.querySelectorAll<HTMLElement>(".item") ] };
+ return () => [ ...mountPoint.querySelectorAll<HTMLElement>(".item") ];
}
- async function redraw() {
+ /** Draws again, which is what the hook reads its befores and afters from. */
+ async function settle() {
await rerender();
}
+ /** Runs the frames the hook asked for, which is where it lets go of what it moved. */
+ function run() {
+ act(() => { for (const frame of frames.splice(0)) frame(); });
+ }
+
/** happy-dom reports no offsets of its own, so each child is told where it stands. */
function place(
- items: HTMLElement[], tops: number[], property: "offsetTop" | "offsetLeft" = "offsetTop"
+ items: HTMLElement[], at: number[], property: "offsetTop" | "offsetLeft" = "offsetTop"
) {
for (const [ index, item ] of items.entries()) {
Object.defineProperty(item, property, {
- value: tops[index], configurable: true, writable: true
+ value: at[index], configurable: true, writable: true
});
- if (!Object.getOwnPropertyDescriptor(item, "offsetParent")) {
- Object.defineProperty(item, "offsetParent", {
- value: item.parentElement, configurable: true, writable: true
- });
- }
}
}
});
diff --git a/apps/client/src/widgets/react/flip.ts b/apps/client/src/widgets/react/flip.ts
index ef9d2e937b..c54b329a53 100644
--- a/apps/client/src/widgets/react/flip.ts
+++ b/apps/client/src/widgets/react/flip.ts
@@ -1,80 +1,156 @@
import { RefObject } from "preact";
-import { useLayoutEffect, useRef } from "preact/hooks";
+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. */
+export const FLIP_DURATION_MS = 200;
+
+/** How long after a growth the places it moved are read again, once it has settled. */
+const SETTLE_MS = FLIP_DURATION_MS + 40;
+
+/**
+ * How far a child moves before it is taken to have moved at all.
+ *
+ * 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.
+ */
+const MIN_MOVE_PX = 4;
export interface FlipOptions {
/** Which children to follow. */
selector: string;
/** Which way they move. 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.
+ */
+ grow?: boolean | ((child: HTMLElement) => boolean);
/** Whether to leave them where the browser puts them. */
disabled?: boolean;
}
/**
- * Slides a container's children from where they stood to where they now stand.
+ * 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.
*
* 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. Nothing about the
- * layout changes: a child inserted between two others still moves them, and this only says so.
+ * 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.
*
* Positions are read as an offset from the page, which neither a scroll nor a transform of a slide
- * still running moves, so neither is taken for a change of place.
+ * 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.
*/
export function useFlip(
- ref: RefObject<HTMLElement>, { selector, axis = "vertical", disabled }: FlipOptions
+ 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.
const seen = useRef(new Map<Element, Place>());
+ /** Whether the container has been drawn at all: its first children arrive with it, not into it. */
+ const drawn = useRef(false);
+ /** Whether a growth is under way, during which the children below it are already in motion. */
+ const settling = useRef(false);
+ const settled = useRef<number>();
+
+ const read = useCallback(() => {
+ 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.
+ const from = child.offsetParent;
+ places.set(child, from
+ ? { at: axis === "vertical" ? child.offsetTop : child.offsetLeft, from }
+ : { at: null, from: null });
+ }
+
+ return places;
+ }, [ ref, selector, axis ]);
useLayoutEffect(() => {
const container = ref.current;
if (!container) {
seen.current.clear();
+ drawn.current = false;
return;
}
const before = seen.current;
- const now = new Map<Element, Place>();
+ const now = read();
const moved: { child: HTMLElement, by: number }[] = [];
+ const arrived: { child: HTMLElement, size: number }[] = [];
- // Read first and write after: a transform written between two reads costs a fresh layout
- // for every child that follows it.
- for (const child of container.querySelectorAll<HTMLElement>(selector)) {
- // A child out of the flow has no place to be moved from, and is left with none, so
- // that coming back is an arrival rather than a slide from wherever it last stood.
- if (!child.offsetParent) {
+ // Read first and write after: a style written between two reads costs a fresh layout for
+ // every child that follows it.
+ for (const [ element, place ] of now) {
+ const child = element as HTMLElement;
+ const previous = before.get(child);
+
+ if (disabled || place.at === null) {
continue;
}
- const from = child.offsetParent;
- const at = axis === "vertical" ? child.offsetTop : child.offsetLeft;
- now.set(child, { at, from });
-
- // Only against the same origin: an offset is measured from whatever is positioned above
- // it, and a change of that is a different number for the very same place.
- const previous = before.get(child);
- if (!disabled && previous?.from === from && Math.abs(previous.at - at) >= 1) {
- moved.push({ child, by: previous.at - at });
+ if (!previous) {
+ const opens = typeof grow === "function" ? grow(child) : grow;
+ if (opens && drawn.current) {
+ arrived.push({
+ child,
+ size: axis === "vertical" ? child.offsetHeight : child.offsetWidth
+ });
+ }
+ } 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.
+ !settling.current && previous.at !== null && previous.from === place.from
+ && Math.abs(previous.at - place.at) >= MIN_MOVE_PX
+ ) {
+ moved.push({ child, by: previous.at - place.at });
}
}
+ // 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.
seen.current = now;
+ drawn.current = true;
for (const { child, by } of moved) {
slide(child, by, axis);
}
+
+ if (!arrived.length) {
+ return;
+ }
+
+ settling.current = true;
+ for (const { child, size } of arrived) {
+ open(child, size, axis);
+ }
+
+ // 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.
+ window.clearTimeout(settled.current);
+ settled.current = window.setTimeout(() => {
+ settling.current = false;
+ seen.current = read();
+ }, SETTLE_MS);
});
+
+ useEffect(() => () => window.clearTimeout(settled.current), []);
}
-/** Where a child stood, and what that was measured from. */
+/** Where a child stood, `null` while it was out of the flow, and what that was measured from. */
interface Place {
- at: number;
+ at: number | null;
from: Element | null;
}
/** Puts a child back where it was, and lets go of it on the next frame. */
-function slide(element: HTMLElement, offset: number, axis: "vertical" | "horizontal") {
- if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) {
+function slide(element: HTMLElement, offset: number, axis: Axis) {
+ if (isStill()) {
return;
}
@@ -90,3 +166,50 @@ function slide(element: HTMLElement, offset: number, axis: "vertical" | "horizon
}
});
}
+
+/**
+ * Takes a child down to nothing and lets it out 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.
+ */
+function open(element: HTMLElement, size: number, axis: Axis) {
+ if (isStill()) {
+ return;
+ }
+
+ const property = axis === "vertical" ? "height" : "width";
+ const margin = axis === "vertical" ? "marginBlock" : "marginInline";
+
+ element.style.transition = "none";
+ element.style.overflow = "hidden";
+ element.style[property] = "0px";
+ element.style[margin] = "0px";
+
+ requestAnimationFrame(() => {
+ if (!element.isConnected) {
+ return;
+ }
+
+ 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.
+ element.style[margin] = "";
+
+ window.setTimeout(() => {
+ if (element.isConnected) {
+ element.style.transition = "";
+ element.style.overflow = "";
+ element.style[property] = "";
+ }
+ }, SETTLE_MS);
+ });
+}
+
+type Axis = "vertical" | "horizontal";
+
+function isStill() {
+ return !!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
+}