Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): prevent mobile message overlap (#482)

Gustavo Ye1770e8b1bd1d
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 44d645a78..f333e2980 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -27,6 +27,7 @@ export const SPEC_SECONDS = {
"18-new-divider-scroll.spec.ts": 46,
"19-marketing-seo.spec.ts": 5,
"20-community-attachment-thumbnails.spec.ts": 60,
+ "21-mobile-message-layout.spec.ts": 20,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 634b7ac4b..9c81ff0ce 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -37,7 +37,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([132, 134, 135, 136, 136])
+ expect(totals.sort((left, right) => left - right)).toEqual([136, 136, 140, 140, 141])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
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 8b066bb0f..8cc11646b 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,6 +16,7 @@ describe("community virtualizer direct DOM contract", () => {
expect(messageList).toContain("<VirtualRows")
expect(scrollAnchor).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")
+ expect(scrollAnchor).toContain("const size = measureMessageRow(element)")
expect(virtualRows).toContain("ref={virtualizer.containerRef}")
expect(virtualRows).toContain("ref={virtualizer.measureElement}")
expect(virtualRows).not.toContain("virtualizer.getTotalSize()")
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
new file mode 100644
index 000000000..d19ad69d4
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
@@ -0,0 +1,148 @@
+/**
+ * The web unit suite runs without a browser DOM. Drive `useScrollAnchor`
+ * through small React/TanStack shims so the row-measurement callback and its
+ * deferred bottom re-pin contract stay covered without duplicating that logic
+ * in a test-only export.
+ */
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import type { VirtualizerOptions } from "@tanstack/react-virtual"
+import type { FlatItem } from "@/lib/community/message-list-items"
+
+let refs: Array<{ current: unknown }> = []
+let refIndex = 0
+let layoutEffects: Array<() => void | (() => void)> = []
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => {
+ const index = refIndex++
+ refs[index] ??= { current: initial }
+ return refs[index]
+ },
+ useLayoutEffect: (effect: () => void | (() => void)) => {
+ layoutEffects.push(effect)
+ },
+ useCallback: <T>(callback: T) => callback,
+}))
+
+const virtualizer = {
+ isAtEnd: vi.fn(() => true),
+ scrollToEnd: vi.fn(),
+ scrollToIndex: vi.fn(),
+ range: null,
+ shouldAdjustScrollPositionOnItemSizeChange: undefined,
+}
+let virtualizerOptions: VirtualizerOptions<HTMLDivElement, Element> | undefined
+
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: (options: VirtualizerOptions<HTMLDivElement, Element>) => {
+ virtualizerOptions = options
+ return virtualizer
+ },
+}))
+
+function resetHarness() {
+ refs = []
+ refIndex = 0
+ layoutEffects = []
+ virtualizerOptions = undefined
+ virtualizer.isAtEnd.mockReturnValue(true)
+ virtualizer.scrollToEnd.mockReset()
+ virtualizer.scrollToIndex.mockReset()
+}
+
+async function mountHook() {
+ const { useScrollAnchor } = await import("./use-scroll-anchor")
+ // The React module is intentionally mocked above; this calls a deterministic
+ // hook shim rather than mounting a real component tree.
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ const result = useScrollAnchor({
+ items: [] as FlatItem[],
+ initialScrollReady: false,
+ heroHeight: 0,
+ heroMeasured: false,
+ })
+
+ const listeners = new Map<string, EventListener>()
+ const scrollWrites: number[] = []
+ let scrollTop = 0
+ const scroller = {
+ scrollHeight: 1_600,
+ clientHeight: 800,
+ addEventListener: (type: string, listener: EventListener) => listeners.set(type, listener),
+ removeEventListener: vi.fn(),
+ get scrollTop() {
+ return scrollTop
+ },
+ set scrollTop(value: number) {
+ scrollTop = value
+ scrollWrites.push(value)
+ },
+ } as unknown as HTMLDivElement
+ result.scrollRef.current = scroller
+
+ // The first layout effect installs the real scroll/wheel intent listeners.
+ layoutEffects[0]?.()
+ return { listeners, scrollWrites }
+}
+
+function growingRow(requestFrame: (callback: FrameRequestCallback) => void) {
+ let height = 400
+ return {
+ element: {
+ getBoundingClientRect: () => ({ height }),
+ get scrollHeight() {
+ return height
+ },
+ isConnected: true,
+ ownerDocument: {
+ defaultView: {
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ requestFrame(callback)
+ return 1
+ },
+ },
+ },
+ } as unknown as Element,
+ growTo: (nextHeight: number) => { height = nextHeight },
+ }
+}
+
+beforeEach(resetHarness)
+
+describe("useScrollAnchor delayed row-growth re-pin", () => {
+ it("measures live growth and re-pins after the direct-DOM size write settles", async () => {
+ const { scrollWrites } = await mountHook()
+ let frame: FrameRequestCallback | undefined
+ const row = growingRow((callback) => { frame = callback })
+ const measure = virtualizerOptions?.measureElement
+ expect(measure).toBeTypeOf("function")
+
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(400)
+ row.growTo(930.4)
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(931)
+ expect(scrollWrites).toEqual([])
+
+ await Promise.resolve()
+ expect(scrollWrites).toEqual([1_600])
+ expect(frame).toBeTypeOf("function")
+
+ frame!(0)
+ expect(scrollWrites).toEqual([1_600, 1_600])
+ })
+
+ it("does not schedule a re-pin after upward user intent", async () => {
+ const { listeners, scrollWrites } = await mountHook()
+ let frame: FrameRequestCallback | undefined
+ const row = growingRow((callback) => { frame = callback })
+ const measure = virtualizerOptions?.measureElement
+
+ listeners.get("wheel")?.({ deltaY: -1 } as WheelEvent)
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(400)
+ row.growTo(780)
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(780)
+ await Promise.resolve()
+
+ expect(scrollWrites).toEqual([])
+ expect(frame).toBeUndefined()
+ })
+})
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 1e8676957..c6413377a 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -6,6 +6,7 @@ import {
findMessageIndex,
findMountScrollTargetIndex,
extractScrollAnchorMessages,
+ measureMessageRow,
NEAR_BOTTOM_PX,
shouldAdjustMessageScrollPosition,
type ScrollAnchorState,
@@ -258,6 +259,31 @@ describe("NEAR_BOTTOM_PX", () => {
})
})
+describe("measureMessageRow", () => {
+ it("re-reads a mounted row after Markdown grows beyond the capped initial estimate", () => {
+ let height = 380
+ const element = {
+ getBoundingClientRect: () => ({ height }),
+ get scrollHeight() {
+ return Math.ceil(height)
+ },
+ } as unknown as Element
+
+ expect(measureMessageRow(element)).toBe(380)
+ height = 812.4
+ expect(measureMessageRow(element)).toBe(813)
+ })
+
+ it("uses overflowing content as the row footprint so the following row cannot intersect it", () => {
+ const element = {
+ getBoundingClientRect: () => ({ height: 400 }),
+ scrollHeight: 967,
+ } as unknown as Element
+
+ expect(measureMessageRow(element)).toBe(967)
+ })
+})
+
describe("shouldAdjustMessageScrollPosition", () => {
const item: VirtualItem = {
key: "message:12",
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index f1b8c8d91..699b29a84 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -40,6 +40,25 @@ import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/commu
// `resizeItem` above-viewport compensation (defaults to 1px otherwise).
export const NEAR_BOTTOM_PX = 100
+/**
+ * Measure the row's current visual footprint instead of trusting the initial
+ * text estimate or a previously cached measurement. The virtualizer's default
+ * synchronous path deliberately reuses its cache, which can leave a narrow,
+ * long Markdown row at the 400px estimate when its content finishes laying
+ * out later. WebKit can also expose `borderBoxSize` differently across
+ * versions, so reading the live element here keeps the result independent of
+ * the ResizeObserverEntry shape.
+ *
+ * `scrollHeight` is included because a descendant that temporarily overflows
+ * the auto-sized wrapper still occupies visible space. Rounding up prevents a
+ * fractional CSS-pixel remainder from placing the following absolute row on
+ * top of the final text line.
+ */
+export function measureMessageRow(element: Element): number {
+ const row = element as HTMLElement
+ return Math.ceil(Math.max(element.getBoundingClientRect().height, row.scrollHeight))
+}
+
// Structural fields used by `shouldAdjustMessageScrollPosition`. Do not
// `Pick<>` them from Virtualizer — `scrollAdjustments` / `itemSizeCache` are
// private on current @tanstack/virtual-core and break `tsc`.
@@ -405,6 +424,10 @@ export function useScrollAnchor({
const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
const messages = extractScrollAnchorMessages(items)
const tailId = messages[messages.length - 1]?.id ?? null
+ const wasAtEndRef = useRef(true)
+ const userScrolledAwayRef = useRef(false)
+ const measuredRowHeightsRef = useRef(new WeakMap<Element, number>())
+ const bottomRepinQueuedRef = useRef(false)
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
@@ -412,6 +435,52 @@ export function useScrollAnchor({
count: items.length,
getScrollElement: () => scrollRef.current,
estimateSize: (index) => estimateRowHeight(items[index]),
+ measureElement: (element) => {
+ const size = measureMessageRow(element)
+ const previousSize = measuredRowHeightsRef.current.get(element)
+ measuredRowHeightsRef.current.set(element, size)
+
+ // `resizeItem` grows the direct-DOM sizer only after this callback
+ // returns. Its immediate scroll adjustment can therefore be clamped by
+ // the old scrollHeight. Queue one follow-up after the sizer update so a
+ // viewer who was already pinned remains pinned; never move somebody who
+ // deliberately scrolled away.
+ if (
+ previousSize !== undefined
+ && previousSize !== size
+ // Read the last real scroll sample, not `instance.isAtEnd()` here.
+ // By the time ResizeObserver calls us, an overflowing child can have
+ // already increased the browser scrollHeight without emitting a
+ // scroll event, making a formerly pinned viewport appear far away.
+ && wasAtEndRef.current
+ && !userScrolledAwayRef.current
+ && !bottomRepinQueuedRef.current
+ ) {
+ bottomRepinQueuedRef.current = true
+ queueMicrotask(() => {
+ if (element.isConnected && !userScrolledAwayRef.current) {
+ const scrollElement = scrollRef.current
+ if (scrollElement) scrollElement.scrollTop = scrollElement.scrollHeight
+ }
+ // Markdown/code layout can settle through more than one observer
+ // callback in the same frame. Keep the batch coalesced and land on
+ // the final browser max once all of those sizes are reflected. The
+ // browser's max is authoritative here because it also includes the
+ // non-virtualized hero above the rows; `scrollToEnd()` operates in
+ // the virtualizer's scroll-margin coordinate system and can stop by
+ // exactly that hero height after a row-only resize.
+ element.ownerDocument.defaultView?.requestAnimationFrame(() => {
+ bottomRepinQueuedRef.current = false
+ if (element.isConnected && !userScrolledAwayRef.current) {
+ const scrollElement = scrollRef.current
+ if (scrollElement) scrollElement.scrollTop = scrollElement.scrollHeight
+ }
+ })
+ })
+ }
+
+ return size
+ },
getItemKey: (index) => items[index].key,
anchorTo: "end",
// Deliberately OFF — see this file's module doc comment for the
@@ -446,8 +515,6 @@ export function useScrollAnchor({
// auto-scroll when I'm at the bottom" bug). Appending content below does not
// move `scrollTop`, so it fires no scroll event; this ref therefore still
// holds the pre-append position when the layout effect below reads it.
- const wasAtEndRef = useRef(true)
- const userScrolledAwayRef = useRef(false)
useLayoutEffect(() => {
const el = scrollRef.current
if (!el) return
diff --git a/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts b/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts
new file mode 100644
index 000000000..e737b9dec
--- /dev/null
+++ b/src/web/src/test/e2e-ui/21-mobile-message-layout.spec.ts
@@ -0,0 +1,140 @@
+import type { Page } from "@playwright/test"
+import { test, expect } from "./_fixtures/community-fixture"
+import { seedChannel, seedMessage, seedServer } from "./_fixtures/seed"
+
+type RowRect = { top: number; bottom: number; height: number }
+
+async function messageRowRect(page: Page, messageId: string): Promise<RowRect> {
+ return page.locator(`[data-msg-id="${messageId}"]`).evaluate((message) => {
+ const row = message.parentElement
+ if (!row?.hasAttribute("data-index")) throw new Error("virtual message row not found")
+ const rect = row.getBoundingClientRect()
+ return { top: rect.top, bottom: rect.bottom, height: rect.height }
+ })
+}
+
+async function expectRowsNotToOverlap(page: Page, messageIds: string[]): Promise<void> {
+ await expect.poll(async () => {
+ const rows = await Promise.all(messageIds.map((messageId) => messageRowRect(page, messageId)))
+ return rows.slice(1).every((row, index) => row.top >= rows[index]!.bottom - 0.5)
+ }).toBe(true)
+}
+
+test("long Markdown rows stay measured and separated at iPhone width", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Mobile rows ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "mobile-rows")
+ const otherChannelId = await seedChannel("alice", serverId, "other-mobile-rows")
+
+ const longParagraph = Array.from(
+ { length: 86 },
+ (_, index) => `wrapped phrase ${index} with \`inline-${index}\` content`,
+ ).join(" ")
+ const longId = await seedMessage(
+ "alice",
+ channelId,
+ `A narrow long paragraph with inline code.\n\n${longParagraph}`,
+ )
+ const codeId = await seedMessage(
+ "alice",
+ channelId,
+ `A fenced block follows.\n\n\`\`\`ts\n${Array.from({ length: 28 }, (_, index) => `const row${index} = "${"x".repeat(48)}"`).join("\n")}\n\`\`\``,
+ )
+ const sentinelId = await seedMessage("alice", channelId, "message after the tall Markdown rows")
+ await seedMessage("alice", otherChannelId, "other channel sentinel")
+
+ const { page } = await asUser("alice")
+ await page.setViewportSize({ width: 390, height: 844 })
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })
+ await expect(page.locator(`[data-msg-id="${sentinelId}"]`)).toBeVisible({ timeout: 30_000 })
+
+ const firstMeasurement = await messageRowRect(page, longId)
+ expect(firstMeasurement.height).toBeGreaterThan(400)
+ await expectRowsNotToOverlap(page, [longId, codeId, sentinelId])
+
+ const scroller = page.locator(`[data-msg-id="${sentinelId}"]`).locator("xpath=ancestor::*[contains(@class, 'overflow-y-auto')][1]")
+ await expect(scroller).toHaveCount(1)
+ await scroller.evaluate((element) => { element.scrollTop = element.scrollHeight })
+ await expect.poll(async () => scroller.evaluate((element) => (
+ element.scrollHeight - element.clientHeight - element.scrollTop
+ ))).toBeLessThanOrEqual(2)
+ // Let the virtualizer consume the scroll event and leave its transient
+ // scrolling state before simulating delayed Markdown growth.
+ await page.waitForTimeout(250)
+
+ const beforeGrowth = await messageRowRect(page, codeId)
+ await page.locator(`[data-msg-id="${codeId}"] [data-community-message-body]`).evaluate((messageBody: Element) => {
+ const delayedBlock = document.createElement("div")
+ delayedBlock.dataset.e2eDelayedCodeBlock = "true"
+ delayedBlock.style.height = "360px"
+ delayedBlock.style.margin = "0"
+ delayedBlock.textContent = "delayed fenced-code expansion"
+ messageBody.appendChild(delayedBlock)
+ })
+
+ await expect.poll(async () => (await messageRowRect(page, codeId)).height).toBeGreaterThan(beforeGrowth.height + 300)
+ await expectRowsNotToOverlap(page, [longId, codeId, sentinelId])
+ await expect.poll(async () => scroller.evaluate((element) => (
+ element.scrollHeight - element.clientHeight - element.scrollTop
+ ))).toBeLessThanOrEqual(2)
+
+ // A later resize must not repin somebody who has deliberately moved up to
+ // read. Record every scroll sample as well as a visible row anchor so a
+ // transient down-and-back yank cannot hide behind the settled position.
+ await scroller.evaluate((element) => {
+ element.scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - 320)
+ })
+ await expect.poll(async () => scroller.evaluate((element) => (
+ element.scrollHeight - element.clientHeight - element.scrollTop
+ ))).toBeGreaterThan(100)
+ await page.waitForTimeout(250)
+
+ const readingAnchorBefore = await messageRowRect(page, codeId)
+ const readingScrollBefore = await scroller.evaluate((element) => {
+ element.dataset.e2eMaxScrollTop = String(element.scrollTop)
+ element.addEventListener("scroll", () => {
+ const previousMax = Number(element.dataset.e2eMaxScrollTop)
+ element.dataset.e2eMaxScrollTop = String(Math.max(previousMax, element.scrollTop))
+ }, { passive: true })
+ return {
+ scrollTop: element.scrollTop,
+ bottomDistance: element.scrollHeight - element.clientHeight - element.scrollTop,
+ }
+ })
+ expect(readingScrollBefore.bottomDistance).toBeGreaterThan(100)
+
+ const beforeReadingGrowth = await messageRowRect(page, codeId)
+ await page.locator(`[data-msg-id="${codeId}"] [data-community-message-body]`).evaluate((messageBody: Element) => {
+ const secondDelayedBlock = document.createElement("div")
+ secondDelayedBlock.dataset.e2eReadingGrowth = "true"
+ secondDelayedBlock.style.height = "240px"
+ secondDelayedBlock.style.margin = "0"
+ secondDelayedBlock.textContent = "growth while reading above the bottom"
+ messageBody.appendChild(secondDelayedBlock)
+ })
+
+ await expect.poll(async () => (await messageRowRect(page, codeId)).height)
+ .toBeGreaterThan(beforeReadingGrowth.height + 200)
+ await expectRowsNotToOverlap(page, [longId, codeId, sentinelId])
+ await page.waitForTimeout(500)
+
+ const readingAnchorAfter = await messageRowRect(page, codeId)
+ const readingScrollAfter = await scroller.evaluate((element) => ({
+ scrollTop: element.scrollTop,
+ maxScrollTop: Number(element.dataset.e2eMaxScrollTop),
+ bottomDistance: element.scrollHeight - element.clientHeight - element.scrollTop,
+ }))
+ expect(readingScrollAfter.bottomDistance).toBeGreaterThan(100)
+ expect(readingScrollAfter.scrollTop).toBeLessThanOrEqual(readingScrollBefore.scrollTop + 1)
+ expect(readingScrollAfter.maxScrollTop).toBeLessThanOrEqual(readingScrollBefore.scrollTop + 1)
+ expect(Math.abs(readingAnchorAfter.top - readingAnchorBefore.top)).toBeLessThanOrEqual(1)
+
+ await page.goto(`/c/channels/${serverId}/${otherChannelId}`)
+ await page.waitForURL(new RegExp(otherChannelId), { timeout: 20_000, waitUntil: "commit" })
+ await expect(page.getByText("other channel sentinel", { exact: true })).toBeVisible({ timeout: 30_000 })
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })
+ await expect(page.locator(`[data-msg-id="${sentinelId}"]`)).toBeVisible({ timeout: 30_000 })
+ await expectRowsNotToOverlap(page, [longId, codeId, sentinelId])
+})