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/ui: create a utility to pan containers by dragging their background
Adorian Doranf0d43cd36429
diff --git a/apps/client/src/widgets/react/drag_pan.spec.tsx b/apps/client/src/widgets/react/drag_pan.spec.tsxnew file mode 100644index 0000000000..476ad7797f--- /dev/null+++ b/apps/client/src/widgets/react/drag_pan.spec.tsx@@ -0,0 +1,237 @@+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 { DragPanOptions, useDragPan } from "./drag_pan";++vi.mock("../../services/utils", () => ({ isMobile: () => false }));++describe("useDragPan", () => {+ 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 scrollWidth = 2000;+ const originals = new Map<string, PropertyDescriptor | undefined>();++ beforeEach(() => {+ vi.useFakeTimers();+ scrollWidth = 2000;+ for (const [ name, get ] of [+ [ "scrollWidth", () => scrollWidth ], [ "clientWidth", () => 500 ]+ ] as const) {+ 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("pans the container by the distance the pointer moved", () => {+ const scroller = setup();++ press(scroller, 100);+ move(scroller, 60);++ expect(scroller.scrollLeft).toBe(40);+ expect(scroller.className).toContain("panning");++ release(scroller, 60);+ expect(scroller.className).not.toContain("panning");+ });++ /**+ * Boards draw their scroller only once the notes have loaded, so the element the hook is given+ * is not there on the first render. A ref triggers no render of its own when it is filled in.+ */+ 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 { isPannable } = useDragPan(ref);+ show = setReady;++ return ready+ ? <div ref={ref} className={isPannable ? "pannable" : ""} />+ : <span />;+ }++ act(() => { render(<Harness />, mountPoint); });+ act(() => { show(true); });++ const scroller = mountPoint.firstElementChild as HTMLElement;+ expect(scroller.className).toContain("pannable");++ press(scroller, 100);+ move(scroller, 60);+ expect(scroller.scrollLeft).toBe(40);+ });++ it("offers no pan while the content fits", () => {+ const scroller = setup({ width: 300 });++ expect(scroller.className).not.toContain("pannable");++ press(scroller, 100);+ move(scroller, 60);++ expect(scroller.scrollLeft).toBe(0);+ });++ /** The background is the board's own; a press on anything standing on it belongs to that. */+ it("starts from the container's background and nothing else", () => {+ const scroller = setup();+ const child = document.createElement("div");+ scroller.appendChild(child);++ press(scroller, 100, { target: child });+ move(scroller, 60);++ expect(scroller.scrollLeft).toBe(0);+ });++ it("takes the predicate it is given over the background rule", () => {+ const scroller = setup({ options: { canStart: () => true } });+ const child = document.createElement("div");+ scroller.appendChild(child);++ press(scroller, 100, { target: child });+ move(scroller, 60);++ expect(scroller.scrollLeft).toBe(40);+ });++ it("ignores a press of any button but the first", () => {+ const scroller = setup();++ press(scroller, 100, { button: 2 });+ move(scroller, 60);++ expect(scroller.scrollLeft).toBe(0);+ });++ it("glides on after the pointer is up, and settles", () => {+ const scroller = setup();++ press(scroller, 400);+ move(scroller, 300, 16);+ release(scroller, 300);++ const released = scroller.scrollLeft;+ act(() => { vi.advanceTimersByTime(50); });+ const glided = scroller.scrollLeft;+ expect(glided).toBeGreaterThan(released);++ act(() => { vi.advanceTimersByTime(2000); });+ const settled = scroller.scrollLeft;+ act(() => { vi.advanceTimersByTime(2000); });+ expect(scroller.scrollLeft).toBe(settled);+ });++ it("does not glide when the pointer was still before it was let go", () => {+ const scroller = setup();++ press(scroller, 400);+ move(scroller, 300, 16);+ // Long enough that the last stretch carries no speed at all.+ move(scroller, 299, 400);+ release(scroller, 299);++ const released = scroller.scrollLeft;+ act(() => { vi.advanceTimersByTime(500); });+ expect(scroller.scrollLeft).toBe(released);+ });++ it("stops a glide when the next pan starts", () => {+ const scroller = setup();++ press(scroller, 400);+ move(scroller, 300, 16);+ release(scroller, 300);+ act(() => { vi.advanceTimersByTime(20); });++ press(scroller, 200);+ const held = scroller.scrollLeft;+ act(() => { vi.advanceTimersByTime(500); });++ expect(scroller.scrollLeft).toBe(held);+ });++ let clock = 0;++ function setup({ width = 2000, options }: {+ width?: number,+ options?: DragPanOptions+ } = {}) {+ clock = 0;+ scrollWidth = width;+ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ function Harness() {+ const ref = useRef<HTMLDivElement>(null);+ const { isPannable, isPanning } = useDragPan(ref, options);+ return (+ <div+ ref={ref}+ className={`${isPannable ? "pannable" : ""} ${isPanning ? "panning" : ""}`}+ />+ );+ }++ act(() => { render(<Harness />, mountPoint); });++ const scroller = mountPoint.firstElementChild as HTMLElement;+ scroller.scrollLeft = 0;+ return scroller;+ }++ function pointer(type: string, clientX: number, elapsed: number, extra: Record<string, unknown>) {+ clock += elapsed;+ const event = new Event(type, { bubbles: true, cancelable: true });+ for (const [ name, value ] of Object.entries({+ clientX, pointerId: 1, button: 0, timeStamp: clock, ...extra+ })) {+ Object.defineProperty(event, name, { value, configurable: true });+ }+ return event;+ }++ function press(scroller: HTMLElement, clientX: number, extra: Record<string, unknown> = {}) {+ const { target, ...rest } = extra as { target?: HTMLElement };+ const event = pointer("pointerdown", clientX, 0, rest);+ act(() => { (target ?? scroller).dispatchEvent(event); });+ }++ function move(scroller: HTMLElement, clientX: number, elapsed = 16) {+ act(() => { scroller.dispatchEvent(pointer("pointermove", clientX, elapsed, {})); });+ }++ function release(scroller: HTMLElement, clientX: number) {+ act(() => { scroller.dispatchEvent(pointer("pointerup", clientX, 0, {})); });+ }+});diff --git a/apps/client/src/widgets/react/drag_pan.ts b/apps/client/src/widgets/react/drag_pan.tsnew file mode 100644index 0000000000..d1f428305a--- /dev/null+++ b/apps/client/src/widgets/react/drag_pan.ts@@ -0,0 +1,168 @@+import { RefObject } from "preact";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";++import { isMobile } from "../../services/utils";++/** How much of the speed survives each frame once the pointer is up. */+const FRICTION = 0.94;++/** Below this speed, in pixels per millisecond, the glide has nothing left to show. */+const MIN_VELOCITY = 0.02;++/** How far back the speed is measured, so a pause before releasing ends the gesture still. */+const VELOCITY_WINDOW_MS = 100;++export interface DragPanOptions {+ /**+ * Whether a press here starts a pan. Defaults to the container's own background, which is+ * whatever its children leave uncovered.+ */+ canStart?: (target: HTMLElement, container: HTMLElement) => boolean;+ /** Whether to offer panning at all. */+ disabled?: boolean;+}++export interface DragPanState {+ /** Whether the content is wider than the container, and so has anywhere to be panned. */+ isPannable: boolean;+ /** Whether a pan is under way. */+ isPanning: boolean;+}++/**+ * Pans a horizontally scrolling container by dragging its background, with a glide after the+ * pointer is up.+ *+ * Touch devices scroll it by dragging already, so this is left to pointers that cannot.+ *+ * @param ref the scrolling container.+ * @param options which presses start a pan, and whether to offer it at all.+ */+export function useDragPan(ref: RefObject<HTMLElement>, options: DragPanOptions = {}): DragPanState {+ const { canStart, disabled } = options;+ const [ isPannable, setPannable ] = useState(false);+ const [ isPanning, setPanning ] = useState(false);+ const glideRef = useRef<number>();++ // A ref holds no render of its own, so an effect keyed on one never hears the element arrive.+ // Containers drawn only once their content has loaded are the ordinary case, so the element is+ // tracked in state instead. Set only when it actually changes, so this settles in one pass.+ // A ref holds no render of its own, so an effect keyed on one never hears the element arrive.+ // Containers drawn only once their content has loaded are the ordinary case, so the element is+ // tracked in state instead. Set only when it actually changes, so this settles in one pass.+ const [ element, setElement ] = useState<HTMLElement | null>(null);+ useLayoutEffect(() => {+ if (ref.current !== element) {+ setElement(ref.current);+ }+ });++ const stopGlide = useCallback(() => {+ if (glideRef.current !== undefined) {+ cancelAnimationFrame(glideRef.current);+ glideRef.current = undefined;+ }+ }, []);++ useEffect(() => {+ const container = element;+ if (!container || disabled || isMobile()) return;++ const measure = () => setPannable(container.scrollWidth > container.clientWidth);+ measure();++ // Enough to keep the cursor honest: the width is read again when the pan is asked for, so a+ // measurement this misses cannot let a pan start where there is nowhere to go.+ const observer = new ResizeObserver(measure);+ observer.observe(container);++ let pointerId: number | undefined;+ let lastX = 0;+ let lastAt = 0;+ let velocity = 0;++ const onPointerDown = (event: PointerEvent) => {+ const target = event.target as HTMLElement | null;+ if (event.button !== 0 || !target) return;++ const starts = canStart ? canStart(target, container) : target === container;+ if (!starts || container.scrollWidth <= container.clientWidth) return;++ stopGlide();+ pointerId = event.pointerId;+ lastX = event.clientX;+ lastAt = event.timeStamp;+ velocity = 0;+ setPanning(true);+ container.setPointerCapture?.(event.pointerId);+ // The press would otherwise start a selection, which the drag then extends.+ event.preventDefault();+ };++ const onPointerMove = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) return;++ const dx = event.clientX - lastX;+ const elapsed = event.timeStamp - lastAt;+ container.scrollLeft -= dx;++ // Measured over the last stretch only, so a drag that stops before the release glides+ // no further than it was going.+ if (elapsed > 0) {+ velocity = elapsed > VELOCITY_WINDOW_MS ? 0 : dx / elapsed;+ lastAt = event.timeStamp;+ }+ lastX = event.clientX;+ };++ const glide = () => {+ let previous = performance.now();++ const step = (now: number) => {+ const elapsed = now - previous;+ previous = now;++ const before = container.scrollLeft;+ container.scrollLeft -= velocity * elapsed;+ velocity *= FRICTION ** (elapsed / 16);++ // An end of the board is as far as the glide goes: the scroller clamps what it is+ // given, so nothing moves however much speed is left.+ const moved = container.scrollLeft !== before;+ glideRef.current = moved && Math.abs(velocity) > MIN_VELOCITY+ ? requestAnimationFrame(step)+ : undefined;+ };++ glideRef.current = requestAnimationFrame(step);+ };++ const onPointerUp = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) return;++ pointerId = undefined;+ setPanning(false);+ container.releasePointerCapture?.(event.pointerId);++ if (Math.abs(velocity) > MIN_VELOCITY) {+ glide();+ }+ };++ container.addEventListener("pointerdown", onPointerDown);+ container.addEventListener("pointermove", onPointerMove);+ container.addEventListener("pointerup", onPointerUp);+ container.addEventListener("pointercancel", onPointerUp);++ return () => {+ observer.disconnect();+ stopGlide();+ container.removeEventListener("pointerdown", onPointerDown);+ container.removeEventListener("pointermove", onPointerMove);+ container.removeEventListener("pointerup", onPointerUp);+ container.removeEventListener("pointercancel", onPointerUp);+ };+ }, [ element, canStart, disabled, stopGlide ]);++ return { isPannable, isPanning };+}