Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): synchronize virtual lists and reuse forum pagination (#1035)

Gener7fe0fb497af5
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index af82ba222..dd4b7e78f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -350,26 +350,26 @@ importers:
specifier: ^1.0.3
version: 1.0.3([email protected])
'@tanstack/query-async-storage-persister':
- specifier: 5.104.2
- version: 5.104.2
+ specifier: 5.104.5
+ version: 5.104.5
'@tanstack/query-db-collection':
- specifier: 1.4.5
- version: 1.4.5(@tanstack/[email protected])([email protected])
+ specifier: 1.4.7
+ version: 1.4.7(@tanstack/[email protected])([email protected])
'@tanstack/react-db':
- specifier: 0.5.10
+ specifier: 0.5.11
'@tanstack/react-query':
- specifier: 5.104.2
- version: 5.104.2([email protected])
+ specifier: 5.104.5
+ version: 5.104.5(@types/[email protected])([email protected])
'@tanstack/react-query-persist-client':
- specifier: 5.104.2
+ specifier: 5.104.5
'@tanstack/react-store':
specifier: 0.11.2
'@tanstack/react-virtual':
- specifier: ^3.14.19
+ specifier: 3.14.21
'@tanstack/store':
specifier: 0.11.2
version: 0.11.2
@@ -570,8 +570,8 @@ importers:
specifier: ^4
version: 4.3.3
'@tanstack/react-query-devtools':
- specifier: 5.104.2
+ specifier: 5.104.5
'@testing-library/jest-dom':
specifier: 7.0.1
version: 7.0.1(@testing-library/[email protected])([email protected])
@@ -3590,8 +3590,8 @@ packages:
peerDependencies:
typescript: '>=4.7'
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-truZ/WWSS48goC3JlxR2dbjSxYcVfwLtA8Z8xexvayR8HG1Jii040rS+PKUs+C50QGNfUQo5jWQUZ+lERZYeQw==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-V47I3xqH8RLeI6BGBvQTBrALaGCArnMhq3sslP10RdBKYO6usa6uDWVvcNbRDyblRwBPOrRPKfi+3X+RVTeFoA==}
peerDependencies:
typescript: '>=4.7'
@@ -3603,46 +3603,57 @@ packages:
resolution: {integrity: sha512-eQ1MyLKCHyXiH7NbdmB80W77OhiMgGBUb+qDx/8WMGbwg5Lf/NlfD0TfNYAqY77i8V3AxoDoYdICrQE5ADw4Yw==}
engines: {node: '>=18'}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-LULNGhfU7JkhTgOvjwe+X7LN5q8VhTTQGhAaCa0uZXfhBUHYY/BTohB9x0LB9dqCNi9QPKQAIm1GJt4Yxnp4eQ==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-PvWWD1tdE9fnQa/ndEREhkZAaW72RcixAFwC2F6c+JhhRCJ/wSjdl6DgY4IjJ+EX0H6AykjEMGw+EPvzSltyqA==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-/qbsxJK5c3Ve1aFIULWYNcT2jeRUAiD4HME6Eu2ZdpofHoVgAjpkQhLg5xHuOoBkTPQUJLfP7zOxy0qsBcqROA==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-Q94gI8Opd+CbdVNOdj8ZCyV8WqLYitrDq1t96Xc8WZT6lY0r5iRnJLXYDxMex7EEf2v+mXvn4FcjaBKSxXZQ9A==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-Yd5+4jJfUzAUG4pG6MnpLczgYSBmghKVbKW/4vZ3ZEEnPrYUBze9WyoXvJ8MwVveqXNI+cRXHvhOMH1/OqVjfg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-8jNXwePOl4QwDAkob4l4yBrhKPb1Q8uPnLodTQ1HgzswOrhIN9kwpE3VMw8fzSM7e9r837KBS/L0zjefr/pZmw==}
peerDependencies:
'@tanstack/query-core': ^5.90.15
typescript: '>=4.7'
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-LQrdtI9mRq1WEXml1ujhRN9K9cEnxH4YGkGoUvhYhGdZx0QcD7FKSV7lUKfMAHUm3ITJsTsqjlUJ7/qNZtQHqg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-BLVEw4lFF7aIRsfqGvI50SSR9oN46/EmlygC+3h5TUdI+fL8GnMQialL3H92TbYi7J1b/hYlUGnckBT2uG5h8w==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-rFbWzV0NmdPU9b6xbJBEH6dtaWbbSX1vmXoi+s5o63ETKJhcKoh3gGq0NMqITtGEGEG8kogvJ56US7DJjwkPKA==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-z0+AuCPPf53bl1nntO9i8ZXGvSdO7nGRZFtcpM2DCZKz88UBzHpJZZJpuUkLFkDU7xYHnUOMrOJmky+Et1nRLg==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-cLXzBQPloOrvS2iyAPY5uJy4a+r/2xTFcUyfuNVMpQQcrNP0QkphxmgfqYDbYMPMKq91RGLgY0hncRu0xslwEg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-o22NPesFU0r59ddePVM6grRTDb8gArKPC8hHMQ0scAeB+yR9XzMh5fnLGhfjrnle1a4gguWvvWCS8SO3lrVxOw==}
peerDependencies:
react: '>=18.0.0'
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-F88xtzaf0QrJTENPMs6xngHuf5n+1zRFatAPhXUqF+DCpIlmuPEZb05U+DQCddfs2HjW25WMx3f9B4G8gApOiA==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-2SMhSSYnOGSaPLuSTKLOj5nPoP4sqasOfkpTn5BLe6LIZuHzrpcqrJx0Rm8uUSN5Ob4lPAbh/1oWClnnGaR7Bg==}
peerDependencies:
- '@tanstack/react-query': ^5.104.2
+ '@tanstack/react-query': ^5.104.5
'@types/react': ^18 || ^19
react: ^18 || ^19
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-IpwHqsJM2KBX9LkYrlH2FmWdq7fVj2NrXJVIkqg3rIYZ9Kv0AwtaUVphf0t1PL+gYqqGfF76YtMjm8vUSr94BQ==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-nXtb9e3smFl5xzGuttzck5VjwA18ZolPLj1ybt2zjEJudIUh/gRFxeNY0855YFp/+N0V1s/lpWLSrO89iQ5IcQ==}
peerDependencies:
- '@tanstack/react-query': ^5.104.2
+ '@tanstack/react-query': ^5.104.5
+ '@types/react': ^18 || ^19
react: ^18 || ^19
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-xKmzWGhadbE5wGS/ZmXShRITnI9oItox5GO14KvFZco3+vhTAyXS1erYzJWdiY280zapAGJXFUL9nHgwP6SV/g==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-RORgFe052U+93weaNuqg7qHq7vNVNzXN/VrXqD4bbAuQCWUqOl2lV5Ui9flWk5CVvMyL/Bh27QWhzwH0aaOx9g==}
peerDependencies:
+ '@types/react': ^18 || ^19
react: ^18 || ^19
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
'@tanstack/[email protected]':
resolution: {integrity: sha512-oj5O5DmiMWE+ih+SioX2ayC1kbK7d3fpLx0B75fPJr9nY3zU+hoW010yr64qXsY/9fyiLVE2bn5mGNV3owm8RQ==}
@@ -3650,8 +3661,8 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-zmVdJO8DDqHphZ2H6SnTmgpVXcUy5DprB+clZF0ik679/d0MQ1UPEb2jtaX6F5VTAX4o3ozSLQaRCnybS2KYLA==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-wWE/ZJDNNDp18JHWy7n5PQooqerHePVkEEu6Op0twKQ2InF9DPhYMQptQY0syDEviMd3/r8D0OUvKJibDGm9HQ==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
@@ -3659,8 +3670,8 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-ygZ3O99Il18dl0gG0q7sH78iSkb96F07G+xK9V83eCgV8NQbcNd7R+cgcJJMFO7llBoebd0A82sCCstQq2Vp6Q==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-CsTW892z23gy7IyxYTTorVu1uZWB+0N349rSMgKz4rFLPpLza7F7TpcCKeI5iUAwYQCt8QUlOU67J+KXCxtpGw==}
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}
@@ -12747,7 +12758,7 @@ snapshots:
fractional-indexing: 3.4.0
typescript: 6.0.3
dependencies:
'@standard-schema/spec': 1.1.0
'@tanstack/db-ivm': 0.2.0([email protected])
@@ -12760,28 +12771,28 @@ snapshots:
'@tanstack/[email protected]': {}
- '@tanstack/[email protected]':
+ '@tanstack/[email protected]':
dependencies:
- '@tanstack/query-core': 5.104.2
- '@tanstack/query-persist-client-core': 5.104.2
+ '@tanstack/query-core': 5.104.5
+ '@tanstack/query-persist-client-core': 5.104.5
- '@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
dependencies:
'@standard-schema/spec': 1.1.0
- '@tanstack/db': 0.15.0([email protected])
- '@tanstack/query-core': 5.104.2
+ '@tanstack/db': 0.15.1([email protected])
+ '@tanstack/query-core': 5.104.5
typescript: 6.0.3
dependencies:
'@kobalte/core': 0.13.14([email protected])
'@solid-primitives/keyed': 1.5.3([email protected])
'@solid-primitives/resize-observer': 2.2.0([email protected])
'@solid-primitives/storage': 1.3.11([email protected])
'@tanstack/match-sorter-utils': 9.2.6
- '@tanstack/query-core': 5.104.2
+ '@tanstack/query-core': 5.104.5
clsx: 2.1.1
goober: 2.1.19([email protected])
solid-js: 1.9.17
@@ -12790,36 +12801,41 @@ snapshots:
transitivePeerDependencies:
- csstype
- '@tanstack/[email protected]':
+ '@tanstack/[email protected]':
dependencies:
- '@tanstack/query-core': 5.104.2
+ '@tanstack/query-core': 5.104.5
dependencies:
- '@tanstack/db': 0.15.0([email protected])
+ '@tanstack/db': 0.15.1([email protected])
react: 19.3.1
transitivePeerDependencies:
- typescript
dependencies:
- '@tanstack/query-devtools': 5.104.2([email protected])
- '@tanstack/react-query': 5.104.2([email protected])
- '@types/react': 19.3.0
+ '@tanstack/query-devtools': 5.104.5([email protected])
+ '@tanstack/react-query': 5.104.5(@types/[email protected])([email protected])
react: 19.3.1
+ optionalDependencies:
+ '@types/react': 19.3.0
transitivePeerDependencies:
- csstype
dependencies:
- '@tanstack/query-persist-client-core': 5.104.2
- '@tanstack/react-query': 5.104.2([email protected])
+ '@tanstack/query-persist-client-core': 5.104.5
+ '@tanstack/react-query': 5.104.5(@types/[email protected])([email protected])
react: 19.3.1
+ optionalDependencies:
+ '@types/react': 19.3.0
dependencies:
- '@tanstack/query-core': 5.104.2
+ '@tanstack/query-core': 5.104.5
react: 19.3.1
+ optionalDependencies:
+ '@types/react': 19.3.0
dependencies:
@@ -12828,15 +12844,15 @@ snapshots:
react-dom: 19.3.1([email protected])
use-sync-external-store: 1.6.0([email protected])
dependencies:
- '@tanstack/virtual-core': 3.19.4
+ '@tanstack/virtual-core': 3.19.6
react: 19.3.1
react-dom: 19.3.1([email protected])
'@tanstack/[email protected]': {}
- '@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
'@tauri-apps/[email protected]': {}
diff --git a/src/web/package.json b/src/web/package.json
index 80ac825d5..7c342c86a 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -69,13 +69,13 @@
"@streamdown/cjk": "^1.0.4",
"@streamdown/math": "^1.0.3",
"@streamdown/mermaid": "^1.0.3",
- "@tanstack/query-async-storage-persister": "5.104.2",
- "@tanstack/query-db-collection": "1.4.5",
- "@tanstack/react-db": "0.5.10",
- "@tanstack/react-query": "5.104.2",
- "@tanstack/react-query-persist-client": "5.104.2",
+ "@tanstack/query-async-storage-persister": "5.104.5",
+ "@tanstack/query-db-collection": "1.4.7",
+ "@tanstack/react-db": "0.5.11",
+ "@tanstack/react-query": "5.104.5",
+ "@tanstack/react-query-persist-client": "5.104.5",
"@tanstack/react-store": "0.11.2",
- "@tanstack/react-virtual": "^3.14.19",
+ "@tanstack/react-virtual": "3.14.21",
"@tanstack/store": "0.11.2",
"@tauri-apps/plugin-clipboard-manager": "^2.5.0",
"@tiptap/extension-list": "^3.32.0",
@@ -144,7 +144,7 @@
"@serwist/turbopack": "9.5.13",
"@tailwindcss/node": "^4.3.3",
"@tailwindcss/postcss": "^4",
- "@tanstack/react-query-devtools": "5.104.2",
+ "@tanstack/react-query-devtools": "5.104.5",
"@testing-library/jest-dom": "7.0.1",
"@testing-library/react": "16.3.3",
"@testing-library/user-event": "14.6.8",
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 1f596a314..90517a1ee 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
@@ -34,7 +34,7 @@ const {
}))
let scrollDescriptor: PropertyDescriptor | undefined
let bodyHeight = 300
-let deferScrollEvents = false
+let pendingScrollRoots = new Set<HTMLElement>()
let rowHeights = new Map<string, number>()
let bodyResizeObservers: Array<{ callback: ResizeObserverCallback; elements: Set<Element> }> = []
@@ -182,8 +182,8 @@ function resizeBody(height: number, settle = true) {
} as unknown as ResizeObserverEntry))
if (entries.length) observer.callback(entries, {} as ResizeObserver)
}
- if (settle) vi.advanceTimersByTime(500)
})
+ if (settle) act(() => vi.advanceTimersByTime(500))
}
describe("BotActivityModal CommunitySheet contract", () => {
@@ -201,7 +201,7 @@ describe("BotActivityModal CommunitySheet contract", () => {
fetchNextPage.mockResolvedValue({ isError: false, data: { pages: [{ events: [] }] } })
sheetProps.current = null
bodyHeight = 300
- deferScrollEvents = false
+ pendingScrollRoots = new Set()
rowHeights = new Map()
bodyResizeObservers = []
vi.useFakeTimers()
@@ -245,9 +245,15 @@ describe("BotActivityModal CommunitySheet contract", () => {
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
+ const previous = this.scrollTop
this.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.scrollHeight - this.clientHeight))
- if (deferScrollEvents) window.setTimeout(() => this.dispatchEvent(new Event("scroll")), 0)
- else this.dispatchEvent(new Event("scroll"))
+ if (this.scrollTop !== previous && !pendingScrollRoots.has(this)) {
+ pendingScrollRoots.add(this)
+ window.setTimeout(() => {
+ pendingScrollRoots.delete(this)
+ if (this.isConnected) this.dispatchEvent(new Event("scroll"))
+ }, 0)
+ }
} })
})
afterEach(() => {
@@ -258,6 +264,26 @@ describe("BotActivityModal CommunitySheet contract", () => {
else Reflect.deleteProperty(HTMLElement.prototype, "scrollTo")
})
+ it("queues one changed scroll delivery after synchronous writes and ignores no-op writes", () => {
+ auditState.events = events(50)
+ const { renderer } = renderModal()
+ act(() => vi.advanceTimersByTime(500))
+ const root = renderer.getByTestId("activity-body")
+ const delivered = vi.fn(() => root.scrollTop)
+ root.addEventListener("scroll", delivered)
+ act(() => {
+ root.scrollTo({ top: 100 })
+ root.scrollTo({ top: 120 })
+ expect(root.scrollTop).toBe(120)
+ expect(delivered).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(0)
+ })
+ expect(delivered).toHaveBeenCalledOnce()
+ expect(delivered.mock.results[0].value).toBe(120)
+ act(() => { root.scrollTo({ top: 120 }); vi.advanceTimersByTime(0) })
+ expect(delivered).toHaveBeenCalledOnce()
+ })
+
it("uses the resizable 672px shared shell and its one dismissal callback", () => {
const { renderer, onOpenChange } = renderModal()
expect(renderer.container.querySelector("community-sheet")).toBeInTheDocument()
@@ -526,7 +552,7 @@ describe("BotActivityModal CommunitySheet contract", () => {
expect(fetchNextPage).not.toHaveBeenCalled()
const root = renderer.getByTestId("activity-body")
expect(renderer.container.querySelector("[data-activity-sticky-date]")).toBeInTheDocument()
- act(() => root.scrollTo({ top: 340 }))
+ act(() => { root.scrollTo({ top: 340 }); vi.advanceTimersByTime(0) })
expect(root.scrollTop).toBeGreaterThan(160)
expect(fetchNextPage).toHaveBeenCalledOnce()
expect(fetchNextPage).toHaveBeenCalledWith({ cancelRefetch: false })
@@ -616,8 +642,7 @@ describe("BotActivityModal CommunitySheet contract", () => {
{ crossDay: false, offset: 80, measuredHeight: 33 },
{ crossDay: true, offset: 0, measuredHeight: 33 },
{ crossDay: true, offset: 80, measuredHeight: 33 },
- ])("keeps event Y with deferred scroll events at $offset, cross-day $crossDay, measured $measuredHeight", ({ crossDay, offset, measuredHeight }) => {
- deferScrollEvents = true
+ ])("keeps event Y independently of pending Query completion at $offset, cross-day $crossDay, measured $measuredHeight", ({ crossDay, offset, measuredHeight }) => {
auditState.events = events(50)
for (const item of auditState.events) rowHeights.set(item.id, measuredHeight)
const { renderer } = renderModal()
@@ -645,7 +670,6 @@ describe("BotActivityModal CommunitySheet contract", () => {
it("updates the visible date at a payload boundary before the native range changes", () => {
- deferScrollEvents = true
auditState.events = [...events(10), ...events(40, "2026-08-28").map(item => ({ ...item, id: `next-${item.id}` }))]
const { renderer } = renderModal()
act(() => vi.advanceTimersByTime(500))
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 0b0c9a5e0..9c6a1a126 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.tsx
+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx
@@ -4,6 +4,8 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useSyncExternalStore } f
import { useAtom, useCreateAtom } from "@tanstack/react-store"
import { useVirtualizer } from "@tanstack/react-virtual"
import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
+import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
+import { VirtualRows } from "@/components/community/messages/virtual-cursor-list"
import { AgentAvatar } from "@/components/avatar"
import { CommunitySheet } from "@/components/community/shell/community-sheet"
import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
@@ -74,7 +76,7 @@ export function BotActivityModal({
const notifyVisibleDate = useCallback(() => visibleDateListener.current?.(), [])
// eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
const virtualizer = useVirtualizer({
- directDomUpdates: true,
+ ...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
onChange: notifyVisibleDate,
count: chronological.length,
getScrollElement: () => scrollRoot,
@@ -114,14 +116,14 @@ export function BotActivityModal({
return chronological[item?.index ?? 0]?.createdAt ?? ""
}, [virtualizer, dateAfter, chronological])
const visibleDate = useSyncExternalStore(subscribeVisibleDate, getVisibleDate, getVisibleDate)
- const virtualItems = virtualizer.getVirtualItems()
const loadOlder = useCallback(() => {
void fetchNextPage({ cancelRefetch: false })
}, [fetchNextPage])
useVirtualCursorPagination({
virtualizer,
count: chronological.length,
- enabled: open && initialized && Boolean(scrollRoot?.clientHeight),
+ enabled: open && initialized && Boolean(scrollRoot?.clientHeight)
+ && Math.abs((virtualizer.scrollOffset ?? 0) - (scrollRoot?.scrollTop ?? 0)) <= 1,
hasMore: hasNextPage,
isFetching: isFetching || isFetchingNextPage,
isError: isFetchNextPageError,
@@ -173,33 +175,24 @@ export function BotActivityModal({
) : chronological.length === 0 ? (
<EmptyState />
) : (
- <div ref={virtualizer.containerRef} style={{ position: "relative", width: "100%" }}>
+ <VirtualRows
+ items={chronological}
+ virtualizer={virtualizer}
+ getRowAttributes={(event, index) => ({
+ "data-activity-row-key": getItemKey(index),
+ "data-activity-event-id": event.id,
+ })}
+ renderItem={(event, index) => (
+ <>
+ <BotActivityRow event={event} />
+ {dateAfter[index] && <DayDivider date={dateAfter[index]} />}
+ </>
+ )}
+ >
<div className="sticky top-0 z-10" data-activity-sticky-date={dayKey(visibleDate)}>
<DayDivider date={visibleDate} />
</div>
- {virtualItems.map((virtualRow) => {
- const event = chronological[virtualRow.index]
- const nextDate = dateAfter[virtualRow.index]
- return (
- <div
- key={virtualRow.key}
- ref={virtualizer.measureElement}
- data-index={virtualRow.index}
- data-activity-row-key={virtualRow.key}
- data-activity-event-id={event.id}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- }}
- >
- <BotActivityRow event={event} />
- {nextDate && <DayDivider date={nextDate} />}
- </div>
- )
- })}
- </div>
+ </VirtualRows>
)}
</CommunitySheet>
)
diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
index 9ceac4e9d..08f730fd7 100644
--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
@@ -215,7 +215,7 @@ describe("useBotListController", () => {
scrollIntoView.mockReset()
})
- afterEach(() => vi.useRealTimers())
+ afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() })
const render = () => {
let renderer!: ReturnType<typeof rtlRender>
@@ -414,18 +414,19 @@ describe("useBotListController", () => {
})
it("does nothing without a target or without bots", () => {
+ const schedule = vi.spyOn(globalThis, "setTimeout")
mocks.target = null
render()
expect(scrollIntoView).not.toHaveBeenCalled()
expect(latest.highlightId).toBeNull()
- expect(vi.getTimerCount()).toBe(0)
+ expect(schedule.mock.calls.filter(([, delay]) => delay === 2000)).toHaveLength(0)
mocks.target = "mac1"
mocks.bots = []
render()
expect(scrollIntoView).not.toHaveBeenCalled()
expect(latest.highlightId).toBeNull()
- expect(vi.getTimerCount()).toBe(0)
+ expect(schedule.mock.calls.filter(([, delay]) => delay === 2000)).toHaveLength(0)
})
it("opens an owned audit deep link only after its bot is available", () => {
@@ -621,28 +622,36 @@ describe("useBotListController", () => {
})
it("clears a normally consumed target after exactly 2000ms", () => {
+ const schedule = vi.spyOn(globalThis, "setTimeout")
render()
expect(latest.highlightId).toBe("mac1")
- expect(vi.getTimerCount()).toBe(1)
+ expect(schedule.mock.calls.filter(([, delay]) => delay === 2000)).toHaveLength(1)
act(() => vi.advanceTimersByTime(1999))
expect(latest.highlightId).toBe("mac1")
act(() => vi.advanceTimersByTime(1))
expect(latest.highlightId).toBeNull()
- expect(vi.getTimerCount()).toBe(0)
+ expect(schedule.mock.calls.filter(([, delay]) => delay === 2000)).toHaveLength(1)
})
it("replaces A with B, cancels A's timer, and cleans the active timer on unmount", () => {
+ const schedule = vi.spyOn(globalThis, "setTimeout")
+ const cancel = vi.spyOn(globalThis, "clearTimeout")
const renderer = render()
expect(scrollIntoView).toHaveBeenCalledTimes(1)
- expect(vi.getTimerCount()).toBe(1)
+ const first = schedule.mock.calls.findIndex(([, delay]) => delay === 2000)
+ expect(first).toBeGreaterThanOrEqual(0)
+ const firstTimer = schedule.mock.results[first].value
mocks.target = "mac2"
act(() => renderer.rerender(React.createElement(Probe)))
expect(scrollIntoView).toHaveBeenCalledTimes(2)
expect(latest.highlightId).toBe("mac2")
- expect(vi.getTimerCount()).toBe(1)
+ const timers = schedule.mock.calls.flatMap(([, delay], index) => delay === 2000 ? [schedule.mock.results[index].value] : [])
+ expect(timers).toHaveLength(2)
+ expect(cancel).toHaveBeenCalledWith(firstTimer)
act(() => vi.advanceTimersByTime(1999))
expect(latest.highlightId).toBe("mac2")
act(() => renderer.unmount())
+ expect(cancel).toHaveBeenCalledWith(timers[1])
act(() => vi.advanceTimersByTime(2000))
expect(scrollIntoView).toHaveBeenCalledTimes(2)
})
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
index 943072d24..7bf540a69 100644
--- 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
@@ -40,8 +40,10 @@ vi.mock("@/lib/community-db/projections", async (load) => ({
...await load<typeof import("@/lib/community-db/projections")>(),
useCanonicalProfilesByUserId: () => new Map(),
}))
-vi.mock("@tanstack/react-virtual", () => ({
+vi.mock("@tanstack/react-virtual", async (load) => ({
+ ...await load<typeof import("@tanstack/react-virtual")>(),
useVirtualizer: ({ count, getItemKey }: { count: number; getItemKey: (index: number) => string | number }) => ({
+ range: count ? { startIndex: 0, endIndex: count - 1 } : null,
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,
diff --git a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
new file mode 100644
index 000000000..523ecee50
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
@@ -0,0 +1,168 @@
+import { createElement } from "react"
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
+import { act, mockElementGeometry, render } from "@/test/react-dom-harness"
+import type { ForumThread } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
+import { ForumView } from "./forum-view"
+
+const posts: ForumThread[] = Array.from({ length: 100 }, (_, index) => ({
+ id: `post-${index}`,
+ name: `Long forum title ${index} `.repeat(6),
+ parentSeq: 100 - index,
+ messageCount: 1,
+ lastMessageAt: "2026-10-21T00:00:00.000Z",
+ parent: { authorName: "Alice", text: "root" },
+ authorId: "alice",
+ authorAvatar: "A",
+ authorAvatarVersion: 0,
+ openerMessageId: `opener-${index}`,
+ tags: [],
+ preview: "Preview text",
+ participants: [],
+ participantCount: 1,
+}))
+const observers = new Map<ResizeObserverCallback, Set<Element>>()
+let rowHeight = (index: number) => 128 + index % 3 * 8
+
+beforeEach(() => {
+ observers.clear()
+ rowHeight = (index: number) => 128 + index % 3 * 8
+ vi.stubGlobal("ResizeObserver", class {
+ private nodes = new Set<Element>()
+ constructor(callback: ResizeObserverCallback) { observers.set(callback, this.nodes) }
+ observe(node: Element) { this.nodes.add(node) }
+ unobserve(node: Element) { this.nodes.delete(node) }
+ disconnect() { this.nodes.clear() }
+ })
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) {
+ return this.hasAttribute("data-index") ? rowHeight(Number(this.dataset.index)) : 0
+ })
+})
+
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
+
+it("keeps native forum rows positioned without individual transforms across scrolling and append", () => {
+ const onLoadMore = vi.fn()
+ const onScrollRoot = (node: HTMLDivElement | null) => {
+ if (!node) return
+ mockElementGeometry(node, { clientHeight: 751, clientWidth: 390, scrollHeight: 15000 })
+ Object.defineProperty(node, "scrollTo", {
+ configurable: true,
+ value: ({ top = 0 }: ScrollToOptions) => { node.scrollTop = top },
+ })
+ }
+ const props = {
+ forumChannelId: "forum-native-layout",
+ members: [],
+ posts,
+ tag: "All",
+ hasMore: true,
+ onTagChange: () => {},
+ onOpenPost: () => {},
+ onLoadMore,
+ onScrollRoot,
+ }
+ const view = render(createElement(ForumView, props))
+ const root = view.getByTestId(tid.forumPostList)
+ const readRows = () => Array.from(root.querySelectorAll<HTMLElement>("[data-index]"))
+ expect(view.queryByTestId(tid.forumThreadCard("post-45"))).toBeNull()
+ act(() => {
+ root.scrollTop = 5900
+ root.dispatchEvent(new Event("scroll"))
+ const rows = readRows()
+ expect(rows.length).toBeGreaterThan(5)
+ expect(rows.every(row => row.style.transform === "")).toBe(true)
+ expect(Number.parseFloat(rows[0].style.top)).toBeLessThanOrEqual(root.scrollTop)
+ const last = rows.at(-1)!
+ expect(Number.parseFloat(last.style.top) + last.offsetHeight).toBeGreaterThan(root.scrollTop + root.clientHeight)
+ })
+ act(() => {
+ for (const [callback, nodes] of observers) {
+ const entries = [...nodes].filter(node => node.hasAttribute("data-index")).map<ResizeObserverEntry>(node => ({
+ target: node,
+ borderBoxSize: [{ blockSize: (node as HTMLElement).offsetHeight, inlineSize: 390 }],
+ contentBoxSize: [{ blockSize: (node as HTMLElement).offsetHeight, inlineSize: 390 }],
+ devicePixelContentBoxSize: [{ blockSize: (node as HTMLElement).offsetHeight, inlineSize: 390 }],
+ contentRect: new DOMRect(0, 0, 390, (node as HTMLElement).offsetHeight),
+ }))
+ if (entries.length) callback(entries, {} as ResizeObserver)
+ }
+ })
+ const previousRows = readRows()
+ for (let index = 1; index < previousRows.length; index++) {
+ expect(Number.parseFloat(previousRows[index].style.top)).toBe(
+ Number.parseFloat(previousRows[index - 1].style.top) + previousRows[index - 1].offsetHeight,
+ )
+ }
+ const positions = previousRows.map(row => row.style.top)
+ view.rerender(createElement(ForumView, {
+ ...props,
+ posts: [...posts, { ...posts[0], id: "post-100", openerMessageId: "opener-100", parentSeq: 0 }],
+ }))
+ expect(readRows()).toEqual(previousRows)
+ expect(readRows().map(row => row.style.top)).toEqual(positions)
+ expect(onLoadMore).not.toHaveBeenCalled()
+})
+
+
+function renderUniformForum(clientHeight: number, count = posts.length) {
+ rowHeight = () => 128
+ const onLoadMore = vi.fn()
+ const props = {
+ forumChannelId: "forum-native-reserve",
+ members: [],
+ posts: posts.slice(0, count),
+ tag: "All",
+ hasMore: true,
+ onTagChange: () => {},
+ onOpenPost: () => {},
+ onLoadMore,
+ onScrollRoot: (node: HTMLDivElement | null) => {
+ if (!node) return
+ mockElementGeometry(node, { clientHeight, clientWidth: 390, scrollHeight: count * 128 })
+ Object.defineProperty(node, "scrollTo", {
+ configurable: true,
+ value: ({ top = 0 }: ScrollToOptions) => { node.scrollTop = top },
+ })
+ },
+ }
+ const view = render(createElement(ForumView, props))
+ return { view, props, onLoadMore, root: view.getByTestId(tid.forumPostList) }
+}
+
+it.each([320, 751, 1500])("keeps mounted rows over a %ipx viewport advance before scroll delivery", (height) => {
+ const { root, onLoadMore } = renderUniformForum(height)
+ const offset = 30 * 128
+ for (const direction of [-1, 1]) {
+ act(() => {
+ root.scrollTop = offset
+ root.dispatchEvent(new Event("scroll"))
+ })
+ const rows = [...root.querySelectorAll<HTMLElement>("[data-index]")]
+ expect(rows.length).toBeLessThan(posts.length)
+ root.scrollTop = offset + direction * height
+ const first = rows[0]
+ const last = rows.at(-1)!
+ expect(Number.parseFloat(first.style.top)).toBeLessThanOrEqual(root.scrollTop)
+ expect(Number.parseFloat(last.style.top) + last.offsetHeight).toBeGreaterThanOrEqual(root.scrollTop + height)
+ }
+ expect(onLoadMore).not.toHaveBeenCalled()
+})
+
+it("keeps the original paging boundary while rendering a larger reserve", () => {
+ const { view, props, root, onLoadMore } = renderUniformForum(751, 20)
+ expect(onLoadMore).not.toHaveBeenCalled()
+ act(() => {
+ root.scrollTop = 8 * 128
+ root.dispatchEvent(new Event("scroll"))
+ })
+ expect(view.queryByTestId(tid.forumThreadCard("post-19"))).not.toBeNull()
+ expect(onLoadMore).not.toHaveBeenCalled()
+ act(() => {
+ root.scrollTop = 9 * 128
+ root.dispatchEvent(new Event("scroll"))
+ })
+ expect(onLoadMore).toHaveBeenCalledTimes(1)
+ view.rerender(createElement(ForumView, props))
+ expect(onLoadMore).toHaveBeenCalledTimes(1)
+})
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 9b9f49cfc..997fec917 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
@@ -78,6 +78,8 @@ describe("ForumView scroll anchoring", () => {
})
afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
for (const [name, descriptor] of [
["scrollTop", scrollTopDescriptor],
["scrollHeight", scrollHeightDescriptor],
@@ -108,6 +110,60 @@ describe("ForumView scroll anchoring", () => {
expect(root.scrollTop).toBe(20)
})
+ it("retains measured titles across unrelated list renders and remeasures changed content and viewport", async () => {
+ let width = 18
+ const frames = new Map<number, FrameRequestCallback>()
+ let frameId = 0
+ const observations = new Map<Element, ResizeObserverCallback>()
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++frameId, callback); return frameId })
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { frames.delete(id) })
+ vi.stubGlobal("ResizeObserver", class {
+ constructor(private callback: ResizeObserverCallback) {}
+ observe(element: Element) { observations.set(element, this.callback) }
+ unobserve(element: Element) { observations.delete(element) }
+ disconnect() {}
+ })
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(() => new DOMRect(0, 0, width, 1))
+ vi.spyOn(HTMLElement.prototype, "getClientRects").mockImplementation(function (this: HTMLElement) {
+ const lines = Math.ceil(Array.from(this.textContent ?? "").length / width)
+ return Object.assign(Array.from({ length: lines }, (_, index) => new DOMRect(0, index * 2, width, 1)), { item: () => null }) as unknown as DOMRectList
+ })
+ const clone = vi.spyOn(HTMLElement.prototype, "cloneNode")
+ const copies = (id: string) => clone.mock.contexts.filter(node => node.querySelector(`[data-testid="${tid.forumThreadTitleText(id)}"]`)).length
+ const flushFrames = () => act(() => {
+ const pending = [...frames.values()]
+ frames.clear()
+ for (const callback of pending) callback(0)
+ })
+ const first = { ...post("p1"), name: "Long wrapping forum title ".repeat(8), parentSeq: 205 }
+ const second = { ...post("p2"), name: "Second title", parentSeq: 204 }
+ const view = render(createElement(ForumView, props([first, second])))
+ await act(async () => { await Promise.resolve() })
+ flushFrames()
+ const measured = [copies("p1"), copies("p2")]
+ expect(measured.every(count => count > 0)).toBe(true)
+ for (let index = 0; index < 5; index++) {
+ view.rerender(createElement(ForumView, props([{ ...first }, { ...second }], "All", index % 2 === 0)))
+ }
+ expect([copies("p1"), copies("p2")]).toEqual(measured)
+ view.rerender(createElement(ForumView, props([first, second, { ...post("p3"), parentSeq: 203 }])))
+ expect([copies("p1"), copies("p2")]).toEqual(measured)
+ expect(copies("p3")).toBeGreaterThan(0)
+ const changed = { ...first, name: "Changed wrapping title ".repeat(8), parentSeq: 999 }
+ view.rerender(createElement(ForumView, props([changed, second])))
+ expect(copies("p1")).toBe(measured[0] + 1)
+ expect(copies("p2")).toBe(measured[1])
+ expect(view.getByTestId(tid.forumThreadTitle("p1"))).toHaveAttribute("aria-label", `${changed.name} #999`)
+ expect(view.getByTestId(tid.forumThreadSeq("p1"))).toHaveTextContent("#999")
+ const title = view.getByTestId(tid.forumThreadTitleText("p1"))
+ const clamp = title.closest<HTMLElement>("[data-clamped]")!
+ width = 28
+ act(() => { observations.get(clamp)!([], {} as ResizeObserver) })
+ flushFrames()
+ expect(copies("p1")).toBe(measured[0] + 2)
+ expect(view.getByTestId(tid.forumThreadTitleText("p1"))).toHaveTextContent("…")
+ })
+
it("updates the full title and sequence without a measured duplicate and keeps row activation", () => {
const onOpenPost = vi.fn()
const initial: ForumThread = { ...post("p1"), name: "Short title", parentSeq: 205 }
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index e7ebb7c80..d6d44172b 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -3,8 +3,8 @@
import { useObservedRegion } from "@/lib/observability/regions"
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useLayoutEffect, useRef } from "react"
-import { useVirtualizer } from "@tanstack/react-virtual"
+import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react"
+import { defaultRangeExtractor, useVirtualizer, type Range } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
import { Archive, ArchiveRestore, MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
@@ -37,6 +37,12 @@ import {
const MAX_AVATARS = 5
const MAX_VISIBLE_TAGS = 2
+const FORUM_VIRTUALIZER_DOM_MODE = "position"
+const FORUM_VIRTUALIZER_OVERSCAN = 5
+const forumRangeExtractor = (range: Range) => defaultRangeExtractor({
+ ...range,
+ overscan: range.overscan + range.endIndex - range.startIndex + 1,
+})
export function shouldActivateForumRow(event: {
key: string
@@ -98,7 +104,7 @@ export function toggleForumArchivedStatus(tags: string[]): string[] {
: [...ordinaryTags, FORUM_ARCHIVE_TAG]
}
-function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; seq?: number }) {
+const ForumPostTitle = memo(function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; seq?: number }) {
return (
<h3
data-testid={tid.forumThreadTitle(postId)}
@@ -121,7 +127,7 @@ function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; s
/>
</h3>
)
-}
+})
// Forum channel body — rendered under the shared ChannelHeader. A feed of posts;
// each post opens as a thread. The filter bar's tag chips are DERIVED from the
@@ -187,13 +193,26 @@ export function ForumView({
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
+ directDomUpdatesMode: FORUM_VIRTUALIZER_DOM_MODE,
count: posts.length,
getScrollElement: () => scrollRef.current,
estimateSize,
getItemKey,
- overscan: 5,
+ overscan: FORUM_VIRTUALIZER_OVERSCAN,
+ rangeExtractor: forumRangeExtractor,
initialRect: { width: 0, height: 800 },
})
+ const virtualItems = virtualizer.getVirtualItems()
+ const paginationRange = virtualizer.range
+ const paginationItems = useMemo(() => {
+ if (!paginationRange) return []
+ const indexes = new Set(defaultRangeExtractor({
+ ...paginationRange,
+ count: posts.length,
+ overscan: FORUM_VIRTUALIZER_OVERSCAN,
+ }))
+ return virtualItems.filter(item => indexes.has(item.index))
+ }, [paginationRange, posts.length, virtualItems])
const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])
useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)
const filterTags = availableTags.length > 0
@@ -221,7 +240,7 @@ export function ForumView({
virtualizer.scrollToIndex(0, { align: "start" })
}, [posts.length, tag, virtualizer])
useVirtualCursorPagination({
- virtualizer,
+ virtualizer: { getVirtualItems: () => paginationItems },
count: posts.length,
enabled: !loading,
hasMore,
@@ -331,6 +350,7 @@ export function ForumView({
) : (
<>
<VirtualRows
+ directDomUpdatesMode={FORUM_VIRTUALIZER_DOM_MODE}
items={posts}
virtualizer={virtualizer}
renderItem={(p, index) => {
diff --git a/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx b/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx
new file mode 100644
index 000000000..2972ad9b6
--- /dev/null
+++ b/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx
@@ -0,0 +1,95 @@
+import { createElement, useCallback, useLayoutEffect, useRef } from "react"
+import { useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render } from "@/test/react-dom-harness"
+import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
+import { VirtualRows } from "./virtual-cursor-list"
+
+const items = Array.from({ length: 100 }, (_, index) => `row-${index}`)
+
+function List({ direct, mode, ready }: {
+ direct: boolean
+ mode: "transform" | "position"
+ ready: (virtualizer: ReactVirtualizer<HTMLDivElement, Element>) => void
+}) {
+ const root = useRef<HTMLDivElement>(null)
+ const bind = useCallback((node: HTMLDivElement | null) => {
+ root.current = node
+ if (!node) return
+ Object.defineProperties(node, {
+ clientHeight: { configurable: true, value: 120 },
+ clientWidth: { configurable: true, value: 320 },
+ offsetHeight: { configurable: true, value: 140 },
+ offsetWidth: { configurable: true, value: 340 },
+ scrollHeight: { configurable: true, value: 4032 },
+ scrollTo: { configurable: true, value: ({ top = 0 }: ScrollToOptions) => { node.scrollTop = top } },
+ })
+ }, [])
+ const virtualizer = useVirtualizer<HTMLDivElement, Element>({
+ ...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
+ directDomUpdates: direct,
+ directDomUpdatesMode: mode,
+ count: items.length,
+ getScrollElement: () => root.current,
+ getItemKey: (index) => items[index],
+ estimateSize: () => 40,
+ paddingStart: 32,
+ overscan: 5,
+ initialRect: { width: 320, height: 120 },
+ })
+ useLayoutEffect(() => { ready(virtualizer) }, [ready, virtualizer])
+ return createElement("div", { ref: bind, "data-testid": "viewport" },
+ createElement(VirtualRows<string>, {
+ items,
+ virtualizer,
+ reactLayout: !direct,
+ directDomUpdatesMode: mode,
+ getRowAttributes: (item) => ({ "data-row-id": item }),
+ renderItem: (item) => item,
+ }, createElement("div", { "data-testid": "sticky-date" }, "Today")),
+ )
+}
+
+beforeEach(() => {
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(40)
+})
+afterEach(() => { vi.restoreAllMocks() })
+
+describe.each([
+ { direct: true, mode: "transform" as const },
+ { direct: true, mode: "position" as const },
+ { direct: false, mode: "transform" as const },
+])("native row shell with direct geometry=$direct, mode=$mode", ({ direct, mode }) => {
+ it("mounts the loaded range in the scroll dispatch and measures the visible client viewport", () => {
+ let native!: ReactVirtualizer<HTMLDivElement, Element>
+ const view = render(createElement(List, { direct, mode, ready: (instance) => { native = instance } }))
+ const root = view.getByTestId("viewport")
+ expect(native.scrollRect).toEqual({ width: 320, height: 120 })
+ expect(view.getByTestId("sticky-date").parentElement).toBe(root.firstElementChild)
+ expect(root.querySelector('[data-row-id="row-25"]')).toBeNull()
+ act(() => {
+ root.scrollTop = 800
+ root.dispatchEvent(new Event("scroll"))
+ const row = root.querySelector<HTMLElement>('[data-row-id="row-25"]')
+ expect(row).not.toBeNull()
+ expect(row!.dataset.index).toBe("25")
+ if (direct && mode === "position") {
+ expect(row!.style.transform).toBe("")
+ expect(row!.style.top).toBe("1032px")
+ } else {
+ expect(row!.style.transform).toBe("translate3d(0, 1032px, 0)")
+ }
+ })
+ expect(root.firstElementChild).toHaveStyle({ height: "4032px" })
+ const row = root.querySelector<HTMLElement>('[data-row-id="row-26"]')!
+ act(() => { native.resizeItem(25, 80) })
+ expect(root.querySelector('[data-row-id="row-26"]')).toBe(row)
+ if (direct && mode === "position") {
+ expect(row.style.top).toBe("1112px")
+ expect(row.style.transform).toBe("")
+ } else {
+ expect(row.style.transform).toBe("translate3d(0, 1112px, 0)")
+ }
+ expect(root.firstElementChild).toHaveStyle({ height: "4072px" })
+ })
+})
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 4dc2c8179..132bd0048 100644
--- a/src/web/src/components/community/messages/virtual-cursor-list.tsx
+++ b/src/web/src/components/community/messages/virtual-cursor-list.tsx
@@ -11,12 +11,18 @@ export function VirtualRows<T>({
renderItem,
rowRole,
reactLayout = false,
+ directDomUpdatesMode = "transform",
+ children,
+ getRowAttributes,
}: {
items: T[]
virtualizer: ReactVirtualizer<HTMLDivElement, Element>
renderItem: (item: T, index: number) => ReactNode
rowRole?: "listitem"
reactLayout?: boolean
+ directDomUpdatesMode?: "transform" | "position"
+ children?: ReactNode
+ getRowAttributes?: (item: T, index: number) => Record<`data-${string}`, string | number | undefined>
}) {
return (
<div
@@ -27,17 +33,19 @@ export function VirtualRows<T>({
...(reactLayout ? { height: virtualizer.getTotalSize() } : {}),
}}
>
+ {children}
{virtualizer.getVirtualItems().map((virtualRow) => {
const item = items[virtualRow.index]
return (
<div
+ {...getRowAttributes?.(item, virtualRow.index)}
key={virtualRow.key}
role={rowRole}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
style={{
position: "absolute",
- top: 0,
+ ...(reactLayout || directDomUpdatesMode === "transform" ? { top: 0 } : {}),
left: 0,
width: "100%",
...(reactLayout ? { transform: `translate3d(0, ${virtualRow.start - virtualizer.options.scrollMargin}px, 0)` } : {}),
diff --git a/src/web/src/hooks/community/use-forum-feed.pagination.dom.test.tsx b/src/web/src/hooks/community/use-forum-feed.pagination.dom.test.tsx
new file mode 100644
index 000000000..33f5a06ed
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-feed.pagination.dom.test.tsx
@@ -0,0 +1,63 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClientProvider } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { useForumFeed } from "./use-forum-feed"
+
+const load = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))
+vi.mock("./use-channel-panels", () => ({ useForumTags: () => ({ data: { tags: [] }, isSuccess: true }) }))
+beforeEach(() => { load.mockReset(); localStorage.clear() })
+
+describe("forum native page demand", () => {
+ it("reuses a held cursor operation across repeated demands and renders before advancing the cursor", async () => {
+ const owner = await createCommunityQueryOwner()
+ const entry = forumConversationEntryFixture()
+ entry.forumFeed!.page = { hasMore: true, nextCursor: "older-2" }
+ type Page = NonNullable<typeof entry.forumFeed>
+ const page = (id: string, cursor: string | null): Page => ({
+ ...entry.forumFeed!,
+ threads: [{ ...entry.forumFeed!.threads[0], id, parentMessageId: `opener-${id}`, createdAt: `2026-09-${id === "t2" ? "29" : "28"}T00:00:00.000Z` }],
+ included: { ...entry.forumFeed!.included, messages: [{ ...entry.forumFeed!.included.messages[0], id: `opener-${id}`, content: id, seq: id === "t2" ? 2 : 3 }] },
+ page: { hasMore: cursor !== null, nextCursor: cursor },
+ })
+ let release!: (value: Page) => void
+ const held = new Promise<Page>((resolve) => { release = resolve })
+ const requests: Array<{ cursor: string | null; signal: AbortSignal }> = []
+ load.mockImplementation((path: string, options?: { signal?: AbortSignal }) => {
+ if (path.includes("/messages?entry=1")) return Promise.resolve(entry)
+ if (path.includes("/threads?")) {
+ const cursor = new URL(path, "https://local").searchParams.get("cursor")
+ requests.push({ cursor, signal: options!.signal! })
+ return cursor === "older-2" ? held : Promise.resolve(page("t3", null))
+ }
+ throw new Error(`Unexpected request: ${path}`)
+ })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ const view = renderHook(() => useForumFeed("s1", "c1"), { wrapper })
+ await waitFor(() => expect(view.result.current.posts.map(({ id }) => id)).toEqual(["t1"]))
+ const append = view.result.current.fetchOlder
+ act(() => { append() })
+ await waitFor(() => expect(requests).toHaveLength(1))
+ await act(async () => {
+ view.rerender()
+ append()
+ view.result.current.fetchOlder()
+ append()
+ await Promise.resolve()
+ })
+ expect(view.result.current.fetchOlder).toBe(append)
+ expect(requests).toHaveLength(1)
+ expect(requests[0].signal.aborted).toBe(false)
+ await act(async () => { release(page("t2", "older-3")) })
+ await waitFor(() => expect(view.result.current.posts.map(({ id }) => id)).toEqual(["t1", "t2"]))
+ act(() => { view.result.current.fetchOlder() })
+ await waitFor(() => expect(view.result.current.posts.map(({ id }) => id)).toEqual(["t1", "t2", "t3"]))
+ expect(requests.map(({ cursor }) => cursor)).toEqual(["older-2", "older-3"])
+ expect(view.result.current.hasMoreOlder).toBe(false)
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 87a010dd7..aebab3caf 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -110,5 +110,7 @@ export function useForumFeed(serverId: string, channelId: string) {
const messageIds = useMemo(() => [...new Set(query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [])], [query.data?.pages])
const messages = useCanonicalMessagesById(messageIds)
const posts = useMemo(() => mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag), [query.data?.pages, messages, channels, profiles, selectedTag])
- return { ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: query.data ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : query.data ? "none" as const : "window" as const }, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() } }
+ const fetchNextPage = query.fetchNextPage
+ const fetchOlder = useCallback(() => { void fetchNextPage({ cancelRefetch: false }) }, [fetchNextPage])
+ return { ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: query.data ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : query.data ? "none" as const : "window" as const }, posts, tag, selectTag, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder }
}
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 908e95887..1a228eec5 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
@@ -116,13 +116,12 @@ describe("locked native adapter and existing message scroll owner", () => {
if (position === "away") h.move(300)
const before = bodyTop(h.root, position === "away" ? "m2" : "m13")
const native = scrollFixture.latest.virtualizer
- const rect = { ...native.scrollRect }
expect(scrollFixture.frames.size).toBe(0)
h.root.style.borderBottom = "100px solid transparent"
expect(h.root.clientHeight).toBe(400)
expect(h.root.offsetHeight).toBe(500)
resize()
- expect(native.scrollRect).toEqual(rect)
+ expect(native.scrollRect).toEqual({ width: h.root.clientWidth, height: h.root.clientHeight })
if (position === "present") expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
else expect(bodyTop(h.root, "m2")).toBe(before)
expect(scrollFixture.latest.readPositionReady).toBe(true)
@@ -133,10 +132,9 @@ describe("locked native adapter and existing message scroll owner", () => {
h.update({ scrollToMessageId: "m4" })
expect(positioned).toHaveBeenCalledWith("m4")
const top = bodyTop(h.root, "m4")
- const rect = { ...scrollFixture.latest.virtualizer.scrollRect }
scrollFixture.scrollbarWidth = 11
resize()
- expect(scrollFixture.latest.virtualizer.scrollRect).toEqual(rect)
+ expect(scrollFixture.latest.virtualizer.scrollRect).toEqual({ width: h.root.clientWidth, height: h.root.clientHeight })
expect(bodyTop(h.root, "m4")).toBe(top)
expect(scrollFixture.latest.readPositionReady).toBe(true)
h.move(0)
@@ -1269,7 +1267,7 @@ describe("locked native adapter and existing message scroll owner", () => {
runFrames(1)
expect(offset).not.toHaveBeenCalled()
})
- it("keeps the content viewport anchor while native border-box delivery is pending with a scrollbar", () => {
+ it("keeps the client viewport anchor while native rectangle delivery is pending with a scrollbar", () => {
vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(() => scrollFixture.width - 11)
const h = mount()
h.move(h.root.scrollHeight - scrollFixture.height - 2)
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index a78b1f85a..981c76fc7 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -123,8 +123,6 @@ export function useScrollAnchor({
itemStart: number
clientHeight: number
clientWidth: number
- outerHeight: number
- outerWidth: number
scrollHeight: number
scrollTop: number
total: number
@@ -345,12 +343,12 @@ export function useScrollAnchor({
const previous = acceptedGeometryRef.current
const pendingViewportRect = viewportTransition && previous?.epoch === owner.epoch
&& (previous.clientHeight !== root?.clientHeight || previous.clientWidth !== root?.clientWidth)
- && Math.abs((native?.scrollRect?.height ?? 0) - previous.outerHeight) <= 1
- && Math.abs((native?.scrollRect?.width ?? 0) - previous.outerWidth) <= 1
+ && Math.abs((native?.scrollRect?.height ?? 0) - previous.clientHeight) <= 1
+ && Math.abs((native?.scrollRect?.width ?? 0) - previous.clientWidth) <= 1
if (!owner.active || !root || !native || root.clientHeight <= 0
|| Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1
- || (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.offsetHeight) > 1
- || Math.abs((native.scrollRect?.width ?? 0) - root.offsetWidth) > 1))) return null
+ || (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.clientHeight) > 1
+ || Math.abs((native.scrollRect?.width ?? 0) - root.clientWidth) > 1))) return null
const total = native.getTotalSize()
const max = Math.max(0, root.scrollHeight - root.clientHeight)
if (root.scrollTop < 0 || root.scrollTop > max + 1) return null
@@ -370,7 +368,6 @@ export function useScrollAnchor({
return {
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: native.isAtEnd(1) && !followSuspension.get()
diff --git a/src/web/src/hooks/community/virtualizer-react-options.test.ts b/src/web/src/hooks/community/virtualizer-react-options.test.ts
index 7d211bf7a..d6072834c 100644
--- a/src/web/src/hooks/community/virtualizer-react-options.test.ts
+++ b/src/web/src/hooks/community/virtualizer-react-options.test.ts
@@ -2,9 +2,9 @@ import { describe, expect, it } from "vitest"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"
describe("COMMUNITY_VIRTUALIZER_REACT_OPTIONS", () => {
- it("keeps lifecycle measurements synchronous through direct DOM updates without React flushSync", () => {
+ it("uses native synchronous range updates with direct DOM geometry", () => {
expect(COMMUNITY_VIRTUALIZER_REACT_OPTIONS).toEqual({
- useFlushSync: false,
+ useFlushSync: true,
directDomUpdates: true,
})
})
diff --git a/src/web/src/hooks/community/virtualizer-react-options.ts b/src/web/src/hooks/community/virtualizer-react-options.ts
index 32e50b720..d5f11cfe6 100644
--- a/src/web/src/hooks/community/virtualizer-react-options.ts
+++ b/src/web/src/hooks/community/virtualizer-react-options.ts
@@ -1,4 +1,4 @@
export const COMMUNITY_VIRTUALIZER_REACT_OPTIONS = {
- useFlushSync: false,
+ useFlushSync: true,
directDomUpdates: true,
} as const