Skip to content

Build your personal knowledge base with Trilium Notes

client/ui: create a scrollable label for mobile

Adorian Doranae727334dcf5
diff --git a/apps/client/src/widgets/react/ScrollableLabel.css b/apps/client/src/widgets/react/ScrollableLabel.css
new file mode 100644
index 0000000000..2cc3a39d4d
--- /dev/null
+++ b/apps/client/src/widgets/react/ScrollableLabel.css
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+.scrollable-label {
+ overflow-x: auto;
+ /* The swipe belongs to the label: without this it carries on into whatever the label sits in once
+ the 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.tsx
new file mode 100644
index 0000000000..76d31c958e
--- /dev/null
+++ b/apps/client/src/widgets/react/ScrollableLabel.spec.tsx
@@ -0,0 +1,125 @@
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import ScrollableLabel from "./ScrollableLabel";
+
+let container: HTMLDivElement | undefined;
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+});
+
+/**
+ * happy-dom lays nothing out, so the metrics the component reads are given directly. `scrollLeft` is
+ * 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 label = container.querySelector<HTMLDivElement>(".scrollable-label");
+
+ if (!label) {
+ throw new Error("the label did not render");
+ }
+
+ Object.defineProperty(label, "scrollWidth", { value: scrollWidth, configurable: true });
+ Object.defineProperty(label, "clientWidth", { value: clientWidth, configurable: true });
+
+ return label;
+}
+
+/**
+ * The component measures on mount and on every scroll; a scroll is how the test asks it to re-read.
+ * Awaited because the classes are state set from the handler, which Preact renders on a microtask.
+ */
+async function scrollTo(label: HTMLDivElement, scrollLeft: number) {
+ label.scrollLeft = scrollLeft;
+ label.dispatchEvent(new Event("scroll"));
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+describe("ScrollableLabel", () => {
+ it("fades whichever end the line carries on past, and neither where it fits", async () => {
+ const label = renderLabel("a name far longer than its box", 300);
+
+ // 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);
+
+ // 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);
+
+ // 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);
+ });
+
+ 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);
+
+ await scrollTo(label, -200);
+ expect(label.classList.contains("scrollable-label-fade-start")).toBe(true);
+ expect(label.classList.contains("scrollable-label-fade-end")).toBe(false);
+ });
+
+ it("walks an auto-scrolling label at its own pace, and stops it at the end", () => {
+ vi.useFakeTimers();
+
+ try {
+ // 200px to travel at 30px a second: a second in, a fraction of the way along; a minute
+ // in, sitting at the end rather than anywhere past it.
+ const label = renderLabel("a name that reads itself out", 300, 100, true);
+
+ vi.advanceTimersByTime(1000);
+ expect(label.scrollLeft).toBeGreaterThan(20);
+ expect(label.scrollLeft).toBeLessThan(40);
+
+ vi.advanceTimersByTime(60_000);
+ expect(label.scrollLeft).toBe(200);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("hands an auto-scrolling label over for good once the reader touches it", () => {
+ vi.useFakeTimers();
+
+ try {
+ const label = renderLabel("a name the reader takes over", 300, 100, true);
+
+ vi.advanceTimersByTime(1000);
+ label.dispatchEvent(new Event("pointerdown", { bubbles: true }));
+
+ const handedOverAt = label.scrollLeft;
+
+ // Left exactly where the reader took it: the walk does not resume, and does not finish
+ // the line off from under them.
+ vi.advanceTimersByTime(10_000);
+ expect(label.scrollLeft).toBe(handedOverAt);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("leaves a label that fits alone, fading nothing", async () => {
+ 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);
+ });
+});
diff --git a/apps/client/src/widgets/react/ScrollableLabel.tsx b/apps/client/src/widgets/react/ScrollableLabel.tsx
new file mode 100644
index 0000000000..498c0117ad
--- /dev/null
+++ b/apps/client/src/widgets/react/ScrollableLabel.tsx
@@ -0,0 +1,160 @@
+import "./ScrollableLabel.css";
+
+import clsx from "clsx";
+import type { ComponentChildren } from "preact";
+import { useCallback, useEffect, 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;
+
+/** How fast a label reads itself out, in pixels a second: walking pace for the eye, not a marquee. */
+const AUTO_SCROLL_SPEED = 30;
+
+interface ScrollableLabelProps {
+ children?: ComponentChildren;
+ className?: string;
+ /**
+ * Walk the line to its end on its own, so what is cut off is read without being asked for. It
+ * stops at the end rather than looping or coming back, and the first sign of the reader taking
+ * over hands it to them for good: what they were reading must not slide out from under them.
+ *
+ * For a line that is shown rather than reached for, and where nothing is lost by it moving. Not
+ * for one the reader is picking a part out of.
+ */
+ autoScroll?: boolean;
+}
+
+/**
+ * A single line of text too long for its box, which the reader swipes along rather than losing the end
+ * of. What is cut off fades out at whichever edge it continues past, so the line says that it goes on
+ * — the ellipsis of a label that can actually be read to the end.
+ *
+ * For where a name has to be given in full and there is no width to give it in: a phone, a narrow
+ * pane, a strip along the foot of a chart. A label that fits behaves as any other, showing no fade
+ * and taking no swipe.
+ */
+export default function ScrollableLabel({ children, className, autoScroll }: ScrollableLabelProps) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [ fades, setFades ] = useState({ start: false, end: false });
+ // Set by the reader's own first scroll, and cleared only by a new label: a walk they interrupted
+ // must not start again while the same line is still on screen.
+ const handedOver = useRef(false);
+ const handOver = useCallback(() => {
+ handedOver.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;
+ 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;
+
+ if (!autoScroll || !element || prefersReducedMotion()) {
+ return;
+ }
+
+ // A new label is a new walk, from its own beginning, whatever became of the last one.
+ handedOver.current = false;
+ element.scrollLeft = 0;
+
+ // Read once rather than per frame: a right-to-left line travels towards negative offsets, so
+ // the same distance is applied with the sign its direction gives it.
+ const sign = getComputedStyle(element).direction === "rtl" ? -1 : 1;
+ let travelled = 0;
+ let previous: number | undefined;
+ let frame = 0;
+
+ // Advanced by elapsed time rather than by a step per frame, so the line reads at one pace
+ // whatever the display refreshes at, and a frame the browser skipped is made up for. Written
+ // out before it is asked for, so that the element read above stays narrowed inside it.
+ const step = (now: number) => {
+ // Tested here rather than only before asking for the next frame: the frame already in
+ // hand when the reader took over would otherwise move the line one last time, under them.
+ if (handedOver.current) {
+ return;
+ }
+
+ const total = element.scrollWidth - element.clientWidth;
+
+ if (previous !== undefined) {
+ travelled = Math.min(travelled + (now - previous) * AUTO_SCROLL_SPEED / 1000, total);
+ element.scrollLeft = sign * travelled;
+ }
+
+ previous = now;
+
+ // The end is where it stops: there is nothing further to read, and a line that came back
+ // to its start would be read as a new one arriving.
+ if (travelled < total) {
+ frame = requestAnimationFrame(step);
+ }
+ };
+
+ frame = requestAnimationFrame(step);
+
+ return () => cancelAnimationFrame(frame);
+ // Restarted per label, which is also how a path that arrived after its own strip did gets
+ // walked: the titles land as a second render.
+ }, [ autoScroll, children ]);
+
+ return (
+ <div
+ ref={ref}
+ className={clsx(
+ "scrollable-label",
+ fades.start && "scrollable-label-fade-start",
+ fades.end && "scrollable-label-fade-end",
+ className
+ )}
+ onScroll={update}
+ // 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 and
+ // the reader's would have to be told apart by their arithmetic.
+ onPointerDown={autoScroll ? handOver : undefined}
+ onWheel={autoScroll ? handOver : undefined}
+ >{children}</div>
+ );
+}
+
+/** A line that moves on its own is the thing this setting is there to ask for less of. */
+function prefersReducedMotion() {
+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+}