+ `); + }); + + it('renders styles', () => { + const style = { + display: 'flex', + flex: 1, + backgroundColor: 'white', + marginInlineStart: 10, + userSelect: 'none', + verticalAlign: 'middle', + }; + + const instance = ReactTestRenderer.create(); + + expect(instance.toJSON()).toMatchInlineSnapshot(` + + `); + }); +}); diff --git a/Libraries/Components/TextInput/__tests__/__snapshots__/InputAccessoryView-test.js.snap b/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/InputAccessoryView-test.js.snap similarity index 100% rename from Libraries/Components/TextInput/__tests__/__snapshots__/InputAccessoryView-test.js.snap rename to packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/InputAccessoryView-test.js.snap diff --git a/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap b/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap similarity index 88% rename from Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap rename to packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap index ea9693e96244..ac93dc2e644c 100644 --- a/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap +++ b/packages/react-native/Libraries/Components/TextInput/__tests__/__snapshots__/TextInput-test.js.snap @@ -4,12 +4,12 @@ exports[`TextInput tests should render as expected: should deep render when mock @@ -32,12 +33,12 @@ exports[`TextInput tests should render as expected: should deep render when not `; -exports[`TextInput tests should render as expected: should shallow render as when mocked 1`] = ``; +exports[`TextInput tests should render as expected: should shallow render as when mocked 1`] = ``; -exports[`TextInput tests should render as expected: should shallow render as when not mocked 1`] = ``; +exports[`TextInput tests should render as expected: should shallow render as when not mocked 1`] = ``; diff --git a/Libraries/Components/ToastAndroid/NativeToastAndroid.js b/packages/react-native/Libraries/Components/ToastAndroid/NativeToastAndroid.js similarity index 94% rename from Libraries/Components/ToastAndroid/NativeToastAndroid.js rename to packages/react-native/Libraries/Components/ToastAndroid/NativeToastAndroid.js index 7325c47d484d..3a13f89bd450 100644 --- a/Libraries/Components/ToastAndroid/NativeToastAndroid.js +++ b/packages/react-native/Libraries/Components/ToastAndroid/NativeToastAndroid.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -9,6 +9,7 @@ */ import type {TurboModule} from '../../TurboModule/RCTExport'; + import * as TurboModuleRegistry from '../../TurboModule/TurboModuleRegistry'; export interface Spec extends TurboModule { diff --git a/Libraries/Components/ToastAndroid/ToastAndroid.android.js b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.android.js similarity index 91% rename from Libraries/Components/ToastAndroid/ToastAndroid.android.js rename to packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.android.js index b15100a1769e..81e03fd8f30f 100644 --- a/Libraries/Components/ToastAndroid/ToastAndroid.android.js +++ b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.android.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -42,11 +42,11 @@ const ToastAndroid = { BOTTOM: (ToastAndroidConstants.BOTTOM: number), CENTER: (ToastAndroidConstants.CENTER: number), - show: function(message: string, duration: number): void { + show: function (message: string, duration: number): void { NativeToastAndroid.show(message, duration); }, - showWithGravity: function( + showWithGravity: function ( message: string, duration: number, gravity: number, @@ -54,7 +54,7 @@ const ToastAndroid = { NativeToastAndroid.showWithGravity(message, duration, gravity); }, - showWithGravityAndOffset: function( + showWithGravityAndOffset: function ( message: string, duration: number, gravity: number, diff --git a/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.d.ts b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.d.ts new file mode 100644 index 000000000000..9e0854380b64 --- /dev/null +++ b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.d.ts @@ -0,0 +1,47 @@ +/** + * 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 + */ + +/** + * This exposes the native ToastAndroid module as a JS module. This has a function 'show' + * which takes the following parameters: + * + * 1. String message: A string with the text to toast + * 2. int duration: The duration of the toast. May be ToastAndroid.SHORT or ToastAndroid.LONG + * + * There is also a function `showWithGravity` to specify the layout gravity. May be + * ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER + */ +export interface ToastAndroidStatic { + /** + * String message: A string with the text to toast + * int duration: The duration of the toast. + * May be ToastAndroid.SHORT or ToastAndroid.LONG + */ + show(message: string, duration: number): void; + /** `gravity` may be ToastAndroid.TOP, ToastAndroid.BOTTOM, ToastAndroid.CENTER */ + showWithGravity(message: string, duration: number, gravity: number): void; + + showWithGravityAndOffset( + message: string, + duration: number, + gravity: number, + xOffset: number, + yOffset: number, + ): void; + // Toast duration constants + SHORT: number; + LONG: number; + // Toast gravity constants + TOP: number; + BOTTOM: number; + CENTER: number; +} + +export const ToastAndroid: ToastAndroidStatic; +export type ToastAndroid = ToastAndroidStatic; diff --git a/Libraries/Components/ToastAndroid/ToastAndroid.ios.js b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.ios.js similarity index 78% rename from Libraries/Components/ToastAndroid/ToastAndroid.ios.js rename to packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.ios.js index 611e50fe87b5..d6e98fc61d97 100644 --- a/Libraries/Components/ToastAndroid/ToastAndroid.ios.js +++ b/packages/react-native/Libraries/Components/ToastAndroid/ToastAndroid.ios.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -11,11 +11,11 @@ 'use strict'; const ToastAndroid = { - show: function(message: string, duration: number): void { + show: function (message: string, duration: number): void { console.warn('ToastAndroid is not supported on this platform.'); }, - showWithGravity: function( + showWithGravity: function ( message: string, duration: number, gravity: number, @@ -23,7 +23,7 @@ const ToastAndroid = { console.warn('ToastAndroid is not supported on this platform.'); }, - showWithGravityAndOffset: function( + showWithGravityAndOffset: function ( message: string, duration: number, gravity: number, diff --git a/Libraries/Components/Touchable/BoundingDimensions.js b/packages/react-native/Libraries/Components/Touchable/BoundingDimensions.js similarity index 84% rename from Libraries/Components/Touchable/BoundingDimensions.js rename to packages/react-native/Libraries/Components/Touchable/BoundingDimensions.js index 114b950733df..87d9279bc686 100644 --- a/Libraries/Components/Touchable/BoundingDimensions.js +++ b/packages/react-native/Libraries/Components/Touchable/BoundingDimensions.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -24,7 +24,7 @@ function BoundingDimensions(width, height) { this.height = height; } -BoundingDimensions.prototype.destructor = function() { +BoundingDimensions.prototype.destructor = function () { this.width = null; this.height = null; }; @@ -33,7 +33,7 @@ BoundingDimensions.prototype.destructor = function() { * @param {HTMLElement} element Element to return `BoundingDimensions` for. * @return {BoundingDimensions} Bounding dimensions of `element`. */ -BoundingDimensions.getPooledFromElement = function(element) { +BoundingDimensions.getPooledFromElement = function (element) { return BoundingDimensions.getPooled( element.offsetWidth, element.offsetHeight, diff --git a/packages/react-native/Libraries/Components/Touchable/PooledClass.js b/packages/react-native/Libraries/Components/Touchable/PooledClass.js new file mode 100644 index 000000000000..67847c1ba0c0 --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/PooledClass.js @@ -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. + * + * @format + * @flow + */ + +'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 ( + CopyConstructor: Class, + pooler: Pooler, +): Class & { + getPooled( + ...args: $ReadOnlyArray + ): /* 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 = (CopyConstructor: any); + 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), +}; + +module.exports = PooledClass; diff --git a/packages/react-native/Libraries/Components/Touchable/Position.js b/packages/react-native/Libraries/Components/Touchable/Position.js new file mode 100644 index 000000000000..adbbd170c0d0 --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/Position.js @@ -0,0 +1,35 @@ +/** + * 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 + */ + +'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. + */ +function Position(left, top) { + this.left = left; + this.top = top; +} + +Position.prototype.destructor = function () { + this.left = null; + this.top = null; +}; + +PooledClass.addPoolingTo(Position, twoArgumentPooler); + +module.exports = Position; diff --git a/packages/react-native/Libraries/Components/Touchable/Touchable.d.ts b/packages/react-native/Libraries/Components/Touchable/Touchable.d.ts new file mode 100644 index 000000000000..3c0065c9e02b --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/Touchable.d.ts @@ -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; +} diff --git a/packages/react-native/Libraries/Components/Touchable/Touchable.flow.js b/packages/react-native/Libraries/Components/Touchable/Touchable.flow.js new file mode 100644 index 000000000000..b93087cbec5d --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/Touchable.flow.js @@ -0,0 +1,284 @@ +/** + * 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 {PressEvent} from '../../Types/CoreEventTypes'; + +import * as React from 'react'; + +/** + * `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 ( + * + * + * 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. + * + * + * ); + * + * - 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 State = + | 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; + +/** + * 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 + */ +interface TouchableMixinType { + /** + * 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`. + */ + touchableHandleFocus: (e: Event) => void; + + /** + * 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`. + */ + touchableHandleBlur: (e: Event) => void; + + componentDidMount: () => void; + + /** + * Clear all timeouts on unmount + */ + componentWillUnmount: () => void; + + /** + * 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: () => { + touchable: { + touchState: ?State, + responderID: ?PressEvent['currentTarget'], + }, + }; + + // ==== Hooks to Gesture Responder system ==== + /** + * Must return true if embedded in a native platform scroll view. + */ + touchableHandleResponderTerminationRequest: () => any; + + /** + * Must return true to start the process of `Touchable`. + */ + touchableHandleStartShouldSetResponder: () => any; + + /** + * Return true to cancel press on long press. + */ + touchableLongPressCancelsPress: () => boolean; + + /** + * Place as callback for a DOM element's `onResponderGrant` event. + * @param {SyntheticEvent} e Synthetic event from event system. + * + */ + touchableHandleResponderGrant: (e: PressEvent) => void; + + /** + * Place as callback for a DOM element's `onResponderRelease` event. + */ + touchableHandleResponderRelease: (e: PressEvent) => void; + + /** + * Place as callback for a DOM element's `onResponderTerminate` event. + */ + touchableHandleResponderTerminate: (e: PressEvent) => void; + + /** + * Place as callback for a DOM element's `onResponderMove` event. + */ + touchableHandleResponderMove: (e: PressEvent) => void; + + withoutDefaultFocusAndBlur: {...}; +} + +export type TouchableType = { + Mixin: TouchableMixinType, + /** + * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). + */ + renderDebugView: ({ + color: ColorValue, + hitSlop: EdgeInsetsProp, + ... + }) => null | React.Node, +}; diff --git a/Libraries/Components/Touchable/Touchable.js b/packages/react-native/Libraries/Components/Touchable/Touchable.js similarity index 87% rename from Libraries/Components/Touchable/Touchable.js rename to packages/react-native/Libraries/Components/Touchable/Touchable.js index 6622645cab6b..50c9b8f6a140 100644 --- a/Libraries/Components/Touchable/Touchable.js +++ b/packages/react-native/Libraries/Components/Touchable/Touchable.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -8,20 +8,31 @@ * @format */ -import * as React from 'react'; -import BoundingDimensions from './BoundingDimensions'; -import Platform from '../../Utilities/Platform'; -import Position from './Position'; -import UIManager from '../../ReactNative/UIManager'; -import SoundManager from '../Sound/SoundManager'; - -import {PressabilityDebugView} from '../../Pressability/PressabilityDebug'; - -import type {ColorValue} from '../../StyleSheet/StyleSheet'; import type {EdgeInsetsProp} from '../../StyleSheet/EdgeInsetsPropType'; +import type {ColorValue} from '../../StyleSheet/StyleSheet'; import type {PressEvent} from '../../Types/CoreEventTypes'; +import type {TouchableType} from './Touchable.flow'; + +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 => { +const extractSingleTouch = (nativeEvent: { + +changedTouches: $ReadOnlyArray, + +force?: number, + +identifier: number, + +locationX: number, + +locationY: number, + +pageX: number, + +pageY: number, + +target: ?number, + +timestamp: number, + +touches: $ReadOnlyArray, +}) => { const touches = nativeEvent.touches; const changedTouches = nativeEvent.changedTouches; const hasTouches = touches && touches.length > 0; @@ -361,7 +372,7 @@ const LONG_PRESS_ALLOWED_MOVEMENT = 10; * @lends Touchable.prototype */ const TouchableMixin = { - componentDidMount: function() { + componentDidMount: function () { if (!Platform.isTV) { return; } @@ -370,7 +381,9 @@ const TouchableMixin = { /** * Clear all timeouts on unmount */ - componentWillUnmount: function() { + /* $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); @@ -383,9 +396,12 @@ const TouchableMixin = { * @return {object} State object to be placed inside of * `this.state.touchable`. */ - touchableGetInitialState: function(): $TEMPORARY$object<{| - touchable: $TEMPORARY$object<{|responderID: null, touchState: void|}>, - |}> { + touchableGetInitialState: function (): { + touchable: { + touchState: ?State, + responderID: ?PressEvent['currentTarget'], + }, + } { return { touchable: {touchState: undefined, responderID: null}, }; @@ -395,21 +411,25 @@ const TouchableMixin = { /** * Must return true if embedded in a native platform scroll view. */ - touchableHandleResponderTerminationRequest: function(): any { + /* $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`. */ - touchableHandleStartShouldSetResponder: function(): any { + /* $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 { + touchableLongPressCancelsPress: function (): boolean { return true; }, @@ -418,8 +438,9 @@ const TouchableMixin = { * @param {SyntheticEvent} e Synthetic event from event system. * */ - // $FlowFixMe[signature-verification-failure] - touchableHandleResponderGrant: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleResponderGrant: function (e: PressEvent) { 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 @@ -460,8 +481,9 @@ const TouchableMixin = { /** * Place as callback for a DOM element's `onResponderRelease` event. */ - // $FlowFixMe[signature-verification-failure] - touchableHandleResponderRelease: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleResponderRelease: function (e: PressEvent) { this.pressInLocation = null; this._receiveSignal(Signals.RESPONDER_RELEASE, e); }, @@ -469,8 +491,9 @@ const TouchableMixin = { /** * Place as callback for a DOM element's `onResponderTerminate` event. */ - // $FlowFixMe[signature-verification-failure] - touchableHandleResponderTerminate: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleResponderTerminate: function (e: PressEvent) { this.pressInLocation = null; this._receiveSignal(Signals.RESPONDER_TERMINATED, e); }, @@ -478,8 +501,9 @@ const TouchableMixin = { /** * Place as callback for a DOM element's `onResponderMove` event. */ - // $FlowFixMe[signature-verification-failure] - touchableHandleResponderMove: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleResponderMove: function (e: PressEvent) { // Measurement may not have returned yet. if (!this.state.touchable.positionOnActivate) { return; @@ -564,8 +588,9 @@ const TouchableMixin = { * element that was blurred just prior to this. This can be overridden when * using `Touchable.Mixin.withoutDefaultFocusAndBlur`. */ - // $FlowFixMe[signature-verification-failure] - touchableHandleFocus: function(e: Event) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleFocus: function (e: Event) { this.props.onFocus && this.props.onFocus(e); }, @@ -577,8 +602,9 @@ const TouchableMixin = { * This can be overridden when using * `Touchable.Mixin.withoutDefaultFocusAndBlur`. */ - // $FlowFixMe[signature-verification-failure] - touchableHandleBlur: function(e: Event) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + touchableHandleBlur: function (e: Event) { this.props.onBlur && this.props.onBlur(e); }, @@ -658,7 +684,9 @@ const TouchableMixin = { * @sideeffects * @private */ - _remeasureMetricsOnActivation: function() { + /* $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; @@ -671,8 +699,9 @@ const TouchableMixin = { } }, - // $FlowFixMe[signature-verification-failure] - _handleQueryLayout: function( + /* $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, @@ -698,14 +727,16 @@ const TouchableMixin = { ); }, - // $FlowFixMe[signature-verification-failure] - _handleDelay: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _handleDelay: function (e: PressEvent) { this.touchableDelayTimeout = null; this._receiveSignal(Signals.DELAY, e); }, - // $FlowFixMe[signature-verification-failure] - _handleLongDelay: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _handleLongDelay: function (e: PressEvent) { this.longPressDelayTimeout = null; const curState = this.state.touchable.touchState; if ( @@ -724,8 +755,9 @@ const TouchableMixin = { * @throws Error if invalid state transition or unrecognized signal. * @sideeffects */ - // $FlowFixMe[signature-verification-failure] - _receiveSignal: function(signal: Signal, e: PressEvent) { + /* $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: PressEvent) { const responderID = this.state.touchable.responderID; const curState = this.state.touchable.touchState; const nextState = Transitions[curState] && Transitions[curState][signal]; @@ -764,20 +796,23 @@ const TouchableMixin = { } }, - _cancelLongPressDelayTimeout: function() { + /* $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: State): boolean { + _isHighlight: function (state: State): boolean { return ( state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN ); }, - // $FlowFixMe[signature-verification-failure] - _savePressInLocation: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _savePressInLocation: function (e: PressEvent) { const touch = extractSingleTouch(e.nativeEvent); const pageX = touch && touch.pageX; const pageY = touch && touch.pageY; @@ -786,7 +821,7 @@ const TouchableMixin = { this.pressInLocation = {pageX, pageY, locationX, locationY}; }, - _getDistanceBetweenPoints: function( + _getDistanceBetweenPoints: function ( aX: number, aY: number, bX: number, @@ -808,8 +843,9 @@ const TouchableMixin = { * @param {Event} e Native event. * @sideeffects */ - // $FlowFixMe[signature-verification-failure] - _performSideEffectsForTransition: function( + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _performSideEffectsForTransition: function ( curState: State, nextState: State, signal: Signal, @@ -870,14 +906,16 @@ const TouchableMixin = { this.touchableDelayTimeout = null; }, - // $FlowFixMe[signature-verification-failure] - _startHighlight: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _startHighlight: function (e: PressEvent) { this._savePressInLocation(e); this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); }, - // $FlowFixMe[signature-verification-failure] - _endHighlight: function(e: PressEvent) { + /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by + * Flow's LTI update could not be added via codemod */ + _endHighlight: function (e: PressEvent) { if (this.touchableHandleActivePressOut) { if ( this.touchableGetPressOutDelayMS && @@ -892,7 +930,7 @@ const TouchableMixin = { } }, - withoutDefaultFocusAndBlur: ({}: $TEMPORARY$object<{||}>), + withoutDefaultFocusAndBlur: ({}: {...}), }; /** @@ -906,9 +944,10 @@ const { touchableHandleBlur, ...TouchableMixinWithoutDefaultFocusAndBlur } = TouchableMixin; -TouchableMixin.withoutDefaultFocusAndBlur = TouchableMixinWithoutDefaultFocusAndBlur; +TouchableMixin.withoutDefaultFocusAndBlur = + TouchableMixinWithoutDefaultFocusAndBlur; -const Touchable = { +const Touchable: TouchableType = { Mixin: TouchableMixin, /** * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableBounce.js b/packages/react-native/Libraries/Components/Touchable/TouchableBounce.js new file mode 100644 index 000000000000..5a8d97e85c0f --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableBounce.js @@ -0,0 +1,213 @@ +/** + * 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 Props = $ReadOnly<{| + ...React.ElementConfig, + + onPressAnimationComplete?: ?() => void, + onPressWithCompletion?: ?(callback: () => void) => void, + releaseBounciness?: ?number, + releaseVelocity?: ?number, + style?: ?ViewStyleProp, + + hostRef: React.Ref, +|}>; + +type State = $ReadOnly<{| + pressability: Pressability, + scale: Animated.Value, +|}>; + +class TouchableBounce extends React.Component { + state: State = { + pressability: new Pressability(this._createPressabilityConfig()), + scale: new Animated.Value(1), + }; + + _createPressabilityConfig(): PressabilityConfig { + return { + cancelable: !this.props.rejectResponderTermination, + disabled: this.props.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._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); + } + }, + }; + } + + _bounceTo( + toValue: number, + velocity: number, + bounciness: number, + callback?: ?() => void, + ) { + Animated.spring(this.state.scale, { + toValue, + velocity, + bounciness, + useNativeDriver: true, + }).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 ( + + {this.props.children} + {__DEV__ ? ( + + ) : null} + + ); + } + + componentDidUpdate(prevProps: Props, prevState: State) { + this.state.pressability.configure(this._createPressabilityConfig()); + } + + componentWillUnmount(): void { + this.state.pressability.reset(); + } +} + +module.exports = (React.forwardRef((props, hostRef) => ( + +)): React.AbstractComponent<$ReadOnly<$Diff>>); diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableHighlight.d.ts b/packages/react-native/Libraries/Components/Touchable/TouchableHighlight.d.ts new file mode 100644 index 000000000000..b9faa3a8798f --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableHighlight.d.ts @@ -0,0 +1,68 @@ +/** + * 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 {NativeMethods} from '../../../types/public/ReactNativeTypes'; +import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; +import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; +import {TouchableMixin} from './Touchable'; +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 | 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 + */ +declare class TouchableHighlightComponent extends React.Component {} +declare const TouchableHighlightBase: Constructor & + Constructor & + Constructor & + typeof TouchableHighlightComponent; +export class TouchableHighlight extends TouchableHighlightBase {} diff --git a/Libraries/Components/Touchable/TouchableHighlight.js b/packages/react-native/Libraries/Components/Touchable/TouchableHighlight.js similarity index 86% rename from Libraries/Components/Touchable/TouchableHighlight.js rename to packages/react-native/Libraries/Components/Touchable/TouchableHighlight.js index c0faac9bdda0..c937344451ce 100644 --- a/Libraries/Components/Touchable/TouchableHighlight.js +++ b/packages/react-native/Libraries/Components/Touchable/TouchableHighlight.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -8,15 +8,16 @@ * @format */ +import type {ColorValue} from '../../StyleSheet/StyleSheet'; +import typeof TouchableWithoutFeedback 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 type {ColorValue} from '../../StyleSheet/StyleSheet'; -import typeof TouchableWithoutFeedback from './TouchableWithoutFeedback'; import Platform from '../../Utilities/Platform'; -import View from '../../Components/View/View'; import * as React from 'react'; type AndroidProps = $ReadOnly<{| @@ -276,15 +277,12 @@ class TouchableHighlight extends React.Component { } render(): React.Node { - const child = React.Children.only(this.props.children); + 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 {onBlur, onFocus, ...eventHandlersWithoutBlurAndFocus} = + this.state.pressability.getEventHandlers(); const accessibilityState = this.props.disabled != null @@ -294,20 +292,43 @@ class TouchableHighlight extends React.Component { } : 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 ( {} +declare const TouchableNativeFeedbackBase: Constructor & + 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; +} diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js b/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js new file mode 100644 index 000000000000..2571ddd0b7ab --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js @@ -0,0 +1,361 @@ +/** + * 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 {PressEvent} from '../../Types/CoreEventTypes'; +import typeof TouchableWithoutFeedback 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'; + +type Props = $ReadOnly<{| + ...React.ElementConfig, + + /** + * 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 static + * methods to generate that dictionary. + */ + background?: ?( + | $ReadOnly<{| + type: 'ThemeAttrAndroid', + attribute: + | 'selectableItemBackground' + | 'selectableItemBackgroundBorderless', + rippleRadius: ?number, + |}> + | $ReadOnly<{| + type: 'RippleAndroid', + color: ?number, + borderless: boolean, + rippleRadius: ?number, + |}> + ), + + /** + * TV preferred focus (see documentation for the View component). + */ + hasTVPreferredFocus?: ?boolean, + + /** + * TV next focus down (see documentation for the View component). + */ + nextFocusDown?: ?number, + + /** + * TV next focus forward (see documentation for the View component). + */ + nextFocusForward?: ?number, + + /** + * TV next focus left (see documentation for the View component). + */ + nextFocusLeft?: ?number, + + /** + * TV next focus right (see documentation for the View component). + */ + nextFocusRight?: ?number, + + /** + * TV next focus up (see documentation for the View component). + */ + nextFocusUp?: ?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 State = $ReadOnly<{| + pressability: Pressability, +|}>; + +class TouchableNativeFeedback extends React.Component { + /** + * Creates a value for the `background` prop that uses the Android theme's + * default background for selectable elements. + */ + static SelectableBackground: (rippleRadius: ?number) => $ReadOnly<{| + attribute: 'selectableItemBackground', + type: 'ThemeAttrAndroid', + rippleRadius: ?number, + |}> = (rippleRadius: ?number) => ({ + type: 'ThemeAttrAndroid', + attribute: 'selectableItemBackground', + rippleRadius, + }); + + /** + * Creates a value for the `background` prop that uses the Android theme's + * default background for borderless selectable elements. Requires API 21+. + */ + static SelectableBackgroundBorderless: (rippleRadius: ?number) => $ReadOnly<{| + attribute: 'selectableItemBackgroundBorderless', + type: 'ThemeAttrAndroid', + rippleRadius: ?number, + |}> = (rippleRadius: ?number) => ({ + type: 'ThemeAttrAndroid', + attribute: 'selectableItemBackgroundBorderless', + rippleRadius, + }); + + /** + * Creates a value for the `background` prop that uses the Android ripple with + * the supplied color. If `borderless` is true, the ripple will render outside + * of the view bounds. Requires API 21+. + */ + 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', + color: processedColor, + borderless, + rippleRadius, + }; + }; + + /** + * Whether `useForeground` is supported. + */ + static canUseNativeForeground: () => boolean = () => + Platform.OS === 'android' && Platform.Version >= 23; + + state: State = { + 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(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: PressEvent): void { + if (Platform.OS === 'android') { + const {locationX, locationY} = event.nativeEvent; + const hostComponentRef = findHostInstance_DEPRECATED(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 = [element.props.children]; + if (__DEV__) { + if (element.type === View) { + children.push( + , + ); + } + } + + // 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 React.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.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: Props, prevState: State) { + 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'; + +module.exports = TouchableNativeFeedback; diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.d.ts b/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.d.ts new file mode 100644 index 000000000000..37c4ce6df43e --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.d.ts @@ -0,0 +1,109 @@ +/** + * 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 {NativeMethods} from '../../../types/public/ReactNativeTypes'; +import {TVParallaxProperties} from '../View/ViewPropTypes'; +import {TouchableMixin} from './Touchable'; +import {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback'; + +export interface TVProps { + /** + * *(Apple TV only)* TV preferred focus (see documentation for the View component). + * + * @platform ios + */ + 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; + + /** + * *(Apple TV only)* Object with properties to control Apple TV parallax effects. + * + * enabled: If true, parallax effects are enabled. Defaults to true. + * shiftDistanceX: Defaults to 2.0. + * shiftDistanceY: Defaults to 2.0. + * tiltAngle: Defaults to 0.05. + * magnification: Defaults to 1.0. + * pressMagnification: Defaults to 1.0. + * pressDuration: Defaults to 0.3. + * pressDelay: Defaults to 0.0. + * + * @platform android + */ + tvParallaxProperties?: TVParallaxProperties | 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 + */ +declare class TouchableOpacityComponent extends React.Component {} +declare const TouchableOpacityBase: Constructor & + Constructor & + Constructor & + typeof TouchableOpacityComponent; +export class TouchableOpacity extends TouchableOpacityBase { + /** + * Animate the touchable to a new opacity. + */ + setOpacityTo: (value: number) => void; +} diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.js b/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.js new file mode 100644 index 000000000000..02dc8abd365b --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableOpacity.js @@ -0,0 +1,325 @@ +/** + * 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 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'; + +type TVProps = $ReadOnly<{| + hasTVPreferredFocus?: ?boolean, + nextFocusDown?: ?number, + nextFocusForward?: ?number, + nextFocusLeft?: ?number, + nextFocusRight?: ?number, + nextFocusUp?: ?number, +|}>; + +type Props = $ReadOnly<{| + ...React.ElementConfig, + ...TVProps, + + activeOpacity?: ?number, + style?: ?ViewStyleProp, + + hostRef?: ?React.Ref, +|}>; + +type State = $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 ( + * + * + * + * ); + * }, + * ``` + * ### 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 ( + * + * + * Touch Here + * + * + * + * { this.state.count !== 0 ? this.state.count: null} + * + * + * + * ) + * } + * } + * + * 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 { + state: State = { + 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] + 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 ( + + {this.props.children} + {__DEV__ ? ( + + ) : null} + + ); + } + + componentDidUpdate(prevProps: Props, prevState: State) { + this.state.pressability.configure(this._createPressabilityConfig()); + if ( + this.props.disabled !== prevProps.disabled || + // $FlowFixMe[underconstrained-implicit-instantiation] + flattenStyle(prevProps.style)?.opacity !== + // $FlowFixMe[underconstrained-implicit-instantiation] + flattenStyle(this.props.style)?.opacity + ) { + this._opacityInactive(250); + } + } + + componentWillUnmount(): void { + this.state.pressability.reset(); + } +} + +const Touchable = (React.forwardRef((props, ref) => ( + +)): React.AbstractComponent>); + +Touchable.displayName = 'TouchableOpacity'; + +module.exports = Touchable; diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts b/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts new file mode 100644 index 000000000000..e0146fc31b35 --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts @@ -0,0 +1,143 @@ +/** + * 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; + + /** + * 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; + + /** + * 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) => 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) => 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 | 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 {} +declare const TouchableWithoutFeedbackBase: Constructor & + Constructor & + typeof TouchableWithoutFeedbackComponent; +export class TouchableWithoutFeedback extends TouchableWithoutFeedbackBase {} diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.js b/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.js new file mode 100755 index 000000000000..7c029ed9a0fc --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/TouchableWithoutFeedback.js @@ -0,0 +1,224 @@ +/** + * 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, + AccessibilityActionInfo, + AccessibilityRole, + AccessibilityState, + AccessibilityValue, +} from '../../Components/View/ViewAccessibility'; +import type {EdgeInsetsOrSizeProp} from '../../StyleSheet/EdgeInsetsPropType'; +import type { + BlurEvent, + FocusEvent, + LayoutEvent, + PressEvent, +} from '../../Types/CoreEventTypes'; + +import View from '../../Components/View/View'; +import Pressability, { + type PressabilityConfig, +} from '../../Pressability/Pressability'; +import {PressabilityDebugView} from '../../Pressability/PressabilityDebug'; +import * as React from 'react'; + +type Props = $ReadOnly<{| + accessibilityActions?: ?$ReadOnlyArray, + accessibilityElementsHidden?: ?boolean, + accessibilityHint?: ?Stringish, + accessibilityLanguage?: ?Stringish, + accessibilityIgnoresInvertColors?: ?boolean, + accessibilityLabel?: ?Stringish, + accessibilityLiveRegion?: ?('none' | 'polite' | 'assertive'), + accessibilityRole?: ?AccessibilityRole, + accessibilityState?: ?AccessibilityState, + accessibilityValue?: ?AccessibilityValue, + 'aria-valuemax'?: AccessibilityValue['max'], + 'aria-valuemin'?: AccessibilityValue['min'], + 'aria-valuenow'?: AccessibilityValue['now'], + 'aria-valuetext'?: AccessibilityValue['text'], + accessibilityViewIsModal?: ?boolean, + 'aria-modal'?: ?boolean, + accessible?: ?boolean, + /** + * alias for accessibilityState + * + * see https://reactnative.dev/docs/accessibility#accessibilitystate + */ + 'aria-busy'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', + 'aria-disabled'?: ?boolean, + 'aria-expanded'?: ?boolean, + 'aria-selected'?: ?boolean, + 'aria-hidden'?: ?boolean, + 'aria-live'?: ?('polite' | 'assertive' | 'off'), + 'aria-label'?: ?Stringish, + children?: ?React.Node, + delayLongPress?: ?number, + delayPressIn?: ?number, + delayPressOut?: ?number, + disabled?: ?boolean, + focusable?: ?boolean, + hitSlop?: ?EdgeInsetsOrSizeProp, + id?: string, + importantForAccessibility?: ?('auto' | 'yes' | 'no' | 'no-hide-descendants'), + nativeID?: ?string, + onAccessibilityAction?: ?(event: AccessibilityActionEvent) => mixed, + onBlur?: ?(event: BlurEvent) => mixed, + onFocus?: ?(event: FocusEvent) => mixed, + onLayout?: ?(event: LayoutEvent) => mixed, + onLongPress?: ?(event: PressEvent) => mixed, + onPress?: ?(event: PressEvent) => mixed, + onPressIn?: ?(event: PressEvent) => mixed, + onPressOut?: ?(event: PressEvent) => mixed, + pressRetentionOffset?: ?EdgeInsetsOrSizeProp, + rejectResponderTermination?: ?boolean, + testID?: ?string, + touchSoundDisabled?: ?boolean, +|}>; + +type State = $ReadOnly<{| + pressability: Pressability, +|}>; + +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', +]; + +class TouchableWithoutFeedback extends React.Component { + state: State = { + pressability: new Pressability(createPressabilityConfig(this.props)), + }; + + render(): React.Node { + const element = React.Children.only<$FlowFixMe>(this.props.children); + const children: Array = [element.props.children]; + const ariaLive = this.props['aria-live']; + + if (__DEV__) { + if (element.type === View) { + children.push( + , + ); + } + } + + 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, + }; + + // 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 elementProps: {[string]: mixed, ...} = { + ...eventHandlersWithoutBlurAndFocus, + accessible: this.props.accessible !== false, + accessibilityState: + this.props.disabled != null + ? { + ..._accessibilityState, + disabled: this.props.disabled, + } + : _accessibilityState, + focusable: + this.props.focusable !== false && this.props.onPress !== undefined, + + accessibilityElementsHidden: + this.props['aria-hidden'] ?? this.props.accessibilityElementsHidden, + importantForAccessibility: + this.props['aria-hidden'] === true + ? 'no-hide-descendants' + : this.props.importantForAccessibility, + accessibilityLiveRegion: + ariaLive === 'off' + ? 'none' + : ariaLive ?? this.props.accessibilityLiveRegion, + nativeID: this.props.id ?? this.props.nativeID, + }; + for (const prop of PASSTHROUGH_PROPS) { + if (this.props[prop] !== undefined) { + elementProps[prop] = this.props[prop]; + } + } + + return React.cloneElement(element, elementProps, ...children); + } + + componentDidUpdate(): void { + this.state.pressability.configure(createPressabilityConfig(this.props)); + } + + componentWillUnmount(): void { + this.state.pressability.reset(); + } +} + +function createPressabilityConfig({ + 'aria-disabled': ariaDisabled, + ...props +}: Props): PressabilityConfig { + const accessibilityStateDisabled = + ariaDisabled ?? props.accessibilityState?.disabled; + return { + cancelable: !props.rejectResponderTermination, + disabled: + props.disabled !== null ? props.disabled : accessibilityStateDisabled, + hitSlop: props.hitSlop, + delayLongPress: props.delayLongPress, + delayPressIn: props.delayPressIn, + delayPressOut: props.delayPressOut, + minPressDuration: 0, + pressRectOffset: props.pressRetentionOffset, + android_disableSound: props.touchSoundDisabled, + onBlur: props.onBlur, + onFocus: props.onFocus, + onLongPress: props.onLongPress, + onPress: props.onPress, + onPressIn: props.onPressIn, + onPressOut: props.onPressOut, + }; +} + +TouchableWithoutFeedback.displayName = 'TouchableWithoutFeedback'; + +module.exports = TouchableWithoutFeedback; diff --git a/Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js similarity index 96% rename from Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js rename to packages/react-native/Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js index f25f4150dedf..024feffaa292 100644 --- a/Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableHighlight-test.js @@ -1,19 +1,19 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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 - * @emails oncall+react_native + * @oncall react_native */ 'use strict'; -import * as React from 'react'; import Text from '../../../Text/Text'; import View from '../../View/View'; import TouchableHighlight from '../TouchableHighlight'; +import * as React from 'react'; const render = require('../../../../jest/renderer'); diff --git a/Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js similarity index 97% rename from Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js rename to packages/react-native/Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js index 237b1a22745c..377c4f373764 100644 --- a/Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableNativeFeedback-test.js @@ -1,20 +1,20 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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 - * @emails oncall+react_native + * @oncall react_native */ 'use strict'; -import * as React from 'react'; -import ReactTestRenderer from 'react-test-renderer'; import Text from '../../../Text/Text'; -import TouchableNativeFeedback from '../TouchableNativeFeedback'; import View from '../../View/View'; +import TouchableNativeFeedback from '../TouchableNativeFeedback'; +import * as React from 'react'; +import ReactTestRenderer from 'react-test-renderer'; const render = require('../../../../jest/renderer'); diff --git a/Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js similarity index 94% rename from Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js rename to packages/react-native/Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js index f38211b67aeb..8f4f4f2f6bcd 100644 --- a/Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableOpacity-test.js @@ -1,19 +1,19 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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 - * @emails oncall+react_native + * @oncall react_native */ 'use strict'; -const React = require('react'); -const ReactTestRenderer = require('react-test-renderer'); const Text = require('../../../Text/Text'); const TouchableOpacity = require('../TouchableOpacity'); +const React = require('react'); +const ReactTestRenderer = require('react-test-renderer'); describe('TouchableOpacity', () => { it('renders correctly', () => { diff --git a/Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js similarity index 96% rename from Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js rename to packages/react-native/Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js index 0648d372d388..4e1f12d45755 100644 --- a/Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/TouchableWithoutFeedback-test.js @@ -1,20 +1,20 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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 - * @emails oncall+react_native + * @oncall react_native */ 'use strict'; -import * as React from 'react'; -import ReactTestRenderer from 'react-test-renderer'; import Text from '../../../Text/Text'; import View from '../../View/View'; import TouchableWithoutFeedback from '../TouchableWithoutFeedback'; +import * as React from 'react'; +import ReactTestRenderer from 'react-test-renderer'; describe('TouchableWithoutFeedback', () => { it('renders correctly', () => { diff --git a/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap similarity index 77% rename from Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap rename to packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap index 70eaabe704a1..35c845e97493 100644 --- a/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableHighlight-test.js.snap @@ -2,6 +2,14 @@ exports[`TouchableHighlight renders correctly 1`] = ` should render as expected 1`] = ` + +`; + +exports[` should overwrite accessibilityState with value of disabled prop 1`] = ` + +`; + +exports[` should be disabled when disabled is true and accessibilityState is empty 1`] = ` + +`; + +exports[` should keep accessibilityState when disabled is true 1`] = ` + +`; + +exports[` should overwrite accessibilityState with value of disabled prop 1`] = ` + +`; + +exports[` should be disabled when disabled is true 1`] = ` + +`; + +exports[`TouchableWithoutFeedback renders correctly 1`] = ` + + Touchable + +`; diff --git a/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableOpacity-test.js.snap b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableOpacity-test.js.snap new file mode 100644 index 000000000000..17f2e7f6f764 --- /dev/null +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableOpacity-test.js.snap @@ -0,0 +1,124 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`TouchableOpacity renders correctly 1`] = ` + + + Touchable + + +`; + +exports[`TouchableOpacity renders in disabled state when a disabled prop is passed 1`] = ` + + + Touchable + + +`; + +exports[`TouchableOpacity renders in disabled state when a key disabled in accessibilityState is passed 1`] = ` + + + Touchable + + +`; diff --git a/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap similarity index 80% rename from Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap rename to packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap index 545e77e54e3b..932c5f133c03 100644 --- a/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap +++ b/packages/react-native/Libraries/Components/Touchable/__tests__/__snapshots__/TouchableWithoutFeedback-test.js.snap @@ -2,6 +2,15 @@ exports[`TouchableWithoutFeedback renders correctly 1`] = ` ], + disableTraceUpdates: [], +}; + +interface Agent { + addListener>( + event: Event, + listener: (...AgentEvents[Event]) => void, + ): void; + removeListener(event: $Keys, listener: () => void): void; +} + +type TraceNode = { + publicInstance?: TraceNode, + // TODO: remove this field when syncing the new version of the renderer from React to React Native. + canonical?: TraceNode, + measure?: ( + ( + x: number, + y: number, + width: number, + height: number, + left: number, + top: number, + ) => void, + ) => void, +}; + +type ReactDevToolsGlobalHook = { + on: (eventName: string, (agent: Agent) => void) => void, + off: (eventName: string, (agent: Agent) => void) => void, + reactDevtoolsAgent: Agent, +}; + +const {useEffect, useRef, useState} = React; +const hook: ReactDevToolsGlobalHook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; +const isNativeComponentReady = + Platform.OS === 'android' && + UIManager.hasViewManagerConfig('TraceUpdateOverlay'); +let devToolsAgent: ?Agent; + +export default function TraceUpdateOverlay(): React.Node { + const [overlayDisabled, setOverlayDisabled] = useState(false); + // This effect is designed to be explicitly shown here to avoid re-subscribe from the same + // overlay component. + useEffect(() => { + if (!isNativeComponentReady) { + return; + } + + function attachToDevtools(agent: Agent) { + devToolsAgent = agent; + agent.addListener('drawTraceUpdates', onAgentDrawTraceUpdates); + agent.addListener('disableTraceUpdates', onAgentDisableTraceUpdates); + } + + function subscribe() { + hook?.on('react-devtools', attachToDevtools); + if (hook?.reactDevtoolsAgent) { + attachToDevtools(hook.reactDevtoolsAgent); + } + } + + function unsubscribe() { + hook?.off('react-devtools', attachToDevtools); + const agent = devToolsAgent; + if (agent != null) { + agent.removeListener('drawTraceUpdates', onAgentDrawTraceUpdates); + agent.removeListener('disableTraceUpdates', onAgentDisableTraceUpdates); + devToolsAgent = null; + } + } + + function onAgentDrawTraceUpdates( + nodesToDraw: Array<{node: TraceNode, color: string}> = [], + ) { + // If overlay is disabled before, now it's enabled. + setOverlayDisabled(false); + + const newFramesToDraw: Array> = []; + nodesToDraw.forEach(({node, color}) => { + // `publicInstance` => Fabric + // TODO: remove this check when syncing the new version of the renderer from React to React Native. + // `canonical` => Legacy Fabric + // `node` => Legacy renderer + const component = node.publicInstance ?? node.canonical ?? node; + if (!component || !component.measure) { + return; + } + const frameToDrawPromise = new Promise(resolve => { + // The if statement here is to make flow happy + if (component.measure) { + // TODO(T145522797): We should refactor this to use `getBoundingClientRect` when Paper is no longer supported. + component.measure((x, y, width, height, left, top) => { + resolve({ + rect: {left, top, width, height}, + color: processColor(color), + }); + }); + } + }); + newFramesToDraw.push(frameToDrawPromise); + }); + Promise.all(newFramesToDraw).then( + results => { + if (nativeComponentRef.current != null) { + Commands.draw( + nativeComponentRef.current, + JSON.stringify( + results.filter( + ({rect, color}) => rect.width >= 0 && rect.height >= 0, + ), + ), + ); + } + }, + err => { + console.error(`Failed to measure updated traces. Error: ${err}`); + }, + ); + } + + function onAgentDisableTraceUpdates() { + // When trace updates are disabled from the backend, we won't receive draw events until it's enabled by the next draw. We can safely remove the overlay as it's not needed now. + setOverlayDisabled(true); + } + + subscribe(); + return unsubscribe; + }, []); // Only run once when the overlay initially rendered + + const nativeComponentRef = + useRef>(null); + + return ( + !overlayDisabled && + isNativeComponentReady && ( + + + + ) + ); +} + +const styles = StyleSheet.create({ + overlay: { + position: 'absolute', + top: 0, + bottom: 0, + left: 0, + right: 0, + }, +}); diff --git a/packages/react-native/Libraries/Components/TraceUpdateOverlay/TraceUpdateOverlayNativeComponent.js b/packages/react-native/Libraries/Components/TraceUpdateOverlay/TraceUpdateOverlayNativeComponent.js new file mode 100644 index 000000000000..837223e3774b --- /dev/null +++ b/packages/react-native/Libraries/Components/TraceUpdateOverlay/TraceUpdateOverlayNativeComponent.js @@ -0,0 +1,43 @@ +/** + * 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 {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; +import type {ProcessedColorValue} from '../../StyleSheet/processColor'; +import type {ViewProps} from '../View/ViewPropTypes'; + +import codegenNativeCommands from '../../Utilities/codegenNativeCommands'; +import codegenNativeComponent from '../../Utilities/codegenNativeComponent'; +import * as React from 'react'; + +type NativeProps = $ReadOnly<{| + ...ViewProps, +|}>; +export type TraceUpdateOverlayNativeComponentType = HostComponent; +export type Overlay = { + rect: {left: number, top: number, width: number, height: number}, + color: ?ProcessedColorValue, +}; + +interface NativeCommands { + +draw: ( + viewRef: React.ElementRef, + // TODO(T144046177): Ideally we can pass array of Overlay, but currently + // Array type is not supported in RN codegen for building native commands. + overlays: string, + ) => void; +} + +export const Commands: NativeCommands = codegenNativeCommands({ + supportedCommands: ['draw'], +}); + +export default (codegenNativeComponent( + 'TraceUpdateOverlay', +): HostComponent); diff --git a/Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js b/packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js similarity index 93% rename from Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js rename to packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js index 2a2969905bc6..3c972820c54f 100644 --- a/Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js +++ b/packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedNativeViewNativeComponent.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -8,11 +8,11 @@ * @flow strict-local */ +import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; import type {WithDefault} from '../../Types/CodegenTypes'; import type {ViewProps} from '../View/ViewPropTypes'; import codegenNativeComponent from '../../Utilities/codegenNativeComponent'; -import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; type NativeProps = $ReadOnly<{| ...ViewProps, diff --git a/Libraries/Components/UnimplementedViews/UnimplementedView.js b/packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedView.js similarity index 94% rename from Libraries/Components/UnimplementedViews/UnimplementedView.js rename to packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedView.js index 4bbb41060ff3..3c884ad3f6c4 100644 --- a/Libraries/Components/UnimplementedViews/UnimplementedView.js +++ b/packages/react-native/Libraries/Components/UnimplementedViews/UnimplementedView.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -9,8 +9,8 @@ */ 'use strict'; -import * as React from 'react'; import StyleSheet from '../../StyleSheet/StyleSheet'; +import * as React from 'react'; /** * Common implementation for a simple stubbed view. Simply applies the view's styles to the inner diff --git a/Libraries/Components/View/ReactNativeStyleAttributes.js b/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js similarity index 76% rename from Libraries/Components/View/ReactNativeStyleAttributes.js rename to packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js index 9f87352219ef..f44cc26a1c88 100644 --- a/Libraries/Components/View/ReactNativeStyleAttributes.js +++ b/packages/react-native/Libraries/Components/View/ReactNativeStyleAttributes.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -9,7 +9,10 @@ */ import type {AnyAttributeType} from '../../Renderer/shims/ReactNativeTypes'; + +import processAspectRatio from '../../StyleSheet/processAspectRatio'; import processColor from '../../StyleSheet/processColor'; +import processFontVariant from '../../StyleSheet/processFontVariant'; import processTransform from '../../StyleSheet/processTransform'; import sizesDiffer from '../../Utilities/differ/sizesDiffer'; @@ -22,13 +25,14 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { alignContent: true, alignItems: true, alignSelf: true, - aspectRatio: true, + aspectRatio: {process: processAspectRatio}, borderBottomWidth: true, borderEndWidth: true, borderLeftWidth: true, borderRightWidth: true, borderStartWidth: true, borderTopWidth: true, + columnGap: true, borderWidth: true, bottom: true, direction: true, @@ -40,13 +44,20 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { flexGrow: true, flexShrink: true, flexWrap: true, + gap: true, height: true, justifyContent: true, left: true, margin: true, + marginBlock: true, + marginBlockEnd: true, + marginBlockStart: true, marginBottom: true, marginEnd: true, marginHorizontal: true, + marginInline: true, + marginInlineEnd: true, + marginInlineStart: true, marginLeft: true, marginRight: true, marginStart: true, @@ -58,9 +69,15 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { minWidth: true, overflow: true, padding: true, + paddingBlock: true, + paddingBlockEnd: true, + paddingBlockStart: true, paddingBottom: true, paddingEnd: true, paddingHorizontal: true, + paddingInline: true, + paddingInlineEnd: true, + paddingInlineStart: true, paddingLeft: true, paddingRight: true, paddingStart: true, @@ -68,6 +85,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { paddingVertical: true, position: true, right: true, + rowGap: true, start: true, top: true, width: true, @@ -85,31 +103,32 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { /** * Transform */ - decomposedMatrix: true, // @deprecated - rotation: true, // @deprecated - scaleX: true, // @deprecated - scaleY: true, // @deprecated transform: {process: processTransform}, - transformMatrix: true, // @deprecated - translateX: true, // @deprecated - translateY: true, // @deprecated /** * View */ backfaceVisibility: true, backgroundColor: colorAttributes, + borderBlockColor: colorAttributes, + borderBlockEndColor: colorAttributes, + borderBlockStartColor: colorAttributes, borderBottomColor: colorAttributes, borderBottomEndRadius: true, borderBottomLeftRadius: true, borderBottomRightRadius: true, borderBottomStartRadius: true, borderColor: colorAttributes, + borderCurve: true, borderEndColor: colorAttributes, + borderEndEndRadius: true, + borderEndStartRadius: true, borderLeftColor: colorAttributes, borderRadius: true, borderRightColor: colorAttributes, borderStartColor: colorAttributes, + borderStartEndRadius: true, + borderStartStartRadius: true, borderStyle: true, borderTopColor: colorAttributes, borderTopEndRadius: true, @@ -117,6 +136,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { borderTopRightRadius: true, borderTopStartRadius: true, opacity: true, + pointerEvents: true, /** * Text @@ -125,7 +145,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { fontFamily: true, fontSize: true, fontStyle: true, - fontVariant: true, + fontVariant: {process: processFontVariant}, fontWeight: true, includeFontPadding: true, letterSpacing: true, @@ -139,6 +159,8 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { textShadowOffset: true, textShadowRadius: true, textTransform: true, + userSelect: true, + verticalAlign: true, writingDirection: true, /** @@ -147,6 +169,7 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = { overlayColor: colorAttributes, resizeMode: true, tintColor: colorAttributes, + objectFit: true, }; module.exports = ReactNativeStyleAttributes; diff --git a/Libraries/Components/View/ReactNativeViewAttributes.js b/packages/react-native/Libraries/Components/View/ReactNativeViewAttributes.js similarity index 94% rename from Libraries/Components/View/ReactNativeViewAttributes.js rename to packages/react-native/Libraries/Components/View/ReactNativeViewAttributes.js index da38aeef7908..f4ea0d2c1f52 100644 --- a/Libraries/Components/View/ReactNativeViewAttributes.js +++ b/packages/react-native/Libraries/Components/View/ReactNativeViewAttributes.js @@ -1,5 +1,5 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * 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. @@ -21,6 +21,7 @@ const UIView = { accessibilityState: true, accessibilityValue: true, accessibilityHint: true, + accessibilityLanguage: true, importantForAccessibility: true, nativeID: true, testID: true, diff --git a/packages/react-native/Libraries/Components/View/View.d.ts b/packages/react-native/Libraries/Components/View/View.d.ts new file mode 100644 index 000000000000..5fbb52928e5a --- /dev/null +++ b/packages/react-native/Libraries/Components/View/View.d.ts @@ -0,0 +1,29 @@ +/** + * 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 {ViewProps} from './ViewPropTypes'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; + +/** + * The most fundamental component for building UI, View is a container that supports layout with flexbox, style, some touch handling, + * and accessibility controls, and is designed to be nested inside other views and to have 0 to many children of any type. + * View maps directly to the native view equivalent on whatever platform React is running on, + * whether that is a UIView,
, android.view, etc. + */ +declare class ViewComponent extends React.Component {} +declare const ViewBase: Constructor & typeof ViewComponent; +export class View extends ViewBase { + /** + * Is 3D Touch / Force Touch available (i.e. will touch events include `force`) + * @platform ios + */ + static forceTouchAvailable: boolean; +} diff --git a/packages/react-native/Libraries/Components/View/View.js b/packages/react-native/Libraries/Components/View/View.js new file mode 100644 index 000000000000..0edf2e6820dd --- /dev/null +++ b/packages/react-native/Libraries/Components/View/View.js @@ -0,0 +1,141 @@ +/** + * 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 + * @flow strict-local + */ + +import type {ViewProps} from './ViewPropTypes'; + +import flattenStyle from '../../StyleSheet/flattenStyle'; +import TextAncestor from '../../Text/TextAncestor'; +import {getAccessibilityRoleFromRole} from '../../Utilities/AcessibilityMapping'; +import ViewNativeComponent from './ViewNativeComponent'; +import * as React from 'react'; + +export type Props = ViewProps; + +/** + * The most fundamental component for building a UI, View is a container that + * supports layout with flexbox, style, some touch handling, and accessibility + * controls. + * + * @see https://reactnative.dev/docs/view + */ +const View: React.AbstractComponent< + ViewProps, + React.ElementRef, +> = React.forwardRef( + ( + { + accessibilityElementsHidden, + accessibilityLabel, + accessibilityLabelledBy, + accessibilityLiveRegion, + accessibilityRole, + accessibilityState, + accessibilityValue, + 'aria-busy': ariaBusy, + 'aria-checked': ariaChecked, + 'aria-disabled': ariaDisabled, + 'aria-expanded': ariaExpanded, + 'aria-hidden': ariaHidden, + 'aria-label': ariaLabel, + 'aria-labelledby': ariaLabelledBy, + 'aria-live': ariaLive, + 'aria-selected': ariaSelected, + 'aria-valuemax': ariaValueMax, + 'aria-valuemin': ariaValueMin, + 'aria-valuenow': ariaValueNow, + 'aria-valuetext': ariaValueText, + focusable, + id, + importantForAccessibility, + nativeID, + pointerEvents, + role, + tabIndex, + ...otherProps + }: ViewProps, + forwardedRef, + ) => { + const _accessibilityLabelledBy = + ariaLabelledBy?.split(/\s*,\s*/g) ?? accessibilityLabelledBy; + + let _accessibilityState; + if ( + accessibilityState != null || + ariaBusy != null || + ariaChecked != null || + ariaDisabled != null || + ariaExpanded != null || + ariaSelected != null + ) { + _accessibilityState = { + busy: ariaBusy ?? accessibilityState?.busy, + checked: ariaChecked ?? accessibilityState?.checked, + disabled: ariaDisabled ?? accessibilityState?.disabled, + expanded: ariaExpanded ?? accessibilityState?.expanded, + selected: ariaSelected ?? accessibilityState?.selected, + }; + } + let _accessibilityValue; + if ( + accessibilityValue != null || + ariaValueMax != null || + ariaValueMin != null || + ariaValueNow != null || + ariaValueText != null + ) { + _accessibilityValue = { + max: ariaValueMax ?? accessibilityValue?.max, + min: ariaValueMin ?? accessibilityValue?.min, + now: ariaValueNow ?? accessibilityValue?.now, + text: ariaValueText ?? accessibilityValue?.text, + }; + } + + // $FlowFixMe[underconstrained-implicit-instantiation] + let style = flattenStyle(otherProps.style); + + const newPointerEvents = style?.pointerEvents || pointerEvents; + + return ( + + + + ); + }, +); + +View.displayName = 'View'; + +module.exports = View; diff --git a/packages/react-native/Libraries/Components/View/ViewAccessibility.d.ts b/packages/react-native/Libraries/Components/View/ViewAccessibility.d.ts new file mode 100644 index 000000000000..acb833ef7fbe --- /dev/null +++ b/packages/react-native/Libraries/Components/View/ViewAccessibility.d.ts @@ -0,0 +1,373 @@ +/** + * 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 {NativeSyntheticEvent} from '../../Types/CoreEventTypes'; + +/** + * @see https://reactnative.dev/docs/accessibility#accessibility-properties + */ +export interface AccessibilityProps + extends AccessibilityPropsAndroid, + AccessibilityPropsIOS { + /** + * When true, indicates that the view is an accessibility element. + * By default, all the touchable elements are accessible. + */ + accessible?: boolean | undefined; + + /** + * Provides an array of custom actions available for accessibility. + */ + accessibilityActions?: ReadonlyArray | undefined; + + /** + * Overrides the text that's read by the screen reader when the user interacts with the element. By default, the + * label is constructed by traversing all the children and accumulating all the Text nodes separated by space. + */ + accessibilityLabel?: string | undefined; + + /** + * Alias for accessibilityLabel https://reactnative.dev/docs/view#accessibilitylabel + * https://github.com/facebook/react-native/issues/34424 + */ + 'aria-label'?: string | undefined; + + /** + * Accessibility Role tells a person using either VoiceOver on iOS or TalkBack on Android the type of element that is focused on. + */ + accessibilityRole?: AccessibilityRole | undefined; + /** + * Accessibility State tells a person using either VoiceOver on iOS or TalkBack on Android the state of the element currently focused on. + */ + accessibilityState?: AccessibilityState | undefined; + + /** + * alias for accessibilityState + * + * see https://reactnative.dev/docs/accessibility#accessibilitystate + */ + 'aria-busy'?: boolean | undefined; + 'aria-checked'?: boolean | 'mixed' | undefined; + 'aria-disabled'?: boolean | undefined; + 'aria-expanded'?: boolean | undefined; + 'aria-selected'?: boolean | undefined; + + /** + * Represents the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud. + * + * @platform android + */ + 'aria-labelledby'?: string | undefined; + + /** + * An accessibility hint helps users understand what will happen when they perform an action on the accessibility element when that result is not obvious from the accessibility label. + */ + accessibilityHint?: string | undefined; + /** + * Represents the current value of a component. It can be a textual description of a component's value, or for range-based components, such as sliders and progress bars, + * it contains range information (minimum, current, and maximum). + */ + accessibilityValue?: AccessibilityValue | undefined; + + 'aria-valuemax'?: AccessibilityValue['max'] | undefined; + 'aria-valuemin'?: AccessibilityValue['min'] | undefined; + 'aria-valuenow'?: AccessibilityValue['now'] | undefined; + 'aria-valuetext'?: AccessibilityValue['text'] | undefined; + /** + * When `accessible` is true, the system will try to invoke this function when the user performs an accessibility custom action. + */ + onAccessibilityAction?: + | ((event: AccessibilityActionEvent) => void) + | undefined; + + /** + * [Android] Controlling if a view fires accessibility events and if it is reported to accessibility services. + */ + importantForAccessibility?: + | ('auto' | 'yes' | 'no' | 'no-hide-descendants') + | undefined; + + /** + * A value indicating whether the accessibility elements contained within + * this accessibility element are hidden. + */ + 'aria-hidden'?: boolean | undefined; + + 'aria-live'?: ('polite' | 'assertive' | 'off') | undefined; + 'aria-modal'?: boolean | undefined; + + /** + * Indicates to accessibility services to treat UI component like a specific role. + */ + role?: Role | undefined; +} + +export type AccessibilityActionInfo = Readonly<{ + name: AccessibilityActionName | string; + label?: string | undefined; +}>; + +export type AccessibilityActionName = + /** + * Generated when a screen reader user double taps the component. + */ + | 'activate' + /** + * Generated when a screen reader user increments an adjustable component. + */ + | 'increment' + /** + * Generated when a screen reader user decrements an adjustable component. + */ + | 'decrement' + /** + * Generated when a TalkBack user places accessibility focus on the component and double taps and holds one finger on the screen. + * @platform android + */ + | 'longpress' + /** + * Generated when a VoiceOver user places focus on or inside the component and double taps with two fingers. + * @platform ios + * */ + | 'magicTap' + /** + * Generated when a VoiceOver user places focus on or inside the component and performs a two finger scrub gesture (left, right, left). + * @platform ios + * */ + | 'escape'; + +export type AccessibilityActionEvent = NativeSyntheticEvent< + Readonly<{ + actionName: string; + }> +>; + +export interface AccessibilityState { + /** + * When true, informs accessible tools if the element is disabled + */ + disabled?: boolean | undefined; + /** + * When true, informs accessible tools if the element is selected + */ + selected?: boolean | undefined; + /** + * For items like Checkboxes and Toggle switches, reports their state to accessible tools + */ + checked?: boolean | 'mixed' | undefined; + /** + * When present, informs accessible tools if the element is busy + */ + busy?: boolean | undefined; + /** + * When present, informs accessible tools the element is expanded or collapsed + */ + expanded?: boolean | undefined; +} + +export interface AccessibilityValue { + /** + * The minimum value of this component's range. (should be an integer) + */ + min?: number | undefined; + + /** + * The maximum value of this component's range. (should be an integer) + */ + max?: number | undefined; + + /** + * The current value of this component's range. (should be an integer) + */ + now?: number | undefined; + + /** + * A textual description of this component's value. (will override minimum, current, and maximum if set) + */ + text?: string | undefined; +} + +export type AccessibilityRole = + | 'none' + | 'button' + | 'togglebutton' + | 'link' + | 'search' + | 'image' + | 'keyboardkey' + | 'text' + | 'adjustable' + | 'imagebutton' + | 'header' + | 'summary' + | 'alert' + | 'checkbox' + | 'combobox' + | 'menu' + | 'menubar' + | 'menuitem' + | 'progressbar' + | 'radio' + | 'radiogroup' + | 'scrollbar' + | 'spinbutton' + | 'switch' + | 'tab' + | 'tabbar' + | 'tablist' + | 'timer' + | 'list' + | 'toolbar'; + +export interface AccessibilityPropsAndroid { + /** + * Indicates to accessibility services whether the user should be notified when this view changes. + * Works for Android API >= 19 only. + * See http://developer.android.com/reference/android/view/View.html#attr_android:accessibilityLiveRegion for references. + * @platform android + */ + accessibilityLiveRegion?: 'none' | 'polite' | 'assertive' | undefined; + + /** + * Controls how view is important for accessibility which is if it fires accessibility events + * and if it is reported to accessibility services that query the screen. + * Works for Android only. See http://developer.android.com/reference/android/R.attr.html#importantForAccessibility for references. + * + * Possible values: + * 'auto' - The system determines whether the view is important for accessibility - default (recommended). + * 'yes' - The view is important for accessibility. + * 'no' - The view is not important for accessibility. + * 'no-hide-descendants' - The view is not important for accessibility, nor are any of its descendant views. + */ + importantForAccessibility?: + | 'auto' + | 'yes' + | 'no' + | 'no-hide-descendants' + | undefined; + + /** + * A reference to another element `nativeID` used to build complex forms. The value of `accessibilityLabelledBy` should match the `nativeID` of the related element. + * @platform android + */ + accessibilityLabelledBy?: string | string[] | undefined; +} + +export interface AccessibilityPropsIOS { + /** + * A Boolean value indicating whether the accessibility elements contained within this accessibility element + * are hidden to the screen reader. + * @platform ios + */ + accessibilityElementsHidden?: boolean | undefined; + + /** + * A Boolean value indicating whether VoiceOver should ignore the elements within views that are siblings of the receiver. + * @platform ios + */ + accessibilityViewIsModal?: boolean | undefined; + + /** + * When accessible is true, the system will invoke this function when the user performs the escape gesture (scrub with two fingers). + * @platform ios + */ + onAccessibilityEscape?: (() => void) | undefined; + + /** + * When `accessible` is true, the system will try to invoke this function when the user performs accessibility tap gesture. + * @platform ios + */ + onAccessibilityTap?: (() => void) | undefined; + + /** + * When accessible is true, the system will invoke this function when the user performs the magic tap gesture. + * @platform ios + */ + onMagicTap?: (() => void) | undefined; + + /** + * https://reactnative.dev/docs/accessibility#accessibilityignoresinvertcolorsios + * @platform ios + */ + accessibilityIgnoresInvertColors?: boolean | undefined; + + /** + * By using the accessibilityLanguage property, the screen reader will understand which language to use while reading the element's label, value and hint. The provided string value must follow the BCP 47 specification (https://www.rfc-editor.org/info/bcp47). + * https://reactnative.dev/docs/accessibility#accessibilitylanguage-ios + * @platform ios + */ + accessibilityLanguage?: string | undefined; +} + +export type Role = + | 'alert' + | 'alertdialog' + | 'application' + | 'article' + | 'banner' + | 'button' + | 'cell' + | 'checkbox' + | 'columnheader' + | 'combobox' + | 'complementary' + | 'contentinfo' + | 'definition' + | 'dialog' + | 'directory' + | 'document' + | 'feed' + | 'figure' + | 'form' + | 'grid' + | 'group' + | 'heading' + | 'img' + | 'link' + | 'list' + | 'listitem' + | 'log' + | 'main' + | 'marquee' + | 'math' + | 'menu' + | 'menubar' + | 'menuitem' + | 'meter' + | 'navigation' + | 'none' + | 'note' + | 'option' + | 'presentation' + | 'progressbar' + | 'radio' + | 'radiogroup' + | 'region' + | 'row' + | 'rowgroup' + | 'rowheader' + | 'scrollbar' + | 'searchbox' + | 'separator' + | 'slider' + | 'spinbutton' + | 'status' + | 'summary' + | 'switch' + | 'tab' + | 'table' + | 'tablist' + | 'tabpanel' + | 'term' + | 'timer' + | 'toolbar' + | 'tooltip' + | 'tree' + | 'treegrid' + | 'treeitem'; diff --git a/packages/react-native/Libraries/Components/View/ViewAccessibility.js b/packages/react-native/Libraries/Components/View/ViewAccessibility.js new file mode 100644 index 000000000000..18da75effcb1 --- /dev/null +++ b/packages/react-native/Libraries/Components/View/ViewAccessibility.js @@ -0,0 +1,167 @@ +/** + * 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 + * @flow strict-local + */ + +'use strict'; + +import type {SyntheticEvent} from '../../Types/CoreEventTypes'; + +// This must be kept in sync with the AccessibilityRolesMask in RCTViewManager.m +export type AccessibilityRole = + | 'none' + | 'button' + | 'dropdownlist' + | 'togglebutton' + | 'link' + | 'search' + | 'image' + | 'keyboardkey' + | 'text' + | 'adjustable' + | 'imagebutton' + | 'header' + | 'summary' + | 'alert' + | 'checkbox' + | 'combobox' + | 'menu' + | 'menubar' + | 'menuitem' + | 'progressbar' + | 'radio' + | 'radiogroup' + | 'scrollbar' + | 'spinbutton' + | 'switch' + | 'tab' + | 'tabbar' + | 'tablist' + | 'timer' + | 'list' + | 'toolbar' + | 'grid' + | 'pager' + | 'scrollview' + | 'horizontalscrollview' + | 'viewgroup' + | 'webview' + | 'drawerlayout' + | 'slidingdrawer' + | 'iconmenu'; + +// Role types for web +export type Role = + | 'alert' + | 'alertdialog' + | 'application' + | 'article' + | 'banner' + | 'button' + | 'cell' + | 'checkbox' + | 'columnheader' + | 'combobox' + | 'complementary' + | 'contentinfo' + | 'definition' + | 'dialog' + | 'directory' + | 'document' + | 'feed' + | 'figure' + | 'form' + | 'grid' + | 'group' + | 'heading' + | 'img' + | 'link' + | 'list' + | 'listitem' + | 'log' + | 'main' + | 'marquee' + | 'math' + | 'menu' + | 'menubar' + | 'menuitem' + | 'meter' + | 'navigation' + | 'none' + | 'note' + | 'option' + | 'presentation' + | 'progressbar' + | 'radio' + | 'radiogroup' + | 'region' + | 'row' + | 'rowgroup' + | 'rowheader' + | 'scrollbar' + | 'searchbox' + | 'separator' + | 'slider' + | 'spinbutton' + | 'status' + | 'summary' + | 'switch' + | 'tab' + | 'table' + | 'tablist' + | 'tabpanel' + | 'term' + | 'timer' + | 'toolbar' + | 'tooltip' + | 'tree' + | 'treegrid' + | 'treeitem'; + +// the info associated with an accessibility action +export type AccessibilityActionInfo = $ReadOnly<{ + name: string, + label?: string, + ... +}>; + +// The info included in the event sent to onAccessibilityAction +export type AccessibilityActionEvent = SyntheticEvent< + $ReadOnly<{actionName: string, ...}>, +>; + +export type AccessibilityState = { + disabled?: boolean, + selected?: boolean, + checked?: ?boolean | 'mixed', + busy?: boolean, + expanded?: boolean, + ... +}; + +export type AccessibilityValue = $ReadOnly<{| + /** + * The minimum value of this component's range. (should be an integer) + */ + min?: number, + + /** + * The maximum value of this component's range. (should be an integer) + */ + max?: number, + + /** + * The current value of this component's range. (should be an integer) + */ + now?: number, + + /** + * A textual description of this component's value. (will override minimum, current, and maximum if set) + */ + text?: Stringish, +|}>; diff --git a/packages/react-native/Libraries/Components/View/ViewNativeComponent.js b/packages/react-native/Libraries/Components/View/ViewNativeComponent.js new file mode 100644 index 000000000000..d8052fb9889b --- /dev/null +++ b/packages/react-native/Libraries/Components/View/ViewNativeComponent.js @@ -0,0 +1,128 @@ +/** + * 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 { + HostComponent, + PartialViewConfig, +} from '../../Renderer/shims/ReactNativeTypes'; + +import * as NativeComponentRegistry from '../../NativeComponent/NativeComponentRegistry'; +import codegenNativeCommands from '../../Utilities/codegenNativeCommands'; +import Platform from '../../Utilities/Platform'; +import {type ViewProps as Props} from './ViewPropTypes'; +import * as React from 'react'; + +export const __INTERNAL_VIEW_CONFIG: PartialViewConfig = + Platform.OS === 'android' + ? { + uiViewClassName: 'RCTView', + validAttributes: { + // ReactClippingViewManager @ReactProps + removeClippedSubviews: true, + + // ReactViewManager @ReactProps + accessible: true, + hasTVPreferredFocus: true, + nextFocusDown: true, + nextFocusForward: true, + nextFocusLeft: true, + nextFocusRight: true, + nextFocusUp: true, + + borderRadius: true, + borderTopLeftRadius: true, + borderTopRightRadius: true, + borderBottomRightRadius: true, + borderBottomLeftRadius: true, + borderTopStartRadius: true, + borderTopEndRadius: true, + borderBottomStartRadius: true, + borderBottomEndRadius: true, + borderEndEndRadius: true, + borderEndStartRadius: true, + borderStartEndRadius: true, + borderStartStartRadius: true, + borderStyle: true, + hitSlop: true, + pointerEvents: true, + nativeBackgroundAndroid: true, + nativeForegroundAndroid: true, + needsOffscreenAlphaCompositing: true, + + borderWidth: true, + borderLeftWidth: true, + borderRightWidth: true, + borderTopWidth: true, + borderBottomWidth: true, + borderStartWidth: true, + borderEndWidth: true, + + borderColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderLeftColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderRightColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderTopColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderBottomColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderStartColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderEndColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderBlockColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderBlockEndColor: { + process: require('../../StyleSheet/processColor').default, + }, + borderBlockStartColor: { + process: require('../../StyleSheet/processColor').default, + }, + + focusable: true, + overflow: true, + backfaceVisibility: true, + }, + } + : { + uiViewClassName: 'RCTView', + }; + +const ViewNativeComponent: HostComponent = + NativeComponentRegistry.get('RCTView', () => __INTERNAL_VIEW_CONFIG); + +interface NativeCommands { + +hotspotUpdate: ( + viewRef: React.ElementRef>, + x: number, + y: number, + ) => void; + +setPressed: ( + viewRef: React.ElementRef>, + pressed: boolean, + ) => void; +} + +export const Commands: NativeCommands = codegenNativeCommands({ + supportedCommands: ['hotspotUpdate', 'setPressed'], +}); + +export default ViewNativeComponent; + +export type ViewNativeComponentType = HostComponent; diff --git a/packages/react-native/Libraries/Components/View/ViewPropTypes.d.ts b/packages/react-native/Libraries/Components/View/ViewPropTypes.d.ts new file mode 100644 index 000000000000..53f5e82c3414 --- /dev/null +++ b/packages/react-native/Libraries/Components/View/ViewPropTypes.d.ts @@ -0,0 +1,245 @@ +/** + * 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 {GestureResponderHandlers} from '../../../types/public/ReactNativeRenderer'; +import {StyleProp} from '../../StyleSheet/StyleSheet'; +import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; +import {LayoutChangeEvent, PointerEvents} from '../../Types/CoreEventTypes'; +import {Touchable} from '../Touchable/Touchable'; +import {AccessibilityProps} from './ViewAccessibility'; + +export type TVParallaxProperties = { + /** + * If true, parallax effects are enabled. Defaults to true. + */ + enabled?: boolean | undefined; + + /** + * Defaults to 2.0. + */ + shiftDistanceX?: number | undefined; + + /** + * Defaults to 2.0. + */ + shiftDistanceY?: number | undefined; + + /** + * Defaults to 0.05. + */ + tiltAngle?: number | undefined; + + /** + * Defaults to 1.0 + */ + magnification?: number | undefined; + + /** + * Defaults to 1.0 + */ + pressMagnification?: number | undefined; + + /** + * Defaults to 0.3 + */ + pressDuration?: number | undefined; + + /** + * Defaults to 0.3 + */ + pressDelay?: number | undefined; +}; + +export interface TVViewPropsIOS { + /** + * *(Apple TV only)* When set to true, this view will be focusable + * and navigable using the Apple TV remote. + * + * @platform ios + */ + isTVSelectable?: boolean | undefined; + + /** + * *(Apple TV only)* May be set to true to force the Apple TV focus engine to move focus to this view. + * + * @platform ios + */ + hasTVPreferredFocus?: boolean | undefined; + + /** + * *(Apple TV only)* Object with properties to control Apple TV parallax effects. + * + * @platform ios + */ + tvParallaxProperties?: TVParallaxProperties | undefined; + + /** + * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. + * + * @platform ios + */ + tvParallaxShiftDistanceX?: number | undefined; + + /** + * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 2.0. + * + * @platform ios + */ + tvParallaxShiftDistanceY?: number | undefined; + + /** + * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 0.05. + * + * @platform ios + */ + tvParallaxTiltAngle?: number | undefined; + + /** + * *(Apple TV only)* May be used to change the appearance of the Apple TV parallax effect when this view goes in or out of focus. Defaults to 1.0. + * + * @platform ios + */ + tvParallaxMagnification?: number | undefined; +} + +export interface ViewPropsIOS extends TVViewPropsIOS { + /** + * Whether this view should be rendered as a bitmap before compositing. + * + * On iOS, this is useful for animations and interactions that do not modify this component's dimensions nor its children; + * for example, when translating the position of a static view, rasterization allows the renderer to reuse a cached bitmap of a static view + * and quickly composite it during each frame. + * + * Rasterization incurs an off-screen drawing pass and the bitmap consumes memory. + * Test and measure when using this property. + */ + shouldRasterizeIOS?: boolean | undefined; +} + +export interface ViewPropsAndroid { + /** + * Views that are only used to layout their children or otherwise don't draw anything + * may be automatically removed from the native hierarchy as an optimization. + * Set this property to false to disable this optimization and ensure that this View exists in the native view hierarchy. + */ + collapsable?: boolean | undefined; + + /** + * Whether this view needs to rendered offscreen and composited with an alpha in order to preserve 100% correct colors and blending behavior. + * The default (false) falls back to drawing the component and its children + * with an alpha applied to the paint used to draw each element instead of rendering the full component offscreen and compositing it back with an alpha value. + * This default may be noticeable and undesired in the case where the View you are setting an opacity on + * has multiple overlapping elements (e.g. multiple overlapping Views, or text and a background). + * + * Rendering offscreen to preserve correct alpha behavior is extremely expensive + * and hard to debug for non-native developers, which is why it is not turned on by default. + * If you do need to enable this property for an animation, + * consider combining it with renderToHardwareTextureAndroid if the view contents are static (i.e. it doesn't need to be redrawn each frame). + * If that property is enabled, this View will be rendered off-screen once, + * saved in a hardware texture, and then composited onto the screen with an alpha each frame without having to switch rendering targets on the GPU. + */ + needsOffscreenAlphaCompositing?: boolean | undefined; + + /** + * Whether this view should render itself (and all of its children) into a single hardware texture on the GPU. + * + * On Android, this is useful for animations and interactions that only modify opacity, rotation, translation, and/or scale: + * in those cases, the view doesn't have to be redrawn and display lists don't need to be re-executed. The texture can just be + * re-used and re-composited with different parameters. The downside is that this can use up limited video memory, so this prop should be set back to false at the end of the interaction/animation. + */ + renderToHardwareTextureAndroid?: boolean | undefined; + + /** + * Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. + */ + focusable?: boolean | undefined; +} + +/** + * @see https://reactnative.dev/docs/view#props + */ +export interface ViewProps + extends ViewPropsAndroid, + ViewPropsIOS, + GestureResponderHandlers, + Touchable, + PointerEvents, + AccessibilityProps { + children?: React.ReactNode | undefined; + /** + * This defines how far a touch event can start away from the view. + * Typical interface guidelines recommend touch targets that are at least + * 30 - 40 points/density-independent pixels. If a Touchable view has + * a height of 20 the touchable height can be extended to 40 with + * hitSlop={{top: 10, bottom: 10, left: 0, right: 0}} + * 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?: Insets | undefined; + + /** + * Used to reference react managed views from native code. + */ + id?: string | undefined; + + /** + * Invoked on mount and layout changes with + * + * {nativeEvent: { layout: {x, y, width, height}}}. + */ + onLayout?: ((event: LayoutChangeEvent) => void) | undefined; + + /** + * + * In the absence of auto property, none is much like CSS's none value. box-none is as if you had applied the CSS class: + * + * .box-none { + * pointer-events: none; + * } + * .box-none * { + * pointer-events: all; + * } + * + * box-only is the equivalent of + * + * .box-only { + * pointer-events: all; + * } + * .box-only * { + * pointer-events: none; + * } + * + * But since pointerEvents does not affect layout/appearance, and we are already deviating from the spec by adding additional modes, + * we opt to not include pointerEvents on style. On some platforms, we would need to implement it as a className anyways. Using style or not is an implementation detail of the platform. + */ + pointerEvents?: 'box-none' | 'none' | 'box-only' | 'auto' | undefined; + + /** + * + * This is a special performance property exposed by RCTView and is useful for scrolling content when there are many subviews, + * most of which are offscreen. For this property to be effective, it must be applied to a view that contains many subviews that extend outside its bound. + * The subviews must also have overflow: hidden, as should the containing view (or one of its superviews). + */ + removeClippedSubviews?: boolean | undefined; + + style?: StyleProp | undefined; + + /** + * Used to locate this view in end-to-end tests. + */ + testID?: string | undefined; + + /** + * Used to reference react managed views from native code. + */ + nativeID?: string | undefined; +} diff --git a/packages/react-native/Libraries/Components/View/ViewPropTypes.js b/packages/react-native/Libraries/Components/View/ViewPropTypes.js new file mode 100644 index 000000000000..e96654a36679 --- /dev/null +++ b/packages/react-native/Libraries/Components/View/ViewPropTypes.js @@ -0,0 +1,623 @@ +/** + * 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 + * @flow strict-local + */ + +'use strict'; + +import type {EdgeInsetsOrSizeProp} from '../../StyleSheet/EdgeInsetsPropType'; +import type {ViewStyleProp} from '../../StyleSheet/StyleSheet'; +import type { + BlurEvent, + FocusEvent, + Layout, + LayoutEvent, + MouseEvent, + PointerEvent, + PressEvent, +} from '../../Types/CoreEventTypes'; +import type { + AccessibilityActionEvent, + AccessibilityActionInfo, + AccessibilityRole, + AccessibilityState, + AccessibilityValue, + Role, +} from './ViewAccessibility'; +import type {Node} from 'react'; + +export type ViewLayout = Layout; +export type ViewLayoutEvent = LayoutEvent; + +type DirectEventProps = $ReadOnly<{| + /** + * When `accessible` is true, the system will try to invoke this function + * when the user performs an accessibility custom action. + * + */ + onAccessibilityAction?: ?(event: AccessibilityActionEvent) => mixed, + + /** + * When `accessible` is true, the system will try to invoke this function + * when the user performs accessibility tap gesture. + * + * See https://reactnative.dev/docs/view#onaccessibilitytap + */ + onAccessibilityTap?: ?() => mixed, + + /** + * Invoked on mount and layout changes with: + * + * `{nativeEvent: { layout: {x, y, width, height}}}` + * + * This event is fired immediately once the layout has been calculated, but + * the new layout may not yet be reflected on the screen at the time the + * event is received, especially if a layout animation is in progress. + * + * See https://reactnative.dev/docs/view#onlayout + */ + onLayout?: ?(event: LayoutEvent) => mixed, + + /** + * When `accessible` is `true`, the system will invoke this function when the + * user performs the magic tap gesture. + * + * See https://reactnative.dev/docs/view#onmagictap + */ + onMagicTap?: ?() => mixed, + + /** + * When `accessible` is `true`, the system will invoke this function when the + * user performs the escape gesture. + * + * See https://reactnative.dev/docs/view#onaccessibilityescape + */ + onAccessibilityEscape?: ?() => mixed, +|}>; + +type MouseEventProps = $ReadOnly<{| + onMouseEnter?: ?(event: MouseEvent) => void, + onMouseLeave?: ?(event: MouseEvent) => void, +|}>; + +// Experimental/Work in Progress Pointer Event Callbacks (not yet ready for use) +type PointerEventProps = $ReadOnly<{| + onPointerEnter?: ?(event: PointerEvent) => void, + onPointerEnterCapture?: ?(event: PointerEvent) => void, + onPointerLeave?: ?(event: PointerEvent) => void, + onPointerLeaveCapture?: ?(event: PointerEvent) => void, + onPointerMove?: ?(event: PointerEvent) => void, + onPointerMoveCapture?: ?(event: PointerEvent) => void, + onPointerCancel?: ?(e: PointerEvent) => void, + onPointerCancelCapture?: ?(e: PointerEvent) => void, + onPointerDown?: ?(e: PointerEvent) => void, + onPointerDownCapture?: ?(e: PointerEvent) => void, + onPointerUp?: ?(e: PointerEvent) => void, + onPointerUpCapture?: ?(e: PointerEvent) => void, + onPointerOver?: ?(e: PointerEvent) => void, + onPointerOverCapture?: ?(e: PointerEvent) => void, + onPointerOut?: ?(e: PointerEvent) => void, + onPointerOutCapture?: ?(e: PointerEvent) => void, +|}>; + +type FocusEventProps = $ReadOnly<{| + onBlur?: ?(event: BlurEvent) => void, + onBlurCapture?: ?(event: BlurEvent) => void, + onFocus?: ?(event: FocusEvent) => void, + onFocusCapture?: ?(event: FocusEvent) => void, +|}>; + +type TouchEventProps = $ReadOnly<{| + onTouchCancel?: ?(e: PressEvent) => void, + onTouchCancelCapture?: ?(e: PressEvent) => void, + onTouchEnd?: ?(e: PressEvent) => void, + onTouchEndCapture?: ?(e: PressEvent) => void, + onTouchMove?: ?(e: PressEvent) => void, + onTouchMoveCapture?: ?(e: PressEvent) => void, + onTouchStart?: ?(e: PressEvent) => void, + onTouchStartCapture?: ?(e: PressEvent) => void, +|}>; + +/** + * For most touch interactions, you'll simply want to wrap your component in + * `TouchableHighlight` or `TouchableOpacity`. Check out `Touchable.js`, + * `ScrollResponder.js` and `ResponderEventPlugin.js` for more discussion. + */ +type GestureResponderEventProps = $ReadOnly<{| + /** + * Does this view want to "claim" touch responsiveness? This is called for + * every touch move on the `View` when it is not the responder. + * + * `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where + * `event` is a synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onmoveshouldsetresponder + */ + onMoveShouldSetResponder?: ?(e: PressEvent) => boolean, + + /** + * If a parent `View` wants to prevent a child `View` from becoming responder + * on a move, it should have this handler which returns `true`. + * + * `View.props.onMoveShouldSetResponderCapture: (event) => [true | false]`, + * where `event` is a synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onMoveShouldsetrespondercapture + */ + onMoveShouldSetResponderCapture?: ?(e: PressEvent) => boolean, + + /** + * The View is now responding for touch events. This is the time to highlight + * and show the user what is happening. + * + * `View.props.onResponderGrant: (event) => {}`, where `event` is a synthetic + * touch event as described above. + * + * PanResponder includes a note `// TODO: t7467124 investigate if this can be removed` that + * should help fixing this return type. + * + * See https://reactnative.dev/docs/view#onrespondergrant + */ + onResponderGrant?: ?(e: PressEvent) => void | boolean, + + /** + * The user is moving their finger. + * + * `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic + * touch event as described above. + * + * See https://reactnative.dev/docs/view#onrespondermove + */ + onResponderMove?: ?(e: PressEvent) => void, + + /** + * Another responder is already active and will not release it to that `View` + * asking to be the responder. + * + * `View.props.onResponderReject: (event) => {}`, where `event` is a + * synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onresponderreject + */ + onResponderReject?: ?(e: PressEvent) => void, + + /** + * Fired at the end of the touch. + * + * `View.props.onResponderRelease: (event) => {}`, where `event` is a + * synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onresponderrelease + */ + onResponderRelease?: ?(e: PressEvent) => void, + + onResponderStart?: ?(e: PressEvent) => void, + onResponderEnd?: ?(e: PressEvent) => void, + + /** + * The responder has been taken from the `View`. Might be taken by other + * views after a call to `onResponderTerminationRequest`, or might be taken + * by the OS without asking (e.g., happens with control center/ notification + * center on iOS) + * + * `View.props.onResponderTerminate: (event) => {}`, where `event` is a + * synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onresponderterminate + */ + onResponderTerminate?: ?(e: PressEvent) => void, + + /** + * Some other `View` wants to become responder and is asking this `View` to + * release its responder. Returning `true` allows its release. + * + * `View.props.onResponderTerminationRequest: (event) => {}`, where `event` + * is a synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onresponderterminationrequest + */ + onResponderTerminationRequest?: ?(e: PressEvent) => boolean, + + /** + * Does this view want to become responder on the start of a touch? + * + * `View.props.onStartShouldSetResponder: (event) => [true | false]`, where + * `event` is a synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onstartshouldsetresponder + */ + onStartShouldSetResponder?: ?(e: PressEvent) => boolean, + + /** + * If a parent `View` wants to prevent a child `View` from becoming responder + * on a touch start, it should have this handler which returns `true`. + * + * `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`, + * where `event` is a synthetic touch event as described above. + * + * See https://reactnative.dev/docs/view#onstartshouldsetrespondercapture + */ + onStartShouldSetResponderCapture?: ?(e: PressEvent) => boolean, +|}>; + +type AndroidDrawableThemeAttr = $ReadOnly<{| + type: 'ThemeAttrAndroid', + attribute: string, +|}>; + +type AndroidDrawableRipple = $ReadOnly<{| + type: 'RippleAndroid', + color?: ?number, + borderless?: ?boolean, + rippleRadius?: ?number, +|}>; + +type AndroidDrawable = AndroidDrawableThemeAttr | AndroidDrawableRipple; + +type AndroidViewProps = $ReadOnly<{| + nativeBackgroundAndroid?: ?AndroidDrawable, + nativeForegroundAndroid?: ?AndroidDrawable, + + /** + * Whether this `View` should render itself (and all of its children) into a + * single hardware texture on the GPU. + * + * @platform android + * + * See https://reactnative.dev/docs/view#rendertohardwaretextureandroid + */ + renderToHardwareTextureAndroid?: ?boolean, + + /** + * Whether this `View` needs to rendered offscreen and composited with an + * alpha in order to preserve 100% correct colors and blending behavior. + * + * @platform android + * + * See https://reactnative.dev/docs/view#needsoffscreenalphacompositing + */ + needsOffscreenAlphaCompositing?: ?boolean, + + /** + * Indicates to accessibility services whether the user should be notified + * when this view changes. Works for Android API >= 19 only. + * + * @platform android + * + * See https://reactnative.dev/docs/view#accessibilityliveregion + */ + accessibilityLiveRegion?: ?('none' | 'polite' | 'assertive'), + + /** + * Indicates to accessibility services whether the user should be notified + * when this view changes. Works for Android API >= 19 only. + * + * @platform android + * + * See https://reactnative.dev/docs/view#accessibilityliveregion + */ + 'aria-live'?: ?('polite' | 'assertive' | 'off'), + + /** + * Controls how view is important for accessibility which is if it + * fires accessibility events and if it is reported to accessibility services + * that query the screen. Works for Android only. + * + * @platform android + * + * See https://reactnative.dev/docs/view#importantforaccessibility + */ + importantForAccessibility?: ?('auto' | 'yes' | 'no' | 'no-hide-descendants'), + + /** + * Whether to force the Android TV focus engine to move focus to this view. + * + * @platform android + */ + hasTVPreferredFocus?: ?boolean, + + /** + * TV next focus down (see documentation for the View component). + * + * @platform android + */ + nextFocusDown?: ?number, + + /** + * TV next focus forward (see documentation for the View component). + * + * @platform android + */ + nextFocusForward?: ?number, + + /** + * TV next focus left (see documentation for the View component). + * + * @platform android + */ + nextFocusLeft?: ?number, + + /** + * TV next focus right (see documentation for the View component). + * + * @platform android + */ + nextFocusRight?: ?number, + + /** + * TV next focus up (see documentation for the View component). + * + * @platform android + */ + nextFocusUp?: ?number, + + /** + * Whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. + * + * @platform android + */ + focusable?: boolean, + + /** + * Indicates whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard. + * See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex + * for more details. + * + * Supports the following values: + * - 0 (View is focusable) + * - -1 (View is not focusable) + * + * @platform android + */ + tabIndex?: 0 | -1, + + /** + * The action to perform when this `View` is clicked on by a non-touch click, eg. enter key on a hardware keyboard. + * + * @platform android + */ + onClick?: ?(event: PressEvent) => mixed, +|}>; + +type IOSViewProps = $ReadOnly<{| + /** + * Prevents view from being inverted if set to true and color inversion is turned on. + * + * @platform ios + */ + accessibilityIgnoresInvertColors?: ?boolean, + + /** + * A value indicating whether VoiceOver should ignore the elements + * within views that are siblings of the receiver. + * Default is `false`. + * + * @platform ios + * + * See https://reactnative.dev/docs/view#accessibilityviewismodal + */ + accessibilityViewIsModal?: ?boolean, + + /** + * The aria-modal attribute indicates content contained within a modal with aria-modal="true" + * should be accessible to the user. + * Default is `false`. + * + * @platform ios + */ + 'aria-modal'?: ?boolean, + + /** + * A value indicating whether the accessibility elements contained within + * this accessibility element are hidden. + * + * @platform ios + * + * See https://reactnative.dev/docs/view#accessibilityElementsHidden + */ + accessibilityElementsHidden?: ?boolean, + + /** + * Whether this `View` should be rendered as a bitmap before compositing. + * + * @platform ios + * + * See https://reactnative.dev/docs/view#shouldrasterizeios + */ + shouldRasterizeIOS?: ?boolean, +|}>; + +export type ViewProps = $ReadOnly<{| + ...DirectEventProps, + ...GestureResponderEventProps, + ...MouseEventProps, + ...PointerEventProps, + ...FocusEventProps, + ...TouchEventProps, + ...AndroidViewProps, + ...IOSViewProps, + + children?: Node, + style?: ?ViewStyleProp, + + /** + * When `true`, indicates that the view is an accessibility element. + * By default, all the touchable elements are accessible. + * + * See https://reactnative.dev/docs/view#accessible + */ + accessible?: ?boolean, + + /** + * Overrides the text that's read by the screen reader when the user interacts + * with the element. By default, the label is constructed by traversing all + * the children and accumulating all the `Text` nodes separated by space. + * + * See https://reactnative.dev/docs/view#accessibilitylabel + */ + accessibilityLabel?: ?Stringish, + + /** + * An accessibility hint helps users understand what will happen when they perform + * an action on the accessibility element when that result is not obvious from the + * accessibility label. + * + * + * See https://reactnative.dev/docs/view#accessibilityHint + */ + accessibilityHint?: ?Stringish, + + /** + * Alias for accessibilityLabel https://reactnative.dev/docs/view#accessibilitylabel + * https://github.com/facebook/react-native/issues/34424 + */ + 'aria-label'?: ?Stringish, + + /** + * Indicates to the accessibility services that the UI component is in + * a specific language. The provided string should be formatted following + * the BCP 47 specification (https://www.rfc-editor.org/info/bcp47). + * + * @platform ios + */ + accessibilityLanguage?: ?Stringish, + + /** + * Indicates to accessibility services to treat UI component like a specific role. + */ + accessibilityRole?: ?AccessibilityRole, + + /** + * Alias for accessibilityRole + */ + role?: ?Role, + + /** + * Indicates to accessibility services that UI Component is in a specific State. + */ + accessibilityState?: ?AccessibilityState, + accessibilityValue?: ?AccessibilityValue, + + /** + * alias for accessibilityState + * It represents textual description of a component's value, or for range-based components, such as sliders and progress bars. + */ + 'aria-valuemax'?: ?AccessibilityValue['max'], + 'aria-valuemin'?: ?AccessibilityValue['min'], + 'aria-valuenow'?: ?AccessibilityValue['now'], + 'aria-valuetext'?: ?AccessibilityValue['text'], + + /** + * Provides an array of custom actions available for accessibility. + * + */ + accessibilityActions?: ?$ReadOnlyArray, + + /** + * Specifies the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud. + * + * @platform android + */ + accessibilityLabelledBy?: ?string | ?Array, + + /** + * alias for accessibilityState + * + * see https://reactnative.dev/docs/accessibility#accessibilitystate + */ + 'aria-busy'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', + 'aria-disabled'?: ?boolean, + 'aria-expanded'?: ?boolean, + 'aria-selected'?: ?boolean, + /** A value indicating whether the accessibility elements contained within + * this accessibility element are hidden. + * + * See https://reactnative.dev/docs/view#aria-hidden + */ + 'aria-hidden'?: ?boolean, + + /** + * It represents the nativeID of the associated label text. When the assistive technology focuses on the component with this props, the text is read aloud. + * + * @platform android + */ + 'aria-labelledby'?: ?string, + + /** + * Views that are only used to layout their children or otherwise don't draw + * anything may be automatically removed from the native hierarchy as an + * optimization. Set this property to `false` to disable this optimization and + * ensure that this `View` exists in the native view hierarchy. + * + * @platform android + * In Fabric, this prop is used in ios as well. + * + * See https://reactnative.dev/docs/view#collapsable + */ + collapsable?: ?boolean, + + /** + * Used to locate this view from native classes. + * + * > This disables the 'layout-only view removal' optimization for this view! + * + * See https://reactnative.dev/docs/view#id + */ + id?: string, + + /** + * Used to locate this view in end-to-end tests. + * + * > This disables the 'layout-only view removal' optimization for this view! + * + * See https://reactnative.dev/docs/view#testid + */ + testID?: ?string, + + /** + * Used to locate this view from native classes. + * + * > This disables the 'layout-only view removal' optimization for this view! + * + * See https://reactnative.dev/docs/view#nativeid + */ + nativeID?: ?string, + + /** + * This defines how far a touch event can start away from the view. + * Typical interface guidelines recommend touch targets that are at least + * 30 - 40 points/density-independent pixels. + * + * > 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. + * + * See https://reactnative.dev/docs/view#hitslop + */ + hitSlop?: ?EdgeInsetsOrSizeProp, + + /** + * Controls whether the `View` can be the target of touch events. + * + * See https://reactnative.dev/docs/view#pointerevents + */ + pointerEvents?: ?('auto' | 'box-none' | 'box-only' | 'none'), + + /** + * This is a special performance property exposed by `RCTView` and is useful + * for scrolling content when there are many subviews, most of which are + * offscreen. For this property to be effective, it must be applied to a + * view that contains many subviews that extend outside its bound. The + * subviews must also have `overflow: hidden`, as should the containing view + * (or one of its superviews). + * + * See https://reactnative.dev/docs/view#removeclippedsubviews + */ + removeClippedSubviews?: ?boolean, +|}>; diff --git a/packages/react-native/Libraries/Components/View/__tests__/View-test.js b/packages/react-native/Libraries/Components/View/__tests__/View-test.js new file mode 100644 index 000000000000..66fac79f4ab4 --- /dev/null +++ b/packages/react-native/Libraries/Components/View/__tests__/View-test.js @@ -0,0 +1,193 @@ +/** + * 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 + * @oncall react_native + */ + +'use strict'; + +const render = require('../../../../jest/renderer'); +const React = require('../React'); +const View = require('../View'); + +jest.unmock('../View'); +jest.unmock('../ViewNativeComponent'); + +describe('View', () => { + it('default render', () => { + const instance = render.create(); + + expect(instance.toJSON()).toMatchInlineSnapshot(``); + }); + + it('has displayName', () => { + expect(View.displayName).toEqual('View'); + }); +}); + +describe('View compat with web', () => { + it('renders core props', () => { + const props = { + id: 'id', + tabIndex: 0, + testID: 'testID', + }; + + const instance = render.create(); + + expect(instance.toJSON()).toMatchInlineSnapshot(` + + `); + }); + + it('renders "aria-*" props', () => { + const props = { + 'aria-activedescendant': 'activedescendant', + 'aria-atomic': true, + 'aria-autocomplete': 'list', + 'aria-busy': true, + 'aria-checked': true, + 'aria-columncount': 5, + 'aria-columnindex': 3, + 'aria-columnspan': 2, + 'aria-controls': 'controls', + 'aria-current': 'current', + 'aria-describedby': 'describedby', + 'aria-details': 'details', + 'aria-disabled': true, + 'aria-errormessage': 'errormessage', + 'aria-expanded': true, + 'aria-flowto': 'flowto', + 'aria-haspopup': true, + 'aria-hidden': true, + 'aria-invalid': true, + 'aria-keyshortcuts': 'Cmd+S', + 'aria-label': 'label', + 'aria-labelledby': 'labelledby', + 'aria-level': 3, + 'aria-live': 'polite', + 'aria-modal': true, + 'aria-multiline': true, + 'aria-multiselectable': true, + 'aria-orientation': 'portrait', + 'aria-owns': 'owns', + 'aria-placeholder': 'placeholder', + 'aria-posinset': 5, + 'aria-pressed': true, + 'aria-readonly': true, + 'aria-required': true, + role: 'main', + 'aria-roledescription': 'roledescription', + 'aria-rowcount': 5, + 'aria-rowindex': 3, + 'aria-rowspan': 3, + 'aria-selected': true, + 'aria-setsize': 5, + 'aria-sort': 'ascending', + 'aria-valuemax': 5, + 'aria-valuemin': 0, + 'aria-valuenow': 3, + 'aria-valuetext': '3', + }; + + const instance = render.create(); + + expect(instance.toJSON()).toMatchInlineSnapshot(` + + `); + }); + + it('renders styles', () => { + const style = { + display: 'flex', + flex: 1, + backgroundColor: 'white', + marginInlineStart: 10, + pointerEvents: 'none', + }; + + const instance = render.create(); + + expect(instance.toJSON()).toMatchInlineSnapshot(` + + `); + }); +}); diff --git a/packages/react-native/Libraries/Components/__tests__/Button-test.js b/packages/react-native/Libraries/Components/__tests__/Button-test.js new file mode 100644 index 000000000000..8ecd5f7f6a64 --- /dev/null +++ b/packages/react-native/Libraries/Components/__tests__/Button-test.js @@ -0,0 +1,59 @@ +/** + * 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. + */ + +import Button from '../Button'; +import * as React from 'react'; +import ReactTestRenderer from 'react-test-renderer'; + +describe('