Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): use native paging and compact message grouping (#892)

Gener6e8f40e91a08
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index 58b88929a..ebfab5576 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -134,6 +134,7 @@ vi.mock("@/contexts/community/current-user", () => ({
}))
vi.mock("@/hooks/community/use-servers", () => ({
serverProjectedQueryFn: () => vi.fn(),
+ useViewerServerRole: () => undefined,
useServer: (serverId: string | null) => {
mocks.useServer(serverId)
return { server: serverId ? mocks.serverSnapshot.current ?? undefined : undefined }
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index ad3307903..854c3f0e8 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -3069,3 +3069,7 @@ body {
transition: none;
}
}
+
+.markdown-chat .message-markdown-blocks > * {
+ margin-block: 0 !important;
+}
diff --git a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
index 6841a5435..639517cea 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
import React from "react"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render } from "@/test/react-dom-harness"
const {
@@ -9,8 +9,6 @@ const {
auditHook,
profileHook,
fetchNextPage,
- scrollNode,
- bottomAnchor,
sheetProps,
} = vi.hoisted(() => ({
auditState: {
@@ -25,14 +23,16 @@ const {
isLoading: false,
hasNextPage: false,
isFetchingNextPage: false,
+ loadedPageCount: 1,
},
auditHook: vi.fn(),
profileHook: vi.fn(),
fetchNextPage: vi.fn(),
- scrollNode: { scrollHeight: 600, scrollTop: 0, clientHeight: 300 },
- bottomAnchor: { scrollIntoView: vi.fn() },
sheetProps: { current: null as Record<string, unknown> | null },
}))
+let scrollDescriptor: PropertyDescriptor | undefined
+let bodyHeight = 300
+let bodyResizeObservers: Array<{ callback: ResizeObserverCallback; elements: Set<Element> }> = []
vi.mock("@/components/community/shell/community-sheet", () => ({
CommunitySheet: ({
@@ -41,10 +41,9 @@ vi.mock("@/components/community/shell/community-sheet", () => ({
...props
}: React.PropsWithChildren<Record<string, unknown>>) => {
sheetProps.current = props
- if (bodyRef && typeof bodyRef === "object" && "current" in bodyRef) {
- bodyRef.current = scrollNode
- }
- return React.createElement("community-sheet", props, children)
+ return React.createElement("community-sheet", props,
+ React.createElement("div", { ref: bodyRef as React.Ref<HTMLDivElement>, "data-testid": "activity-body" }, children),
+ )
},
}))
@@ -131,6 +130,51 @@ function updateModal(renderer: ReturnType<typeof render>, {
onOpenChangeComplete,
}),
))
+ act(() => vi.advanceTimersByTime(500))
+}
+
+function scrollBody(renderer: ReturnType<typeof render>, offset: number) {
+ const root = renderer.getByTestId("activity-body")
+ fireEvent.wheel(root, { deltaY: offset < root.scrollTop ? -20 : 20 })
+ act(() => root.scrollTo({ top: offset }))
+ act(() => vi.advanceTimersByTime(500))
+ return root
+}
+
+function eventTop(renderer: ReturnType<typeof render>, id: string) {
+ return renderer.container.querySelector<HTMLElement>(`[data-activity-event-id="${id}"]`)!.getBoundingClientRect().top
+}
+
+function events(count: number, day = "2026-08-27") {
+ const start = Date.parse(`${day}T12:00:00.000Z`)
+ return Array.from({ length: count }, (_, index) => event(`event-${index}`, new Date(start + index * 60_000).toISOString()))
+}
+
+function prepareOlderPage() {
+ const initialPage = { events: [...auditState.events] }
+ let finish!: (result: unknown) => void
+ fetchNextPage.mockImplementationOnce(() => new Promise(resolvePage => { finish = resolvePage }))
+ return async (pageEvents: ReturnType<typeof events>, failed = false) => {
+ auditState.loadedPageCount = failed ? 1 : 2
+ await act(async () => {
+ finish({ isError: failed, data: { pages: failed ? [initialPage] : [initialPage, { events: pageEvents }] } })
+ })
+ act(() => vi.advanceTimersByTime(500))
+ }
+}
+
+function resizeBody(height: number) {
+ bodyHeight = height
+ act(() => {
+ for (const observer of bodyResizeObservers) {
+ const entries = [...observer.elements].filter(element => element.isConnected).map(target => ({
+ target,
+ borderBoxSize: [{ blockSize: (target as HTMLElement).offsetHeight, inlineSize: 672 }],
+ } as unknown as ResizeObserverEntry))
+ if (entries.length) observer.callback(entries, {} as ResizeObserver)
+ }
+ vi.advanceTimersByTime(500)
+ })
}
describe("BotActivityModal CommunitySheet contract", () => {
@@ -139,22 +183,55 @@ describe("BotActivityModal CommunitySheet contract", () => {
auditState.isLoading = false
auditState.hasNextPage = false
auditState.isFetchingNextPage = false
+ auditState.loadedPageCount = 1
auditHook.mockReset()
profileHook.mockReset()
fetchNextPage.mockReset()
- bottomAnchor.scrollIntoView.mockReset()
+ fetchNextPage.mockResolvedValue({ isError: false, data: { pages: [{ events: [] }] } })
sheetProps.current = null
- Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
- configurable: true,
- value: bottomAnchor.scrollIntoView,
+ bodyHeight = 300
+ bodyResizeObservers = []
+ vi.useFakeTimers()
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 16))
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => window.clearTimeout(id))
+ vi.stubGlobal("ResizeObserver", class {
+ private record: typeof bodyResizeObservers[number]
+ constructor(callback: ResizeObserverCallback) {
+ this.record = { callback, elements: new Set() }
+ bodyResizeObservers.push(this.record)
+ }
+ observe(element: Element) { this.record.elements.add(element) }
+ unobserve(element: Element) { this.record.elements.delete(element) }
+ disconnect() { this.record.elements.clear() }
+ })
+ const isRoot = (node: HTMLElement) => node.dataset.testid === "activity-body"
+ const rowHeight = (node: HTMLElement) => node.closest<HTMLElement>("[data-activity-row-key]")?.dataset.activityRowKey?.includes(":date:") ? 24 : 44
+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockImplementation(function (this: HTMLElement) { return isRoot(this) ? bodyHeight : rowHeight(this) })
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) { return this.clientHeight })
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockImplementation(() => 672)
+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => 672)
+ vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(function (this: HTMLElement) {
+ return isRoot(this) ? Math.max(bodyHeight, Number.parseFloat(this.firstElementChild?.getAttribute("style")?.match(/height: ([\d.]+)px/)?.[1] ?? "0")) : rowHeight(this)
})
- scrollNode.scrollHeight = 600
- scrollNode.scrollTop = 0
- scrollNode.clientHeight = 300
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
- callback(0)
- return 1
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ const row = this.closest<HTMLElement>("[data-activity-row-key]")
+ const root = this.closest<HTMLElement>('[data-testid="activity-body"]')
+ const start = Number.parseFloat(row?.style.transform.match(/translateY\((-?[\d.]+)px\)/)?.[1] ?? "0")
+ return DOMRect.fromRect({ width: 672, height: this.clientHeight, y: isRoot(this) ? 0 : start - (root?.scrollTop ?? 0) })
})
+ scrollDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollTo")
+ Object.defineProperty(HTMLElement.prototype, "scrollTo", { configurable: true, value: function (this: HTMLElement, options: ScrollToOptions | number) {
+ if (typeof options === "number") return
+ this.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.scrollHeight - this.clientHeight))
+ this.dispatchEvent(new Event("scroll"))
+ } })
+ })
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ if (scrollDescriptor) Object.defineProperty(HTMLElement.prototype, "scrollTo", scrollDescriptor)
+ else Reflect.deleteProperty(HTMLElement.prototype, "scrollTo")
})
it("uses the resizable 672px shared shell and its one dismissal callback", () => {
@@ -237,52 +314,202 @@ describe("BotActivityModal CommunitySheet contract", () => {
event("old", "2026-08-26T12:00:00.000Z"),
]
const populated = renderModal().renderer
- expect(populated.container.querySelectorAll("section")).toHaveLength(2)
+ expect(populated.container.querySelectorAll('[data-activity-row-key*="date:"]')).toHaveLength(2)
expect([...populated.container.querySelectorAll("activity-row")]
.map((row) => row.getAttribute("data-event-id")))
.toEqual(["old", "new"])
})
- it("preserves the visible row when an older page prepends", () => {
- auditState.events = [event("new", "2026-08-27T12:00:00.000Z")]
+ it.each([0, 50, 100])("preserves the visible event at offset %i when a same-day older page prepends", async offset => {
+ auditState.events = events(30)
auditState.hasNextPage = true
const { renderer, onOpenChange } = renderModal()
-
- scrollNode.scrollHeight = 600
- scrollNode.scrollTop = 120
+ const root = scrollBody(renderer, offset)
+ const id = offset < 100 ? "event-0" : "event-1"
+ const top = eventTop(renderer, id)
+ const completePage = prepareOlderPage()
fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
expect(fetchNextPage).toHaveBeenCalledOnce()
-
+ auditState.isFetchingNextPage = true
+ updateModal(renderer, { onOpenChange })
auditState.events = [
- event("new", "2026-08-27T12:00:00.000Z"),
- event("old", "2026-08-26T12:00:00.000Z"),
+ ...auditState.events,
+ event("old", "2026-08-27T11:00:00.000Z"),
]
- scrollNode.scrollHeight = 850
+ auditState.isFetchingNextPage = false
updateModal(renderer, { onOpenChange })
- expect(scrollNode.scrollTop).toBe(370)
+ await completePage([event("old", "2026-08-27T11:00:00.000Z")])
+ expect(eventTop(renderer, id)).toBe(top)
+ expect(root.scrollTop).toBe(offset + 44)
})
it("pins a new live row only while the reader is near the tail", () => {
- auditState.events = [event("one", "2026-08-27T12:00:00.000Z")]
+ auditState.events = events(30)
const { renderer, onOpenChange } = renderModal()
-
- scrollNode.scrollHeight = 1_100
- scrollNode.scrollTop = 800
- scrollNode.clientHeight = 250
+ const root = scrollBody(renderer, 10_000)
+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)
auditState.events = [
- event("one", "2026-08-27T12:00:00.000Z"),
- event("two", "2026-08-27T12:01:00.000Z"),
+ ...auditState.events,
+ event("two", "2026-08-27T13:01:00.000Z"),
]
updateModal(renderer, { onOpenChange })
- expect(scrollNode.scrollTop).toBe(1_100)
-
- scrollNode.scrollHeight = 1_300
- scrollNode.scrollTop = 100
+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)
+ scrollBody(renderer, 100)
auditState.events = [
...auditState.events,
event("three", "2026-08-27T12:02:00.000Z"),
]
updateModal(renderer, { onOpenChange })
- expect(scrollNode.scrollTop).toBe(100)
+ expect(root.scrollTop).toBe(100)
+ })
+
+ it("windows a long log and reopens at its actual latest event", () => {
+ auditState.events = events(120)
+ const { renderer } = renderModal()
+ act(() => vi.advanceTimersByTime(500))
+ const root = renderer.getByTestId("activity-body")
+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)
+ expect(renderer.container.querySelectorAll("activity-row").length).toBeLessThan(30)
+ expect(renderer.container.querySelector('[data-event-id="event-119"]')).toBeInTheDocument()
+ expect(renderer.container.querySelector('[data-event-id="event-0"]')).toBeNull()
+ scrollBody(renderer, 100)
+ updateModal(renderer, { open: false })
+ updateModal(renderer, { open: true })
+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)
+ expect(renderer.container.querySelector('[data-event-id="event-119"]')).toBeInTheDocument()
+ })
+
+ it("opens at the latest event after the body changes from zero to positive height", () => {
+ auditState.events = events(120)
+ bodyHeight = 0
+ const { renderer } = renderModal()
+ const root = renderer.getByTestId("activity-body")
+ act(() => vi.advanceTimersByTime(500))
+ expect(root.scrollTop).toBe(0)
+ resizeBody(300)
+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)
+ expect(renderer.container.querySelector('[data-event-id="event-119"]')).toBeInTheDocument()
+ })
+
+ it("does not restore a completed request from before the modal reopened", async () => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ const completePage = prepareOlderPage()
+ const { renderer } = renderModal()
+ scrollBody(renderer, 0)
+ fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
+ auditState.isFetchingNextPage = true
+ updateModal(renderer)
+ updateModal(renderer, { open: false })
+ updateModal(renderer, { open: true })
+ scrollBody(renderer, 600)
+ const top = eventTop(renderer, "event-15")
+ auditState.events = [...auditState.events, event("old", "2026-08-27T11:00:00.000Z")]
+ auditState.isFetchingNextPage = false
+ updateModal(renderer)
+ await completePage([event("old", "2026-08-27T11:00:00.000Z")])
+ expect(eventTop(renderer, "event-15")).toBe(top)
+ })
+
+ it.each([0, 50, 150])("keeps the event at offset %i when an older day and its divider prepend", async offset => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ const { renderer } = renderModal()
+ scrollBody(renderer, offset)
+ const id = offset < 100 ? "event-0" : "event-2"
+ const top = eventTop(renderer, id)
+ const completePage = prepareOlderPage()
+ fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
+ auditState.isFetchingNextPage = true
+ updateModal(renderer)
+ auditState.events = [...auditState.events, event("previous-day", "2026-08-26T12:00:00.000Z")]
+ auditState.isFetchingNextPage = false
+ updateModal(renderer)
+ await completePage([event("previous-day", "2026-08-26T12:00:00.000Z")])
+ expect(eventTop(renderer, id)).toBe(top)
+ })
+
+ it("keeps a reader's event when a late live event inserts in the middle", () => {
+ auditState.events = events(30)
+ const { renderer } = renderModal()
+ scrollBody(renderer, 600)
+ const top = eventTop(renderer, "event-15")
+ auditState.events = [...auditState.events, event("late", "2026-08-27T12:01:30.000Z")]
+ updateModal(renderer)
+ expect(eventTop(renderer, "event-15")).toBe(top)
+ expect(renderer.container.querySelector('[data-event-id="event-29"]')).toBeNull()
+ })
+
+ it("does not restore an old page anchor after the reader takes over", async () => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ const { renderer } = renderModal()
+ scrollBody(renderer, 0)
+ const completePage = prepareOlderPage()
+ fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
+ auditState.isFetchingNextPage = true
+ updateModal(renderer)
+ scrollBody(renderer, 600)
+ const top = eventTop(renderer, "event-15")
+ auditState.events = [...auditState.events, event("old", "2026-08-27T11:00:00.000Z")]
+ auditState.isFetchingNextPage = false
+ updateModal(renderer)
+ await completePage([event("old", "2026-08-27T11:00:00.000Z")])
+ expect(eventTop(renderer, "event-15")).toBe(top)
+ })
+
+ it("retires a zero-row older response before a later live event", async () => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ fetchNextPage.mockResolvedValue({ isError: false, data: { pages: [{ events: auditState.events }, { events: [] }] } })
+ const { renderer } = renderModal()
+ const root = scrollBody(renderer, 0)
+ await act(async () => { fireEvent.click(renderer.getByRole("button", { name: "Load older" })) })
+ auditState.events = [...auditState.events, event("late-earlier", "2026-08-27T11:00:00.000Z")]
+ updateModal(renderer)
+ expect(root.scrollTop).toBe(0)
+ })
+
+ it.each([
+ { offset: 0, liveAt: "2026-08-27T11:00:00.000Z", pageAt: "2026-08-27T10:00:00.000Z" },
+ { offset: 50, liveAt: "2026-08-26T12:00:00.000Z", pageAt: "2026-08-27T11:00:00.000Z" },
+ ])("keeps the header-fold anchor at $offset until its older request completes after an earlier live event", async ({ offset, liveAt, pageAt }) => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ const completePage = prepareOlderPage()
+ const { renderer } = renderModal()
+ const root = scrollBody(renderer, offset)
+ const top = eventTop(renderer, "event-0")
+ fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
+ auditState.isFetchingNextPage = true
+ updateModal(renderer)
+ auditState.events = [...auditState.events, event("earlier-live", liveAt)]
+ updateModal(renderer)
+ auditState.events = [...auditState.events, event("older-page", pageAt)]
+ auditState.isFetchingNextPage = false
+ updateModal(renderer)
+ await completePage([event("older-page", pageAt)])
+ expect(eventTop(renderer, "event-0")).toBe(top)
+ expect(fetchNextPage).toHaveBeenCalledOnce()
+ })
+
+ it.each([false, true])("retires a completed older request without new rows after an earlier live event (failed: %s)", async failed => {
+ auditState.events = events(30)
+ auditState.hasNextPage = true
+ const completePage = prepareOlderPage()
+ const { renderer } = renderModal()
+ const root = scrollBody(renderer, 0)
+ fireEvent.click(renderer.getByRole("button", { name: "Load older" }))
+ auditState.isFetchingNextPage = true
+ updateModal(renderer)
+ auditState.events = [...auditState.events, event("earlier-live", "2026-08-27T11:00:00.000Z")]
+ updateModal(renderer)
+ auditState.isFetchingNextPage = false
+ updateModal(renderer)
+ await completePage([], failed)
+ expect(root.scrollTop).toBe(0)
+ auditState.events = [...auditState.events, event("later-live", "2026-08-27T10:00:00.000Z")]
+ updateModal(renderer)
+ expect(root.scrollTop).toBe(0)
})
})
diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsx
index 955ec58e9..452fe0436 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.tsx
+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx
@@ -1,6 +1,8 @@
"use client"
-import { useLayoutEffect, useMemo, useRef, useEffect } from "react"
+import { useCallback, useLayoutEffect, useMemo, useRef, useEffect } from "react"
+import { useAtom, useCreateAtom } from "@tanstack/react-store"
+import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"
import { AgentAvatar } from "@/components/avatar"
import { CommunitySheet } from "@/components/community/shell/community-sheet"
import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
@@ -51,6 +53,7 @@ export function BotActivityModal({
fetchNextPage,
hasNextPage,
isFetchingNextPage,
+ loadedPageCount,
} = useBotAuditLog(bot?.id ?? null)
// Merged stream = paginated GET (DESC) + live WS ring (arrival-ordered).
@@ -66,94 +69,134 @@ export function BotActivityModal({
})
}, [events])
- // Chronologically-adjacent rows are grouped under a shared day header,
- // rendered when the day boundary changes. Cheap to compute at the render
- // scale we operate at (500-row cap per bot).
- const grouped = useMemo(() => groupByDay(chronological), [chronological])
-
- const scrollRef = useRef<HTMLDivElement | null>(null)
- const bottomAnchorRef = useRef<HTMLDivElement | null>(null)
- const lastCountRef = useRef(0)
- const pendingOlderAnchorRef = useRef<number | null>(null)
+ const rows = useMemo(() => flattenActivityRows(chronological, bot?.id ?? ""), [chronological, bot?.id])
+ const [scrollRoot, setScrollRoot] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
+ const stickyIndexes = useMemo(() => rows.flatMap((row, index) => row.kind === "date" ? [index] : []), [rows])
+ const activeStickyIndexRef = useRef<number | null>(null)
+ const [pendingOlderAnchor, setPendingOlderAnchor] = useAtom(useCreateAtom<{
+ key: string
+ viewportOffset: number
+ pageCount: number
+ receivedOlderRows: boolean
+ settled: boolean
+ } | null>(null))
+ const scrollPaddingStartRef = useRef(0)
+ const ownsIndexRef = useRef(false)
+ const previousTailKeyRef = useRef<string | null>(null)
const didInitialTailScrollRef = useRef(false)
+ useLayoutEffect(() => {
+ setPendingOlderAnchor(null)
+ scrollPaddingStartRef.current = 0
+ ownsIndexRef.current = false
+ previousTailKeyRef.current = null
+ didInitialTailScrollRef.current = false
+ }, [open, bot?.id, scrollRoot, setPendingOlderAnchor])
- const onLoadOlder = () => {
- if (!hasNextPage || isFetchingNextPage) return
- const el = scrollRef.current
- if (el) pendingOlderAnchorRef.current = el.scrollHeight
- void fetchNextPage()
- }
+ const getItemKey = useCallback((index: number) => rows[index].key, [rows])
+ const estimateSize = useCallback((index: number) => rows[index].kind === "date" ? 24 : 44, [rows])
+ const rangeExtractor = useCallback((range: Range) => {
+ const active = [...stickyIndexes].reverse().find((index) => index <= range.startIndex) ?? null
+ activeStickyIndexRef.current = active
+ return [...new Set([
+ ...(active === null ? [] : [active]),
+ ...defaultRangeExtractor(range),
+ ])].sort((a, b) => a - b)
+ }, [stickyIndexes])
+ // eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ getScrollElement: () => scrollRoot,
+ getItemKey,
+ estimateSize,
+ rangeExtractor,
+ anchorTo: "end",
+ followOnAppend: open && didInitialTailScrollRef.current && !isFetchingNextPage && !pendingOlderAnchor,
+ scrollEndThreshold: 80,
+ scrollPaddingStart: scrollPaddingStartRef.current,
+ paddingEnd: 12,
+ overscan: 8,
+ enabled: scrollRoot !== null,
+ useFlushSync: false,
+ })
- // Reset the once-per-open latch when the modal closes or the target bot
- // changes, so the next open lands on the newest event again.
- useEffect(() => {
- if (!open) {
- lastCountRef.current = 0
- pendingOlderAnchorRef.current = null
- didInitialTailScrollRef.current = false
+ useLayoutEffect(() => {
+ if (!open || !scrollRoot || chronological.length === 0) return
+ if (!didInitialTailScrollRef.current && scrollRoot.clientHeight > 0
+ && scrollRoot.querySelector("[data-activity-event-id]")) {
+ didInitialTailScrollRef.current = true
+ ownsIndexRef.current = true
+ virtualizer.scrollToEnd()
}
- }, [open, bot?.id])
+ const tailKey = rows.at(-1)?.key ?? null
+ if (previousTailKeyRef.current && tailKey !== previousTailKeyRef.current
+ && virtualizer.options.followOnAppend && virtualizer.isAtEnd(80)) ownsIndexRef.current = true
+ previousTailKeyRef.current = tailKey
+ const pending = pendingOlderAnchor
+ if (!pending || !pending.settled || isFetchingNextPage) return
+ setPendingOlderAnchor(null)
+ if (pending.receivedOlderRows) {
+ const index = rows.findIndex((row) => row.key === pending.key)
+ if (index >= 0) {
+ scrollPaddingStartRef.current = pending.viewportOffset
+ virtualizer.setOptions({ ...virtualizer.options, scrollPaddingStart: pending.viewportOffset })
+ ownsIndexRef.current = true
+ virtualizer.scrollToIndex(index, { align: "start" })
+ }
+ }
+ })
- // Snap to the newest event on first paint of an open cycle. CommunitySheet
- // mounts its content inside a portal with an entrance animation, so relying
- // on a `useLayoutEffect` that only fires when
- // `chronological.length` changes can race the portal's first layout — the
- // scroll fires before the container has its final height. Anchor + rAF
- // guarantees the browser has laid out at least once before we jump.
useEffect(() => {
- if (!open) return
- if (didInitialTailScrollRef.current) return
- if (chronological.length === 0) return
- const anchor = bottomAnchorRef.current
- const el = scrollRef.current
- if (!anchor || !el) return
- didInitialTailScrollRef.current = true
- lastCountRef.current = chronological.length
- // Two rAFs: one to let the portal layout settle, one to jump after the
- // rows are actually painted. `scrollIntoView({ block: 'end' })` is
- // instant (no smooth-scroll) so the reader doesn't see it move.
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- anchor.scrollIntoView({ block: "end" })
- // Belt-and-braces: if the anchor was already in view before jumping,
- // browsers sometimes no-op scrollIntoView — pin scrollTop explicitly.
- el.scrollTop = el.scrollHeight
- })
- })
- }, [open, chronological.length])
-
- // After the initial tail scroll, handle two ongoing cases:
- // 1. `pendingOlderAnchorRef` set — Load older prepended rows; preserve
- // the reader's visible offset by shifting scrollTop by the height delta.
- // 2. A new live event arrived and the reader was already near the tail —
- // keep the tail pinned so streaming rows stay visible.
- useLayoutEffect(() => {
- const el = scrollRef.current
- if (!el) return
- const prevCount = lastCountRef.current
- const nextCount = chronological.length
- lastCountRef.current = nextCount
- if (nextCount === 0) return
+ if (!scrollRoot || !open) return
+ const cancel = () => {
+ setPendingOlderAnchor(null)
+ scrollPaddingStartRef.current = 0
+ if (ownsIndexRef.current) virtualizer.scrollToOffset(scrollRoot.scrollTop)
+ ownsIndexRef.current = false
+ didInitialTailScrollRef.current = true
+ }
+ const wheel = (event: WheelEvent) => { if (event.deltaY !== 0) cancel() }
+ const key = (event: KeyboardEvent) => {
+ if (["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)) cancel()
+ }
+ scrollRoot.addEventListener("wheel", wheel, { passive: true })
+ scrollRoot.addEventListener("touchstart", cancel, { passive: true })
+ scrollRoot.addEventListener("pointerdown", cancel)
+ scrollRoot.addEventListener("keydown", key)
+ return () => {
+ scrollRoot.removeEventListener("wheel", wheel)
+ scrollRoot.removeEventListener("touchstart", cancel)
+ scrollRoot.removeEventListener("pointerdown", cancel)
+ scrollRoot.removeEventListener("keydown", key)
+ }
+ }, [open, scrollRoot, setPendingOlderAnchor, virtualizer])
- if (pendingOlderAnchorRef.current !== null) {
- // Only consume the anchor when rows were actually prepended. An older-page
- // fetch that settles with zero new rows leaves the pending anchor stale;
- // applying its `delta` on a later live-event render would yank the reader
- // to a scrollTop derived from an unrelated prior scrollHeight.
- if (nextCount > prevCount) {
- const delta = el.scrollHeight - pendingOlderAnchorRef.current
- el.scrollTop = el.scrollTop + delta
+ const onLoadOlder = () => {
+ if (!hasNextPage || isFetchingNextPage) return
+ const offset = virtualizer.scrollOffset ?? 0
+ const fold = virtualizer.getVirtualItemForOffset(offset)
+ let pending: typeof pendingOlderAnchor = null
+ if (fold && rows[fold.index]?.kind !== "event") {
+ const event = virtualizer.getVirtualItems().find((item) => rows[item.index]?.kind === "event" && item.end > offset)
+ if (event) pending = {
+ key: String(event.key),
+ viewportOffset: event.start - offset,
+ pageCount: loadedPageCount,
+ receivedOlderRows: false,
+ settled: false,
}
- pendingOlderAnchorRef.current = null
- return
}
-
- if (!didInitialTailScrollRef.current) return
- const nearTail = el.scrollHeight - (el.scrollTop + el.clientHeight) < 80
- if (nextCount > prevCount && nearTail) {
- el.scrollTop = el.scrollHeight
+ setPendingOlderAnchor(pending)
+ const settle = (result: Awaited<ReturnType<typeof fetchNextPage>> | null) => {
+ if (!pending) return
+ setPendingOlderAnchor(current => current === pending ? {
+ ...current,
+ settled: true,
+ receivedOlderRows: Boolean(result && !result.isError
+ && result.data?.pages.slice(current.pageCount).some(page => page.events.length > 0)),
+ } : current)
}
- }, [chronological.length])
+ void fetchNextPage().then(settle, () => settle(null))
+ }
return (
<CommunitySheet
@@ -181,7 +224,7 @@ export function BotActivityModal({
desktopWidth={672}
resizable
contentTestId={tid.botActivityModal}
- bodyRef={scrollRef}
+ bodyRef={setScrollRoot}
bodyClassName="bg-background p-0"
>
{isLoading && chronological.length === 0 ? (
@@ -189,32 +232,45 @@ export function BotActivityModal({
) : chronological.length === 0 ? (
<EmptyState />
) : (
- <div className="pb-3">
- {hasNextPage ? (
- <div className="flex justify-center py-2">
- <button
- type="button"
- onClick={onLoadOlder}
- disabled={isFetchingNextPage}
- className="min-h-11 rounded-md px-3 py-1 font-mono text-[10px] uppercase tracking-wider text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-8"
+ <div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const row = rows[virtualRow.index]
+ const sticky = row.kind === "date" && virtualRow.index === activeStickyIndexRef.current
+ return (
+ <div
+ key={virtualRow.key}
+ ref={virtualizer.measureElement}
+ data-index={virtualRow.index}
+ data-activity-row-key={row.key}
+ data-activity-event-id={row.kind === "event" ? row.event.id : undefined}
+ style={{
+ position: sticky ? "sticky" : "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ zIndex: row.kind === "date" ? 10 : undefined,
+ transform: sticky ? undefined : `translateY(${virtualRow.start}px)`,
+ }}
>
- {isFetchingNextPage ? "Loading older" : "Load older"}
- </button>
- </div>
- ) : (
- <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">
- Beginning of log
- </div>
- )}
- {grouped.map((group) => (
- <section key={group.dayKey}>
- <DayDivider label={group.label} />
- {group.events.map((event) => (
- <BotActivityRow key={event.id} event={event} />
- ))}
- </section>
- ))}
- <div ref={bottomAnchorRef} aria-hidden />
+ {row.kind === "event" ? <BotActivityRow event={row.event} /> : row.kind === "date" ? <DayDivider label={row.label} /> : hasNextPage ? (
+ <div className="flex justify-center py-2">
+ <button
+ type="button"
+ onClick={onLoadOlder}
+ disabled={isFetchingNextPage}
+ className="min-h-11 rounded-md px-3 py-1 font-mono text-[10px] uppercase tracking-wider text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60 sm:min-h-8"
+ >
+ {isFetchingNextPage ? "Loading older" : "Load older"}
+ </button>
+ </div>
+ ) : (
+ <div className="py-2 text-center font-mono text-[10px] uppercase tracking-wider text-muted-foreground/40">
+ Beginning of log
+ </div>
+ )}
+ </div>
+ )
+ })}
</div>
)}
</CommunitySheet>
@@ -223,7 +279,7 @@ export function BotActivityModal({
function DayDivider({ label }: { label: string }) {
return (
- <div className="sticky top-0 z-10 border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-backdrop-filter:bg-background/80">
+ <div className="border-b border-border/40 bg-background/95 px-4 py-1 backdrop-blur supports-backdrop-filter:bg-background/80">
<span className="font-mono text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
{label}
</span>
@@ -259,20 +315,24 @@ function EmptyState() {
)
}
-type DayGroup = { dayKey: string; label: string; events: AuditEvent[] }
+type ActivityRow =
+ | { kind: "control"; key: string }
+ | { kind: "date"; key: string; label: string }
+ | { kind: "event"; key: string; event: AuditEvent }
-function groupByDay(events: AuditEvent[]): DayGroup[] {
- const groups: DayGroup[] = []
+function flattenActivityRows(events: AuditEvent[], botId: string): ActivityRow[] {
+ if (events.length === 0) return []
+ const rows: ActivityRow[] = [{ kind: "control", key: `${botId}:control` }]
+ let previousDay: string | undefined
for (const event of events) {
const key = dayKey(event.createdAt)
- const tail = groups[groups.length - 1]
- if (tail && tail.dayKey === key) {
- tail.events.push(event)
- } else {
- groups.push({ dayKey: key, label: formatDayLabel(event.createdAt), events: [event] })
+ if (key !== previousDay) {
+ rows.push({ kind: "date", key: `${botId}:date:${key}`, label: formatDayLabel(event.createdAt) })
+ previousDay = key
}
+ rows.push({ kind: "event", key: `${botId}:event:${event.id}`, event })
}
- return groups
+ return rows
}
function dayKey(iso: string): string {
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 2ed8729f0..d919894cd 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -497,6 +497,7 @@ export function DmView({ dmId }: { dmId: string }) {
// `anchorInCache`'s doc comment above.
initialScrollReady={!readSnapshotFetching && anchorInCache}
hasMore={hasMoreMessages}
+ isFetching={messagesFetching}
isFetchingOlder={isFetchingOlderMessages}
onLoadOlder={fetchOlderMessages}
hasMoreNewer={hasMoreNewerMessages}
diff --git a/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts
new file mode 100644
index 000000000..dfdb60bd8
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts
@@ -0,0 +1,86 @@
+import React from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, render, screen, waitFor } from "@/test/react-dom-harness"
+import type { ForumThread } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
+import { ForumSurface } from "./forum-surface"
+
+const mocks = vi.hoisted(() => ({ readPage: vi.fn() }))
+const post: ForumThread = {
+ id: "existing-post", name: "Existing post", messageCount: 1,
+ lastMessageAt: "2026-10-09T00:00:00.000Z",
+ parent: { authorName: "Alice", text: "Body" }, authorId: "alice", authorAvatar: "A",
+ openerMessageId: "opener", tags: [], preview: "Body", participants: [], participantCount: 1,
+}
+const page = { posts: [post], hasMore: true, nextCursor: "older" }
+const queryKey = ["forum-pagination-error"]
+
+vi.mock("@/hooks/community/use-forum-feed", async () => {
+ const { useInfiniteQuery } = await import("@tanstack/react-query")
+ return { useForumFeed: () => {
+ const query = useInfiniteQuery({
+ queryKey, queryFn: mocks.readPage, initialPageParam: null as string | null,
+ initialData: { pages: [page], pageParams: [null] },
+ getNextPageParam: (lastPage: typeof page) => lastPage.hasMore ? lastPage.nextCursor : undefined,
+ staleTime: Infinity, retry: 1, retryDelay: 0,
+ })
+ return {
+ ...query, posts: query.data.pages.flatMap(value => value.posts), tag: "All",
+ availableTags: [], selectTag: vi.fn(), hasMoreOlder: query.hasNextPage,
+ isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() },
+ }
+ } }
+})
+vi.mock("@/hooks/community/use-channel-read-state", () => ({
+ useChannelReadStateSnapshot: () => ({ snapshot: { lastReadSeq: 0 }, isFetching: false, error: null, retrying: false }),
+}))
+vi.mock("@/hooks/community/use-read-observer", () => ({ useTimelineReadObserver: vi.fn() }))
+vi.mock("@/lib/community-db/projections", async (load) => ({
+ ...await load<typeof import("@/lib/community-db/projections")>(),
+ useCanonicalProfilesByUserId: () => new Map(),
+}))
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: ({ count, getItemKey }: { count: number; getItemKey: (index: number) => string | number }) => ({
+ options: { scrollMargin: 0 }, scrollToIndex: vi.fn(), getTotalSize: () => count * 160,
+ getVirtualItems: () => Array.from({ length: count }, (_, index) => ({
+ key: getItemKey(index), index, start: index * 160, end: (index + 1) * 160, size: 160, lane: 0,
+ })), measureElement: vi.fn(),
+ }),
+}))
+
+describe("ForumSurface retained posts pagination", () => {
+ afterEach(() => { mocks.readPage.mockReset() })
+
+ it("keeps posts and stops at the boundary after native Query retries fail, then accepts recovery", async () => {
+ mocks.readPage.mockRejectedValueOnce(new Error("offline"))
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockImplementation(() => new Promise(() => {}))
+ const client = new QueryClient()
+ let failedCycle = false
+ const unsubscribe = client.getQueryCache().subscribe(event => {
+ if (event.query.state.status === "error" && event.query.state.fetchStatus === "idle") failedCycle = true
+ })
+ const tree = () => React.createElement(QueryClientProvider, { client },
+ React.createElement(ForumSurface, { serverId: "server", forumChannelId: "forum", members: [], onOpenPost: vi.fn() }))
+ const view = render(tree())
+ try {
+ await waitFor(() => expect(failedCycle).toBe(true))
+ view.rerender(tree())
+ expect(screen.getByTestId(tid.forumThreadTitleText(post.id))).toHaveTextContent("Existing post")
+ expect(screen.queryByRole("alert")).toBeNull()
+ expect(mocks.readPage).toHaveBeenCalledTimes(2)
+ expect(client.getQueryState(queryKey)).toEqual(expect.objectContaining({ status: "error", fetchStatus: "idle" }))
+
+ mocks.readPage.mockResolvedValueOnce({ ...page, hasMore: false })
+ await act(async () => { await client.refetchQueries({ queryKey, exact: true }) })
+ expect(mocks.readPage).toHaveBeenCalledTimes(3)
+ expect(client.getQueryState(queryKey)).toEqual(expect.objectContaining({ status: "success", fetchStatus: "idle" }))
+ expect(screen.getByTestId(tid.forumThreadTitleText(post.id))).toHaveTextContent("Existing post")
+ } finally {
+ view.unmount()
+ unsubscribe()
+ client.clear()
+ }
+ })
+})
diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsx
index cde30c12f..87559a5f9 100644
--- a/src/web/src/components/community/channels/forum-surface.tsx
+++ b/src/web/src/components/community/channels/forum-surface.tsx
@@ -93,6 +93,8 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {
onTagChange={feed.selectTag}
hasMore={feed.hasMoreOlder}
loadingMore={feed.isFetchingOlder}
+ isFetching={feed.isFetching}
+ isError={feed.isError}
onLoadMore={feed.fetchOlder}
onScrollRoot={setScrollRootEl}
onEditPostTags={(threadId, tags) => {
diff --git a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
index d96c5bb92..081d5144f 100644
--- a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
@@ -7,19 +7,18 @@ const scrollToIndex = vi.fn()
let requestOlder: (() => void) | undefined
let sentinelEdge: string | undefined
vi.mock("@tanstack/react-virtual", () => ({
- useVirtualizer: ({ count }: { count: number }) => ({
+ useVirtualizer: ({ count, getItemKey }: { count: number; getItemKey: (index: number) => string | number }) => ({
options: { scrollMargin: 0 },
scrollToIndex,
getTotalSize: () => count * 160,
- getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 160 })),
+ getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ key: getItemKey(index), index, start: index * 160 })),
measureElement: () => {},
}),
}))
-vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({
- useVirtualCursorSentinel: ({ onLoad, edge }: { onLoad?: () => void; edge: string }) => {
+vi.mock("@/hooks/community/use-virtual-cursor-pagination", () => ({
+ useVirtualCursorPagination: ({ onLoad, edge }: { onLoad?: () => void; edge: string }) => {
requestOlder = onLoad
sentinelEdge = edge
- return () => {}
},
}))
@@ -96,7 +95,7 @@ describe("ForumView scroll anchoring", () => {
expect(scrollToIndex).toHaveBeenCalledWith(0, { align: "start" })
})
- it("loads older feed pages from the bottom sentinel without scroll-height compensation", async () => {
+ it("loads older feed pages from the native bottom range without scroll-height compensation", async () => {
const onLoadMore = vi.fn()
const view = render(createElement(ForumView, { ...props([post("p3"), post("p2")]), onLoadMore }))
act(() => requestOlder?.())
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index da226e345..c589f913d 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -22,7 +22,7 @@ import { tid } from "@/lib/community/testids"
import type { ForumThread } from "@/lib/community/models/message"
import type { Member } from "@/lib/community/models/people"
import { VirtualRows } from "../messages/virtual-cursor-list"
-import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"
+import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"
import { cn } from "@/lib/utils"
import { FORUM_ARCHIVE_TAG } from "@alook/shared"
@@ -190,7 +190,7 @@ export function ForumView({
members,
mentionCandidates,
posts, loading, tag, availableTags = [], onTagChange, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,
- hasMore, loadingMore, onLoadMore,
+ hasMore, loadingMore, isFetching, isError, onLoadMore,
onDeletePost, canDeletePost, deletingPost,
onScrollRoot,
}: {
@@ -204,6 +204,8 @@ export function ForumView({
onTagChange: (tag: string) => void
hasMore?: boolean
loadingMore?: boolean
+ isFetching?: boolean
+ isError?: boolean
onLoadMore?: () => void
onOpenPost: (id: string) => void
// Async — page owns the mutation + `enterThread` navigation and either
@@ -236,13 +238,15 @@ export function ForumView({
onScrollRoot?.(node)
}, [onScrollRoot])
const alignedTagRef = useRef<string | null>(null)
+ const getItemKey = useCallback((index: number) => posts[index]?.id ?? index, [posts])
+ const estimateSize = useCallback(() => 128, [])
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
count: posts.length,
getScrollElement: () => scrollRef.current,
- estimateSize: () => 128,
- getItemKey: (index) => posts[index]?.id ?? index,
+ estimateSize,
+ getItemKey,
overscan: 5,
initialRect: { width: 0, height: 800 },
})
@@ -272,10 +276,13 @@ export function ForumView({
alignedTagRef.current = tag
virtualizer.scrollToIndex(0, { align: "start" })
}, [posts.length, tag, virtualizer])
- const olderSentinelRef = useVirtualCursorSentinel({
- scrollRef,
+ useVirtualCursorPagination({
+ virtualizer,
+ count: posts.length,
+ enabled: !loading,
hasMore,
- isFetching: loadingMore,
+ isFetching: isFetching || loadingMore,
+ isError,
onLoad: onLoadMore,
edge: "end",
})
@@ -382,7 +389,6 @@ export function ForumView({
<VirtualRows
items={posts}
virtualizer={virtualizer}
- itemKey={(post) => post.id}
renderItem={(p, index) => {
const canEdit = !!onEditPostTags && (canEditPostTags?.(p) ?? false)
const canDelete = !!onDeletePost && (canDeletePost?.(p) ?? false)
@@ -517,7 +523,6 @@ export function ForumView({
)
}}
/>
- <div ref={olderSentinelRef} className="h-px" aria-hidden />
</>
)}
</div>
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index b67a7bd7e..d7d1236ab 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -158,6 +158,7 @@ export function TextChannelSurface({
initialScrollReady={!feed.readSnapshotFetching && feed.anchorInCache}
onScrollTargetConsumed={controller.consumeScrollTarget}
hasMore={feed.hasMoreOlder}
+ isFetching={feed.isFetching}
isFetchingOlder={feed.isFetchingOlder}
onLoadOlder={feed.fetchOlder}
hasMoreNewer={feed.hasMoreNewer}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 7889b2380..c37c83355 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -267,6 +267,7 @@ export function ThreadChannelSurface({
initialScrollReady={!controller.feed.readSnapshotFetching && controller.feed.anchorInCache}
onScrollTargetConsumed={controller.consumeScrollTarget}
hasMore={controller.feed.hasMoreOlder}
+ isFetching={controller.feed.isFetching}
isFetchingOlder={controller.feed.isFetchingOlder}
onLoadOlder={controller.feed.fetchOlder}
hasMoreNewer={controller.feed.hasMoreNewer}
diff --git a/src/web/src/components/community/dividers.tsx b/src/web/src/components/community/dividers.tsx
index 1b5621ab1..45a66cead 100644
--- a/src/web/src/components/community/dividers.tsx
+++ b/src/web/src/components/community/dividers.tsx
@@ -12,8 +12,6 @@ export function DateDivider({ label }: { label: string }) {
}
export function NewDivider({ dateLabel }: { dateLabel?: string }) {
- // The row's height tracks the separator line only; the "New" pill is taken
- // out of flow so its taller box doesn't push messages apart.
// `data-new-divider` lets `useScrollAnchor`'s mount effect center on this
// element itself via `querySelector`, instead of the whole message row
// (date divider + full message content) that used to be the only
@@ -22,16 +20,18 @@ export function NewDivider({ dateLabel }: { dateLabel?: string }) {
// date label merges onto the same red line (centered) instead of rendering
// a separate date-divider row above it.
return (
- <div data-new-divider data-testid={tid.newDivider} className="relative my-1 flex items-center gap-2">
- <Separator className="flex-1 bg-destructive/60" />
- {dateLabel && (
- <>
- <span className="text-xs font-semibold text-destructive" suppressHydrationWarning>{dateLabel}</span>
- <Separator className="flex-1 bg-destructive/60" />
- </>
- )}
+ <div data-new-divider data-testid={tid.newDivider} className="my-1 grid items-center">
+ <div className="col-start-1 row-start-1 flex items-center gap-2">
+ <Separator className="flex-1 bg-destructive/60" />
+ {dateLabel && (
+ <>
+ <span className="text-xs font-semibold text-destructive" suppressHydrationWarning>{dateLabel}</span>
+ <Separator className="flex-1 bg-destructive/60" />
+ </>
+ )}
+ </div>
<span
- className="pointer-events-none absolute right-0 top-1/2 -translate-y-1/2 rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold text-white"
+ className="pointer-events-none col-start-1 row-start-1 justify-self-end rounded-sm bg-destructive px-1.5 py-0.5 text-xs font-semibold text-white"
style={{ WebkitTextStroke: "0.4px currentColor" }}
>
New
diff --git a/src/web/src/components/community/members/member-list.tsx b/src/web/src/components/community/members/member-list.tsx
index d4f9d2bec..cbf95c404 100644
--- a/src/web/src/components/community/members/member-list.tsx
+++ b/src/web/src/components/community/members/member-list.tsx
@@ -28,6 +28,7 @@ import {
type CommunityRole as Role,
} from "@alook/shared"
import { MemberIdentityRow } from "./member-identity-row"
+import { VirtualRows } from "../messages/virtual-cursor-list"
// The Leave/Remove confirm flow the row menu opens (private channel/post/thread).
type ManageConfirm = { kind: "leave" | "remove"; memberId: string }
@@ -180,6 +181,8 @@ export function MemberList({
const duplicateNames = useMemo(() => computeDuplicateNames(members), [members])
const scrollRef = useRef<HTMLDivElement>(null)
const sentinelRef = useRef<HTMLDivElement>(null)
+ const getItemKey = useCallback((index: number) => items[index]?.key ?? index, [items])
+ const estimateSize = useCallback((index: number) => items[index]?.kind === "header" ? HEADER_HEIGHT : ROW_HEIGHT, [items])
// TanStack Virtual returns unstable function refs — React Compiler skips memoization.
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation
@@ -190,8 +193,8 @@ export function MemberList({
// React also keys these rows by `item.key`. Keep TanStack Virtual on the
// same identity axis so an insert/re-group does not leave a reused DOM
// node registered under its old numeric index in direct-DOM mode.
- getItemKey: (index) => items[index]?.key ?? index,
- estimateSize: (index) => (items[index]?.kind === "header" ? HEADER_HEIGHT : ROW_HEIGHT),
+ getItemKey,
+ estimateSize,
overscan: 8,
})
@@ -290,45 +293,27 @@ export function MemberList({
)}
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto thin-scrollbar">
<div className="px-4 py-4">
- <div
- ref={rowVirtualizer.containerRef}
- style={{ position: "relative", width: "100%" }}
- >
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const item = items[virtualRow.index]
- return (
- <div
- key={item.key}
- role="listitem"
- data-index={virtualRow.index}
- ref={rowVirtualizer.measureElement}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- }}
- >
- {item.kind === "header" ? (
- <h3 className="mb-2 px-1 text-xs font-medium text-muted-foreground">
- {item.label} — {item.count}
- </h3>
- ) : (
- <MemberRow
- mem={item.member}
- canManage={canManage}
- showDiscriminator={duplicateNames.has(item.member.name.toLowerCase())}
- onOpenProfile={onOpenProfile}
- onSetRole={onSetRole}
- onKick={(mem) => setKickTargetId(mem.id)}
- onRequestManage={(kind, mem) => setManageConfirm({ kind, memberId: mem.id })}
- manageContext={manageContext}
- />
- )}
- </div>
- )
- })}
- </div>
+ <VirtualRows
+ items={items}
+ virtualizer={rowVirtualizer}
+ rowRole="listitem"
+ renderItem={(item) => item.kind === "header" ? (
+ <h3 className="mb-2 px-1 text-xs font-medium text-muted-foreground">
+ {item.label} — {item.count}
+ </h3>
+ ) : (
+ <MemberRow
+ mem={item.member}
+ canManage={canManage}
+ showDiscriminator={duplicateNames.has(item.member.name.toLowerCase())}
+ onOpenProfile={onOpenProfile}
+ onSetRole={onSetRole}
+ onKick={(mem) => setKickTargetId(mem.id)}
+ onRequestManage={(kind, mem) => setManageConfirm({ kind, memberId: mem.id })}
+ manageContext={manageContext}
+ />
+ )}
+ />
{hasMore && (
<div ref={sentinelRef} className="py-3 text-center text-xs text-muted-foreground">
{loadingMore ? "Loading…" : ""}
diff --git a/src/web/src/components/community/messages/attachment-card.tsx b/src/web/src/components/community/messages/attachment-card.tsx
index f4c3f22f3..22ab6d1bf 100644
--- a/src/web/src/components/community/messages/attachment-card.tsx
+++ b/src/web/src/components/community/messages/attachment-card.tsx
@@ -99,12 +99,12 @@ function FileAttachmentCard({
onClick={() => canPreview
? onPreview(attachment)
: download.state.status === "downloading" ? download.cancel() : void download.start()}
- className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
+ className="flex w-full max-w-[320px] items-center gap-2 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground"
aria-label={`${action} ${attachment.name}`}
aria-busy={!canPreview && download.state.status === "downloading"}
>
<Icon className="size-7 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="truncate text-sm font-medium text-primary">{attachment.name}</div>
{statusText ? (
<div
diff --git a/src/web/src/components/community/messages/media-attachment-block.tsx b/src/web/src/components/community/messages/media-attachment-block.tsx
index ee12da8ab..59c1f39c8 100644
--- a/src/web/src/components/community/messages/media-attachment-block.tsx
+++ b/src/web/src/components/community/messages/media-attachment-block.tsx
@@ -195,7 +195,7 @@ export function MediaAttachmentBlock({
<span
data-testid={tid.mediaStatus(attachment.name)}
role="status"
- className="absolute top-2 left-2 rounded-md bg-background/90 px-2 py-1 text-xs text-muted-foreground"
+ className="absolute top-2 left-2 rounded-md bg-background/90 p-2 text-xs text-muted-foreground"
>
Loading media…
</span>
@@ -203,9 +203,9 @@ export function MediaAttachmentBlock({
</div>
)}
- <div className="flex min-h-14 items-center gap-3 px-3 py-2">
+ <div className="flex min-h-14 items-center gap-2 p-2">
<MediaIcon className="size-6 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="truncate text-sm font-medium text-foreground">{attachment.name}</div>
<div className="text-xs text-muted-foreground">
{[mediaKind === "video" ? "Video" : "Audio", attachment.size].filter(Boolean).join(" · ")}
diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsx
index d0cbb772e..cdd9841f2 100644
--- a/src/web/src/components/community/messages/message-body.tsx
+++ b/src/web/src/components/community/messages/message-body.tsx
@@ -109,9 +109,10 @@ function MessageBodyImpl({
return (
<div
data-community-message-body
- className="markdown markdown-chat wrap-anywhere select-text text-[15px] leading-snug text-foreground"
+ className="markdown markdown-chat flex flex-col gap-2 wrap-anywhere select-text text-[15px] leading-snug text-foreground"
>
<Streamdown
+ className="message-markdown-blocks flex flex-col gap-2 space-y-0"
parseIncompleteMarkdown={false}
plugins={{ mermaid, cjk, math }}
remarkPlugins={[remarkGfm, chatSyntaxPlugin, remarkBreaks]}
@@ -135,11 +136,7 @@ function MessageBodyImpl({
{text}
</Streamdown>
{inviteTokens.length > 0 && (
- // `pb-2` is *inside* the message row so the row's hover tint
- // (`bg-accent/40`) extends below the card. A margin on the card
- // itself wouldn't do that — it'd push the card out of the row's
- // padding area.
- <div className="flex flex-col gap-2 pb-2">
+ <div className="flex flex-col gap-2">
{inviteTokens.map((token) => (
<CommunityInviteCard
key={token}
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index 1eddb8959..b6f4e8da9 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -15,8 +15,7 @@ const mocks = vi.hoisted(() => ({
breakpoint: "desktop" as "unknown" | "desktop" | "mobile",
hookOrder: [] as string[],
scrollInputs: [] as unknown[],
- sentinelInputs: [] as unknown[],
- sentinelRefs: [] as Array<{ current: null }>,
+ paginationInputs: [] as unknown[],
scrollRef: { current: null as HTMLDivElement | null },
virtualizer: { scrollToOffset: vi.fn(), containerRef: { current: null } },
jumpToIndex: vi.fn(),
@@ -53,6 +52,7 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({
requestPresentPosition: mocks.requestPresentPosition,
jumpTo: mocks.jumpToIndex,
readPositionReady: false,
+ paginationEnabled: false,
captureOlderPageAnchor: mocks.captureOlderPageAnchor,
isOlderPageAnchorSettling: false,
captureNewerPageAnchor: mocks.captureNewerPageAnchor,
@@ -60,13 +60,10 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({
}
},
}))
-vi.mock("@/hooks/community/use-virtual-cursor-sentinel", () => ({
- useVirtualCursorSentinel: (input: { edge: string }) => {
+vi.mock("@/hooks/community/use-virtual-cursor-pagination", () => ({
+ useVirtualCursorPagination: (input: { edge: string }) => {
mocks.hookOrder.push(input.edge)
- mocks.sentinelInputs.push(input)
- const ref = { current: null }
- mocks.sentinelRefs.push(ref)
- return ref
+ mocks.paginationInputs.push(input)
},
}))
@@ -142,8 +139,7 @@ describe("useMessageListController", () => {
disconnect.mockClear()
mocks.hookOrder.length = 0
mocks.scrollInputs.length = 0
- mocks.sentinelInputs.length = 0
- mocks.sentinelRefs.length = 0
+ mocks.paginationInputs.length = 0
mocks.scrollRef.current = null
mocks.jumpToIndex.mockClear()
mocks.scrollToBottom.mockClear()
@@ -186,6 +182,15 @@ describe("useMessageListController", () => {
return entry[0]
}
+ it("uses whole Query activity to pause both pagination directions", () => {
+ const onLoadOlder = vi.fn(), onLoadNewer = vi.fn()
+ rtlRender(React.createElement(Probe, { value: props({ isFetching: true, hasMore: true, hasMoreNewer: true, onLoadOlder, onLoadNewer }) }))
+ expect(mocks.paginationInputs.slice(-2)).toEqual([
+ expect.objectContaining({ edge: "start", isFetching: true }),
+ expect.objectContaining({ edge: "end", isFetching: true }),
+ ])
+ })
+
it("uses the exact loading predicate and calls anchor/start/end hooks unconditionally in order", () => {
let renderer: ReturnType<typeof rtlRender>
act(() => {
@@ -211,21 +216,28 @@ describe("useMessageListController", () => {
onScrollTargetCancelled: undefined,
onScrollTargetPositioned: expect.any(Function),
})
- expect(mocks.sentinelInputs.slice(0, 2)).toEqual([
+ expect(mocks.paginationInputs.slice(0, 2)).toEqual([
{
- scrollRef: mocks.scrollRef,
+ virtualizer: mocks.virtualizer,
+ count: latest.items.length,
+ enabled: false,
hasMore: undefined,
isFetching: undefined,
isSettling: false,
+ isError: false,
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: undefined,
edge: "start",
},
{
- scrollRef: mocks.scrollRef,
+ virtualizer: mocks.virtualizer,
+ count: latest.items.length,
+ enabled: false,
hasMore: undefined,
isFetching: undefined,
isSettling: false,
+ isError: false,
+ hasMoreAtStart: undefined,
onBeforeLoad: mocks.captureNewerPageAnchor,
onLoad: undefined,
edge: "end",
@@ -233,8 +245,6 @@ describe("useMessageListController", () => {
])
expect(latest.scrollRef).toBe(mocks.scrollRef)
expect(latest.virtualizer).toBe(mocks.virtualizer)
- expect(latest.topSentinelRef).toBe(mocks.sentinelRefs.at(-2))
- expect(latest.bottomSentinelRef).toBe(mocks.sentinelRefs.at(-1))
expect(latest.readPositionReady).toBe(false)
expect(latest.pillCount).toBe(2)
expect(latest.pillMode).toBe("scroll")
@@ -353,21 +363,28 @@ describe("useMessageListController", () => {
onScrollTargetCancelled: undefined,
onScrollTargetPositioned: expect.any(Function),
})
- expect(mocks.sentinelInputs.slice(-2)).toEqual([
+ expect(mocks.paginationInputs.slice(-2)).toEqual([
{
- scrollRef: mocks.scrollRef,
+ virtualizer: mocks.virtualizer,
+ count: latest.items.length,
+ enabled: false,
hasMore: true,
isFetching: true,
isSettling: false,
+ isError: false,
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: loadOlder,
edge: "start",
},
{
- scrollRef: mocks.scrollRef,
+ virtualizer: mocks.virtualizer,
+ count: latest.items.length,
+ enabled: false,
hasMore: true,
isFetching: true,
isSettling: false,
+ isError: false,
+ hasMoreAtStart: true,
onBeforeLoad: mocks.captureNewerPageAnchor,
onLoad: loadNewer,
edge: "end",
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index 735133d24..b4a2dcb0c 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -9,7 +9,7 @@ import {
useScrollAnchor,
} from "@/hooks/community/use-scroll-anchor"
import { useBreakpoint } from "@/hooks/use-mobile"
-import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"
+import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
import { useInitialPositionTransition } from "./initial-position-transition"
import type { ResolvedMessageListProps } from "./message-list-types"
@@ -22,6 +22,7 @@ export function useMessageListController({
initialScrollReady,
hasMore,
hasMoreNewer,
+ isFetching,
isFetchingOlder,
isFetchingNewer,
onLoadOlder,
@@ -40,8 +41,8 @@ export function useMessageListController({
const [anchorPositionSettled, setAnchorPositionSettled] = useAtom(useCreateAtom(false))
const items = useMemo(
- () => flattenMessageItems(messages, newDividerBefore, !!hasMore),
- [messages, newDividerBefore, hasMore],
+ () => flattenMessageItems(messages, newDividerBefore, !!hasMore, !!hasMoreNewer),
+ [messages, newDividerBefore, hasMore, hasMoreNewer],
)
const [selectMode, setSelectMode] = useAtom(useCreateAtom(false))
@@ -96,6 +97,7 @@ export function useMessageListController({
requestPresentPosition,
jumpTo: jumpToIndex,
readPositionReady,
+ paginationEnabled,
captureOlderPageAnchor,
isOlderPageAnchorSettling,
captureNewerPageAnchor,
@@ -128,20 +130,27 @@ export function useMessageListController({
return () => onScrollRoot(null)
}, [onScrollRoot, scrollRef])
- const topSentinelRef = useVirtualCursorSentinel({
- scrollRef,
+ useVirtualCursorPagination({
+ virtualizer,
+ count: items.length,
+ enabled: paginationEnabled,
hasMore,
- isFetching: isFetchingOlder,
- isSettling: isOlderPageAnchorSettling,
+ isFetching: isFetching || isFetchingOlder || isFetchingNewer,
+ isSettling: isOlderPageAnchorSettling || isNewerPageAnchorSettling,
+ isError: !!initialLoadError,
onBeforeLoad: captureOlderPageAnchor,
onLoad: onLoadOlder,
edge: "start",
})
- const bottomSentinelRef = useVirtualCursorSentinel({
- scrollRef,
+ useVirtualCursorPagination({
+ virtualizer,
+ count: items.length,
+ enabled: paginationEnabled,
hasMore: hasMoreNewer,
- isFetching: isFetchingNewer,
- isSettling: isNewerPageAnchorSettling,
+ hasMoreAtStart: hasMore,
+ isFetching: isFetching || isFetchingOlder || isFetchingNewer,
+ isSettling: isOlderPageAnchorSettling || isNewerPageAnchorSettling,
+ isError: !!initialLoadError,
onBeforeLoad: captureNewerPageAnchor,
onLoad: onLoadNewer,
edge: "end",
@@ -230,8 +239,6 @@ export function useMessageListController({
onToggleSelectId,
scrollRef,
virtualizer,
- topSentinelRef,
- bottomSentinelRef,
readPositionReady,
jumpTo,
pillCount,
diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
index adaa1e6a5..3bc36e383 100644
--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
@@ -38,6 +38,7 @@ type ExpectedMessageListProps = {
initialScrollReady?: boolean
onScrollTargetConsumed?: (id: string) => void
hasMore?: boolean
+ isFetching?: boolean
isFetchingOlder?: boolean
onLoadOlder?: () => void
hasMoreNewer?: boolean
@@ -68,7 +69,7 @@ describe("MessageList facade contract", () => {
expect(text).toContain("<VirtualRows")
expect(text).toContain("items={controller.items}")
expect(text).toContain("virtualizer={controller.virtualizer}")
- expect(text).toContain("itemKey={(item) => item.key}")
+ expect(text).not.toContain("itemKey=")
expect(text).toContain(
"renderItem={(item, index) => renderMessageListRow(item, resolvedProps, controller, index)}",
)
diff --git a/src/web/src/components/community/messages/message-list-row.dom.test.ts b/src/web/src/components/community/messages/message-list-row.dom.test.ts
index 29c9ca781..1da9b3758 100644
--- a/src/web/src/components/community/messages/message-list-row.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-row.dom.test.ts
@@ -1,26 +1,39 @@
import React from "react"
+import { compile, optimize } from "@tailwindcss/node"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { render } from "@/test/react-dom-harness"
import { renderMessageListRow } from "./message-list-row"
import { MessageRow } from "./message-row"
-import type { FlatItem } from "@/lib/community/message-list-items"
+import { flattenMessageItems, type FlatItem } from "@/lib/community/message-list-items"
import type { MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
vi.mock("./message-row", () => ({ MessageRow: vi.fn(() => null) }))
-vi.mock("../dividers", () => ({
- DateDivider: ({ label }: { label: string }) => React.createElement("div", {
- "data-testid": "date-divider",
- "data-label": label,
- }),
- NewDivider: ({ dateLabel }: { dateLabel?: string }) => React.createElement("div", {
- "data-testid": "new-divider",
- "data-date-label": dateLabel,
- }),
-}))
const mockedMessageRow = vi.mocked(MessageRow)
+async function withTailwindStyles(container: HTMLElement, check: () => void) {
+ const css = await compile("@theme inline { --spacing: 4px; } @tailwind utilities;", {
+ base: process.cwd(),
+ onDependency: () => {},
+ })
+ const style = document.createElement("style")
+ style.textContent = optimize(css.build(Array.from(container.querySelectorAll("[class]")).flatMap((element) => Array.from(element.classList))), { minify: true }).code
+ document.head.append(style)
+ try {
+ check()
+ } finally {
+ style.remove()
+ }
+}
+
+function marginPx(element: Element, side: "Top" | "Bottom") {
+ const style = getComputedStyle(element)
+ const physical = style[`margin${side}`]
+ // JSDOM leaves an unmapped logical margin's physical default as "0"; explicit physical zero is "0px".
+ return parseFloat(physical === "0" ? style.marginBlock || "0" : physical)
+}
+
const callbacks = {
onOpenThread: vi.fn(),
onOpenProfile: vi.fn(),
@@ -57,25 +70,44 @@ const controller = {
selectedIds: new Set(["m1"]),
jumpTo: vi.fn(),
items: [null],
- topSentinelRef: vi.fn(),
- bottomSentinelRef: vi.fn(),
onToggleSelectId: vi.fn(),
onEnterSelectId: vi.fn(),
} as unknown as MessageListController
describe("renderMessageListRow", () => {
- beforeEach(() => vi.clearAllMocks())
+ it("uses each adjacent row's half-gap and retains8px on the first and last sides", () => {
+ const items = flattenMessageItems(Array.from({ length: 3 }, (_, i) => ({
+ id: `m${i}`, type: "chat" as const, authorId: "same", createdAt: new Date(0).toISOString(),
+ })), undefined)
+ const view = render(React.createElement(React.Fragment, null, items.map((item, index) =>
+ React.createElement(React.Fragment, { key: item.key }, renderMessageListRow(item, props, { ...controller, items }, index)),
+ )))
+ const rows = Array.from(view.container.querySelectorAll<HTMLElement>("[data-msg-id]")).map(row => row.parentElement!)
+ expect(rows.map(row => getComputedStyle(row).paddingBlock))
+ .toEqual(["8px 4px", "4px 4px", "4px 8px"])
+ })
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockedMessageRow.mockImplementation(() => null)
+ })
it("keeps merged New/date and edge decorations outside the actual body", () => {
- const item: FlatItem = { kind: "message", key: "m1", dateLabel: "Today", newDivider: true, m: { id: "m1", type: "chat" } }
- const view = render(renderMessageListRow(item, { ...props, hasMore: true, hasMoreNewer: true }, controller, 0))
+ const items: FlatItem[] = [
+ { kind: "leading", key: "leading" },
+ { kind: "divider", key: "new:m1", messageId: "m1", dateLabel: "Today", newDivider: true },
+ { kind: "message", key: "m1", m: { id: "m1", type: "chat" } },
+ { kind: "trailing", key: "trailing" },
+ ]
+ const view = render(React.createElement(React.Fragment, null, items.map((item, index) =>
+ React.createElement(React.Fragment, { key: item.key }, renderMessageListRow(item, { ...props, hasMore: true, hasMoreNewer: true }, { ...controller, items }, index)),
+ )))
const body = view.container.querySelector('[data-msg-id="m1"]')!
- expect(view.getByTestId("new-divider")).toHaveAttribute("data-date-label", "Today")
- expect(body.querySelector('[data-testid="new-divider"]')).toBeNull()
- expect(view.queryByTestId("date-divider")).toBeNull()
+ expect(view.container.querySelector("[data-new-divider]")).toHaveTextContent("Today")
+ expect(body.querySelector("[data-new-divider]")).toBeNull()
+ expect(view.getAllByText("Today")).toHaveLength(1)
expect(view.container.firstElementChild).toHaveClass("flow-root")
- expect(controller.topSentinelRef).toHaveBeenCalled()
- expect(controller.bottomSentinelRef).toHaveBeenCalled()
+ expect(view.container.querySelectorAll('[data-msg-id]')).toHaveLength(1)
+ expect(view.container.querySelector('[data-message-divider-for="m1"]')).toBeInTheDocument()
expect(mockedMessageRow).toHaveBeenCalledOnce()
})
@@ -135,4 +167,84 @@ describe("renderMessageListRow", () => {
expect(mockedMessageRow.mock.calls.at(-1)?.[0].onEditId).toBeUndefined()
expect(mockedMessageRow.mock.calls.at(-1)?.[0].onImageLoad).toBeUndefined()
})
+
+ it.each([undefined, "Today"])("reserves the visible NEW pill in the same intrinsic row with date %s", async (dateLabel) => {
+ const items: FlatItem[] = [
+ { kind: "divider", key: "new:m1", messageId: "m1", dateLabel, newDivider: true },
+ { kind: "message", key: "m1", m: { id: "m1", type: "chat", grouped: false } },
+ ]
+ const view = render(renderMessageListRow(items[0], props, { ...controller, items }, 0))
+ const divider = view.container.querySelector("[data-new-divider]")!
+ const pill = view.getByText("New")
+ await withTailwindStyles(view.container, () => {
+ expect(getComputedStyle(divider).display).toBe("grid")
+ expect(divider.children).toHaveLength(2)
+ const line = pill.previousElementSibling!
+ const pillStyle = getComputedStyle(pill)
+ const lineStyle = getComputedStyle(line)
+ expect(["absolute", "fixed"]).not.toContain(pillStyle.position)
+ expect(pillStyle.getPropertyValue("translate")).toMatch(/^$|^none$/)
+ expect(pillStyle.gridRowStart).toBe("1")
+ expect(lineStyle.gridRowStart).toBe(pillStyle.gridRowStart)
+ expect(pillStyle.gridColumnStart).toBe("1")
+ expect(lineStyle.gridColumnStart).toBe(pillStyle.gridColumnStart)
+ expect(pillStyle.justifySelf).toBe("flex-end")
+ expect(pillStyle.pointerEvents).toBe("none")
+ expect(lineStyle.display).toBe("flex")
+ if (dateLabel) {
+ const label = view.getByText(dateLabel)
+ expect(label.parentElement).toBe(line)
+ expect(getComputedStyle(label.previousElementSibling!).flexGrow).toBe("1")
+ expect(getComputedStyle(label.nextElementSibling!).flexGrow).toBe("1")
+ }
+ })
+ })
+
+ it.each([
+ { name: "date to ungrouped chat", dateLabel: "Today", newDivider: false, grouped: false, type: "chat", gap: 16 },
+ { name: "NEW to ungrouped chat", dateLabel: undefined, newDivider: true, grouped: false, type: "chat", gap: 16 },
+ { name: "merged date/NEW to ungrouped chat", dateLabel: "Today", newDivider: true, grouped: false, type: "chat", gap: 16 },
+ { name: "date to pending-window grouped chat", dateLabel: "Today", newDivider: false, grouped: true, type: "chat", gap: 16 },
+ { name: "NEW to grouped chat", dateLabel: undefined, newDivider: true, grouped: true, type: "chat", gap: 16 },
+ { name: "date to system", dateLabel: "Today", newDivider: false, grouped: false, type: "system", gap: 16 },
+ { name: "NEW to system", dateLabel: undefined, newDivider: true, grouped: false, type: "system", gap: 16 },
+ ] as const)("uses one symmetric spacing owner between independent rows: $name", async ({ dateLabel, newDivider, grouped, type, gap }) => {
+ mockedMessageRow.mockImplementation(() => React.createElement("div"))
+ const items: FlatItem[] = [
+ { kind: "leading", key: "leading" },
+ { kind: "message", key: "previous", m: { id: "previous", type: "chat", grouped: false } },
+ { kind: "divider", key: "divider", messageId: "m1", dateLabel, newDivider },
+ { kind: "message", key: "m1", m: { id: "m1", type, grouped } },
+ ]
+ const view = render(React.createElement(React.Fragment, null, items.map((item, index) =>
+ React.createElement(React.Fragment, { key: item.key }, renderMessageListRow(item, props, { ...controller, items }, index)),
+ )))
+ await withTailwindStyles(view.container, () => {
+ const divider = view.container.querySelector('[data-message-divider-for="m1"] > div')!
+ const message = view.container.querySelector('[data-msg-id="m1"] > div')!
+ const dividerRow = divider.parentElement!
+ const messageRow = message.closest("[data-message-row-key]")!
+ expect(marginPx(divider, "Bottom") + marginPx(message, "Top")).toBe(0)
+ expect(parseFloat(getComputedStyle(dividerRow).paddingBlock) + parseFloat(getComputedStyle(messageRow).paddingBlock)).toBe(gap)
+ })
+ })
+
+ it.each(["date", "NEW", "merged date/NEW", "message"])("uses row padding at the leading boundary before %s", async (next) => {
+ mockedMessageRow.mockImplementation(() => React.createElement("div"))
+ const items: FlatItem[] = [
+ { kind: "leading", key: "leading" },
+ ...(next === "message" ? [] : [{ kind: "divider" as const, key: "divider", messageId: "m1", dateLabel: next === "NEW" ? undefined : "Today", newDivider: next !== "date" }]),
+ { kind: "message", key: "m1", m: { id: "m1", type: "chat", grouped: false } },
+ ]
+ const view = render(React.createElement(React.Fragment, null, items.map((item, index) =>
+ React.createElement(React.Fragment, { key: item.key }, renderMessageListRow(item, { ...props, hasMore: true }, { ...controller, items }, index)),
+ )))
+ await withTailwindStyles(view.container, () => {
+ const leading = view.container.querySelector('[data-message-row-key="leading"] > div')!
+ const following = view.container.querySelector(next === "message" ? '[data-msg-id="m1"] > div' : '[data-message-divider-for="m1"] > div')!
+ const nextRow = following.closest("[data-message-row-key]")!
+ expect(marginPx(leading, "Bottom") + marginPx(following, "Top")).toBe(0)
+ expect(parseFloat(getComputedStyle(leading).paddingBlock) + parseFloat(getComputedStyle(nextRow).paddingBlock)).toBe(24)
+ })
+ })
})
diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsx
index 229fd075a..29cb7bcc8 100644
--- a/src/web/src/components/community/messages/message-list-row.tsx
+++ b/src/web/src/components/community/messages/message-list-row.tsx
@@ -2,18 +2,18 @@ import { DateDivider, NewDivider } from "../dividers"
import { tid } from "@/lib/community/testids"
import { ChannelIcon } from "../channels/channel-icon"
import { MessageRow } from "./message-row"
-import type { FlatItem } from "@/lib/community/message-list-items"
+import { MESSAGE_ROW_VERTICAL_PADDING_PX, type FlatItem } from "@/lib/community/message-list-items"
import type { MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
export function renderMessageListHero(props: ResolvedMessageListProps) {
return props.hero ?? (
<>
- <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">
+ <div className="grid size-12 place-items-center rounded-full bg-muted/60">
<ChannelIcon className="text-xl text-muted-foreground" />
</div>
<h2 className="text-xl font-semibold leading-tight">{props.channel}</h2>
- <p className="mt-2 text-sm text-muted-foreground">
+ <p className="text-sm text-muted-foreground">
Beginning of the channel. Say hello, share what you&apos;re working on, or drop a link.
</p>
</>
@@ -24,22 +24,39 @@ export function renderMessageListRow(
item: FlatItem,
props: ResolvedMessageListProps,
controller: MessageListController,
- index: number,
+ _index: number,
) {
- return (
- <div className="flow-root" data-message-row-key={item.key}>
- {index === 0 && (
- <div className="mb-6 pt-8">
+ if (item.kind === "leading") {
+ return (
+ <div className="flow-root" data-message-row-key={item.key}>
+ <div className="flex flex-col gap-2 py-4">
{props.hasMore ? (
- <div ref={controller.topSentinelRef} className="flex h-8 items-center justify-center text-xs text-muted-foreground">
+ <div className="flex h-8 items-center justify-center text-xs text-muted-foreground">
{props.isFetchingOlder ? "Loading older messages…" : ""}
</div>
) : renderMessageListHero(props)}
</div>
- )}
- {item.newDivider
- ? <NewDivider dateLabel={item.dateLabel} />
- : item.dateLabel && <DateDivider label={item.dateLabel} />}
+ </div>
+ )
+ }
+ if (item.kind === "trailing") {
+ return (
+ <div className="flow-root py-4" data-message-row-key={item.key}>
+ <div className="flex h-8 items-center justify-center text-xs text-muted-foreground">
+ {props.isFetchingNewer ? "Loading newer messages…" : ""}
+ </div>
+ </div>
+ )
+ }
+ if (item.kind === "divider") {
+ return (
+ <div className="flow-root py-2 *:my-0" data-message-row-key={item.key} data-message-divider-for={item.messageId}>
+ {item.newDivider ? <NewDivider dateLabel={item.dateLabel} /> : <DateDivider label={item.dateLabel!} />}
+ </div>
+ )
+ }
+ return (
+ <div className="flow-root" style={{ paddingBlock: `${item.paddingTop ?? MESSAGE_ROW_VERTICAL_PADDING_PX}px ${item.paddingBottom ?? MESSAGE_ROW_VERTICAL_PADDING_PX}px` }} data-message-row-key={item.key}>
<div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>
<MessageRow
m={item.m}
@@ -73,11 +90,6 @@ export function renderMessageListRow(
onEnterSelectId={controller.onEnterSelectId}
/>
</div>
- {index === controller.items.length - 1 && props.hasMoreNewer && (
- <div ref={controller.bottomSentinelRef} className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground">
- {props.isFetchingNewer ? "Loading newer messages…" : ""}
- </div>
- )}
</div>
)
}
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 0f1ecbac6..1fc061a37 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -37,6 +37,7 @@ export type MessageListProps = {
initialScrollReady?: boolean
onScrollTargetConsumed?: (id: string) => void
hasMore?: boolean
+ isFetching?: boolean
isFetchingOlder?: boolean
onLoadOlder?: () => void
hasMoreNewer?: boolean
diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.ts
index 044049e81..3e5551617 100644
--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts
@@ -82,8 +82,6 @@ function controller(overrides: Partial<MessageListController> = {}): MessageList
onToggleSelectId: vi.fn(),
scrollRef: { current: null },
virtualizer: {} as MessageListController["virtualizer"],
- topSentinelRef: vi.fn(),
- bottomSentinelRef: vi.fn(),
readPositionReady: true,
jumpTo: vi.fn(),
pillCount: 3,
diff --git a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
index d7e236c8d..dcc589272 100644
--- a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
@@ -44,7 +44,8 @@ describe("MessageList loading-to-loaded mount identity", () => {
resize()
expect(renderer.getByTestId(tid.messageScroller)).toBe(root)
expect(renderer.container.querySelector('[data-message-empty-tail]')).toBeNull()
- expect(renderer.container.querySelectorAll('[data-index]')).toHaveLength(1)
+ expect(renderer.container.querySelectorAll('[data-index]')).toHaveLength(3)
+ expect(renderer.container.querySelectorAll('[data-msg-id]')).toHaveLength(1)
expect(root.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height).toBe("500px")
expect(root.querySelector('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
})
diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
index c4b8e05ec..b2f336f51 100644
--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
@@ -5,52 +5,151 @@ import { act, fireEvent, render } from "@/test/react-dom-harness"
import { MessageList } from "./message-list"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames } from "@/test/message-scroll-fixture"
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+const breakpoint = vi.hoisted(() => ({ value: "desktop" as "desktop" | "mobile" }))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => breakpoint.value }))
vi.mock("./message-row", () => ({ MessageRow: () => React.createElement("div") }))
vi.mock("@/components/ui/number-ticker", () => ({ NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value) }))
-describe("MessageList virtual older sentinel does not cascade", () => {
- beforeEach(installMessageScrollFixture)
- afterEach(restoreMessageScrollFixture)
- it("loads once per intersection, retains its fetch lock, and accepts fresh edge input", () => {
- let callback: IntersectionObserverCallback
- let element: Element
- const disconnected = vi.fn()
- vi.stubGlobal("IntersectionObserver", class {
- constructor(next: IntersectionObserverCallback) { callback = next }
- observe(target: Element) { element = target }
- disconnect() { disconnected() }
- })
- const messages = Array.from({ length: 14 }, (_, i) => ({ id: `m${i}`, authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
+describe("MessageList native range pagination", () => {
+ it("loads and settles ordinary older pages after the position deadline while read remains closed", () => {
+ const messages = Array.from({ length: 50 }, (_, i) => ({ id: `m${i}`, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
const onLoadOlder = vi.fn()
- const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, loading: false, hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
- const intersect = (isIntersecting = true) => act(() => callback([{ isIntersecting, target: element } as IntersectionObserverEntry], {} as IntersectionObserver))
+ const view = (isFetchingOlder: boolean) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: false, hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
const renderer = render(view(false))
resize()
const scroller = renderer.getByTestId(tid.messageScroller)
- fireEvent.wheel(scroller, { deltaY: -20 })
act(() => { scroller.scrollTo({ top: 0 }) })
runFrames()
+ expect(onLoadOlder).not.toHaveBeenCalled()
+ act(() => vi.advanceTimersByTime(2000))
+ runFrames()
+ act(() => { scroller.scrollTo({ top: 0 }) })
resize()
- expect(element!.isConnected).toBe(true)
- intersect()
+ expect(renderer.container.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
expect(onLoadOlder).toHaveBeenCalledOnce()
renderer.rerender(view(true))
+ resize()
renderer.rerender(view(false))
resize()
+ expect(onLoadOlder).toHaveBeenCalledTimes(2)
+ expect(renderer.container.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ })
+
+ it.each([
+ ["header", "alice", false], ["first", "alice", false], ["inside", "alice", false],
+ ["header", "bob", false], ["first", "bob", false], ["inside", "bob", false],
+ ["first", "alice", true], ["inside", "alice", true], ["return", "bob", true],
+ ] as const)("retains the first-window body at the %s fold with older author %s and pending move %s", (fold, olderAuthor, pendingMove) => {
+ const message = (i: number) => ({ id: `m${i}`, type: "chat" as const, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(i * 1000).toISOString() })
+ let messages = Array.from({ length: 50 }, (_, i) => message(i + 40))
+ const onLoadOlder = vi.fn()
+ const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: false, hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
+ const renderer = render(view(false, fold === "header" || pendingMove))
+ resize()
+ act(() => vi.advanceTimersByTime(2000))
+ runFrames()
+ const root = renderer.getByTestId(tid.messageScroller)
+ act(() => root.scrollTo({ top: 0 }))
+ resize()
+ const body = renderer.getByTestId(tid.message("m40"))
+ const row = body.closest<HTMLElement>("[data-message-row-key]")!
+ expect(row.style.paddingBlock).toBe("8px 4px")
+ const moveToFold = () => {
+ const start = root.scrollTop + row.getBoundingClientRect().top - root.getBoundingClientRect().top
+ act(() => root.scrollTo({ top: start + (fold === "inside" ? 30 : 0) }))
+ resize()
+ if (fold === "return") {
+ act(() => root.scrollTo({ top: 0 }))
+ resize()
+ }
+ }
+ if (!pendingMove && fold !== "header") {
+ expect(onLoadOlder).not.toHaveBeenCalled()
+ moveToFold()
+ renderer.rerender(view(false))
+ resize()
+ }
expect(onLoadOlder).toHaveBeenCalledOnce()
+ renderer.rerender(view(true))
+ resize()
+ if (pendingMove) moveToFold()
+ const before = body.getBoundingClientRect().top - root.getBoundingClientRect().top
+ messages = [...Array.from({ length: 39 }, (_, i) => ({ ...message(i + 1), authorId: olderAuthor })), ...messages]
+ renderer.rerender(view(false))
+ resize()
+ const after = renderer.getByTestId(tid.message("m40"))
+ expect(after.closest<HTMLElement>("[data-message-row-key]")!.style.paddingBlock).toBe(olderAuthor === "alice" ? "4px 4px" : "8px 4px")
+ const offset = after.getBoundingClientRect().top - root.getBoundingClientRect().top
+ expect(Math.abs(offset - before)).toBeLessThanOrEqual(1)
+ expect(renderer.container.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ })
+ beforeEach(() => { breakpoint.value = "desktop"; installMessageScrollFixture() })
+ afterEach(restoreMessageScrollFixture)
+ it.each([["mobile", 40], ["desktop", 48]] as const)("keeps %s body-to-viewport clearance at %ipx with symmetric row padding", (stage, gap) => {
+ breakpoint.value = stage
+ const messages = Array.from({ length: 14 }, (_, i) => ({ id: `m${i}`, authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
+ const renderer = render(React.createElement(MessageList, { channel: "general", messages, loading: false, hasMore: false, onOpenThread: vi.fn() }))
+ resize()
+ runFrames()
+ const scroller = renderer.getByTestId(tid.messageScroller)
+ act(() => { scroller.scrollTo({ top: scroller.scrollHeight }) })
+ resize()
+ const tail = renderer.getByTestId(tid.message("m13"))
+ const wrapper = tail.closest<HTMLElement>("[data-index]")!
+ expect(tail.getBoundingClientRect().top - wrapper.getBoundingClientRect().top).toBe(8)
+ expect(wrapper.getBoundingClientRect().bottom - tail.getBoundingClientRect().bottom).toBe(8)
+ expect(scroller.getBoundingClientRect().bottom - tail.getBoundingClientRect().bottom).toBe(gap)
+ })
+ it("stops automatic pagination on the existing Query error surface", () => {
+ const messages = Array.from({ length: 50 }, (_, i) => ({ id: `m${i}`, authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
+ const onLoadOlder = vi.fn()
+ const makeView = (error: Error | null) => React.createElement(MessageList, { channel: "general", messages, loading: false, hasMore: true, onLoadOlder, initialLoadError: error, onOpenThread: vi.fn() })
+ const renderer = render(makeView(new Error("page failed after retries")))
+ resize()
+ runFrames()
+ const scroller = renderer.getByTestId(tid.messageScroller)
+ fireEvent.wheel(scroller, { deltaY: -400 })
act(() => { scroller.scrollTo({ top: 0 }) })
- fireEvent.wheel(scroller, { deltaY: -20 })
- expect(onLoadOlder).toHaveBeenCalledTimes(2)
+ runFrames()
+ resize()
+ expect(onLoadOlder).not.toHaveBeenCalled()
+ renderer.rerender(makeView(null))
+ runFrames()
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+ })
+
+ it("continues loading at the top after fetch settlement without a fresh gesture", () => {
+ const messages = Array.from({ length: 50 }, (_, i) => ({ id: `m${i}`, authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
+ const onLoadOlder = vi.fn()
+ const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, loading: false, hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
+ const renderer = render(view(false))
+ resize()
+ runFrames()
+ const scroller = renderer.getByTestId(tid.messageScroller)
+ expect(onLoadOlder).not.toHaveBeenCalled()
+
+ fireEvent.wheel(scroller, { deltaY: -400 })
+ act(() => { scroller.scrollTo({ top: 0 }) })
+ runFrames()
+ resize()
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+
+ renderer.rerender(view(true))
+ fireEvent.wheel(scroller, { deltaY: -400 })
+ act(() => { scroller.scrollTo({ top: 0 }) })
+ runFrames()
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+
renderer.rerender(view(false))
- intersect(false)
- intersect(true)
+ runFrames()
+ resize()
expect(onLoadOlder).toHaveBeenCalledTimes(2)
+
renderer.rerender(view(true))
renderer.rerender(view(false, false))
+ runFrames()
resize()
expect(onLoadOlder).toHaveBeenCalledTimes(2)
renderer.unmount()
- expect(disconnected).toHaveBeenCalled()
})
})
diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsx
index 364d68016..d5a9046f9 100644
--- a/src/web/src/components/community/messages/message-list.tsx
+++ b/src/web/src/components/community/messages/message-list.tsx
@@ -38,7 +38,6 @@ export function MessageList({
<VirtualRows
items={controller.items}
virtualizer={controller.virtualizer}
- itemKey={(item) => item.key}
renderItem={(item, index) => renderMessageListRow(item, resolvedProps, controller, index)}
/>
), footerSlot?.target ?? null)
diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.ts
index 8a07f19f5..ebd90842b 100644
--- a/src/web/src/components/community/messages/message.render.dom.test.ts
+++ b/src/web/src/components/community/messages/message.render.dom.test.ts
@@ -19,6 +19,7 @@ import {
} from "./message"
import { EmojiPickerPopover } from "./emoji-picker"
import type { RenderMsg } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),
useCanonicalCommunityProfile: (userId: string | null | undefined) => userId === "u1"
? { userId, name: "Alice", discriminator: "", avatar: "A", avatarVersion: 0 }
@@ -557,6 +558,20 @@ describe("Message reply content projection", () => {
})
describe("Message embed links", () => {
+ it("omits empty title and field blocks while retaining populated preview fields", () => {
+ let renderer: DomRenderer
+ const renderEmbed = (fields: Array<{ name: string; value: string }>) => makeTree({
+ m: baseMsg({ embeds: [{ title: "", desc: "Preview summary", fields }] }),
+ onOpenThread: vi.fn(),
+ })
+ act(() => { renderer = render(renderEmbed([]), { createNodeMock: () => genericMock }) })
+ const article = renderer!.root.findByType("article")
+ expect(textContent(article)).toBe("Preview summary")
+ expect(article.findAllByType("div").some(node => node.children.length === 0)).toBe(false)
+ act(() => renderer!.rerender(renderEmbed([{ name: "Status", value: "Ready" }])))
+ expect(textContent(renderer!.root.findByType("article"))).toContain("StatusReady")
+ })
+
it("routes author and title URLs through the shared external-link anchor", () => {
let renderer: DomRenderer
act(() => {
@@ -974,6 +989,53 @@ describe("Message portal event ownership", () => {
})
describe("Message reaction picker", () => {
+ it("retains an open reaction details dialog and its empty state through final reaction removal", () => {
+ vi.useFakeTimers()
+ try {
+ const reaction = { emoji: "👍", count: 1, me: true, userIds: ["u1"] }
+ const tree = (reactions: RenderMsg["reactions"]) => makeTree({ m: baseMsg({ reactions }), hoverCapable: false, onOpenThread: vi.fn(), onReact: vi.fn() })
+ const renderer = render(tree([reaction]))
+ const group = renderer.root.findByProps({ "data-testid": tid.reactionGroup("m1") }).element
+ const chip = renderer.root.findByProps({ "data-testid": tid.reactionChip("m1", "👍") }).element
+ fireEvent.pointerDown(chip, { pointerType: "touch", clientX: 10, clientY: 10 })
+ act(() => vi.advanceTimersByTime(450))
+ expect(renderer.root.findByType("mock-dialog").props.open).toBe(true)
+ act(() => renderer.rerender(tree([])))
+ expect(renderer.root.findByType("mock-dialog").props.open).toBe(true)
+ expect(renderer.root.findByProps({ "data-testid": tid.reactionEmpty("m1") }).element.textContent).toBe("No reactions yet")
+ expect(group.isConnected).toBe(true)
+ expect(group.parentElement).toHaveClass("sr-only")
+ const dialog = renderer.root.findByType("mock-dialog")
+ act(() => dialog.props.onOpenChange(false))
+ act(() => renderer.root.findByType("mock-dialog").props.onOpenChangeComplete(false))
+ expect(document.activeElement).toBe(group)
+ act(() => renderer.rerender(tree([reaction])))
+ expect(group.parentElement).not.toHaveClass("sr-only")
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+ it("removes the inline reaction row from flow on1→0 and restores it on0→1 while retaining menu add", () => {
+ const onReact = vi.fn()
+ const reaction = { emoji: "👍", count: 1, me: true, userIds: ["u1"] }
+ const tree = (reactions: RenderMsg["reactions"]) => makeTree({ m: baseMsg({ reactions }), hoverCapable: false, onOpenThread: vi.fn(), onReact })
+ const renderer = render(tree([reaction]))
+ const strip = () => renderer.root.findAllByProps({ "aria-label": "Add reaction" })
+ .filter(node => node.type === "button" && node.props.className.includes("bg-secondary"))
+ expect(strip()).toHaveLength(1)
+ const reactionRow = strip()[0].element.closest("div.flex.flex-wrap")!.parentElement!
+ act(() => renderer.rerender(tree([])))
+ expect(strip()).toHaveLength(0)
+ expect(reactionRow.isConnected).toBe(true)
+ expect(reactionRow).toHaveClass("sr-only")
+ expect(renderer.toJSON()).not.toContain("community-reaction-chip-m1")
+ const row = renderer.root.find(node => typeof node.props.className === "string" && node.props.className.includes("group relative -mx-2"))
+ act(() => row.props.onClick({ clientX: 10, clientY: 10, currentTarget: { contains: () => true }, target: { closest: () => null } }))
+ expect(renderer.root.findAllByType("button").some(button => textContent(button).includes("Add Reaction"))).toBe(true)
+ act(() => renderer.rerender(tree([reaction])))
+ expect(strip()).toHaveLength(1)
+ expect(reactionRow).not.toHaveClass("sr-only")
+ })
it("opens the non-hover picker and suppresses its Shadow DOM selection click at the row", async () => {
vi.stubGlobal("window", { getSelection: () => null })
const onReact = vi.fn()
@@ -988,7 +1050,7 @@ describe("Message reaction picker", () => {
})
const addButton = renderer!.root.findAllByProps({ "aria-label": "Add reaction" })
- .find((node) => node.type === "button" && node.props.className.includes("h-6 w-7"))
+ .find((node) => node.type === "button" && node.props.className.includes("bg-secondary"))
expect(addButton?.props["data-slot"]).toBe("popover-trigger")
expect(renderer!.root.findAllByProps({ "data-slot": "popover-content" })).toHaveLength(0)
@@ -1056,7 +1118,7 @@ describe("Message reaction picker", () => {
expect(renderer!.root.findAllByType(EmojiPickerPopover)).toHaveLength(2)
expect(renderer!.root.findAllByProps({ "data-slot": "popover-content" })).toHaveLength(0)
const stripButton = renderer!.root.findAllByProps({ "aria-label": "Add reaction" })
- .find((node) => node.type === "button" && node.props.className.includes("h-6 w-7"))
+ .find((node) => node.type === "button" && node.props.className.includes("bg-secondary"))
expect(stripButton?.props["data-slot"]).toBe("tooltip-trigger")
await act(async () => {
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 10c71cb39..eac4a5c34 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -25,6 +25,7 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip
import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./message-menu"
import { formatMessageTime } from "@/lib/community/format-time"
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
import { avatarInitial } from "@/lib/community/avatar"
import { stripInlineMarkup } from "@alook/shared"
import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"
@@ -267,7 +268,7 @@ function MessageImpl({
if (m.type === "system") {
const Icon = m.systemKind === "thread" ? MessagesSquare : UserPlus
return (
- <div className="flex items-center gap-2 px-2 py-1 text-sm text-muted-foreground">
+ <div className="flex items-center gap-2 px-2 text-sm text-muted-foreground">
<Icon className="size-4 shrink-0" />
<span className="min-w-0 wrap-break-word">{m.content}</span>
<span className="shrink-0 text-xs" suppressHydrationWarning>{formatMessageTime(m.createdAt)}</span>
@@ -390,7 +391,6 @@ function MessageImpl({
"group relative -mx-2 flex gap-2 rounded px-2 transition-colors",
swipeReplyEnabled ? "z-10 touch-pan-y bg-background" : "",
swipeVisual.active ? "transition-none" : "transition-transform duration-150 ease-out",
- m.grouped ? "py-0" : "mt-3 pt-1.5 pb-0",
selectable ? "cursor-pointer" : "",
selected ? "bg-primary/10" : highlighted ? "bg-primary/10" : selectable ? "hover:bg-accent/40" : "hover:bg-accent/40",
].join(" ")}
@@ -584,7 +584,7 @@ function MessageImpl({
}
: undefined}
>
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
{interactive && activated && !selectMode && (
<div className={`absolute right-2 z-20 flex items-center gap-1 rounded-lg border border-border/60 bg-card px-2 py-1 shadow-(--e1) transition-opacity duration-150 ${m.grouped ? "-top-2" : "-top-3"} ${toolbarOpen ? "opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100"}`}>
{m.seq != null && m.seq > 0 && (
@@ -623,20 +623,22 @@ function MessageImpl({
)}
{m.replyTo && (
- <button onClick={onJumpReply} className="mb-1 ml-13 flex min-w-0 max-w-[calc(100%-3.25rem)] items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
- <div className="h-2 w-4 shrink-0 rounded-tl-md border-l-2 border-t-2 border-border" />
- {m.replyTo.deleted ? (
- <span className="italic text-muted-foreground">Original message was deleted</span>
- ) : (
- <>
- <span className="shrink-0 font-medium text-foreground/80">@{replyAuthorName}</span>
- <span className="min-w-0 truncate">{stripInlineMarkup(m.replyTo.text)}</span>
- </>
- )}
- </button>
+ <div className="grid grid-cols-[2.5rem_minmax(0,1fr)] gap-2">
+ <button onClick={onJumpReply} className="col-start-2 flex min-w-0 items-center gap-2 text-[13px] text-muted-foreground hover:text-foreground">
+ <div className="h-2 w-4 shrink-0 rounded-tl-md border-l-2 border-t-2 border-border" />
+ {m.replyTo.deleted ? (
+ <span className="italic text-muted-foreground">Original message was deleted</span>
+ ) : (
+ <>
+ <span className="shrink-0 font-medium text-foreground/80">@{replyAuthorName}</span>
+ <span className="min-w-0 truncate">{stripInlineMarkup(m.replyTo.text)}</span>
+ </>
+ )}
+ </button>
+ </div>
)}
- <div className="flex gap-3">
+ <div className="flex gap-2">
{m.grouped ? (
<div className="w-10 shrink-0" />
) : (
@@ -650,7 +652,7 @@ function MessageImpl({
<Avatar label={authorAvatar} seed={m.authorId} size={40} />
</button>
)}
- <div className="relative min-w-0 flex-1">
+ <div className="relative flex min-w-0 flex-1 flex-col gap-2">
{m.grouped && selectable && (
<span
aria-hidden
@@ -703,8 +705,8 @@ function MessageImpl({
)
)}
- {m.attachments && (
- <div className="mt-2 flex flex-col gap-2 pb-2">
+ {m.attachments && m.attachments.length > 0 && (
+ <div className="flex flex-col gap-2">
{m.attachments.map((a, i) => {
if (a.kind === "image") {
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
@@ -738,21 +740,21 @@ function MessageImpl({
)}
{m.embeds && m.embeds.length > 0 && (
- <div className="mt-2 flex flex-col gap-2 pb-2">
+ <div className="flex flex-col gap-2">
{m.embeds.map((embed, ei) => (
<article
key={ei}
- className="flex max-w-108 overflow-hidden rounded-lg border border-border bg-card p-3"
+ className="flex max-w-108 items-start gap-2 overflow-hidden rounded-lg border border-border bg-card p-2"
>
{embed.color && (
<span
- className="mt-1.5 mr-3 size-2 shrink-0 self-start rounded-full"
+ className="size-2 shrink-0 self-center rounded-full"
style={{ backgroundColor: embed.color }}
/>
)}
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
{embed.author && (
- <div className="mb-2 flex items-center gap-2">
+ <div className="flex items-center gap-2">
{embed.author.iconUrl ? (
<span className="relative block size-5 overflow-hidden rounded-full" aria-hidden>
<RemoteIdentityImage
@@ -773,17 +775,17 @@ function MessageImpl({
</div>
)}
{embed.provider && <div className="text-xs text-muted-foreground">{embed.provider}</div>}
- {embed.url ? (
- <MessageExternalLink href={embed.url} target="_blank" rel="noopener noreferrer" className="mt-1 block font-medium text-primary hover:underline">{embed.title}</MessageExternalLink>
+ {embed.title && (embed.url ? (
+ <MessageExternalLink href={embed.url} target="_blank" rel="noopener noreferrer" className="block font-medium text-primary hover:underline">{embed.title}</MessageExternalLink>
) : (
- <div className="mt-1 font-medium">{embed.title}</div>
- )}
- {embed.desc && <p className="mt-1 text-sm text-muted-foreground">{embed.desc}</p>}
+ <div className="font-medium">{embed.title}</div>
+ ))}
+ {embed.desc && <p className="text-sm text-muted-foreground">{embed.desc}</p>}
- {embed.fields && (
- <div className="mt-2 flex flex-wrap gap-x-4 gap-y-2">
+ {embed.fields && embed.fields.length > 0 && (
+ <div className="flex flex-wrap gap-2">
{embed.fields.map((f, fi) => (
- <div key={fi} className={f.inline ? "min-w-[30%] flex-1" : "w-full"}>
+ <div key={fi} className={cn("flex flex-col gap-2", f.inline ? "min-w-[30%] flex-1" : "w-full")}>
<div className="text-xs font-semibold">{f.name}</div>
<div className="text-xs text-muted-foreground">{f.value}</div>
</div>
@@ -798,7 +800,7 @@ function MessageImpl({
width={embed.image.width}
height={embed.image.height}
loading="lazy"
- frameClassName="mt-2 w-full max-w-100 rounded-sm"
+ frameClassName="w-full max-w-100 rounded-sm"
frameStyle={{ aspectRatio: embed.image.width && embed.image.height ? `${embed.image.width}/${embed.image.height}` : "40/21" }}
imageClassName="rounded-sm object-cover"
errorLabel="Embed image failed to load"
@@ -807,7 +809,7 @@ function MessageImpl({
)}
{embed.footer && (
- <div className="mt-2 flex items-center gap-2 text-[11px] text-muted-foreground">
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
{embed.footer.iconUrl && (
<span className="relative block size-4 overflow-hidden rounded-full" aria-hidden>
<RemoteIdentityImage
@@ -828,7 +830,7 @@ function MessageImpl({
src={embed.thumbnail.url}
alt="Embed thumbnail"
loading="lazy"
- frameClassName="ml-3 size-16 shrink-0 rounded-md"
+ frameClassName="size-16 shrink-0 rounded-md"
imageClassName="rounded-md object-cover"
errorLabel="Thumbnail failed to load"
/>
@@ -839,7 +841,7 @@ function MessageImpl({
)}
{m.reactions && (
- <div className="mt-2">
+ <div className={m.reactions.length ? undefined : "sr-only"}>
<MessageReactions
messageId={m.id}
authorName={authorName}
@@ -849,7 +851,7 @@ function MessageImpl({
tooltipActive={activated}
onToggleReaction={onToggleReaction}
resolveUserName={resolveUserName}
- trailingControl={reactionAddControl}
+ trailingControl={m.reactions.length ? reactionAddControl : undefined}
/>
</div>
)}
@@ -858,7 +860,7 @@ function MessageImpl({
<button
data-testid={tid.threadIndicator(m.id)}
onClick={() => onOpenThread(m.thread!.id)}
- className="group/thread mt-2 flex items-center gap-2 rounded-md px-2 py-1 text-sm hover:bg-accent/60"
+ className="group/thread flex min-h-11 items-center gap-2 self-start rounded-md p-2 text-sm hover:bg-accent/60 sm:min-h-0"
>
<MessagesSquare className="size-4 text-primary" />
<span className="font-medium text-primary">
@@ -874,12 +876,12 @@ function MessageImpl({
)}
{m.failed && (
- <div className="mt-1 flex items-center gap-3 text-xs text-destructive">
- <button onClick={onRetry} className="flex items-center gap-2 hover:underline">
+ <div className="flex flex-wrap items-center gap-2 text-xs text-destructive">
+ <button onClick={onRetry} className="flex min-h-11 items-center gap-2 rounded-md p-2 hover:underline sm:min-h-0">
<X className="size-3.5" /> Message failed to send. Click to retry.
</button>
{onDismiss && (
- <button onClick={onDismiss} className="text-muted-foreground hover:text-foreground hover:underline">
+ <button onClick={onDismiss} className="min-h-11 rounded-md p-2 text-muted-foreground hover:text-foreground hover:underline sm:min-h-0">
Dismiss
</button>
)}
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index e5f08be30..9db45d3f5 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -90,8 +90,8 @@ export function ThreadOpener({
// lost access) we don't fail the thread view — just render a minimal
// placeholder so the opener slot doesn't collapse the layout.
return (
- <div>
- <div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<MessagesSquare className="size-3.5" />
<span>Thread started from a message</span>
</div>
@@ -109,8 +109,8 @@ export function ThreadOpener({
const visibleContent = displayReplyContent(msg.content ?? "", msg.replyTo)
return (
- <div data-thread-opener className="group relative">
- <div className="mb-2 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <div data-thread-opener className="group relative flex flex-col gap-2">
+ <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<MessagesSquare className="size-3.5" />
<span>Thread started from</span>
</div>
@@ -128,7 +128,7 @@ export function ThreadOpener({
</button>
)}
- <div className="flex gap-3">
+ <div className="flex gap-2">
<button
{...avatarMention}
className="shrink-0 self-start"
@@ -138,7 +138,7 @@ export function ThreadOpener({
>
<Avatar label={avatarLabel} seed={msg.authorId} size={40} />
</button>
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
<div className="flex items-baseline gap-2">
<button
onClick={(e) => onOpenProfile?.(authorName, e, undefined, msg.authorId)}
@@ -160,7 +160,7 @@ export function ThreadOpener({
)}
{msg.attachments && msg.attachments.length > 0 && (
- <div className="mt-2 flex flex-col gap-2 pb-2">
+ <div className="flex flex-col gap-2">
{msg.attachments.map((a, i) => {
if (a.kind === "image") {
const frameStyle = attachmentImageFrameStyle(a.width, a.height)
@@ -192,8 +192,8 @@ export function ThreadOpener({
</div>
)}
- {msg.reactions && (
- <div className="mt-2">
+ {msg.reactions && msg.reactions.length > 0 && (
+ <div>
<MessageReactions
messageId={msg.id}
authorName={authorName}
@@ -214,11 +214,11 @@ export function ThreadOpener({
function ThreadOpenerSkeleton() {
return (
- <div>
- <Skeleton className="mb-2 h-3 w-32 rounded" />
- <div className="flex gap-3">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-3 w-32 rounded" />
+ <div className="flex gap-2">
<Skeleton className="size-10 shrink-0 rounded-full" />
- <div className="flex min-w-0 flex-1 flex-col gap-2 pt-0.5">
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
<Skeleton className="h-4 w-32 rounded" />
<Skeleton className="h-3.5 w-full max-w-80 rounded" />
<Skeleton className="h-3.5 w-48 rounded" />
diff --git a/src/web/src/components/community/messages/virtual-cursor-list.tsx b/src/web/src/components/community/messages/virtual-cursor-list.tsx
index 6d493fe6b..d82758fd8 100644
--- a/src/web/src/components/community/messages/virtual-cursor-list.tsx
+++ b/src/web/src/components/community/messages/virtual-cursor-list.tsx
@@ -8,13 +8,13 @@ import type { ReactVirtualizer } from "@tanstack/react-virtual"
export function VirtualRows<T>({
items,
virtualizer,
- itemKey,
renderItem,
+ rowRole,
}: {
items: T[]
virtualizer: ReactVirtualizer<HTMLDivElement, Element>
- itemKey: (item: T) => string
renderItem: (item: T, index: number) => ReactNode
+ rowRole?: "listitem"
}) {
return (
<div
@@ -28,7 +28,8 @@ export function VirtualRows<T>({
const item = items[virtualRow.index]
return (
<div
- key={itemKey(item)}
+ key={virtualRow.key}
+ role={rowRole}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
style={{
diff --git a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
index 7ad08b365..92189f4d6 100644
--- a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
+++ b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
@@ -16,7 +16,6 @@ describe("community virtualizer direct DOM contract", () => {
expect(messageList).toContain("<VirtualRows")
expect(scrollAnchor).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")
- expect(scrollAnchor).toContain("measureElement: measureMessageRow")
expect(virtualRows).toContain("ref={virtualizer.containerRef}")
expect(virtualRows).toContain("ref={virtualizer.measureElement}")
expect(virtualRows).not.toContain("virtualizer.getTotalSize()")
@@ -36,9 +35,9 @@ describe("community virtualizer direct DOM contract", () => {
const memberList = readComponent("../members/member-list.tsx")
expect(memberList).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")
- expect(memberList).toContain("ref={rowVirtualizer.containerRef}")
- expect(memberList).toContain("ref={rowVirtualizer.measureElement}")
- expect(memberList).toContain("getItemKey: (index) => items[index]?.key ?? index")
+ expect(memberList).toContain("<VirtualRows")
+ expect(memberList).toContain("virtualizer={rowVirtualizer}")
+ expect(memberList).toContain("useCallback((index: number) => items[index]?.key ?? index, [items])")
expect(memberList).not.toContain("rowVirtualizer.getTotalSize()")
expect(memberList).not.toContain("virtualRow.start")
})
@@ -47,9 +46,9 @@ describe("community virtualizer direct DOM contract", () => {
const serverSettings = readComponent("../settings/server-settings.tsx")
expect(serverSettings).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")
- expect(serverSettings).toContain("ref={rowVirtualizer.containerRef}")
- expect(serverSettings).toContain("ref={rowVirtualizer.measureElement}")
- expect(serverSettings).toContain("getItemKey: (index) => members[index]?.id ?? index")
+ expect(serverSettings).toContain("<VirtualRows")
+ expect(serverSettings).toContain("virtualizer={rowVirtualizer}")
+ expect(serverSettings).toContain("useCallback((index: number) => members[index]?.id ?? index, [members])")
expect(serverSettings).not.toContain("rowVirtualizer.getTotalSize()")
expect(serverSettings).not.toContain("virtualRow.start")
})
diff --git a/src/web/src/components/community/settings/server-settings.tsx b/src/web/src/components/community/settings/server-settings.tsx
index cff1993e7..6a1d253f9 100644
--- a/src/web/src/components/community/settings/server-settings.tsx
+++ b/src/web/src/components/community/settings/server-settings.tsx
@@ -3,7 +3,7 @@
import { useObservedRegion } from "@/lib/observability/regions"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useRef } from "react"
+import { useCallback, useEffect, useRef } from "react"
import { useVirtualizer } from "@tanstack/react-virtual"
import { Settings, Users, Link2, Bell, Trash2, X, Shield, Search, Camera, Hash } from "lucide-react"
import {
@@ -40,6 +40,7 @@ import {
} from "@/hooks/community/use-notification-settings"
import { toastApiError } from "@/lib/api/client"
import { ServerSettingsChannels } from "./server-settings-channels"
+import { VirtualRows } from "../messages/virtual-cursor-list"
const SETTABLE_ROLES: Role[] = ["admin", "member"]
@@ -118,7 +119,7 @@ export function ServerSettings({
>
<SettingsShellPanel value="overview"><SettingsOverview serverId={serverId} serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} onRequestDelete={() => setConfirmDelete(true)} /></SettingsShellPanel>
{isAdmin && section === "channels" && <SettingsShellPanel value="channels"><ServerSettingsChannels key={serverId} serverId={serverId} /></SettingsShellPanel>}
- <SettingsShellPanel value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></SettingsShellPanel>
+ <SettingsShellPanel value="members" className="h-full"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></SettingsShellPanel>
<SettingsShellPanel value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></SettingsShellPanel>
<SettingsShellPanel value="notifications"><SettingsNotifications serverId={serverId} level={notifLevel} onSetLevel={onSetNotifLevel} /></SettingsShellPanel>
</SettingsShell>
@@ -229,6 +230,8 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
const [query, setQuery] = useAtom(useCreateAtom(""))
const scrollRef = useRef<HTMLDivElement>(null)
const sentinelRef = useRef<HTMLDivElement>(null)
+ const getItemKey = useCallback((index: number) => members[index]?.id ?? index, [members])
+ const estimateSize = useCallback(() => SETTINGS_ROW_HEIGHT, [])
useEffect(() => {
if (!onSearch) return
@@ -242,8 +245,8 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
count: members.length,
getScrollElement: () => scrollRef.current,
- getItemKey: (index) => members[index]?.id ?? index,
- estimateSize: () => SETTINGS_ROW_HEIGHT,
+ getItemKey,
+ estimateSize,
overscan: 8,
})
@@ -289,55 +292,43 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
{query ? `${members.length} matches` : `${shownCount} members`}
</div>
<div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto thin-scrollbar">
- <div ref={rowVirtualizer.containerRef} style={{ position: "relative", width: "100%" }}>
- {rowVirtualizer.getVirtualItems().map((virtualRow) => {
- const m = members[virtualRow.index]
- return (
- <div
- key={m.id}
- role="listitem"
- data-index={virtualRow.index}
- ref={rowVirtualizer.measureElement}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- paddingBottom: 8,
- }}
- >
- <div className="flex items-center gap-3 rounded-md px-2 py-2 transition-colors hover:bg-accent/40">
- <button onClick={(e) => onOpenProfile?.(m.name, e, undefined, m.userId)} className="grid size-11 shrink-0 place-items-center rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-8">
- <Avatar label={m.avatar} seed={m.userId} size={32} presence={m.status} ringColor="var(--background)" />
- </button>
- <div className="min-w-0 flex-1">
- <div className="truncate text-[15px] font-medium">{m.name}</div>
- <div className="text-xs text-muted-foreground">{capitalize(m.role)}</div>
- </div>
- {isServerOwner(m.role) ? (
- <Badge variant="secondary" className="gap-1"><Shield className="size-3.5" /> Owner</Badge>
- ) : (
- <DropdownMenu>
- <DropdownMenuTrigger
- render={<button className={badgeVariants({ variant: "secondary" }) + " min-h-11 cursor-pointer gap-1 sm:min-h-6"} />}
- >
- <Shield className="size-3.5" /> {capitalize(m.role)}
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-32">
- {SETTABLE_ROLES.map((r) => (
- <DropdownMenuItem key={r} onClick={() => onSetRole?.(m.id, r)}>{capitalize(r)}</DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- {m.role !== "owner" && (
- <Button variant="ghost" size="icon-sm" className="size-11 text-muted-foreground hover:text-destructive sm:size-7" aria-label="Kick member" onClick={() => onKickMember?.(m.id)}><Trash2 className="size-4" /></Button>
- )}
+ <VirtualRows
+ items={members}
+ virtualizer={rowVirtualizer}
+ rowRole="listitem"
+ renderItem={(m) => (
+ <div className="pb-2">
+ <div className="flex items-center gap-3 rounded-md px-2 py-2 transition-colors hover:bg-accent/40">
+ <button onClick={(e) => onOpenProfile?.(m.name, e, undefined, m.userId)} className="grid size-11 shrink-0 place-items-center rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-8">
+ <Avatar label={m.avatar} seed={m.userId} size={32} presence={m.status} ringColor="var(--background)" />
+ </button>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[15px] font-medium">{m.name}</div>
+ <div className="text-xs text-muted-foreground">{capitalize(m.role)}</div>
</div>
+ {isServerOwner(m.role) ? (
+ <Badge variant="secondary" className="gap-1"><Shield className="size-3.5" /> Owner</Badge>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={<button className={badgeVariants({ variant: "secondary" }) + " min-h-11 cursor-pointer gap-1 sm:min-h-6"} />}
+ >
+ <Shield className="size-3.5" /> {capitalize(m.role)}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-32">
+ {SETTABLE_ROLES.map((r) => (
+ <DropdownMenuItem key={r} onClick={() => onSetRole?.(m.id, r)}>{capitalize(r)}</DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {m.role !== "owner" && (
+ <Button variant="ghost" size="icon-sm" className="size-11 text-muted-foreground hover:text-destructive sm:size-7" aria-label="Kick member" onClick={() => onKickMember?.(m.id)}><Trash2 className="size-4" /></Button>
+ )}
</div>
- )
- })}
- </div>
+ </div>
+ )}
+ />
{hasMore && (
<div ref={sentinelRef} className="py-3 text-center text-xs text-muted-foreground">
{loadingMore ? "Loading…" : ""}
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
index b496331f2..152b3e329 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -30,6 +30,7 @@ import { useCurrentUser } from "@/contexts/community/current-user"
import {
useServer,
useServers,
+ useViewerServerRole,
serverProjectedQueryFn,
} from "@/hooks/community/use-servers"
import { useServerMembers } from "@/hooks/community/use-server-members"
@@ -141,10 +142,7 @@ function ServerSidebar({ serverId }: { serverId: string }) {
}),
[currentUser.id, membersHook.members, profilesByUserId],
)
- // `myMember` comes from the raw (not enriched) members list so this stays
- // stable across presence ticks.
- const myMember = membersHook.members.find((m) => m.userId === currentUser.id)
- const isAdmin = canManageServer(myMember?.role)
+ const isAdmin = canManageServer(useViewerServerRole(serverId, currentUser.id))
usePresence(currentServer ? serverId : null)
const notifs = useNotificationSettings()
const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])
diff --git a/src/web/src/components/community/social/community-invite-card.test.ts b/src/web/src/components/community/social/community-invite-card.test.ts
index 5713187bb..f8f979081 100644
--- a/src/web/src/components/community/social/community-invite-card.test.ts
+++ b/src/web/src/components/community/social/community-invite-card.test.ts
@@ -42,7 +42,6 @@ describe("resolveInviteCardPresentation", () => {
describe("invite-card perspective wiring", () => {
it("keeps loading on the real three-line text footprint", () => {
const card = readComponent("community-invite-card.tsx")
- expect(card).toContain('className="min-w-0 flex-1 space-y-1"')
expect(card).toContain('className="h-3 w-32 rounded"')
expect(card).toContain('className="h-4 w-24 rounded"')
expect(card).toContain('className="h-3 w-16 rounded"')
diff --git a/src/web/src/components/community/social/community-invite-card.tsx b/src/web/src/components/community/social/community-invite-card.tsx
index 142aa9d02..5f68570ea 100644
--- a/src/web/src/components/community/social/community-invite-card.tsx
+++ b/src/web/src/components/community/social/community-invite-card.tsx
@@ -80,12 +80,7 @@ export function CommunityInviteCard({
}
}
- // Border keeps the card visually distinct from the message row's hover
- // highlight (`bg-accent/40`), which sits very close to `bg-card`. The
- // parent MessageBody wraps the card in `pt-2 pb-2` so hover highlight
- // extends below the card — a bare `mb-*` on the card wouldn't do that
- // (it'd push the card out of the highlighted area instead).
- const cardBase = "flex max-w-100 items-center gap-3 rounded-md border border-border bg-card p-3"
+ const cardBase = "flex max-w-100 items-center gap-2 rounded-md border border-border bg-card p-2"
if (isLoading) {
return (
@@ -95,7 +90,7 @@ export function CommunityInviteCard({
data-perspective={perspective}
>
<Skeleton className="size-12 shrink-0 rounded-lg" />
- <div className="min-w-0 flex-1 space-y-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<Skeleton className="h-3 w-32 rounded" />
<Skeleton className="h-4 w-24 rounded" />
<Skeleton className="h-3 w-16 rounded" />
@@ -131,7 +126,7 @@ export function CommunityInviteCard({
size={48}
className="shrink-0 rounded-lg"
/>
- <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="text-xs font-medium text-muted-foreground">
{presentation.eyebrow}
</div>
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index 28e7fe4ce..ea7aa6369 100644
--- a/src/web/src/hooks/community/use-bot-audit-log.ts
+++ b/src/web/src/hooks/community/use-bot-audit-log.ts
@@ -134,5 +134,6 @@ export function useBotAuditLog(botId: string | null | undefined) {
fetchNextPage: query.fetchNextPage,
hasNextPage: query.hasNextPage,
isFetchingNextPage: query.isFetchingNextPage,
+ loadedPageCount: query.data?.pages.length ?? 0,
}
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.dom.test.ts
index b5ed81ecf..e9df6b695 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.compensate-delta.dom.test.ts
@@ -38,7 +38,7 @@ describe("locked native iOS deferred adjustment controls, with simulated DOM geo
expect(h.root.scrollTop - before).toBe(60)
expect(offset).not.toHaveBeenCalled()
})
- it("drops an old prefix candidate when a new gesture chooses a different reading offset", () => {
+ it("flushes independent leading-row growth against the new reading offset through native iOS deferral", () => {
scrollFixture.bodyHeights.set("m0", 1200)
const h = mount()
h.move(400)
@@ -51,7 +51,7 @@ describe("locked native iOS deferred adjustment controls, with simulated DOM geo
fireEvent.touchEnd(h.root, { touches: [] })
runFrames()
expect(offset).not.toHaveBeenCalled()
- expect(h.root.scrollTop).toBe(600)
+ expect(h.root.scrollTop).toBe(640)
expect(bodyTop(h.root, "m0")).toBeLessThan(0)
})
it("yields footer settlement during touch and does not restore an old offset after the gesture", () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
index 40be46da3..db7defac6 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
@@ -6,6 +6,60 @@ beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
describe("locked native adapter and existing message scroll owner", () => {
+ it("does not restore the old origin after a reader scroll with a rejected pending row position", () => {
+ const h = mount({ items: Array.from({ length: 28 }, (_, i) => message(`m${i}`)) })
+ h.move(0)
+ fireEvent.wheel(h.root, { deltaY: 600 })
+ runFrames(2)
+ const rows = Array.from(h.root.querySelectorAll<HTMLElement>("[data-index]"))
+ for (const row of rows) {
+ const measured = row.getBoundingClientRect.bind(row)
+ Object.defineProperty(row, "getBoundingClientRect", {
+ configurable: true,
+ value: () => {
+ const rect = measured()
+ return DOMRect.fromRect({ x: rect.x, y: rect.y + 8, width: rect.width, height: rect.height })
+ },
+ })
+ }
+ const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ act(() => h.root.scrollTo({ top: 600 }))
+ runFrames(2)
+ expect(h.root.scrollTop).toBe(600)
+ scrollFixture.firstPrefix += 8
+ for (const row of rows) Reflect.deleteProperty(row, "getBoundingClientRect")
+ resize()
+ expect(h.root.scrollTop).toBe(608)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(offset).not.toHaveBeenCalled()
+ })
+ it.each([undefined, "Today"])("uses the native border box for an unread divider with date label %s", dateLabel => {
+ const unread = message("m0")
+ unread.newDivider = true
+ unread.dateLabel = dateLabel
+ const h = mount({ items: [unread], hasMoreOlder: false })
+ const divider = h.root.querySelector<HTMLElement>("[data-message-divider-for]")!.closest<HTMLElement>("[data-index]")!
+ Object.defineProperty(divider, "scrollHeight", { configurable: true, value: 18 })
+ const entry = {
+ target: divider,
+ borderBoxSize: [{ blockSize: 16, inlineSize: scrollFixture.width }],
+ } as unknown as ResizeObserverEntry
+ const native = scrollFixture.latest.virtualizer
+
+ expect(native.options.measureElement(divider, entry, native)).toBe(16)
+ })
+ it("retains message body overflow when the native border box is smaller", () => {
+ const h = mount({ items: [message("m0")], hasMoreOlder: false })
+ const row = h.root.querySelector<HTMLElement>("[data-msg-id]")!.closest<HTMLElement>("[data-index]")!
+ Object.defineProperty(row, "scrollHeight", { configurable: true, value: 967 })
+ const entry = {
+ target: row,
+ borderBoxSize: [{ blockSize: 400, inlineSize: scrollFixture.width }],
+ } as unknown as ResizeObserverEntry
+ const native = scrollFixture.latest.virtualizer
+
+ expect(native.options.measureElement(row, entry, native)).toBe(967)
+ })
it.each([2, 26])("keeps a present landing after %i frames through consecutive responsive widths", frames => {
scrollFixture.width = 905
scrollFixture.height = 783
@@ -26,7 +80,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.belowCount).toBe(0)
})
- it("keeps a landed present intent unreadable until its native row geometry can be confirmed", () => {
+ it.each(["scroll", "measurement"])("retries rejected Present geometry within two frames on an unchanged-viewport %s event", event => {
const h = mount()
h.move(0)
act(() => scrollFixture.latest.scrollToBottom())
@@ -37,11 +91,42 @@ describe("locked native adapter and existing message scroll owner", () => {
runFrames(3)
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.readPositionReady).toBe(false)
+ runFrames(400)
+ expect(scrollFixture.frames.size).toBe(0)
for (const row of pending) Reflect.deleteProperty(row, "getBoundingClientRect")
- resize()
+ act(() => {
+ if (event === "scroll") fireEvent.scroll(h.root)
+ else {
+ const row = pending.find(row => row.querySelector('[data-msg-id="m13"]'))!
+ scrollFixture.bodyHeights.set("m13", 101)
+ scrollFixture.latest.virtualizer.measureElement(row)
+ }
+ })
+ runFrames(2)
expect(scrollFixture.latest.readPositionReady).toBe(true)
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
})
+ it("uses auto for loaded-tail Present without the old timeout or pure viewport end reissue", () => {
+ const h = mount()
+ h.move(0)
+ const native = scrollFixture.latest.virtualizer
+ const end = vi.spyOn(native, "scrollToEnd")
+ const offset = vi.spyOn(native, "scrollToOffset")
+ vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
+ act(() => scrollFixture.latest.scrollToBottom())
+ runFrames(3)
+ expect(end).toHaveBeenCalledExactlyOnceWith({ behavior: "auto" })
+ runFrames(400)
+ expect(scrollFixture.frames.size).toBe(0)
+ scrollFixture.width = 390
+ resize(2)
+ expect(end).toHaveBeenCalledTimes(1)
+ act(() => vi.advanceTimersByTime(2100))
+ expect(offset).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ fireEvent.wheel(h.root, { deltaY: -20 })
+ expect(offset).toHaveBeenCalledOnce()
+ })
it("keeps an explicit tail scroll when wrapped offscreen rows receive their later native measurements", () => {
scrollFixture.width = 639
scrollFixture.height = 736
@@ -188,13 +273,13 @@ describe("locked native adapter and existing message scroll owner", () => {
it("unifies native total and DOM max while keeping 40/48px rail clearance", () => {
const h = mount()
expect(scrollFixture.latest.readPositionReady).toBe(true)
- expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "end", followOnAppend: false, scrollEndThreshold: 1, scrollMargin: 0, paddingEnd: 48 })
+ expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "end", followOnAppend: false, scrollEndThreshold: 1, scrollMargin: 0, paddingEnd: 40 })
expect(h.root.scrollHeight).toBe(scrollFixture.latest.virtualizer.getTotalSize())
expect(h.root.scrollTop).toBe(h.root.scrollHeight - scrollFixture.height)
h.update({ tailPaddingEnd: 40 })
expect(h.root.scrollHeight).toBe(scrollFixture.latest.virtualizer.getTotalSize())
})
- it("centers the actual New prefix of a long message with one business correction", () => {
+ it("centers the independent New row beside a long message with the native index command", () => {
scrollFixture.bodyHeights.set("m4", 1800)
const items = Array.from({ length: 12 }, (_, i) => ({ ...message(`m${i}`), ...(i === 4 ? { newDivider: true } : {}) }))
const h = mount({ items, newDividerBefore: "m4", hasMoreNewer: true })
@@ -222,6 +307,7 @@ describe("locked native adapter and existing message scroll owner", () => {
runFrames()
expect(shown).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
expect(scrollFixture.latest.virtualizer.options.anchorTo).toBe("start")
const before = h.root.scrollTop
h.update({ items: [...h.input.items, message("late-peer")] })
@@ -230,6 +316,51 @@ describe("locked native adapter and existing message scroll owner", () => {
h.move(300)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
+ it("preserves and settles a prefix page after deadline retirement without opening read or peer follow", () => {
+ const h = mount({ initialScrollReady: false, hasMoreNewer: true })
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ act(() => vi.advanceTimersByTime(2000))
+ runFrames()
+ act(() => h.root.scrollTo({ top: 0 }))
+ resize()
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ scrollFixture.firstPrefix += 40
+ resize()
+ const before = bodyTop(h.root, "m0")
+ h.update({ items: [message("older-0"), message("older-1"), message("older-2"), ...h.input.items], isFetchingOlder: false })
+ expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })
+ })
+ it.each(["m0", "m1"])("uses native row anchoring when the pending page reaches %s with an unchanged body inset", id => {
+ const h = mount({ initialScrollReady: false, hasMoreNewer: true })
+ act(() => vi.advanceTimersByTime(2000))
+ runFrames()
+ act(() => h.root.scrollTo({ top: 0 }))
+ resize()
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "end", followOnAppend: false })
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const row = scrollFixture.latest.virtualizer.getVirtualItems().find(item => item.key === `msg:${id}`)!
+ act(() => h.root.scrollTo({ top: row.start + 30 }))
+ resize()
+ const before = bodyTop(h.root, id)
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ items: [message("older-0"), message("older-1"), message("older-2"), ...h.input.items], isFetchingOlder: false })
+ expect(bodyTop(h.root, id)).toBeCloseTo(before, 0)
+ expect(index).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })
+ const settledOffset = h.root.scrollTop
+ h.update({ items: [...h.input.items, message("late-peer")] })
+ expect(h.root.scrollTop).toBe(settledOffset)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ })
it("does not let pagination retire an unresolved initial intent or its deadline", () => {
const shown = vi.fn()
const h = mount({ initialScrollReady: false, hasMoreNewer: true, onInitialPositionSettled: shown })
@@ -255,7 +386,138 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(offset).not.toHaveBeenCalled()
expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
})
- it("repairs only the current message prefix when an old first row loses its header", () => {
+ it("keeps quote smooth on the native index command without a per-frame offset rewrite", () => {
+ const h = mount()
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ act(() => scrollFixture.latest.jumpTo("m5", "smooth"))
+ runFrames()
+ expect(index).toHaveBeenCalledWith(6, { align: "center", behavior: "smooth" })
+ expect(offset).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+ it("keeps the header-fold message when the newly inserted preceding row grows during native restore", () => {
+ const h = mount()
+ h.move(0)
+ const top = bodyTop(h.root, "m0")
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ resize(2)
+ expect(bodyTop(h.root, "m0")).toBe(top)
+ scrollFixture.bodyHeights.set("older-29", 108)
+ resize()
+ expect(bodyTop(h.root, "m0")).toBe(top)
+ })
+ it.each([-24, 40])("captures the current old-window position after a pending prefix change of %ipx", delta => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ scrollFixture.firstPrefix += delta
+ resize()
+ const currentTop = bodyTop(h.root, "m0")
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ expect(bodyTop(h.root, "m0")).toBe(currentTop)
+ })
+ it("keeps the page settlement gate after the fetch ends until native geometry settles", () => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
+ resize(2)
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
+ runFrames()
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ })
+ it.each(["wheel", "target"])("retires a pending header page when %s takes ownership before the response", input => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
+ if (input === "wheel") h.move(350)
+ else {
+ act(() => scrollFixture.latest.jumpTo("m8", "auto"))
+ runFrames()
+ }
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ const before = bodyTop(h.root, input === "wheel" ? "m3" : "m8")
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ expect(bodyTop(h.root, input === "wheel" ? "m3" : "m8")).toBe(before)
+ expect(index).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
+ })
+ it("returns to native measurement policy when the header-fold restore settles", () => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ const readingTop = bodyTop(h.root, "older-29")
+ const restoredTop = bodyTop(h.root, "m0")
+ scrollFixture.bodyHeights.set("older-29", 108)
+ resize()
+ expect(bodyTop(h.root, "older-29")).toBe(readingTop)
+ expect(bodyTop(h.root, "m0")).toBe(restoredTop + 8)
+ })
+ it("lets the reader keep the new spanning row after taking over a header-fold restore", () => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ h.move(h.root.scrollTop)
+ const readingTop = bodyTop(h.root, "older-29")
+ const retiredTop = bodyTop(h.root, "m0")
+ scrollFixture.bodyHeights.set("older-29", 108)
+ resize()
+ expect(bodyTop(h.root, "older-29")).toBe(readingTop)
+ expect(bodyTop(h.root, "m0")).toBe(retiredTop + 8)
+ })
+ it("returns to native measurement policy when the captured header-fold message is removed", () => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ resize(2)
+ h.stage({ items: h.input.items.filter(item => item.m.id !== "m0") })
+ resize(0)
+ expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
+ runFrames()
+ const readingTop = bodyTop(h.root, "older-29")
+ const nextTop = bodyTop(h.root, "m1")
+ scrollFixture.bodyHeights.set("older-29", 108)
+ resize()
+ expect(bodyTop(h.root, "older-29")).toBe(readingTop)
+ expect(bodyTop(h.root, "m1")).toBe(nextTop + 8)
+ })
+ it("uses native measurement policy for a new quote target after a header-fold restore", () => {
+ const h = mount()
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ act(() => scrollFixture.latest.jumpTo("m10"))
+ runFrames()
+ const targetTop = bodyTop(h.root, "m10")
+ scrollFixture.bodyHeights.set("m5", 108)
+ resize()
+ expect(bodyTop(h.root, "m10")).toBe(targetTop)
+ })
+ it("keeps the old first message through native anchoring after independent rows prepend", () => {
scrollFixture.bodyHeights.set("m0", 1200)
const h = mount()
h.move(400)
@@ -263,7 +525,7 @@ describe("locked native adapter and existing message scroll owner", () => {
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
h.update({ items: [message("older"), ...h.input.items] })
expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
- expect(offset).toHaveBeenCalledTimes(1)
+ expect(offset).not.toHaveBeenCalled()
})
it.each(["wheel", "programmatic"])("retains the current first-row body when prepend finishes before %s scroll quiet", input => {
scrollFixture.bodyHeights.set("m0", 1200)
@@ -277,7 +539,7 @@ describe("locked native adapter and existing message scroll owner", () => {
h.stage({ isFetchingOlder: true })
h.update({ items: [message("older"), ...h.input.items], isFetchingOlder: false })
expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
- expect(offset).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
})
it.each(["peer", "me"])("follows a genuine %s append through later native tail measurement", author => {
const h = mount({ viewerUserId: "me" })
@@ -328,9 +590,9 @@ describe("locked native adapter and existing message scroll owner", () => {
scrollFixture.firstPrefix += 40
h.update({ items: [...h.input.items] })
expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
- expect(offset).toHaveBeenCalledTimes(1)
+ expect(offset).not.toHaveBeenCalled()
resize()
- expect(offset).toHaveBeenCalledTimes(1)
+ expect(offset).not.toHaveBeenCalled()
})
it.each([0, 1, 2])("keeps passive growth separate at %ipx from the end", distance => {
const h = mount()
@@ -712,7 +974,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.querySelector('[data-msg-id]')).toBeNull()
h.update({ items: [message("first")] })
expect(scrollFixture.latest.readPositionReady).toBe(true)
- expect(scrollFixture.latest.virtualizer.getVirtualItems().map(item => item.key)).toEqual(["msg:first"])
+ expect(scrollFixture.latest.virtualizer.getVirtualItems().map(item => item.key)).toEqual(["rail:leading", "msg:first"])
expect(h.root.scrollTop).toBe(0)
expect(scrollFixture.latest.virtualizer.getTotalSize()).toBe(scrollFixture.height)
})
@@ -756,8 +1018,8 @@ describe("locked native adapter and existing message scroll owner", () => {
scrollFixture.firstPrefix += 40
h.update({ items: [...h.input.items] })
expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)
- expect(offset).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
resize()
- expect(offset).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.ts
index 40545f78d..db4ce1ab3 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -18,11 +18,11 @@ import type { FlatItem } from "@/lib/community/message-list-items"
const msgs = (...ids: string[]): ScrollAnchorMessage[] => ids.map((id) => ({ id }))
describe("message rail tail geometry", () => {
- it("resolves the fixed 40px mobile and 48px desktop virtual tail", () => {
- expect(MESSAGE_RAIL_TAIL_PADDING_END_PX).toEqual({ mobile: 40, desktop: 48 })
- expect(resolveMessageRailTailPaddingEnd("mobile")).toBe(40)
- expect(resolveMessageRailTailPaddingEnd("desktop")).toBe(48)
- expect(resolveMessageRailTailPaddingEnd("unknown")).toBe(48)
+ it("counts the final row's 8px once in the 40px mobile and 48px desktop clearance", () => {
+ expect(MESSAGE_RAIL_TAIL_PADDING_END_PX).toEqual({ mobile: 32, desktop: 40 })
+ expect(resolveMessageRailTailPaddingEnd("mobile")).toBe(32)
+ expect(resolveMessageRailTailPaddingEnd("desktop")).toBe(40)
+ expect(resolveMessageRailTailPaddingEnd("unknown")).toBe(40)
})
})
@@ -352,12 +352,15 @@ describe("measureMessageRow", () => {
describe("findMountScrollTargetIndex", () => {
const items: FlatItem[] = [
+ { kind: "leading", key: "leading" },
{ kind: "message", m: { id: "m1", type: "chat", grouped: false }, key: "msg:m1" },
+ { kind: "divider", messageId: "m2", newDivider: true, key: "new:m2" },
{ kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
]
- it("finds the message owning New so native can mount its actual prefix", () => {
- expect(findMountScrollTargetIndex(items, "m2")).toBe(1)
+ it("selects the independent New index while a message target selects the actual body", () => {
+ expect(findMountScrollTargetIndex(items, "m2")).toBe(2)
+ expect(findMessageIndex(items, "m2")).toBe(3)
})
it("falls back to the message's own index when no new-divider item exists (e.g. first-visit anchoring on a non-self message with no divider rendered)", () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 35e4f77f1..085035f70 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -1,14 +1,14 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useCallback, useLayoutEffect, useMemo, useRef } from "react"
-import { useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
+import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"
-import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"
+import { estimateRowHeight, computeBelowCount, MESSAGE_ROW_VERTICAL_PADDING_PX, type FlatItem } from "@/lib/community/message-list-items"
export const INITIAL_POSITION_TIMEOUT_MS = 2_000
export const NEAR_BOTTOM_PX = 100
export const MESSAGE_RAIL_TAIL_PADDING_END_PX = {
- mobile: 40,
- desktop: 48,
+ mobile: 40 - MESSAGE_ROW_VERTICAL_PADDING_PX,
+ desktop: 48 - MESSAGE_ROW_VERTICAL_PADDING_PX,
} as const
export function resolveMessageRailTailPaddingEnd(
@@ -194,7 +194,8 @@ export function findMessageIndex(items: FlatItem[], messageId: string): number |
}
export function findMountScrollTargetIndex(items: FlatItem[], newDividerBefore: string): number | null {
- return findMessageIndex(items, newDividerBefore)
+ const divider = items.findIndex((item) => item.kind === "divider" && item.newDivider && item.messageId === newDividerBefore)
+ return divider >= 0 ? divider : findMessageIndex(items, newDividerBefore)
}
export function extractScrollAnchorMessages(items: FlatItem[]): ScrollAnchorMessage[] {
@@ -242,15 +243,15 @@ export function useScrollAnchor({
type: "unread" | "target" | "end"
id: string | null
index: number | null
- layout: string | null
stableFrames: number
behavior: ScrollBehavior
notifyTarget: boolean
+ loadedTailPresent: boolean
+ viewport: { width: number; height: number }
}
type Geometry = {
epoch: number
key: string | number | bigint
- prefix: number
itemStart: number
clientHeight: number
clientWidth: number
@@ -265,14 +266,22 @@ export function useScrollAnchor({
}
const scrollRef = useRef<HTMLDivElement>(null)
const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)
- const positionOwnerRef = useRef({ epoch: 0, kind: "initial" as Kind, active: true, nativeIndex: false })
- const [ownerKind, setOwnerKind] = useAtom(useCreateAtom<Kind>("initial"))
- const [nativeOriginKey, setNativeOriginKey] = useAtom(useCreateAtom<string | number | bigint | null>(null))
- const nativeOriginKeyRef = useRef<string | number | bigint | null>(null)
- const [readPositionReady, setReadPositionReady] = useAtom(useCreateAtom(false))
+ const positionOwnerRef = useRef({ epoch: 0, active: true, nativeIndex: false })
+ const positionKind = useCreateAtom<Kind>("initial")
+ const [ownerKind, setOwnerKind] = useAtom(positionKind)
+ const nativeOrigin = useCreateAtom<string | number | bigint | null>(null)
+ const [nativeOriginKey, setNativeOriginKey] = useAtom(nativeOrigin)
+ const readReady = useCreateAtom(false)
+ const [readPositionReady, setReadPositionReady] = useAtom(readReady)
const [shortGap, setShortGap] = useAtom(useCreateAtom(0))
const [paginationDirection, setPaginationDirection] = useAtom(useCreateAtom<"older" | "newer" | null>(null))
- const paginationRef = useRef<{ direction: "older" | "newer"; observed: boolean } | null>(null)
+ const paginationRef = useRef<{
+ direction: "older" | "newer"
+ phase: "pending" | "fetching" | "settling"
+ anchor?: { key: string; viewportOffset: number; bodyInset: number; header: boolean; firstKey: string; epoch: number }
+ } | null>(null)
+ const scrollPaddingStartRef = useRef(0)
+ const olderMeasurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)
const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
const initialRetiredRef = useRef(false)
const initialPositionSettledRef = useRef(false)
@@ -294,8 +303,6 @@ export function useScrollAnchor({
onTargetCancelledRef.current = onScrollTargetCancelled
const settleCallbackRef = useRef(onInitialPositionSettled)
settleCallbackRef.current = onInitialPositionSettled
- const readReadyRef = useRef(readPositionReady)
- readReadyRef.current = readPositionReady
const wasAtEndRef = useRef(false)
const userScrolledAwayRef = useRef(false)
const acceptedGeometryRef = useRef<Geometry | null>(null)
@@ -303,12 +310,11 @@ export function useScrollAnchor({
const geometryFrameRef = useRef<number | null>(null)
const scheduleGeometryRef = useRef<() => void>(() => {})
const reconcileViewportRef = useRef<() => void>(() => {})
- const userInputRef = useRef({ at: -Infinity, scrollAt: -Infinity, touch: false, pointers: new Set<number>(), handover: false })
+ const userInputRef = useRef({ touch: false, pointers: new Set<number>(), handover: false })
const tailKeyRef = useRef<string | null>(null)
const messages = useMemo(() => extractScrollAnchorMessages(items), [items])
const tailId = messages.at(-1)?.id ?? null
const holdNativeOrigin = useCallback((key: string | number | bigint | null) => {
- nativeOriginKeyRef.current = key
setNativeOriginKey(key)
const native = virtualizerRef.current
if (key !== null && native) native.setOptions({ ...native.options, anchorTo: "start" })
@@ -327,14 +333,28 @@ export function useScrollAnchor({
initialDeadlineRef.current = null
positionBudgetStartedRef.current = false
}, [])
+ const clearOlderMeasurementAnchor = useCallback(() => {
+ olderMeasurementAnchorRef.current = null
+ if (virtualizerRef.current) virtualizerRef.current.shouldAdjustScrollPositionOnItemSizeChange = undefined
+ }, [])
+ const adjustOlderMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item) => {
+ const anchor = olderMeasurementAnchorRef.current
+ const owner = positionOwnerRef.current
+ const index = anchor && anchor.epoch === owner.epoch && owner.active && positionKind.get() === "idle"
+ ? currentItemsRef.current.findIndex(row => row.key === anchor.key) : -1
+ return item.index < index
+ }, [positionKind])
const claimPosition = useCallback((kind: Kind) => {
const owner = positionOwnerRef.current
if (owner.nativeIndex && scrollRef.current) {
virtualizerRef.current?.scrollToOffset(scrollRef.current.scrollTop, { behavior: "auto" })
}
owner.nativeIndex = false
+ clearOlderMeasurementAnchor()
+ paginationRef.current = null
+ setPaginationDirection(null)
+ scrollPaddingStartRef.current = 0
owner.epoch += 1
- owner.kind = kind
setOwnerKind(kind)
cancelFrame()
clearBudget()
@@ -343,30 +363,29 @@ export function useScrollAnchor({
holdNativeOrigin(null)
geometrySampleRef.current = null
presentIntentEpochRef.current = null
- readReadyRef.current = false
setReadPositionReady(false)
return owner.epoch
- }, [cancelFrame, clearBudget, holdNativeOrigin, setOwnerKind, setReadPositionReady])
+ }, [cancelFrame, clearBudget, clearOlderMeasurementAnchor, holdNativeOrigin, setOwnerKind, setPaginationDirection, setReadPositionReady])
const retireInitialPosition = useCallback(() => {
initialRetiredRef.current = true
stateRef.current = { ...stateRef.current, didInitialScroll: true, didDividerConverge: true }
}, [])
const releasePosition = useCallback((userHandover = false) => {
const intent = semanticIntentRef.current
- const cancelledTarget = positionOwnerRef.current.kind === "target"
+ const cancelledTarget = positionKind.get() === "target"
? intent?.notifyTarget ? intent.id
: !intent && positionedTargetRef.current !== targetIntentRef.current ? targetIntentRef.current : null
: null
- const wasReadable = positionOwnerRef.current.kind === "idle" && readReadyRef.current
+ const wasReadable = positionKind.get() === "idle" && readReady.get()
claimPosition("idle")
- if (userHandover && wasReadable) { readReadyRef.current = true; setReadPositionReady(true) }
+ if (userHandover && wasReadable) setReadPositionReady(true)
retireInitialPosition()
positionedTargetRef.current = targetIntentRef.current
if (cancelledTarget) onTargetCancelledRef.current?.(cancelledTarget)
if (userHandover) userInputRef.current.handover = true
settlePresentation()
scheduleGeometryRef.current()
- }, [claimPosition, retireInitialPosition, setReadPositionReady, settlePresentation])
+ }, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
const armBudget = useCallback(() => {
if (positionBudgetStartedRef.current) return
positionBudgetStartedRef.current = true
@@ -378,28 +397,71 @@ export function useScrollAnchor({
}, [releasePosition])
+ const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {
+ const root = scrollRef.current
+ const native = virtualizerRef.current
+ if (!root || !native || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1) return null
+ const row = native.getVirtualItems().find(item => item.key === key)
+ if (!row) return null
+ const item = currentItemsRef.current[row.index]
+ const wrapper = root.querySelector<HTMLElement>(`[data-index="${row.index}"]`)
+ const body = wrapper?.querySelector<HTMLElement>("[data-msg-id]")
+ if (item?.kind !== "message" || item.key !== key
+ || !wrapper || !body || body.dataset.msgId !== item.m.id) return null
+ const rect = wrapper.getBoundingClientRect()
+ const offset = rect.top - root.getBoundingClientRect().top
+ if (rect.height <= 0 || Math.abs(offset + root.scrollTop - row.start) > 1) return null
+ const bodyInset = body.getBoundingClientRect().top - rect.top
+ return { viewportOffset: offset + bodyInset, bodyInset }
+ }, [])
+ const refreshPendingPageAnchor = useCallback(() => {
+ const page = paginationRef.current
+ const anchor = page?.anchor
+ if (!page || page.phase === "settling" || !anchor
+ || !positionOwnerRef.current.active || anchor.epoch !== positionOwnerRef.current.epoch
+ || positionKind.get() !== "idle"
+ || currentItemsRef.current.find(item => item.kind === "message")?.key !== anchor.firstKey) return
+ const native = virtualizerRef.current
+ const fold = native?.getVirtualItemForOffset(native.scrollOffset ?? 0)
+ if (fold && currentItemsRef.current[fold.index]?.kind === "message") {
+ if (String(fold.key) !== anchor.firstKey) {
+ page.anchor = undefined
+ return
+ }
+ }
+ if (fold) anchor.header = currentItemsRef.current[fold.index]?.kind !== "message"
+ const offset = readPageMessageGeometry(anchor.key)
+ if (offset !== null) Object.assign(anchor, offset)
+ }, [positionKind, readPageMessageGeometry])
const awaitingTarget = !!scrollToMessageId && positionedTargetRef.current !== scrollToMessageId
+ const getItemKey = useCallback((index: number) => items[index].key, [items])
+ const estimateSize = useCallback((index: number) => estimateRowHeight(items[index], !!hasMoreOlder), [items, hasMoreOlder])
// eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
const virtualizer = useVirtualizer({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
count: items.length,
getScrollElement: () => scrollRef.current,
- estimateSize: (index) => estimateRowHeight(items[index])
- + (index === 0 ? (hasMoreOlder ? 88 : 152) : 0)
- + (index === items.length - 1 && hasMoreNewer ? 56 : 0),
- measureElement: measureMessageRow,
- getItemKey: (index) => items[index].key,
- anchorTo: ownerKind === "idle" && readPositionReady && !awaitingTarget
- && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key || paginationDirection !== null) ? "end" : "start",
+ estimateSize,
+ measureElement: (element, entry, instance) => element.querySelector("[data-msg-id]")
+ ? measureMessageRow(element)
+ : measureElement(element, entry, instance),
+ getItemKey,
+ scrollPaddingStart: scrollPaddingStartRef.current,
+ anchorTo: ownerKind === "idle" && !awaitingTarget
+ && (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",
followOnAppend: false,
scrollEndThreshold: 1,
scrollMargin: 0,
paddingStart: shortGap,
paddingEnd: tailPaddingEnd,
overscan: 8,
- onChange: () => { reconcileViewportRef.current(); scheduleGeometryRef.current() },
+ onChange: () => { refreshPendingPageAnchor(); reconcileViewportRef.current(); scheduleGeometryRef.current() },
})
virtualizerRef.current = virtualizer
+ useLayoutEffect(() => {
+ const anchor = olderMeasurementAnchorRef.current
+ if (anchor && !items.some(item => item.key === anchor.key)) clearOlderMeasurementAnchor()
+ }, [clearOlderMeasurementAnchor, items])
const readGeometry = useCallback((viewportTransition = false): Geometry | null => {
const root = scrollRef.current
@@ -417,32 +479,33 @@ export function useScrollAnchor({
const total = native.getTotalSize()
const max = Math.max(0, root.scrollHeight - root.clientHeight)
if (root.scrollTop < 0 || root.scrollTop > max + 1) return null
- const virtualItems = native.getVirtualItems()
- const fold = [...virtualItems].reverse().find((item) => item.start <= root.scrollTop + 1) ?? virtualItems[0]
+ const fold = native.getVirtualItemForOffset(root.scrollTop + 1)
if (!fold) return null
const item = currentItemsRef.current[fold.index]
const wrapper = root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)
const body = wrapper?.querySelector<HTMLElement>("[data-msg-id]")
- if (!item || !wrapper || body?.dataset.msgId !== item.m.id || fold.key !== item.key) return null
+ if (!item || !wrapper || fold.key !== item.key) return null
+ if (item.kind === "message" ? body?.dataset.msgId !== item.m.id
+ : wrapper.querySelector<HTMLElement>("[data-message-row-key]")?.dataset.messageRowKey !== item.key) return null
const wrapperRect = wrapper.getBoundingClientRect()
- const bodyRect = body.getBoundingClientRect()
const viewport = root.getBoundingClientRect()
- if (wrapperRect.height <= 0 || bodyRect.height <= 0
+ if (wrapperRect.height <= 0
|| Math.abs(wrapperRect.height - fold.size) > 1
|| Math.abs(wrapperRect.top - viewport.top + root.scrollTop - fold.start) > 1) return null
return {
- epoch: owner.epoch, key: fold.key, prefix: bodyRect.top - wrapperRect.top,
+ epoch: owner.epoch, key: fold.key,
itemStart: fold.start, clientHeight: root.clientHeight, clientWidth: root.clientWidth,
outerHeight: root.offsetHeight, outerWidth: root.offsetWidth,
scrollHeight: root.scrollHeight, scrollTop: root.scrollTop,
total, paddingEnd: native.options.paddingEnd ?? 0,
- pinEligible: max - root.scrollTop <= 1 && !userScrolledAwayRef.current
- && nativeOriginKeyRef.current !== currentItemsRef.current[0]?.key,
+ pinEligible: native.isAtEnd(1) && !userScrolledAwayRef.current
+ && nativeOrigin.get() !== currentItemsRef.current[0]?.key,
isScrolling: native.isScrolling,
}
- }, [])
+ }, [nativeOrigin])
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
+ if (semanticIntentRef.current?.loadedTailPresent) semanticIntentRef.current.stableFrames = 0
const epoch = positionOwnerRef.current.epoch
const settle = () => {
const owner = positionOwnerRef.current
@@ -454,7 +517,7 @@ export function useScrollAnchor({
if (!intent || intent.epoch !== owner.epoch || !root || !native) return
const viewport = root.getBoundingClientRect()
if (root.clientHeight <= 0 || viewport.height <= 0) {
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
+ if (!intent.loadedTailPresent) initialSettleFrameRef.current = window.requestAnimationFrame(settle)
return
}
let landed = false
@@ -466,36 +529,28 @@ export function useScrollAnchor({
owner.nativeIndex = index >= 0
native.scrollToEnd({ behavior: intent.behavior })
}
- landed = Math.abs(root.scrollHeight - root.clientHeight - root.scrollTop) <= 1
+ landed = native.isAtEnd(1)
} else if (intent.id) {
- const index = findMessageIndex(currentItemsRef.current, intent.id)
+ const index = intent.type === "unread"
+ ? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
+ : findMessageIndex(currentItemsRef.current, intent.id)
if (index !== null && index !== intent.index) {
intent.index = index
- intent.layout = null
intent.stableFrames = 0
owner.nativeIndex = true
- native.scrollToIndex(index, { align: "center", behavior: "auto" })
+ native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
}
const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
.find((element) => element.dataset.msgId === intent.id)
const boundary = intent.type === "unread"
- ? row?.parentElement?.querySelector<HTMLElement>("[data-new-divider]")
+ ? Array.from(root.querySelectorAll<HTMLElement>("[data-message-divider-for]"))
+ .find((element) => element.dataset.messageDividerFor === intent.id)?.querySelector<HTMLElement>("[data-new-divider]") ?? row
: row
const rect = boundary?.getBoundingClientRect()
const body = row?.getBoundingClientRect()
if (rect && body && rect.height > 0 && body.height > 0) {
- const contentCenter = (rect.top + rect.bottom) / 2 - viewport.top + root.scrollTop
- const max = Math.max(0, root.scrollHeight - root.clientHeight)
- const targetOffset = Math.max(0, Math.min(contentCenter - viewport.height / 2, max))
- const layout = JSON.stringify([index, Math.round(contentCenter), max, viewport.height])
- if (intent.layout !== layout) {
- intent.layout = layout
- intent.stableFrames = 0
- const cancelNativeIndex = owner.nativeIndex
- owner.nativeIndex = false
- if (cancelNativeIndex || Math.abs(root.scrollTop - targetOffset) > 1) native.scrollToOffset(targetOffset, { behavior: "auto" })
- }
- landed = Math.abs(root.scrollTop - targetOffset) <= 1
+ const targetOffset = index === null ? undefined : native.getOffsetForIndex(index, "center")?.[0]
+ landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
&& body.bottom > viewport.top + 1 && body.top < viewport.bottom - 1
}
@@ -505,13 +560,11 @@ export function useScrollAnchor({
const geometry = intent.stableFrames >= 2 ? readGeometry() : null
if (geometry) {
settlePresentation()
- if (owner.kind === "initial" && !initialScrollReadyRef.current) return
+ if (positionKind.get() === "initial" && !initialScrollReadyRef.current) return
acceptedGeometryRef.current = geometry
semanticIntentRef.current = null
owner.nativeIndex = false
- owner.kind = "idle"
setOwnerKind("idle")
- readReadyRef.current = true
setReadPositionReady(true)
clearBudget()
if (intent.notifyTarget && intent.id) {
@@ -521,16 +574,22 @@ export function useScrollAnchor({
scheduleGeometryRef.current()
return
}
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
+ if (!intent.loadedTailPresent || (landed && intent.stableFrames < 2)) {
+ initialSettleFrameRef.current = window.requestAnimationFrame(settle)
+ }
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearBudget, holdNativeOrigin, readGeometry, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, setOwnerKind, setReadPositionReady, settlePresentation])
- const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false) => {
+ const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {
const owner = positionOwnerRef.current
const index = type === "end" ? currentItemsRef.current.length - 1
- : id ? findMessageIndex(currentItemsRef.current, id) : null
- semanticIntentRef.current = { epoch: owner.epoch, type, id, index, layout: null, stableFrames: 0, behavior, notifyTarget }
+ : id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id)
+ : findMessageIndex(currentItemsRef.current, id) : null
+ semanticIntentRef.current = {
+ epoch: owner.epoch, type, id, index, stableFrames: 0, behavior, notifyTarget, loadedTailPresent,
+ viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
+ }
if (type === "end") {
owner.nativeIndex = currentItemsRef.current.length > 0
virtualizerRef.current?.scrollToEnd({ behavior })
@@ -539,7 +598,7 @@ export function useScrollAnchor({
owner.nativeIndex = true
virtualizerRef.current?.scrollToIndex(index, { align: "center", behavior })
}
- armBudget()
+ if (!loadedTailPresent) armBudget()
scheduleInitialPositionSettled()
}, [armBudget, scheduleInitialPositionSettled])
@@ -549,8 +608,8 @@ export function useScrollAnchor({
owner.active = true
const intent = semanticIntentRef.current
if (intent && intent.epoch !== owner.epoch) {
- startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget)
- } else if (owner.kind === "present" && presentIntentEpochRef.current !== null) {
+ startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
+ } else if (positionKind.get() === "present" && presentIntentEpochRef.current !== null) {
presentIntentEpochRef.current = owner.epoch
armBudget()
}
@@ -559,19 +618,21 @@ export function useScrollAnchor({
owner.epoch += 1
if (owner.nativeIndex && root) virtualizerRef.current?.scrollToOffset(root.scrollTop, { behavior: "auto" })
owner.nativeIndex = false
+ clearOlderMeasurementAnchor()
+ paginationRef.current = null
cancelFrame()
clearBudget()
if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)
geometryFrameRef.current = null
}
- }, [armBudget, cancelFrame, clearBudget, startIntent])
+ }, [armBudget, cancelFrame, clearBudget, clearOlderMeasurementAnchor, positionKind, startIntent])
useLayoutEffect(() => {
const target = scrollToMessageId ?? null
if (targetIntentRef.current === target) return
targetIntentRef.current = target
if (!target) {
- if (positionOwnerRef.current.kind === "target") releasePosition()
+ if (positionKind.get() === "target") releasePosition()
positionedTargetRef.current = null
return
}
@@ -579,16 +640,16 @@ export function useScrollAnchor({
retireInitialPosition()
positionedTargetRef.current = null
if (items.length > 0) startIntent("target", target, "auto", true)
- }, [claimPosition, items.length, releasePosition, retireInitialPosition, scrollToMessageId, startIntent])
+ }, [claimPosition, items.length, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent])
useLayoutEffect(() => {
if (items.length === 0) return
const owner = positionOwnerRef.current
- if (owner.kind === "target") {
+ if (positionKind.get() === "target") {
if (!semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)
else scheduleInitialPositionSettled()
- } else if (owner.kind === "initial") armBudget()
- }, [armBudget, items, scheduleInitialPositionSettled, startIntent])
+ } else if (positionKind.get() === "initial") armBudget()
+ }, [armBudget, items, positionKind, scheduleInitialPositionSettled, startIntent])
const observeGeometry = useCallback((next: Geometry, scrollEvent = false) => {
const previous = acceptedGeometryRef.current
@@ -598,13 +659,13 @@ export function useScrollAnchor({
&& (previous.clientHeight !== next.clientHeight || previous.paddingEnd !== next.paddingEnd)
&& previous.scrollTop <= Math.max(0, next.scrollHeight - next.clientHeight) + 1
&& previous.scrollTop !== next.scrollTop
- if (positionOwnerRef.current.kind === "idle" && readReadyRef.current
+ if (positionKind.get() === "idle" && readReady.get()
&& (!previous || scrolledAfterResize || (previous.epoch === next.epoch
&& previous.clientHeight === next.clientHeight && previous.clientWidth === next.clientWidth
&& previous.scrollHeight === next.scrollHeight
&& previous.total === next.total && previous.paddingEnd === next.paddingEnd
&& previousFold?.start === previous.itemStart
- && (previous.key !== next.key || previous.prefix === next.prefix)))) {
+ ))) {
const unchangedPosition = previous?.epoch === next.epoch
&& previous.clientHeight === next.clientHeight && previous.clientWidth === next.clientWidth
&& previous.scrollHeight === next.scrollHeight
@@ -615,14 +676,14 @@ export function useScrollAnchor({
}
holdNativeOrigin(next.scrollTop <= 1 && !next.pinEligible ? currentItemsRef.current[0]?.key ?? null : null)
}
- }, [holdNativeOrigin])
+ }, [holdNativeOrigin, positionKind, readReady])
const reconcileGeometry = useCallback((viewportOnly = false) => {
const root = scrollRef.current
const native = virtualizerRef.current
const owner = positionOwnerRef.current
if (!owner.active || !root || !native) return false
- if (viewportOnly && (owner.kind !== "idle" || !readReadyRef.current
+ if (viewportOnly && (positionKind.get() !== "idle" || !readReady.get()
|| acceptedGeometryRef.current?.epoch !== owner.epoch
|| (acceptedGeometryRef.current.clientHeight === root.clientHeight
&& acceptedGeometryRef.current.clientWidth === root.clientWidth
@@ -633,7 +694,7 @@ export function useScrollAnchor({
setShortGap(gap)
return true
}
- if (owner.kind !== "idle" || (!readReadyRef.current && !userInputRef.current.handover)) return false
+ if (positionKind.get() !== "idle" || (!readReady.get() && !userInputRef.current.handover && !paginationRef.current)) return false
const next = readGeometry(viewportOnly)
if (next) observeGeometry(next)
const input = userInputRef.current
@@ -645,8 +706,7 @@ export function useScrollAnchor({
&& Math.abs(root.scrollTop - max) <= 1
if (input.touch || input.pointers.size > 0 || (native.isScrolling && !clampedByResize)
|| root.scrollTop < 0 || root.scrollTop > max + 1
- || performance.now() - input.at < 180
- || (!clampedByResize && performance.now() - input.scrollAt < 180)) return true
+ ) return true
if (!next) return native.getVirtualItems().length > 0
const virtualItems = native.getVirtualItems()
const value = JSON.stringify(next)
@@ -655,11 +715,9 @@ export function useScrollAnchor({
if (!viewportResized && geometrySampleRef.current.frames < 2) return true
let offset = root.scrollTop
let originHeld = false
- if (previous?.epoch === owner.epoch && readReadyRef.current) {
+ if (previous?.epoch === owner.epoch && readReady.get()) {
originHeld = !previous.pinEligible && previous.scrollTop <= 1
&& previous.key === currentItemsRef.current[0]?.key && previous.itemStart <= 1
- const prefixDelta = previous.key === next.key && !previous.pinEligible && !originHeld ? next.prefix - previous.prefix : 0
- offset += prefixDelta
if (originHeld) offset = previous.scrollTop
else if (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd) {
const previousFold = virtualItems.find((candidate) => candidate.key === previous.key)
@@ -674,7 +732,7 @@ export function useScrollAnchor({
nextScrollHeight: next.scrollHeight,
previousScrollTop: adjustedPreviousOffset,
})
- offset = resized.scrollTop + (resized.anchor === "start" ? prefixDelta : 0)
+ offset = resized.scrollTop
}
}
}
@@ -687,7 +745,6 @@ export function useScrollAnchor({
wasAtEndRef.current = max - offset <= NEAR_BOTTOM_PX
if (input.handover) {
input.handover = false
- readReadyRef.current = true
setReadPositionReady(true)
}
if (viewportResized && previous.pinEligible && previous.clientWidth !== next.clientWidth) {
@@ -696,9 +753,33 @@ export function useScrollAnchor({
return true
}
if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })
+ if (olderMeasurementAnchorRef.current) {
+ clearOlderMeasurementAnchor()
+ owner.nativeIndex = false
+ }
+ if (paginationRef.current?.phase === "settling") {
+ paginationRef.current = null
+ setPaginationDirection(null)
+ }
return false
- }, [holdNativeOrigin, observeGeometry, readGeometry, setReadPositionReady, setShortGap])
- reconcileViewportRef.current = () => { reconcileGeometry(true) }
+ }, [clearOlderMeasurementAnchor, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, setPaginationDirection, setReadPositionReady, setShortGap])
+ reconcileViewportRef.current = () => {
+ const intent = semanticIntentRef.current
+ const root = scrollRef.current
+ const native = virtualizerRef.current
+ if (intent && root && native && intent.epoch === positionOwnerRef.current.epoch
+ && (intent.viewport.width !== root.clientWidth || intent.viewport.height !== root.clientHeight)) {
+ intent.viewport = { width: root.clientWidth, height: root.clientHeight }
+ intent.stableFrames = 0
+ if (root.clientHeight > 0 && !intent.loadedTailPresent) {
+ if (intent.type === "end") native.scrollToEnd({ behavior: intent.behavior })
+ else if (intent.index !== null) native.scrollToIndex(intent.index, { align: "center", behavior: intent.behavior })
+ scheduleInitialPositionSettled()
+ }
+ }
+ if (intent?.loadedTailPresent) scheduleInitialPositionSettled()
+ reconcileGeometry(true)
+ }
const scheduleGeometry = useCallback(() => {
if (geometryFrameRef.current !== null || !positionOwnerRef.current.active) return
@@ -716,19 +797,18 @@ export function useScrollAnchor({
if (!root) return
const inputOwner = userInputRef.current
const onScroll = () => {
- const input = userInputRef.current
const previous = acceptedGeometryRef.current
const native = virtualizerRef.current
- if (positionOwnerRef.current.kind === "idle" && readReadyRef.current
+ if (positionKind.get() === "idle" && readReady.get()
&& previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop > 1
&& root.scrollTop <= 1 && root.scrollHeight - root.clientHeight > 1
&& Math.abs((native?.scrollOffset ?? 0) - root.scrollTop) <= 1) {
acceptedGeometryRef.current = null
holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
- } else if (positionOwnerRef.current.kind === "idle" && readReadyRef.current
+ } else if (positionKind.get() === "idle" && readReady.get()
&& previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop <= 1
- && nativeOriginKeyRef.current === currentItemsRef.current[0]?.key && root.scrollTop > 1
- && root.scrollHeight - root.clientHeight - root.scrollTop <= 1
+ && nativeOrigin.get() === currentItemsRef.current[0]?.key && root.scrollTop > 1
+ && native?.isAtEnd(1)
&& previous.clientHeight === root.clientHeight && previous.clientWidth === root.clientWidth
&& previous.scrollHeight === root.scrollHeight && previous.total === native?.getTotalSize()
&& previous.paddingEnd === (native?.options.paddingEnd ?? 0)
@@ -736,22 +816,22 @@ export function useScrollAnchor({
acceptedGeometryRef.current = null
holdNativeOrigin(null)
}
- const unchanged = previous?.epoch === positionOwnerRef.current.epoch
- && previous.clientHeight === root.clientHeight && previous.clientWidth === root.clientWidth
- && previous.scrollHeight === root.scrollHeight
- && virtualizerRef.current?.scrollOffset === previous.scrollTop
- && Math.abs(previous.scrollTop - root.scrollTop) <= 1
- if (!unchanged) input.scrollAt = performance.now()
reconcileGeometry(true)
- const distance = Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop)
- wasAtEndRef.current = distance <= NEAR_BOTTOM_PX
+ if (semanticIntentRef.current?.loadedTailPresent) scheduleInitialPositionSettled()
+ wasAtEndRef.current = native?.isAtEnd(NEAR_BOTTOM_PX) ?? false
if (wasAtEndRef.current) userScrolledAwayRef.current = false
const next = readGeometry()
if (next) observeGeometry(next, true)
+ else if (positionKind.get() === "idle" && readReady.get()
+ && previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop !== root.scrollTop
+ && previous.clientHeight === root.clientHeight && previous.clientWidth === root.clientWidth
+ && previous.paddingEnd === (native?.options.paddingEnd ?? 0)) {
+ acceptedGeometryRef.current = null
+ holdNativeOrigin(root.scrollTop <= 1 ? currentItemsRef.current[0]?.key ?? null : null)
+ }
scheduleGeometry()
}
const onUserIntent = () => {
- userInputRef.current.at = performance.now()
userScrolledAwayRef.current = true
releasePosition(true)
userScrolledAwayRef.current = true
@@ -762,16 +842,13 @@ export function useScrollAnchor({
if (["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)) onUserIntent()
}
const onTouchStart = () => { userInputRef.current.touch = true; onUserIntent() }
- const onTouchMove = () => { userInputRef.current.at = performance.now() }
const onTouchEnd = (event: TouchEvent) => {
userInputRef.current.touch = event.touches.length > 0
- userInputRef.current.at = performance.now()
scheduleGeometry()
}
const onPointerDown = (event: PointerEvent) => { userInputRef.current.pointers.add(event.pointerId); onUserIntent() }
const onPointerUp = (event: PointerEvent) => {
if (!userInputRef.current.pointers.delete(event.pointerId)) return
- userInputRef.current.at = performance.now()
scheduleGeometry()
}
const onBlur = () => {
@@ -783,26 +860,24 @@ export function useScrollAnchor({
root.addEventListener("wheel", onWheel, { passive: true })
root.addEventListener("keydown", onKeyDown)
root.addEventListener("touchstart", onTouchStart, { passive: true })
- root.addEventListener("touchmove", onTouchMove, { passive: true })
root.addEventListener("touchend", onTouchEnd, { passive: true })
root.addEventListener("touchcancel", onTouchEnd, { passive: true })
root.addEventListener("pointerdown", onPointerDown)
root.ownerDocument.addEventListener("pointerup", onPointerUp)
root.ownerDocument.addEventListener("pointercancel", onPointerUp)
root.ownerDocument.defaultView?.addEventListener("blur", onBlur)
- const ro = new ResizeObserver(() => { reconcileGeometry(true); scheduleGeometry() })
+ const ro = new ResizeObserver(() => { reconcileViewportRef.current(); scheduleGeometry() })
ro.observe(root)
const footer = root.closest<HTMLElement>('[data-slot="community-conversation-surface"]')
?.querySelector<HTMLElement>('[data-slot="community-conversation-footer"]')
const mo = footer && typeof MutationObserver !== "undefined"
- ? new MutationObserver(() => { reconcileGeometry(true); scheduleGeometry() }) : null
+ ? new MutationObserver(() => { reconcileViewportRef.current(); scheduleGeometry() }) : null
mo?.observe(footer!, { attributes: true, characterData: true, childList: true, subtree: true })
return () => {
root.removeEventListener("scroll", onScroll)
root.removeEventListener("wheel", onWheel)
root.removeEventListener("keydown", onKeyDown)
root.removeEventListener("touchstart", onTouchStart)
- root.removeEventListener("touchmove", onTouchMove)
root.removeEventListener("touchend", onTouchEnd)
root.removeEventListener("touchcancel", onTouchEnd)
root.removeEventListener("pointerdown", onPointerDown)
@@ -814,31 +889,64 @@ export function useScrollAnchor({
inputOwner.touch = false
inputOwner.pointers.clear()
}
- }, [holdNativeOrigin, observeGeometry, readGeometry, reconcileGeometry, releasePosition, scheduleGeometry])
+ }, [holdNativeOrigin, nativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled])
const capturePageAnchor = useCallback((direction: "older" | "newer") => {
- if (positionOwnerRef.current.kind === "idle" && readReadyRef.current) {
+ clearOlderMeasurementAnchor()
+ let anchor: NonNullable<typeof paginationRef.current>["anchor"]
+ if (positionKind.get() === "idle") {
const geometry = readGeometry()
if (geometry) acceptedGeometryRef.current = geometry
+ const native = virtualizerRef.current
+ const offset = native?.scrollOffset ?? 0
+ const fold = native?.getVirtualItemForOffset(offset)
+ const first = currentItemsRef.current.find(item => item.kind === "message")
+ const header = !!fold && currentItemsRef.current[fold.index]?.kind !== "message"
+ if (direction === "older" && fold && (header || String(fold.key) === first?.key)) {
+ const message = native?.getVirtualItems().find(item => currentItemsRef.current[item.index]?.kind === "message" && item.end > offset)
+ const viewportOffset = message && readPageMessageGeometry(String(message.key))
+ if (message && first && viewportOffset !== null && viewportOffset !== undefined) anchor = {
+ key: String(message.key), ...viewportOffset, header,
+ firstKey: first.key, epoch: positionOwnerRef.current.epoch,
+ }
+ }
}
- paginationRef.current = { direction, observed: false }
+ paginationRef.current = { direction, phase: "pending", anchor }
setPaginationDirection(direction)
- }, [readGeometry, setPaginationDirection])
+ }, [clearOlderMeasurementAnchor, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
const captureOlderPageAnchor = useCallback(() => capturePageAnchor("older"), [capturePageAnchor])
const captureNewerPageAnchor = useCallback(() => capturePageAnchor("newer"), [capturePageAnchor])
useLayoutEffect(() => {
const page = paginationRef.current
- if (!page) return
+ if (!page || page.phase === "settling") return
const fetching = page.direction === "older" ? isFetchingOlder : isFetchingNewer
- if (fetching) { page.observed = true; return }
- if (!page.observed) return
- paginationRef.current = null
- setPaginationDirection(null)
+ if (fetching) { page.phase = "fetching"; return }
+ if (page.phase !== "fetching") return
+ page.phase = "settling"
+ geometrySampleRef.current = null
+ if (page.anchor && page.anchor.epoch === positionOwnerRef.current.epoch
+ && positionKind.get() === "idle"
+ && items.find(item => item.kind === "message")?.key !== page.anchor.firstKey) {
+ const index = items.findIndex(item => item.key === page.anchor?.key)
+ const item = items[index]
+ const native = virtualizerRef.current
+ const bodyInset = item?.kind === "message" ? item.paddingTop ?? page.anchor.bodyInset : page.anchor.bodyInset
+ if (index >= 0 && native && (page.anchor.header || bodyInset !== page.anchor.bodyInset)) {
+ olderMeasurementAnchorRef.current = { key: page.anchor.key, epoch: page.anchor.epoch }
+ native.shouldAdjustScrollPositionOnItemSizeChange = adjustOlderMeasurement
+ scrollPaddingStartRef.current = page.anchor.viewportOffset - bodyInset
+ native.setOptions({ ...native.options, scrollPaddingStart: scrollPaddingStartRef.current })
+ acceptedGeometryRef.current = null
+ holdNativeOrigin(null)
+ positionOwnerRef.current.nativeIndex = true
+ native.scrollToIndex(index, { align: "start" })
+ }
+ }
stateRef.current = { ...stateRef.current, lastTailId: tailId }
tailKeyRef.current = items.at(-1)?.key ?? null
scheduleInitialPositionSettled()
scheduleGeometry()
- }, [isFetchingNewer, isFetchingOlder, items, scheduleGeometry, scheduleInitialPositionSettled, setPaginationDirection, tailId])
+ }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled, tailId])
useLayoutEffect(() => {
if (!presentVersion || !tailId || hasMoreNewer || consumedPresentVersionRef.current === presentVersion) return
@@ -846,12 +954,12 @@ export function useScrollAnchor({
stateRef.current = { ...stateRef.current, lastTailId: tailId }
tailKeyRef.current = items.at(-1)?.key ?? null
const owner = positionOwnerRef.current
- if (!owner.active || owner.kind !== "present" || presentIntentEpochRef.current !== owner.epoch) return
+ if (!owner.active || positionKind.get() !== "present" || presentIntentEpochRef.current !== owner.epoch) return
presentIntentEpochRef.current = null
retireInitialPosition()
userScrolledAwayRef.current = false
startIntent("end", null)
- }, [hasMoreNewer, items, presentVersion, retireInitialPosition, startIntent, tailId])
+ }, [hasMoreNewer, items, positionKind, presentVersion, retireInitialPosition, startIntent, tailId])
const virtualItems = virtualizer.getVirtualItems()
useLayoutEffect(() => {
@@ -859,12 +967,12 @@ export function useScrollAnchor({
const root = scrollRef.current
const viewportReady = !!root && root.clientHeight > 0 && virtualItems.length > 0
&& !!root.querySelector("[data-index]")
- if (owner.kind === "target" || owner.kind === "present") {
+ if (positionKind.get() === "target" || positionKind.get() === "present") {
stateRef.current = { ...stateRef.current, lastTailId: tailId }
tailKeyRef.current = items.at(-1)?.key ?? null
return
}
- if (owner.kind === "initial" && stateRef.current.didInitialScroll) {
+ if (positionKind.get() === "initial" && stateRef.current.didInitialScroll) {
stateRef.current = { ...stateRef.current, lastTailId: tailId }
tailKeyRef.current = items.at(-1)?.key ?? null
if (!stateRef.current.didDividerConverge && initialScrollReady && viewportReady) {
@@ -891,18 +999,18 @@ export function useScrollAnchor({
? { ...nextState, didInitialScroll: true, didDividerConverge: true }
: nextState
tailKeyRef.current = nextTailKey
- if (action.type === "mount" && owner.kind === "initial") {
+ if (action.type === "mount" && positionKind.get() === "initial") {
startIntent(action.newDividerBefore ? "unread" : "end", action.newDividerBefore ?? null)
} else if (action.type === "scrollToEnd") {
- if (owner.kind === "initial") startIntent("end", null)
- else if (readReadyRef.current && previousTailKey !== nextTailKey) {
+ if (positionKind.get() === "initial") startIntent("end", null)
+ else if (readReady.get() && previousTailKey !== nextTailKey) {
claimPosition("present")
retireInitialPosition()
userScrolledAwayRef.current = false
startIntent("end", null)
}
} else if (semanticIntentRef.current) scheduleInitialPositionSettled()
- }, [claimPosition, hasMoreNewer, initialScrollReady, isFetchingNewer, items, messages, newDividerBefore, paginationDirection, retireInitialPosition, scheduleInitialPositionSettled, startIntent, tailId, viewerUserId, virtualItems, virtualizer])
+ }, [claimPosition, hasMoreNewer, initialScrollReady, isFetchingNewer, items, messages, newDividerBefore, paginationDirection, positionKind, readReady, retireInitialPosition, scheduleInitialPositionSettled, startIntent, tailId, viewerUserId, virtualItems, virtualizer])
const requestPresentPosition = useCallback(() => {
presentIntentEpochRef.current = claimPosition("present")
@@ -913,7 +1021,7 @@ export function useScrollAnchor({
claimPosition("present")
retireInitialPosition()
userScrolledAwayRef.current = false
- startIntent("end", null, "smooth")
+ startIntent("end", null, "auto", false, true)
}, [claimPosition, retireInitialPosition, startIntent])
const jumpTo = useCallback((messageId: string, behavior: ScrollBehavior = "smooth") => {
if (findMessageIndex(currentItemsRef.current, messageId) === null) return
@@ -926,10 +1034,10 @@ export function useScrollAnchor({
const lastVisibleIndex = root
? visibleItems.filter((item) => item.start < root.scrollTop + root.clientHeight).at(-1)?.index ?? -1
: -1
- const belowCount = root && root.scrollHeight - root.clientHeight - root.scrollTop <= NEAR_BOTTOM_PX
+ const belowCount = root && virtualizer.isAtEnd(NEAR_BOTTOM_PX)
? 0 : computeBelowCount(items, lastVisibleIndex)
return {
- scrollRef, virtualizer, readPositionReady, belowCount,
+ scrollRef, virtualizer, readPositionReady, paginationEnabled: ownerKind === "idle" && !awaitingTarget, belowCount,
scrollToBottom, requestPresentPosition, jumpTo,
captureOlderPageAnchor, captureNewerPageAnchor,
isOlderPageAnchorSettling: paginationDirection === "older",
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
new file mode 100644
index 000000000..141876be9
--- /dev/null
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
@@ -0,0 +1,142 @@
+import { createElement } from "react"
+import { describe, expect, it, vi } from "vitest"
+import type { VirtualItem } from "@tanstack/react-virtual"
+import { render } from "@/test/react-dom-harness"
+import { useVirtualCursorPagination } from "./use-virtual-cursor-pagination"
+
+type Props = Parameters<typeof useVirtualCursorPagination>[0]
+function Harness(props: Props) {
+ useVirtualCursorPagination(props)
+ return null
+}
+const range = (...indices: number[]): VirtualItem[] => indices.map(index => ({
+ index, key: index, start: index * 100, end: (index + 1) * 100, size: 100, lane: 0,
+}))
+
+describe.each(["start", "end"] as const)("native virtual cursor pagination (%s)", edge => {
+ function fixture(overrides: Partial<Props> = {}) {
+ let items = range(4, 5)
+ const onLoad = vi.fn()
+ const onBeforeLoad = vi.fn()
+ const base: Props = { edge, count: 10, hasMore: true, isFetching: false,
+ virtualizer: { getVirtualItems: () => items }, onLoad, onBeforeLoad, ...overrides }
+ const view = render(createElement(Harness, base))
+ return { base, view, onLoad, onBeforeLoad, setRange: (...indices: number[]) => { items = range(...indices) },
+ rerender: (next: Partial<Props> = {}) => view.rerender(createElement(Harness, { ...base, ...next })) }
+ }
+ const boundary = edge === "start" ? [0, 1] : [8, 9]
+
+ it("loads when the native range reaches the boundary, with anchor capture first", () => {
+ const f = fixture()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ expect(f.onBeforeLoad.mock.invocationCallOrder[0]).toBeLessThan(f.onLoad.mock.invocationCallOrder[0])
+ f.rerender()
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("rechecks a boundary reached while fetching after the request becomes idle", () => {
+ const f = fixture({ isFetching: true })
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ isFetching: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("can load another page without ending a physical scrolling gesture", () => {
+ const f = fixture()
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ f.rerender({ isFetching: true })
+ f.setRange(...(edge === "start" ? [0, 1] : [18, 19]))
+ f.rerender({ count: 20, isFetching: true })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ f.rerender({ count: 20, isFetching: false })
+ expect(f.onLoad).toHaveBeenCalledTimes(2)
+ })
+
+ it("waits for anchor settlement and then rechecks the current range", () => {
+ const f = fixture({ isSettling: true })
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ isSettling: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("does not replay demand after scrolling away during a request", () => {
+ const f = fixture()
+ f.setRange(...boundary)
+ f.rerender()
+ f.rerender({ isFetching: true })
+ f.setRange(4, 5)
+ f.rerender({ isFetching: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("keeps initial and target positioning separate from pagination", () => {
+ const f = fixture({ enabled: false })
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ enabled: true })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("stops when the cursor is exhausted and accepts a later available cursor", () => {
+ const f = fixture({ hasMore: false })
+ f.setRange(...boundary)
+ f.rerender()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ hasMore: true })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ f.rerender({ hasMore: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("ignores empty ranges, empty data and absent callbacks", () => {
+ const f = fixture()
+ f.setRange()
+ f.rerender()
+ f.setRange(...boundary)
+ f.rerender({ count: 0 })
+ f.rerender({ onLoad: undefined })
+ expect(f.onLoad).not.toHaveBeenCalled()
+ expect(f.onBeforeLoad).not.toHaveBeenCalled()
+ })
+
+ it("does not start a new fetch cycle after Query exhausts its retry policy", () => {
+ const f = fixture({ isFetching: true })
+ f.setRange(...boundary)
+ f.rerender()
+ f.rerender({ isFetching: false, isError: true })
+ f.setRange(...boundary)
+ f.rerender({ isFetching: false, isError: true })
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ isFetching: false, isError: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("requests one side of a short bidirectional window at a time", () => {
+ const f = fixture({ hasMoreAtStart: true })
+ f.setRange(0, 1, 8, 9)
+ f.rerender()
+ expect(f.onLoad).toHaveBeenCalledTimes(edge === "start" ? 1 : 0)
+ if (edge === "end") {
+ f.rerender({ hasMoreAtStart: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ }
+ })
+
+ it("has no pending input or observer work after unmount", () => {
+ const f = fixture({ isFetching: true })
+ f.setRange(...boundary)
+ f.rerender()
+ f.view.unmount()
+ expect(f.onLoad).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
new file mode 100644
index 000000000..71b2e4674
--- /dev/null
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
@@ -0,0 +1,31 @@
+"use client"
+
+import { useEffect } from "react"
+import type { VirtualItem } from "@tanstack/react-virtual"
+
+export function useVirtualCursorPagination({
+ virtualizer, count, enabled = true, hasMore, hasMoreAtStart, isFetching, isSettling, isError,
+ onBeforeLoad, onLoad, edge,
+}: {
+ virtualizer: { getVirtualItems: () => VirtualItem[] }
+ count: number
+ enabled?: boolean
+ hasMore?: boolean
+ hasMoreAtStart?: boolean
+ isFetching?: boolean
+ isSettling?: boolean
+ isError?: boolean
+ onBeforeLoad?: () => void
+ onLoad?: () => void
+ edge: "start" | "end"
+}) {
+ const virtualItems = virtualizer.getVirtualItems()
+ useEffect(() => {
+ const boundary = edge === "start" ? virtualItems[0] : virtualItems.at(-1)
+ if (!enabled || !boundary || count === 0 || !hasMore || isFetching || isSettling || isError || !onLoad) return
+ if (edge === "start" ? boundary.index > 0 : boundary.index < count - 1) return
+ if (edge === "end" && hasMoreAtStart && virtualItems[0]?.index === 0) return
+ onBeforeLoad?.()
+ onLoad()
+ }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isSettling, isError, onBeforeLoad, onLoad, virtualItems])
+}
diff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts
deleted file mode 100644
index 658bab832..000000000
--- a/src/web/src/hooks/community/use-virtual-cursor-sentinel.dom.test.ts
+++ /dev/null
@@ -1,364 +0,0 @@
-import { createElement, useCallback, useRef } from "react"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render } from "@/test/react-dom-harness"
-import { useVirtualCursorSentinel } from "./use-virtual-cursor-sentinel"
-
-type Props = {
- showSentinel?: boolean
- elementRevision?: number
- rootRevision?: number
- edge: "start" | "end"
- hasMore: boolean
- isFetching: boolean
- isSettling?: boolean
- onBeforeLoad?: () => void
- onLoad: () => void
-}
-
-let intersectionCallback: IntersectionObserverCallback
-let disconnect: ReturnType<typeof vi.fn>
-let observed: Element | undefined
-
-function Harness(props: Props) {
- const scrollRef = useRef<HTMLDivElement>(null)
- const sentinelRef = useVirtualCursorSentinel({ scrollRef, ...props })
- const bindRoot = useCallback((node: HTMLDivElement | null) => { scrollRef.current = node }, [])
- return createElement(
- "div",
- // eslint-disable-next-line react-hooks/refs -- React DOM invokes these ref callbacks during commit.
- { "data-testid": "scroll", key: props.rootRevision ?? 0, ref: bindRoot },
- props.showSentinel === false ? null : createElement("div", { "data-testid": "sentinel", key: props.elementRevision ?? 0, ref: sentinelRef }),
- )
-}
-
-function renderView(props: Props) {
- const rendered = render(createElement(Harness, props))
- return {
- rerender: (next: Props) => rendered.rerender(createElement(Harness, next)),
- unmount: rendered.unmount,
- }
-}
-
-function intersect(isIntersecting: boolean) {
- act(() => {
- intersectionCallback(
- [{ isIntersecting, target: observed } as IntersectionObserverEntry],
- {} as IntersectionObserver,
- )
- })
-}
-
-describe.each(["start", "end"] as const)("useVirtualCursorSentinel (%s edge)", (edge) => {
- beforeEach(() => {
- disconnect = vi.fn()
- observed = undefined
- class FakeIntersectionObserver {
- constructor(callback: IntersectionObserverCallback) {
- intersectionCallback = callback
- }
- observe(element: Element) { observed = element }
- disconnect() { disconnect() }
- }
- vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver)
- })
-
- afterEach(() => {
- vi.useRealTimers()
- vi.unstubAllGlobals()
- })
-
- it("loads on a true intersection and ignores false entries", () => {
- const onLoad = vi.fn()
- renderView({ edge, hasMore: true, isFetching: false, onLoad })
-
- intersect(false)
- expect(onLoad).not.toHaveBeenCalled()
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
- })
-
- it("drops input while busy and requires fresh same-direction input after settle", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const view = renderView({ edge, hasMore: true, isFetching: false, onLoad })
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
-
- view.rerender({ edge, hasMore: true, isFetching: true, onLoad })
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledOnce()
- view.rerender({ edge, hasMore: true, isFetching: false, onLoad })
- expect(onLoad).toHaveBeenCalledOnce()
-
- act(() => vi.advanceTimersByTime(181))
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("waits for anchor settlement before accepting the next demand", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const view = renderView({ edge, hasMore: true, isFetching: false, onLoad })
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
-
- view.rerender({ edge, hasMore: true, isFetching: true, onLoad })
- view.rerender({ edge, hasMore: true, isFetching: false, onLoad, isSettling: true })
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledOnce()
-
- view.rerender({ edge, hasMore: true, isFetching: false, onLoad, isSettling: false })
- act(() => vi.advanceTimersByTime(181))
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("does not accept a second page before the active touch gesture ends", () => {
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, isSettling: false, onLoad }
- const view = renderView(base)
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
-
- fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
-
- view.rerender({ ...base, isFetching: true, isSettling: true })
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })
- view.rerender(base)
-
- // This is still the same physical gesture: no touchend/new touchstart occurred.
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 160 : 40 }] })
- expect(onLoad).toHaveBeenCalledOnce()
-
- fireEvent.touchEnd(scroll, { touches: [] })
- fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("treats trackpad momentum as one wheel gesture until input goes idle", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- intersect(true)
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(2)
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -10 : 10 })
- expect(onLoad).toHaveBeenCalledTimes(2)
-
- act(() => vi.advanceTimersByTime(181))
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(3)
- })
-
- it("treats keyboard repeat as one key gesture until keyup", () => {
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const key = edge === "start" ? "PageUp" : "PageDown"
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- intersect(true)
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(2)
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- fireEvent.keyDown(scroll, { key, repeat: true })
- expect(onLoad).toHaveBeenCalledTimes(2)
-
- fireEvent.keyUp(scroll, { key })
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(3)
- })
-
- it("ignores navigation keys while focus is outside the scroller", () => {
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const key = edge === "start" ? "PageUp" : "PageDown"
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- const outside = document.createElement("button")
- document.body.append(outside)
- intersect(true)
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
-
- outside.focus()
- fireEvent.keyDown(outside, { key })
- expect(onLoad).toHaveBeenCalledOnce()
-
- scroll.tabIndex = -1
- scroll.focus()
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(2)
- outside.remove()
- })
-
- it("clears held key, touch, wheel, and timer state on window blur", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const key = edge === "start" ? "PageUp" : "PageDown"
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- intersect(true)
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
-
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? 20 : -20 })
- fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(2)
- expect(vi.getTimerCount()).toBe(1)
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
-
- act(() => window.dispatchEvent(new Event("blur")))
- expect(vi.getTimerCount()).toBe(0)
-
- // No keyup is needed after blur: the next press is a fresh gesture.
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(3)
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
-
- // The pre-blur touch no longer has a live coordinate, while wheel is fresh.
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })
- expect(onLoad).toHaveBeenCalledTimes(3)
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(4)
- })
-
- it("accepts only fresh input toward the active edge", () => {
- const calls: string[] = []
- const onBeforeLoad = () => calls.push("before")
- const onLoad = () => calls.push("load")
- const base = { edge, hasMore: true, isFetching: false, onBeforeLoad, onLoad }
- const view = renderView(base)
- intersect(true)
- expect(calls).toEqual(["before", "load"])
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? 20 : -20 })
- fireEvent.keyDown(scroll, { key: edge === "start" ? "ArrowDown" : "ArrowUp" })
- expect(calls).toHaveLength(2)
-
- fireEvent.keyDown(scroll, { key: edge === "start" ? "PageUp" : "PageDown" })
- expect(calls).toEqual(["before", "load", "before", "load"])
-
- view.rerender({ ...base, isFetching: true })
- view.rerender(base)
- fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })
- expect(calls).toEqual(["before", "load", "before", "load", "before", "load"])
- })
-
- it("clears pending demand when hasMore becomes false and disconnects on unmount", () => {
- const onLoad = vi.fn()
- const view = renderView({ edge, hasMore: true, isFetching: true, onLoad })
- intersect(true)
- view.rerender({ edge, hasMore: false, isFetching: false, onLoad })
- expect(onLoad).not.toHaveBeenCalled()
-
- view.unmount()
- expect(disconnect).toHaveBeenCalled()
- })
-
- it("preserves the demanded intersection and rejects the detached observer callback", () => {
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- intersect(true)
- const retiredCallback = intersectionCallback
- const retiredElement = observed
- view.rerender({ ...base, isFetching: true, showSentinel: false })
- view.rerender({ ...base, elementRevision: 1 })
- act(() => retiredCallback([{ isIntersecting: false, target: retiredElement } as IntersectionObserverEntry], {} as IntersectionObserver))
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
- intersect(false)
- intersect(true)
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("keeps the load locked through detach until its fetch is actually observed", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- intersect(true)
- view.rerender({ ...base, showSentinel: false })
- view.rerender({ ...base, elementRevision: 1 })
- intersect(false)
- intersect(true)
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledOnce()
- view.rerender({ ...base, isFetching: true, elementRevision: 1 })
- view.rerender({ ...base, elementRevision: 1 })
- act(() => vi.advanceTimersByTime(181))
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("preserves held keys, touch budget, and wheel idle timer across element replacement", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const scroll = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- const key = edge === "start" ? "PageUp" : "PageDown"
- fireEvent.touchStart(scroll, { touches: [{ clientY: 100 }] })
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- fireEvent.keyDown(scroll, { key })
- intersect(true)
- view.rerender({ ...base, isFetching: true, showSentinel: false })
- view.rerender({ ...base, elementRevision: 1 })
- intersect(true)
- expect(vi.getTimerCount()).toBe(1)
- fireEvent.keyDown(scroll, { key })
- fireEvent.touchMove(scroll, { touches: [{ clientY: edge === "start" ? 130 : 70 }] })
- fireEvent.wheel(scroll, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledOnce()
- fireEvent.keyUp(scroll, { key })
- fireEvent.keyDown(scroll, { key })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-
- it("retires the root timer and gesture listeners when the actual scroller is replaced", () => {
- vi.useFakeTimers()
- const onLoad = vi.fn()
- const base = { edge, hasMore: true, isFetching: false, onLoad }
- const view = renderView(base)
- const oldRoot = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(oldRoot, { deltaY: edge === "start" ? 20 : -20 })
- expect(vi.getTimerCount()).toBe(1)
- view.rerender({ ...base, rootRevision: 1 })
- expect(vi.getTimerCount()).toBe(0)
- intersect(true)
- expect(onLoad).toHaveBeenCalledOnce()
- view.rerender({ ...base, rootRevision: 1, isFetching: true })
- view.rerender({ ...base, rootRevision: 1 })
- fireEvent.wheel(oldRoot, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledOnce()
- const current = document.querySelector<HTMLElement>('[data-testid="scroll"]')!
- fireEvent.wheel(current, { deltaY: edge === "start" ? -20 : 20 })
- expect(onLoad).toHaveBeenCalledTimes(2)
- })
-})
diff --git a/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts b/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts
deleted file mode 100644
index 077100b8a..000000000
--- a/src/web/src/hooks/community/use-virtual-cursor-sentinel.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-"use client"
-
-import { useCallback, useEffect, useLayoutEffect, useRef, type RefObject } from "react"
-import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store"
-
-const WHEEL_GESTURE_IDLE_MS = 180
-
-export function useVirtualCursorSentinel({
- scrollRef,
- hasMore,
- isFetching,
- isSettling,
- onBeforeLoad,
- onLoad,
- edge,
-}: {
- scrollRef: RefObject<HTMLElement | null>
- hasMore?: boolean
- isFetching?: boolean
- isSettling?: boolean
- onBeforeLoad?: () => void
- onLoad?: () => void
- edge: "start" | "end"
-}) {
- const [element, setElement] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
- const [root, setRoot] = useAtom(useCreateAtom<HTMLElement | null>(null))
- const consumeActiveGesturesRef = useRef<() => void>(() => {})
- const protocol = useCreateStore({ inputs: { onBeforeLoad, onLoad, hasMore, isFetching, isSettling }, intersecting: false, intersectionDemanded: false, loadLocked: false, fetchObserved: false })
- const sentinelRef = useCallback((node: HTMLDivElement | null) => { setElement(node) }, [setElement])
-
- useLayoutEffect(() => {
- setRoot(scrollRef.current)
- protocol.setState((state) => ({ ...state, inputs: { onBeforeLoad, onLoad, hasMore, isFetching, isSettling } }))
- const state = protocol.get()
- if (!hasMore) {
- protocol.setState((state) => ({ ...state, loadLocked: false, fetchObserved: false, intersectionDemanded: false }))
- } else if (isFetching && !state.fetchObserved) {
- protocol.setState((state) => ({ ...state, fetchObserved: true }))
- } else if (state.loadLocked && state.fetchObserved && !isFetching && !isSettling) {
- protocol.setState((state) => ({ ...state, loadLocked: false, fetchObserved: false }))
- }
- })
-
- const nearEdge = useCallback(() => !!root && (edge === "start"
- ? root.scrollTop <= 200
- : root.scrollHeight - root.clientHeight - root.scrollTop <= 200), [edge, root])
- const requestPage = useCallback((requireNearEdge: boolean) => {
- const state = protocol.get()
- if (state.loadLocked || !state.intersecting || (requireNearEdge && !nearEdge())
- || !state.inputs.onLoad || !state.inputs.hasMore || state.inputs.isFetching || state.inputs.isSettling) return
- protocol.setState((state) => ({ ...state, loadLocked: true, fetchObserved: false }))
- consumeActiveGesturesRef.current()
- state.inputs.onBeforeLoad?.()
- state.inputs.onLoad()
- }, [nearEdge, protocol])
-
- useEffect(() => {
- if (!root) return
- let touchY: number | null = null
- let touchDemanded = false
- let wheelGestureActive = false
- let wheelDemanded = false
- let wheelIdleTimer: ReturnType<typeof setTimeout> | undefined
- const heldKeys = new Set<string>()
- const finishWheelGesture = () => {
- wheelGestureActive = false
- wheelDemanded = false
- wheelIdleTimer = undefined
- }
- consumeActiveGesturesRef.current = () => {
- if (touchY !== null) touchDemanded = true
- if (wheelGestureActive) wheelDemanded = true
- }
- const onScroll = () => {
- if (!nearEdge()) protocol.setState((state) => ({ ...state, intersectionDemanded: false }))
- }
- const onWheel = (event: WheelEvent) => {
- if (!wheelGestureActive) { wheelGestureActive = true; wheelDemanded = false }
- if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)
- wheelIdleTimer = setTimeout(finishWheelGesture, WHEEL_GESTURE_IDLE_MS)
- const towardEdge = (edge === "start" && event.deltaY < 0) || (edge === "end" && event.deltaY > 0)
- if (towardEdge && !wheelDemanded) { wheelDemanded = true; requestPage(true) }
- }
- const onKeyDown = (event: KeyboardEvent) => {
- const active = root.ownerDocument.activeElement
- if (active && active !== root.ownerDocument.body && active !== root && !root.contains(active)) return
- const towardEdge = edge === "start"
- ? ["ArrowUp", "PageUp", "Home"].includes(event.key)
- : ["ArrowDown", "PageDown", "End"].includes(event.key)
- if (!towardEdge || event.repeat || heldKeys.has(event.key)) return
- heldKeys.add(event.key)
- requestPage(true)
- }
- const onKeyUp = (event: KeyboardEvent) => { heldKeys.delete(event.key) }
- const onTouchStart = (event: TouchEvent) => {
- if (touchY === null) touchDemanded = false
- touchY = event.touches[0]?.clientY ?? null
- }
- const onTouchMove = (event: TouchEvent) => {
- const nextY = event.touches[0]?.clientY ?? null
- if (touchY === null || nextY === null) return
- const delta = nextY - touchY
- touchY = nextY
- const towardEdge = (edge === "start" && delta > 0) || (edge === "end" && delta < 0)
- if (towardEdge && !touchDemanded) { touchDemanded = true; requestPage(true) }
- }
- const onTouchEnd = (event: TouchEvent) => {
- touchY = event.touches[0]?.clientY ?? null
- if (touchY === null) touchDemanded = false
- }
- const onWindowBlur = () => {
- heldKeys.clear()
- touchY = null
- touchDemanded = false
- if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)
- finishWheelGesture()
- }
- root.addEventListener("scroll", onScroll, { passive: true })
- root.addEventListener("wheel", onWheel, { passive: true })
- root.ownerDocument.addEventListener("keydown", onKeyDown)
- root.ownerDocument.addEventListener("keyup", onKeyUp)
- root.ownerDocument.defaultView?.addEventListener("blur", onWindowBlur)
- root.addEventListener("touchstart", onTouchStart, { passive: true })
- root.addEventListener("touchmove", onTouchMove, { passive: true })
- root.addEventListener("touchend", onTouchEnd, { passive: true })
- root.addEventListener("touchcancel", onTouchEnd, { passive: true })
- return () => {
- consumeActiveGesturesRef.current = () => {}
- protocol.setState((state) => ({ ...state, intersecting: false, intersectionDemanded: false }))
- if (wheelIdleTimer !== undefined) clearTimeout(wheelIdleTimer)
- root.removeEventListener("scroll", onScroll)
- root.removeEventListener("wheel", onWheel)
- root.ownerDocument.removeEventListener("keydown", onKeyDown)
- root.ownerDocument.removeEventListener("keyup", onKeyUp)
- root.ownerDocument.defaultView?.removeEventListener("blur", onWindowBlur)
- root.removeEventListener("touchstart", onTouchStart)
- root.removeEventListener("touchmove", onTouchMove)
- root.removeEventListener("touchend", onTouchEnd)
- root.removeEventListener("touchcancel", onTouchEnd)
- }
- }, [edge, nearEdge, protocol, requestPage, root])
-
- useEffect(() => {
- if (!element || !root || typeof IntersectionObserver === "undefined") return
- let active = true
- const observer = new IntersectionObserver((entries) => {
- if (!active || !root.contains(element)) return
- for (const entry of entries) {
- if (entry.target !== element) continue
- protocol.setState((state) => ({ ...state, intersecting: entry.isIntersecting }))
- if (!entry.isIntersecting) {
- protocol.setState((state) => ({ ...state, intersectionDemanded: false }))
- } else if (!protocol.get().intersectionDemanded) {
- protocol.setState((state) => ({ ...state, intersectionDemanded: true }))
- requestPage(false)
- }
- }
- }, { root, rootMargin: "200px" })
- observer.observe(element)
- return () => {
- active = false
- observer.disconnect()
- protocol.setState((state) => ({ ...state, intersecting: false }))
- }
- }, [element, protocol, requestPage, root])
-
- return sentinelRef
-}
diff --git a/src/web/src/lib/community/message-list-items.test.ts b/src/web/src/lib/community/message-list-items.test.ts
index 447d7d1bb..c24bcdcfc 100644
--- a/src/web/src/lib/community/message-list-items.test.ts
+++ b/src/web/src/lib/community/message-list-items.test.ts
@@ -5,6 +5,7 @@ import type { Msg } from "./models/message"
function msg(overrides: Partial<Msg> & { id: string }): Msg {
return {
type: "chat",
+ authorId: "alice",
authorName: "Alice",
content: "hello",
createdAt: "2026-01-01T10:00:00.000Z",
@@ -13,52 +14,91 @@ function msg(overrides: Partial<Msg> & { id: string }): Msg {
}
describe("flattenMessageItems", () => {
- it("has exactly one stable virtual row per actual message", () => {
+ it("splits8px internal and16px external gaps across the adjacent canonical author rows", () => {
+ const rows = flattenMessageItems([
+ msg({ id: "m1" }), msg({ id: "m2", authorName: "Renamed Alice" }), msg({ id: "m3" }),
+ msg({ id: "m4", authorId: "another-alice" }),
+ ], undefined).filter(item => item.kind === "message")
+ expect(rows.map(item => item.m.grouped)).toEqual([false, true, true, false])
+ expect(rows).toMatchObject([
+ { paddingTop: 8, paddingBottom: 4 }, { paddingTop: 4, paddingBottom: 4 },
+ { paddingTop: 4, paddingBottom: 8 }, { paddingTop: 8, paddingBottom: 8 },
+ ])
+ })
+
+ it.each([
+ { type: "system" as const },
+ { replyTo: { id: "prior", authorName: "Alice", text: "reply" } },
+ { authorId: undefined },
+ ])("does not group either side of a system/reply/unknown-identity row: %j", (boundary) => {
+ const rows = flattenMessageItems([msg({ id: "m1" }), msg({ id: "m2", ...boundary }), msg({ id: "m3" })], undefined)
+ .filter(item => item.kind === "message")
+ expect(rows.map(item => item.m.grouped)).toEqual([false, false, false])
+ expect(rows).toMatchObject(Array.from({ length: 3 }, () => ({ paddingTop: 8, paddingBottom: 8 })))
+ })
+
+ it("breaks grouping at New while preserving the pending-window avatar rule without an unknown spacing link", () => {
+ const rows = flattenMessageItems([msg({ id: "m1" }), msg({ id: "m2" })], "m2", true)
+ .filter(item => item.kind === "message")
+ expect(rows.map(item => item.m.grouped)).toEqual([true, false])
+ expect(rows).toMatchObject([{ paddingTop: 8, paddingBottom: 8 }, { paddingTop: 8, paddingBottom: 8 }])
+ })
+ it.each(["2026-01-01T10:07:00.000Z", "2026-01-01T09:59:00.000Z"])("does not join an exact7-minute or reverse-time boundary: %s", (createdAt) => {
+ const rows = flattenMessageItems([msg({ id: "m1" }), msg({ id: "m2", createdAt })], undefined)
+ .filter(item => item.kind === "message")
+ expect(rows.map(item => item.m.grouped)).toEqual([false, false])
+ expect(rows).toMatchObject([{ paddingTop: 8, paddingBottom: 8 }, { paddingTop: 8, paddingBottom: 8 }])
+ })
+ it("gives the leading content, date and message independent stable rows", () => {
const items = flattenMessageItems([msg({ id: "m1" })], undefined)
- expect(items).toHaveLength(1)
- expect(items[0]).toMatchObject({ kind: "message", key: "msg:id:m1", dateLabel: expect.any(String) })
+ expect(items.map(item => item.kind)).toEqual(["leading", "divider", "message"])
+ expect(items[1]).toMatchObject({ messageId: "m1", dateLabel: expect.any(String) })
+ expect(items[2]).toMatchObject({ kind: "message", key: "msg:id:m1" })
+ expect(items[2]).not.toHaveProperty("dateLabel")
})
- it("adds date metadata only at the first message of each day", () => {
+ it("adds a date row only at the first message of each day", () => {
const items = flattenMessageItems([
msg({ id: "m1" }),
msg({ id: "m2", createdAt: "2026-01-01T10:01:00.000Z" }),
msg({ id: "m3", createdAt: "2026-01-02T12:00:00.000Z" }),
], undefined)
- expect(items.map(item => !!item.dateLabel)).toEqual([true, false, true])
- expect(items.map(item => item.m.id)).toEqual(["m1", "m2", "m3"])
+ expect(items.filter(item => item.kind === "divider").map(item => item.messageId)).toEqual(["m1", "m3"])
+ expect(items.filter(item => item.kind === "message").map(item => item.m.id)).toEqual(["m1", "m2", "m3"])
})
- it("puts same-day New metadata on its owning message without a second key", () => {
+ it("gives same-day New its own key while preserving the message keys", () => {
const messages = [msg({ id: "m1" }), msg({ id: "m2" })]
const items = flattenMessageItems(messages, "m2")
- expect(items).toHaveLength(2)
- expect(items[1]).toMatchObject({ newDivider: true, m: { id: "m2" } })
- expect(items[1].dateLabel).toBeUndefined()
- expect(items.map(item => item.key)).toEqual(flattenMessageItems(messages, undefined).map(item => item.key))
+ expect(items).toHaveLength(5)
+ expect(items[3]).toMatchObject({ kind: "divider", newDivider: true, messageId: "m2" })
+ expect(items[3]).not.toHaveProperty("dateLabel")
+ expect(items.filter(item => item.kind === "message").map(item => item.key))
+ .toEqual(flattenMessageItems(messages, undefined).filter(item => item.kind === "message").map(item => item.key))
})
- it("merges date and New metadata in one actual message row", () => {
+ it("merges date and New in one divider before the actual message", () => {
const items = flattenMessageItems([
msg({ id: "m1", createdAt: "2026-01-01T12:00:00.000Z" }),
msg({ id: "m2", createdAt: "2026-01-02T12:00:00.000Z" }),
], "m2")
- expect(items).toHaveLength(2)
- expect(items[1]).toMatchObject({ newDivider: true, dateLabel: expect.any(String) })
- expect(items[0].newDivider).toBeUndefined()
+ expect(items).toHaveLength(5)
+ expect(items[3]).toMatchObject({ kind: "divider", messageId: "m2", newDivider: true, dateLabel: expect.any(String) })
+ expect(items.filter(item => item.kind === "divider")).toHaveLength(2)
})
it("does not invent a New row for an absent anchor", () => {
- expect(flattenMessageItems([msg({ id: "m1" })], "absent").some(item => item.newDivider)).toBe(false)
+ expect(flattenMessageItems([msg({ id: "m1" })], "absent").some(item => item.kind === "divider" && item.newDivider)).toBe(false)
})
it("keeps the old first message key when a same-day prepend removes its date prefix", () => {
const anchor = msg({ id: "anchor", createdAt: "2026-01-01T12:01:00.000Z" })
- const original = flattenMessageItems([anchor], "anchor")[0]
- const next = flattenMessageItems([msg({ id: "older", createdAt: "2026-01-01T12:00:00.000Z" }), anchor], undefined)[1]
+ const original = flattenMessageItems([anchor], "anchor").find(item => item.kind === "message")!
+ const next = flattenMessageItems([msg({ id: "older", createdAt: "2026-01-01T12:00:00.000Z" }), anchor], undefined)
+ .find(item => item.kind === "message" && item.m.id === "anchor")!
expect(next.key).toBe(original.key)
- expect(next.dateLabel).toBeUndefined()
- expect(next.newDivider).toBeUndefined()
+ expect(next).not.toHaveProperty("dateLabel")
+ expect(next).not.toHaveProperty("newDivider")
expect(next.m.grouped).toBe(true)
})
@@ -91,7 +131,7 @@ describe("flattenMessageItems", () => {
const items = flattenMessageItems(
[
msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
- msg({ id: "m2", authorName: "Bob", createdAt: "2026-01-01T10:01:00.000Z" }),
+ msg({ id: "m2", authorId: "bob", authorName: "Bob", createdAt: "2026-01-01T10:01:00.000Z" }),
],
undefined,
)
@@ -118,7 +158,7 @@ describe("flattenMessageItems", () => {
const items = flattenMessageItems(
[
msg({ id: "m1", authorName: "Alice", createdAt: "2026-01-01T10:00:00.000Z" }),
- msg({ id: "m2", authorName: "Bob", createdAt: "2026-01-01T10:01:00.000Z" }),
+ msg({ id: "m2", authorId: "bob", authorName: "Bob", createdAt: "2026-01-01T10:01:00.000Z" }),
],
undefined,
true,
@@ -194,6 +234,18 @@ describe("flattenMessageItems", () => {
expect(new Set(keys).size).toBe(keys.length)
})
+ it("keeps repeated calendar-day boundaries distinct and excludes both loading edges from message counts", () => {
+ const items = flattenMessageItems([
+ msg({ id: "m1", createdAt: "2026-01-01T12:00:00.000Z" }),
+ msg({ id: "m2", createdAt: "2026-01-02T12:00:00.000Z" }),
+ msg({ id: "m3", createdAt: "2026-01-01T12:01:00.000Z" }),
+ ], "m2", true, true)
+ expect(new Set(items.map(item => item.key)).size).toBe(items.length)
+ expect(items.at(-1)?.kind).toBe("trailing")
+ expect(computeBelowCount(items, 0)).toBe(3)
+ expect(computeBelowCount(items, items.length - 2)).toBe(0)
+ })
+
it("keeps the FlatItem key stable across temp id, server id, and GET refetch", () => {
const keyFor = (message: Msg) =>
flattenMessageItems([message], undefined).find((item) => item.kind === "message")!.key
@@ -221,11 +273,12 @@ describe("flattenMessageItems", () => {
})
describe("estimateRowHeight", () => {
- it("estimates date and New prefixes once within the message", () => {
- const body = flattenMessageItems([msg({ id: "m1", createdAt: undefined })], undefined)[0]
- expect(estimateRowHeight({ ...body, dateLabel: "Today" }) - estimateRowHeight(body)).toBe(32)
- expect(estimateRowHeight({ ...body, newDivider: true }) - estimateRowHeight(body)).toBe(24)
- expect(estimateRowHeight({ ...body, dateLabel: "Today", newDivider: true }) - estimateRowHeight(body)).toBe(32)
+ it("estimates independent decorations without changing the message estimate", () => {
+ expect(estimateRowHeight({ kind: "divider", key: "date", messageId: "m1", dateLabel: "Today" })).toBe(32)
+ expect(estimateRowHeight({ kind: "divider", key: "new", messageId: "m1", newDivider: true })).toBe(24)
+ expect(estimateRowHeight({ kind: "divider", key: "both", messageId: "m1", dateLabel: "Today", newDivider: true })).toBe(32)
+ expect(estimateRowHeight({ kind: "leading", key: "leading" }, true)).toBe(88)
+ expect(estimateRowHeight({ kind: "trailing", key: "trailing" })).toBe(56)
})
it("scales up with longer text content", () => {
@@ -297,7 +350,7 @@ describe("computeBelowCount", () => {
it("counts only message rows strictly after the last visible index", () => {
// lastVisibleIndex 1 (first message) → m2, m3 remain below = 2
- expect(computeBelowCount(items, 0)).toBe(2)
+ expect(computeBelowCount(items, items.findIndex(item => item.kind === "message" && item.m.id === "m1"))).toBe(2)
})
it("excludes divider rows below the fold from the count", () => {
@@ -311,8 +364,8 @@ describe("computeBelowCount", () => {
],
undefined,
)
- expect(twoDay.map((i) => i.kind)).toEqual(["message", "message"])
- expect(computeBelowCount(twoDay, 0)).toBe(1)
+ expect(twoDay.map((i) => i.kind)).toEqual(["leading", "divider", "message", "divider", "message"])
+ expect(computeBelowCount(twoDay, 2)).toBe(1)
})
it("returns 0 for an empty list", () => {
diff --git a/src/web/src/lib/community/message-list-items.ts b/src/web/src/lib/community/message-list-items.ts
index 2c67a491f..fd641d25d 100644
--- a/src/web/src/lib/community/message-list-items.ts
+++ b/src/web/src/lib/community/message-list-items.ts
@@ -8,11 +8,24 @@ function messageDisplayKey(message: Msg): string {
}
const MESSAGE_GROUP_WINDOW_MS = 7 * 60 * 1000
+export const MESSAGE_ROW_VERTICAL_PADDING_PX = 8
export type FlatItem = {
kind: "message"
m: RenderMsg
key: string
+ paddingTop?: number
+ paddingBottom?: number
+} | {
+ kind: "leading"
+ key: string
+} | {
+ kind: "trailing"
+ key: string
+} | {
+ kind: "divider"
+ key: string
+ messageId: string
dateLabel?: string
newDivider?: boolean
}
@@ -21,8 +34,10 @@ export function flattenMessageItems(
messages: Msg[],
newDividerBefore: string | undefined,
hasMoreOlder = false,
+ hasMoreNewer = false,
): FlatItem[] {
const items: FlatItem[] = []
+ if (messages.length > 0) items.push({ kind: "leading", key: "rail:leading" })
let prev: Msg | null = null
let seenFirstMessage = false
for (const m of messages) {
@@ -30,19 +45,34 @@ export function flattenMessageItems(
const curDate = dateKey(m.createdAt)
const showDateDivider = !!(curDate && curDate !== prevDate)
const isNewDivider = m.id === newDividerBefore
- const isPendingWindowFirst = !seenFirstMessage && hasMoreOlder && m.type === "chat"
- const grouped = isPendingWindowFirst || !!(prev && m.type === "chat" && !m.replyTo && !showDateDivider && prev.authorName === m.authorName
- && prev.createdAt && m.createdAt && (new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime()) < MESSAGE_GROUP_WINDOW_MS)
+ const isPendingWindowFirst = !seenFirstMessage && hasMoreOlder && m.type === "chat" && !m.replyTo && !isNewDivider
+ const elapsed = prev?.createdAt && m.createdAt ? new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime() : NaN
+ const joinsPrevious = !!(prev && prev.type === "chat" && m.type === "chat" && !prev.replyTo && !m.replyTo
+ && !showDateDivider && !isNewDivider && m.authorId && prev.authorId === m.authorId
+ && elapsed >= 0 && elapsed < MESSAGE_GROUP_WINDOW_MS)
+ const grouped = isPendingWindowFirst || joinsPrevious
+ const previousItem = items.at(-1)
+ if (joinsPrevious && previousItem?.kind === "message") previousItem.paddingBottom = MESSAGE_ROW_VERTICAL_PADDING_PX / 2
+ if (showDateDivider || isNewDivider) {
+ items.push({
+ kind: "divider",
+ key: isNewDivider ? `new:${messageDisplayKey(m)}` : `date:${messageDisplayKey(m)}`,
+ messageId: m.id,
+ ...(showDateDivider ? { dateLabel: formatDateLabel(m.createdAt!) } : {}),
+ ...(isNewDivider ? { newDivider: true } : {}),
+ })
+ }
items.push({
kind: "message",
m: { ...m, grouped },
key: messageDisplayKey(m),
- ...(showDateDivider ? { dateLabel: formatDateLabel(m.createdAt!) } : {}),
- ...(isNewDivider ? { newDivider: true } : {}),
+ paddingTop: joinsPrevious ? MESSAGE_ROW_VERTICAL_PADDING_PX / 2 : MESSAGE_ROW_VERTICAL_PADDING_PX,
+ paddingBottom: MESSAGE_ROW_VERTICAL_PADDING_PX,
})
seenFirstMessage = true
prev = m
}
+ if (messages.length > 0 && hasMoreNewer) items.push({ kind: "trailing", key: "rail:trailing" })
return items
}
@@ -52,7 +82,7 @@ export function flattenMessageItems(
// already relies on for its own rows. No precision beyond that is required.
const DATE_DIVIDER_ESTIMATE_PX = 32
const NEW_DIVIDER_ESTIMATE_PX = 24
-const MESSAGE_BASE_ESTIMATE_PX = 24
+const MESSAGE_BASE_ESTIMATE_PX = 8
const CHARS_PER_LINE_ESTIMATE = 55
const LINE_HEIGHT_ESTIMATE_PX = 20
const MAX_TEXT_ESTIMATE_PX = 400
@@ -86,11 +116,13 @@ function estimateAttachmentsHeight(m: Msg): number {
}
// Exported for direct unit testing (see message-list.test.ts).
-export function estimateRowHeight(item: FlatItem): number {
+export function estimateRowHeight(item: FlatItem, hasMoreOlder = false): number {
+ if (item.kind === "leading") return hasMoreOlder ? 88 : 152
+ if (item.kind === "trailing") return 56
+ if (item.kind === "divider") return item.dateLabel ? DATE_DIVIDER_ESTIMATE_PX : NEW_DIVIDER_ESTIMATE_PX
const m = item.m
- let height = MESSAGE_BASE_ESTIMATE_PX + estimateTextHeight(m.content) + estimateAttachmentsHeight(m)
- if (item.dateLabel) height += DATE_DIVIDER_ESTIMATE_PX
- else if (item.newDivider) height += NEW_DIVIDER_ESTIMATE_PX
+ let height = MESSAGE_BASE_ESTIMATE_PX + (item.paddingTop ?? MESSAGE_ROW_VERTICAL_PADDING_PX)
+ + (item.paddingBottom ?? MESSAGE_ROW_VERTICAL_PADDING_PX) + estimateTextHeight(m.content) + estimateAttachmentsHeight(m)
if (m.replyTo) height += REPLY_HEADER_ESTIMATE_PX
if (m.embeds?.length) height += EMBED_ESTIMATE_PX * m.embeds.length
if (m.reactions?.length) height += REACTIONS_ESTIMATE_PX
@@ -99,5 +131,5 @@ export function estimateRowHeight(item: FlatItem): number {
}
export function computeBelowCount(items: FlatItem[], lastVisibleIndex: number): number {
- return Math.max(0, items.length - Math.max(0, lastVisibleIndex + 1))
+ return items.slice(Math.max(0, lastVisibleIndex + 1)).filter((item) => item.kind === "message").length
}
diff --git a/src/web/src/lib/observability/virtual-window.dom.test.tsx b/src/web/src/lib/observability/virtual-window.dom.test.tsx
index 7553ce8b5..c3e301c5d 100644
--- a/src/web/src/lib/observability/virtual-window.dom.test.tsx
+++ b/src/web/src/lib/observability/virtual-window.dom.test.tsx
@@ -39,7 +39,7 @@ function WindowPanel({ rows, overscan, attached = true }: { rows: Row[]; oversca
useLayoutEffect(() => { native = virtualizer })
const selected = visibleVirtualItems(virtualizer).map(item => rows[item.index]!)
useObservedRegion("messages", selected.length > 0, selected.length)
- return attached ? <div ref={bind} data-testid="viewport"><VirtualRows items={rows} virtualizer={virtualizer} itemKey={row => row.id} renderItem={row => <p>{row.id}</p>} /></div> : null
+ return attached ? <div ref={bind} data-testid="viewport"><VirtualRows items={rows} virtualizer={virtualizer} renderItem={row => <p>{row.id}</p>} /></div> : null
}
function rows() {
return Array.from({ length: 20 }, (_, index) => ({ id: "row-" + index }))
diff --git a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
index 2b6401f11..2b77b3666 100644
--- a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
+++ b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
@@ -1,6 +1,6 @@
import { test, expect, userId } from "./_fixtures/community-fixture"
import { tid } from "./_fixtures/testids"
-import { seedServer, seedChannel, seedJoinServer, seedCategory, seedMessage, seedThread } from "./_fixtures/seed"
+import { seedServer, seedChannel, seedJoinServer, seedCategory, seedMessage, seedThread, memberInfo } from "./_fixtures/seed"
// Journey 6 — channel / member administration + the eject branch (needs a
// second identity). Focuses on member list presence and non-member ejection.
@@ -58,6 +58,58 @@ test.describe.serial("channel & member admin", () => {
await page.getByTestId(tid.serverSettingsOpen).click()
await expect(page.getByTestId(tid.settingsShell)).toBeVisible()
expect(requests).toHaveLength(0)
+ const membersPanel = page.getByRole("tabpanel", { name: "Members" })
+ const expectFiniteMembersFrame = async () => {
+ await expect(membersPanel.getByRole("listitem").first()).toBeVisible()
+ await expect.poll(() => membersPanel.evaluate((panel) => {
+ const content = panel.parentElement!
+ const style = getComputedStyle(content)
+ const availableHeight = content.clientHeight
+ - Number.parseFloat(style.paddingTop)
+ - Number.parseFloat(style.paddingBottom)
+ const frame = panel.getBoundingClientRect()
+ const scrollport = panel.querySelector('[role="listitem"]')!
+ .parentElement!.parentElement!
+ const scrollFrame = scrollport.getBoundingClientRect()
+ return {
+ panelFillsContent: availableHeight > 0 && Math.abs(frame.height - availableHeight) <= 1,
+ scrollportFillsRemainingFrame: scrollport.clientHeight > 0
+ && scrollFrame.top >= frame.top
+ && Math.abs(scrollFrame.bottom - frame.bottom) <= 1,
+ scrollOwner: getComputedStyle(scrollport).overflowY === "auto",
+ }
+ })).toEqual({
+ panelFillsContent: true,
+ scrollportFillsRemainingFrame: true,
+ scrollOwner: true,
+ })
+ }
+ await page.getByTestId(tid.settingsTab("members")).click()
+ await expectFiniteMembersFrame()
+ expect(requests).toHaveLength(0)
+ const bob = await memberInfo("alice", serverId, userId("bob"))
+ const searchInput = membersPanel.getByPlaceholder("Search members")
+ const searchResponse = page.waitForResponse((res) => {
+ const url = new URL(res.url())
+ return url.pathname === `/api/community/servers/${serverId}/members/search`
+ && url.searchParams.get("q") === bob.name
+ })
+ await searchInput.fill(bob.name)
+ const searched = await searchResponse
+ expect(searched.status()).toBe(200)
+ const searchData = await searched.json() as { members: { id: string; userId: string }[] }
+ expect(searchData.members).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: bob.id, userId: userId("bob") }),
+ ]))
+ await expect(page.getByTestId(tid.settingsShell)).toBeVisible()
+ await expect(searchInput).toHaveValue(bob.name)
+ await expect(membersPanel.getByRole("listitem").filter({ hasText: bob.name })
+ .getByRole("button", { name: "Member", exact: true })).toBeVisible()
+ await searchInput.fill("")
+ await expect(searchInput).toHaveValue("")
+ await expect(membersPanel.getByRole("listitem").filter({ hasText: "Owner" }).first()).toBeVisible()
+ await expectFiniteMembersFrame()
+ expect(requests).toHaveLength(0)
const response = page.waitForResponse((res) => new URL(res.url()).pathname === adminPath)
await page.getByTestId(tid.settingsTab("channels")).click()
const result = await response
@@ -99,6 +151,8 @@ test.describe.serial("channel & member admin", () => {
expect(responses).toEqual([200])
const messages = await page.request.get(`/api/community/channels/${privateId}/messages`)
expect(messages.status()).toBe(403)
+ await page.getByTestId(tid.settingsTab("members")).click()
+ await expectFiniteMembersFrame()
await page.getByTestId(tid.settingsClose).click()
await expect(page.getByTestId(tid.channelRow(privateId))).toHaveCount(0)
})
diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
index 337482016..9d4573c80 100644
--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -213,12 +213,17 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const coldThumbnailGate = new Promise<void>((resolve) => { releaseColdThumbnail = resolve })
let holdColdThumbnail = true
let coldThumbnailRequests = 0
+ let coldThumbnailPath: string | null = null
const thumbnailPattern = "**/api/community/channels/**/attachments/**/thumbnail"
await page.route(thumbnailPattern, async (route) => {
+ const pathname = new URL(route.request().url()).pathname
if (
holdColdThumbnail
&& route.request().method() === "GET"
+ && pathname.startsWith(`/api/community/channels/${channelId}/attachments/`)
+ && (coldThumbnailPath === null || pathname === coldThumbnailPath)
) {
+ coldThumbnailPath = pathname
coldThumbnailRequests++
const response = route.fetch()
await coldThumbnailGate
@@ -238,6 +243,7 @@ test("image previews keep one frame through loading, decode, failure, retry, and
const landscapeListImage = page.getByTestId(tid.messageImage(landscape.messageId, 0))
await expect(landscapeListImage).toHaveAttribute("src", landscape.thumbnailPath)
await expect.poll(() => observedGetPaths.filter((path) => path === landscape.thumbnailPath).length).toBeGreaterThan(0)
+ await expect.poll(() => coldThumbnailPath).toBe(landscape.thumbnailPath)
expect(observedGetPaths.filter((path) => path === landscape.originalPath)).toHaveLength(0)
const landscapeListFrame = landscapeListImage.locator("xpath=ancestor::*[@data-remote-image-frame]")
await expect(landscapeListFrame).toHaveAttribute("data-remote-image-state", "pending")
@@ -266,6 +272,7 @@ test("image previews keep one frame through loading, decode, failure, retry, and
await expect.poll(() => coldThumbnailRequests).toBeGreaterThan(0)
await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()
await expect(page.getByTestId(tid.imageLightboxLoading)).toBeVisible()
+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveAttribute("src", landscape.thumbnailPath)
await waitForDialogEntrance(page)
const coldPendingRect = await previewRects(page)
expect(await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({
@@ -279,13 +286,13 @@ test("image previews keep one frame through loading, decode, failure, retry, and
expectSameRect(await boundingRect(landscapeListFrame), pendingListRect)
await expect(page.getByTestId(tid.imageLightbox)).toBeVisible()
expectSameRect(await previewRects(page).then((rects) => rects.container), coldPendingRect.container)
+ await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveClass(/opacity-100/)
const coldThumbnailReady = await page.getByTestId(tid.imageLightboxThumbnail).evaluate((element: HTMLImageElement) => ({
complete: element.complete,
naturalWidth: element.naturalWidth,
}))
expect(coldThumbnailReady.complete).toBe(true)
expect(coldThumbnailReady.naturalWidth).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.imageLightboxThumbnail)).toHaveClass(/opacity-100/)
await attachScreenshot(testInfo, "desktop-landscape-first-visible", page)
await page.unroute(thumbnailPattern)
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 279317394..184390db6 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -942,7 +942,7 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
for (let index = 0; index < 24; index += 1) {
await seedMessage("alice", channelId, `scroll row ${index} ${stamp}`)
}
- await seedMessage("alice", channelId, Array.from(
+ const longMessageId = await seedMessage("alice", channelId, Array.from(
{ length: 95 },
(_, index) => `scroll line ${index} ${stamp}`,
).join("\n\n"))
@@ -965,6 +965,13 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
const editable = composerEditable(alice.page)
const scroller = alice.page.getByTestId(tid.messageScroller)
await expect(editable).toBeVisible()
+ await scroller.hover()
+ await expect.poll(async () => {
+ if (await alice.page.getByTestId(tid.message(longMessageId)).count()) return true
+ await alice.page.mouse.wheel(0, 600)
+ return false
+ }).toBe(true)
+ await expect(alice.page.getByTestId(tid.message(longMessageId))).toBeVisible()
await expect.poll(() => scroller.evaluate((element) => (
element.scrollHeight - element.clientHeight
))).toBeGreaterThanOrEqual(2200)
diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.ts
index 2e3a7b811..eba12a9e1 100644
--- a/src/web/src/test/message-scroll-fixture.ts
+++ b/src/web/src/test/message-scroll-fixture.ts
@@ -1,11 +1,12 @@
-import { createElement, StrictMode, useLayoutEffect } from "react"
+import { createElement, StrictMode, useLayoutEffect, useMemo } from "react"
import { vi } from "vitest"
import { act, render, fireEvent } from "@/test/react-dom-harness"
import { VirtualRows } from "@/components/community/messages/virtual-cursor-list"
import type { FlatItem } from "@/lib/community/message-list-items"
import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
-export const message = (id: string, authorId = "peer"): FlatItem => ({ kind: "message", key: `msg:${id}`, m: { id, type: "chat", authorId, grouped: false } })
+type FixtureMessage = Extract<FlatItem, { kind: "message" }> & { dateLabel?: string; newDivider?: boolean }
+export const message = (id: string, authorId = "peer"): FixtureMessage => ({ kind: "message", key: `msg:${id}`, m: { id, type: "chat", authorId, grouped: false } })
type Input = Parameters<typeof useScrollAnchor>[0]
type Result = ReturnType<typeof useScrollAnchor>
let latest: Result
@@ -19,9 +20,6 @@ let resizeObservers: Array<{ callback: ResizeObserverCallback; elements: Set<Ele
let scrollCalls: number[]
let scrollDescriptor: PropertyDescriptor | undefined
-function prefix(item: FlatItem, index: number) {
- return (index === 0 ? firstPrefix : 0) + (item.dateLabel ? 32 : item.newDivider ? 24 : 0)
-}
const ROOT_SELECTOR = '[data-testid="scroll"], [data-testid="community-message-scroller"]'
function isScrollRoot(node: HTMLElement) { return node.matches(ROOT_SELECTOR) }
function rootFor(node: HTMLElement) { return node.closest<HTMLElement>(ROOT_SELECTOR) }
@@ -31,28 +29,58 @@ function rowGeometry(node: HTMLElement) {
const content = wrapper?.querySelector<HTMLElement>('[data-msg-id]')
const size = content ? bodyHeights.get(content.dataset.msgId!) ?? 100 : 0
const actualRow = wrapper?.querySelector<HTMLElement>("[data-message-row-key]")
- const before = content?.dataset.prefix !== undefined ? Number(content.dataset.prefix)
- : (wrapper?.dataset.index === "0" ? firstPrefix : 0)
- + (actualRow?.querySelector("[data-new-divider]") ? 24
- : actualRow?.querySelector("span.text-xs") ? 32 : 0)
+ const key = actualRow?.dataset.messageRowKey
+ const kind = actualRow?.dataset.fixtureKind ?? (key === "rail:leading" ? "leading" : key === "rail:trailing" ? "trailing"
+ : key?.startsWith("date:") || key?.startsWith("new:") ? "divider" : "message")
+ const hasDate = actualRow?.dataset.fixtureDate === "true" || !!actualRow?.querySelector("span.text-xs")
+ const decoration = kind === "leading" ? firstPrefix : kind === "trailing" ? 56
+ : kind === "divider" ? hasDate ? 32 : 24 : 0
+ const padding = kind === "message" ? (actualRow?.style.paddingBlock ?? "").split(/\s+/).map(Number.parseFloat) : [0]
+ const topPadding = padding[0] || (actualRow?.classList.contains("py-2") ? 8 : 0)
+ const bottomPadding = padding.length > 1 ? padding[1] : topPadding
const translation = wrapper?.style.transform.match(/translate3d\(0,\s*(-?[\d.]+)px/)
const start = Number.parseFloat(translation?.[1] ?? wrapper?.style.top ?? "0") || 0
const y = start - (root?.scrollTop ?? 0)
- if (node.matches('[data-msg-id]')) return DOMRect.fromRect({ y: y + before, width, height: size })
- if (node.matches('[data-new-divider]')) return DOMRect.fromRect({ y: y + before - 24, width, height: 24 })
- return DOMRect.fromRect({ y, width, height: size + before })
+ if (node.matches('[data-msg-id]')) return DOMRect.fromRect({ y: y + topPadding, width, height: size })
+ if (node.matches('[data-new-divider]')) return DOMRect.fromRect({ y, width, height: decoration })
+ return DOMRect.fromRect({ y, width, height: size + decoration + topPadding + bottomPadding })
}
function Probe({ input, onLayout }: { input: Input; onLayout?: (result: Result) => void }) {
- const result = useScrollAnchor(input)
+ const items = useMemo<FlatItem[]>(() => {
+ if (input.items.length === 0 || input.items.some(item => item.kind !== "message")) return input.items
+ return [
+ { kind: "leading", key: "rail:leading" },
+ ...input.items.flatMap(item => {
+ const message = item as FixtureMessage
+ return [
+ ...(message.dateLabel || message.newDivider ? [{
+ kind: "divider" as const,
+ key: `divider:${message.key}`,
+ messageId: message.m.id,
+ dateLabel: message.dateLabel,
+ newDivider: message.newDivider,
+ }] : []),
+ message,
+ ]
+ }),
+ ...(input.hasMoreNewer ? [{ kind: "trailing" as const, key: "rail:trailing" }] : []),
+ ]
+ }, [input.items, input.hasMoreNewer])
+ const result = useScrollAnchor({ ...input, items })
useLayoutEffect(() => { latest = result; onLayout?.(result) })
return createElement("div", { "data-slot": "community-conversation-surface" },
createElement("div", { ref: result.scrollRef, "data-testid": "scroll" },
createElement("div", { "data-message-list-content": "", "data-read-position-ready": String(result.readPositionReady) },
createElement(VirtualRows<FlatItem>, {
- items: input.items, virtualizer: result.virtualizer, itemKey: (item) => item.key,
- renderItem: (item, index) => createElement("div", null,
- item.newDivider ? createElement("div", { "data-new-divider": "" }) : null,
- createElement("div", { "data-msg-id": item.m.id, "data-prefix": prefix(item, index) }),
+ items, virtualizer: result.virtualizer,
+ renderItem: (item) => createElement("div", {
+ "data-message-row-key": item.key,
+ "data-fixture-kind": item.kind,
+ "data-fixture-date": String(item.kind === "divider" && !!item.dateLabel),
+ "data-message-divider-for": item.kind === "divider" ? item.messageId : undefined,
+ },
+ item.kind === "divider" && item.newDivider ? createElement("div", { "data-new-divider": "" }) : null,
+ item.kind === "message" ? createElement("div", { "data-msg-id": item.m.id }) : null,
),
}),
),