first commit

This commit is contained in:
2026-03-10 16:18:05 +00:00
commit 11f9c069b5
31635 changed files with 3187747 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
import PooledClass from './PooledClass';
const twoArgumentPooler = PooledClass.twoArgumentPooler;
/**
* PooledClass representing the bounding rectangle of a region.
*
* @param {number} width Width of bounding rectangle.
* @param {number} height Height of bounding rectangle.
* @constructor BoundingDimensions
*/
// $FlowFixMe[missing-this-annot]
function BoundingDimensions(width: number, height: number) {
this.width = width;
this.height = height;
}
// $FlowFixMe[prop-missing]
// $FlowFixMe[missing-this-annot]
BoundingDimensions.prototype.destructor = function () {
this.width = null;
this.height = null;
};
/**
* @param {HTMLElement} element Element to return `BoundingDimensions` for.
* @return {BoundingDimensions} Bounding dimensions of `element`.
*/
BoundingDimensions.getPooledFromElement = function (
element: HTMLElement,
): typeof BoundingDimensions {
// $FlowFixMe[prop-missing]
return BoundingDimensions.getPooled(
element.offsetWidth,
element.offsetHeight,
);
};
PooledClass.addPoolingTo(BoundingDimensions as $FlowFixMe, twoArgumentPooler);
export default BoundingDimensions;

View File

