Skip to content

[$250] Rules - Description bar is not correctly centered after user focus back on #106059

Open

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.32-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: #105457
Email or phone of affected tester (no customers): winnaire@gmail.com
Issue reported by: Applause Internal Team
Bug source: Pull Request QA execution
Device used: Pixel 7 pro / Android 16
App Component: Workspace Settings

Action Performed:

  1. Open https://staging.new.expensify.com/
  2. Open Workspace, and Select 'Rules'
  3. Tap on 'Add rule' at top left
  4. Locate 'Or just describe it below' section and tap to expand keyboard
  5. Insert 'Text the approver's phone whenever a report is submitted' and tap on 'Next'
  6. While keyboard is still expanded swipe to top so the previous section is out of range
  7. Tap anywhere in keyboard to insert a keyword and focus again on previous section

Expected Result:

The user should be scrolled to where the caret position is

Actual Result:

The user is not correctly to where the caret is positioned

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7305366_1793839636267.PR_105457_fail.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Julia Ponikarchuk
Bug ID: 7305366

Upwork Automation - Do Not Edit

Activity

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

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    Medium confidence: the description restores its visibility on focus, but not when typing resumes in an already-focused field. Scrolling away with the keyboard open need not blur the input, so subsequent typing does not trigger the existing scroll handler. This explains why the caret can remain off-screen.

    Code evidence and alternatives checked

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

    Add local visibility recovery when the description is edited while focused, limited to the scrolling form. Reveal the caret when obscured, preserve intentional scrolling until editing resumes, and coalesce requests to avoid jumping on every keystroke. Keep the existing initial-focus and refusal scrolling; preserve form value/draft handling.

    Validation required
    • Add a regression test that edits without firing another focus event. The current input mock:123–145 forwards only focus and cannot exercise this scenario.
    • Verify the exact sequence on Android and iOS, both before submission and after refusal. Include long multiline text, rapid typing, and the non-scrolling Describe modal. Scrolling to the box’s top alone must not be assumed to reveal every caret position.
    • Web verification was blocked by a Control-plan upgrade dialog before reaching the description. No caret failure or fix was verified; desktop web also cannot establish native software-keyboard behavior. No code changes were made.

    What alternative solutions did you explore? (Optional)

    Another focus-only handler cannot cover retained-focus typing. Dismissing the keyboard changes the intended editing flow rather than fixing caret visibility. A shared scrolling overhaul is broader than this issue currently warrants.

    Related issues: New rule scrolls in two jumps when the describe box gets focus and App does not scroll down to Describe field when field is focused concern initial focus; they are related, not confirmed duplicates of this resumed-editing case.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106059) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.


    view run

  3. MelvinBot commented on Nov 5, 2026

    @MelvinBot
    Contributor

    🤖 Web test steps verification results: ⚠️ partial

    Verified app access and Workspace Rules navigation on dev NewDot web. Add rule opened a Control-plan upgrade dialog, blocking form and caret checks; native keyboard behavior cannot be verified on desktop web.

    Control-plan upgrade dialog displayed after clicking Add rule

    Step Status
    Open appAuthenticated Home screen rendered.
    ✅
    Workspace > RulesCreated a workspace, enabled Rules, and opened the Rules page.
    ✅
    Add ruleClicked Add rule, but reached a Control-plan upgrade dialog rather than the rule form. No upgrade was authorized.
    Control-plan upgrade dialog displayed after clicking Add rule
    ⚠️
    Focus 'Or just describe it below'Blocked by the upgrade dialog; description field was not reached.
    ⚠️
    Enter "Text the approver's phone whenever a report is submitted" and press NextBlocked because the rule form was not reached.
    ⚠️
    Scroll away while preserving focus and keeping the keyboard expandedBlocked before description entry. Native keyboard expansion is also unverifiable on desktop web.
    ⚠️
    Type again and verify caret visibilityBlocked before description entry; caret behavior was not observed.
    ⚠️

    view run · view recording

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Nov 5, 2026
  5. melvin-bot commented on Nov 5, 2026

    @melvin-bot

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

  6. changed the title [-]Rules - Description bar is not correctly centered after user focus back on[/-] [+][$175] Rules - Description bar is not correctly centered after user focus back on[/+] on Nov 5, 2026
  7. melvin-bot commented on Nov 5, 2026

    @melvin-bot
  8. khizzcr7 commented on Nov 5, 2026

    @khizzcr7

    Problem: In Workspace > Rules > Add rule, after typing a description and scrolling away while the keyboard stays open, tapping back into the description and typing again leaves the caret off-screen instead of scrolling the form to it.

    Root cause: In src/pages/workspace/rules/DescribeRuleForm.tsx, scrolling is attached only to focus: the description input has onFocus={scrollToInput}, and scrollToInput scrolls the form to the input container's top (inputTopOffsetRef from the container's onLayout). Scrolling away with the keyboard open does not blur the input, so typing again fires no focus event and no scroll runs — the caret can sit hidden below the keyboard or above the viewport. Even on focus, the scroll targets the container top, not the caret line.

    Fix:

    1. Reuse the existing scroll machinery on edit as well as focus: call scrollToInput from onChangeText/onSelectionChange on the description input, coalesced (e.g. via requestAnimationFrame or a short debounce) so it does not jump on every keystroke.
    2. Scroll to the caret, not just the container top: use the selection start from onSelectionChange to compute the caret line's offset and scroll that line above the keyboard, falling back to the existing container-top scroll when no selection is available.
    3. Only scroll when the caret is actually obscured (below the keyboard top or above the viewport), so intentional manual scrolling is preserved until editing resumes. Keep the existing initial-focus scroll and the refusal scroll untouched.

    Verification: Reproduce the exact steps (add rule, type a description, scroll away with the keyboard open, tap back in and type) and confirm the caret stays visible; confirm normal typing does not jump; confirm the refusal flow still scrolls to the refused rule. Add a regression test that edits the description without firing another focus event and asserts the scroll runs.

  9. camesenin commented on Nov 5, 2026

    @camesenin
  10. melvin-bot commented on Nov 5, 2026

    @melvin-bot

    ✅ Contributor details stored successfully. Thank you for contributing to Expensify!

  11. vanshshah11 commented on Nov 5, 2026

    @vanshshah11

    Proposal for Issue #106059 — Rules description bar not centered after focus ($175)

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

    In Workspace → Rules → "Create a rule" form, when the user taps on a text input (e.g. the rule name or description field), the form scrolls to make the input visible (scrollToInput). However, the description bar does not remain centered/near the input — after the field gains focus and the form scrolls, the field's label/title bar is positioned off-screen or mis-aligned vertically, so the user can't see what they're typing into.

    What is the root cause of that problem?

    In src/pages/workspace/rules/DescribeRuleForm.tsx:

    • Line 301: const scrollToInput = () => formRef.current?.scrollTo(inputTopOffsetRef.current);
    • Line 363: onFocus={scrollToInput}

    The scrollToInput function is called only on onFocus. The problem is that onFocus fires once — when the input first gains focus. But the form may be scrolled by the system (keyboard avoidance), or the user may scroll manually. When the user taps another input lower on the form, the onFocus fires for that field, BUT:

    1. The scroll offset stored in inputTopOffsetRef (line 297) is set by onLayout of the input's container — but onLayout gives coordinates relative to the parent ScrollView, not accounting for the current scroll position of the keyboard avoidance view.

    2. The scrollTo(inputTopOffsetRef.current) uses the raw layout offset. If the keyboard is already visible (from a previously focused field), the form has already been scrolled by the keyboard-avoidance system. Scrolling to the raw inputTopOffset value without adjusting for the keyboard height leads to the input being positioned at the top of the visible area (or even partially hidden behind the keyboard) rather than centered.

    The core issue: scrollToInput does not account for the visible viewport height after keyboard avoidance has already shifted the scroll position. It scrolls to a fixed offset calculated from the field's position within the form, not from the field's actual visible position.

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

    Use scrollToInput correctly — instead of scrolling to a fixed offset, use formRef.current?.scrollTo({y: inputTopOffsetRef.current, animated: true}) and additionally ensure the input is centered in the visible area by accounting for the keyboard height.

    Specifically:

    1. Track the keyboard height (via KeyboardAvoidingView behavior or a useKeyboardHeight hook which is already available in the codebase).

    2. In scrollToInput, compute the target scroll position so that the input field is vertically centered in the area above the keyboard:

    const scrollToInput = () => {
        const keyboardHeight = keyboardHeightRef.current;
        const inputTop = inputTopOffsetRef.current;
        const formHeight = formRef.current?.getScrollHeight?.() ?? 0;
        const visibleHeight = Dimensions.get('window').height - keyboardHeight;
        const targetOffset = Math.max(0, inputTop - (visibleHeight / 2));
        formRef.current?.scrollTo({y: targetOffset, animated: true});
    };
    1. Also call scrollToInput on onContentSizeChange or onKeyPress so that if the field is already focused (no new onFocus fires) the form re-scrolls correctly.

    What specific scenarios should be covered by automated tests?

    • When an input gains focus and keyboard appears, the input should be visible and centered in the viewport above the keyboard
    • When switching between inputs in the form, each one should be properly scrolled into view
    • When the keyboard is dismissed and a field is tapped again, the input should be centered

    What alternative solutions did you explore?

    1. Using KeyboardAvoidingView with behavior="padding" — Already in use but alone doesn't provide centering; it only ensures the field is visible. The issue specifically asks for better positioning than just "visible."

    2. Using scrollToFocusedInput from React Native's ScrollViewTextInput — Not available in this codebase's setup.

    PR

    PR will be linked here once created.

  12. 36 remaining items

  13. TassioSales commented on Nov 18, 2026

    @TassioSales

    @situchan Just following up on this issue: my proposal above remains fully verified and active. The root cause in DescribeRuleForm.tsx (handling focus-back and keyboard offset adjustments during caret repositioning) is isolated and ready for immediate PR branch creation whenever you are ready to assign. Thanks!

  14. github-actions commented on Nov 18, 2026

    @github-actions
    Contributor

    ⚠️ @TassioSales Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

  15. expensify-chore-bot commented on Nov 18, 2026

    @expensify-chore-bot

    @situchan Eep! 4 days overdue now. Issues have feelings too...

  16. laveshfonix commented on Nov 19, 2026

    @laveshfonix
    Contributor

    Proposal

    What is the root cause of that problem?

    The box is scrolled into view only when it gets focus. Swiping keeps the box focused and the keyboard open, so typing or tapping it again fires no focus or keyboard event, and nothing scrolls it back.

    1. scrollToInput runs only from onFocus:

      // On iOS and Android, the keyboard covers the focused input unless the form scrolls to it. The scroll stops at the end of
      // the content, therefore the submit button below the input also stays in view when it fits.
      const scrollToInput = () => formRef.current?.scrollTo(inputTopOffsetRef.current);

      onFocus={scrollToInput}

    2. A tap on the box calls focus() again, and React Native ignores focus() on an input that already has focus, so no onFocus comes:

      const onPress = (event?: GestureResponderEvent | KeyboardEvent) => {
      if (!!inputProps.disabled || !event) {
      return;
      }
      inputProps.onPress?.(event);
      if ('isDefaultPrevented' in event && !event?.isDefaultPrevented()) {
      input.current?.focus();
      }

    3. Nothing else scrolls to the caret. iOS doesn't for this scroll view, and on Android Stop the New rule page from scrolling twice on Android #105662 turned the native scroll off, so a key press moves nothing:

      // scrollToInput moves the whole box above the keyboard. If Android also moves the box, the page moves two times.
      shouldScrollChildToFocus={false}

      When this was reported (9.5.32), Android still had that scroll, but it stops once the caret line reaches the keyboard. That is the small move in the video.

    #106343 (Android's back button closes the keyboard and the box keeps focus) is fixed by the approved #107088, which scrolls when the keyboard opens again. Here the keyboard never closes, so it doesn't help: with #107088 on Android, typing and tapping after the swipe still leave the box covered (2/2 each).

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

    Add a reusable hook, useRevealInputAboveKeyboard (the review of #106803 asked for a separate hook and an animated scroll). The box gets onValueChange={revealInput} and onPress={revealInputOnPress}, and its View gets the hook's ref and onTouchStart={rememberInputTopAtTouchStart}. When the admin types or taps, the hook scrolls to the box only if the open keyboard covers it:

    const revealInput = () => {
        if (!inputRef.current?.isFocused() || keyboardHeightRef.current === 0) {
            return;
        }
        const keyboardTop = windowHeight - keyboardHeightRef.current;
        inputContainerRef.current?.measureInWindow((x, y, width, height) => {
            // A scroll to the input is already on its way, or the input is fully above the keyboard
            if (Date.now() < revealEndTimeRef.current || y + height <= keyboardTop) {
                return;
            }
            revealEndTimeRef.current = Date.now() + REVEAL_DURATION_MS;
            scrollToInput();
        });
    };
    
    const rememberInputTopAtTouchStart = () => {
        inputContainerRef.current?.measureInWindow((x, y) => {
            inputTopAtTouchStartRef.current = y;
        });
    };
    
    // A swipe that starts on the input ends its press too, and scrolling back then would pull the page against the finger.
    // The page moves under the finger during a swipe, before or right after the press ends, so only a press after which the
    // input is still where the touch started is a tap.
    const revealInputOnPress = () => {
        clearTimeout(pressCheckTimeoutRef.current);
        const inputTopAtTouchStart = inputTopAtTouchStartRef.current;
        pressCheckTimeoutRef.current = setTimeout(() => {
            inputContainerRef.current?.measureInWindow((x, y) => {
                if (inputTopAtTouchStart === undefined || Math.abs(y - inputTopAtTouchStart) > SWIPE_DISTANCE) {
                    return;
                }
                revealInput();
            });
        }, CONST.ANIMATION_IN_TIMING);
    };
    • A finger that rests on the box and then swipes isn't a tap. The swipe ends the box's press too, sometimes while the box is still covered. A check at that moment pulls the page back against the finger. So a press counts only if, 100 ms after it ends, the box is still where it was when the touch started.
    • No scroll for a keyboard that opens. The keyboard height comes from the same react-native-keyboard-controller events that withKeyboardState uses, and stays 0 while the keyboard opens. That scroll stays with the focus scroll or Restore Describe Rule scrolling when Android keyboard reopens #107088's reopen scroll, so Back then a tap moves the page once.
    • One scroll for fast typing. Keys during a running scroll (300 ms) don't start it again.
    • No wait. The keyboard is already open, so the form passes () => scrollToInput(false) to the hook, using the option Restore Describe Rule scrolling when Android keyboard reopens #107088 adds to skip the 300 ms keyboard wait.

    The hook only takes a scroll callback. If #106203 (in review) lands first, the callback becomes its scrollWithKeyboard, which scrolls right away when the keyboard is open. On web the hook does nothing.

    Tests:

    • useRevealInputAboveKeyboardTest: 11 cases. Each of these fails its own case when removed or changed: the swipe check (both timings), the covered check, the keyboard-open check, the one-scroll window, the focus check, the reset when the keyboard closes, the timer cleanup, and a tap whose press ends twice (as on iOS).
    • RulesNewPageDescribeRuleTest: typing, touching and tapping the box call the hook, its ref is attached, and its scroll doesn't wait for the keyboard.
    • 99 tests in the 7 describe-rule and form suites pass, with Restore Describe Rule scrolling when Android keyboard reopens #107088 applied.

    What I ran: dev builds of main with #107088 applied (this patch applies cleanly on top of it), on the iOS simulator (iPhone 17 Pro, iOS 26.5, software keyboard) and the Android emulator (Pixel, Android 16). Taps, swipes and typing were real touches (XCUITest on iOS, adb on Android). After each step I read the box's and the keyboard's position. The middle columns are my own minimal versions of approaches posted here, not those patches.

    Box has focus, keyboard open main + #107088 scroll on every tap and key check at the tap or key this change
    Swipe it under the keyboard, then type covered: iOS 3/3, Android 2/2 in view: iOS 1/1 in view: iOS 1/1 in view: iOS 3/3, Android 3/3
    Swipe so only its top shows, then tap it covered: iOS 3/3, Android 2/2 in view: iOS 3/3 in view: iOS 3/3 in view: iOS 3/3, Android 3/3
    Finger rests on the half-covered box, then swipes down page stays: iOS 3/3 pulled back: iOS 3/3, Android 2/2 pulled back: iOS 3/3, Android 5/5 page stays: iOS 3/3, Android 2/2
    Same, as a slow drag without a fling – – pulled back: iOS 2/2, Android 2/2 page stays: iOS 2/2, Android 2/2
    • The issue's own steps (Next, the refusal, swipe, type), iOS: main left the box covered (1/1). With this change the box came back, with the refusal and both buttons above the keyboard (1/1).
    • A description longer than the box (iOS): the box came back with the caret line visible inside it (2/2).
    • Typing with the box in view: the page didn't move (iOS 3/3, Android 2/2).
    • Typing 48 more characters after the reveal (iOS): no bounce, with the box's position sampled every 40 ms (3/3).
    • Back, then tap the box (Android): in view, with one scroll, from Restore Describe Rule scrolling when Android keyboard reopens #107088 (2/2).
    • First focus: one scroll on iOS (3/3). On Android the first focus sometimes stops short, on main too (main 3/5, this change 2/5, alternating runs). That is the form's fixed 300 ms wait, which Scroll focused form inputs together with the keyboard on native #106203 replaces.

    Not tested:

    • a real phone
    • landscape
    • 3-button navigation
    • mWeb
    • the Describe modal, which has no scroll view

    The check looks only at the keyboard's edge, so a box swiped up out of view at the top isn't brought back. That needs content below the box, like the refusal.

    Before (main, iOS):

    106059-ios-before-main.mp4

    After this change (iOS):

    106059-ios-after-fix.mp4

    What alternative solutions did you explore? (Optional)

    • Scroll to the box on every tap and key press: a finger that rests on the box and then swipes gets the page pulled back (iOS 3/3, Android 2/2). Without a guard, it also starts a scroll on every key.
    • Check whether the box is covered at the moment of the tap or key press: fixes typing and taps. But the press of a swipe that starts on the half-covered box ends while the box is still covered, so the page is pulled back (iOS 5/5, Android 7/7).
    • Reveal on typing only: a tap doesn't trigger it, so the half-hidden box stays covered.
    • Reveal on onSelectionChange: a tap that doesn't move the caret doesn't fire it. After typing, the caret is at the end, so tapping the half-hidden box left it covered (iOS 3/3, Android 2/2).
    • Cancel the scroll when a drag starts (onScrollBeginDrag): this needs new drag props through FormProvider and FormWrapper, which Restore Describe Rule scrolling when Android keyboard reopens #107088 and Scroll focused form inputs together with the keyboard on native #106203 also change. The hook compares the box's position instead, so the form code stays as it is.
    • Also scroll when the keyboard opens: Restore Describe Rule scrolling when Android keyboard reopens #107088 already does this for the back button case.
    • Turn Android's own scroll back on: it stops once the caret line is in view, not the whole box and Next (Stop the New rule page from scrolling twice on Android #105662). iOS has no such scroll.
  17. gesh1518 commented on Nov 19, 2026

    @gesh1518

    Proposal

    What is the root cause of that problem?

    DescribeRuleForm brings the description into view only through onFocus={scrollToInput}. Scrolling the form while the keyboard is open does not blur the input. Typing again therefore updates the text without firing another focus event, leaving the input behind the keyboard.

    <View
    style={inputContainerStyle}
    onLayout={(event) => {
    inputTopOffsetRef.current = event.nativeEvent.layout.y;
    }}
    >
    <InputWrapper
    InputComponent={TextInput}
    ref={inputRef}
    inputID={INPUT_IDS.PROMPT}
    label={placeholder ? undefined : inputLabel}
    placeholder={placeholder}
    // Without a label, the input has no top padding. Match the padding at its sides.
    textInputContainerStyles={placeholder ? styles.pt2 : undefined}
    accessibilityLabel={inputLabel}
    role={CONST.ROLE.PRESENTATION}
    onKeyPress={submitFormOnModEnter}
    onFocus={scrollToInput}
    maxLength={CONST.GENERATED_RULE.PROMPT_MAX_LENGTH}
    multiline
    shouldSaveDraft

    The form deliberately keeps the keyboard open on submission and disables Android's child-focus scrolling. The refusal handler also scrolls to the response below the input. Those behaviors explain how the focused input can move out of view; the missing part is bringing it back when editing resumes.

    stopNewRulePromptLoading();
    // The answer and its buttons show below the input, where the keyboard on iOS and Android covers them
    formRef.current?.scrollToEnd();
    return;
    }
    if (generatedRuleState !== CONST.GENERATED_RULE.STATE.RULE) {
    setNewRulePromptError(generatedRuleState);
    clearGeneratedRule();

    shouldUseScrollView={shouldUseScrollView}
    // scrollToInput moves the whole box above the keyboard. If Android also moves the box, the page moves two times.
    shouldScrollChildToFocus={false}
    submitFlexEnabled={submitFlexEnabled}
    shouldHideFixErrorsAlert
    isSubmitButtonNeutral={suggestionButtonRow.isSubmitButtonNeutral}
    submitButtonAndFooterContainerStyles={suggestionButtonRow.containerStyles}
    submitButtonInnerStyles={suggestionButtonRow.submitButtonStyles}
    footerContent={suggestionButtonRow.footerContent}
    // An empty description sends no request, so nothing would stop a loading state that starts on the press.
    shouldShowLoadingImmediatelyOnPress={!canSkipDescription}
    keyboardSubmitBehavior={CONST.KEYBOARD_SUBMIT_BEHAVIOR.SUBMIT_ONLY}

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

    Bring the focused description back when the user types or deliberately taps it, and scroll only when it is outside the visible form area. A drag that starts on the input should remain a drag.

    • In BaseTextInput/implementation/index.native.tsx, remove the extra onPressOut={inputProps.onPress} forwarding. The underlying input already receives onPress through the props spread. Calling it again on press release also invokes the callback when a gesture is canceled, which can turn a drag into an unwanted recovery scroll. Keep the wrapper's press-to-focus behavior and verify that each completed tap delivers the callback once.

    if (typeof ref === 'function') {
    ref(baseTextInputRef);
    } else if (ref && 'current' in ref) {
    // eslint-disable-next-line no-param-reassign
    ref.current = baseTextInputRef;
    }
    const elementRef = element as AnimatedTextInputRef | AnimatedMarkdownTextInputRef | null;
    input.current = elementRef;
    }}
    {...inputProps}
    autoFocus={isInLandscapeMode && !shouldAllowFocusInLandscapeMode ? false : inputProps.autoFocus}
    accessibilityLabel={resolvedAccessibilityLabel}
    accessibilityLabelledBy={accessibilityLabelledBy}
    accessibilityValue={accessibilityValue}
    accessibilityHint={errorText || inputProps.accessibilityHint}
    autoCorrect={inputProps.secureTextEntry ? false : autoCorrect}
    placeholder={placeholderValue}
    placeholderTextColor={placeholderTextColor ?? theme.placeholderText}
    underlineColorAndroid="transparent"
    style={[
    styles.flex1,
    styles.w100,
    inputStyle,
    (!hasLabel || isMultiline) && styles.pv0,
    inputPaddingLeft,
    inputPaddingRight,
    inputProps.secureTextEntry && styles.secureInput,
    // Explicitly remove `lineHeight` from single line inputs so that long text doesn't disappear
    // once it exceeds the input space on iOS (See https://github.com/Expensify/App/issues/13802)
    shouldApplyHeight && {height, lineHeight: undefined},
    // Stop scrollbar flashing when breaking lines with autoGrowHeight enabled.
    ...(autoGrowHeight && !isAutoGrowHeightMarkdown
    ? [
    StyleUtils.getAutoGrowHeightInputStyle(textInputHeight, typeof maxAutoGrowHeight === 'number' ? maxAutoGrowHeight : 0, autoGrowVerticalInset),
    styles.verticalAlignTop,
    ]
    : []),
    isAutoGrowHeightMarkdown ? [StyleUtils.getMarkdownMaxHeight(maxAutoGrowHeight), styles.verticalAlignTop] : undefined,
    // Add disabled color theme when field is not editable.
    inputProps.disabled && styles.textInputDisabled,
    styles.pointerEventsAuto,
    ]}
    multiline={isMultiline}
    maxLength={maxLength}
    onFocus={onFocus}
    onBlur={onBlur}
    onChangeText={setValue}
    secureTextEntry={passwordHidden}
    onPressOut={inputProps.onPress}

    • Add an explicitly invoked ensureInputVisible(inputRef) operation to FormWrapper, exposed through FormProvider and the form ref types. This keeps measurement and scrolling with the component that owns the scroll view. Measure the input against the actual visible viewport after keyboard avoidance, rather than the content height or a second subtraction of the keyboard height. Scroll upward or downward only when necessary, using the current scroll offset and an animated, clamped target. This operation should do nothing for a non-scrolling form.

    • Combine recovery requests arriving in the same frame and measure again before scrolling. Check that the input is still focused and the form is active. Cancel pending recovery when the user starts dragging or the form unmounts, and avoid restarting an animation already targeting the required position. Recovery with an already-open keyboard should not queue the keyboard-opening timeout used by the existing scrollTo method.

    • In DescribeRuleForm, call this operation from onValueChange and the completed onPress event, limited to the active scrolling form. Keep the existing initial-focus scroll, refusal scroll and shouldScrollChildToFocus={false} behavior. The Describe modal uses the same form without a scroll view and should retain its existing layout.

    FormProvider.registerInput already supplies onValueChange after updating the value and draft. Reusing that callback preserves normal form handling without replacing onChangeText or subscribing separately to draft changes.

    onInputChange: (value, key) => {
    const inputKey = key ?? inputID;
    setInputValues((prevState) => {
    const newState = {
    ...prevState,
    [inputKey]: value,
    };
    if (shouldValidateOnChange) {
    onValidate(newState);
    }
    return newState as Form;
    });
    if (inputProps.shouldSaveDraft && !formID.includes('Draft')) {
    setDraftValues(formID, {[inputKey]: value});
    }
    inputProps.onValueChange?.(value, inputKey);

    SelectionList's useScrollToFocusedInput provides a relevant measurement pattern: measure the container and input in the same coordinate space, then adjust the current scroll offset. Its cleanup also removes pending keyboard work. I would adapt those parts for the form; the hook itself targets a FlashList footer and is not a drop-in replacement.

    const cleanup = () => {
    keyboardListenerRef.current?.remove();
    keyboardListenerRef.current = null;
    if (!scrollTimeoutRef.current) {
    return;
    }
    clearTimeout(scrollTimeoutRef.current);
    scrollTimeoutRef.current = null;
    };
    useEffect(() => cleanup, [cleanup]);
    const trackScrollOffset = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    scrollOffsetRef.current = event.nativeEvent.contentOffset.y;
    };
    const scrollInputIntoView = (input: MeasurableInput) => {
    if (!isMeasurable(input)) {
    return;
    }
    const performScroll = () => {
    const container = containerRef.current;
    const list = listRef.current;
    if (!container || !list) {
    return;
    }
    // The list container grows to fit its content, so we can't treat its bottom as the visible area.
    // Instead we use its top (just below the header) as a stable anchor and pull the focused input up
    // toward it. The list viewport is bounded above any sticky footer (which itself sits above the
    // keyboard), so anchoring to the top reliably brings the input into view, clamped by the available
    // scroll range.
    container.measureInWindow((containerX, containerY) => {
    input.measureInWindow((inputX, inputY) => {
    const target = containerY + EXTRA_SCROLL_PADDING;
    const delta = inputY - target;
    // The input is already at or above the target anchor, so there's nothing to do.
    if (delta <= 0) {
    return;
    }
    list.scrollToOffset({offset: scrollOffsetRef.current + delta, animated: true});
    });
    });

    The investigation reproduced the retained-focus failure on standalone iOS and confirmed that invoking the existing scroll helper restores visibility. Five existing baseline suites covering the input, Rules form, Describe modal and form wrapper passed, with 39 tests. These results establish the baseline, not this proposed implementation. The complete change has not been implemented or tested. Native checks still need to cover typing, tapping without edits, dragging, long text and selection, keyboard reopening, and Android's single-scroll behavior. Because the native press correction is shared, date/list pickers and amount inputs also need regression checks; web press handling should remain unchanged.

  18. melvin-bot commented on Nov 19, 2026

    @melvin-bot

    📣 @gesh1518! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  19. gesh1518 commented on Nov 19, 2026

    @gesh1518

    @situchan, I’ve posted a new proposal after testing the available implementations on iOS:

    • Adding only onValueChange fixes typing, but tapping the already-focused input without editing still leaves it behind the keyboard.
    • Adding onPress directly restores it on tap, but also causes an unwanted jump when dragging from the input. The native component forwards that callback through onPressOut, which can fire when a press is canceled.

    My proposal addresses that event forwarding and checks visibility before scrolling. The full approach still needs implementation and native validation.

  20. yuvrajangadsingh commented on Nov 19, 2026

    @yuvrajangadsingh
    Contributor

    Proposal

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

    As part of #105457, On New rule in the Android and iOS apps, the describe box keeps focus and the keyboard stays open while the admin scrolls the form. When they type again or tap the box again, the form doesn't come back to the box, so the caret and Next stay off screen or under the keyboard.

    What is the root cause of that problem?

    The form puts the box above the keyboard in one place, and that place runs only when the box gets focus.

    // On iOS and Android, the keyboard covers the focused input unless the form scrolls to it. The scroll stops at the end of
    // the content, therefore the submit button below the input also stays in view when it fits.
    const scrollToInput = () => formRef.current?.scrollTo(inputTopOffsetRef.current);

    onFocus={scrollToInput}

    In the issue's steps the box never loses focus, so that scroll never runs again. Next submits without closing the keyboard:

    keyboardSubmitBehavior={CONST.KEYBOARD_SUBMIT_BEHAVIOR.SUBMIT_ONLY}

    The form's scroll view sets no keyboardDismissMode, so swiping it doesn't blur the box:

    <ScrollView
    style={[styles.w100, styles.flex1]}
    contentContainerStyle={styles.flexGrow1}
    keyboardShouldPersistTaps="handled"
    scrollsChildToFocus={shouldScrollChildToFocus}
    addBottomSafeAreaPadding={shouldApplyBottomSafeAreaPadding}
    addOfflineIndicatorBottomSafeAreaPadding={addOfflineIndicatorBottomSafeAreaPadding}
    ref={formRef}
    onScroll={onScroll}
    >

    And the refusal scrolls the form to its end while the box still has focus:

    // The answer and its buttons show below the input, where the keyboard on iOS and Android covers them
    formRef.current?.scrollToEnd();

    Nothing else follows the caret. Since #105662 the form turns off scrollsChildToFocus. In React Native 0.86 that one flag stops the Android scroll on focus and also requestChildRectangleOnScreen, the call that follows the caret while typing. The issue was filed on 9.5.32, before that PR merged, so on current main Android doesn't nudge the caret line into view either.

    // scrollToInput moves the whole box above the keyboard. If Android also moves the box, the page moves two times.
    shouldScrollChildToFocus={false}

    @situchan, on the regressions in #106803: going by its diff, it missed two things.

    • Editing doesn't resume only by typing. It ran on text change, and a tap on the focused box changes no text, so nothing scrolled.
    • The target. It didn't reuse the focus scroll. It scrolled the smallest distance that fits the box inside the scroll view, so Next, which sits below the box, stayed hidden. The cut off bottom of the box fits the same choice. On this page the scroll view runs under the keyboard by the bottom inset, because New rule uses edge to edge mode and that mode shortens the keyboard offset by the inset.

    <ScreenWrapper
    testID="RulesNewPage"
    enableEdgeToEdgeBottomSafeAreaPadding
    shouldEnableMaxHeight={shouldShowDescribeSection}
    >

    const shouldKeyboardOffsetBottomSafeAreaPadding = shouldKeyboardOffsetBottomSafeAreaPaddingProp ?? isUsingEdgeToEdgeMode;

    const keyboardVerticalOffset = (keyboardVerticalOffsetProp ?? 0) + (shouldOffsetBottomSafeAreaPadding ? -paddingBottom : 0);

    The focus scroll doesn't have that target problem. It asks for the top of the box, and the scroll view stops at the end of the content, which already has that inset as padding.

    Reproduction

    I reproduced this on an Android emulator (Android 15, 1080x2400) with a dev build of main at dd3885e (9.5.42-2), using the issue's steps.

    My test workspace is on Collect, where Add rule opens the upgrade page, so I made isControlPolicy return true for Collect locally to reach New rule. Nothing else was changed for this video.

    What the video shows: Rules > Add rule, I tap the describe box, the keyboard opens and the form scrolls the box above it. I type "Text the approver's phone whenever a report is submitted" and tap Next. The keyboard stays open and the box keeps focus. I swipe the form back to the top, so the box goes under the keyboard. Then I press "a" on the keyboard. The suggestion row changes to "submitteda", so the letter went into the box, but the form stays at the top and the box, the caret and Next stay hidden behind the keyboard.

    Next kept showing its loading spinner for the rest of the clip in my run. The scroll problem doesn't depend on what comes back.

    repro.mp4

    Same steps on the same build with the change below applied locally. After the key press the form scrolls back and the whole box is above the keyboard again, with Next under it.

    after.mp4

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

    In DescribeRuleForm, call the existing scrollToInput again when the admin types in the box or taps it, while the keyboard is open and only if the form has scrolled since the box was last put in place. It's the same target and the same animated scroll as focus, so the whole box comes back with Next, or with the refusal and its buttons.

    const {isKeyboardShown} = useKeyboardState();
    const hasFormScrolledRef = useRef(false);
    const isTapOnInputRef = useRef(false);
    
    const trackFormScroll = () => {
        hasFormScrolledRef.current = true;
        // A touch that scrolls the form is a swipe, so the form stays where the admin left it
        isTapOnInputRef.current = false;
    };
    
    // The box keeps focus while the form scrolls, so editing it again sends no focus event
    const scrollBackToInput = () => {
        if (!isKeyboardShown || !hasFormScrolledRef.current) {
            return;
        }
        hasFormScrolledRef.current = false;
        scrollToInput();
    };
    • Scroll tracking: pass trackFormScroll as the form's onScroll, which it already forwards to its scroll view.

    /** Fires at most once per frame during scrolling. */
    onScroll?: () => void;

    • Typing: pass scrollBackToInput as the input's onValueChange, which the form calls after each edit. resetForm doesn't call it, so Use suggestion doesn't scroll.

    inputProps.onValueChange?.(value, inputKey);

    • Tap: on the View around the input, onTouchStart sets isTapOnInputRef and onTouchEnd calls scrollBackToInput if it's still set. A swipe that starts on the box either gets its touch cancelled, so onTouchEnd never comes, or scrolls the form before it ends, which clears the flag.

    <View
    style={inputContainerStyle}
    onLayout={(event) => {
    inputTopOffsetRef.current = event.nativeEvent.layout.y;
    }}
    >

    • With the box in place, typing asks for no scroll: no timer per key, and nothing pending under a later swipe. The scroll back sets the flag once more, so one more key asks for the same offset, which moves nothing.
    • isKeyboardShown is false while the keyboard is still opening, so the first tap scrolls once, from focus, as it does now. It stays false on web, where the keyboard events never fire, so web doesn't change.

    const keyboardDidShowListener = KeyboardEvents.addListener('keyboardDidShow', (e) => {
    setKeyboardHeight(getKeyboardHeight(e.height, bottom));

    Tests: Not run yet, this is what I'd add with the PR:

    • the suite's input mock forwards only onFocus today, so I'd forward onValueChange from it and onScroll from the form mock, and mock the keyboard state

    jest.mock('@components/Form/InputWrapper', () => {
    const ReactModule = jest.requireActual<typeof React>('react');
    const {TextInput} = jest.requireActual<{TextInput: React.ComponentType<{accessibilityLabel?: string; onFocus?: () => void}>}>('react-native');
    return ({accessibilityLabel, onFocus}: {accessibilityLabel: string; onFocus?: () => void}) => ReactModule.createElement(TextInput, {accessibilityLabel, onFocus});
    });

    • keyboard open, form scrolled, admin types: the form scrolls to the top of the box
    • more typing with no scroll in between: no second scroll
    • keyboard open, form scrolled, a touch on the box ends without the form moving: the form scrolls to the box
    • the form scrolls during a touch on the box: no scroll back
    • keyboard closed: typing and touching don't scroll, focus still does

    What alternative solutions did you explore? (Optional)

    • onPress on the input for the tap. On native the input forwards it from onPressOut, which React Native also calls when a swipe that starts on the box cancels or ends the press, so the form gets pulled back against the finger. Changing that forwarding changes press handling for every other input.

  21. yuvrajangadsingh commented on Nov 19, 2026

    @yuvrajangadsingh
    Contributor

    Proposal updated: added Android emulator videos of the bug on main and of the same steps with the change applied.

  22. RajGahoi commented on Nov 19, 2026

    @RajGahoi

    Proposal

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

    On mobile platforms (Android and iOS native apps), when navigating to Workspace > Rules > Add rule and describing a rule in "Or just describe it below", scrolling the form while the soft keyboard remains expanded obscures the description box. Resuming typing or tapping into the already-focused input does not scroll the input/caret back into view above the keyboard.

    What is the root cause of that problem?

    In src/pages/workspace/rules/DescribeRuleForm.tsx, view scroll restoration is exclusively bound to onFocus={scrollToInput} on InputWrapper. When the user scrolls the form while the keyboard is open, the input retains native focus without triggering a blur event. Consequently, when typing resumes or the input is re-tapped, no new focus event is fired, and scrollToInput is never called.

    PR #106803 attempted an over-engineered global hook useRevealEditedInput which introduced layout race conditions and scroll jumps.

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

    1. Attach a throttled visibility check to onSelectionChange and onChangeText in DescribeRuleForm.tsx.
    2. When the caret position or text changes while the input is focused, check whether the input container's offset is outside the current viewport. If obscured, invoke scrollToInput smoothly.
    3. Ensure no-op when the input is already comfortably visible above the keyboard to avoid jumping on continuous typing.

    What alternative solutions did you explore? (Optional)

    Dismissing the keyboard on drag was explored, but that degrades UX by breaking the user's typing flow.

  23. expensify-chore-bot commented on Nov 19, 2026

    @expensify-chore-bot

    @situchan this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!

  24. yusufdeveloper2903 commented on Nov 20, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    Updated

  25. sinescribe commented on Nov 20, 2026

    @sinescribe

    Proposal

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

    In Workspace > Rules > Add rule, when typing in the "Or just describe it below" multiline input, submitting via Next (which keeps the software keyboard open via SUBMIT_ONLY), manually scrolling the form upward so the description box is scrolled off-screen, and then resuming typing or tapping the partially visible box, the form fails to scroll the description input and caret back into view above the keyboard.

    What is the root cause of that problem?

    1. In src/pages/workspace/rules/DescribeRuleForm.tsx, scrollToInput is wired only to onFocus (scrollToFocusedInput) and Android keyboard reopen events (useScrollOnKeyboardReopen).
    2. Because keyboardSubmitBehavior={CONST.KEYBOARD_SUBMIT_BEHAVIOR.SUBMIT_ONLY} keeps the input focused and the software keyboard expanded on submission, and swiping the parent FormWrapper ScrollView does not blur the focused TextInput, resuming typing or tapping inside the already-focused input fires neither onFocus nor a keyboard visibility transition.
    3. Furthermore, DescribeRuleForm sets shouldScrollChildToFocus={false} (from #105662) to prevent double-scrolling on initial focus, which also disables native Android caret-following when the focused input is scrolled out of the visible viewport.

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

    1. In src/pages/workspace/rules/DescribeRuleForm.tsx, trigger scrollToInput() when editing or caret interaction resumes while the input is already focused by wiring onSelectionChange on the description InputWrapper:
      • Pass onSelectionChange={() => scrollToInput()} alongside onFocus={scrollToFocusedInput} and onBlur={resetScrollOnKeyboardReopen}.
      • Wrapping in an arrow function ensures the selection event object is not passed into scrollToInput(shouldDelayScroll = true), preserving the default delayed scroll behavior across both keystrokes and taps that move the caret inside an already-focused box.
    2. In tests/ui/RulesNewPageDescribeRuleTest.tsx, forward onSelectionChange in the InputWrapper test mock and add a regression test verifying that selection/typing changes on an already-focused description input invoke scrollTo.

    What alternative solutions did you explore? (Optional)

    • Re-enabling shouldScrollChildToFocus on FormWrapper: Rejected because it reintroduces the double-scroll jump on initial Android focus (#105662).
    • Scrolling only on onValueChange: Rejected because tapping a half-hidden focused box on iOS moves the caret without changing the text value, leaving the box clipped until a key is pressed.
  26. expensify-chore-bot commented on Nov 20, 2026

    @expensify-chore-bot

    @situchan 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

  27. abbasifaizan70 commented on Nov 20, 2026

    @abbasifaizan70
    Contributor

    @situchan Proposal updated. It's rebased on current main (after #107088) and addresses the regressions found in #106803:

    • Animated scroll: when editing resumes with the keyboard open, the form scrolls back with animation, right away, and doesn't wait ANIMATED_TRANSITION on each key press.
    • Whole box comes back: it scrolls to the same spot as the focus scroll, so the box, the caret, and Next (or the refusal buttons) all show above the keyboard.
    • No double jump: it only runs once the keyboard has finished opening. First focus and the Android keyboard reopen still scroll once, through the existing paths.
    • Doesn't fight the user: it uses onSelectionChange, not onPress. onPress is forwarded to onPressOut on native, so it also fires at the end of a swipe. onSelectionChange doesn't fire when the form scrolls, so a swipe that starts on the box isn't pulled back.
    • Small and safe: one handler in DescribeRuleForm, with no changes to shared form or input components.

    Tests: 3 new cases in RulesNewPageDescribeRuleTest. The resume-editing case fails on main and passes with the fix, and the full suite passes (22/22). Typecheck, lint and the React Compiler check are clean.

    Videos (main vs fix) are attached in the proposal.

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

Metadata

Metadata

Assignees

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributorsOverdue

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions