diff --git a/cspell.json b/cspell.json index ac25b59fc7cd..ad8b7670510b 100644 --- a/cspell.json +++ b/cspell.json @@ -648,6 +648,7 @@ "RPID", "RRGGBB", "rstrip", + "recyclerview", "RTER", "s3uqn2oe4m85tufi6mqflbfbuajrm2i3", "SAASPASS", diff --git a/jest/setup.ts b/jest/setup.ts index 9255404f5d68..aef83f583b3a 100644 --- a/jest/setup.ts +++ b/jest/setup.ts @@ -262,7 +262,7 @@ jest.mock('../src/components/Icon/IllustrationLoader.ts', () => ({ })); jest.mock( - '@components/FlatList/InvertedFlatList/RenderTaskQueue', + '@components/FlatList/RenderTaskQueue', () => class SyncRenderTaskQueue { private handler: (info: unknown) => void = () => {}; diff --git a/jest/setupAfterEnv.ts b/jest/setupAfterEnv.ts index c9ef9afc5d98..c074877a3f02 100644 --- a/jest/setupAfterEnv.ts +++ b/jest/setupAfterEnv.ts @@ -4,6 +4,35 @@ import ONYXKEYS from '@src/ONYXKEYS'; jest.useRealTimers(); +// This mock must live in setupAfterEnv (not setupFiles) because @shopify/flash-list/jestSetup, +// imported in setup.ts, registers its own measureLayout mock. Placing ours here ensures it +// runs after FlashList's setup and takes precedence. +jest.mock( + '@shopify/flash-list/dist/recyclerview/utils/measureLayout', + () => + ({ + ...jest.requireActual('@shopify/flash-list/dist/recyclerview/utils/measureLayout'), + measureParentSize: jest.fn().mockImplementation(() => ({ + x: 0, + y: 0, + width: 300, + height: 400, + })), + measureFirstChildLayout: jest.fn().mockImplementation(() => ({ + x: 0, + y: 0, + width: 300, + height: 400, + })), + measureItemLayout: jest.fn().mockImplementation(() => ({ + x: 0, + y: 0, + width: 300, + height: 75, + })), + }) as Record, +); + // Auto-initialize Onyx for tests. // Tests that already call Onyx.init() in their own beforeAll will safely re-configure Onyx — // the second init() just re-runs initStoreValues and re-resolves the already-resolved deferred task. diff --git a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+001+fix-horizontal-height-normalization.patch b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+001+fix-horizontal-height-normalization.patch index 007d0682e1cc..e9d9e3dfd981 100644 --- a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+001+fix-horizontal-height-normalization.patch +++ b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+001+fix-horizontal-height-normalization.patch @@ -1,5 +1,5 @@ diff --git a/node_modules/@shopify/flash-list/dist/recyclerview/layout-managers/LinearLayoutManager.js b/node_modules/@shopify/flash-list/dist/recyclerview/layout-managers/LinearLayoutManager.js -index fb40ded..ea4eba2 100644 +index fb40ded..12375d9 100644 --- a/node_modules/@shopify/flash-list/dist/recyclerview/layout-managers/LinearLayoutManager.js +++ b/node_modules/@shopify/flash-list/dist/recyclerview/layout-managers/LinearLayoutManager.js @@ -92,6 +92,17 @@ export class RVLinearLayoutManagerImpl extends RVLayoutManager { diff --git a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+003+fix-inverted-scroll-direction-on-web.patch b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+003+fix-inverted-scroll-direction-on-web.patch new file mode 100644 index 000000000000..edb436a356b4 --- /dev/null +++ b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+003+fix-inverted-scroll-direction-on-web.patch @@ -0,0 +1,191 @@ +diff --git a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +index dd2d3bc..d7a3d84 100644 +--- a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js ++++ b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +@@ -2,8 +2,8 @@ + * RecyclerView is a high-performance list component that efficiently renders and recycles list items. + * It's designed to handle large lists with optimal memory usage and smooth scrolling. + */ +-import React, { useCallback, useLayoutEffect, useMemo, useRef, forwardRef, useState, useId, } from "react"; +-import { Animated, I18nManager, } from "react-native"; ++import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, forwardRef, useState, useId, } from "react"; ++import { Animated, I18nManager, Platform, } from "react-native"; + import { ErrorMessages } from "../errors/ErrorMessages"; + import { WarningMessages } from "../errors/WarningMessages"; + import { areDimensionsNotEqual, measureFirstChildLayout, measureItemLayout, measureParentSize, } from "./utils/measureLayout"; +@@ -66,6 +66,66 @@ const RecyclerViewComponent = (props, ref) => { + // Hook to detect when scrolling reaches list bounds + const { checkBounds } = useBoundDetection(recyclerViewManager, scrollViewRef); + const isHorizontalRTL = I18nManager.isRTL && horizontal; ++ // Web-only: Fix inverted scroll direction. ++ useEffect(() => { ++ if (!inverted || Platform.OS !== "web") { ++ return; ++ } ++ const scrollRef = scrollViewRef.current; ++ if (!scrollRef || typeof scrollRef.getScrollableNode !== "function") { ++ return; ++ } ++ const node = scrollRef.getScrollableNode(); ++ if (!node) { ++ return; ++ } ++ const wheelHandler = (ev) => { ++ const target = ev.target; ++ const deltaX = ev.deltaX || ev.wheelDeltaX || 0; ++ const deltaY = ev.deltaY || ev.wheelDeltaY || 0; ++ // Compute scroll limits from the DOM node for overscroll recoil prevention. ++ const nodeScrollOffset = horizontal ? node.scrollLeft : node.scrollTop; ++ const nodeScrollLength = horizontal ? node.scrollWidth : node.scrollHeight; ++ const nodeClientLength = horizontal ? node.clientWidth : node.clientHeight; ++ const isOnScrollLimit = nodeScrollOffset <= 0 || Math.ceil(nodeScrollOffset) >= nodeScrollLength - nodeClientLength; ++ const scrollOffset = horizontal ? target.scrollLeft : target.scrollTop; ++ const scrollLength = horizontal ? target.scrollWidth : target.scrollHeight; ++ const clientLength = horizontal ? target.clientWidth : target.clientHeight; ++ const isEventTargetScrollable = scrollLength > clientLength; ++ const delta = horizontal ? deltaX : deltaY; ++ let leftoverDelta = delta; ++ if (isEventTargetScrollable) { ++ leftoverDelta = delta < 0 ++ ? Math.min(delta + scrollOffset, 0) ++ : Math.max(delta - (scrollLength - clientLength - scrollOffset), 0); ++ } ++ const targetDelta = delta - leftoverDelta; ++ if (horizontal) { ++ if (Math.abs(deltaX) > Math.abs(deltaY)) { ++ target.scrollLeft += targetDelta; ++ node.scrollLeft = node.scrollLeft - leftoverDelta; ++ ev.preventDefault(); ++ ev.stopPropagation(); ++ } ++ } ++ else { ++ // Prevent overscroll recoil/rubber band at scroll boundaries. ++ if (isOnScrollLimit && Math.abs(deltaY) > 0) { ++ ev.preventDefault(); ++ } ++ if (Math.abs(deltaY) > Math.abs(deltaX)) { ++ target.scrollTop += targetDelta; ++ node.scrollTop = node.scrollTop - leftoverDelta; ++ ev.preventDefault(); ++ ev.stopPropagation(); ++ } ++ } ++ }; ++ node.addEventListener("wheel", wheelHandler, { passive: false }); ++ return () => { ++ node.removeEventListener("wheel", wheelHandler); ++ }; ++ }, [inverted, horizontal]); + /** + * Initialize the RecyclerView by measuring and setting up the window size + * This effect runs when the component mounts or when layout changes +diff --git a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +index 34722d4..ea801d2 100644 +--- a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx ++++ b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +@@ -5,6 +5,7 @@ + import React, { + RefObject, + useCallback, ++ useEffect, + useLayoutEffect, + useMemo, + useRef, +@@ -17,6 +18,7 @@ import { + I18nManager, + NativeScrollEvent, + NativeSyntheticEvent, ++ Platform, + } from "react-native"; + + import { FlashListRef } from "../FlashListRef"; +@@ -158,6 +160,88 @@ const RecyclerViewComponent = ( + + const isHorizontalRTL = I18nManager.isRTL && horizontal; + ++ /** ++ * Web-only: Fix inverted scroll direction. ++ * When a list is visually inverted via scaleY/scaleX: -1, the browser's native ++ * wheel scroll goes in the wrong visual direction. This effect attaches a wheel ++ * event listener that negates the delta to correct the scroll direction. ++ * Mirrors the fix in react-native-web's VirtualizedList. ++ */ ++ useEffect(() => { ++ if (!inverted || Platform.OS !== "web") { ++ return; ++ } ++ const scrollRef = scrollViewRef.current; ++ if (!scrollRef || typeof (scrollRef as any).getScrollableNode !== "function") { ++ return; ++ } ++ const node = (scrollRef as any).getScrollableNode() as HTMLElement; ++ if (!node) { ++ return; ++ } ++ ++ const wheelHandler = (ev: WheelEvent) => { ++ const target = ev.target as HTMLElement; ++ const deltaX = ev.deltaX || (ev as any).wheelDeltaX || 0; ++ const deltaY = ev.deltaY || (ev as any).wheelDeltaY || 0; ++ ++ // Compute scroll limits from the DOM node for overscroll recoil prevention. ++ const nodeScrollOffset = horizontal ? node.scrollLeft : node.scrollTop; ++ const nodeScrollLength = horizontal ? node.scrollWidth : node.scrollHeight; ++ const nodeClientLength = horizontal ? node.clientWidth : node.clientHeight; ++ const isOnScrollLimit = ++ nodeScrollOffset <= 0 || ++ Math.ceil(nodeScrollOffset) >= nodeScrollLength - nodeClientLength; ++ ++ const scrollOffset = horizontal ? target.scrollLeft : target.scrollTop; ++ const scrollLength = horizontal ? target.scrollWidth : target.scrollHeight; ++ const clientLength = horizontal ? target.clientWidth : target.clientHeight; ++ const isEventTargetScrollable = scrollLength > clientLength; ++ const delta = horizontal ? deltaX : deltaY; ++ ++ // Calculate how much delta the event target can consume vs leftover for parent ++ let leftoverDelta = delta; ++ if (isEventTargetScrollable) { ++ leftoverDelta = ++ delta < 0 ++ ? Math.min(delta + scrollOffset, 0) ++ : Math.max( ++ delta - (scrollLength - clientLength - scrollOffset), ++ 0 ++ ); ++ } ++ const targetDelta = delta - leftoverDelta; ++ ++ // Only adjust scroll and consume the event when the dominant axis ++ // matches the list orientation. stopPropagation prevents parent ++ // inverted lists from also handling this event. ++ if (horizontal) { ++ if (Math.abs(deltaX) > Math.abs(deltaY)) { ++ target.scrollLeft += targetDelta; ++ node.scrollLeft = node.scrollLeft - leftoverDelta; ++ ev.preventDefault(); ++ ev.stopPropagation(); ++ } ++ } else { ++ // Prevent overscroll recoil/rubber band at scroll boundaries. ++ if (isOnScrollLimit && Math.abs(deltaY) > 0) { ++ ev.preventDefault(); ++ } ++ if (Math.abs(deltaY) > Math.abs(deltaX)) { ++ target.scrollTop += targetDelta; ++ node.scrollTop = node.scrollTop - leftoverDelta; ++ ev.preventDefault(); ++ ev.stopPropagation(); ++ } ++ } ++ }; ++ ++ node.addEventListener("wheel", wheelHandler, { passive: false }); ++ return () => { ++ node.removeEventListener("wheel", wheelHandler); ++ }; ++ }, [inverted, horizontal]); ++ + /** + * Initialize the RecyclerView by measuring and setting up the window size + * This effect runs when the component mounts or when layout changes diff --git a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+004+fix-inverted-first-item-offset.patch b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+004+fix-inverted-first-item-offset.patch new file mode 100644 index 000000000000..98bac124be64 --- /dev/null +++ b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+004+fix-inverted-first-item-offset.patch @@ -0,0 +1,38 @@ +diff --git a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +index d7a3d84..ffcdad8 100644 +--- a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js ++++ b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +@@ -142,9 +142,11 @@ const RecyclerViewComponent = (props, ref) => { + containerViewSizeRef.current = outerViewSize; + // firstChildViewLayout is already relative to the outer container, + // so its x/y directly gives the first item offset. +- const firstItemOffset = horizontal +- ? firstChildViewLayout.x +- : firstChildViewLayout.y; ++ const firstItemOffset = inverted ++ ? 0 ++ : horizontal ++ ? firstChildViewLayout.x ++ : firstChildViewLayout.y; + // Update the RecyclerView manager with window dimensions + recyclerViewManager.updateLayoutParams({ + width: horizontal ? outerViewSize.width : firstChildViewLayout.width, +diff --git a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +index ea801d2..8a7deff 100644 +--- a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx ++++ b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +@@ -259,9 +259,11 @@ const RecyclerViewComponent = ( + + // firstChildViewLayout is already relative to the outer container, + // so its x/y directly gives the first item offset. +- const firstItemOffset = horizontal +- ? firstChildViewLayout.x +- : firstChildViewLayout.y; ++ const firstItemOffset = inverted ++ ? 0 ++ : horizontal ++ ? firstChildViewLayout.x ++ : firstChildViewLayout.y; + + // Update the RecyclerView manager with window dimensions + recyclerViewManager.updateLayoutParams( diff --git a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+005+fix-pending-children-blocking-measurements.patch b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+005+fix-pending-children-blocking-measurements.patch new file mode 100644 index 000000000000..6b96845c5875 --- /dev/null +++ b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+005+fix-pending-children-blocking-measurements.patch @@ -0,0 +1,68 @@ +diff --git a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +index ffcdad8..ee42f63 100644 +--- a/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js ++++ b/node_modules/@shopify/flash-list/dist/recyclerview/RecyclerView.js +@@ -166,9 +166,6 @@ const RecyclerViewComponent = (props, ref) => { + // eslint-disable-next-line react-hooks/exhaustive-deps + useLayoutEffect(() => { + var _a, _b; +- if (pendingChildIds.size > 0) { +- return; +- } + if (((_a = containerViewSizeRef.current) === null || _a === void 0 ? void 0 : _a.width) === 0 && + ((_b = containerViewSizeRef.current) === null || _b === void 0 ? void 0 : _b.height) === 0) { + return; +@@ -196,8 +193,17 @@ const RecyclerViewComponent = (props, ref) => { + } + if (recyclerViewManager.modifyChildrenLayout(layoutInfo, (_a = data === null || data === void 0 ? void 0 : data.length) !== null && _a !== void 0 ? _a : 0) && + !hasExceededMaxRendersWithoutCommit) { +- // Trigger re-render if layout modifications were made +- setRenderId((prev) => prev + 1); ++ if (pendingChildIds.size > 0) { ++ // When child FlashLists are still loading, avoid triggering a full ++ // RecyclerView re-render (setRenderId) to prevent cascading setState ++ // calls that could cause "Maximum update depth exceeded" errors. ++ // Instead, just commit the layout to update item positions in ++ // ViewHolderCollection without re-measuring. ++ (_b = viewHolderCollectionRef.current) === null || _b === void 0 ? void 0 : _b.commitLayout(); ++ } else { ++ // Trigger re-render if layout modifications were made ++ setRenderId((prev) => prev + 1); ++ } + } + else { + (_b = viewHolderCollectionRef.current) === null || _b === void 0 ? void 0 : _b.commitLayout(); +diff --git a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +index 8a7deff..b2bd67a 100644 +--- a/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx ++++ b/node_modules/@shopify/flash-list/src/recyclerview/RecyclerView.tsx +@@ -287,9 +287,6 @@ const RecyclerViewComponent = ( + */ + // eslint-disable-next-line react-hooks/exhaustive-deps + useLayoutEffect(() => { +- if (pendingChildIds.size > 0) { +- return; +- } + const layoutInfo = Array.from(refHolder, ([index, viewHolderRef]) => { + const layout = measureItemLayout( + viewHolderRef.current!, +@@ -323,8 +320,17 @@ const RecyclerViewComponent = ( + recyclerViewManager.modifyChildrenLayout(layoutInfo, data?.length ?? 0) && + !hasExceededMaxRendersWithoutCommit + ) { +- // Trigger re-render if layout modifications were made +- setRenderId((prev) => prev + 1); ++ if (pendingChildIds.size > 0) { ++ // When child FlashLists are still loading, avoid triggering a full ++ // RecyclerView re-render (setRenderId) to prevent cascading setState ++ // calls that could cause "Maximum update depth exceeded" errors. ++ // Instead, just commit the layout to update item positions in ++ // ViewHolderCollection without re-measuring. ++ viewHolderCollectionRef.current?.commitLayout(); ++ } else { ++ // Trigger re-render if layout modifications were made ++ setRenderId((prev) => prev + 1); ++ } + } else { + viewHolderCollectionRef.current?.commitLayout(); + applyOffsetCorrection(); diff --git a/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+006+fix-inverted-mvcp-android.patch b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+006+fix-inverted-mvcp-android.patch new file mode 100644 index 000000000000..814d54311362 --- /dev/null +++ b/patches/@shopify/flash-list/@shopify+flash-list+2.3.0+006+fix-inverted-mvcp-android.patch @@ -0,0 +1,114 @@ +diff --git a/node_modules/@shopify/flash-list/dist/recyclerview/hooks/useRecyclerViewController.js b/node_modules/@shopify/flash-list/dist/recyclerview/hooks/useRecyclerViewController.js +index 70f856a..52546f7 100644 +--- a/node_modules/@shopify/flash-list/dist/recyclerview/hooks/useRecyclerViewController.js ++++ b/node_modules/@shopify/flash-list/dist/recyclerview/hooks/useRecyclerViewController.js +@@ -1,5 +1,5 @@ + import { useCallback, useImperativeHandle, useMemo, useRef, useState, } from "react"; +-import { I18nManager } from "react-native"; ++import { I18nManager, Platform } from "react-native"; + import { adjustOffsetForRTL } from "../utils/adjustOffsetForRTL"; + import { PlatformConfig } from "../../native/config/PlatformHelper"; + import { WarningMessages } from "../../errors/WarningMessages"; +@@ -25,6 +25,8 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + const isUnmounted = useUnmountFlag(); + const [_, setRenderId] = useState(0); + const pauseOffsetCorrection = useRef(false); ++ const pendingAndroidInvertedRafId = useRef(null); ++ const skipNextAndroidInvertedCorrection = useRef(false); + const lastDataLengthRef = useRef(recyclerViewManager.getDataLength()); + const { setTimeout } = useUnmountAwareTimeout(); + // Track the first visible item for maintaining scroll position +@@ -79,7 +81,7 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + */ + const applyOffsetCorrection = useCallback(() => { + var _a, _b, _c; +- const { horizontal, data } = recyclerViewManager.props; ++ const { horizontal, data, inverted } = recyclerViewManager.props; + // Execute all pending callbacks from previous scroll offset updates + // This ensures any scroll operations that were waiting for render are completed + const callbacks = pendingScrollCallbacks.current; +@@ -91,6 +93,11 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + currentDataLength > 0 && + recyclerViewManager.shouldMaintainVisibleContentPosition()) { + const hasDataChanged = currentDataLength !== lastDataLengthRef.current; ++ // Read and reset the skip flag so it never persists across multiple correction cycles ++ const shouldSkipAndroidInvertedCorrection = hasDataChanged && inverted && Platform.OS === 'android' && skipNextAndroidInvertedCorrection.current; ++ if (shouldSkipAndroidInvertedCorrection) { ++ skipNextAndroidInvertedCorrection.current = false; ++ } + // If we have a tracked first visible item, maintain its position + if (firstVisibleItemKey.current) { + const currentIndexOfFirstVisibleItem = (_a = recyclerViewManager +@@ -115,10 +122,31 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + !pauseOffsetCorrection.current && + !recyclerViewManager.animationOptimizationsEnabled) { + // console.log("diff", diff, firstVisibleItemKey.current); +- if (PlatformConfig.supportsOffsetCorrection) { +- // console.log("scrollBy", diff); ++ const useAndroidInvertedFallback = hasDataChanged && inverted && Platform.OS === 'android'; ++ if (PlatformConfig.supportsOffsetCorrection && !useAndroidInvertedFallback) { + (_b = scrollAnchorRef.current) === null || _b === void 0 ? void 0 : _b.scrollBy(diff); + } ++ else if (useAndroidInvertedFallback) { ++ if (!shouldSkipAndroidInvertedCorrection) { ++ const scrollToParams = horizontal ++ ? { ++ x: recyclerViewManager.getAbsoluteLastScrollOffset() + diff, ++ animated: false, ++ } ++ : { ++ y: recyclerViewManager.getAbsoluteLastScrollOffset() + diff, ++ animated: false, ++ }; ++ if (pendingAndroidInvertedRafId.current !== null) { ++ cancelAnimationFrame(pendingAndroidInvertedRafId.current); ++ } ++ // rAF scrollTo to correct after native layout commits ++ pendingAndroidInvertedRafId.current = requestAnimationFrame(() => { ++ pendingAndroidInvertedRafId.current = null; ++ (_c = scrollViewRef.current) === null || _c === void 0 ? void 0 : _c.scrollTo(scrollToParams); ++ }); ++ } ++ } + else { + const scrollToParams = horizontal + ? { +@@ -162,6 +190,13 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + * Handles RTL layouts and first item offset adjustments. + */ + scrollToOffset: ({ offset, animated, skipFirstItemOffset = true, }) => { ++ if (pendingAndroidInvertedRafId.current !== null) { ++ cancelAnimationFrame(pendingAndroidInvertedRafId.current); ++ pendingAndroidInvertedRafId.current = null; ++ } ++ if (recyclerViewManager.props.inverted && Platform.OS === 'android') { ++ skipNextAndroidInvertedCorrection.current = true; ++ } + const { horizontal } = recyclerViewManager.props; + if (scrollViewRef.current) { + // Adjust offset for RTL layouts in horizontal mode +@@ -205,6 +240,13 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + * Scrolls to the end of the list. + */ + scrollToEnd: async ({ animated } = {}) => { ++ if (pendingAndroidInvertedRafId.current !== null) { ++ cancelAnimationFrame(pendingAndroidInvertedRafId.current); ++ pendingAndroidInvertedRafId.current = null; ++ } ++ if (recyclerViewManager.props.inverted && Platform.OS === 'android') { ++ skipNextAndroidInvertedCorrection.current = true; ++ } + const { data } = recyclerViewManager.props; + if (data && data.length > 0) { + const lastIndex = data.length - 1; +@@ -235,6 +277,10 @@ export function useRecyclerViewController(recyclerViewManager, ref, scrollViewRe + * Returns a Promise that resolves when the scroll is complete. + */ + scrollToIndex: ({ index, animated, viewPosition, viewOffset, }) => { ++ if (pendingAndroidInvertedRafId.current !== null) { ++ cancelAnimationFrame(pendingAndroidInvertedRafId.current); ++ pendingAndroidInvertedRafId.current = null; ++ } + return new Promise((resolve) => { + const { horizontal } = recyclerViewManager.props; + if (scrollViewRef.current && diff --git a/patches/@shopify/flash-list/details.md b/patches/@shopify/flash-list/details.md index 6012a1c00a87..45570d16761f 100644 --- a/patches/@shopify/flash-list/details.md +++ b/patches/@shopify/flash-list/details.md @@ -20,3 +20,31 @@ - Upstream PR/issue: TBD - E/App issue: https://github.com/Expensify/App/issues/83976 - PR introducing patch: https://github.com/Expensify/App/pull/84887 + +### [@shopify+flash-list+2.3.0+003+fix-inverted-scroll-direction-on-web.patch](@shopify+flash-list+2.3.0+003+fix-inverted-scroll-direction-on-web.patch) + +- Reason: Fixes inverted scroll direction on web. FlashList uses `scaleY: -1` / `scaleX: -1` CSS transform to visually invert the list, but the browser's native wheel scroll doesn't flip accordingly — scrolling down visually scrolls up and vice versa. This patch adds a `useEffect` in `RecyclerView` that attaches a `wheel` event listener on web when `inverted` is true, intercepting the event, negating the scroll delta, and manually adjusting `scrollTop`/`scrollLeft`. Mirrors the same fix applied in react-native-web's `VirtualizedList`. +- Upstream PR/issue: TBD +- E/App issue: https://github.com/Expensify/App/issues/33725 +- PR introducing patch: https://github.com/Expensify/App/pull/85114 + +### [@shopify+flash-list+2.3.0+004+fix-inverted-first-item-offset.patch](@shopify+flash-list+2.3.0+004+fix-inverted-first-item-offset.patch) + +- Reason: Fixes inverted lists rendering only a few items with white space on scroll. FlashList's `RecyclerView` measures `firstItemOffset` by calling `measureFirstChildLayout` relative to the outer container. When `inverted` is true, the outer container has `scaleY: -1`, which flips the coordinate system — causing the measured y-offset to equal the container height instead of 0. This makes all scroll offsets negative after adjustment (`adjustedOffset = scrollOffset - firstItemOffset`), so the viewport thinks it's in negative space where no items exist. Only items caught by the draw-distance buffer render. The fix forces `firstItemOffset` to 0 for inverted lists, since the transform already handles visual inversion. +- Upstream PR/issue: TBD +- E/App issue: https://github.com/Expensify/App/issues/33725 +- PR introducing patch: https://github.com/Expensify/App/pull/85114 + +### [@shopify+flash-list+2.3.0+005+fix-pending-children-blocking-measurements.patch](@shopify+flash-list+2.3.0+005+fix-pending-children-blocking-measurements.patch) + +- Reason: Fixes items overlapping on initial load when a list contains nested FlashLists (e.g. a horizontal list inside a chat message). The `RecyclerView` layout measurement `useLayoutEffect` had an early return when `pendingChildIds.size > 0` — while any nested FlashList was still doing its progressive first layout, the parent list skipped ALL measurement processing. This meant newly added items stayed at estimated positions (wrong heights/y-offsets) while being visible (`opacity: 1`), causing overlap. The fix moves the `pendingChildIds` check so that measurements are always collected and processed by the layout manager, but when children are pending, `commitLayout()` is called instead of `setRenderId()`. This updates item positions in `ViewHolderCollection` without triggering a full `RecyclerView` re-render, avoiding the cascading `setState` calls that the original guard was meant to prevent. +- Upstream PR/issue: TBD +- E/App issue: https://github.com/Expensify/App/issues/33725 +- PR introducing patch: https://github.com/Expensify/App/pull/85114 + +### [@shopify+flash-list+2.3.0+006+fix-inverted-mvcp-android.patch](@shopify+flash-list+2.3.0+006+fix-inverted-mvcp-android.patch) + +- Reason: Fixes `maintainVisibleContentPosition` not working on Android for inverted lists when items are prepended (e.g. new messages arriving, or `useFlashListScrollKey` switching from sliced to full data). FlashList's offset correction uses a `ScrollAnchor` component — an invisible absolutely-positioned element whose `top` changes to trigger the native `maintainVisibleContentPosition` on the ScrollView. On Android, where inversion uses `rotate: 180deg` (vs `scaleY: -1` on iOS), this mechanism silently fails: the anchor position changes but the native ScrollView does not adjust its scroll offset. The fix detects the specific case (`inverted && Platform.OS === 'android' && hasDataChanged`) and bypasses `ScrollAnchor` in favor of a deferred `scrollTo` via `requestAnimationFrame`, which fires after the native layout has committed the new content size. Non-inverted lists, iOS, web, and layout-only corrections (no data change) are unaffected and continue using the original code paths. +- Upstream PR/issue: TBD +- E/App issue: https://github.com/Expensify/App/issues/33725 +- PR introducing patch: https://github.com/Expensify/App/pull/85114 diff --git a/src/components/FlatList/InvertedFlatList/CellRendererComponent.tsx b/src/components/FlashList/InvertedFlashList/CellRendererComponent.tsx similarity index 94% rename from src/components/FlatList/InvertedFlatList/CellRendererComponent.tsx rename to src/components/FlashList/InvertedFlashList/CellRendererComponent.tsx index 8f1640a2305d..65397e70a570 100644 --- a/src/components/FlatList/InvertedFlatList/CellRendererComponent.tsx +++ b/src/components/FlashList/InvertedFlashList/CellRendererComponent.tsx @@ -21,7 +21,7 @@ function CellRendererComponent(props: CellRendererComponentProps) { * list items. Consequently, lower list items can overflow the upper list items. * See: https://github.com/Expensify/App/issues/20451 */ - {zIndex: -props.index, position: 'relative'}, + {zIndex: -props.index}, ]} /> ); diff --git a/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.android.ts b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.android.ts new file mode 100644 index 000000000000..4fae55425796 --- /dev/null +++ b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.android.ts @@ -0,0 +1,8 @@ +import type GetShowScrollIndicator from './types'; + +// On Android, the scroll indicator appears on the left side due to a known FlashList issue with inverted lists. +// See: https://shopify.github.io/flash-list/docs/usage#inverted +// So we hide it. +const getShowScrollIndicator: GetShowScrollIndicator = () => false; + +export default getShowScrollIndicator; diff --git a/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.ts b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.ts new file mode 100644 index 000000000000..29f175e80830 --- /dev/null +++ b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/index.ts @@ -0,0 +1,5 @@ +import type GetShowScrollIndicator from './types'; + +const getShowScrollIndicator: GetShowScrollIndicator = (shouldScrollToEndAfterLayout) => !shouldScrollToEndAfterLayout; + +export default getShowScrollIndicator; diff --git a/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/types.ts b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/types.ts new file mode 100644 index 000000000000..5714c8365219 --- /dev/null +++ b/src/components/FlashList/InvertedFlashList/getShowScrollIndicator/types.ts @@ -0,0 +1,3 @@ +type GetShowScrollIndicator = (shouldScrollToEndAfterLayout: boolean) => boolean; + +export default GetShowScrollIndicator; diff --git a/src/components/FlashList/InvertedFlashList/index.tsx b/src/components/FlashList/InvertedFlashList/index.tsx new file mode 100644 index 000000000000..44444f908220 --- /dev/null +++ b/src/components/FlashList/InvertedFlashList/index.tsx @@ -0,0 +1,43 @@ +import type {FlashListProps} from '@shopify/flash-list'; +import React from 'react'; +import useFlashListScrollKey from '@components/FlashList/useFlashListScrollKey'; +import type {FlatListRefType} from '@pages/inbox/ReportScreenContext'; +import FlashList from '..'; +import CellRendererComponent from './CellRendererComponent'; + +type InvertedFlashListProps = FlashListProps & { + /** Key of the item to initially scroll to when the list first renders. */ + initialScrollKey?: string | null; + + /** The array of items to render in the list. */ + data: T[]; + + /** Function that extracts a unique key for each item in the list. */ + keyExtractor: (item: T, index: number) => string; + + /** Ref to the underlying list instance. */ + ref: FlatListRefType; +}; + +function InvertedFlashList({data, keyExtractor, initialScrollKey, onStartReached: onStartReachedProp, ...restProps}: InvertedFlashListProps) { + const {displayedData, onStartReached} = useFlashListScrollKey({ + data, + keyExtractor, + initialScrollKey, + onStartReached: onStartReachedProp, + }); + + return ( + + // eslint-disable-next-line react/jsx-props-no-spreading + {...restProps} + inverted + onStartReached={onStartReached} + data={displayedData} + keyExtractor={keyExtractor} + CellRendererComponent={CellRendererComponent} + /> + ); +} + +export default InvertedFlashList; diff --git a/src/components/FlashList/index.tsx b/src/components/FlashList/index.tsx new file mode 100644 index 000000000000..888821e8d1a3 --- /dev/null +++ b/src/components/FlashList/index.tsx @@ -0,0 +1,26 @@ +import {FlashList as ShopifyFlashList} from '@shopify/flash-list'; +import type {FlashListProps} from '@shopify/flash-list'; +import React from 'react'; +import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; +import useEmitComposerScrollEvents from '@hooks/useEmitComposerScrollEvents'; + +function FlashList({onScroll: onScrollProp, inverted, ...restProps}: FlashListProps) { + const emitComposerScrollEvents = useEmitComposerScrollEvents({enabled: true, inverted}); + + const handleScroll = (e: NativeSyntheticEvent) => { + onScrollProp?.(e); + // Emit scroll events so that ActiveHoverable can suppress hover effects during scroll + emitComposerScrollEvents(); + }; + + return ( + + // eslint-disable-next-line react/jsx-props-no-spreading + {...restProps} + inverted={inverted} + onScroll={handleScroll} + /> + ); +} + +export default FlashList; diff --git a/src/components/FlashList/useFlashListScrollKey.ts b/src/components/FlashList/useFlashListScrollKey.ts new file mode 100644 index 000000000000..851091566f1c --- /dev/null +++ b/src/components/FlashList/useFlashListScrollKey.ts @@ -0,0 +1,42 @@ +import type {FlashListProps} from '@shopify/flash-list'; +import {useEffect, useState} from 'react'; + +type FlashListScrollKeyProps = { + /** The array of items to render in the list. */ + data: T[]; + + /** Function that extracts a unique key for each item in the list. */ + keyExtractor: (item: T, index: number) => string; + + /** Key of the item to initially scroll to when the list first renders. */ + initialScrollKey: string | null | undefined; + + /** Callback invoked when the user scrolls close to the start of the list. */ + onStartReached: FlashListProps['onStartReached']; +}; + +export default function useFlashListScrollKey({data, keyExtractor, initialScrollKey, onStartReached}: FlashListScrollKeyProps) { + const [isInitialRender, setIsInitialRender] = useState(true); + + // After the first render with sliced data, give FlashList one frame to lay out, + // then switch to the full data array. maintainVisibleContentPosition keeps the target pinned. + useEffect(() => { + if (!isInitialRender || !initialScrollKey) { + return; + } + requestAnimationFrame(() => setIsInitialRender(false)); + }, [isInitialRender, initialScrollKey]); + + if (!isInitialRender || !initialScrollKey) { + return {displayedData: data, onStartReached}; + } + + const targetIndex = data.findIndex((item, index) => keyExtractor(item, index) === initialScrollKey); + if (targetIndex <= 0) { + return {displayedData: data, onStartReached}; + } + + // On the first render, slice from the target onward so the target item + // appears at the visual bottom of the inverted list — no scrolling needed. + return {displayedData: data.slice(targetIndex), onStartReached: () => {}}; +} diff --git a/src/components/FlatList/InvertedFlatList/index.tsx b/src/components/FlatList/InvertedFlatList/index.tsx deleted file mode 100644 index 87af6b05d957..000000000000 --- a/src/components/FlatList/InvertedFlatList/index.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import React from 'react'; -import FlatList from '@components/FlatList/FlatList'; -import useFlatListScrollKey from '@components/FlatList/hooks/useFlatListScrollKey'; -import CellRendererComponent from './CellRendererComponent'; -import shouldRemoveClippedSubviews from './shouldRemoveClippedSubviews'; -import type {InvertedFlatListProps} from './types'; - -// Adapted from https://github.com/facebook/react-native/blob/29a0d7c3b201318a873db0d1b62923f4ce720049/packages/virtualized-lists/Lists/VirtualizeUtils.js#L237 -function defaultKeyExtractor(item: T | {key: string} | {id: string}, index: number): string { - if (item != null) { - if (typeof item === 'object' && 'key' in item) { - return item.key; - } - if (typeof item === 'object' && 'id' in item) { - return item.id; - } - } - return String(index); -} - -function InvertedFlatList({ - ref, - shouldEnableAutoScrollToTopThreshold, - initialScrollKey, - data, - onStartReached, - renderItem, - keyExtractor = defaultKeyExtractor, - ...restProps -}: InvertedFlatListProps) { - const {displayedData, maintainVisibleContentPosition, handleStartReached, handleRenderItem, listRef} = useFlatListScrollKey({ - data, - keyExtractor, - initialScrollKey, - inverted: true, - onStartReached, - shouldEnableAutoScrollToTopThreshold, - renderItem, - ref, - }); - - return ( - - // eslint-disable-next-line react/jsx-props-no-spreading - {...restProps} - ref={listRef} - maintainVisibleContentPosition={maintainVisibleContentPosition} - inverted - data={displayedData} - renderItem={handleRenderItem} - keyExtractor={keyExtractor} - onStartReached={handleStartReached} - CellRendererComponent={CellRendererComponent} - removeClippedSubviews={shouldRemoveClippedSubviews} - /> - ); -} - -export default InvertedFlatList; diff --git a/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.native.ts b/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.native.ts deleted file mode 100644 index 1da980d0e6cc..000000000000 --- a/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.native.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * To achieve absolute positioning and handle overflows for list items, the property must be disabled - * for Android native builds. - * Source: https://reactnative.dev/docs/0.71/optimizing-flatlist-configuration#removeclippedsubviews - */ -export default false; diff --git a/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.ts b/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.ts deleted file mode 100644 index f237ddf58ed4..000000000000 --- a/src/components/FlatList/InvertedFlatList/shouldRemoveClippedSubviews/index.ts +++ /dev/null @@ -1 +0,0 @@ -export default undefined; diff --git a/src/components/FlatList/InvertedFlatList/types.ts b/src/components/FlatList/InvertedFlatList/types.ts deleted file mode 100644 index a779bc247bd9..000000000000 --- a/src/components/FlatList/InvertedFlatList/types.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type {ForwardedRef} from 'react'; -import type {ListRenderItem, FlatList as RNFlatList} from 'react-native'; -import type {CustomFlatListProps} from '@components/FlatList/FlatList/types'; - -type InvertedFlatListProps = Omit, 'data' | 'renderItem' | 'initialScrollIndex'> & { - shouldEnableAutoScrollToTopThreshold?: boolean; - data: T[]; - renderItem: ListRenderItem; - initialScrollKey?: string | null; - ref?: ForwardedRef; -}; - -// eslint-disable-next-line import/prefer-default-export -export type {InvertedFlatListProps}; diff --git a/src/components/FlatList/InvertedFlatList/RenderTaskQueue.tsx b/src/components/FlatList/RenderTaskQueue.tsx similarity index 100% rename from src/components/FlatList/InvertedFlatList/RenderTaskQueue.tsx rename to src/components/FlatList/RenderTaskQueue.tsx diff --git a/src/components/FlatList/hooks/useFlatListScrollKey.ts b/src/components/FlatList/hooks/useFlatListScrollKey.ts index 85af699a5c2b..85ee67fb18a7 100644 --- a/src/components/FlatList/hooks/useFlatListScrollKey.ts +++ b/src/components/FlatList/hooks/useFlatListScrollKey.ts @@ -4,7 +4,7 @@ import type {ForwardedRef} from 'react'; import type {ListRenderItem, ListRenderItemInfo, FlatList as RNFlatList} from 'react-native'; import {View} from 'react-native'; import getInitialPaginationSize from '@components/FlatList/getInitialPaginationSize'; -import RenderTaskQueue from '@components/FlatList/InvertedFlatList/RenderTaskQueue'; +import RenderTaskQueue from '@components/FlatList/RenderTaskQueue'; import type {FlatListInnerRefType} from '@components/FlatList/types'; import type {ScrollViewProps} from '@components/ScrollView'; import usePrevious from '@hooks/usePrevious'; diff --git a/src/components/VideoPlayer/BaseVideoPlayer.tsx b/src/components/VideoPlayer/BaseVideoPlayer.tsx index 4941ba798246..b42c3477ec13 100644 --- a/src/components/VideoPlayer/BaseVideoPlayer.tsx +++ b/src/components/VideoPlayer/BaseVideoPlayer.tsx @@ -574,7 +574,7 @@ function BaseVideoPlayer({ if (!(videoPlayerElementParentRef.current && 'addEventListener' in videoPlayerElementParentRef.current)) { return; } - // When the video is in fullscreen, we don't want the scroll to be captured by the InvertedFlatList of report screen. + // When the video is in fullscreen, we don't want the scroll to be captured by the InvertedFlashList of report screen. // This will also allow the user to scroll the video playback speed. videoPlayerElementParentRef.current.addEventListener('wheel', stopWheelPropagation); }} diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index 32689dec4c96..1566fa7bbb51 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -1,14 +1,15 @@ -import type {ListRenderItemInfo} from '@react-native/virtualized-lists'; import {useIsFocused, useRoute} from '@react-navigation/native'; import {isUserValidatedSelector} from '@selectors/Account'; import {tierNameSelector} from '@selectors/UserWallet'; +import type {ListRenderItemInfo} from '@shopify/flash-list'; import React, {memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'; import type {LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import {DeviceEventEmitter, InteractionManager, View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import {renderScrollComponent as renderActionSheetAwareScrollView} from '@components/ActionSheetAwareScrollView'; import Button from '@components/Button'; -import InvertedFlatList from '@components/FlatList/InvertedFlatList'; +import InvertedFlashList from '@components/FlashList/InvertedFlashList'; +import getShowScrollIndicator from '@components/FlashList/InvertedFlashList/getShowScrollIndicator'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; @@ -22,6 +23,7 @@ import useReportIsArchived from '@hooks/useReportIsArchived'; import useReportScrollManager from '@hooks/useReportScrollManager'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useScrollToEndOnNewMessageReceived from '@hooks/useScrollToEndOnNewMessageReceived'; +import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; import {isSafari} from '@libs/Browser'; @@ -116,9 +118,6 @@ type ReportActionsListProps = { /** ID of the list */ listID: number; - /** Should enable auto scroll to top threshold */ - shouldEnableAutoScrollToTopThreshold?: boolean; - /** Whether the optimistic CREATED report action was added */ hasCreatedActionAdded?: boolean; @@ -154,8 +153,6 @@ function keyExtractor(item: OnyxTypes.ReportAction): string { return item.reportActionID; } -const onScrollToIndexFailed = () => {}; - function ReportActionsList({ report, transactionThreadReport, @@ -168,7 +165,6 @@ function ReportActionsList({ onLayout, isComposerFullSize, listID, - shouldEnableAutoScrollToTopThreshold, parentReportActionForTransactionThread, hasCreatedActionAdded, isConciergeSidePanel, @@ -180,6 +176,7 @@ function ReportActionsList({ const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const personalDetailsList = usePersonalDetails(); const styles = useThemeStyles(); + const StyleUtils = useStyleUtils(); const {translate} = useLocalize(); const expensifyIcons = useMemoizedLazyExpensifyIcons(['UpArrow']); const {windowHeight} = useWindowDimensions(); @@ -214,14 +211,14 @@ function ReportActionsList({ const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`); const backTo = route?.params?.backTo as string; - // Display the new message indicator when comment linking and not close to the newest message. - const reportActionID = route?.params?.reportActionID; + const linkedReportActionID = route?.params?.reportActionID; const isTransactionThreadReport = useMemo(() => isTransactionThread(parentReportAction) && !isSentMoneyReportAction(parentReportAction), [parentReportAction]); const isMoneyRequestOrInvoiceReport = useMemo(() => isMoneyRequestReport(report) || isInvoiceReport(report), [report]); const shouldFocusToTopOnMount = useMemo(() => isTransactionThreadReport || isMoneyRequestOrInvoiceReport, [isMoneyRequestOrInvoiceReport, isTransactionThreadReport]); const topReportAction = sortedVisibleReportActions.at(-1); - const [shouldScrollToEndAfterLayout, setShouldScrollToEndAfterLayout] = useState(shouldFocusToTopOnMount && !reportActionID); + const [shouldScrollToEndAfterLayout, setShouldScrollToEndAfterLayout] = useState(shouldFocusToTopOnMount && !linkedReportActionID); + const scrollEndTimerRef = useRef | undefined>(undefined); const isAnonymousUser = useIsAnonymousUser(); useEffect(() => { @@ -234,7 +231,6 @@ function ReportActionsList({ const readActionSkipped = useRef(false); const hasHeaderRendered = useRef(false); - const linkedReportActionID = route?.params?.reportActionID; const lastAction = sortedVisibleReportActions.at(0); const sortedVisibleReportActionsObjects: OnyxTypes.ReportActions = useMemo( @@ -358,13 +354,20 @@ function ReportActionsList({ onTrackScrolling: (event: NativeSyntheticEvent) => { scrollOffsetRef.current = event.nativeEvent.contentOffset.y; onScroll?.(event); - if (shouldScrollToEndAfterLayout && (!hasCreatedActionAdded || isOffline)) { - setShouldScrollToEndAfterLayout(false); + // We use a timeout to wait for the scroll to finish before resetting the flag. + // onMomentumScrollEnd would be ideal but it doesn't work on web. + if (shouldScrollToEndAfterLayout && (!hasCreatedActionAdded || isOffline) && !scrollEndTimerRef.current) { + scrollEndTimerRef.current = setTimeout(() => { + setShouldScrollToEndAfterLayout(false); + scrollEndTimerRef.current = undefined; + }, CONST.TIMING.LIST_SCROLLING_DEBOUNCE_TIME); } }, hasOnceLoadedReportActions: !!reportMetadata?.hasOnceLoadedReportActions, }); + useEffect(() => () => clearTimeout(scrollEndTimerRef.current), []); + useScrollToEndOnNewMessageReceived({ sizeChangeType: 'changed', scrollOffsetRef, @@ -865,20 +868,22 @@ function ReportActionsList({ fsClass={reportActionsListFSClass} > {shouldScrollToEndAfterLayout && topReportAction ? renderTopReportActions() : undefined} - item.actionName} + initialScrollKey={linkedReportActionID} onContentSizeChange={() => { trackVerticalScrolling(undefined); }} diff --git a/src/pages/inbox/report/ReportActionsView.tsx b/src/pages/inbox/report/ReportActionsView.tsx index 8f4ce82ebfd6..f24a634bec19 100755 --- a/src/pages/inbox/report/ReportActionsView.tsx +++ b/src/pages/inbox/report/ReportActionsView.tsx @@ -1,6 +1,5 @@ import {useIsFocused, useRoute} from '@react-navigation/native'; -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; -import {InteractionManager} from 'react-native'; +import React, {useCallback, useEffect, useMemo, useRef} from 'react'; import type {LayoutChangeEvent} from 'react-native'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useConciergeSidePanelReportActions from '@hooks/useConciergeSidePanelReportActions'; @@ -140,14 +139,12 @@ function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { const [transactionThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`); const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const [visibleReportActionsData] = useOnyx(ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS); - const prevTransactionThreadReport = usePrevious(transactionThreadReport); const prevReportActionID = usePrevious(reportActionID); const reportPreviewAction = useMemo(() => getReportPreviewAction(report?.chatReportID, report?.reportID), [report?.chatReportID, report?.reportID]); const didLayout = useRef(false); const {shouldUseNarrowLayout} = useResponsiveLayout(); const isFocused = useIsFocused(); - const [isNavigatingToLinkedMessage, setNavigatingToLinkedMessage] = useState(false); const prevShouldUseNarrowLayoutRef = useRef(shouldUseNarrowLayout); const isReportFullyVisible = useMemo(() => getIsReportFullyVisible(isFocused), [isFocused]); const {transactions: reportTransactions} = useTransactionsAndViolationsForReport(reportID); @@ -273,12 +270,6 @@ function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { [reportActions, isOffline, canPerformWriteAction, reportTransactionIDs, visibleReportActionsData, reportID], ); - const newestReportAction = useMemo(() => reportActions?.at(0), [reportActions]); - const lastActionCreated = visibleReportActions.at(0)?.created; - const isNewestAction = (actionCreated: string | undefined, lastVisibleActionCreated: string | undefined) => - actionCreated && lastVisibleActionCreated ? actionCreated >= lastVisibleActionCreated : actionCreated === lastVisibleActionCreated; - const hasNewestReportAction = isNewestAction(lastActionCreated, report?.lastVisibleActionCreated) || isNewestAction(lastActionCreated, transactionThreadReport?.lastVisibleActionCreated); - const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; @@ -337,33 +328,6 @@ function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { } }; - // Check if the first report action in the list is the one we're currently linked to - const isTheFirstReportActionIsLinked = newestReportAction?.reportActionID === reportActionID; - - useEffect(() => { - let timerID: NodeJS.Timeout; - - if (!isTheFirstReportActionIsLinked && reportActionID) { - setNavigatingToLinkedMessage(true); - // After navigating to the linked reportAction, apply this to correctly set - // `autoscrollToTopThreshold` prop when linking to a specific reportAction. - // eslint-disable-next-line @typescript-eslint/no-deprecated - InteractionManager.runAfterInteractions(() => { - // Using a short delay to ensure the view is updated after interactions - timerID = setTimeout(() => setNavigatingToLinkedMessage(false), 10); - }); - } else { - setNavigatingToLinkedMessage(false); - } - - return () => { - if (!timerID) { - return; - } - clearTimeout(timerID); - }; - }, [isTheFirstReportActionIsLinked, reportActionID]); - // Show skeleton while loading initial report actions when data is incomplete/missing and online const shouldShowSkeletonForInitialLoad = isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; @@ -399,8 +363,6 @@ function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { return ; } - // AutoScroll is disabled when we do linking to a specific reportAction - const shouldEnableAutoScroll = (hasNewestReportAction && (!reportActionID || !isNavigatingToLinkedMessage)) || (transactionThreadReport && !prevTransactionThreadReport); return ( <> { + return styles.opacity0; +}; + +export default getHiddenChatContentStyle; diff --git a/src/styles/utils/getHiddenChatContentStyle/index.ts b/src/styles/utils/getHiddenChatContentStyle/index.ts new file mode 100644 index 000000000000..d50dd359542c --- /dev/null +++ b/src/styles/utils/getHiddenChatContentStyle/index.ts @@ -0,0 +1,5 @@ +import type GetHiddenChatContentStyle from './types'; + +const getHiddenChatContentStyle: GetHiddenChatContentStyle = (styles) => styles.visibilityHidden; + +export default getHiddenChatContentStyle; diff --git a/src/styles/utils/getHiddenChatContentStyle/types.ts b/src/styles/utils/getHiddenChatContentStyle/types.ts new file mode 100644 index 000000000000..f9159f68a4f6 --- /dev/null +++ b/src/styles/utils/getHiddenChatContentStyle/types.ts @@ -0,0 +1,6 @@ +import type {ViewStyle} from 'react-native'; +import type {ThemeStyles} from '@src/styles'; + +type GetHiddenChatContentStyle = (styles: ThemeStyles) => ViewStyle; + +export default GetHiddenChatContentStyle; diff --git a/src/styles/utils/index.ts b/src/styles/utils/index.ts index f381f4cd7af8..edc6ec42d00a 100644 --- a/src/styles/utils/index.ts +++ b/src/styles/utils/index.ts @@ -27,6 +27,7 @@ import createModalStyleUtils from './generators/ModalStyleUtils'; import createReportActionContextMenuStyleUtils from './generators/ReportActionContextMenuStyleUtils'; import createTooltipStyleUtils from './generators/TooltipStyleUtils'; import getContextMenuItemStyles from './getContextMenuItemStyles'; +import getHiddenChatContentStyle from './getHiddenChatContentStyle'; import getHighResolutionInfoWrapperStyle from './getHighResolutionInfoWrapperStyle'; import getMoneyRequestReportPreviewStyle from './getMoneyRequestReportPreviewStyle'; import getNavigationBarType from './getNavigationBarType/index'; @@ -1435,6 +1436,7 @@ const createStyleUtils = (theme: ThemeColors, styles: ThemeStyles) => ({ getCompactContentContainerStyles: () => compactContentContainerStyles(styles), getContextMenuItemStyles: (windowWidth?: number) => getContextMenuItemStyles(styles, windowWidth), getContainerComposeStyles: () => containerComposeStyles(styles), + getHiddenChatContentStyle: () => getHiddenChatContentStyle(styles), /** * Gets styles for AutoCompleteSuggestion row diff --git a/tests/ui/PaginationTest.tsx b/tests/ui/PaginationTest.tsx index 630a4c94b355..32989fc5d4c3 100644 --- a/tests/ui/PaginationTest.tsx +++ b/tests/ui/PaginationTest.tsx @@ -372,6 +372,7 @@ describe('Pagination', () => { scrollToOffset(0); // ReportScreen relies on the onLayout event to receive updates from onyx. triggerListLayout(); + await waitForNetworkPromises(); await waitForBatchedUpdatesWithAct(); // Here we have 5 messages from the initial OpenReport and 5 from the initial GetNewerActions. diff --git a/tests/unit/RenderTaskQueueTest.ts b/tests/unit/RenderTaskQueueTest.ts index 010f2ce94bc5..fd2e9f8620a4 100644 --- a/tests/unit/RenderTaskQueueTest.ts +++ b/tests/unit/RenderTaskQueueTest.ts @@ -1,6 +1,6 @@ -import RenderTaskQueue from '../../src/components/FlatList/InvertedFlatList/RenderTaskQueue'; +import RenderTaskQueue from '@components/FlatList/RenderTaskQueue'; -jest.unmock('../../src/components/FlatList/InvertedFlatList/RenderTaskQueue'); +jest.unmock('@components/FlatList/RenderTaskQueue'); describe('RenderTaskQueue', () => { beforeEach(() => {