Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep message scrolling under user control (#946)

Gener94cb954fd28f
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2b853130e..8c4b82aeb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -365,8 +365,8 @@ importers:
specifier: 0.11.2
'@tanstack/react-virtual':
- specifier: ^3.14.13
+ specifier: ^3.14.17
'@tanstack/store':
specifier: 0.11.2
version: 0.11.2
@@ -3804,8 +3804,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-JbDTAwtzZ99aOeCrAfW5EsE5KSq5RWh6Af2dtFwyLIIk48Ja7vm6n4axu/43T3vfjFnEGJalxJ1wyYjSQD6bSg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-b7b5LwydgQAWcsAWEZyd3iZkN5/QcC6S0K5E1zNheyFoSZl7E78foepGeDHlX2+JuXilA+VIGGFsUYPFddOrig==}
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
@@ -3813,8 +3813,8 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-Ch+e8t097FdTfuihfRwBMqz/OfRZKHOH/C213dbM1lXDZ8bv6r330Bcc9k9XCrP6NkoMYy0/ZCHcddOAPihW4w==}
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==}
@@ -13077,15 +13077,15 @@ snapshots:
react-dom: 19.3.0([email protected])
use-sync-external-store: 1.6.0([email protected])
dependencies:
- '@tanstack/virtual-core': 3.17.11
+ '@tanstack/virtual-core': 3.19.2
react: 19.3.0
react-dom: 19.3.0([email protected])
'@tanstack/[email protected]': {}
- '@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
'@tauri-apps/[email protected]': {}
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 7883b002b..b2645541e 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -30,7 +30,7 @@ export const SPEC_SECONDS = {
"15-mention-scope.spec.ts": 10.94,
"16-jump-to-present.spec.ts": 5.997,
"17-forum-sidebar-stage-b.spec.ts": 43.842,
- "18-new-divider-scroll.spec.ts": 10.956,
+ "18-new-divider-scroll.spec.ts": DEFAULT_SPEC_SECONDS,
"19-marketing-seo.spec.ts": 1.713,
"20-community-attachment-thumbnails.spec.ts": 11.117,
"21-mobile-message-layout.spec.ts": 5.12,
@@ -75,7 +75,7 @@ export const SPEC_SECONDS = {
"53-mobile-inbox-surface.spec.ts": 8.362,
"54-authenticated-context-menu-policy.spec.ts": 13.721,
"54-blog-multizone.spec.ts": 5.485,
- "55-message-scroll-characterization.spec.ts": 109.548,
+ "55-message-scroll-characterization.spec.ts": DEFAULT_SPEC_SECONDS,
"56-inbox-friend-requests.spec.ts": 60,
"56-retired-workspace-links.spec.ts": DEFAULT_SPEC_SECONDS,
"57-server-delete-navigation-races.spec.ts": 55,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 14042f9f1..e7c5ea497 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -75,17 +75,18 @@ describe("planE2eShards", () => {
expect(first).toEqual(second)
expect(Object.keys(SPEC_SECONDS).sort()).toEqual(specs)
- expect(first).toHaveLength(14)
+ expect(first).toHaveLength(15)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(109.548)
+ expect(SPEC_SECONDS["18-new-divider-scroll.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)
+ expect(SPEC_SECONDS["55-message-scroll-characterization.spec.ts"]).toBe(DEFAULT_SPEC_SECONDS)
expect(specSeconds).toEqual([
- 165, 165, 165, 151.379, 152.389, 150.76, 151.219, 151.183,
- 153.805, 154.219, 151.127, 150.794, 154.182, 153.225,
+ 165, 165, 165, 165, 165, 155.638, 154.234, 155.283,
+ 156.095, 155.905, 156.323, 155.711, 153.963, 154.488, 156.138,
])
expect(predictedSeconds).toEqual([
- 240, 240, 240, 226.379, 227.389, 225.76, 226.219, 226.183,
- 228.805, 229.219, 226.127, 225.794, 229.182, 228.225,
+ 240, 240, 240, 240, 240, 230.638, 229.234, 230.283,
+ 231.095, 230.905, 231.323, 230.711, 228.963, 229.488, 231.138,
])
expect(first.every((shard) => (
shard.fixed_setup_seconds === E2E_FIXED_SETUP_SECONDS
diff --git a/src/web/package.json b/src/web/package.json
index 520db0b38..8a60a8403 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -75,7 +75,7 @@
"@tanstack/react-query": "5.104.0",
"@tanstack/react-query-persist-client": "5.104.0",
"@tanstack/react-store": "0.11.2",
- "@tanstack/react-virtual": "^3.14.13",
+ "@tanstack/react-virtual": "^3.14.17",
"@tanstack/store": "0.11.2",
"@tauri-apps/plugin-clipboard-manager": "^2.4.1",
"@tiptap/extension-list": "^3.31.4",
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index d919894cd..91b2ccaf9 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -308,6 +308,7 @@ export function DmView({ dmId }: { dmId: string }) {
}, [communityRuntime, dmId])
const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))
useEffect(() => {
setReplyTo(null)
@@ -406,6 +407,8 @@ export function DmView({ dmId }: { dmId: string }) {
},
})
if (!receipt.accepted) return false
+ setLocalSubmitVersion((version) => version + 1)
+ if (hasMoreNewerMessages) jumpToPresent()
void receipt.committed.then((result) => {
try { assertActive() } catch { return }
if (result.ok) advanceOnboardingAfterSend()
@@ -505,6 +508,7 @@ export function DmView({ dmId }: { dmId: string }) {
onLoadNewer={fetchNewerMessages}
onJumpToPresent={jumpToPresent}
presentVersion={presentVersion}
+ localSubmitVersion={localSubmitVersion}
unreadCount={unreadCount}
typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}
hero={
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 8be5ed416..7a8998f6f 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -166,6 +166,7 @@ export function TextChannelSurface({
onLoadNewer={feed.fetchNewer}
onJumpToPresent={feed.jumpToPresent}
presentVersion={feed.presentVersion}
+ localSubmitVersion={controller.localSubmitVersion}
unreadCount={feed.unreadCount}
typingUsers={controller.typingUsers}
/>
diff --git a/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts
index ba62d92fb..f90a3e65d 100644
--- a/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts
@@ -78,6 +78,7 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
jumpToSeq: vi.fn(),
messageActions: {} as MessageChannelControllerValue["messageActions"],
threadActions: {} as MessageChannelControllerValue["threadActions"],
+ localSubmitVersion: 0,
acceptMessage: vi.fn(() => true),
handleTyping: vi.fn(),
typingUsers: [],
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index d4086ef5c..03f98f8ea 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -130,6 +130,7 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onPreviewImage: vi.fn(),
},
acceptMessage: mocks.acceptMessage,
+ localSubmitVersion: 0,
handleTyping: mocks.handleTyping,
typingUsers: ["Alice"],
}),
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 c37c83355..a1f350486 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -275,6 +275,7 @@ export function ThreadChannelSurface({
onLoadNewer={controller.feed.fetchNewer}
onJumpToPresent={controller.feed.jumpToPresent}
presentVersion={controller.feed.presentVersion}
+ localSubmitVersion={controller.localSubmitVersion}
unreadCount={controller.feed.unreadCount}
typingUsers={controller.typingUsers}
/>
diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
index 2e60bc7e4..71e7d4b9e 100644
--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
@@ -55,6 +55,7 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
onSheetReply: vi.fn(), jumpToSeq: vi.fn(),
messageActions: {} as MessageChannelControllerValue["messageActions"],
threadActions: {} as MessageChannelControllerValue["threadActions"],
+ localSubmitVersion: 0,
acceptMessage: vi.fn(() => true), handleTyping: vi.fn(), typingUsers: [],
}),
}))
diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
index ec804e7a6..dad0ac0cc 100644
--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
@@ -58,6 +58,7 @@ type ExpectedControllerValue = {
attachments?: SendAttachment[],
mentionType?: MentionType,
) => boolean
+ localSubmitVersion: number
handleTyping: () => void
typingUsers: string[]
}
@@ -145,7 +146,7 @@ describe("MessageChannelController facade contract", () => {
expect(position, token).toBeGreaterThan(cursor)
cursor = position
}
- expect(body.match(/\buseCreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(4)
+ expect(body.match(/\buseCreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(5)
expect(body).toContain('queryKey: ["community", "message-search", channelId, term]')
expect(body).toContain("const searchMessages = useCanonicalMessagesById(searchIds)")
expect(body).not.toMatch(/\buseState(?:<[^>]+>)?\(/)
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index da421f142..1b4183c1c 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -166,6 +166,7 @@ describe("useMessageChannelController", () => {
mocks.seq = null
mocks.storeState.pendingReply = null
mocks.apiFetch.mockResolvedValue({ results: [] })
+ mocks.accept.mockReturnValue(true)
mocks.createActions.mockImplementation(() => mocks.messageActions)
mocks.typingScopes.users.length = 0
mocks.typingScopes.names.length = 0
@@ -318,6 +319,32 @@ describe("useMessageChannelController", () => {
expect(latest.replyTo).toBeNull()
})
+ it("publishes one local intent per accepted submission and requests the newest history window", () => {
+ const jumpToPresent = vi.fn()
+ const view = rtlRender(React.createElement(Probe, {
+ value: props({ feed: { ...feed, hasMoreNewer: true, jumpToPresent } }),
+ }))
+ expect(latest.localSubmitVersion).toBe(0)
+ mocks.accept.mockReturnValueOnce(false)
+ act(() => { expect(latest.acceptMessage("")).toBe(false) })
+ expect(latest.localSubmitVersion).toBe(0)
+ expect(jumpToPresent).not.toHaveBeenCalled()
+ act(() => { expect(latest.acceptMessage("new text")).toBe(true) })
+ expect(latest.localSubmitVersion).toBe(1)
+ expect(jumpToPresent).toHaveBeenCalledOnce()
+ act(() => { expect(latest.acceptMessage("", [{ file: {} as File }])).toBe(true) })
+ expect(latest.localSubmitVersion).toBe(2)
+ expect(jumpToPresent).toHaveBeenCalledTimes(2)
+ act(() => latest.messageActions.onRetry("failed-nonce"))
+ expect(latest.localSubmitVersion).toBe(2)
+ view.rerender(React.createElement(Probe, {
+ value: props({ feed: { ...feed, hasMoreNewer: false, jumpToPresent } }),
+ }))
+ act(() => { expect(latest.acceptMessage("at present")).toBe(true) })
+ expect(latest.localSubmitVersion).toBe(3)
+ expect(jumpToPresent).toHaveBeenCalledTimes(2)
+ })
+
it("preserves pending/context/seq navigation without claiming global pane handlers", () => {
mocks.seq = "7"
const navigate = vi.fn()
@@ -601,7 +628,7 @@ describe("useMessageChannelController", () => {
"feed", "pinnedIds", "replyTo", "setReplyTo", "searchQuery", "searchResults", "searchError", "searchLoading",
"search", "scrollTargetId", "setScrollTargetId", "consumeScrollTarget",
"contextTarget", "setContextTarget", "openContextSeq", "onSheetReply", "jumpToSeq",
- "messageActions", "threadActions", "acceptMessage", "handleTyping", "typingUsers",
+ "messageActions", "threadActions", "acceptMessage", "localSubmitVersion", "handleTyping", "typingUsers",
])
const actionKeys = [
"onToggleReaction", "onReact", "onReply", "onPin", "onMark", "onCreateThread",
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index bdfd95be4..4c696967a 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -75,6 +75,7 @@ export function useMessageChannelController({
const pathname = usePathname()
const searchParams = useSearchParams()
const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))
+ const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))
const [searchQuery, setSearchQuery] = useAtom(useCreateAtom(""))
const [scrollTargetId, setScrollTargetId] = useAtom(useCreateAtom<string | null>(anchorMessageId))
const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))
@@ -293,19 +294,24 @@ export function useMessageChannelController({
mentionType?: MentionType,
): boolean => {
const command = captureSendCommand()
- return acceptChannelMessage({
- runtime: communityRuntime,
- markdown,
- attachments,
- mentionType,
- messageScope,
- viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },
- replyTo,
- runAcceptedIntent: (nonce) => runAcceptedIntent(nonce, command),
- channelId,
- clearReply: () => setReplyTo(null),
+ const accepted = acceptChannelMessage({
+ runtime: communityRuntime,
+ markdown,
+ attachments,
+ mentionType,
+ messageScope,
+ viewer: { id: viewer.id, name: viewer.name, avatar: viewer.avatar },
+ replyTo,
+ runAcceptedIntent: (nonce) => runAcceptedIntent(nonce, command),
+ channelId,
+ clearReply: () => setReplyTo(null),
})
- }, [captureSendCommand, channelId, communityRuntime, messageScope, replyTo, runAcceptedIntent, setReplyTo, viewer.avatar, viewer.id, viewer.name])
+ if (accepted) {
+ setLocalSubmitVersion((version) => version + 1)
+ if (feed.hasMoreNewer) feed.jumpToPresent()
+ }
+ return accepted
+ }, [captureSendCommand, channelId, communityRuntime, feed.hasMoreNewer, feed.jumpToPresent, messageScope, replyTo, runAcceptedIntent, setLocalSubmitVersion, setReplyTo, viewer.avatar, viewer.id, viewer.name])
return useMemo<MessageChannelControllerValue>(() => ({
feed,
@@ -328,7 +334,8 @@ export function useMessageChannelController({
messageActions,
threadActions: { ...messageActions, onCreateThread: undefined },
acceptMessage,
+ localSubmitVersion,
handleTyping: () => communityWsSendTyping(communityRuntime, { channelId }),
typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),
- }), [feed, pinnedIds, replyTo, setReplyTo, searchQuery, searchResults, searchResource.isError, searchResource.isFetching, search, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])
+ }), [feed, pinnedIds, replyTo, setReplyTo, searchQuery, searchResults, searchResource.isError, searchResource.isFetching, search, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])
}
diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.ts
index 1e6092aef..08c5f20c5 100644
--- a/src/web/src/components/community/messages/message-channel-controller-types.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts
@@ -64,6 +64,7 @@ export type MessageChannelControllerValue = {
attachments?: SendAttachment[],
mentionType?: MentionType,
) => boolean
+ localSubmitVersion: number
handleTyping: () => void
typingUsers: string[]
}
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 b6f4e8da9..a37821adb 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
@@ -182,6 +182,16 @@ describe("useMessageListController", () => {
return entry[0]
}
+ it("passes only the current composer acceptance version through loading and loaded commits", () => {
+ const value = props({ messages: [], loading: true, localSubmitVersion: 7, presentVersion: 3 })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ expect(mocks.scrollInputs.at(-1)).toMatchObject({ localSubmitVersion: 7, presentVersion: 3 })
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [baseMessage], loading: false } }))
+ expect(mocks.scrollInputs.at(-1)).toMatchObject({ localSubmitVersion: 7, presentVersion: 3 })
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [baseMessage], loading: false, localSubmitVersion: 8 } }))
+ expect(mocks.scrollInputs.at(-1)).toMatchObject({ localSubmitVersion: 8, presentVersion: 3 })
+ })
+
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 }) }))
@@ -208,7 +218,7 @@ describe("useMessageListController", () => {
isFetchingOlder: undefined,
isFetchingNewer: undefined,
presentVersion: undefined,
- viewerUserId: undefined,
+ localSubmitVersion: undefined,
hasMoreOlder: undefined,
tailPaddingEnd: 48,
onInitialPositionSettled: expect.any(Function),
@@ -355,7 +365,7 @@ describe("useMessageListController", () => {
isFetchingOlder: true,
isFetchingNewer: true,
presentVersion: 7,
- viewerUserId: "viewer_1",
+ localSubmitVersion: undefined,
hasMoreOlder: true,
tailPaddingEnd: 48,
onInitialPositionSettled: expect.any(Function),
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 b4a2dcb0c..5d00e554f 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -29,8 +29,8 @@ export function useMessageListController({
onLoadNewer,
onJumpToPresent,
presentVersion,
+ localSubmitVersion,
unreadCount,
- viewerUserId,
onScrollRoot,
onScrollTargetConsumed,
}: ResolvedMessageListProps) {
@@ -113,7 +113,7 @@ export function useMessageListController({
isFetchingOlder,
isFetchingNewer,
presentVersion,
- viewerUserId,
+ localSubmitVersion,
hasMoreOlder: hasMore,
tailPaddingEnd,
onInitialPositionSettled: settleAnchorPosition,
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 3bc36e383..5fec6f56b 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
@@ -46,6 +46,7 @@ type ExpectedMessageListProps = {
onLoadNewer?: () => void
onJumpToPresent?: () => void
presentVersion?: number
+ localSubmitVersion?: number
unreadCount?: number
}
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 1fc061a37..3c106047b 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -45,6 +45,7 @@ export type MessageListProps = {
onLoadNewer?: () => void
onJumpToPresent?: () => void
presentVersion?: number
+ localSubmitVersion?: number
unreadCount?: number
}
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 e9df6b695..0e6001c0f 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
@@ -13,7 +13,9 @@ describe("locked native iOS deferred adjustment controls, with simulated DOM geo
const h = mount()
h.move(500)
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
fireEvent.touchStart(h.root, { touches: [{ clientY: 300 }] })
+ expect(cancel).toHaveBeenCalledOnce()
const before = h.root.scrollTop
h.update({ items: [message("older"), ...h.input.items] })
expect(offset).not.toHaveBeenCalled()
diff --git a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
index 46e99ad5b..956750029 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
@@ -61,7 +61,7 @@ describe("native pagination and original semantic epoch", () => {
expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
})
it("finishes a replacement window without inventing preservation of a removed key or following its historical tail", () => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
h.move(500)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
act(() => scrollFixture.latest.captureNewerPageAnchor())
@@ -87,8 +87,10 @@ describe("native pagination and original semantic epoch", () => {
h.stage({ scrollToMessageId: "m12" })
const stale = [...scrollFixture.frames.values()]
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
h.stage({ scrollToMessageId: "unloaded" })
- expect(offset).toHaveBeenCalledTimes(1)
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(offset).not.toHaveBeenCalled()
act(() => stale.forEach(callback => callback(performance.now())))
expect(consumed).not.toHaveBeenCalled()
h.update({ items: [...h.input.items, message("unloaded")] })
@@ -98,8 +100,10 @@ describe("native pagination and original semantic epoch", () => {
const h = mount()
h.stage({ scrollToMessageId: "m12" })
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
fireEvent.wheel(h.root, { deltaY: -20 })
- expect(offset).toHaveBeenCalledTimes(1)
+ expect(cancel).toHaveBeenCalledTimes(1)
+ expect(offset).not.toHaveBeenCalled()
runFrames()
offset.mockClear()
fireEvent.wheel(h.root, { deltaY: -20 })
@@ -135,15 +139,19 @@ describe("native pagination and original semantic epoch", () => {
it("retires an unsettled native end request on user takeover before late tail measurements", () => {
const h = mount()
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
act(() => scrollFixture.latest.scrollToBottom())
+ cancel.mockClear()
fireEvent.wheel(h.root, { deltaY: -20 })
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
act(() => h.root.scrollTo({ top: 300 }))
runFrames()
scrollFixture.bodyHeights.set("m13", 240)
h.update({ items: [...h.input.items] })
expect(h.root.scrollTop).toBe(300)
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
})
it.each(["target", "end"] as const)("retires an unsettled native %s request on keyboard takeover before late geometry", kind => {
const consumed = vi.fn()
@@ -153,10 +161,12 @@ describe("native pagination and original semantic epoch", () => {
else act(() => scrollFixture.latest.scrollToBottom())
const stale = [...scrollFixture.frames.values()]
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
fireEvent.keyDown(h.root, { key: "Enter" })
expect(offset).not.toHaveBeenCalled()
fireEvent.keyDown(h.root, { key: "PageUp" })
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
act(() => h.root.scrollTo({ top: 300 }))
act(() => stale.forEach(callback => callback(performance.now())))
runFrames()
@@ -165,7 +175,8 @@ describe("native pagination and original semantic epoch", () => {
act(() => vi.advanceTimersByTime(2500))
runFrames()
expect(h.root.scrollTop).toBe(300)
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
expect(consumed).not.toHaveBeenCalled()
if (kind === "target") expect(cancelled).toHaveBeenCalledExactlyOnceWith("m12")
else expect(cancelled).not.toHaveBeenCalled()
@@ -175,13 +186,16 @@ describe("native pagination and original semantic epoch", () => {
const h = mount()
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
act(() => scrollFixture.latest.scrollToBottom())
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
h.stage({ scrollToMessageId: "unloaded" })
const before = h.root.scrollTop
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
scrollFixture.bodyHeights.set("m13", 240)
h.update({ items: [...h.input.items] })
expect(h.root.scrollTop).toBe(before)
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
})
it("waits for an absent explicit target, closes read, and finishes through its finite deadline", () => {
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 be831bc92..bb970b660 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
@@ -7,6 +7,33 @@ beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
describe("locked native adapter and existing message scroll owner", () => {
+ it("writes and clamps immediately, then coalesces native scroll delivery before frame callbacks", () => {
+ const h = mount()
+ const delivered = vi.fn(() => h.root.scrollTop)
+ h.root.addEventListener("scroll", delivered)
+ const frame = vi.fn(() => {
+ expect(delivered).toHaveBeenCalledOnce()
+ expect(delivered.mock.results[0].value).toBe(120)
+ expect(scrollFixture.latest.virtualizer.scrollOffset).toBe(120)
+ })
+ act(() => {
+ h.root.scrollTo({ top: -20 })
+ expect(h.root.scrollTop).toBe(0)
+ h.root.scrollTo({ top: 100 })
+ h.root.scrollTo({ top: 120 })
+ expect(h.root.scrollTop).toBe(120)
+ window.requestAnimationFrame(frame)
+ })
+ expect(delivered).not.toHaveBeenCalled()
+ runFrames(1)
+ expect(frame).toHaveBeenCalledOnce()
+ runFrames(1)
+ expect(delivered).toHaveBeenCalledOnce()
+ act(() => h.root.scrollTo({ top: 130 }))
+ h.view.unmount()
+ runFrames(1)
+ expect(delivered).toHaveBeenCalledOnce()
+ })
it("delivers only the changed observed box and keeps content, client and border sizes separate", () => {
scrollFixture.scrollbarWidth = 11
const h = mount()
@@ -200,20 +227,21 @@ describe("locked native adapter and existing message scroll owner", () => {
const h = mount()
h.move(0)
act(() => scrollFixture.latest.scrollToBottom())
- const pending = Array.from(h.root.querySelectorAll<HTMLElement>("[data-index]"))
- for (const row of pending) Object.defineProperty(row, "getBoundingClientRect", {
- configurable: true, value: () => DOMRect.fromRect(),
+ const bounds = vi.mocked(HTMLElement.prototype.getBoundingClientRect)
+ const originalBounds = bounds.getMockImplementation()!
+ bounds.mockImplementation(function (this: HTMLElement) {
+ return this.matches("[data-index]") ? DOMRect.fromRect() : originalBounds.call(this)
})
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")
+ bounds.mockImplementation(originalBounds)
act(() => {
if (event === "scroll") fireEvent.scroll(h.root)
else {
- const row = pending.find(row => row.querySelector('[data-msg-id="m13"]'))!
+ const row = h.root.querySelector<HTMLElement>('[data-msg-id="m13"]')!.closest<HTMLElement>("[data-index]")!
scrollFixture.bodyHeights.set("m13", 101)
scrollFixture.latest.virtualizer.measureElement(row)
}
@@ -228,8 +256,10 @@ describe("locked native adapter and existing message scroll owner", () => {
const native = scrollFixture.latest.virtualizer
const end = vi.spyOn(native, "scrollToEnd")
const offset = vi.spyOn(native, "scrollToOffset")
+ const cancel = vi.spyOn(native, "cancelScroll")
vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
act(() => scrollFixture.latest.scrollToBottom())
+ cancel.mockClear()
runFrames(3)
expect(end).toHaveBeenCalledExactlyOnceWith({ behavior: "auto" })
runFrames(400)
@@ -241,7 +271,8 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(offset).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
fireEvent.wheel(h.root, { deltaY: -20 })
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
})
it("keeps an explicit tail scroll when wrapped offscreen rows receive their later native measurements", () => {
scrollFixture.width = 639
@@ -389,7 +420,7 @@ 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: 40 })
+ expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "end", followOnAppend: "auto", 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 })
@@ -658,10 +689,10 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(offset).not.toHaveBeenCalled()
})
it.each(["peer", "me"])("follows a genuine %s append through later native tail measurement", author => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
const top = author === "peer" ? h.root.scrollHeight - scrollFixture.height : 400
h.move(top)
- h.stage({ items: [...h.input.items, message("new-tail", author)] })
+ h.stage({ items: [...h.input.items, message("new-tail", author)], localSubmitVersion: author === "me" ? 1 : 0 })
runFrames(2)
scrollFixture.bodyHeights.set("new-tail", 456)
resize()
@@ -669,18 +700,18 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it.each(["peer", "me"])("keeps a pending %s end intent on the current tail when another row arrives", author => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
h.move(author === "peer" ? h.root.scrollHeight - scrollFixture.height : 400)
- h.stage({ items: [...h.input.items, message("first-tail", author)] })
+ h.stage({ items: [...h.input.items, message("first-tail", author)], localSubmitVersion: author === "me" ? 1 : 0 })
h.stage({ items: [...h.input.items, message("second-tail", author)] })
resize()
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it("keeps a pending end intent on the current tail after history is prepended", () => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
h.move(400)
- h.stage({ items: [...h.input.items, message("self-tail", "me")] })
+ h.stage({ items: [...h.input.items, message("self-tail", "me")], localSubmitVersion: 1 })
h.stage({ items: [message("older-one"), message("older-two"), ...h.input.items] })
resize()
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
@@ -730,15 +761,15 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.scrollTop - before).toBe(60)
expect(offset).not.toHaveBeenCalled()
})
- it.each([0, 99, 100, 101])("qualifies peer append from the actual prior %ipx tail distance", distance => {
+ it.each([0, 1, 2, 20, 100, 101])("qualifies peer append from the actual prior %ipx tail distance", distance => {
const h = mount()
h.move(h.root.scrollHeight - scrollFixture.height - distance)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
h.update({ items: [...h.input.items, message("peer-new")] })
- expect(end).toHaveBeenCalledTimes(distance <= 100 ? 1 : 0)
+ expect(end).toHaveBeenCalledTimes(distance <= 1 ? 1 : 0)
})
it("does not follow a historical self-authored tail from newer pagination", () => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
h.move(300)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
act(() => scrollFixture.latest.captureNewerPageAnchor())
@@ -752,7 +783,7 @@ describe("locked native adapter and existing message scroll owner", () => {
act(() => scrollFixture.latest.requestPresentPosition())
h.move(300)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
- h.update({ items: [...h.input.items, message("historical-me", "me")], hasMoreNewer: false, presentVersion: 1, viewerUserId: "me" })
+ h.update({ items: [...h.input.items, message("historical-me", "me")], hasMoreNewer: false, presentVersion: 1 })
h.update({ items: [...h.input.items] })
expect(end).not.toHaveBeenCalled()
})
@@ -947,23 +978,76 @@ describe("locked native adapter and existing message scroll owner", () => {
const native = scrollFixture.latest.virtualizer
const end = vi.spyOn(native, "scrollToEnd")
const offset = vi.spyOn(native, "scrollToOffset")
+ const cancel = vi.spyOn(native, "cancelScroll")
scrollFixture.width = 266
resize(2)
expect(end).toHaveBeenCalledOnce()
+ cancel.mockClear()
const pending = [...scrollFixture.frames.values()]
expect(pending.length).toBeGreaterThan(0)
h.stage({ items: [...h.input.items.slice(0, -1), message("replacement")] })
- expect(offset).toHaveBeenCalledOnce()
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(offset).not.toHaveBeenCalled()
expect(h.root.querySelector('[data-msg-id="replacement"]')).not.toBeNull()
resize()
- const calls = [end.mock.calls.length, offset.mock.calls.length, scrollFixture.scrollCalls.length]
+ const calls = [end.mock.calls.length, offset.mock.calls.length, cancel.mock.calls.length, scrollFixture.scrollCalls.length]
const top = h.root.scrollTop
act(() => { for (const callback of pending) callback(performance.now()) })
- expect([end.mock.calls.length, offset.mock.calls.length, scrollFixture.scrollCalls.length]).toEqual(calls)
+ expect([end.mock.calls.length, offset.mock.calls.length, cancel.mock.calls.length, scrollFixture.scrollCalls.length]).toEqual(calls)
expect(h.root.scrollTop).toBe(top)
expect(h.root.querySelector('[data-msg-id="replacement"]')).not.toBeNull()
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
+ it.each(["timer", "frame"])("ends a width request at its original deadline through repeated appends and %s delivery", async delivery => {
+ let pending: Promise<void> | null = null
+ function Gate() {
+ if (pending) use(pending)
+ return null
+ }
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(Suspense, { fallback: createElement("div", { "data-testid": "pending-width" }) },
+ children, createElement(Gate))
+ }
+ scrollFixture.width = 639
+ const h = mount({ tailPaddingEnd: 40 }, false, undefined, Wrapper)
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ scrollFixture.width = 266
+ resize(0)
+ const startedAt = Date.now()
+ for (let i = 0; i < 5; i++) {
+ let resume!: () => void
+ pending = new Promise<void>(resolve => { resume = resolve })
+ await act(async () => {
+ startTransition(() => h.stage({ items: [...h.input.items, message(`deadline-tail-${i}`)] }))
+ })
+ runFrames(1)
+ expect(end).not.toHaveBeenCalled()
+ await act(async () => {
+ pending = null
+ resume()
+ })
+ expect(h.root.querySelector(`[data-msg-id="deadline-tail-${i}"]`)).not.toBeNull()
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ act(() => vi.advanceTimersByTime(350))
+ }
+ act(() => vi.advanceTimersByTime(1_999 - (Date.now() - startedAt)))
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ act(() => {
+ if (delivery === "timer") vi.advanceTimersByTime(1)
+ else {
+ const callbacks = [...scrollFixture.frames.values()]
+ expect(callbacks.length).toBeGreaterThan(0)
+ vi.setSystemTime(startedAt + 2_000)
+ for (const callback of callbacks) callback(performance.now())
+ }
+ })
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ h.update({ items: [...h.input.items, message("after-width-deadline")] })
+ expect(end).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ })
it("preserves a two-pixel DM tail distance through consecutive composer resizes", () => {
const h = mount()
scrollFixture.height -= 100
@@ -1235,11 +1319,11 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeGreaterThan(1)
})
it("follows a new self-send once and retains its stable display key on canonical acknowledgement", () => {
- const h = mount({ viewerUserId: "me" })
+ const h = mount()
h.move(300)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
const optimistic = { ...message("optimistic", "me"), key: "client:send-1" }
- h.update({ items: [...h.input.items, optimistic] })
+ h.update({ items: [...h.input.items, optimistic], localSubmitVersion: 1 })
expect(end).toHaveBeenCalledOnce()
const canonical = { ...optimistic, m: { ...optimistic.m, id: "canonical" } }
h.update({ items: [...h.input.items.slice(0, -1), canonical] })
@@ -1270,3 +1354,120 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(offset).not.toHaveBeenCalled()
})
})
+
+describe("current composer intent and native passive ownership", () => {
+ it.each([0, 1, 2, 20, 100, 101])("applies the same passive rule to another device at %ipx", distance => {
+ const h = mount()
+ h.move(h.root.scrollHeight - scrollFixture.height - distance)
+ const before = bodyTop(h.root, "m13")
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ h.update({ items: [...h.input.items, message("remote-self", "me")] })
+ expect(end).toHaveBeenCalledTimes(distance <= 1 ? 1 : 0)
+ if (distance <= 1) expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ else expect(bodyTop(h.root, "m13")).toBeCloseTo(before, 0)
+ })
+ it("does not reinterpret an old composer version on a new list mount", () => {
+ const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
+ const h = mount({ items, newDividerBefore: "m4", localSubmitVersion: 8 })
+ const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
+ expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ h.move(300)
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ h.update({ items: [...h.input.items, message("remote-self", "me")] })
+ expect(end).not.toHaveBeenCalled()
+ })
+ it("does not replay retired New entry after a transient empty projection", () => {
+ const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
+ const h = mount({ items, newDividerBefore: "m4" })
+ h.move(300)
+ h.update({ items: [] })
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ items })
+ expect(index).not.toHaveBeenCalled()
+ })
+ it("waits for a local history submission's newest window and lets input retire its completion", () => {
+ const h = mount({ hasMoreNewer: true })
+ h.move(300)
+ h.update({ localSubmitVersion: 1, isFetchingNewer: true })
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ expect(end).not.toHaveBeenCalled()
+ fireEvent.wheel(h.root, { deltaY: -24 })
+ h.update({ hasMoreNewer: false, isFetchingNewer: false, presentVersion: 1, items: [...h.input.items, message("local-tail", "me")] })
+ expect(end).not.toHaveBeenCalled()
+ })
+ it.each(["loaded", "unloaded", "history"])("consumes a pending %s reference superseded by local submission and restores native follow and pagination", reference => {
+ const cancelled = vi.fn()
+ const positioned = vi.fn()
+ const historical = reference === "history"
+ const h = mount({ hasMoreNewer: historical, onScrollTargetCancelled: cancelled, onScrollTargetPositioned: positioned })
+ const target = reference === "unloaded" ? "unloaded-reference" : "m4"
+ h.stage({ scrollToMessageId: target })
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const stale = [...scrollFixture.frames.values()]
+ h.update({ localSubmitVersion: 1, isFetchingNewer: historical, items: [...h.input.items, message("accepted-local", "me")] })
+ if (historical) {
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ hasMoreNewer: false, isFetchingNewer: false, presentVersion: 1 })
+ }
+ expect(cancelled).toHaveBeenCalledExactlyOnceWith(target)
+ expect(positioned).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ act(() => { for (const callback of stale) callback(performance.now()) })
+ expect(positioned).not.toHaveBeenCalled()
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ h.update({ items: [...h.input.items, message("received-after-supersession")] })
+ expect(end).toHaveBeenCalledOnce()
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ const top = bodyTop(h.root, "received-after-supersession")
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.stage({ isFetchingOlder: true })
+ h.update({ isFetchingOlder: false, items: [message("older-after-supersession"), ...h.input.items] })
+ expect(bodyTop(h.root, "received-after-supersession")).toBeCloseTo(top, 0)
+ expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ })
+ it("does not complete a local history submission from tail attachment without its newest-window receipt", () => {
+ const h = mount({ hasMoreNewer: true })
+ h.move(300)
+ h.update({ localSubmitVersion: 1, isFetchingNewer: true })
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ h.update({ hasMoreNewer: false, isFetchingNewer: false, items: [...h.input.items, message("unqualified-tail", "me")] })
+ expect(end).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ presentVersion: 1 })
+ expect(end).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+ it("finishes a current local history submission once and ignores its later ACK", () => {
+ const h = mount({ hasMoreNewer: true })
+ h.move(300)
+ h.update({ localSubmitVersion: 1, isFetchingNewer: true })
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ const optimistic = { ...message("optimistic", "me"), key: "client:history-send" }
+ h.update({ hasMoreNewer: false, isFetchingNewer: false, presentVersion: 1, items: [...h.input.items, optimistic] })
+ expect(end).toHaveBeenCalledOnce()
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ h.update({ items: [...h.input.items.slice(0, -1), { ...optimistic, m: { ...optimistic.m, id: "canonical" } }] })
+ expect(end).toHaveBeenCalledOnce()
+ })
+})
+
+describe("public native cancellation", () => {
+ it("retires an automatic follow target before later row measurement and sustained upward input", () => {
+ const h = mount()
+ h.stage({ items: [...h.input.items, message("late-measured-peer")] })
+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
+ const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
+ for (let step = 0; step < 20; step++) {
+ fireEvent.wheel(h.root, { deltaY: -24 })
+ act(() => h.root.scrollTo({ top: Math.max(0, h.root.scrollTop - 24) }))
+ const before = h.root.scrollTop
+ if (step === 4) scrollFixture.bodyHeights.set("late-measured-peer", 420)
+ resize(2)
+ expect(h.root.scrollTop).toBe(before)
+ }
+ expect(cancel).toHaveBeenCalledTimes(20)
+ 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 db4ce1ab3..a851a614f 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -1,22 +1,15 @@
import { describe, it, expect } from "vitest"
import {
- decideScrollAction,
- createScrollAnchorState,
findMessageIndex,
findMountScrollTargetIndex,
- extractScrollAnchorMessages,
measureMessageRow,
MESSAGE_RAIL_TAIL_PADDING_END_PX,
- NEAR_BOTTOM_PX,
+ MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX,
resolveMessageRailTailPaddingEnd,
resolveViewportResizeAnchor,
- type ScrollAnchorState,
- type ScrollAnchorMessage,
} from "./use-scroll-anchor"
import type { FlatItem } from "@/lib/community/message-list-items"
-const msgs = (...ids: string[]): ScrollAnchorMessage[] => ids.map((id) => ({ id }))
-
describe("message rail tail geometry", () => {
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 })
@@ -70,258 +63,9 @@ describe("resolveViewportResizeAnchor", () => {
})
})
-function baseInput(overrides: Partial<Parameters<typeof decideScrollAction>[0]> = {}) {
- return {
- state: createScrollAnchorState(),
- messages: msgs("m1", "m2", "m3"),
- initialScrollReady: true,
- viewportReady: true,
- isAtEnd: true,
- ...overrides,
- }
-}
-
-describe("decideScrollAction — mount (rewritten — neither case is free with the virtualizer, both must be explicit)", () => {
- it("centers on the NEW divider when present", () => {
- const { action, nextState } = decideScrollAction(baseInput({ newDividerBefore: "m2" }))
- expect(action).toEqual({ type: "mount", newDividerBefore: "m2" })
- expect(nextState.didInitialScroll).toBe(true)
- })
-
- it("scrolls to end when no NEW divider is present — NOT free, must be an explicit action", () => {
- const { action } = decideScrollAction(baseInput())
- expect(action).toEqual({ type: "mount", newDividerBefore: undefined })
- })
-
- it("scrolls a warm tail-attached cache to the bottom early — before initialScrollReady (instant switch phase 1)", () => {
- // A revisit has its newest tail already hydrated; don't wait on the read
- // snapshot to paint-and-scroll to the bottom. Consumes the phase-1 one-shot
- // but leaves phase-2 (divider convergence) pending.
- const { action, nextState } = decideScrollAction(baseInput({ initialScrollReady: false }))
- expect(action).toEqual({ type: "scrollToEnd" })
- expect(nextState.didInitialScroll).toBe(true)
- expect(nextState.didDividerConverge).toBe(false)
- })
-
- it("does NOT take the early-bottom path for an older-only / mid-history window (hasMoreNewer) — waits on initialScrollReady", () => {
- // A jump target or cold anchor fetch loads a window whose bottom is a
- // mid-history edge, not the present. Scrolling "to the end" there would
- // strand the viewer mid-history, so this must wait for the full mount
- // (Cecilia's red line #1: judge the tail by hasMoreNewer, not "are there rows").
- const { action, nextState } = decideScrollAction(
- baseInput({ initialScrollReady: false, hasMoreNewer: true }),
- )
- expect(action).toEqual({ type: "none" })
- expect(nextState.didInitialScroll).toBe(false)
- })
-
- it("does not fire (and does not consume the one-shot gate) until the actual viewport is ready", () => {
- // Regression: the hero's real height is only known after its own
- // ResizeObserver effect runs (a later commit than the one that first
- // renders real messages). scrollMargin defaults to 0 until then — if
- // mount fired on that stale scrollMargin, scrollToIndex's offset math
- // (align: "center") would target the wrong scrollTop, and the
- // virtualizer's own reconcile loop stabilizes on that wrong value
- // within a frame, well before heroHeight's real value lands. Observed
- // as: page loads, view flashes at the tail then snaps to the top hero,
- // and unread messages near the true tail never enter the viewport so
- // useChannelWatermark never advances the read pointer.
- const { action, nextState } = decideScrollAction(baseInput({ viewportReady: false }))
- expect(action).toEqual({ type: "none" })
- expect(nextState.didInitialScroll).toBe(false)
- })
-
- it("for a cold / mid-history window fires the full mount once both initialScrollReady and viewportReady become true, even if one lagged", () => {
- // hasMoreNewer keeps it off the early-bottom path so this still exercises
- // the "wait for both gates, then mount" sequence.
- const notReady = decideScrollAction(baseInput({ initialScrollReady: false, viewportReady: false, hasMoreNewer: true }))
- expect(notReady.action).toEqual({ type: "none" })
- const heroOnly = decideScrollAction(baseInput({ state: notReady.nextState, initialScrollReady: false, viewportReady: true, hasMoreNewer: true }))
- expect(heroOnly.action).toEqual({ type: "none" })
- const bothReady = decideScrollAction(baseInput({ state: heroOnly.nextState, initialScrollReady: true, viewportReady: true, hasMoreNewer: true }))
- expect(bothReady.action.type).toBe("mount")
- // Full mount with the snapshot already resolved completes both phases.
- expect(bothReady.nextState.didDividerConverge).toBe(true)
- })
-
- it("phase 2 — converges to the NEW divider once the snapshot resolves after an early bottom, only while still at the bottom", () => {
- // Phase 1: warm early bottom (snapshot not ready).
- const phase1 = decideScrollAction(baseInput({ initialScrollReady: false, newDividerBefore: undefined }))
- expect(phase1.action).toEqual({ type: "scrollToEnd" })
- expect(phase1.nextState.didDividerConverge).toBe(false)
- // Phase 2: snapshot resolves, a divider is now named, viewer still at bottom.
- const phase2 = decideScrollAction(
- baseInput({ state: phase1.nextState, initialScrollReady: true, newDividerBefore: "m2", isAtEnd: true }),
- )
- expect(phase2.action).toEqual({ type: "mount", newDividerBefore: "m2" })
- expect(phase2.nextState.didDividerConverge).toBe(true)
- })
-
- it("phase 2 — does NOT yank the viewport if the user scrolled away before the snapshot resolved", () => {
- const phase1 = decideScrollAction(baseInput({ initialScrollReady: false }))
- expect(phase1.action).toEqual({ type: "scrollToEnd" })
- // Snapshot resolves with a divider, but the viewer is no longer at the bottom.
- const phase2 = decideScrollAction(
- baseInput({ state: phase1.nextState, initialScrollReady: true, newDividerBefore: "m2", isAtEnd: false }),
- )
- expect(phase2.action).toEqual({ type: "none" })
- // One-shot still consumed so it can't fire on a later revalidation.
- expect(phase2.nextState.didDividerConverge).toBe(true)
- })
-
- it("does not run a delayed phase-1 mount after an upward user intent", () => {
- const result = decideScrollAction(baseInput({
- initialScrollReady: true,
- newDividerBefore: "m2",
- isAtEnd: true,
- userScrolledAway: true,
- }))
- expect(result.action).toEqual({ type: "none" })
- expect(result.nextState.didInitialScroll).toBe(true)
- expect(result.nextState.didDividerConverge).toBe(true)
- })
-
- it("does not run phase-2 convergence from a stale at-end sample after an upward user intent", () => {
- const phase1 = decideScrollAction(baseInput({ initialScrollReady: false }))
- const phase2 = decideScrollAction(baseInput({
- state: phase1.nextState,
- initialScrollReady: true,
- newDividerBefore: "m2",
- isAtEnd: true,
- userScrolledAway: true,
- }))
- expect(phase2.action).toEqual({ type: "none" })
- expect(phase2.nextState.didDividerConverge).toBe(true)
- })
-
- it("fires exactly once — a second commit with didInitialScroll already true does not re-mount-scroll", () => {
- const first = decideScrollAction(baseInput())
- expect(first.action.type).toBe("mount")
- const second = decideScrollAction(baseInput({ state: first.nextState }))
- expect(second.action.type).not.toBe("mount")
- })
-
- it("does not fire on an empty message list, and does not consume the gate", () => {
- const { action, nextState } = decideScrollAction(baseInput({ messages: [] }))
- expect(action).toEqual({ type: "none" })
- expect(nextState.didInitialScroll).toBe(false)
- })
-
- it("re-arms and re-fires the mount scroll after a transient empty following the initial scroll", () => {
- // Regression (live-Playwright-verified): the message list can round-trip
- // through `[]` AFTER the initial scroll already fired, when a live path
- // invalidates the message query mid-mount — the observed trigger is
- // `useCommunityWs`'s `handleReconnect` firing ~1.5s into a fresh load and
- // invalidating both `channelMessages` and the `gcTime: 0` read-state
- // snapshot. Before the fix, the consumed one-shot gate stayed consumed,
- // so when rows returned the view was stuck at the top hero with the NEW
- // divider off-screen. The empty commit must RE-ARM the gate.
- const first = decideScrollAction(baseInput({ newDividerBefore: "m2" }))
- expect(first.action.type).toBe("mount")
- expect(first.nextState.didInitialScroll).toBe(true)
-
- // Mid-mount invalidation empties the list — gate must re-arm to false.
- const emptied = decideScrollAction(baseInput({ state: first.nextState, messages: [] }))
- expect(emptied.action).toEqual({ type: "none" })
- expect(emptied.nextState.didInitialScroll).toBe(false)
-
- // Rows return — mount must fire again to re-anchor on the NEW divider.
- const returned = decideScrollAction(baseInput({ state: emptied.nextState, newDividerBefore: "m2" }))
- expect(returned.action).toEqual({ type: "mount", newDividerBefore: "m2" })
- expect(returned.nextState.didInitialScroll).toBe(true)
- })
-})
-
-// Helper: state as-if mount already happened, tail = "m3".
-function mountedState(overrides: Partial<ScrollAnchorState> = {}): ScrollAnchorState {
- return {
- didInitialScroll: true,
- lastTailId: "m3",
- ...overrides,
- }
-}
-
-describe("decideScrollAction — self-send / peer-follow (both hand-rolled — followOnAppend is deliberately off)", () => {
- it("self-send (tail author === viewer) snaps to bottom regardless of isAtEnd", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "viewer" }]
- const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: false }))
- expect(action).toEqual({ type: "scrollToEnd" })
- })
-
- it("peer send while isAtEnd is true snaps to bottom", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
- const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: true }))
- expect(action).toEqual({ type: "scrollToEnd" })
- })
-
- it("peer send while isAtEnd is false does not scroll — leaves the pill to prompt the user back down", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
- const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer", isAtEnd: false }))
- expect(action).toEqual({ type: "none" })
- })
-
- it("peer send does not follow a stale at-end sample after an upward user intent", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
- const { action } = decideScrollAction(baseInput({
- state,
- messages,
- viewerUserId: "viewer",
- isAtEnd: true,
- userScrolledAway: true,
- }))
- expect(action).toEqual({ type: "none" })
- })
-
- it("peer send is ignored (no auto-follow) when hasMoreNewer is true — loaded window isn't tail-attached, even if isAtEnd is true", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
- const { action } = decideScrollAction(
- baseInput({ state, messages, viewerUserId: "viewer", hasMoreNewer: true, isAtEnd: true }),
- )
- expect(action).toEqual({ type: "none" })
- })
-
- it("newer-page pagination never follows the changed tail as a live append", () => {
- const state = mountedState()
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]
- const { action } = decideScrollAction(baseInput({
- state,
- messages,
- hasMoreNewer: false,
- isPaginatingNewer: true,
- isAtEnd: true,
- }))
- expect(action).toEqual({ type: "none" })
- })
-
- it("no action when the tail id is unchanged", () => {
- const state = mountedState()
- const { action } = decideScrollAction(baseInput({ state, viewerUserId: "viewer" }))
- expect(action).toEqual({ type: "none" })
- })
-
- it("temp-id → canonical-id identity reconcile: tail id changes but author/content/position are otherwise unchanged — resolves as an idempotent self-send, not a misclassified no-op", () => {
- // Simulates: viewer sent a message (tempId "temp_123"), it's already the
- // tail, then postAck advances the id to the canonical server id
- // ("srv_abc") — same author, same position, nothing
- // about scroll position should change, but the tail id STRING changed.
- // With getItemKey keyed on message id, this is a bigger structural event
- // for the virtualizer than it was for raw DOM (the item's key changes) —
- // still must resolve as self-send, not fall through to "none".
- const state = mountedState({ lastTailId: "temp_123" })
- const messages = [{ id: "m1" }, { id: "m2" }, { id: "srv_abc", authorId: "viewer" }]
- const { action } = decideScrollAction(baseInput({ state, messages, viewerUserId: "viewer" }))
- expect(action).toEqual({ type: "scrollToEnd" })
- })
-})
-
-describe("NEAR_BOTTOM_PX", () => {
- it("is the single shared threshold, reused for both isAtEnd checks and the virtualizer's own scrollEndThreshold config", () => {
- expect(NEAR_BOTTOM_PX).toBe(100)
+describe("MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX", () => {
+ it("keeps the 100px presentation and viewport policy separate from physical follow", () => {
+ expect(MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX).toBe(100)
})
})
@@ -394,21 +138,3 @@ describe("findMessageIndex", () => {
expect(findMessageIndex(items, "d1")).toBeNull()
})
})
-
-describe("extractScrollAnchorMessages", () => {
- it("extracts only 'message' items' id/authorId, in order, skipping dividers", () => {
- const items: FlatItem[] = [
- { kind: "message", m: { id: "m1", type: "chat", grouped: false, authorId: "u1" }, key: "msg:m1" },
- { kind: "message", m: { id: "m2", type: "chat", grouped: false }, key: "msg:m2" },
- ]
- expect(extractScrollAnchorMessages(items)).toEqual([
- { id: "m1", authorId: "u1" },
- { id: "m2", authorId: undefined },
- ])
- })
-
- it("returns an empty array when there are no message items", () => {
- const items: FlatItem[] = []
- expect(extractScrollAnchorMessages(items)).toEqual([])
- })
-})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 3f9d22082..cdafecc8a 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -1,11 +1,12 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useLayoutEffect, useMemo, useRef } from "react"
+import { useCallback, useLayoutEffect, useRef } from "react"
import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"
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_LIST_DISPLAY_END_THRESHOLD_PX = 100
+const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100
export const MESSAGE_RAIL_TAIL_PADDING_END_PX = {
mobile: 40 - MESSAGE_ROW_VERTICAL_PADDING_PX,
desktop: 48 - MESSAGE_ROW_VERTICAL_PADDING_PX,
@@ -48,7 +49,7 @@ export function resolveViewportResizeAnchor({
)
const viewportGrowth = Math.max(0, nextClientHeight - previousClientHeight)
const anchor: ViewportResizeAnchor = distanceToEnd <= Math.max(
- NEAR_BOTTOM_PX,
+ VIEWPORT_RESIZE_TAIL_DISTANCE_PX,
viewportGrowth,
)
? "tail"
@@ -69,122 +70,6 @@ export function measureMessageRow(element: Element): number {
const row = element as HTMLElement
return Math.ceil(Math.max(element.getBoundingClientRect().height, row.scrollHeight))
}
-export interface ScrollAnchorMessage {
- id: string
- authorId?: string
-}
-
-export interface ScrollAnchorState {
- didInitialScroll: boolean
- didDividerConverge: boolean
- lastTailId: string | null
-}
-
-export function createScrollAnchorState(): ScrollAnchorState {
- return {
- didInitialScroll: false,
- didDividerConverge: false,
- lastTailId: null,
- }
-}
-
-export interface DecideScrollActionInput {
- state: ScrollAnchorState
- messages: ScrollAnchorMessage[]
- newDividerBefore?: string
- initialScrollReady: boolean
- viewportReady: boolean
- hasMoreNewer?: boolean
- isPaginatingNewer?: boolean
- viewerUserId?: string
- isAtEnd: boolean
- userScrolledAway?: boolean
-}
-
-type ScrollAction =
- | { type: "none" }
- | { type: "mount"; newDividerBefore: string | undefined }
- | { type: "scrollToEnd" }
-
-export interface DecideScrollActionResult {
- action: ScrollAction
- nextState: ScrollAnchorState
-}
-
-export function decideScrollAction(input: DecideScrollActionInput): DecideScrollActionResult {
- const { state, messages, newDividerBefore, initialScrollReady, viewportReady, hasMoreNewer, isPaginatingNewer, viewerUserId, isAtEnd, userScrolledAway } = input
-
- const nextTail = messages[messages.length - 1]?.id ?? null
- const nextLen = messages.length
-
- const baseNextState: ScrollAnchorState = {
- didInitialScroll: state.didInitialScroll,
- didDividerConverge: state.didDividerConverge,
- lastTailId: nextTail,
- }
- if (nextLen === 0) {
- return {
- action: { type: "none" },
- nextState: { ...baseNextState, didInitialScroll: false, didDividerConverge: false },
- }
- }
- const tailAttached = !hasMoreNewer
- if (!state.didInitialScroll) {
- if (viewportReady && userScrolledAway) {
- return {
- action: { type: "none" },
- nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: true },
- }
- }
- if (viewportReady && initialScrollReady) {
- return {
- action: { type: "mount", newDividerBefore },
- nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: true },
- }
- }
- if (viewportReady && tailAttached) {
- return {
- action: { type: "scrollToEnd" },
- nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: false },
- }
- }
- return {
- action: { type: "none" },
- nextState: { ...baseNextState, didInitialScroll: false },
- }
- }
- const tailChanged = state.lastTailId !== null && state.lastTailId !== nextTail
- if (!state.didDividerConverge && !tailChanged) {
- if (!initialScrollReady || !viewportReady) {
- return { action: { type: "none" }, nextState: baseNextState }
- }
- if (newDividerBefore && isAtEnd && !userScrolledAway) {
- return {
- action: { type: "mount", newDividerBefore },
- nextState: { ...baseNextState, didDividerConverge: true },
- }
- }
- return { action: { type: "none" }, nextState: { ...baseNextState, didDividerConverge: true } }
- }
- if (tailChanged) {
- const liveState = { ...baseNextState, didDividerConverge: true }
- if (isPaginatingNewer) {
- return { action: { type: "none" }, nextState: liveState }
- }
- const tail = messages[messages.length - 1]
- const isSelfSend = !!viewerUserId && tail?.authorId === viewerUserId
- if (isSelfSend) {
- return { action: { type: "scrollToEnd" }, nextState: liveState }
- }
- if (!hasMoreNewer && isAtEnd && !userScrolledAway) {
- return { action: { type: "scrollToEnd" }, nextState: liveState }
- }
- return { action: { type: "none" }, nextState: liveState }
- }
-
- return { action: { type: "none" }, nextState: baseNextState }
-}
-
export function findMessageIndex(items: FlatItem[], messageId: string): number | null {
for (let i = 0; i < items.length; i++) {
const item = items[i]
@@ -198,14 +83,6 @@ export function findMountScrollTargetIndex(items: FlatItem[], newDividerBefore:
return divider >= 0 ? divider : findMessageIndex(items, newDividerBefore)
}
-export function extractScrollAnchorMessages(items: FlatItem[]): ScrollAnchorMessage[] {
- const out: ScrollAnchorMessage[] = []
- for (const item of items) {
- if (item.kind === "message") out.push({ id: item.m.id, authorId: item.m.authorId })
- }
- return out
-}
-
export function useScrollAnchor({
items,
newDividerBefore,
@@ -218,7 +95,7 @@ export function useScrollAnchor({
isFetchingOlder,
isFetchingNewer,
presentVersion,
- viewerUserId,
+ localSubmitVersion,
tailPaddingEnd = MESSAGE_RAIL_TAIL_PADDING_END_PX.desktop,
onInitialPositionSettled,
}: {
@@ -233,7 +110,7 @@ export function useScrollAnchor({
isFetchingOlder?: boolean
isFetchingNewer?: boolean
presentVersion?: number
- viewerUserId?: string
+ localSubmitVersion?: number
tailPaddingEnd?: number
onInitialPositionSettled?: () => void
}) {
@@ -247,7 +124,7 @@ export function useScrollAnchor({
behavior: ScrollBehavior
notifyTarget: boolean
loadedTailPresent: boolean
- singleEnd: { key: string | null; index: number } | null
+ singleEnd: { key: string | null; index: number; retired: boolean } | null
viewport: { width: number; height: number }
}
type Geometry = {
@@ -267,7 +144,7 @@ export function useScrollAnchor({
}
const scrollRef = useRef<HTMLDivElement>(null)
const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)
- const positionOwnerRef = useRef({ epoch: 0, active: true, nativeIndex: false })
+ const positionOwnerRef = useRef({ epoch: 0, active: true })
const positionKind = useCreateAtom<Kind>("initial")
const [ownerKind, setOwnerKind] = useAtom(positionKind)
const nativeOrigin = useCreateAtom<string | number | bigint | null>(null)
@@ -283,17 +160,17 @@ export function useScrollAnchor({
} | null>(null)
const scrollPaddingStartRef = useRef(0)
const olderMeasurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)
- const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
+ const entryResolvedRef = useRef(false)
const initialRetiredRef = useRef(false)
const initialPositionSettledRef = useRef(false)
- const initialDeadlineRef = useRef<number | null>(null)
- const positionBudgetStartedRef = useRef(false)
+ const initialDeadlineRef = useRef<{ handle: number; at: number } | null>(null)
const initialSettleFrameRef = useRef<number | null>(null)
const semanticIntentRef = useRef<Intent | null>(null)
const targetIntentRef = useRef<string | null>(null)
const positionedTargetRef = useRef<string | null>(null)
- const presentIntentEpochRef = useRef<number | null>(null)
- const consumedPresentVersionRef = useRef(0)
+ const presentIntentRef = useRef<{ epoch: number; allowAttachedTail: boolean } | null>(null)
+ const consumedPresentVersionRef = useRef(presentVersion ?? 0)
+ const consumedLocalSubmitVersionRef = useRef(localSubmitVersion ?? 0)
const currentItemsRef = useRef(items)
currentItemsRef.current = items
const initialScrollReadyRef = useRef(initialScrollReady)
@@ -304,17 +181,17 @@ export function useScrollAnchor({
onTargetCancelledRef.current = onScrollTargetCancelled
const settleCallbackRef = useRef(onInitialPositionSettled)
settleCallbackRef.current = onInitialPositionSettled
- const wasAtEndRef = useRef(false)
- const userScrolledAwayRef = useRef(false)
+ const followSuspension = useCreateAtom(false)
+ const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
const acceptedGeometryRef = useRef<Geometry | null>(null)
const geometrySampleRef = useRef<{ value: string; frames: number } | null>(null)
const geometryFrameRef = useRef<number | null>(null)
const scheduleGeometryRef = useRef<() => void>(() => {})
const reconcileViewportRef = useRef<() => void>(() => {})
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 hasMessages = items.some(item => item.kind === "message")
+ const hadMessagesRef = useRef(false)
+ const pendingLocalSubmit = (localSubmitVersion ?? 0) > consumedLocalSubmitVersionRef.current
const holdNativeOrigin = useCallback((key: string | number | bigint | null) => {
setNativeOriginKey(key)
const native = virtualizerRef.current
@@ -330,9 +207,8 @@ export function useScrollAnchor({
settleCallbackRef.current?.()
}, [])
const clearBudget = useCallback(() => {
- if (initialDeadlineRef.current !== null) window.clearTimeout(initialDeadlineRef.current)
+ if (initialDeadlineRef.current !== null) window.clearTimeout(initialDeadlineRef.current.handle)
initialDeadlineRef.current = null
- positionBudgetStartedRef.current = false
}, [])
const clearOlderMeasurementAnchor = useCallback(() => {
olderMeasurementAnchorRef.current = null
@@ -347,10 +223,7 @@ export function useScrollAnchor({
}, [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
+ virtualizerRef.current?.cancelScroll()
clearOlderMeasurementAnchor()
paginationRef.current = null
setPaginationDirection(null)
@@ -363,13 +236,13 @@ export function useScrollAnchor({
acceptedGeometryRef.current = null
holdNativeOrigin(null)
geometrySampleRef.current = null
- presentIntentEpochRef.current = null
+ presentIntentRef.current = null
setReadPositionReady(false)
return owner.epoch
}, [cancelFrame, clearBudget, clearOlderMeasurementAnchor, holdNativeOrigin, setOwnerKind, setPaginationDirection, setReadPositionReady])
const retireInitialPosition = useCallback(() => {
initialRetiredRef.current = true
- stateRef.current = { ...stateRef.current, didInitialScroll: true, didDividerConverge: true }
+ entryResolvedRef.current = true
}, [])
const releasePosition = useCallback((userHandover = false) => {
const intent = semanticIntentRef.current
@@ -388,13 +261,14 @@ export function useScrollAnchor({
scheduleGeometryRef.current()
}, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
const armBudget = useCallback(() => {
- if (positionBudgetStartedRef.current) return
- positionBudgetStartedRef.current = true
+ if (initialDeadlineRef.current !== null) return
const epoch = positionOwnerRef.current.epoch
- initialDeadlineRef.current = window.setTimeout(() => {
+ const at = Date.now() + INITIAL_POSITION_TIMEOUT_MS
+ const handle = window.setTimeout(() => {
if (!positionOwnerRef.current.active || positionOwnerRef.current.epoch !== epoch) return
releasePosition()
}, INITIAL_POSITION_TIMEOUT_MS)
+ initialDeadlineRef.current = { handle, at }
}, [releasePosition])
@@ -448,9 +322,12 @@ export function useScrollAnchor({
: measureElement(element, entry, instance),
getItemKey,
scrollPaddingStart: scrollPaddingStartRef.current,
- anchorTo: ownerKind === "idle" && !awaitingTarget
+ anchorTo: ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit
&& (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",
- followOnAppend: false,
+ followOnAppend: ownerKind === "idle" && readPositionReady && !awaitingTarget && hasMessages && hadMessagesRef.current
+ && !pendingLocalSubmit && !followSuspended && !hasMoreNewer
+ && !isFetchingOlder && !isFetchingNewer && paginationDirection === null
+ && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,
scrollEndThreshold: 1,
scrollMargin: 0,
paddingStart: shortGap,
@@ -459,6 +336,7 @@ export function useScrollAnchor({
onChange: () => { refreshPendingPageAnchor(); reconcileViewportRef.current(); scheduleGeometryRef.current() },
})
virtualizerRef.current = virtualizer
+ useLayoutEffect(() => { hadMessagesRef.current = hasMessages }, [hasMessages])
useLayoutEffect(() => {
const anchor = olderMeasurementAnchorRef.current
if (anchor && !items.some(item => item.key === anchor.key)) clearOlderMeasurementAnchor()
@@ -499,11 +377,11 @@ export function useScrollAnchor({
outerHeight: root.offsetHeight, outerWidth: root.offsetWidth,
scrollHeight: root.scrollHeight, scrollTop: root.scrollTop,
total, paddingEnd: native.options.paddingEnd ?? 0,
- pinEligible: native.isAtEnd(1) && !userScrolledAwayRef.current
+ pinEligible: native.isAtEnd(1) && !followSuspension.get()
&& nativeOrigin.get() !== currentItemsRef.current[0]?.key,
isScrolling: native.isScrolling,
}
- }, [nativeOrigin])
+ }, [followSuspension, nativeOrigin])
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
if (semanticIntentRef.current?.loadedTailPresent) semanticIntentRef.current.stableFrames = 0
@@ -516,10 +394,16 @@ export function useScrollAnchor({
const root = scrollRef.current
const native = virtualizerRef.current
if (!intent || intent.epoch !== owner.epoch || !root || !native) return
+ if (intent.singleEnd && initialDeadlineRef.current !== null && Date.now() >= initialDeadlineRef.current.at) {
+ releasePosition()
+ return
+ }
+ if (intent.singleEnd?.retired) return
const index = currentItemsRef.current.length - 1
if (intent.singleEnd && (index < 0 || intent.singleEnd.index !== index
|| intent.singleEnd.key !== currentItemsRef.current[index]?.key)) {
- releasePosition()
+ intent.singleEnd.retired = true
+ native.cancelScroll()
return
}
const viewport = root.getBoundingClientRect()
@@ -536,7 +420,6 @@ export function useScrollAnchor({
if (geometrySampleRef.current && geometrySampleRef.current.frames >= 2) {
intent.index = index
geometrySampleRef.current = null
- owner.nativeIndex = true
native.scrollToEnd({ behavior: intent.behavior })
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
@@ -544,12 +427,6 @@ export function useScrollAnchor({
}
let landed = false
if (intent.type === "end") {
- if (!intent.singleEnd && intent.index !== index) {
- intent.index = index
- intent.stableFrames = 0
- owner.nativeIndex = index >= 0
- native.scrollToEnd({ behavior: intent.behavior })
- }
landed = native.isAtEnd(1) && (!intent.singleEnd
|| Math.abs(Math.max(0, root.scrollHeight - root.clientHeight) - root.scrollTop) <= 1)
} else if (intent.id) {
@@ -559,7 +436,6 @@ export function useScrollAnchor({
if (index !== null && index !== intent.index) {
intent.index = index
intent.stableFrames = 0
- owner.nativeIndex = true
native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
}
const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
@@ -592,9 +468,9 @@ export function useScrollAnchor({
if (positionKind.get() === "initial" && !initialScrollReadyRef.current) return
acceptedGeometryRef.current = geometry
semanticIntentRef.current = null
- owner.nativeIndex = false
setOwnerKind("idle")
setReadPositionReady(true)
+ retireInitialPosition()
clearBudget()
if (intent.notifyTarget && intent.id) {
positionedTargetRef.current = intent.id
@@ -608,7 +484,7 @@ export function useScrollAnchor({
}
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, releasePosition, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])
const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false, singleEnd = false) => {
const owner = positionOwnerRef.current
@@ -617,15 +493,13 @@ export function useScrollAnchor({
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
epoch: owner.epoch, type, id, index: singleEnd ? null : index, stableFrames: 0, behavior, notifyTarget, loadedTailPresent,
- singleEnd: singleEnd ? { key: currentItemsRef.current[index ?? -1]?.key ?? null, index: index ?? -1 } : null,
+ singleEnd: singleEnd ? { key: currentItemsRef.current[index ?? -1]?.key ?? null, index: index ?? -1, retired: false } : null,
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
}
if (type === "end" && !singleEnd) {
- owner.nativeIndex = currentItemsRef.current.length > 0
virtualizerRef.current?.scrollToEnd({ behavior })
}
else if (type !== "end" && index !== null) {
- owner.nativeIndex = true
virtualizerRef.current?.scrollToIndex(index, { align: "center", behavior })
}
if (!loadedTailPresent || singleEnd) armBudget()
@@ -634,21 +508,19 @@ export function useScrollAnchor({
useLayoutEffect(() => {
const owner = positionOwnerRef.current
- const root = scrollRef.current
owner.active = true
const intent = semanticIntentRef.current
if (intent && intent.epoch !== owner.epoch) {
if (intent.singleEnd) releasePosition()
else startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
- } else if (positionKind.get() === "present" && presentIntentEpochRef.current !== null) {
- presentIntentEpochRef.current = owner.epoch
+ } else if (positionKind.get() === "present" && presentIntentRef.current !== null) {
+ presentIntentRef.current.epoch = owner.epoch
armBudget()
}
return () => {
owner.active = false
owner.epoch += 1
- if (owner.nativeIndex && root) virtualizerRef.current?.scrollToOffset(root.scrollTop, { behavior: "auto" })
- owner.nativeIndex = false
+ virtualizerRef.current?.cancelScroll()
clearOlderMeasurementAnchor()
paginationRef.current = null
cancelFrame()
@@ -675,7 +547,6 @@ export function useScrollAnchor({
useLayoutEffect(() => {
if (items.length === 0) return
- const owner = positionOwnerRef.current
if (positionKind.get() === "target") {
if (!semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)
else scheduleInitialPositionSettled()
@@ -684,7 +555,6 @@ export function useScrollAnchor({
const observeGeometry = useCallback((next: Geometry, scrollEvent = false) => {
const previous = acceptedGeometryRef.current
- const previousFold = previous && virtualizerRef.current?.getVirtualItems().find((item) => item.key === previous.key)
const scrolledAfterResize = scrollEvent && previous?.epoch === next.epoch
&& previous.clientWidth === next.clientWidth
&& (previous.clientHeight !== next.clientHeight || previous.paddingEnd !== next.paddingEnd)
@@ -693,9 +563,7 @@ export function useScrollAnchor({
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.paddingEnd === next.paddingEnd
))) {
const unchangedPosition = previous?.epoch === next.epoch
&& previous.clientHeight === next.clientHeight && previous.clientWidth === next.clientWidth
@@ -727,12 +595,16 @@ export function useScrollAnchor({
}
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
const max = Math.max(0, root.scrollHeight - root.clientHeight)
const previous = acceptedGeometryRef.current
- const viewportResized = !!next && previous?.epoch === owner.epoch
- && (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd)
+ const viewportResized = previous?.epoch === owner.epoch
+ && (previous.clientHeight !== root.clientHeight || previous.clientWidth !== root.clientWidth
+ || previous.paddingEnd !== (native.options.paddingEnd ?? 0))
+ if (!viewportResized && !input.handover && paginationRef.current?.phase !== "settling") {
+ if (next) observeGeometry(next)
+ return false
+ }
const clampedByResize = viewportResized && !previous.isScrolling && previous.scrollTop > max
&& Math.abs(root.scrollTop - max) <= 1
if (input.touch || input.pointers.size > 0 || (native.isScrolling && !clampedByResize)
@@ -750,10 +622,10 @@ export function useScrollAnchor({
const value = JSON.stringify(next)
const sample = geometrySampleRef.current
geometrySampleRef.current = { value, frames: sample?.value === value ? sample.frames + 1 : 1 }
- if (!viewportResized && geometrySampleRef.current.frames < 2) return true
+ if (!viewportResized && paginationRef.current?.phase === "settling" && geometrySampleRef.current.frames < 2) return true
let offset = root.scrollTop
let originHeld = false
- if (previous?.epoch === owner.epoch && readReady.get()) {
+ if (viewportResized && previous?.epoch === owner.epoch && readReady.get()) {
originHeld = !previous.pinEligible && previous.scrollTop <= 1
&& previous.key === currentItemsRef.current[0]?.key && previous.itemStart <= 1
if (originHeld) offset = previous.scrollTop
@@ -780,16 +652,12 @@ export function useScrollAnchor({
isScrolling: clampedByResize ? previous.isScrolling : next.isScrolling,
}
holdNativeOrigin(originHeld || (offset <= 1 && !acceptedGeometryRef.current.pinEligible) ? currentItemsRef.current[0]?.key ?? null : null)
- wasAtEndRef.current = max - offset <= NEAR_BOTTOM_PX
if (input.handover) {
input.handover = false
setReadPositionReady(true)
}
if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })
- if (olderMeasurementAnchorRef.current) {
- clearOlderMeasurementAnchor()
- owner.nativeIndex = false
- }
+ if (olderMeasurementAnchorRef.current) clearOlderMeasurementAnchor()
if (paginationRef.current?.phase === "settling") {
paginationRef.current = null
setPaginationDirection(null)
@@ -805,11 +673,10 @@ export function useScrollAnchor({
intent.viewport = { width: root.clientWidth, height: root.clientHeight }
intent.stableFrames = 0
if (intent.singleEnd) geometrySampleRef.current = null
- if (root.clientHeight > 0 && !intent.loadedTailPresent && !intent.singleEnd) {
- if (intent.type === "end") native.scrollToEnd({ behavior: intent.behavior })
- else if (intent.index !== null) native.scrollToIndex(intent.index, { align: "center", behavior: intent.behavior })
- scheduleInitialPositionSettled()
+ else if (intent.type !== "end" && intent.index !== null && root.clientHeight > 0) {
+ native.scrollToIndex(intent.index, { align: "center", behavior: intent.behavior })
}
+ scheduleInitialPositionSettled()
}
if (intent?.loadedTailPresent) scheduleInitialPositionSettled()
reconcileGeometry(true)
@@ -852,9 +719,11 @@ export function useScrollAnchor({
}
reconcileGeometry(true)
if (semanticIntentRef.current?.loadedTailPresent) scheduleInitialPositionSettled()
- wasAtEndRef.current = native?.isAtEnd(NEAR_BOTTOM_PX) ?? false
- if (wasAtEndRef.current) userScrolledAwayRef.current = false
const next = readGeometry()
+ if (next && native?.isAtEnd(1) && Math.abs(Math.max(0, next.scrollHeight - next.clientHeight) - next.scrollTop) <= 1
+ && !userInputRef.current.touch && userInputRef.current.pointers.size === 0
+ && positionKind.get() === "idle" && readReady.get()
+ && nativeOrigin.get() !== currentItemsRef.current[0]?.key) setFollowSuspended(false)
if (next) observeGeometry(next, true)
else if (positionKind.get() === "idle" && readReady.get()
&& previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop !== root.scrollTop
@@ -873,12 +742,11 @@ export function useScrollAnchor({
const geometry = readGeometry()
if (!geometry || geometry.isScrolling || !native?.isAtEnd(1)
|| Math.abs(Math.max(0, geometry.scrollHeight - geometry.clientHeight) - geometry.scrollTop) > 1) return
- wasAtEndRef.current = true
- userScrolledAwayRef.current = false
+ setFollowSuspended(false)
}
const onUserIntent = (towardEnd = false) => {
releasePosition(true)
- userScrolledAwayRef.current = true
+ setFollowSuspended(true)
if (root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
if (towardEnd) restoreEndEligibility()
}
@@ -941,7 +809,7 @@ export function useScrollAnchor({
inputOwner.touch = false
inputOwner.pointers.clear()
}
- }, [holdNativeOrigin, nativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled])
+ }, [holdNativeOrigin, nativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
const capturePageAnchor = useCallback((direction: "older" | "newer") => {
if (semanticIntentRef.current?.singleEnd) releasePosition()
@@ -991,93 +859,85 @@ export function useScrollAnchor({
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()
- }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled, tailId])
+ }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled])
+
+ useLayoutEffect(() => {
+ const version = localSubmitVersion ?? 0
+ if (version === consumedLocalSubmitVersionRef.current) return
+ const accepted = version > consumedLocalSubmitVersionRef.current
+ consumedLocalSubmitVersionRef.current = version
+ if (!accepted) return
+ if (positionKind.get() === "target") releasePosition()
+ const epoch = claimPosition("present")
+ retireInitialPosition()
+ setFollowSuspended(false)
+ if (hasMessages && !hasMoreNewer && !isFetchingNewer) startIntent("end", null)
+ else {
+ presentIntentRef.current = { epoch, allowAttachedTail: !hasMoreNewer && !isFetchingNewer }
+ armBudget()
+ }
+ }, [armBudget, claimPosition, hasMessages, hasMoreNewer, isFetchingNewer, localSubmitVersion, positionKind, releasePosition, retireInitialPosition, setFollowSuspended, startIntent])
useLayoutEffect(() => {
- if (!presentVersion || !tailId || hasMoreNewer || consumedPresentVersionRef.current === presentVersion) return
- consumedPresentVersionRef.current = presentVersion
- stateRef.current = { ...stateRef.current, lastTailId: tailId }
- tailKeyRef.current = items.at(-1)?.key ?? null
+ if (!hasMessages || hasMoreNewer || isFetchingNewer) return
+ const completedWindow = !!presentVersion && consumedPresentVersionRef.current !== presentVersion
+ if (completedWindow) consumedPresentVersionRef.current = presentVersion
const owner = positionOwnerRef.current
- if (!owner.active || positionKind.get() !== "present" || presentIntentEpochRef.current !== owner.epoch) return
- presentIntentEpochRef.current = null
+ const intent = presentIntentRef.current
+ if (!owner.active || positionKind.get() !== "present" || intent?.epoch !== owner.epoch
+ || (!completedWindow && !intent.allowAttachedTail)) return
+ presentIntentRef.current = null
retireInitialPosition()
- userScrolledAwayRef.current = false
+ setFollowSuspended(false)
startIntent("end", null)
- }, [hasMoreNewer, items, positionKind, presentVersion, retireInitialPosition, startIntent, tailId])
+ }, [hasMessages, hasMoreNewer, isFetchingNewer, positionKind, presentVersion, retireInitialPosition, setFollowSuspended, startIntent])
const virtualItems = virtualizer.getVirtualItems()
useLayoutEffect(() => {
- const owner = positionOwnerRef.current
const root = scrollRef.current
const viewportReady = !!root && root.clientHeight > 0 && virtualItems.length > 0
&& !!root.querySelector("[data-index]")
- const singleEnd = semanticIntentRef.current?.singleEnd
- if (singleEnd && (singleEnd.index !== items.length - 1 || singleEnd.key !== items.at(-1)?.key)) releasePosition()
- if (positionKind.get() === "target" || positionKind.get() === "present") {
- stateRef.current = { ...stateRef.current, lastTailId: tailId }
- tailKeyRef.current = items.at(-1)?.key ?? null
- return
- }
- 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) {
- stateRef.current = { ...stateRef.current, didDividerConverge: true }
- startIntent(newDividerBefore ? "unread" : "end", newDividerBefore ?? null)
- } else scheduleInitialPositionSettled()
- return
- }
- const previousTailKey = tailKeyRef.current
- const nextTailKey = items.at(-1)?.key ?? null
- const { action, nextState } = decideScrollAction({
- state: stateRef.current,
- messages,
- newDividerBefore,
- initialScrollReady,
- viewportReady,
- hasMoreNewer,
- isPaginatingNewer: !!isFetchingNewer || paginationDirection === "newer",
- viewerUserId,
- isAtEnd: wasAtEndRef.current,
- userScrolledAway: userScrolledAwayRef.current,
- })
- stateRef.current = initialRetiredRef.current
- ? { ...nextState, didInitialScroll: true, didDividerConverge: true }
- : nextState
- tailKeyRef.current = nextTailKey
- if (action.type === "mount" && positionKind.get() === "initial") {
- startIntent(action.newDividerBefore ? "unread" : "end", action.newDividerBefore ?? null)
- } else if (action.type === "scrollToEnd") {
- if (positionKind.get() === "initial") startIntent("end", null)
- else if (readReady.get() && previousTailKey !== nextTailKey) {
- claimPosition("present")
- retireInitialPosition()
- userScrolledAwayRef.current = false
- startIntent("end", null)
+ const intent = semanticIntentRef.current
+ const singleEnd = intent?.singleEnd
+ if (intent && singleEnd && (singleEnd.retired || singleEnd.index !== items.length - 1 || singleEnd.key !== items.at(-1)?.key)) {
+ const committedAppend = singleEnd.retired && intent.index === null
+ && singleEnd.index < items.length - 1 && items[singleEnd.index]?.key === singleEnd.key
+ && initialDeadlineRef.current !== null && Date.now() < initialDeadlineRef.current.at
+ if (!committedAppend) releasePosition()
+ else {
+ cancelFrame()
+ singleEnd.index = items.length - 1
+ singleEnd.key = items.at(-1)?.key ?? null
+ singleEnd.retired = false
+ intent.stableFrames = 0
+ geometrySampleRef.current = null
+ scheduleInitialPositionSettled()
}
- } else if (semanticIntentRef.current) scheduleInitialPositionSettled()
- }, [claimPosition, hasMoreNewer, initialScrollReady, isFetchingNewer, items, messages, newDividerBefore, paginationDirection, positionKind, readReady, releasePosition, retireInitialPosition, scheduleInitialPositionSettled, startIntent, tailId, viewerUserId, virtualItems, virtualizer])
+ }
+ if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages || !viewportReady) return
+ if (initialScrollReady && !entryResolvedRef.current) {
+ entryResolvedRef.current = true
+ startIntent(newDividerBefore ? "unread" : "end", newDividerBefore ?? null)
+ } else if (!initialScrollReady && !hasMoreNewer && !semanticIntentRef.current) startIntent("end", null)
+ else scheduleInitialPositionSettled()
+ }, [cancelFrame, hasMessages, hasMoreNewer, initialScrollReady, items, newDividerBefore, positionKind, releasePosition, scheduleInitialPositionSettled, startIntent, virtualItems])
const requestPresentPosition = useCallback(() => {
- presentIntentEpochRef.current = claimPosition("present")
+ presentIntentRef.current = { epoch: claimPosition("present"), allowAttachedTail: false }
retireInitialPosition()
armBudget()
}, [armBudget, claimPosition, retireInitialPosition])
const scrollToBottom = useCallback(() => {
claimPosition("present")
retireInitialPosition()
- userScrolledAwayRef.current = false
+ setFollowSuspended(false)
startIntent("end", null, "auto", false, true)
- }, [claimPosition, retireInitialPosition, startIntent])
+ }, [claimPosition, retireInitialPosition, setFollowSuspended, startIntent])
const jumpTo = useCallback((messageId: string, behavior: ScrollBehavior = "smooth") => {
if (findMessageIndex(currentItemsRef.current, messageId) === null) return
claimPosition("target")
@@ -1089,7 +949,7 @@ export function useScrollAnchor({
const lastVisibleIndex = root
? visibleItems.filter((item) => item.start < root.scrollTop + root.clientHeight).at(-1)?.index ?? -1
: -1
- const belowCount = root && virtualizer.isAtEnd(NEAR_BOTTOM_PX)
+ const belowCount = root && virtualizer.isAtEnd(MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX)
? 0 : computeBelowCount(items, lastVisibleIndex)
return {
scrollRef, virtualizer, readPositionReady, paginationEnabled: ownerKind === "idle" && !awaitingTarget, belowCount,
diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
index 38752b1dc..99649450f 100644
--- a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
@@ -1,4 +1,6 @@
import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
+import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
import { tid } from "./_fixtures/testids"
import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"
import { WEB_URL } from "./_setup/paths"
@@ -43,8 +45,9 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
)
}
- const { page } = await asUser("alice")
- await page.goto(`/c/channels/${serverId}/${channelId}`)
+ const { page, context } = await asUser("alice")
+ const proxy = await proxyCommunityWebSockets(context)
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })
const divider = page.getByTestId(tid.newDivider)
await expect(divider).toBeVisible({ timeout: 30_000 })
@@ -91,6 +94,7 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
})
let bodySamples: BodySample[] = []
+ let liveMessageId = ""
try {
const liveAppend = (async () => {
await page.waitForTimeout(250) // inject the append during the upward-scroll gesture
@@ -101,13 +105,16 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
await page.waitForTimeout(24) // fixed wheel-event cadence under test
await recorder.evaluate((recording) => recording.sample())
}
- await liveAppend
+ liveMessageId = await liveAppend
await page.waitForTimeout(250) // post-append scroll-correction exclusion window
} finally {
bodySamples = await recorder.evaluate((recording) => recording.finish())
await recorder.dispose()
}
+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === liveMessageId,
+ )).length).toBe(1)
expect(bodySamples.length).toBeGreaterThan(1)
let upwardProgress = 0
for (let index = 1; index < bodySamples.length; index++) {
@@ -127,3 +134,51 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
}
expect(upwardProgress).toBeGreaterThan(600)
})
+
+test("New reading near the tail survives peer and remote-self messages until the current composer submits", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `NEW near tail ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "new-near-tail")
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
+ let readThroughId = ""
+ for (let index = 0; index < 18; index++) readThroughId = await seedMessage("alice", channelId, `read ${index}`)
+ const read = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ method: "PUT",
+ headers: { Cookie: sessionCookie("alice"), "Content-Type": "application/json", Origin: WEB_URL },
+ body: JSON.stringify({ lastReadMessageId: readThroughId }),
+ })
+ expect(read.status).toBe(200)
+ for (let index = 0; index < 5; index++) await seedMessage(index % 2 ? "bob" : "carol", channelId, `unread ${index}`)
+ const { page, context } = await asUser("alice")
+ await page.setViewportSize({ width: 1280, height: 800 })
+ const proxy = await proxyCommunityWebSockets(context)
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const scroller = page.getByTestId(tid.messageScroller)
+ const divider = page.getByTestId(tid.newDivider)
+ await expect(divider).toBeVisible()
+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
+ await scroller.evaluate(element => {
+ element.scrollTop = element.scrollHeight - element.clientHeight - 20
+ element.dispatchEvent(new Event("scroll"))
+ })
+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight - element.clientHeight - element.scrollTop)).toBe(20)
+ await expect(divider).toBeVisible()
+ const before = await divider.evaluate(element => element.getBoundingClientRect().top)
+ for (const author of ["bob", "alice"] as const) {
+ const id = await seedMessage(author, channelId, `remote ${author} near New ${Date.now()}`)
+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === id,
+ )).length).toBe(1)
+ await expect(divider).toBeVisible()
+ await page.waitForTimeout(250)
+ expect(Math.abs(await divider.evaluate(element => element.getBoundingClientRect().top) - before)).toBeLessThanOrEqual(1)
+ }
+ const content = `local composer near New ${Date.now()}`
+ await sendMessage(page, content)
+ await expect(page.getByText(content, { exact: true })).toHaveCount(1)
+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.content === content,
+ )).length).toBe(1)
+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight - element.clientHeight - element.scrollTop)).toBeLessThanOrEqual(1)
+})
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index 2f8daaf8d..9feae73f0 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -512,6 +512,25 @@ function messageCreateCount(
&& event.message?.content?.includes(body))).length
}
+type PostedMessageIdentity = { id: string; seq: number; channelId: string; authorId: string; content: string }
+
+async function expectMessageCreateIdentity(
+ frames: Awaited<ReturnType<typeof proxyCommunityWebSockets>>["frames"],
+ channelId: string,
+ message: PostedMessageIdentity,
+ nonce: string,
+): Promise<void> {
+ expect(message.id.length).toBeGreaterThan(0)
+ expect(message.seq).toBeGreaterThan(0)
+ await expect.poll(() => frames.flatMap(communityFrameEvents).filter(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,
+ ).length).toBe(1)
+ const created = frames.flatMap(communityFrameEvents).find(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === message.id,
+ )!
+ expect(created.message).toMatchObject({ id: message.id, seq: message.seq, authorId: message.authorId, clientNonce: nonce })
+}
+
test.describe.serial("message scroll characterization", () => {
let serverId: string
let coldChannelId: string
@@ -756,6 +775,97 @@ test.describe.serial("message scroll characterization", () => {
}
})
+ test("local history submission and passive remote append use distinct owners", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const channelId = await seedChannel("alice", serverId, `scroll-passive-threshold-${Date.now()}`)
+ await seedProfile(channelId, 130, false, "rotate", 18)
+ const alice = await asUser("alice")
+ await alice.page.setViewportSize(VIEWPORT)
+ const proxy = await proxyCommunityWebSockets(alice.context)
+ let composerPosts = 0
+ alice.page.on("request", request => {
+ if (request.method() === "POST" && new URL(request.url()).pathname === `/api/community/channels/${channelId}/messages`) composerPosts += 1
+ })
+ const anchorResponse = alice.page.waitForResponse(response => response.request().method() === "GET"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`
+ && new URL(response.url()).searchParams.has("anchor"))
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
+ const scroller = alice.page.getByTestId(tid.messageScroller)
+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
+ const anchored = await anchorResponse
+ expect(anchored.status()).toBe(200)
+ const anchorPage = await anchored.json() as { page: { hasMoreNewer: boolean } }
+ expect(anchorPage.page.hasMoreNewer).toBe(true)
+ let newestGets = 0
+ alice.page.on("request", request => {
+ const url = new URL(request.url())
+ if (request.method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages` && url.search === "") newestGets += 1
+ })
+ const newest = await holdNextRequest(alice.page, `**/api/community/channels/${channelId}/messages**`, url => url.search === "")
+ const localContent = `local history submission ${Date.now()}`
+ const localPost = alice.page.waitForResponse(response => response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`
+ && response.request().postDataJSON().content === localContent)
+ try {
+ await sendMessage(alice.page, localContent)
+ await newest.matched
+ newest.release()
+ const response = await localPost
+ expect(response.status()).toBe(201)
+ const nonce = response.request().postDataJSON().nonce as string
+ expect(nonce.length).toBeGreaterThan(0)
+ const result = await response.json() as { message: PostedMessageIdentity }
+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId, content: localContent })
+ await expect.poll(() => messageCreateCount(proxy.frames, channelId, localContent)).toBe(1)
+ await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)
+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()
+ await expect(alice.page.getByText(localContent, { exact: true })).toHaveCount(1)
+ await waitForStableTail(scroller, "local-history-submission-ack")
+ expect(newestGets).toBe(1)
+ expect(composerPosts).toBe(1)
+ } finally {
+ await newest.dispose()
+ }
+ for (const author of ["bob", "alice"] as const) {
+ for (const distance of [0, 1, 2, 20, 100, 101]) {
+ await establishScrollDistancePrecondition(scroller, `${author}-${distance}`, distance)
+ const before = await waitForCommittedGeometry(scroller)
+ expect(before.firstVisibleId).not.toBeNull()
+ expect(Math.abs(before.distanceToEnd - distance)).toBeLessThanOrEqual(0.01)
+ const nonce = `scroll186_${author}_${distance}_${Date.now()}`
+ const content = `passive ${author} at ${distance} ${nonce}`
+ const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {
+ method: "POST",
+ headers: { Cookie: sessionCookie(author), "Content-Type": "application/json", Origin: WEB_URL },
+ body: JSON.stringify({ content, nonce }),
+ })
+ expect(response.status).toBe(201)
+ const result = await response.json() as { message: PostedMessageIdentity }
+ expect(result.message).toMatchObject({ authorId: userId(author), channelId, content })
+ await expect.poll(() => proxy.frames.filter(frame => communityFrameEvents(frame).some(event =>
+ event.type === "community:message.create" && event.channelId === channelId && event.message?.id === result.message.id,
+ )).length).toBe(1)
+ await expectMessageCreateIdentity(proxy.frames, channelId, result.message, nonce)
+ if (distance <= 1) {
+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()
+ await waitForStableTail(scroller, `${author}-${distance}-received`)
+ } else {
+ await alice.page.waitForTimeout(250)
+ const bodyOffset = await scroller.locator(`[data-msg-id="${before.firstVisibleId}"]`).evaluate((element, scrollerTestId) => {
+ const root = element.closest<HTMLElement>(`[data-testid="${scrollerTestId}"]`)!
+ return element.getBoundingClientRect().top - root.getBoundingClientRect().top
+ }, tid.messageScroller)
+ expect(Math.abs(bodyOffset - before.firstVisibleOffset!)).toBeLessThanOrEqual(1)
+ const after = await waitForCommittedGeometry(scroller)
+ expect(Math.abs(after.scrollTop - before.scrollTop)).toBeLessThanOrEqual(1)
+ expect(after.distanceToEnd).toBeGreaterThan(distance)
+ }
+ expect(composerPosts).toBe(1)
+ }
+ }
+ expect(newestGets).toBe(1)
+ })
+
test("remote receive states and sustained upward input produce diagnostic traces", async ({ asUser }, testInfo) => {
test.setTimeout(180_000)
const alice = await asUser("alice")
@@ -1091,6 +1201,25 @@ test.describe.serial("message scroll characterization", () => {
expect(messagePosts).toBe(0)
expect(proxy.frames.flatMap(communityFrameEvents).filter((event) =>
event.type === "community:message.create" && event.channelId === composerDmId)).toHaveLength(0)
+
+ await establishScrollDistancePrecondition(scroller, "dm-local-submit-away", 300)
+ const content = `dm local acceptance ${Date.now()}`
+ const post = alice.page.waitForResponse(response => response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${composerDmId}/messages`
+ && response.request().postDataJSON().content === content)
+ await sendMessage(alice.page, content)
+ const response = await post
+ expect(response.status()).toBe(201)
+ const nonce = response.request().postDataJSON().nonce as string
+ expect(nonce.length).toBeGreaterThan(0)
+ const result = await response.json() as { message: PostedMessageIdentity }
+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: composerDmId, content })
+ await expect.poll(() => messageCreateCount(proxy.frames, composerDmId, content)).toBe(1)
+ await expectMessageCreateIdentity(proxy.frames, composerDmId, result.message, nonce)
+ await expect(alice.page.getByTestId(tid.message(result.message.id))).toBeVisible()
+ await expect(alice.page.getByText(content, { exact: true })).toHaveCount(1)
+ await waitForStableTail(scroller, "dm-local-submit-ack")
+ expect(messagePosts).toBe(1)
})
test("normal-flow composer resizes preserve semantic anchors and interaction boundaries", async ({ asUser }, testInfo) => {
@@ -1347,6 +1476,28 @@ test.describe.serial("message scroll characterization", () => {
expectInFlowMessageGeometry(parentGeometry, "split-parent")
expectInFlowMessageGeometry(threadGeometry, "split-thread")
expect(mutationPosts).toBe(0)
+
+ await parentEditable.fill("")
+ await threadEditable.fill("")
+ const parentBefore = await waitForCommittedGeometry(parentScroller)
+ const content = `thread local acceptance ${Date.now()}`
+ const post = alice.page.waitForResponse(response => response.request().method() === "POST"
+ && new URL(response.url()).pathname === `/api/community/channels/${splitThreadId}/messages`
+ && response.request().postDataJSON().content === content)
+ await sendMessage(alice.page, content, threadPanel)
+ const response = await post
+ expect(response.status()).toBe(201)
+ const nonce = response.request().postDataJSON().nonce as string
+ expect(nonce.length).toBeGreaterThan(0)
+ const result = await response.json() as { message: PostedMessageIdentity }
+ expect(result.message).toMatchObject({ authorId: userId("alice"), channelId: splitThreadId, content })
+ await expect.poll(() => messageCreateCount(proxy.frames, splitThreadId, content)).toBe(1)
+ await expectMessageCreateIdentity(proxy.frames, splitThreadId, result.message, nonce)
+ await expect(threadPanel.getByTestId(tid.message(result.message.id))).toBeVisible()
+ await expect(threadPanel.getByText(content, { exact: true })).toHaveCount(1)
+ await waitForStableTail(threadScroller, "thread-local-submit-ack")
+ const parentAfter = await waitForCommittedGeometry(parentScroller)
+ expectViewportAnchorPreserved(parentBefore, parentAfter, "thread-local-submit-parent")
})
test.afterEach(async ({ page }) => {
diff --git a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
index 603be9d8e..ccf0b7112 100644
--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
@@ -725,11 +725,17 @@ test.describe.serial("desktop default User Bar width", () => {
await expect(bob.page.getByTestId(tid.inboxFriendRequestAccept(friendRequestId))).toBeVisible()
await expect(bob.page.getByTestId(tid.inboxFriendRequestReject(friendRequestId))).toBeVisible()
} else {
+ const content = tab === "Mentions" ? `Mention ${stamp}` : `Marked ${stamp}`
await expect(activeBody).toContainText(
- tab === "Mentions" ? `Mention ${stamp}` : `Marked ${stamp}`,
+ content,
)
- await activeBody.getByRole("button").first().hover()
- await expect(activeBody.getByRole("button", { name: "More" })).toBeVisible()
+ const rowButton = activeBody.getByRole("button", { name: new RegExp(content) })
+ const row = rowButton.locator("..")
+ const more = row.getByRole("button", { name: "More", exact: true })
+ await expect(row).toHaveCount(1)
+ await expect(more).toHaveCount(1)
+ await row.hover()
+ await expect(more).toBeVisible()
}
const sample = await extension.evaluate((element, ids) => {
diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.ts
index ae8dc1132..00e769488 100644
--- a/src/web/src/test/message-scroll-fixture.ts
+++ b/src/web/src/test/message-scroll-fixture.ts
@@ -23,11 +23,18 @@ let resizeObservers: Array<{
}>
let scrollbarWidth: number
let scrollCalls: number[]
+let pendingScrollEvents: Set<HTMLElement>
let scrollDescriptor: PropertyDescriptor | undefined
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) }
+function deliverScrollEvents() {
+ for (const root of pendingScrollEvents) {
+ if (root.isConnected) root.dispatchEvent(new Event("scroll"))
+ }
+ pendingScrollEvents.clear()
+}
function rowGeometry(node: HTMLElement) {
const wrapper = node.matches('[data-index]') ? node : node.closest<HTMLElement>('[data-index]')
const root = rootFor(node)
@@ -101,9 +108,10 @@ export function runFrames(count = 26) {
const clamped = Math.max(0, Math.min(root.scrollTop, root.scrollHeight - root.clientHeight))
if (root.scrollTop !== clamped) {
root.scrollTop = clamped
- root.dispatchEvent(new Event("scroll"))
+ pendingScrollEvents.add(root)
}
}
+ deliverScrollEvents()
const pending = [...frames]
frames.clear()
for (const [, callback] of pending) callback(performance.now())
@@ -112,6 +120,7 @@ export function runFrames(count = 26) {
}
export function resize(frameCount = 26) {
act(() => {
+ deliverScrollEvents()
for (const observer of [...resizeObservers]) {
const entries: ResizeObserverEntry[] = []
for (const [target, observation] of observer.elements) {
@@ -170,6 +179,7 @@ export function installMessageScrollFixture() {
resizeObservers = []
scrollbarWidth = 0
scrollCalls = []
+ pendingScrollEvents = new Set()
vi.useFakeTimers()
vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => { frames.set(++frameId, callback); return frameId })
vi.spyOn(window, "cancelAnimationFrame").mockImplementation(id => { frames.delete(id) })
@@ -202,12 +212,14 @@ export function installMessageScrollFixture() {
})
scrollDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "scrollTo")
Object.defineProperty(HTMLElement.prototype, "scrollTo", { configurable: true, value(this: HTMLElement, options: ScrollToOptions) {
+ const previous = this.scrollTop
this.scrollTop = Math.max(0, Math.min(options.top ?? this.scrollTop, this.scrollHeight - this.clientHeight))
scrollCalls.push(this.scrollTop)
- this.dispatchEvent(new Event("scroll"))
+ if (this.scrollTop !== previous) pendingScrollEvents.add(this)
} })
}
export function restoreMessageScrollFixture() {
+ pendingScrollEvents.clear()
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.useRealTimers()