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: refactor
Adorian Doran8466635c5da5
diff --git a/apps/client/src/widgets/react/ScrollableLabel.css b/apps/client/src/widgets/react/ScrollableLabel.cssindex 2cc3a39d4d..a457056e72 100644--- a/apps/client/src/widgets/react/ScrollableLabel.css+++ b/apps/client/src/widgets/react/ScrollableLabel.css@@ -1,69 +1,17 @@/*- * A custom property only animates once it is registered with a type, so the two ends are declared as- * lengths for the transition below to have something to interpolate: the mask is recomputed as they- * grow, and a fade arrives and leaves over its 300ms instead of appearing whole. Where `@property` is- * not supported the fades simply snap, as they did before, and the `var()` fallbacks in the mask keep- * standing in for the initial values.- */-@property --scrollable-label-fade-start {- syntax: "<length>";- inherits: false;- initial-value: 0px;-}--@property --scrollable-label-fade-end {- syntax: "<length>";- inherits: false;- initial-value: 0px;-}--/*- * One line of text, swiped along where it does not fit, fading out at whichever edge it continues- * past. The fade is a mask rather than a painted gradient, as `.scroll-edge-fade` in style.css is for- * the vertical axis: it holds over any background, including a semi-transparent tint over a window- * material, which no painted color could match.- *- * The two ends are `var()` fallbacks rather than declarations, so a consumer's own fade width wins- * regardless of how the stylesheets end up bundled; the classes below are set by the component as the- * line is scrolled. The gradient's direction is a variable because a gradient can only be given a- * physical one, and the ends swap in a right-to-left page.+ * One line of text, swiped along where it does not fit. The edges it continues past are faded by+ * `useScrollFade`, which paints the mask and holds the classes.*/.scrollable-label {overflow-x: auto;/* The swipe belongs to the label: without this it carries on into whatever the label sits in oncethe line reaches its end, which on a phone is the page or the gesture that changes tabs. */overscroll-behavior-inline: contain;- mask-image: linear-gradient(- var(--scrollable-label-direction, to right),- transparent,- black var(--scrollable-label-fade-start, 0px),- black calc(100% - var(--scrollable-label-fade-end, 0px)),- transparent- );white-space: nowrap;/* No room for a bar under a single line, and nothing for it to say that the fades do not. */scrollbar-width: none;- transition:- --scrollable-label-fade-start 300ms ease,- --scrollable-label-fade-end 300ms ease;}.scrollable-label::-webkit-scrollbar {display: none;}--/* Far enough to read as a fade rather than as a cut, and no further: the text under it is still- being read. */-.scrollable-label-fade-start {- --scrollable-label-fade-start: 20px;-}--.scrollable-label-fade-end {- --scrollable-label-fade-end: 20px;-}--/* Flipping the gradient flips which physical edge each end names, so the two stops above go on- meaning the start and the end of the line. */-body[dir=rtl] .scrollable-label {- --scrollable-label-direction: to left;-}diff --git a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx b/apps/client/src/widgets/react/ScrollableLabel.spec.tsxindex 7c8ca1f78c..6dbbadbc97 100644--- a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx+++ b/apps/client/src/widgets/react/ScrollableLabel.spec.tsx@@ -1,4 +1,5 @@import { render } from "preact";+import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";import ScrollableLabel from "./ScrollableLabel";@@ -18,10 +19,15 @@ afterEach(() => {* writable already; the two widths are not, and stand for a line of the given length in a 100px box.*/function renderLabel(text: string, scrollWidth: number, clientWidth = 100, autoScroll = false) {- container = document.body.appendChild(document.createElement("div"));- render(<ScrollableLabel autoScroll={autoScroll}>{text}</ScrollableLabel>, container);+ const mountPoint = document.body.appendChild(document.createElement("div"));+ container = mountPoint;+ // Flushed here: the fade attaches its listeners from an effect, which Preact defers past the+ // render, and a test that scrolled before that would be scrolling at nothing.+ act(() => {+ render(<ScrollableLabel autoScroll={autoScroll}>{text}</ScrollableLabel>, mountPoint);+ });- const label = container.querySelector<HTMLDivElement>(".scrollable-label");+ const label = mountPoint.querySelector<HTMLDivElement>(".scrollable-label");if (!label) {throw new Error("the label did not render");@@ -41,7 +47,7 @@ async function scrollTo(label: HTMLDivElement, scrollLeft: number) {label.scrollLeft = scrollLeft;label.dispatchEvent(new Event("scroll"));- await new Promise((resolve) => setTimeout(resolve, 0));+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });}describe("ScrollableLabel", () => {@@ -50,30 +56,30 @@ describe("ScrollableLabel", () => {// Sitting at the start: the end continues, nothing is cut off behind.await scrollTo(label, 0);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(false);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(true);+ expect(label.classList.contains("scroll-fade-start")).toBe(false);+ expect(label.classList.contains("scroll-fade-end")).toBe(true);// Part way along: cut off at both ends.await scrollTo(label, 100);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(true);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(true);+ expect(label.classList.contains("scroll-fade-start")).toBe(true);+ expect(label.classList.contains("scroll-fade-end")).toBe(true);// Scrolled to the end: only what is behind is cut off.await scrollTo(label, 200);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(true);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(false);+ expect(label.classList.contains("scroll-fade-start")).toBe(true);+ expect(label.classList.contains("scroll-fade-end")).toBe(false);});it("takes a right-to-left line's negative offsets as the same distance travelled", async () => {const label = renderLabel("a right-to-left name", 300);await scrollTo(label, -100);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(true);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(true);+ expect(label.classList.contains("scroll-fade-start")).toBe(true);+ expect(label.classList.contains("scroll-fade-end")).toBe(true);await scrollTo(label, -200);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(true);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(false);+ expect(label.classList.contains("scroll-fade-start")).toBe(true);+ expect(label.classList.contains("scroll-fade-end")).toBe(false);});it("walks an auto-scrolling label at its own pace, and stops it at the end", () => {@@ -160,7 +166,7 @@ describe("ScrollableLabel", () => {const label = renderLabel("short", 100);await scrollTo(label, 0);- expect(label.classList.contains("scrollable-label-fade-start")).toBe(false);- expect(label.classList.contains("scrollable-label-fade-end")).toBe(false);+ expect(label.classList.contains("scroll-fade-start")).toBe(false);+ expect(label.classList.contains("scroll-fade-end")).toBe(false);});});diff --git a/apps/client/src/widgets/react/ScrollableLabel.tsx b/apps/client/src/widgets/react/ScrollableLabel.tsxindex 41258fb472..b80801d04e 100644--- a/apps/client/src/widgets/react/ScrollableLabel.tsx+++ b/apps/client/src/widgets/react/ScrollableLabel.tsx@@ -2,10 +2,9 @@ import "./ScrollableLabel.css";import clsx from "clsx";import type { ComponentChildren } from "preact";-import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef } from "preact/hooks";-/** Fractional scroll offsets are reported at sub-pixel precision, so an edge is never tested exactly. */-const EDGE_EPSILON = 1;+import { useScrollFade } from "./scroll_fade";/** How fast a label reads itself out, in pixels a second: walking pace for the eye, not a marquee. */const AUTO_SCROLL_SPEED = 30;@@ -35,12 +34,10 @@ interface ScrollableLabelProps {*/export default function ScrollableLabel({ children, className, autoScroll }: ScrollableLabelProps) {const ref = useRef<HTMLDivElement>(null);- const [ fades, setFades ] = useState({ start: false, end: false });- // How much of the line lies outside the box. Kept because the walk below starts over whenever it- // changes, which is what walks a label whose words arrived after it did — a path waiting on its- // titles — without asking the caller to say so, and without restarting on a render that changed- // nothing (children given as elements rather than as text are a new value every time).- const [ overflow, setOverflow ] = useState(0);+ // The walk below starts over whenever the overflow changes, which is what walks a label whose+ // words arrived after it did, a path waiting on its titles, without asking the caller to say so+ // and without restarting on a render that changed nothing.+ const { className: fadeClass, overflow } = useScrollFade(ref, { direction: "horizontal" });// Set by the reader's own first scroll, and cleared only by a remount, which is what a new label// is: a walk they interrupted must not start again while the same line is still on screen. A// consumer whose label changes what it names keys it, so the new one arrives with a fresh walk.@@ -49,49 +46,6 @@ export default function ScrollableLabel({ children, className, autoScroll }: ScrhandedOver.current = true;}, []);- const update = useCallback(() => {- const element = ref.current;-- if (!element) {- return;- }-- // Read as a distance travelled rather than as a coordinate: a right-to-left page scrolls the- // same line towards negative offsets, and both ends are the same question either way.- const travelled = Math.abs(element.scrollLeft);- const total = element.scrollWidth - element.clientWidth;-- setOverflow(total);-- const next = {- start: travelled > EDGE_EPSILON,- end: travelled < total - EDGE_EPSILON- };-- setFades((current) =>- current.start === next.start && current.end === next.end ? current : next);- }, []);-- useEffect(() => {- const element = ref.current;-- if (!element) {- return;- }-- update();-- // The box can be resized without the text changing, and the pane this sits in is resized by- // everything from a rotation to a keyboard opening.- const observer = new ResizeObserver(update);-- observer.observe(element);-- return () => observer.disconnect();- // Re-measured on a new label as well: the same box holding a longer name overflows where the- // last one did not, and no resize says so.- }, [ update, children ]);-useEffect(() => {const element = ref.current;@@ -147,13 +101,7 @@ export default function ScrollableLabel({ children, className, autoScroll }: Scrreturn (<divref={ref}- className={clsx(- "scrollable-label",- fades.start && "scrollable-label-fade-start",- fades.end && "scrollable-label-fade-end",- className- )}- onScroll={update}+ className={clsx("scrollable-label", fadeClass, className)}// The gesture rather than the scrolling it causes: a pointer going down on the label, or a// wheel over it, says the reader has taken over before the line has moved an inch. Which// is also why this is not read off the scroll events, where the walk's own scrolling anddiff --git a/apps/client/src/widgets/react/scroll_fade.ts b/apps/client/src/widgets/react/scroll_fade.tsindex aa301af67b..e677583584 100644--- a/apps/client/src/widgets/react/scroll_fade.ts+++ b/apps/client/src/widgets/react/scroll_fade.ts@@ -73,8 +73,9 @@ export function useScrollFade(ref: RefObject<HTMLElement>, options: ScrollFadeOpuseEffect(() => {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.+ // Coalesced, for the observers alone: a batch of cards arriving fires one per change, and+ // each measurement reads a layout the last one just invalidated. A scroll is measured as it+ // happens, so the fade keeps up with the finger rather than trailing it by a frame.const request = () => {if (frameRef.current === undefined) {frameRef.current = requestAnimationFrame(() => {@@ -92,12 +93,12 @@ export function useScrollFade(ref: RefObject<HTMLElement>, options: ScrollFadeOpresize.observe(element);const mutations = new MutationObserver(request);mutations.observe(element, { childList: true, subtree: true, characterData: true });- element.addEventListener("scroll", request, { passive: true });+ element.addEventListener("scroll", measure, { passive: true });return () => {resize.disconnect();mutations.disconnect();- element.removeEventListener("scroll", request);+ element.removeEventListener("scroll", measure);if (frameRef.current !== undefined) {cancelAnimationFrame(frameRef.current);frameRef.current = undefined;