Skip to content
TypeScript

fix(web): screen readers can wrap to the first and last message of a long thread (#23780)

shivam6838e31b9c29
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 9323dfb5174..6ea5ea56562 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -15,7 +15,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
import "~/index.css";
-import { act, render } from "../../../test/render";
+import { act, fakeTimers, render } from "../../../test/render";
import { MessagesTimeline } from "./MessagesTimeline";
import { makeStreamingTimelineFixture } from "../../test-fixtures";
import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
@@ -201,6 +201,146 @@ describe("MessagesTimeline messages", () => {
expect(maxNestedCommits).toBeLessThan(20);
});
+ it("keeps the first and last message headings reachable from either end", async () => {
+ setup();
+ const props = baseProps();
+ // Folded messages at both ends: their headings must not live inside the fold.
+ const entries = Array.from({ length: 120 }, (_, index) =>
+ index === 0
+ ? message("First turn", { scheduledTaskId: TASK_ID }, "turn-0")
+ : index === 119
+ ? message(
+ "Last turn",
+ { createdBy: "agent", senderThreadId: ThreadId.make("thread-sender") },
+ "turn-119",
+ )
+ : message(
+ `Turn ${index}:\n\n${"x ".repeat(200)}`,
+ { role: index % 2 === 0 ? "user" : "assistant" },
+ `turn-${index}`,
+ ),
+ );
+ await using screen = await renderElement(
+ <MessagesTimeline {...props} timelineEntries={entries} />,
+ );
+ const headings = () => [...screen.container.querySelectorAll("h3")];
+ const headingFor = (text: string) =>
+ headings().find((heading) => heading.parentElement?.textContent?.includes(text));
+ const viewport = props.listRef.current!.getScrollableNode()!;
+ // A screen reader scrolls the heading it moves to into view.
+ const expectHeadingInView = async (text: string, neighbour: string) => {
+ await act(() => headingFor(text)!.scrollIntoView({ block: "start" }));
+ await vi.waitFor(() => expect(screen.text()).toContain(neighbour));
+ const row = headingFor(text)!.parentElement!.getBoundingClientRect();
+ const view = viewport.getBoundingClientRect();
+ expect(row.top).toBeLessThan(view.bottom);
+ expect(row.bottom).toBeGreaterThan(view.top);
+ };
+
+ await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:"));
+ expect(screen.text()).not.toContain("Turn 60:");
+ // Wrapping follows DOM order, so the ends must also sit first and last.
+ await vi.waitFor(() => {
+ expect(headings()[0]).toBe(headingFor("First turn"));
+ expect(headings().at(-1)).toBe(headingFor("Last turn"));
+ });
+
+ await expectHeadingInView("First turn", "Turn 1:");
+ expect(headingFor("Last turn")).toBeDefined();
+ await expectHeadingInView("Last turn", "Turn 118:");
+ });
+
+ it("keeps rows in item order after a reload or thread switch, before any timer runs", async () => {
+ setup();
+ // NVDA's browse mode keeps the first DOM order it reads, so a timer that sorts rows later is too late.
+ using _timers = fakeTimers();
+ const thread = (name: string) =>
+ Array.from({ length: 120 }, (_, index) =>
+ message(
+ `${name} turn ${index}:\n\n${"x ".repeat(200)}`,
+ { role: index % 2 === 0 ? "user" : "assistant" },
+ `${name}-${index}`,
+ ),
+ );
+ const props = baseProps();
+ await using screen = await renderElement(
+ <MessagesTimeline {...props} timelineEntries={thread("A")} />,
+ );
+ const turnsInDomOrder = () =>
+ [...screen.container.querySelectorAll("h3")].map((heading) =>
+ Number(/turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]),
+ );
+ const expectItemOrder = () => {
+ const turns = turnsInDomOrder();
+ expect(turns).toEqual(turns.toSorted((a, b) => a - b));
+ };
+
+ expect(screen.text()).toContain("A turn 118:");
+ expect(turnsInDomOrder()).toContain(0);
+ expectItemOrder();
+
+ await screen.rerender(
+ <MessagesTimeline
+ {...props}
+ routeThreadKey={`${props.routeThreadKey}-other`}
+ timelineEntries={thread("B")}
+ />,
+ );
+ expect(screen.text()).toContain("B turn 118:");
+ expect(screen.text()).not.toContain("A turn");
+ expectItemOrder();
+ });
+
+ it("puts rows back in item order soon after a continuous scroll stops", async () => {
+ setup();
+ const props = baseProps();
+ await using screen = await renderElement(
+ <MessagesTimeline
+ {...props}
+ timelineEntries={Array.from({ length: 120 }, (_, index) =>
+ message(
+ `Turn ${index}:\n\n${"x ".repeat(200)}`,
+ { role: index % 2 === 0 ? "user" : "assistant" },
+ `turn-${index}`,
+ ),
+ )}
+ />,
+ );
+ await vi.waitFor(() => expect(screen.text()).toContain("Turn 118:"));
+ using _timers = fakeTimers();
+ const turnsInDomOrder = () =>
+ [...screen.container.querySelectorAll("h3")].map((heading) =>
+ Number(/Turn (\d+):/.exec(heading.parentElement?.textContent ?? "")?.[1]),
+ );
+ const viewport = props.listRef.current!.getScrollableNode()!;
+
+ const scroll = async (by: number) => {
+ for (let step = 0; step < 40; step++) {
+ await act(() => {
+ viewport.scrollTop += by;
+ viewport.dispatchEvent(new Event("scroll"));
+ vi.advanceTimersByTime(16);
+ });
+ }
+ // Wrapping right after a scroll must still reach the first and last message.
+ expect(turnsInDomOrder()[0]).toBe(0);
+ expect(turnsInDomOrder().at(-1)).toBe(119);
+ };
+
+ await act(() => {
+ viewport.scrollTop = 0;
+ viewport.dispatchEvent(new Event("scroll"));
+ vi.advanceTimersByTime(300);
+ });
+ await scroll(300);
+ expect(turnsInDomOrder().filter((turn) => turn > 0 && turn < 100).length).toBeGreaterThan(0);
+ await scroll(-300);
+
+ await act(() => vi.advanceTimersByTime(300));
+ const turns = turnsInDomOrder();
+ expect(turns).toEqual(turns.toSorted((a, b) => a - b));
+ });
+
it("preserves XML-like tags and comparisons in user messages as text", async () => {
const source = [
'Without reading a file, do you have <global-agent-instructions scope="workspace">',
@@ -576,6 +716,8 @@ describe("MessagesTimeline attachments", () => {
const props = baseProps();
await using screen = await renderTimeline(
[
+ // The first message row is always mounted, so the recordings go in the second.
+ message("Start of the thread.", { role: "user" }, "opening"),
message(
"Two recordings.",
{
@@ -601,7 +743,7 @@ describe("MessagesTimeline attachments", () => {
await vi.waitFor(
async () => {
await act(() => {
- void props.listRef.current?.scrollToIndex({ index: 0, animated: false });
+ void props.listRef.current?.scrollToIndex({ index: 1, animated: false });
});
expect(screen.container.querySelectorAll("audio")).toHaveLength(2);
},
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index a8a81d66dd8..89715cc593c 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -743,7 +743,13 @@ const ConversationTimeline = memo(function ConversationTimeline({
setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
};
const alwaysRenderIndices = restoringAlwaysRender?.indices ?? [];
+ // Screen readers can only reach headings in the DOM. Keeping the first and
+ // last messages mounted lets heading navigation wrap to either end.
+ const firstMessageRow = rows.find(isMessageRow);
+ const lastMessageRow = rows.findLast(isMessageRow);
const alwaysRenderKeys = [
+ ...(firstMessageRow ? [firstMessageRow.id] : []),
+ ...(lastMessageRow && lastMessageRow !== firstMessageRow ? [lastMessageRow.id] : []),
...(citationAlwaysRender?.keys ?? []),
...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
...new Set(
@@ -1354,6 +1360,10 @@ function TimelineHistoryControl(props: MessagesTimelineHistoryControls) {
);
}
+function isMessageRow(row: MessagesTimelineRow) {
+ return row.kind === "message" && row.message.role !== "system";
+}
+
function keyExtractor(item: MessagesTimelineRow) {
return item.id;
}
diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
index 392311aacd4..203fb34d2db 100644
--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx
+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx
@@ -168,6 +168,7 @@ function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mess
expanded && "w-full",
)}
>
+ <MessageAuthorHeading>Automation</MessageAuthorHeading>
<FoldedMessageHeader
icon={CalendarClockIcon}
label="Automation"
@@ -311,6 +312,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
? { environmentId: ctx.activeThreadEnvironmentId, threadId: senderThreadId }
: null,
);
+ const senderLabel = senderShell?.title.trim() || "Agent";
const resolvedContext = resolveUserMessageContext(
userMessage.attribution === "guest" ? { ...row.message, text: userMessage.text } : row.message,
);
@@ -457,10 +459,18 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
folded && expanded && "w-full",
)}
>
+ {/* Outside the fold so a collapsed message still has a heading to navigate to. */}
+ <MessageAuthorHeading>
+ {folded
+ ? senderLabel
+ : userMessage.guestName === undefined
+ ? "You"
+ : `${userMessage.guestName} (guest)`}
+ </MessageAuthorHeading>
{folded ? (
<FoldedMessageHeader
icon={MessagesSquareIcon}
- label={senderShell?.title.trim() || "Agent"}
+ label={senderLabel}
summary={foldSummary}
expanded={expanded}
onToggle={() => setExpanded((value) => !value)}
@@ -476,9 +486,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
folded && !ctx.findActive && "max-h-96 overflow-auto",
)}
>
- <MessageAuthorHeading>
- {userMessage.guestName === undefined ? "You" : `${userMessage.guestName} (guest)`}
- </MessageAuthorHeading>
{(regularImages.length > 0 || userVideos.length > 0) && (
<div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
{regularImages.map((image) => (
diff --git a/patches/@[email protected] b/patches/@[email protected]
index 58f642e725e..42572476c6c 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1619,10 +1619,102 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..d7cbe1cb43449cc29822b2646deabbdd
}
}
diff --git a/react.js b/react.js
-index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c0430059a 100644
+index 914d2dafaafa001c9ab6791a0a0581659295e333..8c320b0dfb3ea60ef145274b37b1297b7dee26dc 100644
--- a/react.js
+++ b/react.js
-@@ -4702,7 +4702,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
+@@ -1908,6 +1908,10 @@ function updateScroll(ctx, newScroll, forceUpdate, options) {
+ state.scrollTime = currentTime;
+ const scrollDelta = Math.abs(newScroll - prevScroll);
+ const isUserScrollEvent = !!(options == null ? void 0 : options.fromNativeScrollEvent) && scrollDelta > 0.1 && !adjustChanged && scrollingTo === void 0 && !state.pendingNativeMVCPAdjust;
++ if (isUserScrollEvent) {
++ state.userScrollPrevTime = state.userScrollTime;
++ state.userScrollTime = currentTime;
++ }
+ const allowedEdge = isUserScrollEvent ? beginReachedEdgeUserScroll(ctx, newScroll - prevScroll) : void 0;
+ const didResolvePendingNativeMVCPAdjust = resolvePendingNativeMVCPAdjust(ctx, newScroll);
+ const scrollLength = state.scrollLength;
+@@ -3257,6 +3261,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ const itemKey = (_a3 = state.idCache[itemIndex]) != null ? _a3 : getId(state, itemIndex);
+ const updateLayout = (_b = options == null ? void 0 : options.updateLayout) != null ? _b : true;
+ let didChangePosition = false;
++ let didChangeIndex = false;
+ let didRefreshData = false;
+ if (updateLayout) {
+ const positionValue = positions[itemIndex];
+@@ -3286,6 +3291,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ const prevIndex = peek$(ctx, `containerItemIndex${containerIndex}`);
+ if (prevIndex !== itemIndex) {
+ set$(ctx, `containerItemIndex${containerIndex}`, itemIndex);
++ didChangeIndex = true;
+ }
+ const prevData = peek$(ctx, `containerItemData${containerIndex}`);
+ const updateData = () => {
+@@ -3324,7 +3330,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ }
+ }
+ }
+- return { didChangePosition, didRefreshData };
++ return { didChangeIndex, didChangePosition, didRefreshData };
+ }
+
+ // src/core/prepareColumnStartState.ts
+@@ -3542,7 +3548,11 @@ function updateItemPositions(ctx, dataChanged, {
+ }
+ if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
+ const itemsPerRow = hasColumns ? numColumns : 1;
+- breakAt = i + itemsPerRow + 10;
++ // alwaysRender rows stay mounted outside the visible window, so keep their
++ // positions current instead of leaving them where they were last laid out.
++ const pinnedIndices = state.props.alwaysRenderIndicesArr;
++ const lastPinnedIndex = pinnedIndices && pinnedIndices.length > 0 ? pinnedIndices[pinnedIndices.length - 1] : -1;
++ breakAt = Math.max(i + itemsPerRow + 10, lastPinnedIndex);
+ }
+ const id = (_e = idCache[i]) != null ? _e : getId(state, i);
+ let span = 1;
+@@ -4243,6 +4253,7 @@ function calculateItemsInView(ctx, params = {}) {
+ }
+ let totalSize = getContentSize(ctx);
+ let changedContainerIds;
++ let didChangeContainerOrder = false;
+ const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "alignItemsAtEndPadding") + peek$(ctx, "headerSize");
+ const numColumns = peek$(ctx, "numColumns");
+ const speed = (_b = params.scrollVelocity) != null ? _b : getScrollVelocity(state);
+@@ -4545,6 +4556,9 @@ function calculateItemsInView(ctx, params = {}) {
+ const containerIndex = allocation.containerIndex;
+ const id = (_o = idCache[i]) != null ? _o : getId(state, i);
+ const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
++ if (oldKey !== id || peek$(ctx, `containerItemIndex${containerIndex}`) !== i) {
++ didChangeContainerOrder = true;
++ }
+ if (oldKey && oldKey !== id) {
+ containerItemKeys.delete(oldKey);
+ }
+@@ -4629,10 +4643,12 @@ function calculateItemsInView(ctx, params = {}) {
+ } else {
+ const itemIndex = indexByKey.get(itemKey);
+ if (itemIndex !== void 0) {
+- didChangePositions = syncMountedContainer(ctx, i, itemIndex, {
++ const synced = syncMountedContainer(ctx, i, itemIndex, {
+ scrollAdjustPending,
+ updateLayout: true
+- }).didChangePosition || didChangePositions;
++ });
++ didChangePositions = synced.didChangePosition || didChangePositions;
++ didChangeContainerOrder = synced.didChangeIndex || didChangeContainerOrder;
+ }
+ }
+ }
+@@ -4642,6 +4658,9 @@ function calculateItemsInView(ctx, params = {}) {
+ if (didChangePositions) {
+ set$(ctx, "lastPositionUpdate", Date.now());
+ }
++ if (didChangeContainerOrder) {
++ set$(ctx, "containerOrderUpdate", (peek$(ctx, "containerOrderUpdate") || 0) + 1);
++ }
+ if (suppressInitialScrollSideEffects) {
+ evaluateBootstrapInitialScroll(ctx);
+ return;
+@@ -4702,7 +4721,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
isReady = !hasUnknownTailSize;
@@ -1632,7 +1724,7 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
} else if (anchorIndex >= 0) {
isReady = false;
}
-@@ -4722,6 +4723,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
+@@ -4722,6 +4742,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
}
(_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
@@ -1645,7 +1737,7 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
}
return nextSize;
}
-@@ -4956,7 +4963,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
+@@ -4956,7 +4982,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
const itemKey = peek$(ctx, `containerItemKey${containerId}`);
const element = viewRef == null ? void 0 : viewRef.current;
if (itemKey !== void 0 && element) {
@@ -1655,7 +1747,7 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
setContainerLayoutBaseline(element, rect);
measurements.push({
containerId,
-@@ -4978,12 +4986,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
+@@ -4978,12 +5005,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
}) {
const ctx = useStateContext();
const [containerLayoutEpoch] = useArr$(["containerLayoutEpoch"]);
@@ -1687,7 +1779,7 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
}
}, [ctx, containerLayoutEpoch]);
return children;
-@@ -5651,6 +5673,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
+@@ -5651,6 +5692,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
});
// src/utils/reordering.ts
@@ -1706,7 +1798,7 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
function sortDOMElements(container, indexByElement) {
const elements = Array.from(container.children);
if (elements.length <= 1) return elements;
-@@ -5690,9 +5724,9 @@ function sortDOMElements(container, indexByElement) {
+@@ -5690,9 +5743,9 @@ function sortDOMElements(container, indexByElement) {
}
}
if (nextStableElement) {
@@ -1718,7 +1810,89 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
}
}
}
-@@ -6446,8 +6480,8 @@ function ScrollAdjust() {
+@@ -5734,37 +5787,55 @@ function findLIS(arr) {
+ }
+
+ // src/hooks/useDOMOrder.ts
++var DOM_ORDER_SETTLE_MS = 150;
++function isUserScrolling(state) {
++ const { userScrollPrevTime, userScrollTime } = state;
++ return userScrollTime !== void 0 && userScrollPrevTime !== void 0 && userScrollTime - userScrollPrevTime < DOM_ORDER_SETTLE_MS && Date.now() - userScrollTime < DOM_ORDER_SETTLE_MS;
++}
+ function useDOMOrder(ref) {
+ const ctx = useStateContext();
+- const debounceRef = React3.useRef(void 0);
+- React3.useEffect(() => {
+- const unsubscribe = listen$(ctx, "lastPositionUpdate", () => {
+- if (debounceRef.current !== void 0) {
+- clearTimeout(debounceRef.current);
+- }
+- debounceRef.current = setTimeout(() => {
+- const parent = ref.current;
+- if (parent) {
+- const indexByElement = /* @__PURE__ */ new Map();
+- for (const [containerId, viewRef] of ctx.viewRefs) {
+- const element = viewRef.current;
+- const index = peek$(ctx, `containerItemIndex${containerId}`);
+- if (element && index !== void 0) {
+- indexByElement.set(element, index);
+- }
+- }
+- sortDOMElements(parent, indexByElement);
++ const [containerOrderUpdate] = useArr$(["containerOrderUpdate"]);
++ const settleRef = React3.useRef(void 0);
++ React3.useLayoutEffect(() => {
++ const sort = () => {
++ settleRef.current = void 0;
++ const parent = ref.current;
++ if (!parent) {
++ return;
++ }
++ const indexByElement = /* @__PURE__ */ new Map();
++ for (const [containerId, viewRef] of ctx.viewRefs) {
++ const element = viewRef.current;
++ const index = peek$(ctx, `containerItemIndex${containerId}`);
++ if (element && index !== void 0) {
++ indexByElement.set(element, index);
+ }
+- debounceRef.current = void 0;
+- }, 500);
+- });
+- return () => {
+- unsubscribe();
+- if (debounceRef.current !== void 0) {
+- clearTimeout(debounceRef.current);
+ }
++ sortDOMElements(parent, indexByElement);
+ };
+- }, [ctx]);
++ if (settleRef.current !== void 0) {
++ clearTimeout(settleRef.current);
++ }
++ // Before paint: NVDA's browse mode keeps the first DOM order it reads. Each move
++ // lays its row out again, so during a continuous scroll, sort once it settles.
++ if (!isUserScrolling(ctx.state)) {
++ sort();
++ return;
++ }
++ const settle = () => {
++ if (isUserScrolling(ctx.state)) {
++ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
++ } else {
++ sort();
++ }
++ };
++ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
++ }, [ctx, containerOrderUpdate]);
++ React3.useEffect(() => () => {
++ if (settleRef.current !== void 0) {
++ clearTimeout(settleRef.current);
++ }
++ }, []);
+ }
+ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
+ const [completedTransitionEpoch, setCompletedTransitionEpoch] = React3.useState(transitionEpoch);
+@@ -6446,8 +6517,8 @@ function ScrollAdjust() {
window.getComputedStyle(contentNode)[axis.paddingEndProp]
);
const temporaryPaddingEnd = `${(currentPaddingEnd || 0) + pad}px`;
@@ -1729,10 +1903,102 @@ index 914d2dafaafa001c9ab6791a0a0581659295e333..199aae77b3620b7c4bb2ecd96b82978c
scrollBy();
if (resetPaddingRafRef.current !== void 0) {
diff --git a/react.mjs b/react.mjs
-index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e2e456cfc 100644
+index 95465f2ab89ce41a10553f58af83618f7310e83c..252a9d5b23e271c089d30c357a78dff754f1c899 100644
--- a/react.mjs
+++ b/react.mjs
-@@ -4681,7 +4681,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
+@@ -1887,6 +1887,10 @@ function updateScroll(ctx, newScroll, forceUpdate, options) {
+ state.scrollTime = currentTime;
+ const scrollDelta = Math.abs(newScroll - prevScroll);
+ const isUserScrollEvent = !!(options == null ? void 0 : options.fromNativeScrollEvent) && scrollDelta > 0.1 && !adjustChanged && scrollingTo === void 0 && !state.pendingNativeMVCPAdjust;
++ if (isUserScrollEvent) {
++ state.userScrollPrevTime = state.userScrollTime;
++ state.userScrollTime = currentTime;
++ }
+ const allowedEdge = isUserScrollEvent ? beginReachedEdgeUserScroll(ctx, newScroll - prevScroll) : void 0;
+ const didResolvePendingNativeMVCPAdjust = resolvePendingNativeMVCPAdjust(ctx, newScroll);
+ const scrollLength = state.scrollLength;
+@@ -3236,6 +3240,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ const itemKey = (_a3 = state.idCache[itemIndex]) != null ? _a3 : getId(state, itemIndex);
+ const updateLayout = (_b = options == null ? void 0 : options.updateLayout) != null ? _b : true;
+ let didChangePosition = false;
++ let didChangeIndex = false;
+ let didRefreshData = false;
+ if (updateLayout) {
+ const positionValue = positions[itemIndex];
+@@ -3265,6 +3270,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ const prevIndex = peek$(ctx, `containerItemIndex${containerIndex}`);
+ if (prevIndex !== itemIndex) {
+ set$(ctx, `containerItemIndex${containerIndex}`, itemIndex);
++ didChangeIndex = true;
+ }
+ const prevData = peek$(ctx, `containerItemData${containerIndex}`);
+ const updateData = () => {
+@@ -3303,7 +3309,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
+ }
+ }
+ }
+- return { didChangePosition, didRefreshData };
++ return { didChangeIndex, didChangePosition, didRefreshData };
+ }
+
+ // src/core/prepareColumnStartState.ts
+@@ -3521,7 +3527,11 @@ function updateItemPositions(ctx, dataChanged, {
+ }
+ if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
+ const itemsPerRow = hasColumns ? numColumns : 1;
+- breakAt = i + itemsPerRow + 10;
++ // alwaysRender rows stay mounted outside the visible window, so keep their
++ // positions current instead of leaving them where they were last laid out.
++ const pinnedIndices = state.props.alwaysRenderIndicesArr;
++ const lastPinnedIndex = pinnedIndices && pinnedIndices.length > 0 ? pinnedIndices[pinnedIndices.length - 1] : -1;
++ breakAt = Math.max(i + itemsPerRow + 10, lastPinnedIndex);
+ }
+ const id = (_e = idCache[i]) != null ? _e : getId(state, i);
+ let span = 1;
+@@ -4222,6 +4232,7 @@ function calculateItemsInView(ctx, params = {}) {
+ }
+ let totalSize = getContentSize(ctx);
+ let changedContainerIds;
++ let didChangeContainerOrder = false;
+ const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "alignItemsAtEndPadding") + peek$(ctx, "headerSize");
+ const numColumns = peek$(ctx, "numColumns");
+ const speed = (_b = params.scrollVelocity) != null ? _b : getScrollVelocity(state);
+@@ -4524,6 +4535,9 @@ function calculateItemsInView(ctx, params = {}) {
+ const containerIndex = allocation.containerIndex;
+ const id = (_o = idCache[i]) != null ? _o : getId(state, i);
+ const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
++ if (oldKey !== id || peek$(ctx, `containerItemIndex${containerIndex}`) !== i) {
++ didChangeContainerOrder = true;
++ }
+ if (oldKey && oldKey !== id) {
+ containerItemKeys.delete(oldKey);
+ }
+@@ -4608,10 +4622,12 @@ function calculateItemsInView(ctx, params = {}) {
+ } else {
+ const itemIndex = indexByKey.get(itemKey);
+ if (itemIndex !== void 0) {
+- didChangePositions = syncMountedContainer(ctx, i, itemIndex, {
++ const synced = syncMountedContainer(ctx, i, itemIndex, {
+ scrollAdjustPending,
+ updateLayout: true
+- }).didChangePosition || didChangePositions;
++ });
++ didChangePositions = synced.didChangePosition || didChangePositions;
++ didChangeContainerOrder = synced.didChangeIndex || didChangeContainerOrder;
+ }
+ }
+ }
+@@ -4621,6 +4637,9 @@ function calculateItemsInView(ctx, params = {}) {
+ if (didChangePositions) {
+ set$(ctx, "lastPositionUpdate", Date.now());
+ }
++ if (didChangeContainerOrder) {
++ set$(ctx, "containerOrderUpdate", (peek$(ctx, "containerOrderUpdate") || 0) + 1);
++ }
+ if (suppressInitialScrollSideEffects) {
+ evaluateBootstrapInitialScroll(ctx);
+ return;
+@@ -4681,7 +4700,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
isReady = !hasUnknownTailSize;
@@ -1742,7 +2008,7 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
} else if (anchorIndex >= 0) {
isReady = false;
}
-@@ -4701,6 +4702,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
+@@ -4701,6 +4721,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
}
(_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
@@ -1755,7 +2021,7 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
}
return nextSize;
}
-@@ -4935,7 +4942,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
+@@ -4935,7 +4961,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
const itemKey = peek$(ctx, `containerItemKey${containerId}`);
const element = viewRef == null ? void 0 : viewRef.current;
if (itemKey !== void 0 && element) {
@@ -1765,7 +2031,7 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
setContainerLayoutBaseline(element, rect);
measurements.push({
containerId,
-@@ -4957,12 +4965,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
+@@ -4957,12 +4984,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
}) {
const ctx = useStateContext();
const [containerLayoutEpoch] = useArr$(["containerLayoutEpoch"]);
@@ -1797,7 +2063,7 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
}
}, [ctx, containerLayoutEpoch]);
return children;
-@@ -5630,6 +5652,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
+@@ -5630,6 +5671,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
});
// src/utils/reordering.ts
@@ -1816,7 +2082,7 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
function sortDOMElements(container, indexByElement) {
const elements = Array.from(container.children);
if (elements.length <= 1) return elements;
-@@ -5669,9 +5703,9 @@ function sortDOMElements(container, indexByElement) {
+@@ -5669,9 +5722,9 @@ function sortDOMElements(container, indexByElement) {
}
}
if (nextStableElement) {
@@ -1828,7 +2094,89 @@ index 95465f2ab89ce41a10553f58af83618f7310e83c..a123bd3e9df510100d44dfae1f59b87e
}
}
}
-@@ -6425,8 +6459,8 @@ function ScrollAdjust() {
+@@ -5713,37 +5766,55 @@ function findLIS(arr) {
+ }
+
+ // src/hooks/useDOMOrder.ts
++var DOM_ORDER_SETTLE_MS = 150;
++function isUserScrolling(state) {
++ const { userScrollPrevTime, userScrollTime } = state;
++ return userScrollTime !== void 0 && userScrollPrevTime !== void 0 && userScrollTime - userScrollPrevTime < DOM_ORDER_SETTLE_MS && Date.now() - userScrollTime < DOM_ORDER_SETTLE_MS;
++}
+ function useDOMOrder(ref) {
+ const ctx = useStateContext();
+- const debounceRef = useRef(void 0);
+- useEffect(() => {
+- const unsubscribe = listen$(ctx, "lastPositionUpdate", () => {
+- if (debounceRef.current !== void 0) {
+- clearTimeout(debounceRef.current);
+- }
+- debounceRef.current = setTimeout(() => {
+- const parent = ref.current;
+- if (parent) {
+- const indexByElement = /* @__PURE__ */ new Map();
+- for (const [containerId, viewRef] of ctx.viewRefs) {
+- const element = viewRef.current;
+- const index = peek$(ctx, `containerItemIndex${containerId}`);
+- if (element && index !== void 0) {
+- indexByElement.set(element, index);
+- }
+- }
+- sortDOMElements(parent, indexByElement);
++ const [containerOrderUpdate] = useArr$(["containerOrderUpdate"]);
++ const settleRef = useRef(void 0);
++ useLayoutEffect(() => {
++ const sort = () => {
++ settleRef.current = void 0;
++ const parent = ref.current;
++ if (!parent) {
++ return;
++ }
++ const indexByElement = /* @__PURE__ */ new Map();
++ for (const [containerId, viewRef] of ctx.viewRefs) {
++ const element = viewRef.current;
++ const index = peek$(ctx, `containerItemIndex${containerId}`);
++ if (element && index !== void 0) {
++ indexByElement.set(element, index);
+ }
+- debounceRef.current = void 0;
+- }, 500);
+- });
+- return () => {
+- unsubscribe();
+- if (debounceRef.current !== void 0) {
+- clearTimeout(debounceRef.current);
+ }
++ sortDOMElements(parent, indexByElement);
+ };
+- }, [ctx]);
++ if (settleRef.current !== void 0) {
++ clearTimeout(settleRef.current);
++ }
++ // Before paint: NVDA's browse mode keeps the first DOM order it reads. Each move
++ // lays its row out again, so during a continuous scroll, sort once it settles.
++ if (!isUserScrolling(ctx.state)) {
++ sort();
++ return;
++ }
++ const settle = () => {
++ if (isUserScrolling(ctx.state)) {
++ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
++ } else {
++ sort();
++ }
++ };
++ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
++ }, [ctx, containerOrderUpdate]);
++ useEffect(() => () => {
++ if (settleRef.current !== void 0) {
++ clearTimeout(settleRef.current);
++ }
++ }, []);
+ }
+ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
+ const [completedTransitionEpoch, setCompletedTransitionEpoch] = useState(transitionEpoch);
+@@ -6425,8 +6496,8 @@ function ScrollAdjust() {
window.getComputedStyle(contentNode)[axis.paddingEndProp]
);
const temporaryPaddingEnd = `${(currentPaddingEnd || 0) + pad}px`;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 80fb20106b3..b8751435402 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -352,7 +352,7 @@ patchedDependencies:
'@expo/[email protected]': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760
'@expo/[email protected]': 5a26480373850c1a7943919aa21f904151b335a0cb01042109e0746def37923e
'@ff-labs/[email protected]': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c
- '@legendapp/[email protected]': 011a862a7116ec5b5f4bba17d37bc58c9b5a8f64a6a9f527345f316ce9c96e63
+ '@legendapp/[email protected]': 6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896
'@muse-code/[email protected]': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101
'@pierre/[email protected]': 4645364ddf113e48e8827f3b4966b3b1ff745317011e5a3d904e2d8672dee7dc
'@react-native-ai/[email protected]': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
@@ -530,7 +530,7 @@ importers:
'@legendapp/list':
specifier: 3.3.5
'@material/material-color-utilities':
specifier: 0.3.0
version: 0.3.0
@@ -1039,7 +1039,7 @@ importers:
version: 0.9.0
'@legendapp/list':
specifier: 3.3.5
'@noble/hashes':
specifier: 'catalog:'
version: 1.8.0
@@ -14766,7 +14766,7 @@ snapshots:
dependencies:
jsbi: 4.3.2
dependencies:
react: 19.3.0
use-sync-external-store: 1.6.0([email protected])