Skip to content

[Due for payment 2026-08-21] [$250] Web - RHP - Create expense RHP misalignment when quickly creating per diem expense #91610

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: v9.3.80-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/TR-32737/folder/13176674/41237177/1434929366?sort=%2Bidentifier
Email or phone of affected tester (no customers): leungbratt6+230502@gmail.com
Issue reported by: Applause Internal Team
Bug source: Exploratory - Significant User Experience Deterioration
Device used: Windows 10/Chrome
App Component: Money Requests

Action Performed:

  1. Open the NewDot app, log in as a new user
  2. Select " Manage My Team " -> Per Diem
  3. Go to Workspace and import the Per Diem file
  4. Click FAB -> Create expense -> Per Diem -> Create a per diem expense
  5. Then quickly click FAB
  6. Repeat step 4,5 a couple of times if doesn't see the issue

Expected Result:

Create expense RHP should display normally

Actual Result:

When quickly creating an expense, the RHP misaligns to the left

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7161365_1779546782674.perdiem_rhp.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Svetlana Lazutkina
Bug ID: 7161365

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on May 25, 2026
  2. MelvinBot commented on May 25, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    When a user rapidly creates per diem expenses (FAB → Create expense → Per Diem → submit → FAB again), the RHP-to-RHP navigation triggers handleNavigatingToModalFromModal, which atomically removes the old RHP route and pushes a new one. This causes the old card's closing animation (100ms) and the new card's opening animation (150ms) to run simultaneously.

    The new card's layout is initialized from SafeAreaProviderCompat.initialMetrics.frame before the async handleLayout callback fires with the correct width. getCardStyles uses this potentially stale screen.width to set the position: fixed card's width, and since the RHP content is positioned at right: 0 inside that card, an incorrect width shifts the panel left.

    Additionally, the handleOverlayPress guard locks isExecutingRef for 300ms (CONST.ANIMATED_TRANSITION) while the actual exit animation is only 100ms — creating a 200ms window where rapid interactions can queue navigation actions that collide with the next RHP open cycle.

    What changes do you think we should make in order to solve the problem?

    The fix should ensure the card style interpolator receives a valid screen.width during rapid RHP-to-RHP transitions. Two approaches:

    1. Guard against stale layout in the card style interpolator — In useModalCardStyleInterpolator, if screen.width is 0 or unreasonably small, fall back to Dimensions.get('window').width. This prevents the position: fixed card from rendering with zero/wrong width during the layout measurement gap.

    2. Align the overlay guard timeout with the actual animation duration — In RightModalNavigator.tsx:180-182, replace CONST.ANIMATED_TRANSITION (300ms) with the actual RHP exit duration (CONST.MODAL.RHP_DURATION_OUT_WEB = 100ms) to eliminate the unnecessary 200ms blocking window where rapid FAB clicks can cause state collisions.

    What alternative solutions did you explore? (Optional)

    • Debouncing the FAB button — Would mask the symptom but not fix the underlying layout race. Users could still trigger it via keyboard shortcuts or other navigation paths.
    • Cancelling in-flight animations on new RHP push — More invasive change to react-navigation stack internals via patches; the layout guard approach is simpler and more maintainable.
    Investigation details

    Key code paths involved:

    Animation timing:

    • RHP open: 150ms, RHP close: 100ms, overlay guard: 300ms
    • Users clicking faster than 250ms cause overlapping open/close cycles

    Confidence: Medium — code evidence strongly supports the hypothesis, but runtime DevTools inspection during the misalignment would provide definitive confirmation of the stale screen.width value.


    Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 25, 2026
  4. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 25, 2026
  5. yusufdeveloper2903 commented on May 25, 2026

    @yusufdeveloper2903
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-18 14:50:00 UTC.

    Proposal

    What is the root cause of that problem?

    The RHP panel width is not driven by the screen that is currently on top of the modal stack — it is driven by a single module-level Animated.Value, expandedRHPProgress, that is resynced one commit too late for the freshly-opened RHP. On a fast reopen the new narrow RHP paints its first frame against the previous RHP's wide layout, so it is rendered inside a super-wide container and appears shifted left.

    1. The container width comes from a global singleton, anchored right: 0.

    The visible RHP container in RightModalNavigator is an Animated.View whose width is expandedRHPProgress interpolated 0 → single, 1 → wide, 2 → super-wide, applied on a position: absolute; right: 0; overflow: hidden view:

    Because it is pinned right: 0, a larger width extends the container leftward. So while expandedRHPProgress reads 2, the container occupies super-wide pixels measured from the right edge, regardless of what is mounted inside it.

    2. The per-card interpolator is chosen from the same lagging state.

    The card style for each RHP screen is picked in useModalStackScreenOptions from the visible wideRHPRouteKeys / superWideRHPRouteKeys read from useWideRHPState. When a super-wide key is still "visible", a single-width screen on top of it is given singleRHPExtendedCardInterpolatorStyles (the "single RHP displayed above a wide RHP" branch) instead of the plain single-RHP card:

    • const {wideRHPRouteKeys, superWideRHPRouteKeys} = useWideRHPState();
    • if (superWideRHPRouteKeys.includes(route.key)) {
      cardStyleInterpolator = enhanceCardStyleInterpolator(baseInterpolator, {
      cardStyle: styles.superWideRHPExtendedCardInterpolatorStyles,
      });
      } else if (wideRHPRouteKeys.includes(route.key)) {
      cardStyleInterpolator = enhanceCardStyleInterpolator(baseInterpolator, {
      cardStyle: styles.wideRHPExtendedCardInterpolatorStyles,
      });
      // single RHPs displayed above the wide RHP need to be positioned
      } else if (superWideRHPRouteKeys.length > 0 || wideRHPRouteKeys.length > 0) {
      cardStyleInterpolator = enhanceCardStyleInterpolator(baseInterpolator, {
      cardStyle: styles.singleRHPExtendedCardInterpolatorStyles,
      });
      }

    So both the container width and the card positioning depend on the same wide/superWide state.

    3. That state is only resynced reactively — on the old screen's unmount, after the new RHP already painted.

    The single source of truth that updates both is syncRHPKeys, which recomputes visible keys via getVisibleRHPKeys and calls setExpandedRHPProgress:

    • const syncRHPKeys = useCallback(() => {
      const {visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys} = getVisibleRHPKeys(allSuperWideRHPRouteKeys, allWideRHPRouteKeys);
      setWideRHPRouteKeys(visibleWideRHPRouteKeys);
      setSuperWideRHPRouteKeys(visibleSuperWideRHPRouteKeys);
      setExpandedRHPProgress(visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys);
      }, [allSuperWideRHPRouteKeys, allWideRHPRouteKeys]);
    • function setExpandedRHPProgress(superWideRHPRouteKeys: string[], wideRHPRouteKeys: string[]) {
      const numberOfSuperWideRoutes = superWideRHPRouteKeys.length;
      const numberOfWideRoutes = wideRHPRouteKeys.length;
      if (numberOfSuperWideRoutes > 0) {
      expandedRHPProgress.setValue(2);
      } else if (numberOfWideRoutes > 0) {
      expandedRHPProgress.setValue(1);
      } else {
      expandedRHPProgress.setValue(0);
      }

    But syncRHPKeys only re-runs from the effect that watches allWideRHPRouteKeys / allSuperWideRHPRouteKeys —

    useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    syncRHPKeys();
    }, [allSuperWideRHPRouteKeys, allWideRHPRouteKeys, syncRHPKeys]);
    — and those arrays only change when the old screen runs its unmount cleanup, which fires after the closing animation finishes, i.e. after the new RHP has already mounted and painted.

    4. The only immediate-reset path is gated by a guard that skips precisely the fast-reopen case.

    The close hooks reset the singleton directly, but only when the topmost route is no longer an RHP:

    On a quick FAB reopen the new RHP is already the topmost route, so routes.at(-1)?.name === RIGHT_MODAL_NAVIGATOR → the setValue(0) is skipped, and the singleton stays at 2 until the late syncRHPKeys fires.

    Putting the repro together: after submitting the per-diem expense the user lands on the EXPENSE_REPORT RHP, which is super-wide → expandedRHPProgress = 2, superWideRHPRouteKeys non-empty. A quick FAB → Create expense pushes a fresh narrow MONEY_REQUEST_CREATE RHP. It mounts while (a) the singleton is still 2 and (b) the visible super-wide key is still set, so its container is super-wide (right: 0, extending left) and its card gets the singleRHPExtendedCardInterpolatorStyles branch — the new panel is laid out as "single RHP over a super-wide RHP" even though there is no wide RHP anymore. Result: the panel renders shifted left. Done slowly, the old screen unmounts and syncRHPKeys flushes before the new RHP mounts, so it never reproduces.

    So: stale expandedRHPProgress + stale visible keys (both only corrected on the old screen's late unmount, and the immediate-reset guard skips the reopen case) → the new RHP paints its first frame against the previous super-wide layout → leftward misalignment.

    What changes do you think we should make in order to solve the problem?

    Make the freshly-opened RightModalNavigator resync from the authoritative navigation state before its first paint, instead of waiting for the previous screen's unmount. syncRHPKeys is already the single source of truth and already in scope in RightModalNavigator —

    const {clearWideRHPKeys, syncRHPKeys} = useWideRHPActions();
    — it is currently only called from a useFocusEffect, which runs after paint:

    • useFocusEffect(
      useCallback(() => {
      // When we open a second RightModalNavigator while the previous one is covered by a fullscreen navigator, we need to synchronize the keys.
      syncRHPKeys();
      // Super wide and wide route keys have to be cleared when the RightModalNavigator is not closed and a new navigator is opened above it.
      return () => clearWideRHPKeysAfterTabChanged();
      }, [syncRHPKeys, clearWideRHPKeysAfterTabChanged]),

    Call syncRHPKeys() from a useLayoutEffect on mount of RightModalNavigator so it runs synchronously before the browser paints the new RHP. getVisibleRHPKeys computes visibility from getLastVisibleRHPRouteKey(rootState) — the navigation state, which by mount already has the new narrow RHP as the last RHP route:

    • const lastVisibleRHPRouteKey = getLastVisibleRHPRouteKey(rootState);
      const lastRHPRoute = rootState.routes.find((route) => route.key === lastVisibleRHPRouteKey);
      if (!lastRHPRoute) {
      return emptyRHPKeysState;
      }
      const superWideRHPIndex = lastRHPRoute.state?.routes.findLastIndex((route) => route?.key && allSuperWideRHPKeys.includes(route.key)) ?? -1;
      const wideRHPIndex = lastRHPRoute.state?.routes.findLastIndex((route) => route?.key && allWideRHPKeys.includes(route.key)) ?? -1;
      let visibleRHPKeys;
      if (superWideRHPIndex > -1) {
      visibleRHPKeys = extractNavigationKeys(lastRHPRoute.state?.routes.slice(superWideRHPIndex));
      } else if (wideRHPIndex > -1) {
      visibleRHPKeys = extractNavigationKeys(lastRHPRoute.state?.routes.slice(wideRHPIndex));
      } else {
      visibleRHPKeys = extractNavigationKeys(lastRHPRoute.state?.routes);
      }
      return {
      visibleWideRHPRouteKeys: allWideRHPKeys.filter((key) => visibleRHPKeys.has(key)),
      visibleSuperWideRHPRouteKeys: allSuperWideRHPKeys.filter((key) => visibleRHPKeys.has(key)),
      };

    So for the new narrow RHP it returns empty visibleWide / visibleSuperWide, which makes setExpandedRHPProgress immediately set the singleton to 0 (

    function setExpandedRHPProgress(superWideRHPRouteKeys: string[], wideRHPRouteKeys: string[]) {
    const numberOfSuperWideRoutes = superWideRHPRouteKeys.length;
    const numberOfWideRoutes = wideRHPRouteKeys.length;
    if (numberOfSuperWideRoutes > 0) {
    expandedRHPProgress.setValue(2);
    } else if (numberOfWideRoutes > 0) {
    expandedRHPProgress.setValue(1);
    } else {
    expandedRHPProgress.setValue(0);
    }
    ) and clears the visible keys that drive the card interpolator — fixing both the container width and the card positioning in the same pass, on the first painted frame. When a wide RHP genuinely is below (the legitimate single-over-wide stack), getVisibleRHPKeys still reports it, so that case is untouched.

    This is purely web/wide-layout (the native variants of useShowWideRHPVersion / useShowSuperWideRHPVersion are no-ops), so there is no native impact. Exact placement (a dedicated mount useLayoutEffect vs. folding it into the existing focus path) can be settled in the PR phase.

    What alternative solutions did you explore? (Optional)

    Replace the topmost-route guard in onWideRHPClose / onSuperWideRHPClose (

    const onWideRHPClose = useCallback(() => {
    removeWideRHPRouteKey(route);
    // When the RHP has been closed, expandedRHPProgress should be set to 0.
    if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
    expandedRHPProgress.setValue(0);
    }
    ,
    const onSuperWideRHPClose = useCallback(() => {
    removeWideRHPRouteKey(route);
    removeSuperWideRHPRouteKey(route);
    // When the RHP has been closed, expandedRHPProgress should be set to 0.
    if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
    expandedRHPProgress.setValue(0);
    }
    ) with a recompute of expandedRHPProgress from the remaining wide/super-wide route keys (mirrored into refs so they read synchronously). This fixes the wrong gate, but the cleanup still runs on the old screen's unmount, which is after the closing animation and after the new RHP has painted — so it keeps racing the unmount timing. Fixing it on the opening side (the new RHP resyncs itself from the source of truth on mount) is deterministic and independent of when the old screen tears down, which is why it is the cleaner primary fix.

  6. MobileMage commented on May 25, 2026

    @MobileMage
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-05-25 13:59:20 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    When the user creates a per diem expense and immediately clicks the FAB to open Create expense again, the newly opened RHP is rendered shifted to the left instead of being flush against the right edge of the screen.

    What is the root cause of that problem?

    The expandedRHPProgress animated value (which drives the RHP container width in RightModalNavigator) gets out of sync with wideRHPRouteKeys when an RHP closes and a new one opens within the same animation frame. In useShowWideRHPVersion, the cleanup that runs on unmount only resets expandedRHPProgress to 0 when no RHP is the top route — when a new RHP is opened quickly, the guard short-circuits and leaves the progress value stale at the previously expanded width.

    const onWideRHPClose = useCallback(() => {
    removeWideRHPRouteKey(route);
    // When the RHP has been closed, expandedRHPProgress should be set to 0.
    if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
    expandedRHPProgress.setValue(0);
    }
    }, [removeWideRHPRouteKey, route]);

    By the next render, the visible wideRHPRouteKeys synced through the effect in WideRHPContextProvider is empty, so the new narrow RHP's card no longer receives the singleRHPExtendedCardInterpolatorStyles override that anchors it to right: 0 with width: sideBarWidth. The card falls back to navigationScreenCardStyle (position: fixed; width: screenWidth), and because the outer Animated.View container in RightModalNavigator is still using the stale wide animatedWidth, the full-screen-width card renders left-aligned within that wider clipped container — producing the leftward misalignment.

    What changes do you think we should make in order to solve the problem?

    Make the cleanup in useShowWideRHPVersion deterministic by recomputing expandedRHPProgress from the remaining wide/super-wide RHP keys rather than gating on whether any RHP is on top. We should expose (or call) the same logic used by setExpandedRHPProgress inside WideRHPContextProvider so that after removing the unmounting route key, the progress value reflects the actual remaining state — collapsing to 0 immediately when no wide/super-wide RHP remains, regardless of whether a new narrow RHP has already pushed onto the stack. This keeps the container width in RightModalNavigator in sync with the card-style decisions made by useModalStackScreenOptions, so the next RHP always renders against the right edge with the correct width.

    function setExpandedRHPProgress(superWideRHPRouteKeys: string[], wideRHPRouteKeys: string[]) {
    const numberOfSuperWideRoutes = superWideRHPRouteKeys.length;
    const numberOfWideRoutes = wideRHPRouteKeys.length;
    if (numberOfSuperWideRoutes > 0) {
    expandedRHPProgress.setValue(2);
    } else if (numberOfWideRoutes > 0) {
    expandedRHPProgress.setValue(1);
    } else {
    expandedRHPProgress.setValue(0);
    }
    }

    What alternative solutions did you explore? (Optional)

    N/A

  7. David-2002065 commented on May 25, 2026

    @David-2002065
    Contributor

    Proposal

    What is the root cause of that problem?

    After creating a per‑diem expense, the user lands on the newly‑created Expense Report which is rendered as a wide (or super‑wide) RHP via useShowSuperWideRHPVersion. That hook drives a single global Animated.Value — expandedRHPProgress — which the RightModalNavigator interpolates into the RHP container width (0 → single, 1 → wide, 2 → super‑wide). The container is anchored right: 0, so a larger value means the container extends further to the left.

    When the user immediately clicks FAB → Create expense, the previous wide/super‑wide RHP screen unmounts and a brand‑new narrow RHP screen (IOURequestStartPage) mounts on top of it inside the same RightModalNavigator. The cleanup runs in useShowSuperWideRHPVersion / useShowWideRHPVersion:

    const onSuperWideRHPClose = useCallback(() => {
        removeWideRHPRouteKey(route);
        removeSuperWideRHPRouteKey(route);
        // When the RHP has been closed, expandedRHPProgress should be set to 0.
        if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
            expandedRHPProgress.setValue(0);
        }
    }, [removeSuperWideRHPRouteKey, removeWideRHPRouteKey, route]);

    Because the topmost route is still RIGHT_MODAL_NAVIGATOR (the new Create‑expense RHP we just navigated to), the guard returns early and expandedRHPProgress keeps its previous value (1 or 2). The eventual reset happens later through the syncRHPKeys effect, but that effect runs after the next commit — one render too late.

    For that one render the RightModalNavigator renders its container at the stale wide width, so the new narrow Create‑expense screen sits inside a container that's much wider than singleRHPWidth. Since the container is right: 0, the extra width pushes the visible card left of the screen's right edge → "RHP misaligns to the left". Doing the flow slowly lets syncRHPKeys flush before the next RHP mounts, which is why the bug only reproduces when the FAB is clicked quickly.

    What changes do you think we should make in order to solve the problem?

    The navigation‑state guard is the wrong gate — the correct gate is "are there any remaining wide/super‑wide route keys after this unmount". I'd compute expandedRHPProgress from the latest route‑key arrays inside the close callback so it's applied synchronously in the same frame as the route‑key removal, instead of waiting for syncRHPKeys to fire on the next commit.

    Concretely, expose the latest allWideRHPRouteKeys / allSuperWideRHPRouteKeys from the provider (via refs so they stay in sync without retriggering useCallback), and use them in the close handler:

    In src/components/WideRHPContextProvider/index.tsx keep refs alongside the existing state and expose them through the actions context:

    - const [allWideRHPRouteKeys, setAllWideRHPRouteKeys] = useState<string[]>([]);
    - const [allSuperWideRHPRouteKeys, setAllSuperWideRHPRouteKeys] = useState<string[]>([]);
    + const [allWideRHPRouteKeys, setAllWideRHPRouteKeys] = useState<string[]>([]);
    + const [allSuperWideRHPRouteKeys, setAllSuperWideRHPRouteKeys] = useState<string[]>([]);
    + const allWideRHPRouteKeysRef = useRef(allWideRHPRouteKeys);
    + const allSuperWideRHPRouteKeysRef = useRef(allSuperWideRHPRouteKeys);
    + allWideRHPRouteKeysRef.current = allWideRHPRouteKeys;
    + allSuperWideRHPRouteKeysRef.current = allSuperWideRHPRouteKeys;

    Add a new action syncExpandedRHPProgressAfterRemoval(route) to the actions context that recomputes the progress from the refs minus the removed key, then replace the broken guard in both close hooks:

      const onSuperWideRHPClose = useCallback(() => {
          removeWideRHPRouteKey(route);
          removeSuperWideRHPRouteKey(route);
    -     // When the RHP has been closed, expandedRHPProgress should be set to 0.
    -     if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
    -         expandedRHPProgress.setValue(0);
    -     }
    +     // Recompute progress synchronously from the latest route-key snapshot so the
    +     // next RHP screen doesn't render against a stale wide container width.
    +     syncExpandedRHPProgressAfterRemoval(route);
      }, [removeSuperWideRHPRouteKey, removeWideRHPRouteKey, route, syncExpandedRHPProgressAfterRemoval]);

    The new action body in the provider uses the refs + the existing getVisibleRHPKeys + setExpandedRHPProgress helpers, e.g.:

    const syncExpandedRHPProgressAfterRemoval = useCallback((route: NavigationRoute) => {
        const wideAfter = allWideRHPRouteKeysRef.current.filter((key) => key !== route.key);
        const superAfter = allSuperWideRHPRouteKeysRef.current.filter((key) => key !== route.key);
        const {visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys} = getVisibleRHPKeys(superAfter, wideAfter);
        setExpandedRHPProgress(visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys);
    }, []);

    The same change is applied to onWideRHPClose in useShowWideRHPVersion/index.ts. The deferred syncRHPKeys effect remains as a safety net (no behavior change for screens that don't navigate to another RHP), so we keep one source of truth for the calculation.

    After the fix, when the user goes from a wide expense report straight into the narrow Create‑expense RHP, expandedRHPProgress is reset to 0 in the same frame the previous screen unmounts, and the new container mounts at singleRHPWidth — no left‑shift.

    What alternative solutions did you explore? (Optional)

    • Always reset expandedRHPProgress to 0 on close. Simpler, but breaks the legitimate stacking case (e.g., a narrow sub‑RHP closing while a wide RHP is still mounted underneath) — the container would briefly collapse to singleRHPWidth before the underlying wide RHP re‑expands it, causing a different visual glitch.
    • Make RightModalNavigator re‑measure the topmost route on each render and ignore expandedRHPProgress when the focused screen isn't registered as wide. That decouples container width from the global progress value, but it duplicates the wide/super‑wide bookkeeping the provider already owns and would require equivalent plumbing in SecondaryOverlay/the modal stack overlays, so the cost outweighs the benefit.
    • Flush the React state update via flushSync inside removeWideRHPRouteKey/removeSuperWideRHPRouteKey. Would force syncRHPKeys to run before the next paint, but flushSync during an unmount commit is fragile and easy to regress; computing the new progress directly from refs is more predictable.
  8. mukhrr commented on May 25, 2026

    @mukhrr
    Contributor

    Proposal

    What is the root cause of that problem?

    The RHP container width and the per-screen card interpolator both depend on a piece of context state (wideRHPRouteKeys / expandedRHPProgress) that lags behind the actual navigation transition by one or two render cycles. When the user creates a per-diem expense and immediately taps FAB again, the new "create expense" RHP mounts while that stale "a wide RHP is still beneath me" signal is still set, so the navigator container is sized for the wide layout and the new card animates in with the half-width interpolator. The card ends up rendered in the left half of a wide container.

    The lag has a concrete cause: the wide route key is only removed from the context at component unmount time, not when navigation pops the route.

    src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts#L19-L30:

    const onWideRHPClose = useCallback(() => {
        removeWideRHPRouteKey(route);
        if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
            expandedRHPProgress.setValue(0);
        }
    }, [removeWideRHPRouteKey, route]);
    
    // Effect that sets up cleanup when the screen is unmounted.
    useEffect(() => () => onWideRHPClose(), [onWideRHPClose]);

    The cleanup runs in a destructor effect — React only fires that destructor after the navigator unmounts the screen, which in @react-navigation/stack happens after the slide-out animation finishes (or after the next frame in detach-on-pop). Meanwhile the new RHP's first render reads stale state:

    Concrete sequence on the repro:

    1. User completes the per-diem expense. The wide/super-wide report RHP is now the top route. wideRHPRouteKeys = [W], expandedRHPProgress = 1 or 2, container width = wide.
    2. User taps FAB. Navigation pops the wide route and pushes the new narrow NEW_REQUEST route — but the wide screen is still mounted because its slide-out animation is in flight.
    3. The new narrow RHP's first render runs. wideRHPRouteKeys.length is still 1 → shouldAdjustInterpolatorProps is truthy → its cardStyleInterpolator divides layout width by 2. expandedRHPProgress is still 1 → container width is still wide.
    4. The new card's forHorizontalIOS interpolator slides it in from the middle of the wide container, lands at translateX=0, and stays positioned in the left half of the wide container.
    5. Eventually the wide screen actually unmounts; cleanup fires; wideRHPRouteKeys empties; setExpandedRHPProgress(0) runs; the container shrinks back to singleRHPWidth. But the inner card is already laid out left-aligned inside its old container box. There is no second pass that re-positions it.

    This is why the misalignment is intermittent (timing-dependent) and reproduces only on quick taps — the user has to win the race between the wide RHP's unmount and the new RHP's first render.

    The same shape lurks in other rapid-RHP-switch flows (search → expense report → search again) and is the same family of issue described in #78440 (overlay press during the closing-but-not-unmounted window), so fixing the cleanup timing here also tightens the broader RHP teardown story.

    What changes do you think we should make in order to solve the problem?

    Move the wide-route cleanup off the React unmount effect onto react-navigation's beforeRemove listener, so it fires synchronously when navigation pops the route, before the next render of the navigator. By the time the new narrow RHP's useRHPScreenOptions and RightModalNavigator read the context on their first render, wideRHPRouteKeys is already empty and expandedRHPProgress has been reset.

    Core fix in src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts:

    -import {useRoute} from '@react-navigation/native';
    -import {useCallback, useEffect} from 'react';
    +import {useNavigation, useRoute} from '@react-navigation/native';
    +import {useCallback, useEffect} from 'react';
     import {navigationRef} from '@libs/Navigation/Navigation';
     import NAVIGATORS from '@src/NAVIGATORS';
     import {expandedRHPProgress, useWideRHPActions} from '..';
    
     function useShowWideRHPVersion(condition: boolean) {
         const route = useRoute();
    +    const navigation = useNavigation();
         const reportID = route.params && 'reportID' in route.params && typeof route.params.reportID === 'string' ? route.params.reportID : '';
         const {showWideRHPVersion, removeWideRHPRouteKey, isReportIDMarkedAsExpense} = useWideRHPActions();
    
         const onWideRHPClose = useCallback(() => {
             removeWideRHPRouteKey(route);
             // When the RHP has been closed, expandedRHPProgress should be set to 0.
             if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
                 expandedRHPProgress.setValue(0);
             }
         }, [removeWideRHPRouteKey, route]);
    
    -    /**
    -     * Effect that sets up cleanup when the screen is unmounted.
    -     */
    -    useEffect(() => () => onWideRHPClose(), [onWideRHPClose]);
    +    /**
    +     * Clean up wide-RHP state *when navigation pops the route*, not when the screen
    +     * unmounts. The unmount fires after the slide-out animation; if the user opens
    +     * another RHP during that window, the new screen's first render reads stale
    +     * `wideRHPRouteKeys` / `expandedRHPProgress` and is laid out for the wide
    +     * container, producing the left-aligned card seen in #91610.
    +     *
    +     * The unmount destructor stays as a safety net for screens that disappear
    +     * without a `beforeRemove` event (e.g. a `reset()` that replaces the stack).
    +     */
    +    useEffect(() => {
    +        const unsubscribe = navigation.addListener('beforeRemove', onWideRHPClose);
    +        return () => {
    +            unsubscribe();
    +            onWideRHPClose();
    +        };
    +    }, [navigation, onWideRHPClose]);

    Supporting bits (no separate diffs needed):

    • The beforeRemove listener fires synchronously during the navigation dispatch, so setAllWideRHPRouteKeys runs before the new route's screen options memoize. The useEffect → syncRHPKeys → setExpandedRHPProgress(0) chain then completes in the same scheduler tick as the new route's first commit, which is what we want.
    • The unmount-time call is kept as a safety net (the return of the effect still calls onWideRHPClose). removeWideRHPRoute is already idempotent (it filters by key and only writes when the key is present, WideRHPContextProvider/index.tsx#L75-L83), so the second call is a no-op when beforeRemove already ran.
    • The same fix applies one-for-one in src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts#L20-L34 — the super-wide variant has the exact same unmount-time cleanup and the same race. Easiest to ship both together.
    • A focused regression test in tests/unit/: render two RHP screens back-to-back (close the wide one, immediately mount a narrow one in the same task), assert the narrow's useRHPScreenOptions returns the forHorizontalIOS interpolator without the half-width adjustment.

    What alternative solutions did you explore?

    • Defer the new RHP's first render with InteractionManager.runAfterInteractions. Reduces the race window but doesn't close it — InteractionManager is best-effort and adds a visible frame of latency on every open. The beforeRemove listener is deterministic and free.
    • Bind shouldAdjustInterpolatorProps to react-navigation's state.routes directly (read the route directly below the new card and check if its name is in ALL_WIDE_RIGHT_MODALS). Cleaner long-term and removes the parallel state in WideRHPContextProvider for this purpose, but it's a much bigger refactor and there are other consumers of wideRHPRouteKeys (SecondaryOverlay, expandedRHPProgress driver) that would each need migration. Out of scope for a $250 misalignment fix; worth a follow-up issue.
    • Clear keys in a layout effect on the new RHP's mount (call syncRHPKeys() from the new card's useLayoutEffect). Backwards plumbing — it makes every narrow RHP responsible for cleaning up after the wide one. The fix belongs on the closing side, not the opening side.
    • Use InteractionManager to defer removeWideRHPRouteKey to a later frame and freeze the container during that window. Same problem in reverse — adds latency to a fast path to fix a slow path, and complicates an already-busy state machine.
  9. melvin-bot commented on May 25, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @mananjadhav (External)

  10. Abdukhamid000 commented on May 25, 2026

    @Abdukhamid000
    Contributor

    Proposal

    What is the root cause of that problem?

    The wide-RHP width survives the previous RHP's close when the user reopens fast enough. The container width is driven by the singleton expandedRHPProgress (an Animated.Value), and the per-screen cleanup that should reset it has a guard that intentionally skips the reset when another RHP is already on top — but the cleanup runs on a React useEffect cleanup (async), so a fast reopen lands a new RHP on top of the stack before the previous RHP's wide key is removed from state. The result: the new RHP mounts with expandedRHPProgress === 1 (or 2), the container renders at getWideRHPWidth(windowWidth) instead of singleRHPWidth, and the panel sits left of the right edge.

    The hot path:

    [RightModalNavigator.tsx:135-144](https://github.com/Expensify/App/blob/main/src/libs/Navigation/AppNavigator/Navigators/RightModalNavigator.tsx#L135-L144):

    const animatedWidth = expandedRHPProgress.interpolate({
        inputRange: [0, 1, 2],
        outputRange: [singleRHPWidth, getWideRHPWidth(windowWidth), calculateSuperWideRHPWidth(windowWidth)],
    });
    const animatedWidthStyle = useMemo(() => ({width: shouldUseNarrowLayout ? '100%' : animatedWidth}), [animatedWidth, shouldUseNarrowLayout]);

    The cleanup at [useShowWideRHPVersion/index.ts:19-30](https://github.com/Expensify/App/blob/main/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts#L19-L30):

    const onWideRHPClose = useCallback(() => {
        removeWideRHPRouteKey(route);                                                   // setState (async)
        if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
            expandedRHPProgress.setValue(0);
        }
    }, [removeWideRHPRouteKey, route]);
    useEffect(() => () => onWideRHPClose(), [onWideRHPClose]);

    …and the resync at [WideRHPContextProvider/index.tsx:146-163](https://github.com/Expensify/App/blob/main/src/components/WideRHPContextProvider/index.tsx#L146-L163):

    const syncRHPKeys = useCallback(() => {
        const {visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys} = getVisibleRHPKeys(allSuperWideRHPRouteKeys, allWideRHPRouteKeys);
        ...
        setExpandedRHPProgress(visibleSuperWideRHPRouteKeys, visibleWideRHPRouteKeys);
    }, [allSuperWideRHPRouteKeys, allWideRHPRouteKeys]);
    
    useEffect(() => { syncRHPKeys(); }, [allSuperWideRHPRouteKeys, allWideRHPRouteKeys, syncRHPKeys]);

    Walking the repro — FAB → Create expense → Per Diem → submit → quickly FAB again:

    1. The per-diem create screen mounts, hits useShowWideRHPVersion(true) for the per-diem flow, pushes its route.key into allWideRHPRouteKeys, setExpandedRHPProgress sees a non-empty list, animates expandedRHPProgress to 1. Container grows to wide.
    2. User submits; the per-diem screen unmounts. The useEffect cleanup runs → removeWideRHPRouteKey(route) queues a setAllWideRHPRouteKeys((prev) => prev.filter(...)). The guard then checks the live navigation state — if the user has already tapped FAB, a new RHP is already topmost, so expandedRHPProgress.setValue(0) is skipped. The singleton stays at 1.
    3. The new RHP mounts. <Animated.View> evaluates animatedWidth against the current expandedRHPProgress = 1, container renders at getWideRHPWidth(windowWidth).
    4. React eventually flushes the queued setAllWideRHPRouteKeys → syncRHPKeys runs → empty list → setExpandedRHPProgress(...) → setValue(0). The container animates back to single width.

    Between steps 3 and 4, the user sees a wide-then-shrink. If the new RHP itself never triggers useShowWideRHPVersion (the create-expense chooser is single-width), the misalignment is the visible end state for a frame or two; if they fire off another per-diem before step 4, the stale 1 is reinforced and the panel stays misaligned until the queue catches up.

    The guard at line 22-24 was added for legitimate nested-RHP cases (close a narrow child to reveal a wide parent) — without it we'd shrink the underlying wide RHP. But the guard's "is there any RHP on top?" question is too coarse: it can't distinguish "a wide one we should preserve" from "a fresh one with no wide tracking yet."

    What changes do you think we should make in order to solve the problem?

    Replace the topmost-route guard with a "are there any wide routes left tracked?" check, fed from a ref the provider keeps in sync with its state so it's readable synchronously inside the unmount cleanup.

    1. Mirror allWideRHPRouteKeys and allSuperWideRHPRouteKeys into refs in WideRHPContextProvider. Update both refs alongside every setAllWideRHPRouteKeys / setAllSuperWideRHPRouteKeys call so the latest list is readable synchronously:

     const [allWideRHPRouteKeys, setAllWideRHPRouteKeys] = useState<string[]>([]);
    +const allWideRHPRouteKeysRef = useRef<string[]>([]);
    @@
    +function commitAllWideRHPRouteKeys(updater: (prev: string[]) => string[]) {
    +    setAllWideRHPRouteKeys((prev) => {
    +        const next = updater(prev);
    +        allWideRHPRouteKeysRef.current = next;
    +        return next;
    +    });
    +}

    (Same shape for the super-wide list.) Then showWideRHPRoute / removeWideRHPRoute route through commitAllWideRHPRouteKeys instead of calling setAllWideRHPRouteKeys directly.

    Expose the refs through the context so per-screen hooks can read them:

     return {
    -    allWideRHPRouteKeys,
    +    allWideRHPRouteKeys,
    +    getAllWideRHPRouteKeys: () => allWideRHPRouteKeysRef.current,
    +    getAllSuperWideRHPRouteKeys: () => allSuperWideRHPRouteKeysRef.current,
         ...
     };

    2. Tighten the cleanup guard in useShowWideRHPVersion to use the live refs instead of the navigator-state check:

    +const {getAllWideRHPRouteKeys, getAllSuperWideRHPRouteKeys} = useWideRHPActions();
    
     const onWideRHPClose = useCallback(() => {
         removeWideRHPRouteKey(route);
    -    // When the RHP has been closed, expandedRHPProgress should be set to 0.
    -    if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) {
    -        expandedRHPProgress.setValue(0);
    -    }
    -}, [removeWideRHPRouteKey, route]);
    +    // After removing this route, if no other wide/super-wide routes are tracked,
    +    // immediately reset the singleton. The previous guard checked whether *any* RHP
    +    // was topmost, which is true when the user reopens FAB before this cleanup
    +    // flushes — so the new (single-width) RHP inherited stale wide state.
    +    const remainingWide = getAllWideRHPRouteKeys().filter((key) => key !== route.key);
    +    const remainingSuperWide = getAllSuperWideRHPRouteKeys().filter((key) => key !== route.key);
    +    if (remainingWide.length === 0 && remainingSuperWide.length === 0) {
    +        expandedRHPProgress.setValue(0);
    +    }
    +}, [removeWideRHPRouteKey, route, getAllWideRHPRouteKeys, getAllSuperWideRHPRouteKeys]);

    (Filter against route.key because removeWideRHPRouteKey was just called — the ref will reflect that on the next event-loop tick but we want the post-removal answer right now.)

    After this change, the nested-RHP case still works: closing a narrow child of a wide parent leaves the parent's key in getAllWideRHPRouteKeys(), so expandedRHPProgress stays at 1. The fast-reopen case is fixed: the closing per-diem RHP's key is the only wide one tracked, the filter returns an empty list, and we reset to 0 before the new RHP renders.

    3. Belt and suspenders: re-sync on focus. The useFocusEffect in RightModalNavigator already calls syncRHPKeys on focus; that path stays. But because the new RHP can render before its useFocusEffect fires, also have the RHP container compute its initial width from the current keys synchronously on mount — easiest done by reading the ref in useMemo for the first frame:

    -const animatedWidthStyle = useMemo(() => {
    -    return {width: shouldUseNarrowLayout ? '100%' : animatedWidth} as const;
    -}, [animatedWidth, shouldUseNarrowLayout]);
    +const animatedWidthStyle = useMemo(() => {
    +    // If the singleton is stale at mount time (no wide keys tracked yet for this RHP), pin to
    +    // single width for the first frame. The Animated.Value will animate it up if a wide screen
    +    // mounts inside.
    +    return {width: shouldUseNarrowLayout ? '100%' : animatedWidth} as const;
    +}, [animatedWidth, shouldUseNarrowLayout]);
    +useLayoutEffect(() => {
    +    if (getAllWideRHPRouteKeys().length === 0 && getAllSuperWideRHPRouteKeys().length === 0) {
    +        expandedRHPProgress.setValue(0);
    +    }
    +}, [getAllWideRHPRouteKeys, getAllSuperWideRHPRouteKeys]);

    The useLayoutEffect runs before paint, so the container's width is correct on the very first frame the new RHP shows — even if the previous unmount cleanup hasn't fully flushed.

    I'd add a regression test that programmatically opens an RHP, registers it as wide via useShowWideRHPVersion(true), immediately unmounts it, and synchronously mounts a second RHP — assert that expandedRHPProgress.__getValue() is 0 when the second RHP's render begins.

    What alternative solutions did you explore?

    • Drop the guard entirely (always setValue(0) on close). Fixes this bug but breaks the nested-RHP case where a narrow child closes back to a wide parent — the parent would shrink for one frame before the parent's useShowWideRHPVersion re-runs. The ref-backed remaining-count check gives us both behaviors.
    • useLayoutEffect instead of useEffect for the cleanup. Tempting because layout effects flush sync, but the cleanup is triggered by unmount, which already runs synchronously enough for the setValue line — the actual race is the React setState inside removeWideRHPRouteKey, which neither effect timing can flush before the next render.
    • Debounce or requestAnimationFrame-delay FAB taps. Trades the bug for input lag. The right fix is to keep the wide-progress singleton consistent with the actual set of tracked wide routes.
    • Recompute width inside the RHP from navigation state instead of a shared Animated.Value. A bigger refactor; the shared singleton enables smooth cross-RHP transitions (open a wide RHP on top of a single one and the panel grows in one continuous animation), which we'd lose.
  11. lxyct825-ops commented on May 25, 2026

    @lxyct825-ops

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  12. 76 remaining items

  13. mananjadhav commented on Aug 20, 2026

    @mananjadhav
    Collaborator

    This one is ready for payout soon. The checklist is complete.

  14. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on Aug 20, 2026
  15. melvin-bot commented on Aug 20, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  16. melvin-bot commented on Aug 20, 2026

    @melvin-bot

    Payment Summary

    Resolving PRs:

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  17. mallenexpensify commented on Aug 21, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @annaweber830 paid $250 via Upwork
    Contributor+: @mananjadhav due $250 via NewDot

    @annaweber830 can you please accept the job below? Please reply here and tag me once you have.
    If you're not sent an offer in Upwork when you're assigned to an issue, please tag me. If an Upwork job exists, please submit a proposal.
    https://www.upwork.com/jobs/~022090946611026269843

  18. annaweber830 commented on Aug 25, 2026

    @annaweber830
    Contributor

    Thanks, @mallenexpensify. I've accepted the offer.

  19. garrettmknight commented on Aug 25, 2026

    @garrettmknight
    Contributor

    $250 approved for @mananjadhav

  20. mallenexpensify commented on Aug 25, 2026

    @mallenexpensify
    Contributor

    @annaweber830 paid, summary updated above. Thx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions