🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(events): animate the realtime log's new-events pill and arriving rows (#1256)
Goldflag17f3c56c0587
diff --git a/client/src/app/[site]/events/components/EventLog/EventLog.tsx b/client/src/app/[site]/events/components/EventLog/EventLog.tsxindex 93fbae7e7..023d23738 100644--- a/client/src/app/[site]/events/components/EventLog/EventLog.tsx+++ b/client/src/app/[site]/events/components/EventLog/EventLog.tsx@@ -4,6 +4,7 @@ import { useExtracted } from "next-intl";import { useVirtualizer } from "@tanstack/react-virtual";import { useParams } from "next/navigation";import { useCallback, useState } from "react";+import { NewItemsPill } from "@/components/interior/new-items-pill";import { Event } from "../../../../../api/analytics/endpoints";import { EVENT_TYPE_CONFIG } from "../../../../../lib/events";import { EventTypeFilter } from "../../../../../components/EventTypeFilter";@@ -11,11 +12,12 @@ import { NothingFound } from "../../../../../components/NothingFound";import { ErrorState } from "../../../../../components/ErrorState";import { ScrollArea } from "../../../../../components/ui/scroll-area";import { EventDetailsSheet } from "./EventDetailsSheet";+import { getEventKey } from "./eventLogUtils";import { EventRow } from "./EventRow";import { RealtimeToggle } from "./RealtimeToggle";import { useEventLogState } from "./useEventLogState";-const ALL_EVENT_TYPES = new Set(EVENT_TYPE_CONFIG.map((c) => c.value as string));+const ALL_EVENT_TYPES = new Set(EVENT_TYPE_CONFIG.map(c => c.value as string));export function EventLog() {const t = useExtracted();@@ -25,7 +27,7 @@ export function EventLog() {const [visibleTypes, setVisibleTypes] = useState<Set<string>>(ALL_EVENT_TYPES);const handleToggleType = useCallback((type: string) => {- setVisibleTypes((prev) => {+ setVisibleTypes(prev => {const next = new Set(prev);if (next.has(type)) {next.delete(type);@@ -52,8 +54,15 @@ export function EventLog() {isLive,bufferedCount,flushAndScrollToTop,+ arrivals,} = useEventLogState({ visibleTypes });+ const jumpToNewEvents = () => {+ flushAndScrollToTop();+ // The pill unmounts with the click; keep keyboard focus in the list instead of dropping it on <body>.+ scrollElement?.focus({ preventScroll: true });+ };+const rowVirtualizer = useVirtualizer({count: allEvents.length,getScrollElement: () => scrollElement,@@ -65,13 +74,7 @@ export function EventLog() {// --- Infinite scroll trigger ---const lastItem = virtualItems[virtualItems.length - 1];- if (- lastItem &&- lastItem.index >= allEvents.length - 5 &&- hasNextPage &&- !isFetchingNextPage &&- !isLoading- ) {+ if (lastItem && lastItem.index >= allEvents.length - 5 && hasNextPage && !isFetchingNextPage && !isLoading) {fetchNextPage();}@@ -87,15 +90,19 @@ export function EventLog() {</div><div className="relative">- {/* New events indicator */}- {isRealtime && !isLive && bufferedCount > 0 && (- <button- onClick={flushAndScrollToTop}- className="absolute top-12 left-1/2 -translate-x-1/2 z-30 px-3 py-1 rounded-full bg-accent-400 dark:bg-accent-600 text-white text-xs font-medium shadow-lg hover:bg-accent-300 dark:hover:bg-accent-500 transition-colors cursor-pointer"- >- {t("{bufferedCount} new events", { bufferedCount: String(bufferedCount) })}- </button>- )}+ {/* Events that arrived while scrolled away from the top wait in a buffer; the pill brings them in. */}+ <NewItemsPill+ className="top-10"+ count={isRealtime && !isLive ? bufferedCount : 0}+ onJump={jumpToNewEvents}+ describe={count => t("{count, plural, one {# new event} other {# new events}}", { count })}+ label={(count, ticker) =>+ t.rich("{count, plural, one {<ticker>#</ticker> new event} other {<ticker>#</ticker> new events}}", {+ count,+ ticker: () => ticker,+ })+ }+ /><ScrollAreaclassName="h-[90vh] border border-neutral-100 dark:border-neutral-800 rounded-lg"@@ -129,10 +136,7 @@ export function EventLog() {)}{isFetched && !isError && allEvents.length === 0 && (- <NothingFound- title={t("No events found")}- description={t("Try a different date range or filter")}- />+ <NothingFound title={t("No events found")} description={t("Try a different date range or filter")} />)}{showBody && (@@ -144,7 +148,7 @@ export function EventLog() {position: "relative",}}>- {virtualItems.map((virtualRow) => {+ {virtualItems.map(virtualRow => {const event = allEvents[virtualRow.index];if (!event) return null;@@ -162,7 +166,8 @@ export function EventLog() {<EventRowevent={event}site={site as string}- onClick={(selected) => {+ arrivedAt={arrivals.size ? arrivals.get(getEventKey(event)) : undefined}+ onClick={selected => {setSelectedEvent(selected);setSheetOpen(true);}}@@ -188,7 +193,7 @@ export function EventLog() {<EventDetailsSheetopen={sheetOpen}- onOpenChange={(open) => {+ onOpenChange={open => {setSheetOpen(open);if (!open) setSelectedEvent(null);}}@@ -221,9 +226,7 @@ function EventLogItemSkeleton({ showProperties }: { showProperties?: boolean })<div className="h-3 w-28 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" /></div><div className="flex items-center px-2">- {showProperties && (- <div className="h-3 w-32 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />- )}+ {showProperties && <div className="h-3 w-32 rounded bg-neutral-200 dark:bg-neutral-700 animate-pulse" />}</div></div>);diff --git a/client/src/app/[site]/events/components/EventLog/EventRow.tsx b/client/src/app/[site]/events/components/EventLog/EventRow.tsxindex 877947f7c..e66db86b5 100644--- a/client/src/app/[site]/events/components/EventLog/EventRow.tsx+++ b/client/src/app/[site]/events/components/EventLog/EventRow.tsx@@ -3,6 +3,8 @@import { useExtracted } from "next-intl";import Link from "next/link";import { DateTime } from "luxon";+import { useRef } from "react";+import { useArrivalHighlight } from "@/components/interior/use-arrival-highlight";import { Event } from "../../../../../api/analytics/endpoints";import { Avatar } from "../../../../../components/Avatar";import { EventTypeIcon } from "../../../../../components/EventIcons";@@ -21,16 +23,18 @@ interface EventRowProps {event: Event;site: string;onClick: (event: Event) => void;+ /** performance.now() when the row arrived from a poll; it gets a brief neutral highlight. */+ arrivedAt?: number;}-export function EventRow({ event, site, onClick }: EventRowProps) {+export function EventRow({ event, site, onClick, arrivedAt }: EventRowProps) {const t = useExtracted();+ const rowRef = useRef<HTMLDivElement>(null);+ useArrivalHighlight(rowRef, arrivedAt);const getEventDisplayName = useEventDisplayName();const { locale, hour12, formatRelative } = useDateTimeFormat();const eventProperties = parseEventProperties(event);- const eventTime = DateTime.fromSQL(event.timestamp, { zone: "utc" })- .setLocale(locale)- .setZone(getTimezone());+ const eventTime = DateTime.fromSQL(event.timestamp, { zone: "utc" }).setLocale(locale).setZone(getTimezone());const pagePath = buildEventPath(event);const pageUrl = `https://${event.hostname}${pagePath}`;const isPageview = event.type === "pageview";@@ -44,7 +48,8 @@ export function EventRow({ event, site, onClick }: EventRowProps) {return (<div- className="grid grid-cols-[28px_145px_180px_100px_1fr_1fr] border-b border-neutral-100 dark:border-neutral-800 hover:bg-neutral-50/60 dark:hover:bg-neutral-800/40 cursor-pointer"+ ref={rowRef}+ className="grid grid-cols-[28px_145px_180px_100px_1fr_1fr] border-b border-neutral-100 dark:border-neutral-800 hover:bg-neutral-50/60 dark:hover:bg-neutral-800/40 cursor-pointer [--arrival-bg:hsl(var(--neutral-100))] dark:[--arrival-bg:hsl(var(--neutral-800))]"onClick={() => onClick(event)}><div className="flex items-center justify-center py-1">@@ -78,7 +83,9 @@ export function EventRow({ event, site, onClick }: EventRowProps) {className="flex items-center gap-2"><Avatar size={18} id={event.user_id} lastActiveTime={eventTime} />- <div className="text-neutral-700 dark:text-neutral-200 truncate max-w-[160px] hover:underline">{displayName}</div>+ <div className="text-neutral-700 dark:text-neutral-200 truncate max-w-[160px] hover:underline">+ {displayName}+ </div></Link></div>@@ -141,8 +148,8 @@ export function EventRow({ event, site, onClick }: EventRowProps) {</div><div className="text-neutral-600 dark:text-neutral-300 px-2 py-1 truncate">- {eventData && (- eventData.url ? (+ {eventData &&+ (eventData.url ? (<Linkhref={eventData.url}target="_blank"@@ -154,11 +161,8 @@ export function EventRow({ event, site, onClick }: EventRowProps) {{truncateString(eventData.label, 60)}</Link>) : (- <span title={eventData.label}>- {truncateString(eventData.label, 60)}- </span>- )- )}+ <span title={eventData.label}>{truncateString(eventData.label, 60)}</span>+ ))}</div></div>);diff --git a/client/src/app/[site]/events/components/EventLog/useEventLogState.ts b/client/src/app/[site]/events/components/EventLog/useEventLogState.tsindex 896b2ab16..d63376848 100644--- a/client/src/app/[site]/events/components/EventLog/useEventLogState.ts+++ b/client/src/app/[site]/events/components/EventLog/useEventLogState.ts@@ -1,17 +1,17 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { type Arrivals, NO_ARRIVALS, recordArrivals } from "@/components/interior/use-arrival-highlight";import { Event } from "../../../../../api/analytics/endpoints";-import {- useGetEventsCursor,- useNewEventsPoll,-} from "../../../../../api/analytics/hooks/events/useGetEvents";+import { useGetEventsCursor, useNewEventsPoll } from "../../../../../api/analytics/hooks/events/useGetEvents";import { getEventKey } from "./eventLogUtils";const MAX_EVENTS = 10_000;const PAGE_SIZE = 100;-export function useEventLogState(options: {- visibleTypes: Set<string>;-} = { visibleTypes: new Set() }) {+export function useEventLogState(+ options: {+ visibleTypes: Set<string>;+ } = { visibleTypes: new Set() }+) {// --- Mode state ---const [isRealtime, setIsRealtime] = useState(true);@@ -29,10 +29,16 @@ export function useEventLogState(options: {const bufferedEventsRef = useRef<Event[]>([]);const [bufferedCount, setBufferedCount] = useState(0);+ // --- Rows that just entered the list (event key → arrival time), for a brief highlight ---+ const [arrivals, setArrivals] = useState<Arrivals>(NO_ARRIVALS);+ const markArrived = useCallback((events: Event[]) => {+ const now = performance.now();+ const keys = events.map(getEventKey);+ setArrivals(prev => recordArrivals(prev, keys, now));+ }, []);+// --- Scroll refs ---- const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(- null- );+ const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);const viewportRef = useRef<HTMLDivElement | null>(null);// --- Cursor query (both modes) ---@@ -47,10 +53,7 @@ export function useEventLogState(options: {} = useGetEventsCursor({ isRealtime, pageSize: PAGE_SIZE });// --- Derive cursor events from query data ---- const cursorEvents = useMemo(- () => cursorData?.pages.flatMap((p) => p.data) ?? [],- [cursorData]- );+ const cursorEvents = useMemo(() => cursorData?.pages.flatMap(p => p.data) ?? [], [cursorData]);// --- Combined event list ---const mergedEvents = useMemo(() => {@@ -62,7 +65,7 @@ export function useEventLogState(options: {const { visibleTypes } = options;const allEvents = useMemo(() => {if (visibleTypes.size === 0) return mergedEvents;- return mergedEvents.filter((ev) => visibleTypes.has(ev.type));+ return mergedEvents.filter(ev => visibleTypes.has(ev.type));}, [mergedEvents, visibleTypes]);// --- Rebuild seenKeys + set latestTimestamp when cursor data changes ---@@ -78,10 +81,7 @@ export function useEventLogState(options: {}, [cursorEvents]);// --- Poll query (realtime only) ---- const getSinceTimestamp = useCallback(- () => latestTimestampRef.current,- []- );+ const getSinceTimestamp = useCallback(() => latestTimestampRef.current, []);const { data: pollData } = useNewEventsPoll({getSinceTimestamp,enabled: isRealtime,@@ -104,27 +104,22 @@ export function useEventLogState(options: {// Update latest timestampconst newestTs = newEvents[0].timestamp;- if (- !latestTimestampRef.current ||- newestTs > latestTimestampRef.current- ) {+ if (!latestTimestampRef.current || newestTs > latestTimestampRef.current) {latestTimestampRef.current = newestTs;}if (isLiveRef.current) {- setPrependedEvents((prev) => {+ setPrependedEvents(prev => {const combined = [...newEvents, ...prev];if (combined.length + cursorEvents.length > MAX_EVENTS) {return combined.slice(0, MAX_EVENTS - cursorEvents.length);}return combined;});+ markArrived(newEvents);} else {- bufferedEventsRef.current = [- ...newEvents,- ...bufferedEventsRef.current,- ];- setBufferedCount((c) => c + newEvents.length);+ bufferedEventsRef.current = [...newEvents, ...bufferedEventsRef.current];+ setBufferedCount(c => c + newEvents.length);}// eslint-disable-next-line react-hooks/exhaustive-deps}, [pollData]);@@ -137,26 +132,25 @@ export function useEventLogState(options: {bufferedEventsRef.current = [];setBufferedCount(0);setIsLive(true);+ setArrivals(prev => (prev.size ? NO_ARRIVALS : prev));}, [isRealtime]);// --- Callback ref: capture viewport whenever ScrollArea mounts ---- const scrollAreaCallbackRef = useCallback(- (node: HTMLDivElement | null) => {- if (node) {- const viewport = node.querySelector<HTMLDivElement>(- '[data-slot="scroll-area-viewport"]'- );- if (viewport) {- viewportRef.current = viewport;- setScrollElement(viewport);- }- } else {- viewportRef.current = null;- setScrollElement(null);+ const scrollAreaCallbackRef = useCallback((node: HTMLDivElement | null) => {+ if (node) {+ const viewport = node.querySelector<HTMLDivElement>('[data-slot="scroll-area-viewport"]');+ if (viewport) {+ // Focus lands here after a jump to new events (the pill leaves with the click).+ // -1 makes it focusable from script without adding a tab stop.+ if (!viewport.hasAttribute("tabindex")) viewport.tabIndex = -1;+ viewportRef.current = viewport;+ setScrollElement(viewport);}- },- []- );+ } else {+ viewportRef.current = null;+ setScrollElement(null);+ }+ }, []);// --- Scroll listener for auto-pause/resume ---useEffect(() => {@@ -172,7 +166,8 @@ export function useEventLogState(options: {const buffered = bufferedEventsRef.current;bufferedEventsRef.current = [];setBufferedCount(0);- setPrependedEvents((prev) => [...buffered, ...prev]);+ setPrependedEvents(prev => [...buffered, ...prev]);+ markArrived(buffered);}} else if (!atTop && isLiveRef.current) {setIsLive(false);@@ -196,14 +191,15 @@ export function useEventLogState(options: {setIsLive(true);if (buffered.length > 0) {- setPrependedEvents((prev) => [...buffered, ...prev]);+ setPrependedEvents(prev => [...buffered, ...prev]);+ markArrived(buffered);}viewport.scrollTop = 0;- }, []);+ }, [markArrived]);const toggleRealtime = useCallback(() => {- setIsRealtime((prev) => !prev);+ setIsRealtime(prev => !prev);}, []);return {@@ -231,5 +227,8 @@ export function useEventLogState(options: {isLive,bufferedCount,flushAndScrollToTop,++ // Arrival highlight+ arrivals,};}diff --git a/client/src/components/interior/new-items-pill.test.tsx b/client/src/components/interior/new-items-pill.test.tsxnew file mode 100644index 000000000..0169ed84b--- /dev/null+++ b/client/src/components/interior/new-items-pill.test.tsx@@ -0,0 +1,108 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ANNOUNCE_DELAY_MS, ANNOUNCE_INTERVAL_MS, NewItemsPill } from "./new-items-pill";++vi.mock("next-intl", () => ({ useLocale: () => "en" }));+vi.mock("@number-flow/react", () => ({+ default: ({ value }: { value: number }) => <span data-testid="ticker">{value}</span>,+}));++const describe_ = (count: number) => `${count} new ${count === 1 ? "event" : "events"}`;++function Pill({ count, onJump = () => {} }: { count: number; onJump?: () => void }) {+ return (+ <NewItemsPill+ count={count}+ onJump={onJump}+ describe={describe_}+ label={(n, ticker) => (+ <>+ {ticker} new {n === 1 ? "event" : "events"}+ </>+ )}+ />+ );+}++const status = () => screen.getByRole("status");++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("NewItemsPill", () => {+ it("renders no button while nothing is waiting", () => {+ render(<Pill count={0} />);+ expect(screen.queryByRole("button")).toBeNull();+ expect(status().textContent).toBe("");+ });++ it("appears as a real, labelled button whose count is the ticker", () => {+ const { rerender } = render(<Pill count={0} />);+ rerender(<Pill count={3} />);++ const button = screen.getByRole("button", { name: "3 new events" });+ expect(button.getAttribute("type")).toBe("button");+ expect(screen.getByTestId("ticker").textContent).toBe("3");+ // No resting shadow: it is an in-page control, not an overlay.+ expect(button.className).not.toMatch(/shadow/);++ rerender(<Pill count={7} />);+ expect(screen.getByRole("button", { name: "7 new events" })).toBeTruthy();+ expect(screen.getByTestId("ticker").textContent).toBe("7");+ });++ it("jumps on click", () => {+ const onJump = vi.fn();+ render(<Pill count={2} onJump={onJump} />);+ fireEvent.click(screen.getByRole("button"));+ expect(onJump).toHaveBeenCalledOnce();+ });++ it("announces politely once the count settles, then at most once per interval with the latest count", () => {+ let now = 0;+ const advance = (ms: number) => {+ now += ms;+ act(() => vi.advanceTimersByTime(ms));+ };+ const { rerender } = render(<Pill count={2} />);++ advance(ANNOUNCE_DELAY_MS - 1);+ expect(status().textContent).toBe("");+ advance(1);+ expect(status().textContent).toBe("2 new events");+ const spokenAt = now;++ // Polls land every two seconds; none of them is spoken straight away...+ advance(2000);+ rerender(<Pill count={5} />);+ advance(2000);+ rerender(<Pill count={9} />);+ advance(ANNOUNCE_DELAY_MS);+ expect(status().textContent).toBe("2 new events");++ // ...the latest count is, once the interval since the last announcement has passed.+ advance(spokenAt + ANNOUNCE_INTERVAL_MS - now - 1);+ expect(status().textContent).toBe("2 new events");+ advance(1);+ expect(status().textContent).toBe("9 new events");+ });++ it("clears the announcement as soon as the count drops to zero, and starts fresh after", () => {+ const { rerender } = render(<Pill count={4} />);+ act(() => vi.advanceTimersByTime(ANNOUNCE_DELAY_MS));+ expect(status().textContent).toBe("4 new events");++ rerender(<Pill count={0} />);+ expect(status().textContent).toBe("");++ rerender(<Pill count={1} />);+ act(() => vi.advanceTimersByTime(ANNOUNCE_DELAY_MS));+ expect(status().textContent).toBe("1 new event");+ });+});diff --git a/client/src/components/interior/new-items-pill.tsx b/client/src/components/interior/new-items-pill.tsxnew file mode 100644index 000000000..dee80f2a3--- /dev/null+++ b/client/src/components/interior/new-items-pill.tsx@@ -0,0 +1,93 @@+// Adapted from interior.dev "New Items Pill" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import NumberFlow from "@number-flow/react";+import { AnimatePresence, motion } from "framer-motion";+import { ArrowUp } from "lucide-react";+import { useLocale } from "next-intl";+import { type ReactNode, useEffect, useRef, useState } from "react";++import { buttonVariants } from "@/components/ui/button";+import { FADE_IN, FADE_OUT, SPRING_PANEL } from "@/lib/motion";+import { cn } from "@/lib/utils";++// Let a burst settle before speaking (upstream's delay)...+export const ANNOUNCE_DELAY_MS = 700;+// ...and on a feed that polls every couple of seconds, speak at most this often, always the latest count.+export const ANNOUNCE_INTERVAL_MS = 10_000;++export type NewItemsPillProps = {+ /** Items waiting out of view. The pill shows while this is above zero. */+ count: number;+ /** Bring the new items into view (and put focus somewhere sensible: the pill leaves with the click). */+ onJump: () => void;+ /** The count as a plain phrase ("3 new events"): the button's accessible name and the polite announcement. */+ describe: (count: number) => string;+ /** Visible label. `ticker` is the count as a ticking NumberFlow; place it where the locale puts numbers. */+ label: (count: number, ticker: ReactNode) => ReactNode;+ /** Position the pill inside its `relative` container, e.g. "top-10". */+ className?: string;+};++/**+ * "N new items" above a list the user has scrolled away from. It springs in, its count ticks as more+ * arrive, it is a real button (Tab reaches it), and it announces politely without chattering.+ */+export function NewItemsPill({ count, onJump, describe, label, className }: NewItemsPillProps) {+ const locale = useLocale();+ const announced = usePoliteCount(count);++ return (+ <div className={cn("pointer-events-none absolute inset-x-0 z-30 flex justify-center", className)}>+ <AnimatePresence initial={false}>+ {count > 0 && (+ <motion.button+ key="new-items-pill"+ type="button"+ onClick={onJump}+ aria-label={describe(count)}+ initial={{ opacity: 0, y: -8, scale: 0.96 }}+ animate={{ opacity: 1, y: 0, scale: 1 }}+ exit={{ opacity: 0, y: -4, scale: 0.98, transition: FADE_OUT }}+ transition={{ ...SPRING_PANEL, opacity: FADE_IN }}+ className={cn(+ buttonVariants({ variant: "accent", size: "xs" }),+ "pointer-events-auto h-7 gap-1.5 rounded-full pr-2.5 pl-2 [&_svg]:size-3.5"+ )}+ >+ <ArrowUp aria-hidden="true" strokeWidth={2.5} />+ <span aria-hidden="true" className="tabular-nums">+ {label(count, <NumberFlow value={count} locales={locale} />)}+ </span>+ </motion.button>+ )}+ </AnimatePresence>+ <span role="status" aria-live="polite" className="sr-only">+ {announced > 0 ? describe(announced) : ""}+ </span>+ </div>+ );+}++// The count to announce: settles for ANNOUNCE_DELAY_MS, then speaks at most once per+// ANNOUNCE_INTERVAL_MS. Clears as soon as the count drops to zero.+function usePoliteCount(count: number) {+ const [announced, setAnnounced] = useState(0);+ const lastSpokenAt = useRef(Number.NEGATIVE_INFINITY);++ useEffect(() => {+ if (count === 0) {+ setAnnounced(0);+ lastSpokenAt.current = Number.NEGATIVE_INFINITY;+ return;+ }+ const wait = Math.max(ANNOUNCE_DELAY_MS, lastSpokenAt.current + ANNOUNCE_INTERVAL_MS - Date.now());+ const timer = setTimeout(() => {+ lastSpokenAt.current = Date.now();+ setAnnounced(count);+ }, wait);+ return () => clearTimeout(timer);+ }, [count]);++ return announced;+}diff --git a/client/src/components/interior/use-arrival-highlight.test.tsx b/client/src/components/interior/use-arrival-highlight.test.tsxnew file mode 100644index 000000000..f2b455a85--- /dev/null+++ b/client/src/components/interior/use-arrival-highlight.test.tsx@@ -0,0 +1,120 @@+import { cleanup, render } from "@testing-library/react";+import { useRef } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ARRIVAL_MS, NO_ARRIVALS, recordArrivals, useArrivalHighlight } from "./use-arrival-highlight";++describe("recordArrivals", () => {+ it("stamps the arriving keys with the arrival time", () => {+ const arrivals = recordArrivals(NO_ARRIVALS, ["a", "b"], 5000);+ expect([...arrivals]).toEqual([+ ["a", 5000],+ ["b", 5000],+ ]);+ });++ it("keeps stamps still highlighting and drops finished ones", () => {+ const first = recordArrivals(NO_ARRIVALS, ["old"], 1000);+ const second = recordArrivals(first, ["mid"], 1000 + ARRIVAL_MS / 2);+ const third = recordArrivals(second, ["new"], 1000 + ARRIVAL_MS);++ expect(third.has("old")).toBe(false);+ expect(third.get("mid")).toBe(1000 + ARRIVAL_MS / 2);+ expect(third.get("new")).toBe(1000 + ARRIVAL_MS);+ });++ it("returns a new map and leaves the previous one untouched", () => {+ const first = recordArrivals(NO_ARRIVALS, ["a"], 0);+ const second = recordArrivals(first, ["b"], 10);+ expect(second).not.toBe(first);+ expect([...first.keys()]).toEqual(["a"]);+ expect(NO_ARRIVALS.size).toBe(0);+ });++ it("stamps at most the top 200 of a large flushed batch", () => {+ const keys = Array.from({ length: 1000 }, (_, i) => `event-${i}`);+ const arrivals = recordArrivals(NO_ARRIVALS, keys, 0);+ expect(arrivals.size).toBe(200);+ expect(arrivals.has("event-0")).toBe(true);+ expect(arrivals.has("event-200")).toBe(false);+ });+});++describe("useArrivalHighlight", () => {+ const cancel = vi.fn();+ const animate = vi.fn(() => ({ cancel }) as unknown as Animation);+ let wash = "rgb(48, 48, 48)";++ function Row({ arrivedAt }: { arrivedAt?: number }) {+ const ref = useRef<HTMLDivElement>(null);+ useArrivalHighlight(ref, arrivedAt);+ return <div ref={ref}>row</div>;+ }++ beforeEach(() => {+ vi.spyOn(performance, "now").mockReturnValue(10_000);+ vi.spyOn(window, "getComputedStyle").mockImplementation(+ () => ({ getPropertyValue: (name: string) => (name === "--arrival-bg" ? ` ${wash}` : "") }) as CSSStyleDeclaration+ );+ HTMLElement.prototype.animate = animate as unknown as HTMLElement["animate"];+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ animate.mockClear();+ cancel.mockClear();+ wash = "rgb(48, 48, 48)";+ delete (HTMLElement.prototype as Partial<HTMLElement>).animate;+ });++ it("leaves rows that didn't arrive from a poll alone", () => {+ render(<Row />);+ expect(animate).not.toHaveBeenCalled();+ });++ it("fades the token color off a row that just arrived", () => {+ render(<Row arrivedAt={10_000} />);++ expect(animate).toHaveBeenCalledOnce();+ const [keyframes, timing] = animate.mock.calls[0] as unknown as [Keyframe[], KeyframeAnimationOptions];+ expect(keyframes[0]).toEqual({ backgroundColor: "rgb(48, 48, 48)" });+ expect(keyframes.at(-1)).toEqual({ backgroundColor: "transparent" });+ expect(timing).toMatchObject({ duration: ARRIVAL_MS });+ expect(timing.delay).toBeCloseTo(0);+ });++ it("resumes mid-fade when a virtualized row remounts, instead of starting over", () => {+ render(<Row arrivedAt={10_000 - 400} />);+ const [, timing] = animate.mock.calls[0] as unknown as [Keyframe[], KeyframeAnimationOptions];+ expect(timing.delay).toBe(-400);+ });++ it("holds the mark and drops it without a fade under reduced motion", () => {+ // jsdom has no matchMedia; the hook treats its absence as "no preference".+ window.matchMedia = (query: string) =>+ ({ matches: query === "(prefers-reduced-motion: reduce)" }) as MediaQueryList;+ render(<Row arrivedAt={10_000} />);+ delete (window as Partial<Window>).matchMedia;++ const [keyframes, timing] = animate.mock.calls[0] as unknown as [Keyframe[], KeyframeAnimationOptions];+ expect(keyframes).toEqual([{ backgroundColor: "rgb(48, 48, 48)" }, { backgroundColor: "rgb(48, 48, 48)" }]);+ expect(timing).toMatchObject({ duration: ARRIVAL_MS });+ });++ it("stays plain once the highlight window has passed", () => {+ render(<Row arrivedAt={10_000 - ARRIVAL_MS} />);+ expect(animate).not.toHaveBeenCalled();+ });++ it("does nothing without a color token", () => {+ wash = "";+ render(<Row arrivedAt={10_000} />);+ expect(animate).not.toHaveBeenCalled();+ });++ it("cancels the fade when the row unmounts", () => {+ const { unmount } = render(<Row arrivedAt={10_000} />);+ unmount();+ expect(cancel).toHaveBeenCalledOnce();+ });+});diff --git a/client/src/components/interior/use-arrival-highlight.ts b/client/src/components/interior/use-arrival-highlight.tsnew file mode 100644index 000000000..30455e0d7--- /dev/null+++ b/client/src/components/interior/use-arrival-highlight.ts@@ -0,0 +1,67 @@+"use client";++// Companion to the New Items Pill: a brief neutral wash on rows that just arrived in a live list.+// Rybbit's own; not adapted from a third-party source.++import { type RefObject, useEffect, useLayoutEffect } from "react";++const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;++/** How long an arrived row stays marked, in ms: a short hold, then a fade to nothing. */+export const ARRIVAL_MS = 1000;+// Only the top of a large flushed batch is on screen after a jump; stamping thousands buys nothing.+const MAX_STAMPED = 200;++/** Row key → performance.now() at arrival. */+export type Arrivals = ReadonlyMap<string, number>;++export const NO_ARRIVALS: Arrivals = new Map();++/**+ * Stamps `keys` (newest first) as arrived at `now` and drops stamps whose highlight has finished, so+ * the map only ever holds the last second's worth of rows.+ */+export function recordArrivals(previous: Arrivals, keys: readonly string[], now: number): Arrivals {+ const next = new Map<string, number>();+ for (const [key, at] of previous) {+ if (now - at < ARRIVAL_MS) next.set(key, at);+ }+ for (const key of keys.slice(0, MAX_STAMPED)) next.set(key, now);+ return next;+}++/**+ * Fades a neutral wash off an element that arrived at `arrivedAt` (a performance.now() stamp).+ *+ * Keyed to the arrival time, not to mount: a virtualized row that remounts mid-fade picks up where it+ * was instead of starting over, and one that scrolls into view after the fade stays plain. The color+ * comes from the element's `--arrival-bg` custom property, so the tokens (and dark mode) stay in CSS.+ */+export function useArrivalHighlight(ref: RefObject<HTMLElement | null>, arrivedAt: number | undefined) {+ useIsoLayoutEffect(() => {+ const element = ref.current;+ if (arrivedAt === undefined || !element || typeof element.animate !== "function") return;++ const elapsed = performance.now() - arrivedAt;+ if (elapsed >= ARRIVAL_MS) return;++ const wash = getComputedStyle(element).getPropertyValue("--arrival-bg").trim();+ if (!wash) return;++ // Reduced motion: the same mark for the same time, dropped at the end instead of faded (the+ // global reduced-motion CSS rule can't reach a Web Animation).+ const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;+ const animation = element.animate(+ reduced+ ? [{ backgroundColor: wash }, { backgroundColor: wash }]+ : [+ { backgroundColor: wash },+ // Hold long enough to be seen, then fade.+ { backgroundColor: wash, offset: 0.2, easing: "ease-in-out" },+ { backgroundColor: "transparent" },+ ],+ { duration: ARRIVAL_MS, delay: -elapsed }+ );+ return () => animation.cancel();+ }, [ref, arrivedAt]);+}