@@ -0,0 +1,133 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
import invariant from 'invariant';
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
const oneArgumentPooler = function (copyFieldsFrom: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
const twoArgumentPooler = function (a1: any, a2: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
const threeArgumentPooler = function (a1: any, a2: any, a3: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
const fourArgumentPooler = function (a1: any, a2: any, a3: any, a4: any) {
const Klass = this; // eslint-disable-line consistent-this
if (Klass.instancePool.length) {
const instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
const standardReleaser = function (instance) {
const Klass = this; // eslint-disable-line consistent-this
invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.',
);
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
const DEFAULT_POOL_SIZE = 10;
const DEFAULT_POOLER = oneArgumentPooler;
type Pooler = any;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
const addPoolingTo = function <T>(
CopyConstructor: Class<T>,
pooler: Pooler,
): Class<T> & {
getPooled(
...args: $ReadOnlyArray<mixed>
): /* arguments of the constructor */ T,
release(instance: mixed): void,
...
} {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
const NewKlass: any = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
const PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: (oneArgumentPooler: Pooler),
twoArgumentPooler: (twoArgumentPooler: Pooler),
threeArgumentPooler: (threeArgumentPooler: Pooler),
fourArgumentPooler: (fourArgumentPooler: Pooler),
};
export default PooledClass;

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
'use strict';
import PooledClass from './PooledClass';
const twoArgumentPooler = PooledClass.twoArgumentPooler;
/**
* Position does not expose methods for construction via an `HTMLDOMElement`,
* because it isn't meaningful to construct such a thing without first defining
* a frame of reference.
*
* @param {number} windowStartKey Key that window starts at.
* @param {number} windowEndKey Key that window ends at.
*/
// $FlowFixMe[missing-this-annot]
function Position(left: number, top: number) {
this.left = left;
this.top = top;
}
// $FlowFixMe[prop-missing]
// $FlowFixMe[missing-this-annot]
Position.prototype.destructor = function () {
this.left = null;
this.top = null;
};
PooledClass.addPoolingTo(Position as $FlowFixMe, twoArgumentPooler);
export default Position;

View File

@@ -0,0 +1,90 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import type * as React from 'react';
import {Insets} from '../../../types/public/Insets';
import {GestureResponderEvent} from '../../Types/CoreEventTypes';
/**
* //FIXME: need to find documentation on which component is a TTouchable and can implement that interface
* @see React.DOMAttributes
*/
export interface Touchable {
onTouchStart?: ((event: GestureResponderEvent) => void) | undefined;
onTouchMove?: ((event: GestureResponderEvent) => void) | undefined;
onTouchEnd?: ((event: GestureResponderEvent) => void) | undefined;
onTouchCancel?: ((event: GestureResponderEvent) => void) | undefined;
onTouchEndCapture?: ((event: GestureResponderEvent) => void) | undefined;
}
export const Touchable: {
TOUCH_TARGET_DEBUG: boolean;
renderDebugView: (config: {
color: string | number;
hitSlop?: Insets | undefined;
}) => React.ReactElement | null;
};
/**
* @see https://github.com/facebook/react-native/blob/0.34-stable\Libraries\Components\Touchable\Touchable.js
*/
interface TouchableMixin {
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*/
touchableHandleActivePressIn(e: GestureResponderEvent): void;
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*/
touchableHandleActivePressOut(e: GestureResponderEvent): void;
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*/
touchableHandlePress(e: GestureResponderEvent): void;
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*/
touchableHandleLongPress(e: GestureResponderEvent): void;
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*/
touchableGetPressRectOffset(): Insets;
/**
* Returns the number of millis to wait before triggering a highlight.
*/
touchableGetHighlightDelayMS(): number;
// These methods are undocumented but still being used by TouchableMixin internals
touchableGetLongPressDelayMS(): number;
touchableGetPressOutDelayMS(): number;
touchableGetHitSlop(): Insets;
}

View File

@@ -0,0 +1,987 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType';
import type {ColorValue} from '../../StyleSheet/StyleSheet';
import type {
BlurEvent,
FocusEvent,
GestureResponderEvent,
} from '../../Types/CoreEventTypes';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import UIManager from '../../ReactNative/UIManager';
import Platform from '../../Utilities/Platform';
import SoundManager from '../Sound/SoundManager';
import BoundingDimensions from './BoundingDimensions';
import Position from './Position';
import * as React from 'react';
const extractSingleTouch = (nativeEvent: {
+changedTouches: $ReadOnlyArray<GestureResponderEvent['nativeEvent']>,
+force?: number,
+identifier: number,
+locationX: number,
+locationY: number,
+pageX: number,
+pageY: number,
+target: ?number,
+timestamp: number,
+touches: $ReadOnlyArray<GestureResponderEvent['nativeEvent']>,
}) => {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
const hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches
? changedTouches[0]
: hasTouches
? touches[0]
: nativeEvent;
};
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
const States = {
NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder
RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold
ERROR: 'ERROR',
};
type TouchableState =
| typeof States.NOT_RESPONDER
| typeof States.RESPONDER_INACTIVE_PRESS_IN
| typeof States.RESPONDER_INACTIVE_PRESS_OUT
| typeof States.RESPONDER_ACTIVE_PRESS_IN
| typeof States.RESPONDER_ACTIVE_PRESS_OUT
| typeof States.RESPONDER_ACTIVE_LONG_PRESS_IN
| typeof States.RESPONDER_ACTIVE_LONG_PRESS_OUT
| typeof States.ERROR;
/*
* Quick lookup map for states that are considered to be "active"
*/
const baseStatesConditions = {
NOT_RESPONDER: false,
RESPONDER_INACTIVE_PRESS_IN: false,
RESPONDER_INACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_PRESS_IN: false,
RESPONDER_ACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_LONG_PRESS_IN: false,
RESPONDER_ACTIVE_LONG_PRESS_OUT: false,
ERROR: false,
};
const IsActive = {
...baseStatesConditions,
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true,
};
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
const IsPressingIn = {
...baseStatesConditions,
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
const IsLongPressingIn = {
...baseStatesConditions,
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
/**
* Inputs to the state machine.
*/
const Signals = {
DELAY: 'DELAY',
RESPONDER_GRANT: 'RESPONDER_GRANT',
RESPONDER_RELEASE: 'RESPONDER_RELEASE',
RESPONDER_TERMINATED: 'RESPONDER_TERMINATED',
ENTER_PRESS_RECT: 'ENTER_PRESS_RECT',
LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT',
LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED',
};
type Signal =
| typeof Signals.DELAY
| typeof Signals.RESPONDER_GRANT
| typeof Signals.RESPONDER_RELEASE
| typeof Signals.RESPONDER_TERMINATED
| typeof Signals.ENTER_PRESS_RECT
| typeof Signals.LEAVE_PRESS_RECT
| typeof Signals.LONG_PRESS_DETECTED;
/**
* Mapping from States x Signals => States
*/
const Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER,
},
};
// ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
const HIGHLIGHT_DELAY_MS = 130;
const PRESS_EXPAND_PX = 20;
const LONG_PRESS_THRESHOLD = 500;
const LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
const LONG_PRESS_ALLOWED_MOVEMENT = 10;
// Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
const TouchableMixinImpl = {
componentDidMount: function () {
if (!Platform.isTV) {
return;
}
},
/**
* Clear all timeouts on unmount
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
componentWillUnmount: function () {
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function (): {
touchable: {
touchState: ?TouchableState,
responderID: ?GestureResponderEvent['currentTarget'],
},
} {
return {
touchable: {touchState: undefined, responderID: null},
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleResponderTerminationRequest: function (): any {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleStartShouldSetResponder: function (): any {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function (): boolean {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {NativeSyntheticEvent} e Synthetic event from event system.
*
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleResponderGrant: function (e: GestureResponderEvent) {
const dispatchID = e.currentTarget;
// Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
let delayMS =
this.touchableGetHighlightDelayMS !== undefined
? Math.max(this.touchableGetHighlightDelayMS(), 0)
: HIGHLIGHT_DELAY_MS;
delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS;
if (delayMS !== 0) {
this.touchableDelayTimeout = setTimeout(
this._handleDelay.bind(this, e),
delayMS,
);
} else {
this._handleDelay(e);
}
let longDelayMS =
this.touchableGetLongPressDelayMS !== undefined
? Math.max(this.touchableGetLongPressDelayMS(), 10)
: LONG_PRESS_DELAY_MS;
longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS;
this.longPressDelayTimeout = setTimeout(
this._handleLongDelay.bind(this, e),
longDelayMS + delayMS,
);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleResponderRelease: function (e: GestureResponderEvent) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleResponderTerminate: function (e: GestureResponderEvent) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleResponderMove: function (e: GestureResponderEvent) {
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
const positionOnActivate = this.state.touchable.positionOnActivate;
const dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
const pressRectOffset = this.touchableGetPressRectOffset
? this.touchableGetPressRectOffset()
: {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX,
};
let pressExpandLeft = pressRectOffset.left;
let pressExpandTop = pressRectOffset.top;
let pressExpandRight = pressRectOffset.right;
let pressExpandBottom = pressRectOffset.bottom;
const hitSlop = this.touchableGetHitSlop
? this.touchableGetHitSlop()
: null;
if (hitSlop) {
pressExpandLeft += hitSlop.left || 0;
pressExpandTop += hitSlop.top || 0;
pressExpandRight += hitSlop.right || 0;
pressExpandBottom += hitSlop.bottom || 0;
}
const touch = extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
if (this.pressInLocation) {
const movedDistance = this._getDistanceBetweenPoints(
pageX,
pageY,
this.pressInLocation.pageX,
this.pressInLocation.pageY,
);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
const isTouchWithinActive =
pageX > positionOnActivate.left - pressExpandLeft &&
pageY > positionOnActivate.top - pressExpandTop &&
pageX <
positionOnActivate.left +
dimensionsOnActivate.width +
pressExpandRight &&
pageY <
positionOnActivate.top +
dimensionsOnActivate.height +
pressExpandBottom;
if (isTouchWithinActive) {
const prevState = this.state.touchable.touchState;
this._receiveSignal(Signals.ENTER_PRESS_RECT, e);
const curState = this.state.touchable.touchState;
if (
curState === States.RESPONDER_INACTIVE_PRESS_IN &&
prevState !== States.RESPONDER_INACTIVE_PRESS_IN
) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
/**
* Invoked when the item receives focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* currently has the focus. Most platforms only support a single element being
* focused at a time, in which case there may have been a previously focused
* element that was blurred just prior to this. This can be overridden when
* using `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleFocus: function (e: FocusEvent) {
this.props.onFocus && this.props.onFocus(e);
},
/**
* Invoked when the item loses focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* no longer has focus. Most platforms only support a single element being
* focused at a time, in which case the focus may have moved to another.
* This can be overridden when using
* `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
touchableHandleBlur: function (e: BlurEvent) {
this.props.onBlur && this.props.onBlur(e);
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_remeasureMetricsOnActivation: function () {
const responderID = this.state.touchable.responderID;
if (responderID == null) {
return;
}
if (typeof responderID === 'number') {
UIManager.measure(responderID, this._handleQueryLayout);
} else {
responderID.measure(this._handleQueryLayout);
}
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_handleQueryLayout: function (
l: number,
t: number,
w: number,
h: number,
globalX: number,
globalY: number,
) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate &&
// $FlowFixMe[prop-missing]
Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate &&
// $FlowFixMe[prop-missing]
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
// $FlowFixMe[prop-missing]
this.state.touchable.positionOnActivate = Position.getPooled(
globalX,
globalY,
);
// $FlowFixMe[prop-missing]
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(
w,
h,
);
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_handleDelay: function (e: GestureResponderEvent) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_handleLongDelay: function (e: GestureResponderEvent) {
this.longPressDelayTimeout = null;
const curState = this.state.touchable.touchState;
if (
curState === States.RESPONDER_ACTIVE_PRESS_IN ||
curState === States.RESPONDER_ACTIVE_LONG_PRESS_IN
) {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_receiveSignal: function (signal: Signal, e: GestureResponderEvent) {
const responderID = this.state.touchable.responderID;
const curState = this.state.touchable.touchState;
const nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error(
'Unrecognized signal `' +
signal +
'` or state `' +
curState +
'` for Touchable responder `' +
typeof this.state.touchable.responderID ===
'number'
? this.state.touchable.responderID
: 'host component' + '`',
);
}
if (nextState === States.ERROR) {
throw new Error(
'Touchable cannot transition from `' +
curState +
'` to `' +
signal +
'` for responder `' +
typeof this.state.touchable.responderID ===
'number'
? this.state.touchable.responderID
: '<<host component>>' + '`',
);
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_cancelLongPressDelayTimeout: function () {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function (state: TouchableState): boolean {
return (
state === States.RESPONDER_ACTIVE_PRESS_IN ||
state === States.RESPONDER_ACTIVE_LONG_PRESS_IN
);
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_savePressInLocation: function (e: GestureResponderEvent) {
const touch = extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
const locationX = touch && touch.locationX;
const locationY = touch && touch.locationY;
this.pressInLocation = {pageX, pageY, locationX, locationY};
},
_getDistanceBetweenPoints: function (
aX: number,
aY: number,
bX: number,
bY: number,
): number {
const deltaX = aX - bX;
const deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_performSideEffectsForTransition: function (
curState: TouchableState,
nextState: TouchableState,
signal: Signal,
e: GestureResponderEvent,
) {
const curIsHighlight = this._isHighlight(curState);
const newIsHighlight = this._isHighlight(nextState);
const isFinalSignal =
signal === Signals.RESPONDER_TERMINATED ||
signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
const isInitialTransition =
curState === States.NOT_RESPONDER &&
nextState === States.RESPONDER_INACTIVE_PRESS_IN;
/* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See
* https://fburl.com/workplace/6291gfvu */
const isActiveTransition = !IsActive[curState] && IsActive[nextState];
if (isInitialTransition || isActiveTransition) {
this._remeasureMetricsOnActivation();
}
/* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See
* https://fburl.com/workplace/6291gfvu */
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
/* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See
* https://fburl.com/workplace/6291gfvu */
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
const hasLongPressHandler = !!this.props.onLongPress;
const pressIsLongButStillCallOnPress =
/* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See
* https://fburl.com/workplace/6291gfvu */
IsLongPressingIn[curState] && // We *are* long pressing.. // But either has no long handler
(!hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it.
const shouldInvokePress =
/* $FlowFixMe[invalid-computed-prop] Natural Inference rollout. See
* https://fburl.com/workplace/6291gfvu */
!IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
if (Platform.OS === 'android' && !this.props.touchSoundDisabled) {
SoundManager.playTouchSound();
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_startHighlight: function (e: GestureResponderEvent) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
/* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by
* Flow's LTI update could not be added via codemod */
_endHighlight: function (e: GestureResponderEvent) {
if (this.touchableHandleActivePressOut) {
if (
this.touchableGetPressOutDelayMS &&
this.touchableGetPressOutDelayMS()
) {
this.pressOutDelayTimeout = setTimeout(() => {
this.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
withoutDefaultFocusAndBlur: ({}: {...}),
};
/**
* Provide an optional version of the mixin where `touchableHandleFocus` and
* `touchableHandleBlur` can be overridden. This allows appropriate defaults to
* be set on TV platforms, without breaking existing implementations of
* `Touchable`.
*/
const {
touchableHandleFocus,
touchableHandleBlur,
...TouchableMixinWithoutDefaultFocusAndBlur
} = TouchableMixinImpl;
TouchableMixinImpl.withoutDefaultFocusAndBlur =
TouchableMixinWithoutDefaultFocusAndBlur;
const TouchableImpl = {
Mixin: TouchableMixinImpl,
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: ({
color,
hitSlop,
}: {
color: ColorValue,
hitSlop?: EdgeInsetsProp,
...
}): null | React.Node => {
if (__DEV__) {
return <PressabilityDebugView color={color} hitSlop={hitSlop} />;
}
return null;
},
};
export default TouchableImpl;

View File

@@ -0,0 +1,235 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
import typeof TouchableWithoutFeedback from './TouchableWithoutFeedback';
import Animated from '../../Animated/Animated';
import Pressability, {
type PressabilityConfig,
} from '../../Pressability/Pressability';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import Platform from '../../Utilities/Platform';
import * as React from 'react';
type TouchableBounceProps = $ReadOnly<{
...React.ElementConfig<TouchableWithoutFeedback>,
onPressAnimationComplete?: ?() => void,
onPressWithCompletion?: ?(callback: () => void) => void,
releaseBounciness?: ?number,
releaseVelocity?: ?number,
style?: ?ViewStyleProp,
hostRef: React.RefSetter<React.ElementRef<typeof Animated.View>>,
}>;
type TouchableBounceState = $ReadOnly<{
pressability: Pressability,
scale: Animated.Value,
}>;
class TouchableBounce extends React.Component<
TouchableBounceProps,
TouchableBounceState,
> {
state: TouchableBounceState = {
pressability: new Pressability(this._createPressabilityConfig()),
scale: new Animated.Value(1),
};
_createPressabilityConfig(): PressabilityConfig {
return {
android_disableSound: this.props.touchSoundDisabled,
cancelable: !this.props.rejectResponderTermination,
delayLongPress: this.props.delayLongPress,
delayPressIn: this.props.delayPressIn,
delayPressOut: this.props.delayPressOut,
disabled: this.props.disabled,
hitSlop: this.props.hitSlop,
minPressDuration: 0,
onBlur: event => {
if (Platform.isTV) {
this._bounceTo(1, 0.4, 0);
}
if (this.props.onBlur != null) {
this.props.onBlur(event);
}
},
onFocus: event => {
if (Platform.isTV) {
this._bounceTo(0.93, 0.1, 0);
}
if (this.props.onFocus != null) {
this.props.onFocus(event);
}
},
onLongPress: this.props.onLongPress,
onPress: event => {
const {onPressAnimationComplete, onPressWithCompletion} = this.props;
const releaseBounciness = this.props.releaseBounciness ?? 10;
const releaseVelocity = this.props.releaseVelocity ?? 10;
if (onPressWithCompletion != null) {
onPressWithCompletion(() => {
this.state.scale.setValue(0.93);
this._bounceTo(
1,
releaseVelocity,
releaseBounciness,
onPressAnimationComplete,
);
});
return;
}
this._bounceTo(
1,
releaseVelocity,
releaseBounciness,
onPressAnimationComplete,
);
if (this.props.onPress != null) {
this.props.onPress(event);
}
},
onPressIn: event => {
this._bounceTo(0.93, 0.1, 0);
if (this.props.onPressIn != null) {
this.props.onPressIn(event);
}
},
onPressOut: event => {
this._bounceTo(1, 0.4, 0);
if (this.props.onPressOut != null) {
this.props.onPressOut(event);
}
},
pressRectOffset: this.props.pressRetentionOffset,
};
}
_bounceTo(
toValue: number,
velocity: number,
bounciness: number,
callback?: ?() => void,
) {
Animated.spring(this.state.scale, {
bounciness,
toValue,
useNativeDriver: true,
velocity,
}).start(callback);
}
render(): React.Node {
// BACKWARD-COMPATIBILITY: Focus and blur events were never supported before
// adopting `Pressability`, so preserve that behavior.
const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} =
this.state.pressability.getEventHandlers();
const accessibilityLiveRegion =
this.props['aria-live'] === 'off'
? 'none'
: (this.props['aria-live'] ?? this.props.accessibilityLiveRegion);
const _accessibilityState = {
busy: this.props['aria-busy'] ?? this.props.accessibilityState?.busy,
checked:
this.props['aria-checked'] ?? this.props.accessibilityState?.checked,
disabled:
this.props['aria-disabled'] ?? this.props.accessibilityState?.disabled,
expanded:
this.props['aria-expanded'] ?? this.props.accessibilityState?.expanded,
selected:
this.props['aria-selected'] ?? this.props.accessibilityState?.selected,
};
const accessibilityValue = {
max: this.props['aria-valuemax'] ?? this.props.accessibilityValue?.max,
min: this.props['aria-valuemin'] ?? this.props.accessibilityValue?.min,
now: this.props['aria-valuenow'] ?? this.props.accessibilityValue?.now,
text: this.props['aria-valuetext'] ?? this.props.accessibilityValue?.text,
};
const accessibilityLabel =
this.props['aria-label'] ?? this.props.accessibilityLabel;
return (
<Animated.View
style={[{transform: [{scale: this.state.scale}]}, this.props.style]}
accessible={this.props.accessible !== false}
accessibilityLabel={accessibilityLabel}
accessibilityHint={this.props.accessibilityHint}
accessibilityLanguage={this.props.accessibilityLanguage}
accessibilityRole={this.props.accessibilityRole}
accessibilityState={_accessibilityState}
accessibilityActions={this.props.accessibilityActions}
onAccessibilityAction={this.props.onAccessibilityAction}
accessibilityValue={accessibilityValue}
accessibilityLiveRegion={accessibilityLiveRegion}
importantForAccessibility={
this.props['aria-hidden'] === true
? 'no-hide-descendants'
: // $FlowFixMe[incompatible-type] - AnimatedProps types were made more strict and need refining at this call site
this.props.importantForAccessibility
}
accessibilityViewIsModal={
this.props['aria-modal'] ?? this.props.accessibilityViewIsModal
}
accessibilityElementsHidden={
this.props['aria-hidden'] ?? this.props.accessibilityElementsHidden
}
nativeID={this.props.id ?? this.props.nativeID}
testID={this.props.testID}
hitSlop={this.props.hitSlop}
focusable={
this.props.focusable !== false &&
this.props.onPress !== undefined &&
!this.props.disabled
}
// $FlowFixMe[prop-missing]
ref={this.props.hostRef}
{...eventHandlersWithoutBlurAndFocus}>
{this.props.children}
{__DEV__ ? (
<PressabilityDebugView color="orange" hitSlop={this.props.hitSlop} />
) : null}
</Animated.View>
);
}
componentDidUpdate(
prevProps: TouchableBounceProps,
prevState: TouchableBounceState,
) {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentDidMount(): mixed {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentWillUnmount(): void {
this.state.pressability.reset();
this.state.scale.resetAnimation();
}
}
export default (function TouchableBounceWrapper({
ref: hostRef,
...props
}: {
ref: React.RefSetter<mixed>,
...$ReadOnly<Omit<TouchableBounceProps, 'hostRef'>>,
}) {
return <TouchableBounce {...props} hostRef={hostRef} />;
} as component(
ref?: React.RefSetter<mixed>,
...props: $ReadOnly<Omit<TouchableBounceProps, 'hostRef'>>
));

View File

@@ -0,0 +1,62 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import type * as React from 'react';
import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet';
import {ViewStyle} from '../../StyleSheet/StyleSheetTypes';
import {View} from '../../Components/View/View';
import {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
/**
* @see https://reactnative.dev/docs/touchablehighlight#props
*/
export interface TouchableHighlightProps extends TouchableWithoutFeedbackProps {
/**
* Determines what the opacity of the wrapped view should be when touch is active.
*/
activeOpacity?: number | undefined;
/**
*
* Called immediately after the underlay is hidden
*/
onHideUnderlay?: (() => void) | undefined;
/**
* Called immediately after the underlay is shown
*/
onShowUnderlay?: (() => void) | undefined;
/**
* @see https://reactnative.dev/docs/view#style
*/
style?: StyleProp<ViewStyle> | undefined;
/**
* The color of the underlay that will show through when the touch is active.
*/
underlayColor?: ColorValue | undefined;
}
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased,
* which allows the underlay color to show through, darkening or tinting the view.
* The underlay comes from adding a view to the view hierarchy,
* which can sometimes cause unwanted visual artifacts if not used correctly,
* for example if the backgroundColor of the wrapped view isn't explicitly set to an opaque color.
*
* NOTE: TouchableHighlight supports only one child
* If you wish to have several child components, wrap them in a View.
*
* @see https://reactnative.dev/docs/touchablehighlight
*/
export const TouchableHighlight: React.ForwardRefExoticComponent<
React.PropsWithoutRef<TouchableHighlightProps> & React.RefAttributes<View>
>;

View File

@@ -0,0 +1,426 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {ColorValue} from '../../StyleSheet/StyleSheet';
import type {AccessibilityState} from '../View/ViewAccessibility';
import type {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
import View from '../../Components/View/View';
import Pressability, {
type PressabilityConfig,
} from '../../Pressability/Pressability';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import StyleSheet, {type ViewStyleProp} from '../../StyleSheet/StyleSheet';
import Platform from '../../Utilities/Platform';
import * as React from 'react';
import {cloneElement} from 'react';
type AndroidProps = $ReadOnly<{
nextFocusDown?: ?number,
nextFocusForward?: ?number,
nextFocusLeft?: ?number,
nextFocusRight?: ?number,
nextFocusUp?: ?number,
}>;
type IOSProps = $ReadOnly<{
/**
* @deprecated Use `focusable` instead
*/
hasTVPreferredFocus?: ?boolean,
}>;
type TouchableHighlightBaseProps = $ReadOnly<{
/**
* Determines what the opacity of the wrapped view should be when touch is active.
*/
activeOpacity?: ?number,
/**
* The color of the underlay that will show through when the touch is active.
*/
underlayColor?: ?ColorValue,
/**
* @see https://reactnative.dev/docs/view#style
*/
style?: ?ViewStyleProp,
/**
* Called immediately after the underlay is shown
*/
onShowUnderlay?: ?() => void,
/**
* Called immediately after the underlay is hidden
*/
onHideUnderlay?: ?() => void,
testOnly_pressed?: ?boolean,
hostRef?: React.RefSetter<React.ElementRef<typeof View>>,
}>;
export type TouchableHighlightProps = $ReadOnly<{
...TouchableWithoutFeedbackProps,
...AndroidProps,
...IOSProps,
...TouchableHighlightBaseProps,
}>;
type ExtraStyles = $ReadOnly<{
child: ViewStyleProp,
underlay: ViewStyleProp,
}>;
type TouchableHighlightState = $ReadOnly<{
pressability: Pressability,
extraStyles: ?ExtraStyles,
}>;
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, which allows
* the underlay color to show through, darkening or tinting the view.
*
* The underlay comes from wrapping the child in a new View, which can affect
* layout, and sometimes cause unwanted visual artifacts if not used correctly,
* for example if the backgroundColor of the wrapped view isn't explicitly set
* to an opaque color.
*
* TouchableHighlight must have one child (not zero or more than one).
* If you wish to have several child components, wrap them in a View.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableHighlight onPress={this._onPressButton}>
* <Image
* style={styles.button}
* source={require('./myButton.png')}
* />
* </TouchableHighlight>
* );
* },
* ```
*
*
* ### Example
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react'
* import {
* AppRegistry,
* StyleSheet,
* TouchableHighlight,
* Text,
* View,
* } from 'react-native'
*
* class App extends Component {
* constructor(props) {
* super(props)
* this.state = { count: 0 }
* }
*
* onPress = () => {
* this.setState({
* count: this.state.count+1
* })
* }
*
* render() {
* return (
* <View style={styles.container}>
* <TouchableHighlight
* style={styles.button}
* onPress={this.onPress}
* >
* <Text> Touch Here </Text>
* </TouchableHighlight>
* <View style={[styles.countContainer]}>
* <Text style={[styles.countText]}>
* { this.state.count !== 0 ? this.state.count: null}
* </Text>
* </View>
* </View>
* )
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* justifyContent: 'center',
* paddingHorizontal: 10
* },
* button: {
* alignItems: 'center',
* backgroundColor: '#DDDDDD',
* padding: 10
* },
* countContainer: {
* alignItems: 'center',
* padding: 10
* },
* countText: {
* color: '#FF00FF'
* }
* })
*
* AppRegistry.registerComponent('App', () => App)
* ```
*
*/
class TouchableHighlightImpl extends React.Component<
TouchableHighlightProps,
TouchableHighlightState,
> {
_hideTimeout: ?TimeoutID;
_isMounted: boolean = false;
state: TouchableHighlightState = {
pressability: new Pressability(this._createPressabilityConfig()),
extraStyles:
this.props.testOnly_pressed === true ? this._createExtraStyles() : null,
};
_createPressabilityConfig(): PressabilityConfig {
return {
cancelable: !this.props.rejectResponderTermination,
disabled:
this.props.disabled != null
? this.props.disabled
: this.props.accessibilityState?.disabled,
hitSlop: this.props.hitSlop,
delayLongPress: this.props.delayLongPress,
delayPressIn: this.props.delayPressIn,
delayPressOut: this.props.delayPressOut,
minPressDuration: 0,
pressRectOffset: this.props.pressRetentionOffset,
android_disableSound: this.props.touchSoundDisabled,
onBlur: event => {
if (Platform.isTV) {
this._hideUnderlay();
}
if (this.props.onBlur != null) {
this.props.onBlur(event);
}
},
onFocus: event => {
if (Platform.isTV) {
this._showUnderlay();
}
if (this.props.onFocus != null) {
this.props.onFocus(event);
}
},
onLongPress: this.props.onLongPress,
onPress: event => {
if (this._hideTimeout != null) {
clearTimeout(this._hideTimeout);
}
if (!Platform.isTV) {
this._showUnderlay();
this._hideTimeout = setTimeout(() => {
this._hideUnderlay();
}, this.props.delayPressOut ?? 0);
}
if (this.props.onPress != null) {
this.props.onPress(event);
}
},
onPressIn: event => {
if (this._hideTimeout != null) {
clearTimeout(this._hideTimeout);
this._hideTimeout = null;
}
this._showUnderlay();
if (this.props.onPressIn != null) {
this.props.onPressIn(event);
}
},
onPressOut: event => {
if (this._hideTimeout == null) {
this._hideUnderlay();
}
if (this.props.onPressOut != null) {
this.props.onPressOut(event);
}
},
};
}
_createExtraStyles(): ExtraStyles {
return {
child: {opacity: this.props.activeOpacity ?? 0.85},
underlay: {
backgroundColor:
this.props.underlayColor === undefined
? 'black'
: this.props.underlayColor,
},
};
}
_showUnderlay(): void {
if (!this._isMounted || !this._hasPressHandler()) {
return;
}
this.setState({extraStyles: this._createExtraStyles()});
if (this.props.onShowUnderlay != null) {
this.props.onShowUnderlay();
}
}
_hideUnderlay(): void {
if (this._hideTimeout != null) {
clearTimeout(this._hideTimeout);
this._hideTimeout = null;
}
if (this.props.testOnly_pressed === true) {
return;
}
if (this._hasPressHandler()) {
this.setState({extraStyles: null});
if (this.props.onHideUnderlay != null) {
this.props.onHideUnderlay();
}
}
}
_hasPressHandler(): boolean {
return (
this.props.onPress != null ||
this.props.onPressIn != null ||
this.props.onPressOut != null ||
this.props.onLongPress != null
);
}
render(): React.Node {
const child = React.Children.only<$FlowFixMe>(this.props.children);
// BACKWARD-COMPATIBILITY: Focus and blur events were never supported before
// adopting `Pressability`, so preserve that behavior.
const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} =
this.state.pressability.getEventHandlers();
const accessibilityState: ?AccessibilityState =
this.props.disabled != null
? {
...this.props.accessibilityState,
disabled: this.props.disabled,
}
: this.props.accessibilityState;
const accessibilityValue = {
max: this.props['aria-valuemax'] ?? this.props.accessibilityValue?.max,
min: this.props['aria-valuemin'] ?? this.props.accessibilityValue?.min,
now: this.props['aria-valuenow'] ?? this.props.accessibilityValue?.now,
text: this.props['aria-valuetext'] ?? this.props.accessibilityValue?.text,
};
const accessibilityLiveRegion =
this.props['aria-live'] === 'off'
? 'none'
: (this.props['aria-live'] ?? this.props.accessibilityLiveRegion);
const accessibilityLabel =
this.props['aria-label'] ?? this.props.accessibilityLabel;
return (
<View
accessible={this.props.accessible !== false}
accessibilityLabel={accessibilityLabel}
accessibilityHint={this.props.accessibilityHint}
accessibilityLanguage={this.props.accessibilityLanguage}
accessibilityRole={this.props.accessibilityRole}
accessibilityState={accessibilityState}
accessibilityValue={accessibilityValue}
accessibilityActions={this.props.accessibilityActions}
onAccessibilityAction={this.props.onAccessibilityAction}
importantForAccessibility={
this.props['aria-hidden'] === true
? 'no-hide-descendants'
: this.props.importantForAccessibility
}
accessibilityViewIsModal={
this.props['aria-modal'] ?? this.props.accessibilityViewIsModal
}
accessibilityLiveRegion={accessibilityLiveRegion}
accessibilityElementsHidden={
this.props['aria-hidden'] ?? this.props.accessibilityElementsHidden
}
style={StyleSheet.compose(
this.props.style,
this.state.extraStyles?.underlay,
)}
onLayout={this.props.onLayout}
hitSlop={this.props.hitSlop}
hasTVPreferredFocus={this.props.hasTVPreferredFocus}
nextFocusDown={this.props.nextFocusDown}
nextFocusForward={this.props.nextFocusForward}
nextFocusLeft={this.props.nextFocusLeft}
nextFocusRight={this.props.nextFocusRight}
nextFocusUp={this.props.nextFocusUp}
focusable={
this.props.focusable !== false &&
this.props.onPress !== undefined &&
!this.props.disabled
}
nativeID={this.props.id ?? this.props.nativeID}
testID={this.props.testID}
ref={this.props.hostRef}
{...eventHandlersWithoutBlurAndFocus}>
{cloneElement(child, {
style: StyleSheet.compose(
child.props.style,
this.state.extraStyles?.child,
),
})}
{__DEV__ ? (
<PressabilityDebugView color="green" hitSlop={this.props.hitSlop} />
) : null}
</View>
);
}
componentDidMount(): void {
this._isMounted = true;
this.state.pressability.configure(this._createPressabilityConfig());
}
componentDidUpdate(
prevProps: TouchableHighlightProps,
prevState: TouchableHighlightState,
) {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentWillUnmount(): void {
this._isMounted = false;
if (this._hideTimeout != null) {
clearTimeout(this._hideTimeout);
}
this.state.pressability.reset();
}
}
const TouchableHighlight: component(
ref?: React.RefSetter<React.ElementRef<typeof View>>,
...props: $ReadOnly<Omit<TouchableHighlightProps, 'hostRef'>>
) = ({
ref: hostRef,
...props
}: {
ref?: React.RefSetter<React.ElementRef<typeof View>>,
...$ReadOnly<Omit<TouchableHighlightProps, 'hostRef'>>,
}) => <TouchableHighlightImpl {...props} hostRef={hostRef} />;
TouchableHighlight.displayName = 'TouchableHighlight';
export default TouchableHighlight;

View File

@@ -0,0 +1,114 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import type * as React from 'react';
import {Constructor} from '../../../types/private/Utilities';
import {ColorValue} from '../../StyleSheet/StyleSheet';
import {TouchableMixin} from './Touchable';
import type {TVProps} from './TouchableOpacity';
import {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
interface BaseBackgroundPropType {
type: string;
rippleRadius?: number | null | undefined;
}
interface RippleBackgroundPropType extends BaseBackgroundPropType {
type: 'RippleAndroid';
borderless: boolean;
color?: number | null | undefined;
}
interface ThemeAttributeBackgroundPropType extends BaseBackgroundPropType {
type: 'ThemeAttrAndroid';
attribute: string;
}
type BackgroundPropType =
| RippleBackgroundPropType
| ThemeAttributeBackgroundPropType;
/**
* @see https://reactnative.dev/docs/touchablenativefeedback#props
*/
export interface TouchableNativeFeedbackProps
extends TouchableWithoutFeedbackProps,
TVProps {
/**
* Determines the type of background drawable that's going to be used to display feedback.
* It takes an object with type property and extra data depending on the type.
* It's recommended to use one of the following static methods to generate that dictionary:
* 1) TouchableNativeFeedback.SelectableBackground() - will create object that represents android theme's
* default background for selectable elements (?android:attr/selectableItemBackground)
* 2) TouchableNativeFeedback.SelectableBackgroundBorderless() - will create object that represent android
* theme's default background for borderless selectable elements
* (?android:attr/selectableItemBackgroundBorderless). Available on android API level 21+
* 3) TouchableNativeFeedback.Ripple(color, borderless) - will create object that represents ripple drawable
* with specified color (as a string). If property borderless evaluates to true the ripple will render
* outside of the view bounds (see native actionbar buttons as an example of that behavior). This background
* type is available on Android API level 21+
*/
background?: BackgroundPropType | undefined;
useForeground?: boolean | undefined;
}
/**
* A wrapper for making views respond properly to touches (Android only).
* On Android this component uses native state drawable to display touch feedback.
* At the moment it only supports having a single View instance as a child node,
* as it's implemented by replacing that View with another instance of RCTView node with some additional properties set.
*
* Background drawable of native feedback touchable can be customized with background property.
*
* @see https://reactnative.dev/docs/touchablenativefeedback#content
*/
declare class TouchableNativeFeedbackComponent extends React.Component<TouchableNativeFeedbackProps> {}
declare const TouchableNativeFeedbackBase: Constructor<TouchableMixin> &
typeof TouchableNativeFeedbackComponent;
export class TouchableNativeFeedback extends TouchableNativeFeedbackBase {
/**
* Creates an object that represents android theme's default background for
* selectable elements (?android:attr/selectableItemBackground).
*
* @param rippleRadius The radius of ripple effect
*/
static SelectableBackground(
rippleRadius?: number | null,
): ThemeAttributeBackgroundPropType;
/**
* Creates an object that represent android theme's default background for borderless
* selectable elements (?android:attr/selectableItemBackgroundBorderless).
* Available on android API level 21+.
*
* @param rippleRadius The radius of ripple effect
*/
static SelectableBackgroundBorderless(
rippleRadius?: number | null,
): ThemeAttributeBackgroundPropType;
/**
* Creates an object that represents ripple drawable with specified color (as a
* string). If property `borderless` evaluates to true the ripple will
* render outside of the view bounds (see native actionbar buttons as an
* example of that behavior). This background type is available on Android
* API level 21+.
*
* @param color The ripple color
* @param borderless If the ripple can render outside it's bounds
* @param rippleRadius The radius of ripple effect
*/
static Ripple(
color: ColorValue,
borderless: boolean,
rippleRadius?: number | null,
): RippleBackgroundPropType;
static canUseNativeForeground(): boolean;
}

View File

@@ -0,0 +1,416 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {GestureResponderEvent} from '../../Types/CoreEventTypes';
import type {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
import View from '../../Components/View/View';
import Pressability, {
type PressabilityConfig,
} from '../../Pressability/Pressability';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import {findHostInstance_DEPRECATED} from '../../ReactNative/RendererProxy';
import processColor from '../../StyleSheet/processColor';
import Platform from '../../Utilities/Platform';
import {Commands} from '../View/ViewNativeComponent';
import invariant from 'invariant';
import * as React from 'react';
import {cloneElement} from 'react';
type TouchableNativeFeedbackTVProps = {
/**
* *(Apple TV only)* TV preferred focus (see documentation for the View component).
*
* @platform ios
* @deprecated Use `focusable` instead
*/
hasTVPreferredFocus?: ?boolean,
/**
* Designates the next view to receive focus when the user navigates down. See the Android documentation.
*
* @platform android
*/
nextFocusDown?: ?number,
/**
* Designates the next view to receive focus when the user navigates forward. See the Android documentation.
*
* @platform android
*/
nextFocusForward?: ?number,
/**
* Designates the next view to receive focus when the user navigates left. See the Android documentation.
*
* @platform android
*/
nextFocusLeft?: ?number,
/**
* Designates the next view to receive focus when the user navigates right. See the Android documentation.
*
* @platform android
*/
nextFocusRight?: ?number,
/**
* Designates the next view to receive focus when the user navigates up. See the Android documentation.
*
* @platform android
*/
nextFocusUp?: ?number,
};
export type TouchableNativeFeedbackProps = $ReadOnly<{
...TouchableWithoutFeedbackProps,
...TouchableNativeFeedbackTVProps,
/**
* Determines the type of background drawable that's going to be used to display feedback.
* It takes an object with type property and extra data depending on the type.
* It's recommended to use one of the following static methods to generate that dictionary:
* 1) TouchableNativeFeedback.SelectableBackground() - will create object that represents android theme's
* default background for selectable elements (?android:attr/selectableItemBackground)
* 2) TouchableNativeFeedback.SelectableBackgroundBorderless() - will create object that represent android
* theme's default background for borderless selectable elements
* (?android:attr/selectableItemBackgroundBorderless). Available on android API level 21+
* 3) TouchableNativeFeedback.Ripple(color, borderless) - will create object that represents ripple drawable
* with specified color (as a string). If property borderless evaluates to true the ripple will render
* outside of the view bounds (see native actionbar buttons as an example of that behavior). This background
* type is available on Android API level 21+
*/
background?: ?(
| $ReadOnly<{
type: 'ThemeAttrAndroid',
attribute:
| 'selectableItemBackground'
| 'selectableItemBackgroundBorderless',
rippleRadius: ?number,
}>
| $ReadOnly<{
type: 'RippleAndroid',
color: ?number,
borderless: boolean,
rippleRadius: ?number,
}>
),
/**
* Set to true to add the ripple effect to the foreground of the view, instead
* of the background. This is useful if one of your child views has a
* background of its own, or you're e.g. displaying images, and you don't want
* the ripple to be covered by them.
*
* Check TouchableNativeFeedback.canUseNativeForeground() first, as this is
* only available on Android 6.0 and above. If you try to use this on older
* versions, this will fallback to background.
*/
useForeground?: ?boolean,
}>;
type TouchableNativeFeedbackState = $ReadOnly<{
pressability: Pressability,
}>;
/**
* A wrapper for making views respond properly to touches (Android only).
* On Android this component uses native state drawable to display touch feedback.
* At the moment it only supports having a single View instance as a child node,
* as it's implemented by replacing that View with another instance of RCTView node with some additional properties set.
*
* Background drawable of native feedback touchable can be customized with background property.
*
* @see https://reactnative.dev/docs/touchablenativefeedback#content
*/
class TouchableNativeFeedback extends React.Component<
TouchableNativeFeedbackProps,
TouchableNativeFeedbackState,
> {
/**
* Creates an object that represents android theme's default background for
* selectable elements (?android:attr/selectableItemBackground).
*
* @param rippleRadius The radius of ripple effect
*/
static SelectableBackground: (rippleRadius?: ?number) => $ReadOnly<{
attribute: 'selectableItemBackground',
type: 'ThemeAttrAndroid',
rippleRadius: ?number,
}> = (rippleRadius?: ?number) => ({
type: 'ThemeAttrAndroid',
attribute: 'selectableItemBackground',
rippleRadius,
});
/**
* Creates an object that represent android theme's default background for borderless
* selectable elements (?android:attr/selectableItemBackgroundBorderless).
* Available on android API level 21+.
*
* @param rippleRadius The radius of ripple effect
*/
static SelectableBackgroundBorderless: (rippleRadius?: ?number) => $ReadOnly<{
attribute: 'selectableItemBackgroundBorderless',
type: 'ThemeAttrAndroid',
rippleRadius: ?number,
}> = (rippleRadius?: ?number) => ({
type: 'ThemeAttrAndroid',
attribute: 'selectableItemBackgroundBorderless',
rippleRadius,
});
/**
* Creates an object that represents ripple drawable with specified color (as a
* string). If property `borderless` evaluates to true the ripple will
* render outside of the view bounds (see native actionbar buttons as an
* example of that behavior). This background type is available on Android
* API level 21+.
*
* @param color The ripple color
* @param borderless If the ripple can render outside it's bounds
* @param rippleRadius The radius of ripple effect
*/
static Ripple: (
color: string,
borderless: boolean,
rippleRadius?: ?number,
) => $ReadOnly<{
borderless: boolean,
color: ?number,
rippleRadius: ?number,
type: 'RippleAndroid',
}> = (color: string, borderless: boolean, rippleRadius?: ?number) => {
const processedColor = processColor(color);
invariant(
processedColor == null || typeof processedColor === 'number',
'Unexpected color given for Ripple color',
);
return {
type: 'RippleAndroid',
// $FlowFixMe[incompatible-type]
color: processedColor,
borderless,
rippleRadius,
};
};
/**
* Whether `useForeground` is supported.
*/
static canUseNativeForeground: () => boolean = () =>
Platform.OS === 'android';
state: TouchableNativeFeedbackState = {
pressability: new Pressability(this._createPressabilityConfig()),
};
_createPressabilityConfig(): PressabilityConfig {
const accessibilityStateDisabled =
this.props['aria-disabled'] ?? this.props.accessibilityState?.disabled;
return {
cancelable: !this.props.rejectResponderTermination,
disabled:
this.props.disabled != null
? this.props.disabled
: accessibilityStateDisabled,
hitSlop: this.props.hitSlop,
delayLongPress: this.props.delayLongPress,
delayPressIn: this.props.delayPressIn,
delayPressOut: this.props.delayPressOut,
minPressDuration: 0,
pressRectOffset: this.props.pressRetentionOffset,
android_disableSound: this.props.touchSoundDisabled,
onLongPress: this.props.onLongPress,
onPress: this.props.onPress,
onPressIn: event => {
if (Platform.OS === 'android') {
this._dispatchHotspotUpdate(event);
this._dispatchPressedStateChange(true);
}
if (this.props.onPressIn != null) {
this.props.onPressIn(event);
}
},
onPressMove: event => {
if (Platform.OS === 'android') {
this._dispatchHotspotUpdate(event);
}
},
onPressOut: event => {
if (Platform.OS === 'android') {
this._dispatchPressedStateChange(false);
}
if (this.props.onPressOut != null) {
this.props.onPressOut(event);
}
},
};
}
_dispatchPressedStateChange(pressed: boolean): void {
if (Platform.OS === 'android') {
const hostComponentRef = findHostInstance_DEPRECATED<$FlowFixMe>(this);
if (hostComponentRef == null) {
console.warn(
'Touchable: Unable to find HostComponent instance. ' +
'Has your Touchable component been unmounted?',
);
} else {
Commands.setPressed(hostComponentRef, pressed);
}
}
}
_dispatchHotspotUpdate(event: GestureResponderEvent): void {
if (Platform.OS === 'android') {
const {locationX, locationY} = event.nativeEvent;
const hostComponentRef = findHostInstance_DEPRECATED<$FlowFixMe>(this);
if (hostComponentRef == null) {
console.warn(
'Touchable: Unable to find HostComponent instance. ' +
'Has your Touchable component been unmounted?',
);
} else {
Commands.hotspotUpdate(
hostComponentRef,
locationX ?? 0,
locationY ?? 0,
);
}
}
}
render(): React.Node {
const element = React.Children.only<$FlowFixMe>(this.props.children);
const children: Array<React.Node> = [element.props.children];
if (__DEV__) {
if (element.type === View) {
children.push(
<PressabilityDebugView color="brown" hitSlop={this.props.hitSlop} />,
);
}
}
// BACKWARD-COMPATIBILITY: Focus and blur events were never supported before
// adopting `Pressability`, so preserve that behavior.
const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} =
this.state.pressability.getEventHandlers();
let _accessibilityState = {
busy: this.props['aria-busy'] ?? this.props.accessibilityState?.busy,
checked:
this.props['aria-checked'] ?? this.props.accessibilityState?.checked,
disabled:
this.props['aria-disabled'] ?? this.props.accessibilityState?.disabled,
expanded:
this.props['aria-expanded'] ?? this.props.accessibilityState?.expanded,
selected:
this.props['aria-selected'] ?? this.props.accessibilityState?.selected,
};
_accessibilityState =
this.props.disabled != null
? {
..._accessibilityState,
disabled: this.props.disabled,
}
: _accessibilityState;
const accessibilityValue = {
max: this.props['aria-valuemax'] ?? this.props.accessibilityValue?.max,
min: this.props['aria-valuemin'] ?? this.props.accessibilityValue?.min,
now: this.props['aria-valuenow'] ?? this.props.accessibilityValue?.now,
text: this.props['aria-valuetext'] ?? this.props.accessibilityValue?.text,
};
const accessibilityLiveRegion =
this.props['aria-live'] === 'off'
? 'none'
: (this.props['aria-live'] ?? this.props.accessibilityLiveRegion);
const accessibilityLabel =
this.props['aria-label'] ?? this.props.accessibilityLabel;
return cloneElement(
element,
{
...eventHandlersWithoutBlurAndFocus,
...getBackgroundProp(
this.props.background === undefined
? TouchableNativeFeedback.SelectableBackground()
: this.props.background,
this.props.useForeground === true,
),
accessible: this.props.accessible !== false,
accessibilityHint: this.props.accessibilityHint,
accessibilityLanguage: this.props.accessibilityLanguage,
accessibilityLabel: accessibilityLabel,
accessibilityRole: this.props.accessibilityRole,
accessibilityState: _accessibilityState,
accessibilityActions: this.props.accessibilityActions,
onAccessibilityAction: this.props.onAccessibilityAction,
accessibilityValue: accessibilityValue,
importantForAccessibility:
this.props['aria-hidden'] === true
? 'no-hide-descendants'
: this.props.importantForAccessibility,
accessibilityViewIsModal:
this.props['aria-modal'] ?? this.props.accessibilityViewIsModal,
accessibilityLiveRegion: accessibilityLiveRegion,
accessibilityElementsHidden:
this.props['aria-hidden'] ?? this.props.accessibilityElementsHidden,
hasTVPreferredFocus: this.props.hasTVPreferredFocus,
hitSlop: this.props.hitSlop,
focusable:
this.props.focusable !== false &&
this.props.onPress !== undefined &&
!this.props.disabled,
nativeID: this.props.id ?? this.props.nativeID,
nextFocusDown: this.props.nextFocusDown,
nextFocusForward: this.props.nextFocusForward,
nextFocusLeft: this.props.nextFocusLeft,
nextFocusRight: this.props.nextFocusRight,
nextFocusUp: this.props.nextFocusUp,
onLayout: this.props.onLayout,
testID: this.props.testID,
},
...children,
);
}
componentDidUpdate(
prevProps: TouchableNativeFeedbackProps,
prevState: TouchableNativeFeedbackState,
) {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentDidMount(): mixed {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentWillUnmount(): void {
this.state.pressability.reset();
}
}
const getBackgroundProp =
Platform.OS === 'android'
? /* $FlowFixMe[missing-local-annot] The type annotation(s) required by
* Flow's LTI update could not be added via codemod */
(background, useForeground: boolean) =>
useForeground && TouchableNativeFeedback.canUseNativeForeground()
? {nativeForegroundAndroid: background}
: {nativeBackgroundAndroid: background}
: /* $FlowFixMe[missing-local-annot] The type annotation(s) required by
* Flow's LTI update could not be added via codemod */
(background, useForeground: boolean) => null;
TouchableNativeFeedback.displayName = 'TouchableNativeFeedback';
export default TouchableNativeFeedback;

View File

@@ -0,0 +1,82 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import type * as React from 'react';
import {View} from '../../Components/View/View';
import {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
export interface TVProps {
/**
* *(Apple TV only)* TV preferred focus (see documentation for the View component).
*
* @platform ios
* @deprecated Use `focusable` instead
*/
hasTVPreferredFocus?: boolean | undefined;
/**
* Designates the next view to receive focus when the user navigates down. See the Android documentation.
*
* @platform android
*/
nextFocusDown?: number | undefined;
/**
* Designates the next view to receive focus when the user navigates forward. See the Android documentation.
*
* @platform android
*/
nextFocusForward?: number | undefined;
/**
* Designates the next view to receive focus when the user navigates left. See the Android documentation.
*
* @platform android
*/
nextFocusLeft?: number | undefined;
/**
* Designates the next view to receive focus when the user navigates right. See the Android documentation.
*
* @platform android
*/
nextFocusRight?: number | undefined;
/**
* Designates the next view to receive focus when the user navigates up. See the Android documentation.
*
* @platform android
*/
nextFocusUp?: number | undefined;
}
/**
* @see https://reactnative.dev/docs/touchableopacity#props
*/
export interface TouchableOpacityProps
extends TouchableWithoutFeedbackProps,
TVProps {
/**
* Determines what the opacity of the wrapped view should be when touch is active.
* Defaults to 0.2
*/
activeOpacity?: number | undefined;
}
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, dimming it.
* This is done without actually changing the view hierarchy,
* and in general is easy to add to an app without weird side-effects.
*
* @see https://reactnative.dev/docs/touchableopacity
*/
export const TouchableOpacity: React.ForwardRefExoticComponent<
React.PropsWithoutRef<TouchableOpacityProps> & React.RefAttributes<View>
>;

View File

@@ -0,0 +1,393 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
import type {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback';
import Animated from '../../Animated/Animated';
import Easing from '../../Animated/Easing';
import Pressability, {
type PressabilityConfig,
} from '../../Pressability/Pressability';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import flattenStyle from '../../StyleSheet/flattenStyle';
import Platform from '../../Utilities/Platform';
import * as React from 'react';
export type TouchableOpacityTVProps = $ReadOnly<{
/**
* *(Apple TV only)* TV preferred focus (see documentation for the View component).
*
* @platform ios
* @deprecated Use `focusable` instead
*/
hasTVPreferredFocus?: ?boolean,
/**
* Designates the next view to receive focus when the user navigates down. See the Android documentation.
*
* @platform android
*/
nextFocusDown?: ?number,
/**
* Designates the next view to receive focus when the user navigates forward. See the Android documentation.
*
* @platform android
*/
nextFocusForward?: ?number,
/**
* Designates the next view to receive focus when the user navigates left. See the Android documentation.
*
* @platform android
*/
nextFocusLeft?: ?number,
/**
* Designates the next view to receive focus when the user navigates right. See the Android documentation.
*
* @platform android
*/
nextFocusRight?: ?number,
/**
* Designates the next view to receive focus when the user navigates up. See the Android documentation.
*
* @platform android
*/
nextFocusUp?: ?number,
}>;
type TouchableOpacityBaseProps = $ReadOnly<{
/**
* Determines what the opacity of the wrapped view should be when touch is active.
* Defaults to 0.2
*/
activeOpacity?: ?number,
style?: ?Animated.WithAnimatedValue<ViewStyleProp>,
hostRef?: ?React.RefSetter<React.ElementRef<typeof Animated.View>>,
}>;
export type TouchableOpacityProps = $ReadOnly<{
...TouchableWithoutFeedbackProps,
...TouchableOpacityTVProps,
...TouchableOpacityBaseProps,
}>;
type TouchableOpacityState = $ReadOnly<{
anim: Animated.Value,
pressability: Pressability,
}>;
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, dimming it.
*
* Opacity is controlled by wrapping the children in an Animated.View, which is
* added to the view hierarchy. Be aware that this can affect layout.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableOpacity onPress={this._onPressButton}>
* <Image
* style={styles.button}
* source={require('./myButton.png')}
* />
* </TouchableOpacity>
* );
* },
* ```
* ### Example
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react'
* import {
* AppRegistry,
* StyleSheet,
* TouchableOpacity,
* Text,
* View,
* } from 'react-native'
*
* class App extends Component {
* state = { count: 0 }
*
* onPress = () => {
* this.setState(state => ({
* count: state.count + 1
* }));
* };
*
* render() {
* return (
* <View style={styles.container}>
* <TouchableOpacity
* style={styles.button}
* onPress={this.onPress}>
* <Text> Touch Here </Text>
* </TouchableOpacity>
* <View style={[styles.countContainer]}>
* <Text style={[styles.countText]}>
* { this.state.count !== 0 ? this.state.count: null}
* </Text>
* </View>
* </View>
* )
* }
* }
*
* const styles = StyleSheet.create({
* container: {
* flex: 1,
* justifyContent: 'center',
* paddingHorizontal: 10
* },
* button: {
* alignItems: 'center',
* backgroundColor: '#DDDDDD',
* padding: 10
* },
* countContainer: {
* alignItems: 'center',
* padding: 10
* },
* countText: {
* color: '#FF00FF'
* }
* })
*
* AppRegistry.registerComponent('App', () => App)
* ```
*
*/
class TouchableOpacity extends React.Component<
TouchableOpacityProps,
TouchableOpacityState,
> {
state: TouchableOpacityState = {
anim: new Animated.Value(this._getChildStyleOpacityWithDefault()),
pressability: new Pressability(this._createPressabilityConfig()),
};
_createPressabilityConfig(): PressabilityConfig {
return {
cancelable: !this.props.rejectResponderTermination,
disabled:
this.props.disabled ??
this.props['aria-disabled'] ??
this.props.accessibilityState?.disabled,
hitSlop: this.props.hitSlop,
delayLongPress: this.props.delayLongPress,
delayPressIn: this.props.delayPressIn,
delayPressOut: this.props.delayPressOut,
minPressDuration: 0,
pressRectOffset: this.props.pressRetentionOffset,
onBlur: event => {
if (Platform.isTV) {
this._opacityInactive(250);
}
if (this.props.onBlur != null) {
this.props.onBlur(event);
}
},
onFocus: event => {
if (Platform.isTV) {
this._opacityActive(150);
}
if (this.props.onFocus != null) {
this.props.onFocus(event);
}
},
onLongPress: this.props.onLongPress,
onPress: this.props.onPress,
onPressIn: event => {
this._opacityActive(
event.dispatchConfig.registrationName === 'onResponderGrant'
? 0
: 150,
);
if (this.props.onPressIn != null) {
this.props.onPressIn(event);
}
},
onPressOut: event => {
this._opacityInactive(250);
if (this.props.onPressOut != null) {
this.props.onPressOut(event);
}
},
};
}
/**
* Animate the touchable to a new opacity.
*/
_setOpacityTo(toValue: number, duration: number): void {
Animated.timing(this.state.anim, {
toValue,
duration,
easing: Easing.inOut(Easing.quad),
useNativeDriver: true,
}).start();
}
_opacityActive(duration: number): void {
this._setOpacityTo(this.props.activeOpacity ?? 0.2, duration);
}
_opacityInactive(duration: number): void {
this._setOpacityTo(this._getChildStyleOpacityWithDefault(), duration);
}
_getChildStyleOpacityWithDefault(): number {
// $FlowFixMe[underconstrained-implicit-instantiation]
// $FlowFixMe[prop-missing]
const opacity = flattenStyle(this.props.style)?.opacity;
return typeof opacity === 'number' ? opacity : 1;
}
render(): React.Node {
// BACKWARD-COMPATIBILITY: Focus and blur events were never supported before
// adopting `Pressability`, so preserve that behavior.
const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} =
this.state.pressability.getEventHandlers();
let _accessibilityState = {
busy: this.props['aria-busy'] ?? this.props.accessibilityState?.busy,
checked:
this.props['aria-checked'] ?? this.props.accessibilityState?.checked,
disabled:
this.props['aria-disabled'] ?? this.props.accessibilityState?.disabled,
expanded:
this.props['aria-expanded'] ?? this.props.accessibilityState?.expanded,
selected:
this.props['aria-selected'] ?? this.props.accessibilityState?.selected,
};
_accessibilityState =
this.props.disabled != null
? {
..._accessibilityState,
disabled: this.props.disabled,
}
: _accessibilityState;
const accessibilityValue = {
max: this.props['aria-valuemax'] ?? this.props.accessibilityValue?.max,
min: this.props['aria-valuemin'] ?? this.props.accessibilityValue?.min,
now: this.props['aria-valuenow'] ?? this.props.accessibilityValue?.now,
text: this.props['aria-valuetext'] ?? this.props.accessibilityValue?.text,
};
const accessibilityLiveRegion =
this.props['aria-live'] === 'off'
? 'none'
: (this.props['aria-live'] ?? this.props.accessibilityLiveRegion);
const accessibilityLabel =
this.props['aria-label'] ?? this.props.accessibilityLabel;
return (
<Animated.View
accessible={this.props.accessible !== false}
accessibilityLabel={accessibilityLabel}
accessibilityHint={this.props.accessibilityHint}
accessibilityLanguage={this.props.accessibilityLanguage}
accessibilityRole={this.props.accessibilityRole}
accessibilityState={_accessibilityState}
accessibilityActions={this.props.accessibilityActions}
onAccessibilityAction={this.props.onAccessibilityAction}
accessibilityValue={accessibilityValue}
importantForAccessibility={
this.props['aria-hidden'] === true
? 'no-hide-descendants'
: // $FlowFixMe[incompatible-type] - AnimatedProps types were made more strict and need refining at this call site
this.props.importantForAccessibility
}
accessibilityViewIsModal={
this.props['aria-modal'] ?? this.props.accessibilityViewIsModal
}
accessibilityLiveRegion={accessibilityLiveRegion}
accessibilityElementsHidden={
this.props['aria-hidden'] ?? this.props.accessibilityElementsHidden
}
style={[this.props.style, {opacity: this.state.anim}]}
nativeID={this.props.id ?? this.props.nativeID}
testID={this.props.testID}
onLayout={this.props.onLayout}
nextFocusDown={this.props.nextFocusDown}
nextFocusForward={this.props.nextFocusForward}
nextFocusLeft={this.props.nextFocusLeft}
nextFocusRight={this.props.nextFocusRight}
nextFocusUp={this.props.nextFocusUp}
hasTVPreferredFocus={this.props.hasTVPreferredFocus}
hitSlop={this.props.hitSlop}
focusable={
this.props.focusable !== false &&
this.props.onPress !== undefined &&
!this.props.disabled
}
// $FlowFixMe[prop-missing]
ref={this.props.hostRef}
{...eventHandlersWithoutBlurAndFocus}>
{this.props.children}
{__DEV__ ? (
<PressabilityDebugView color="cyan" hitSlop={this.props.hitSlop} />
) : null}
</Animated.View>
);
}
componentDidUpdate(
prevProps: TouchableOpacityProps,
prevState: TouchableOpacityState,
) {
this.state.pressability.configure(this._createPressabilityConfig());
if (
this.props.disabled !== prevProps.disabled ||
// $FlowFixMe[underconstrained-implicit-instantiation]
// $FlowFixMe[prop-missing]
flattenStyle(prevProps.style)?.opacity !==
// $FlowFixMe[underconstrained-implicit-instantiation]
// $FlowFixMe[prop-missing]
flattenStyle(this.props.style)?.opacity
) {
this._opacityInactive(250);
}
}
componentDidMount(): void {
this.state.pressability.configure(this._createPressabilityConfig());
}
componentWillUnmount(): void {
this.state.pressability.reset();
this.state.anim.resetAnimation();
}
}
const Touchable: component(
ref?: React.RefSetter<React.ElementRef<typeof Animated.View>>,
...props: TouchableOpacityProps
) = ({
ref,
...props
}: {
ref?: React.RefSetter<React.ElementRef<typeof Animated.View>>,
...TouchableOpacityProps,
}) => <TouchableOpacity {...props} hostRef={ref} />;
Touchable.displayName = 'TouchableOpacity';
export default Touchable;

View File

@@ -0,0 +1,151 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import type * as React from 'react';
import {Constructor} from '../../../types/private/Utilities';
import {TimerMixin} from '../../../types/private/TimerMixin';
import {Insets} from '../../../types/public/Insets';
import {StyleProp} from '../../StyleSheet/StyleSheet';
import {ViewStyle} from '../../StyleSheet/StyleSheetTypes';
import {
GestureResponderEvent,
LayoutChangeEvent,
NativeSyntheticEvent,
TargetedEvent,
} from '../../Types/CoreEventTypes';
import {AccessibilityProps} from '../View/ViewAccessibility';
import {TouchableMixin} from './Touchable';
export interface TouchableWithoutFeedbackPropsIOS {}
export interface TouchableWithoutFeedbackPropsAndroid {
/**
* If true, doesn't play a system sound on touch.
*
* @platform android
*/
touchSoundDisabled?: boolean | undefined;
}
/**
* @see https://reactnative.dev/docs/touchablewithoutfeedback#props
*/
export interface TouchableWithoutFeedbackProps
extends TouchableWithoutFeedbackPropsIOS,
TouchableWithoutFeedbackPropsAndroid,
AccessibilityProps {
children?: React.ReactNode | undefined;
rejectResponderTermination?: boolean | undefined;
/**
* Delay in ms, from onPressIn, before onLongPress is called.
*/
delayLongPress?: number | undefined;
/**
* Delay in ms, from the start of the touch, before onPressIn is called.
*/
delayPressIn?: number | undefined;
/**
* Delay in ms, from the release of the touch, before onPressOut is called.
*/
delayPressOut?: number | undefined;
/**
* If true, disable all interactions for this component.
*/
disabled?: boolean | undefined;
/**
* Whether this View should be focusable with a non-touch input device,
* eg. receive focus with a hardware keyboard / TV remote.
*/
focusable?: boolean | undefined;
/**
* This defines how far your touch can start away from the button.
* This is added to pressRetentionOffset when moving off of the button.
* NOTE The touch area never extends past the parent view bounds and
* the Z-index of sibling views always takes precedence if a touch hits
* two overlapping views.
*/
hitSlop?: null | Insets | number | undefined;
/**
* Used to reference react managed views from native code.
*/
id?: string | undefined;
/**
* When `accessible` is true (which is the default) this may be called when
* the OS-specific concept of "blur" occurs, meaning the element lost focus.
* Some platforms may not have the concept of blur.
*/
onBlur?: ((e: NativeSyntheticEvent<TargetedEvent>) => void) | undefined;
/**
* When `accessible` is true (which is the default) this may be called when
* the OS-specific concept of "focus" occurs. Some platforms may not have
* the concept of focus.
*/
onFocus?: ((e: NativeSyntheticEvent<TargetedEvent>) => void) | undefined;
/**
* Invoked on mount and layout changes with
* {nativeEvent: {layout: {x, y, width, height}}}
*/
onLayout?: ((event: LayoutChangeEvent) => void) | undefined;
onLongPress?: ((event: GestureResponderEvent) => void) | undefined;
/**
* Called when the touch is released,
* but not if cancelled (e.g. by a scroll that steals the responder lock).
*/
onPress?: ((event: GestureResponderEvent) => void) | undefined;
onPressIn?: ((event: GestureResponderEvent) => void) | undefined;
onPressOut?: ((event: GestureResponderEvent) => void) | undefined;
/**
* //FIXME: not in doc but available in examples
*/
style?: StyleProp<ViewStyle> | undefined;
/**
* When the scroll view is disabled, this defines how far your
* touch may move off of the button, before deactivating the button.
* Once deactivated, try moving it back and you'll see that the button
* is once again reactivated! Move it back and forth several times
* while the scroll view is disabled. Ensure you pass in a constant
* to reduce memory allocations.
*/
pressRetentionOffset?: null | Insets | number | undefined;
/**
* Used to locate this view in end-to-end tests.
*/
testID?: string | undefined;
}
/**
* Do not use unless you have a very good reason.
* All the elements that respond to press should have a visual feedback when touched.
* This is one of the primary reason a "web" app doesn't feel "native".
*
* @see https://reactnative.dev/docs/touchablewithoutfeedback
*/
declare class TouchableWithoutFeedbackComponent extends React.Component<TouchableWithoutFeedbackProps> {}
declare const TouchableWithoutFeedbackBase: Constructor<TimerMixin> &
Constructor<TouchableMixin> &
typeof TouchableWithoutFeedbackComponent;
export class TouchableWithoutFeedback extends TouchableWithoutFeedbackBase {}

View File

@@ -0,0 +1,287 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {AccessibilityActionEvent} from '../../Components/View/ViewAccessibility';
import type {EdgeInsetsOrSizeProp} from '../../StyleSheet/EdgeInsetsPropType';
import type {
BlurEvent,
FocusEvent,
GestureResponderEvent,
LayoutChangeEvent,
} from '../../Types/CoreEventTypes';
import View from '../../Components/View/View';
import {type AccessibilityProps} from '../../Components/View/ViewAccessibility';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import usePressability from '../../Pressability/usePressability';
import {type ViewStyleProp} from '../../StyleSheet/StyleSheet';
import * as React from 'react';
import {cloneElement, useMemo} from 'react';
export type TouchableWithoutFeedbackPropsIOS = {};
export type TouchableWithoutFeedbackPropsAndroid = {
/**
* If true, doesn't play a system sound on touch.
*
* @platform android
*/
touchSoundDisabled?: ?boolean,
};
export type TouchableWithoutFeedbackProps = $ReadOnly<
{
children?: ?React.Node,
/**
* Delay in ms, from onPressIn, before onLongPress is called.
*/
delayLongPress?: ?number,
/**
* Delay in ms, from the start of the touch, before onPressIn is called.
*/
delayPressIn?: ?number,
/**
* Delay in ms, from the release of the touch, before onPressOut is called.
*/
delayPressOut?: ?number,
/**
* If true, disable all interactions for this component.
*/
disabled?: ?boolean,
/**
* Whether this View should be focusable with a non-touch input device,
* eg. receive focus with a hardware keyboard / TV remote.
*/
focusable?: ?boolean,
/**
* This defines how far your touch can start away from the button.
* This is added to pressRetentionOffset when moving off of the button.
* NOTE The touch area never extends past the parent view bounds and
* the Z-index of sibling views always takes precedence if a touch hits
* two overlapping views.
*/
hitSlop?: ?EdgeInsetsOrSizeProp,
/**
* Used to reference react managed views from native code.
*/
id?: string,
importantForAccessibility?: ?(
| 'auto'
| 'yes'
| 'no'
| 'no-hide-descendants'
),
nativeID?: ?string,
onAccessibilityAction?: ?(event: AccessibilityActionEvent) => mixed,
/**
* When `accessible` is true (which is the default) this may be called when
* the OS-specific concept of "blur" occurs, meaning the element lost focus.
* Some platforms may not have the concept of blur.
*/
onBlur?: ?(event: BlurEvent) => mixed,
/**
* When `accessible` is true (which is the default) this may be called when
* the OS-specific concept of "focus" occurs. Some platforms may not have
* the concept of focus.
*/
onFocus?: ?(event: FocusEvent) => mixed,
/**
* Invoked on mount and layout changes with
* {nativeEvent: {layout: {x, y, width, height}}}
*/
onLayout?: ?(event: LayoutChangeEvent) => mixed,
onLongPress?: ?(event: GestureResponderEvent) => mixed,
/**
* Called when the touch is released,
* but not if cancelled (e.g. by a scroll that steals the responder lock).
*/
onPress?: ?(event: GestureResponderEvent) => mixed,
onPressIn?: ?(event: GestureResponderEvent) => mixed,
onPressOut?: ?(event: GestureResponderEvent) => mixed,
/**
* When the scroll view is disabled, this defines how far your
* touch may move off of the button, before deactivating the button.
* Once deactivated, try moving it back and you'll see that the button
* is once again reactivated! Move it back and forth several times
* while the scroll view is disabled. Ensure you pass in a constant
* to reduce memory allocations.
*/
pressRetentionOffset?: ?EdgeInsetsOrSizeProp,
rejectResponderTermination?: ?boolean,
/**
* Used to locate this view in end-to-end tests.
*/
testID?: ?string,
/**
* //FIXME: not in doc but available in examples
*/
style?: ?ViewStyleProp,
} & TouchableWithoutFeedbackPropsAndroid &
TouchableWithoutFeedbackPropsIOS &
AccessibilityProps,
>;
const PASSTHROUGH_PROPS = [
'accessibilityActions',
'accessibilityElementsHidden',
'accessibilityHint',
'accessibilityLanguage',
'accessibilityIgnoresInvertColors',
'accessibilityLabel',
'accessibilityLiveRegion',
'accessibilityRole',
'accessibilityValue',
'aria-valuemax',
'aria-valuemin',
'aria-valuenow',
'aria-valuetext',
'accessibilityViewIsModal',
'aria-modal',
'hitSlop',
'importantForAccessibility',
'nativeID',
'onAccessibilityAction',
'onBlur',
'onFocus',
'onLayout',
'testID',
] as const;
/**
* Do not use unless you have a very good reason.
* All the elements that respond to press should have a visual feedback when touched.
* This is one of the primary reason a "web" app doesn't feel "native".
*
* @see https://reactnative.dev/docs/touchablewithoutfeedback
*/
export default function TouchableWithoutFeedback(
props: TouchableWithoutFeedbackProps,
): React.Node {
const {
disabled,
rejectResponderTermination,
'aria-disabled': ariaDisabled,
accessibilityState,
hitSlop,
delayLongPress,
delayPressIn,
delayPressOut,
pressRetentionOffset,
touchSoundDisabled,
onBlur: _onBlur,
onFocus: _onFocus,
onLongPress,
onPress,
onPressIn,
onPressOut,
} = props;
const pressabilityConfig = useMemo(
() => ({
cancelable: !rejectResponderTermination,
disabled:
disabled !== null
? disabled
: (ariaDisabled ?? accessibilityState?.disabled),
hitSlop: hitSlop,
delayLongPress: delayLongPress,
delayPressIn: delayPressIn,
delayPressOut: delayPressOut,
minPressDuration: 0,
pressRectOffset: pressRetentionOffset,
android_disableSound: touchSoundDisabled,
onBlur: _onBlur,
onFocus: _onFocus,
onLongPress: onLongPress,
onPress: onPress,
onPressIn: onPressIn,
onPressOut: onPressOut,
}),
[
rejectResponderTermination,
disabled,
ariaDisabled,
accessibilityState?.disabled,
hitSlop,
delayLongPress,
delayPressIn,
delayPressOut,
pressRetentionOffset,
touchSoundDisabled,
_onBlur,
_onFocus,
onLongPress,
onPress,
onPressIn,
onPressOut,
],
);
const eventHandlers = usePressability(pressabilityConfig);
const element = React.Children.only<$FlowFixMe>(props.children);
const children: Array<React.Node> = [element.props.children];
const ariaLive = props['aria-live'];
if (__DEV__) {
if (element.type === View) {
children.push(
<PressabilityDebugView color="red" hitSlop={props.hitSlop} />,
);
}
}
let _accessibilityState = {
busy: props['aria-busy'] ?? props.accessibilityState?.busy,
checked: props['aria-checked'] ?? props.accessibilityState?.checked,
disabled: props['aria-disabled'] ?? props.accessibilityState?.disabled,
expanded: props['aria-expanded'] ?? props.accessibilityState?.expanded,
selected: props['aria-selected'] ?? props.accessibilityState?.selected,
};
// BACKWARD-COMPATIBILITY: Focus and blur events were never supported before
// adopting `Pressability`, so preserve that behavior.
const {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} = eventHandlers;
const elementProps: {[string]: mixed, ...} = {
...eventHandlersWithoutBlurAndFocus,
accessible: props.accessible !== false,
accessibilityState:
props.disabled != null
? {
..._accessibilityState,
disabled: props.disabled,
}
: _accessibilityState,
focusable:
props.focusable !== false &&
props.onPress !== undefined &&
!props.disabled,
accessibilityElementsHidden:
props['aria-hidden'] ?? props.accessibilityElementsHidden,
importantForAccessibility:
props['aria-hidden'] === true
? 'no-hide-descendants'
: props.importantForAccessibility,
accessibilityLiveRegion:
ariaLive === 'off' ? 'none' : (ariaLive ?? props.accessibilityLiveRegion),
nativeID: props.id ?? props.nativeID,
};
for (const prop of PASSTHROUGH_PROPS) {
if (props[prop] !== undefined) {
elementProps[prop] = props[prop];
}
}
// $FlowFixMe[incompatible-type]
return cloneElement(element, elementProps, ...children);
}