From ca514b34a7f6363bd292ed0a5b2c468445255028 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sat, 21 Nov 2026 13:20:02 +0700 Subject: [PATCH] Keep Android composer buttons working on the first tap (#10308) * fix(app): keep mobile composer buttons working on the first tap After an unmatched native touch start (such as dismissing an Android Modal while a finger is down, double ACTION_DOWN in ReactRootView/ReactModalHostView, or a dropped synthetic ACTION_CANCEL), ReactFabric's ResponderEventPlugin left trackedTouchCount > 0 for the rest of the session because it only incremented/decremented by 1 instead of reconciling with nativeEvent.touches.length. On Android, @mattermost/react-native-paste-input's PasteTextInput also set onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue} (which React Native core only sets on iOS). Whenever trackedTouchCount stayed > 0, every keystroke in the composer triggered topSelectionChange and let PasteTextInput claim the JS responder, swallowing the first tap on Send or any toolbar button. Reconcile trackedTouchCount from nativeEvent.touches.length in ReactFabric (dev, prod, profiling) and ReactNativeResponder, remove the iOS-only onSelectionChangeShouldSetResponder prop from Android PasteTextInput, and drop the now-redundant createReactCancelEvent multi-pointer workaround from react-native-gesture-handler. * fix(app): clear stale touchBank contacts when native touches reach zero When a multi-touch gesture is cancelled by a single-pointer synthetic ACTION_CANCEL (or a prior touch end was dropped), ResponderTouchHistoryStore.recordTouchTrack only ended contacts listed in changedTouches, leaving other touchBank entries marked touchActive = true even though nativeEvent.touches.length was 0. Mark all remaining active touchBank entries inactive whenever topTouchEnd or topTouchCancel reports 0 active native touches, so onResponderTerminate sees a clean touchHistory without needing RNGH's createReactCancelEvent workaround. --- ...rmost+react-native-paste-input+2.0.1.patch | 98 ++++-- patches/react-native+0.86.3.patch | 223 ++++++++++++++ .../react-native-gesture-handler+2.32.0.patch | 80 +---- scripts/postinstall-patches.mjs | 11 + scripts/postinstall-patches.test.mjs | 289 ++++++++++++++++++ 5 files changed, 605 insertions(+), 96 deletions(-) create mode 100644 patches/react-native+0.86.3.patch diff --git a/patches/@mattermost+react-native-paste-input+2.0.1.patch b/patches/@mattermost+react-native-paste-input+2.0.1.patch index d3a4f760b6..4b028ddecc 100644 --- a/patches/@mattermost+react-native-paste-input+2.0.1.patch +++ b/patches/@mattermost+react-native-paste-input+2.0.1.patch @@ -28,17 +28,28 @@ index 73466dd..8440ac9 100644 auto textSize = textLayoutManager_ diff --git a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt -index 9e429b8..1d10014 100644 +index 1794b53..eca5e57 100644 --- a/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt +++ b/node_modules/@mattermost/react-native-paste-input/android/src/main/java/com/mattermost/pasteinputtext/PasteInputEditText.kt -@@ -36,2 +36,2 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) { +@@ -33,8 +33,8 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) { + return mOnPasteListener + } + - override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { - val ic = super.onCreateInputConnection(outAttrs) + override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { + val ic = super.onCreateInputConnection(outAttrs) ?: return null -@@ -58 +58 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) { + + EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("*/*")) + +@@ -55,6 +55,6 @@ class PasteInputEditText(context: ThemedReactContext) : ReactEditText(context) { + true + } + - return InputConnectionCompat.createWrapper(ic!!, outAttrs, callback) + return InputConnectionCompat.createWrapper(ic, outAttrs, callback) + } + } diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js index 51b9dfa..501badf 100644 --- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteInput.js @@ -108,10 +119,18 @@ index 51b9dfa..501badf 100644 // For Android, PasteTextInput already handles everything internally // Just need to adapt the onPaste callback format diff --git a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js -index 5119e65..287216a 100644 +index 5119e65..77c3aea 100644 --- a/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js +++ b/node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js -@@ -52,6 +52,7 @@ function InternalTextInput(props) { +@@ -16,7 +16,6 @@ var _nullthrows = _interopRequireDefault(require("nullthrows")); + var _jsxRuntime = require("react/jsx-runtime"); + function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } + function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } +-const emptyFunctionThatReturnsTrue = () => true; + function useMergeRefs(...refs) { + return React.useCallback(current => { + for (const ref of refs) { +@@ -52,6 +51,7 @@ function InternalTextInput(props) { end: propsSelection.end ?? propsSelection.start }, [propsSelection]); const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0); @@ -119,7 +138,7 @@ index 5119e65..287216a 100644 const [lastNativeText, setLastNativeText] = React.useState(props.value); const [lastNativeSelectionState, setLastNativeSelection] = React.useState({ selection: { -@@ -103,7 +104,12 @@ function InternalTextInput(props) { +@@ -103,7 +103,12 @@ function InternalTextInput(props) { Object.assign(instance, { clear() { if (inputRef.current != null) { @@ -133,7 +152,7 @@ index 5119e65..287216a 100644 } }, isFocused() { -@@ -114,12 +120,12 @@ function InternalTextInput(props) { +@@ -114,12 +119,12 @@ function InternalTextInput(props) { }, setSelection(start, end) { if (inputRef.current != null) { @@ -148,7 +167,7 @@ index 5119e65..287216a 100644 const ref = useMergeRefs(setLocalRef, props.forwardedRef); const _onChange = event => { const currentText = event.nativeEvent.text; -@@ -128,6 +134,7 @@ function InternalTextInput(props) { +@@ -128,6 +133,7 @@ function InternalTextInput(props) { if (inputRef.current == null) { return; } @@ -156,6 +175,14 @@ index 5119e65..287216a 100644 setLastNativeText(currentText); setMostRecentEventCount(event.nativeEvent.eventCount); }; +@@ -294,7 +300,6 @@ function InternalTextInput(props) { + onPaste: _onPaste, + onScroll: _onScroll, + onSelectionChange: _onSelectionChange, +- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue, + placeholder: placeholder, + style: _style, + text: text, diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js index 75fe015..1d3cd64 100644 --- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteInput.js @@ -225,10 +252,18 @@ index 75fe015..1d3cd64 100644 // For Android, PasteTextInput already handles everything internally // Just need to adapt the onPaste callback format diff --git a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js -index 39bd607..f2b1d2f 100644 +index 39bd607..832dcc2 100644 --- a/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js +++ b/node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js -@@ -46,6 +46,7 @@ function InternalTextInput(props) { +@@ -10,7 +10,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability + import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle'; + import nullthrows from 'nullthrows'; + import { jsx as _jsx } from "react/jsx-runtime"; +-const emptyFunctionThatReturnsTrue = () => true; + function useMergeRefs(...refs) { + return React.useCallback(current => { + for (const ref of refs) { +@@ -46,6 +45,7 @@ function InternalTextInput(props) { end: propsSelection.end ?? propsSelection.start }, [propsSelection]); const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0); @@ -236,7 +271,7 @@ index 39bd607..f2b1d2f 100644 const [lastNativeText, setLastNativeText] = React.useState(props.value); const [lastNativeSelectionState, setLastNativeSelection] = React.useState({ selection: { -@@ -97,7 +98,12 @@ function InternalTextInput(props) { +@@ -97,7 +97,12 @@ function InternalTextInput(props) { Object.assign(instance, { clear() { if (inputRef.current != null) { @@ -250,7 +285,7 @@ index 39bd607..f2b1d2f 100644 } }, isFocused() { -@@ -108,12 +114,12 @@ function InternalTextInput(props) { +@@ -108,12 +113,12 @@ function InternalTextInput(props) { }, setSelection(start, end) { if (inputRef.current != null) { @@ -265,7 +300,7 @@ index 39bd607..f2b1d2f 100644 const ref = useMergeRefs(setLocalRef, props.forwardedRef); const _onChange = event => { const currentText = event.nativeEvent.text; -@@ -122,6 +128,7 @@ function InternalTextInput(props) { +@@ -122,6 +127,7 @@ function InternalTextInput(props) { if (inputRef.current == null) { return; } @@ -273,6 +308,14 @@ index 39bd607..f2b1d2f 100644 setLastNativeText(currentText); setMostRecentEventCount(event.nativeEvent.eventCount); }; +@@ -288,7 +294,6 @@ function InternalTextInput(props) { + onPaste: _onPaste, + onScroll: _onScroll, + onSelectionChange: _onSelectionChange, +- onSelectionChangeShouldSetResponder: emptyFunctionThatReturnsTrue, + placeholder: placeholder, + style: _style, + text: text, diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx index 12befab..0d23ca5 100644 --- a/node_modules/@mattermost/react-native-paste-input/src/PasteInput.tsx @@ -342,10 +385,19 @@ index 12befab..0d23ca5 100644 // For Android, PasteTextInput already handles everything internally // Just need to adapt the onPaste callback format diff --git a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx -index dcc4a2b..1156458 100644 +index dcc4a2b..7d10e11 100644 --- a/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx +++ b/node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx -@@ -84,6 +84,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { +@@ -27,8 +27,6 @@ import usePressability from 'react-native/Libraries/Pressability/usePressability + import flattenStyle from 'react-native/Libraries/StyleSheet/flattenStyle'; + import nullthrows from 'nullthrows'; + +-const emptyFunctionThatReturnsTrue = () => true; +- + function useMergeRefs( + ...refs: ReadonlyArray | null | undefined> + ): (arg0: Instance | null) => void { +@@ -84,6 +82,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { const [mostRecentEventCount, setMostRecentEventCount] = React.useState(0); @@ -353,7 +405,7 @@ index dcc4a2b..1156458 100644 const [lastNativeText, setLastNativeText] = React.useState< string | undefined >(props.value); -@@ -181,13 +182,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { +@@ -181,13 +180,24 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { if (inputRef.current != null) { Commands.setTextAndSelection( inputRef.current, @@ -379,7 +431,7 @@ index dcc4a2b..1156458 100644 isFocused(): boolean { return ( TextInputState.currentlyFocusedInput() === -@@ -203,7 +215,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { +@@ -203,7 +213,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { if (inputRef.current != null) { Commands.setTextAndSelection( inputRef.current, @@ -388,7 +440,7 @@ index dcc4a2b..1156458 100644 null, start, end -@@ -213,7 +225,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { +@@ -213,7 +223,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { }); } }, @@ -397,7 +449,7 @@ index dcc4a2b..1156458 100644 ); const ref = useMergeRefs( -@@ -232,6 +244,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { +@@ -232,6 +242,7 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { return; } @@ -405,3 +457,11 @@ index dcc4a2b..1156458 100644 setLastNativeText(currentText); setMostRecentEventCount(event.nativeEvent.eventCount); }; +@@ -445,7 +456,6 @@ function InternalTextInput(props: PasteInputProps): React.ReactNode { + onPaste={_onPaste} + onScroll={_onScroll} + onSelectionChange={_onSelectionChange} +- onSelectionChangeShouldSetResponder={emptyFunctionThatReturnsTrue} + placeholder={placeholder} + style={_style} + text={text} diff --git a/patches/react-native+0.86.3.patch b/patches/react-native+0.86.3.patch new file mode 100644 index 0000000000..80db067ef6 --- /dev/null +++ b/patches/react-native+0.86.3.patch @@ -0,0 +1,223 @@ +diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js +index daab0e3..d3a629c 100644 +--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js ++++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-dev.js +@@ -16214,12 +16214,21 @@ __DEV__ && + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType +- ) +- if ( +- (nativeEvent.changedTouches.forEach(recordTouchEnd), +- (touchHistory.numberActiveTouches = nativeEvent.touches.length), +- 1 === touchHistory.numberActiveTouches) +- ) { ++ ) { ++ nativeEvent.changedTouches.forEach(recordTouchEnd); ++ touchHistory.numberActiveTouches = nativeEvent.touches.length; ++ if (0 === touchHistory.numberActiveTouches) { ++ for ( ++ topLevelType = 0; ++ topLevelType < touchBank.length; ++ topLevelType++ ++ ) ++ if ( ++ ((nativeEvent = touchBank[topLevelType]), ++ null != nativeEvent && nativeEvent.touchActive) ++ ) ++ nativeEvent.touchActive = !1; ++ } else if (1 === touchHistory.numberActiveTouches) { + for ( + topLevelType = 0; + topLevelType < touchBank.length; +@@ -16236,6 +16245,7 @@ __DEV__ && + (null != topLevelType && topLevelType.touchActive) || + console.error("Cannot find single active touch."); + } ++ } + }, + touchHistory: touchHistory + }, +@@ -16314,12 +16324,18 @@ __DEV__ && + nativeEvent, + nativeEventTarget + ) { +- if (isStartish(topLevelType)) trackedTouchCount += 1; ++ if (isStartish(topLevelType)) ++ trackedTouchCount = ++ nativeEvent && Array.isArray(nativeEvent.touches) ++ ? nativeEvent.touches.length ++ : trackedTouchCount + 1; + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType + ) +- if (0 <= trackedTouchCount) --trackedTouchCount; ++ if (nativeEvent && Array.isArray(nativeEvent.touches)) ++ trackedTouchCount = nativeEvent.touches.length; ++ else if (0 <= trackedTouchCount) --trackedTouchCount; + else + return ( + console.warn( +diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js +index 2625bf6..3d85e32 100644 +--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js ++++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-prod.js +@@ -546,12 +546,21 @@ var instrumentationCallback, + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType +- ) +- if ( +- (nativeEvent.changedTouches.forEach(recordTouchEnd), +- (touchHistory.numberActiveTouches = nativeEvent.touches.length), +- 1 === touchHistory.numberActiveTouches) +- ) ++ ) { ++ nativeEvent.changedTouches.forEach(recordTouchEnd); ++ touchHistory.numberActiveTouches = nativeEvent.touches.length; ++ if (0 === touchHistory.numberActiveTouches) { ++ for ( ++ topLevelType = 0; ++ topLevelType < touchBank.length; ++ topLevelType++ ++ ) ++ if ( ++ ((nativeEvent = touchBank[topLevelType]), ++ null != nativeEvent && nativeEvent.touchActive) ++ ) ++ nativeEvent.touchActive = !1; ++ } else if (1 === touchHistory.numberActiveTouches) + for ( + topLevelType = 0; + topLevelType < touchBank.length; +@@ -564,6 +573,7 @@ var instrumentationCallback, + touchHistory.indexOfSingleActiveTouch = topLevelType; + break; + } ++ } + }, + touchHistory: touchHistory + }; +@@ -745,12 +755,18 @@ var ResponderEventPlugin = { + nativeEvent, + nativeEventTarget + ) { +- if (isStartish(topLevelType)) trackedTouchCount += 1; ++ if (isStartish(topLevelType)) ++ trackedTouchCount = ++ nativeEvent && Array.isArray(nativeEvent.touches) ++ ? nativeEvent.touches.length ++ : trackedTouchCount + 1; + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType + ) +- if (0 <= trackedTouchCount) --trackedTouchCount; ++ if (nativeEvent && Array.isArray(nativeEvent.touches)) ++ trackedTouchCount = nativeEvent.touches.length; ++ else if (0 <= trackedTouchCount) --trackedTouchCount; + else return null; + ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); + if ( +diff --git a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js +index 544c754..4d5ec08 100644 +--- a/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js ++++ b/node_modules/react-native/Libraries/Renderer/implementations/ReactFabric-profiling.js +@@ -611,12 +611,21 @@ var instrumentationCallback, + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType +- ) +- if ( +- (nativeEvent.changedTouches.forEach(recordTouchEnd), +- (touchHistory.numberActiveTouches = nativeEvent.touches.length), +- 1 === touchHistory.numberActiveTouches) +- ) ++ ) { ++ nativeEvent.changedTouches.forEach(recordTouchEnd); ++ touchHistory.numberActiveTouches = nativeEvent.touches.length; ++ if (0 === touchHistory.numberActiveTouches) { ++ for ( ++ topLevelType = 0; ++ topLevelType < touchBank.length; ++ topLevelType++ ++ ) ++ if ( ++ ((nativeEvent = touchBank[topLevelType]), ++ null != nativeEvent && nativeEvent.touchActive) ++ ) ++ nativeEvent.touchActive = !1; ++ } else if (1 === touchHistory.numberActiveTouches) + for ( + topLevelType = 0; + topLevelType < touchBank.length; +@@ -629,6 +638,7 @@ var instrumentationCallback, + touchHistory.indexOfSingleActiveTouch = topLevelType; + break; + } ++ } + }, + touchHistory: touchHistory + }; +@@ -810,12 +820,18 @@ var ResponderEventPlugin = { + nativeEvent, + nativeEventTarget + ) { +- if (isStartish(topLevelType)) trackedTouchCount += 1; ++ if (isStartish(topLevelType)) ++ trackedTouchCount = ++ nativeEvent && Array.isArray(nativeEvent.touches) ++ ? nativeEvent.touches.length ++ : trackedTouchCount + 1; + else if ( + "topTouchEnd" === topLevelType || + "topTouchCancel" === topLevelType + ) +- if (0 <= trackedTouchCount) --trackedTouchCount; ++ if (nativeEvent && Array.isArray(nativeEvent.touches)) ++ trackedTouchCount = nativeEvent.touches.length; ++ else if (0 <= trackedTouchCount) --trackedTouchCount; + else return null; + ResponderTouchHistoryStore.recordTouchTrack(topLevelType, nativeEvent); + if ( +diff --git a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js +index da29336..7167a2f 100644 +--- a/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js ++++ b/node_modules/react-native/src/private/renderer/events/ReactNativeResponder.js +@@ -560,9 +560,13 @@ export function processResponderEvent( + ): void { + // Track touch count + if (isStartish(topLevelType)) { +- trackedTouchCount += 1; ++ trackedTouchCount = Array.isArray(nativeEvent.touches) ++ ? nativeEvent.touches.length ++ : trackedTouchCount + 1; + } else if (isEndish(topLevelType)) { +- if (trackedTouchCount >= 0) { ++ if (Array.isArray(nativeEvent.touches)) { ++ trackedTouchCount = nativeEvent.touches.length; ++ } else if (trackedTouchCount >= 0) { + trackedTouchCount -= 1; + } else { + if (__DEV__) { +diff --git a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js +index c0b4d12..b4aab95 100644 +--- a/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js ++++ b/node_modules/react-native/src/private/renderer/events/ResponderTouchHistoryStore.js +@@ -234,7 +234,14 @@ const ResponderTouchHistoryStore = { + } else if (isEndish(topLevelType)) { + nativeEvent.changedTouches.forEach(recordTouchEnd); + touchHistory.numberActiveTouches = nativeEvent.touches.length; +- if (touchHistory.numberActiveTouches === 1) { ++ if (touchHistory.numberActiveTouches === 0) { ++ for (let i = 0; i < touchBank.length; i++) { ++ const touchTrackToCheck = touchBank[i]; ++ if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { ++ touchTrackToCheck.touchActive = false; ++ } ++ } ++ } else if (touchHistory.numberActiveTouches === 1) { + for (let i = 0; i < touchBank.length; i++) { + const touchTrackToCheck = touchBank[i]; + if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { diff --git a/patches/react-native-gesture-handler+2.32.0.patch b/patches/react-native-gesture-handler+2.32.0.patch index 1a8e6ae60f..b6e3a810f1 100644 --- a/patches/react-native-gesture-handler+2.32.0.patch +++ b/patches/react-native-gesture-handler+2.32.0.patch @@ -152,92 +152,18 @@ index 8d78aea..b84d19e 100644 viewGroup: ViewGroup, coords: FloatArray, diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -index 629c155..2efd508 100644 +index 629c155..dc0790d 100644 --- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt +++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt -@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: +@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: private val jsGestureHandler: GestureHandler? val rootView: ViewGroup private var shouldIntercept = false + private var wasIntercepting = false private var passingTouch = false -+ private var lastTouch: MotionEvent? = null init { - UiThreadUtil.assertOnUiThread() -@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: - } - - fun tearDown() { -+ clearLastTouch() - Log.i( - ReactConstants.TAG, - "[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView", -@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: - - override fun onCancel() { - shouldIntercept = true -- val time = SystemClock.uptimeMillis() -- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply { -- action = MotionEvent.ACTION_CANCEL -- } - if (rootView is RootView) { -- rootView.onChildStartedNativeGesture(rootView, event) -+ val cancel = createReactCancelEvent() -+ try { -+ rootView.onChildStartedNativeGesture(rootView, cancel) -+ } finally { -+ cancel.recycle() -+ clearLastTouch() -+ } - } -- event.recycle() - } - } - -+ private fun clearLastTouch() { -+ lastTouch?.recycle() -+ lastTouch = null -+ } -+ -+ private fun createReactCancelEvent(): MotionEvent { -+ val now = SystemClock.uptimeMillis() -+ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) -+ // The enclosing React root already dispatched this event before it reached the -+ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS. -+ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1 -+ val count = touch.pointerCount - if (lifted >= 0) 1 else 0 -+ val properties = Array(count) { MotionEvent.PointerProperties() } -+ val coords = Array(count) { MotionEvent.PointerCoords() } -+ var index = 0 -+ for (pointer in 0 until touch.pointerCount) { -+ if (pointer == lifted) continue -+ touch.getPointerProperties(pointer, properties[index]) -+ touch.getPointerCoords(pointer, coords[index]) -+ index++ -+ } -+ return MotionEvent.obtain( -+ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords, -+ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision, -+ touch.deviceId, touch.edgeFlags, touch.source, touch.flags, -+ ) -+ } -+ - fun requestDisallowInterceptTouchEvent() { - // If this method gets called it means that some native view is attempting to grab lock for - // touch event delivery. In that case we cancel all gesture recognizers -@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: - // We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell - // if `requestDisallow` has been called as a result of a normal gesture handling process or - // as a result of one of the gesture handlers activating -+ // Keep the stream for recognizers that activate between events (e.g. long press). -+ // Once native handling begins, React no longer receives the remaining touches. -+ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) { -+ clearLastTouch() -+ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) { -+ lastTouch = MotionEvent.obtainNoHistory(event) -+ } -+ } +@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: passingTouch = true orchestrator!!.onTouchEvent(event) passingTouch = false diff --git a/scripts/postinstall-patches.mjs b/scripts/postinstall-patches.mjs index da82ecfda4..7919a4077f 100644 --- a/scripts/postinstall-patches.mjs +++ b/scripts/postinstall-patches.mjs @@ -82,6 +82,17 @@ const patchedPackages = [ patchPrefix: "react-native-svg+", cwd: "packages/app", }, + // Reconcile ResponderEventPlugin trackedTouchCount and ResponderTouchHistoryStore touchBank with + // nativeEvent.touches.length so an unmatched touch start or single-pointer synthetic cancel + // (e.g. Modal dismiss while touching, RNGH pinch takeover, or double ACTION_DOWN in + // ReactRootView/ReactModalHostView) self-heals instead of leaving trackedTouchCount > 0 or stale + // active contacts in touchBank. Remove once upstream React/React Native reconciles both. + { + nodeModulesPath: "node_modules/react-native", + patchPrefix: "react-native+", + }, + // Keep Android PasteTextInput aligned with RN AndroidTextInput (omit iOS-only + // onSelectionChangeShouldSetResponder), plus ref/eventCount/trailing-newline fixes. { nodeModulesPath: "node_modules/@mattermost/react-native-paste-input", patchPrefix: "@mattermost+react-native-paste-input+", diff --git a/scripts/postinstall-patches.test.mjs b/scripts/postinstall-patches.test.mjs index 11cd2d157a..8a227f3aeb 100644 --- a/scripts/postinstall-patches.test.mjs +++ b/scripts/postinstall-patches.test.mjs @@ -1,9 +1,11 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; +import vm from "node:vm"; const script = path.resolve("scripts", "postinstall-patches.mjs"); const bin = path.resolve("node_modules", ".bin"); @@ -134,3 +136,290 @@ test("a missing patch-package fails the install and leaves the package in place" rmSync(root, { recursive: true, force: true }); } }); + +function loadReactFabricDispatchEvent(bundleName, isDev) { + const bundlePath = path.resolve( + "node_modules/react-native/Libraries/Renderer/implementations", + bundleName, + ); + const code = readFileSync(bundlePath, "utf8"); + const nodeRequire = createRequire(import.meta.url); + let dispatchEvent = null; + const warnings = []; + const rawEventListeners = new Map(); + + const nativeFabricUIManager = { + createNode: () => ({}), + cloneNodeWithNewChildren: () => ({}), + cloneNodeWithNewChildrenAndProps: () => ({}), + cloneNodeWithNewProps: () => ({}), + createChildSet: () => ({}), + appendChild: () => {}, + appendChildToSet: () => {}, + completeRoot: () => {}, + registerEventHandler: (fn) => { + dispatchEvent = fn; + }, + setIsJSResponder: () => {}, + clearIsJSResponder: () => {}, + unstable_DiscreteEventPriority: 1, + unstable_ContinuousEventPriority: 2, + unstable_IdleEventPriority: 3, + unstable_getCurrentEventPriority: () => 1, + }; + + const privateInterface = { + ReactNativeViewConfigRegistry: { + get: () => ({}), + customBubblingEventTypes: { + topTouchStart: { + phasedRegistrationNames: { bubbled: "onTouchStart", captured: "onTouchStartCapture" }, + }, + topTouchMove: { + phasedRegistrationNames: { bubbled: "onTouchMove", captured: "onTouchMoveCapture" }, + }, + topTouchEnd: { + phasedRegistrationNames: { bubbled: "onTouchEnd", captured: "onTouchEndCapture" }, + }, + topTouchCancel: { + phasedRegistrationNames: { bubbled: "onTouchCancel", captured: "onTouchCancelCapture" }, + }, + topSelectionChange: { + phasedRegistrationNames: { + bubbled: "onSelectionChange", + captured: "onSelectionChangeCapture", + }, + }, + }, + customDirectEventTypes: {}, + }, + RawEventEmitter: { + emit: (name, payload) => { + for (const fn of rawEventListeners.get(name) ?? []) { + fn(payload); + } + }, + }, + UIManager: {}, + deepDiffer: () => false, + flattenStyle: (s) => s, + getNativeTagFromPublicInstance: () => null, + getNodeFromPublicInstance: () => null, + legacySendAccessibilityEvent: () => {}, + createPublicInstance: (tag) => ({ _nativeTag: tag }), + createPublicTextInstance: () => ({}), + ReactFiberErrorDialog: { showErrorDialog: () => true }, + Platform: { OS: "android" }, + }; + + const customRequire = (id) => { + if (id === "react") { + return nodeRequire("react"); + } + if (id === "scheduler") { + return nodeRequire("scheduler"); + } + if (id === "react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore") { + return {}; + } + if (id === "react-native/Libraries/ReactPrivate/ReactNativePrivateInterface") { + return privateInterface; + } + return nodeRequire(id); + }; + + const moduleObj = { exports: {} }; + const sandbox = { + __DEV__: isDev, + console: { + ...console, + warn: (...args) => warnings.push(args.join(" ")), + error: (...args) => warnings.push(args.join(" ")), + }, + exports: moduleObj.exports, + module: moduleObj, + nativeFabricUIManager, + performance, + queueMicrotask, + require: customRequire, + setTimeout, + clearTimeout, + }; + sandbox.global = sandbox; + sandbox.globalThis = sandbox; + + vm.runInNewContext(code, sandbox, { filename: bundleName }); + assert.equal( + typeof dispatchEvent, + "function", + `Expected ${bundleName} to register dispatchEvent`, + ); + return { dispatchEvent, warnings }; +} + +function createHostFiber(type, props, parent = null) { + const publicInstance = { _nativeTag: Math.floor(Math.random() * 100000) + 1 }; + return { + tag: 5, + type, + return: parent, + alternate: null, + stateNode: { + canonical: { + currentProps: props, + publicInstance, + publicInstanceType: 0, + }, + }, + }; +} + +function makeTouch(identifier, timestamp) { + return { + identifier, + target: 1, + pageX: 100, + pageY: 100, + locationX: 10, + locationY: 10, + timestamp, + }; +} + +for (const [bundleName, isDev] of [ + ["ReactFabric-dev.js", true], + ["ReactFabric-prod.js", false], + ["ReactFabric-profiling.js", false], +]) { + test(`${bundleName} reconciles trackedTouchCount from nativeEvent.touches after a dropped touch end`, () => { + const { dispatchEvent, warnings } = loadReactFabricDispatchEvent(bundleName, isDev); + const rootFiber = createHostFiber("RCTView", {}); + let inputGrants = 0; + let buttonGrants = 0; + const inputFiber = createHostFiber( + "PasteTextInput", + { + onSelectionChangeShouldSetResponder: () => true, + onResponderGrant: () => { + inputGrants += 1; + }, + }, + rootFiber, + ); + const buttonFiber = createHostFiber( + "RCTView", + { + onStartShouldSetResponder: () => true, + onResponderGrant: () => { + buttonGrants += 1; + }, + }, + rootFiber, + ); + + // 1. Unmatched touch start (e.g. Modal dismissed while touch is down or double ACTION_DOWN). + const orphanTouch = makeTouch(0, 1); + dispatchEvent(rootFiber, "topTouchStart", { + touches: [orphanTouch], + changedTouches: [orphanTouch], + }); + + // 2. Subsequent normal tap completes with zero remaining native touches. + const tapTouch = makeTouch(1, 2); + dispatchEvent(inputFiber, "topTouchStart", { + touches: [tapTouch], + changedTouches: [tapTouch], + }); + dispatchEvent(inputFiber, "topTouchEnd", { + touches: [], + changedTouches: [tapTouch], + }); + + // 3. Typing triggers topSelectionChange. With trackedTouchCount reconciled to 0, + // the input must not claim responder and swallow the next tap on a sibling button. + dispatchEvent(inputFiber, "topSelectionChange", { + selection: { start: 1, end: 1 }, + }); + assert.equal( + inputGrants, + 0, + "topSelectionChange must not claim responder when no touches are active", + ); + + // 4. First tap on sibling send button must be granted immediately. + const sendTouch = makeTouch(2, 3); + dispatchEvent(buttonFiber, "topTouchStart", { + touches: [sendTouch], + changedTouches: [sendTouch], + }); + dispatchEvent(buttonFiber, "topTouchEnd", { + touches: [], + changedTouches: [sendTouch], + }); + assert.equal(buttonGrants, 1, "first tap on sibling button must receive responder grant"); + + // 5. Two-finger gesture cancelled by a single synthetic topTouchCancel (e.g. RNGH pinch takeover) + // must reconcile trackedTouchCount to 0 and mark every touchBank contact inactive before + // onResponderTerminate runs. + let terminatedHistory = null; + const gestureFiber = createHostFiber( + "RCTView", + { + onStartShouldSetResponder: () => true, + onResponderTerminate: (event) => { + terminatedHistory = { + numberActiveTouches: event.touchHistory.numberActiveTouches, + activeBankIds: Array.from(event.touchHistory.touchBank, (record, index) => + record?.touchActive ? index : -1, + ).filter((index) => index >= 0), + }; + }, + }, + rootFiber, + ); + const p0 = makeTouch(3, 4); + const p1 = makeTouch(4, 5); + dispatchEvent(gestureFiber, "topTouchStart", { touches: [p0], changedTouches: [p0] }); + dispatchEvent(gestureFiber, "topTouchStart", { touches: [p0, p1], changedTouches: [p1] }); + dispatchEvent(gestureFiber, "topTouchCancel", { touches: [], changedTouches: [p0] }); + assert.deepEqual(terminatedHistory, { + numberActiveTouches: 0, + activeBankIds: [], + }); + dispatchEvent(inputFiber, "topSelectionChange", { selection: { start: 2, end: 2 } }); + assert.equal( + inputGrants, + 0, + "single topTouchCancel after 2-finger touch must reset trackedTouchCount to 0", + ); + + // 6. Multi-touch cancel emitting two topTouchCancel events with touches: [] must stay at 0 without warning. + const t0 = makeTouch(5, 6); + const t1 = makeTouch(6, 7); + dispatchEvent(rootFiber, "topTouchStart", { touches: [t0], changedTouches: [t0] }); + dispatchEvent(rootFiber, "topTouchStart", { touches: [t0, t1], changedTouches: [t1] }); + dispatchEvent(rootFiber, "topTouchCancel", { touches: [], changedTouches: [t0, t1] }); + dispatchEvent(rootFiber, "topTouchCancel", { touches: [], changedTouches: [t0, t1] }); + dispatchEvent(inputFiber, "topSelectionChange", { selection: { start: 3, end: 3 } }); + assert.equal(inputGrants, 0, "multi-touch cancel must leave trackedTouchCount at 0"); + assert.deepEqual( + warnings.filter((w) => w.includes("trackedTouchCount")), + [], + ); + }); +} + +test("patched @mattermost/react-native-paste-input Android PasteTextInput does not claim responder on selection change", () => { + for (const relPath of [ + "node_modules/@mattermost/react-native-paste-input/src/PasteTextInput.tsx", + "node_modules/@mattermost/react-native-paste-input/lib/commonjs/PasteTextInput.js", + "node_modules/@mattermost/react-native-paste-input/lib/module/PasteTextInput.js", + ]) { + const source = readFileSync(path.resolve(relPath), "utf8"); + assert.equal( + source.includes("onSelectionChangeShouldSetResponder"), + false, + `${relPath} must not set onSelectionChangeShouldSetResponder (matches RN AndroidTextInput)`, + ); + } +});