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.
This commit is contained in:
Mohamed Boudra
2026-11-21 13:20:02 +07:00
committed by GitHub
parent efb65d7b82
commit ca514b34a7
5 changed files with 605 additions and 96 deletions
+11
View File
@@ -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+",
+289
View File
@@ -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)`,
);
}
});