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: add a scroll fade for the column content
Adorian Doran10efdfb67bb2
diff --git a/apps/client/src/widgets/react/scroll_fade.spec.tsx b/apps/client/src/widgets/react/scroll_fade.spec.tsxnew file mode 100644index 0000000000..899a74427f--- /dev/null+++ b/apps/client/src/widgets/react/scroll_fade.spec.tsx@@ -0,0 +1,169 @@+import { render } from "preact";+import { useRef, useState } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { ScrollFadeOptions, useScrollFade } from "./scroll_fade";++describe("useScrollFade", () => {+ let container: HTMLElement | undefined;++ // happy-dom lays nothing out, so every element reports what the test declares. Declared on the+ // prototype rather than on one element, since the hook measures as soon as its container is+ // drawn, which is before a test can reach it.+ let content = 1000;+ let travelled = 0;+ const originals = new Map<string, PropertyDescriptor | undefined>();++ beforeEach(() => {+ vi.useFakeTimers();+ content = 1000;+ travelled = 0;++ const sizes: Record<string, () => number> = {+ scrollHeight: () => content,+ clientHeight: () => 200,+ scrollWidth: () => content,+ clientWidth: () => 200,+ scrollTop: () => travelled,+ scrollLeft: () => travelled+ };+ for (const [ name, get ] of Object.entries(sizes)) {+ originals.set(name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name));+ Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get });+ }+ });++ afterEach(() => {+ for (const [ name, descriptor ] of originals) {+ if (descriptor) {+ Object.defineProperty(HTMLElement.prototype, name, descriptor);+ } else {+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)[name];+ }+ }+ originals.clear();+ vi.useRealTimers();++ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ it("fades the end alone while the content is scrolled to the start", () => {+ const scroller = setup();++ expect(scroller.className).toContain("scroll-fade-end");+ expect(scroller.className).not.toContain("scroll-fade-start");+ });++ it("fades both ends once the content is scrolled between them", () => {+ const scroller = setup();++ scrollTo(scroller, 400);++ expect(scroller.className).toContain("scroll-fade-start");+ expect(scroller.className).toContain("scroll-fade-end");+ });++ it("fades the start alone once the content is scrolled to the end", () => {+ const scroller = setup();++ scrollTo(scroller, 800);++ expect(scroller.className).toContain("scroll-fade-start");+ expect(scroller.className).not.toContain("scroll-fade-end");+ });++ it("fades neither end while the content fits", () => {+ const scroller = setup({ contentSize: 150 });++ expect(scroller.className).not.toContain("scroll-fade-start");+ expect(scroller.className).not.toContain("scroll-fade-end");+ });++ /** Cards arrive and leave without the box changing size, which no resize reports. */+ it("measures again when the content changes", async () => {+ const scroller = setup({ contentSize: 150 });+ expect(scroller.className).not.toContain("scroll-fade-end");++ content = 1000;+ await act(async () => {+ scroller.appendChild(document.createElement("div"));+ // The observer delivers on a microtask, and only then is the frame asked for.+ await Promise.resolve();+ vi.advanceTimersByTime(20);+ });++ expect(scroller.className).toContain("scroll-fade-end");+ });++ it("names the axis it was given, and carries the size and duration into CSS", () => {+ const scroller = setup({ options: { direction: "horizontal", size: 32, duration: 120 } });++ expect(scroller.className).toContain("scroll-fade-horizontal");+ expect(scroller.getAttribute("style")).toContain("--scroll-fade-size: 32px");+ expect(scroller.getAttribute("style")).toContain("--scroll-fade-duration: 120ms");+ });++ it("leaves the size and duration to CSS when it is given neither", () => {+ const scroller = setup();++ expect(scroller.getAttribute("style") ?? "").not.toContain("--scroll-fade-size");+ expect(scroller.className).toContain("scroll-fade-vertical");+ });++ /** Columns draw their card area only once open, so the element is not there on the first render. */+ it("picks up a container that is drawn after the first render", () => {+ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ let show: (ready: boolean) => void = () => {};++ function Harness() {+ const [ ready, setReady ] = useState(false);+ const ref = useRef<HTMLDivElement>(null);+ const { className } = useScrollFade(ref);+ show = setReady;++ return ready ? <div ref={ref} className={className} /> : <span />;+ }++ act(() => { render(<Harness />, mountPoint); });+ act(() => { show(true); });++ expect((mountPoint.firstElementChild as HTMLElement).className)+ .toContain("scroll-fade-end");+ });++ function setup({ contentSize, options }: {+ contentSize?: number,+ options?: ScrollFadeOptions+ } = {}) {+ if (contentSize !== undefined) content = contentSize;++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ function Harness() {+ const ref = useRef<HTMLDivElement>(null);+ const { className, style } = useScrollFade(ref, options);+ return <div ref={ref} className={className} style={style} />;+ }++ act(() => { render(<Harness />, mountPoint); });+ return mountPoint.firstElementChild as HTMLElement;+ }++ function scrollTo(scroller: HTMLElement, offset: number) {+ travelled = offset;+ act(() => {+ scroller.dispatchEvent(new Event("scroll"));+ vi.advanceTimersByTime(20);+ });+ }+});diff --git a/apps/client/src/widgets/react/scroll_fade.ts b/apps/client/src/widgets/react/scroll_fade.tsnew file mode 100644index 0000000000..aa301af67b--- /dev/null+++ b/apps/client/src/widgets/react/scroll_fade.ts@@ -0,0 +1,120 @@+import "./scroll_fade.css";++import clsx from "clsx";+import { RefObject } from "preact";+import { CSSProperties } from "preact/compat";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";++/** Fractional scroll offsets are reported at sub-pixel precision, so an edge is never tested exactly. */+const EDGE_EPSILON = 1;++export interface ScrollFadeOptions {+ /** Which way the container scrolls. */+ direction?: "horizontal" | "vertical";+ /** How far the fade reaches from each edge, in pixels. */+ size?: number;+ /** How long a fade takes to arrive and to leave, in milliseconds. */+ duration?: number;+}++export interface ScrollFade {+ /** Goes on the scroll container, alongside whatever else it wears. */+ className: string;+ /** Carries the size and duration, which CSS reads as lengths and times. */+ style: CSSProperties;+ /** How much of the content lies outside the box, along the scrolling axis. */+ overflow: number;+ /** Re-measures, for content that changes without the DOM or the box saying so. */+ measure: () => void;+}++/**+ * Fades the edges a scroll container continues past, so the reader can tell there is more without+ * reading the scrollbar.+ *+ * @param ref the scroll container.+ * @param options which way it scrolls, how far each fade reaches and how long it takes.+ */+export function useScrollFade(ref: RefObject<HTMLElement>, options: ScrollFadeOptions = {}): ScrollFade {+ const { direction = "vertical", size, duration } = options;+ const [ fades, setFades ] = useState({ start: false, end: false });+ const [ overflow, setOverflow ] = useState(0);+ const frameRef = useRef<number>();++ // A ref holds no render of its own, so an effect keyed on one never hears the element arrive.+ const [ element, setElement ] = useState<HTMLElement | null>(null);+ useLayoutEffect(() => {+ if (ref.current !== element) {+ setElement(ref.current);+ }+ });++ const measure = useCallback(() => {+ if (!element) return;++ const horizontal = direction === "horizontal";+ // Read as a distance travelled rather than as a coordinate: a right-to-left page scrolls the+ // same content towards negative offsets, and both ends ask the same question either way.+ const travelled = Math.abs(horizontal ? element.scrollLeft : element.scrollTop);+ const total = horizontal+ ? element.scrollWidth - element.clientWidth+ : element.scrollHeight - element.clientHeight;++ setOverflow(total);+ setFades((current) => {+ const next = {+ start: travelled > EDGE_EPSILON,+ end: travelled < total - EDGE_EPSILON+ };+ return current.start === next.start && current.end === next.end ? current : next;+ });+ }, [ element, direction ]);++ useEffect(() => {+ if (!element) return;++ // Coalesced: a batch of cards arriving fires the observer once per change, and each+ // measurement reads a layout the last one just invalidated.+ const request = () => {+ if (frameRef.current === undefined) {+ frameRef.current = requestAnimationFrame(() => {+ frameRef.current = undefined;+ measure();+ });+ }+ };++ measure();++ // The box is resized by everything from a window to a pane being dragged; the content grows+ // and shrinks without either, which no resize reports.+ const resize = new ResizeObserver(request);+ resize.observe(element);+ const mutations = new MutationObserver(request);+ mutations.observe(element, { childList: true, subtree: true, characterData: true });+ element.addEventListener("scroll", request, { passive: true });++ return () => {+ resize.disconnect();+ mutations.disconnect();+ element.removeEventListener("scroll", request);+ if (frameRef.current !== undefined) {+ cancelAnimationFrame(frameRef.current);+ frameRef.current = undefined;+ }+ };+ }, [ element, measure ]);++ return {+ className: clsx("scroll-fade", `scroll-fade-${direction}`, {+ "scroll-fade-start": fades.start,+ "scroll-fade-end": fades.end+ }),+ style: {+ ...(size !== undefined && { "--scroll-fade-size": `${size}px` }),+ ...(duration !== undefined && { "--scroll-fade-duration": `${duration}ms` })+ } as CSSProperties,+ overflow,+ measure+ };+}