Граф коммитов

24904 Коммитов

Автор SHA1 Сообщение Дата
Kunal Farmah 87cfd386cb Added additional builder method receiving arguments for using jsc or hermes to correctly decide which DSO to load at app startup. (#33952)
Summary:
The current implementation of **getDefaultJSExecutorFactory** relies solely on try catch to load the correct .so file for jsc or hermes based on the project configuration.
Relying solely on try catch block and loading jsc even when project is using hermes can lead to launch time crashes especially in monorepo architectures and hybrid apps using both native android and react native.
So we can make use of an additional **ReactInstanceManager :: setJsEngineAsHermes** method that accepts a Boolean argument from the host app while building ReactInstanceManager which can tell which library to load at startup in **ReactInstanceManagerBuilder** which will now have an enhanced getDefaultJSExecutorFactory method that will combine the old logic with the new one to load the dso files.

The code snippet in **ReactInstanceManager** for adding a new setter method:

```
  /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }
```

The code snippet for the new logic in **ReactInstanceManagerBuilder**:

1) Setting up the new logic:
Adding a new enum class :
```
  public enum JSInterpreter {
    OLD_LOGIC,
    JSC,
    HERMES
  }
```

A setter getting boolean value telling whether to use hermes or not and calling a private setter to update the enum variable.
```
 /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }
```

2) Modifying the getDefaultJSExecutorFactory method to incorporate the new logic with the old one:

```
   private JavaScriptExecutorFactory getDefaultJSExecutorFactory(
    String appName, String deviceName, Context applicationContext) {

    // Relying solely on try catch block and loading jsc even when
    // project is using hermes can lead to launch-time crashes especially in
    // monorepo architectures and hybrid apps using both native android
    // and react native.
    // So we can use the value of enableHermes received by the constructor
    // to decide which library to load at launch

    // if nothing is specified, use old loading method
    // else load the required engine
    if (jsEngine == JSInterpreter.OLD_LOGIC) {
      try {
        // If JSC is included, use it as normal
        initializeSoLoaderIfNecessary(applicationContext);
        JSCExecutor.loadLibrary();
        return new JSCExecutorFactory(appName, deviceName);
      } catch (UnsatisfiedLinkError jscE) {
        if (jscE.getMessage().contains("__cxa_bad_typeid")) {
          throw jscE;
        }
        HermesExecutor.loadLibrary();
        return new HermesExecutorFactory();
      }
    } else if (jsEngine == JSInterpreter.HERMES) {
      HermesExecutor.loadLibrary();
      return new HermesExecutorFactory();
    } else {
      JSCExecutor.loadLibrary();
      return new JSCExecutorFactory(appName, deviceName);
    }
  }
```

### **Suggested changes in any Android App's MainApplication that extends ReactApplication to take advantage of this fix**
```
builder = ReactInstanceManager.builder()
                .setApplication(this)
                .setJsEngineAsHermes(BuildConfig.HERMES_ENABLED)
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
```

where HERMES_ENABLED is a buildConfigField based on the enableHermes flag in build.gradle:

`def enableHermes = project.ext.react.get("enableHermes", true)
`
and then

```
defaultConfig{
if(enableHermes) {
            buildConfigField("boolean", "HERMES_ENABLED", "true")
        }
        else{
            buildConfigField("boolean", "HERMES_ENABLED", "false")
        }
}
```

Our app was facing a similar issue as listed in this list:  **https://github.com/facebook/react-native/issues?q=is%3Aissue+is%3Aopen+DSO**. Which was react-native trying to load jsc even when our project used hermes when a debug build was deployed on a device using android studio play button.

This change can possibly solve many of the issues listed in the list as it solved ours.

## Changelog

[GENERAL] [ADDED] - An enum JSInterpreter  in com.facebook.react package:
```
/**
 * An enum that specifies the JS Engine to be used in the app
 * Old Logic uses the legacy code
 * JSC/HERMES loads the respective engine using the revamped logic
 */
public enum JSInterpreter {
  OLD_LOGIC,
  JSC,
  HERMES
}
```

[GENERAL] [ADDED] - An enum variable storing the default value of Js Engine loading mechanism in ReactInstanceManagerBuilder:

```
   private JSInterpreter  jsEngine = JSInterpreter.OLD_LOGIC;
```

[GENERAL] [ADDED] - A new setter method and a helper method to set the js engine in ReactInstanceManagerBuilder:
```
  /**
   * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call
   * Uses the enum {link JSInterpreter}
   * param jsEngine
   */
  private void setJSEngine(JSInterpreter jsEngine){
    this.jsEngine = jsEngine;
  }

  /**
   * Utility setter to set the required JSEngine as HERMES or JSC
   * Defaults to OLD_LOGIC if not called by the host app
   * param hermesEnabled
   * hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise
   */
  public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled){
    if(hermesEnabled){
      setJSEngine(JSInterpreter.HERMES);
    }
    else{
      setJSEngine(JSInterpreter.JSC);
    }
    return this;
  }

```

[GENERAL] [ADDED] - Modified **getDefaultJSExecutorFactory** method

```
private JavaScriptExecutorFactory getDefaultJSExecutorFactory(
    String appName, String deviceName, Context applicationContext) {

    // Relying solely on try catch block and loading jsc even when
    // project is using hermes can lead to launch-time crashes especially in
    // monorepo architectures and hybrid apps using both native android
    // and react native.
    // So we can use the value of enableHermes received by the constructor
    // to decide which library to load at launch

    // if nothing is specified, use old loading method
    // else load the required engine
    if (jsEngine == JSInterpreter.OLD_LOGIC) {
      try {
        // If JSC is included, use it as normal
        initializeSoLoaderIfNecessary(applicationContext);
        JSCExecutor.loadLibrary();
        return new JSCExecutorFactory(appName, deviceName);
      } catch (UnsatisfiedLinkError jscE) {
        if (jscE.getMessage().contains("__cxa_bad_typeid")) {
          throw jscE;
        }
        HermesExecutor.loadLibrary();
        return new HermesExecutorFactory();
      }
    } else if (jsEngine == JSInterpreter.HERMES) {
      HermesExecutor.loadLibrary();
      return new HermesExecutorFactory();
    } else {
      JSCExecutor.loadLibrary();
      return new JSCExecutorFactory(appName, deviceName);
    }
  }
```

Pull Request resolved: https://github.com/facebook/react-native/pull/33952

Test Plan:
The testing for this change might be tricky but can be done by following the reproduction steps in the issues related to DSO loading here: https://github.com/facebook/react-native/issues?q=is%3Aissue+is%3Aopen+DSO

Generally, the app will not crash anymore on deploying debug using android studio if we are removing libjsc and its related libraries in **packagingOptions** in build.gradle and using hermes in the project.
It can be like:
```
packagingOptions {
        if (enableHermes) {
            exclude "**/libjsc*.so"
        }
    }
```

Reviewed By: lunaleaps

Differential Revision: D37191981

Pulled By: cortinico

fbshipit-source-id: c528ead126939f1d788af7523f3798ed2a14f36e
2022-06-23 15:43:35 -07:00
Luna Wei fa814d4875 PointerEvents: Fix dispatch optimization
Summary:
Changelog: [Internal] Fixing a recent optimization to prevent event dispatches for events that are not listened for. An incorrect hitpath was passed in for `leave` events.

Refactored the PointerEvent optimization such that `filterByShouldDispatch` determines what views should dispatch a PointerEvent, and `dispatchEventForViewTargets` to actually dispatch them. We are separating this because the order of dispatch differs between `enter` and `leave` events.

Reviewed By: vincentriemer

Differential Revision: D37348726

fbshipit-source-id: a09a04df3ae027cce95e0d93a4163c2015fe3fe3
2022-06-23 11:01:04 -07:00
Luna Wei 15d9aa0cdb Back out "Back out "PointerEvents: Don't dispatch when no listeners for hover events" because hover events stopped working in felios apps in headsets"
Summary: Changelog: [Internal] - Reland pointer event dispatch optimization. Have a fix in followup commit.

Reviewed By: vincentriemer

Differential Revision: D37348771

fbshipit-source-id: 495dda301849255ddc2b35cc5ef9054f10f77ce8
2022-06-23 11:01:04 -07:00
Genki Kondo b5f1b3dffc Add check for native animated node existing before starting animation
Summary:
We need to check that the animated node exists prior to executing the animation. The native animated node lifecycle is not synced with Fabric and nodes are frequently destroyed and re-created on rerenders. Therefore, there is a possibility that the the animated node does not exist when the native event is dispatched, in particular with native call batching.

Changelog:
[Internal] - Make NativeAnimatedNodesManager.getNodeById public

Reviewed By: JoshuaGross

Differential Revision: D37323138

fbshipit-source-id: ed0567871b4189c454b6b3145b853ecdfe844840
2022-06-23 08:14:03 -07:00
Pieter De Baets a0d597dbca Throw error when accessing undefined property on runtimeScheduler
Summary:
This improves errors significantly, which is especially helpful as the runtime scheduler only implements a subset of the JS API.

Example error: `Error: Exception in HostObject::get for prop 'unstable_next': undefined property`

Changelog: [Internal]

Reviewed By: rickhanlonii

Differential Revision: D37313924

fbshipit-source-id: b53bc67b9cc36dee34dba86c07fdcf2353338c72
2022-06-23 03:37:56 -07:00
Nicola Corti ea8d8e2f49 Bump @react-native/eslint-plugin-specs to 0.0.4
Summary:
As we changed the deps for react-native/eslint-plugin-specs, let's release a new version of it.

Changelog:
[General] [Changed] - Bump react-native/eslint-plugin-specs to 0.0.4

Reviewed By: jacdebug

Differential Revision: D37353474

fbshipit-source-id: dc77c987ee06d72903d246544c63816a64ecd7f6
2022-06-23 01:23:52 -07:00
Pieter Vanderwerff c940eb0c49 Add LTI annotations to function params in xplat/js [manually-modified]
Summary: Add annotations to function parameters required for Flow's Local Type Inference project. This codemod prepares the codebase to match Flow's new typechecking algorithm. The new algorithm will make Flow more reliable and predicatable.

Reviewed By: bradzacher

Differential Revision: D37363351

fbshipit-source-id: a9d3df7db6f9d094ac2ce81aae1f3ab4f62b243a
2022-06-22 23:01:55 -07:00
Pieter Vanderwerff e7a4dbcefc Add LTI annotations to function params in xplat/js [1/2]
Summary: Add annotations to function parameters required for Flow's Local Type Inference project. This codemod prepares the codebase to match Flow's new typechecking algorithm. The new algorithm will make Flow more reliable and predicatable.

Reviewed By: evanyeung

Differential Revision: D37353648

fbshipit-source-id: e5a0c685ced85a8ff353d578b373f836b376bb28
2022-06-22 21:36:52 -07:00
Nicola Corti a7db8df207 Make Hermes the default engine on Android. (#34049)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/34049

This just flips the switch for having Hermes on by default
on new projects for React Native.

Changelog:
[Android] [Changed] - Make Hermes the default engine on Android

Reviewed By: neildhar, jpporto

Differential Revision: D37354079

fbshipit-source-id: cb0391eb3927d13432e7d4b9efef7b8812938a98
2022-06-22 20:38:36 -07:00
Nicola Corti 78cd689f9a Do not depend on hermes-engine NPM package anymore
Summary:
This removes the `hermes-engine` NPM package from the RN package.json.
Users are not supposed to use this package anymore as we now ship Hermes
bundled with React Native.

More on this here: https://reactnative.dev/architecture/bundled-hermes

Changelog:
[General] [Changed] - Do not depend on hermes-engine NPM package anymore

Reviewed By: neildhar

Differential Revision: D37353977

fbshipit-source-id: b049d18e945a72c1f37c3e4b040af83b5e395774
2022-06-22 20:38:36 -07:00
Pieter Vanderwerff d96744e277 Add LTI annotations to function params in xplat/js [2/2]
Summary: Add annotations to function parameters required for Flow's Local Type Inference project. This codemod prepares the codebase to match Flow's new typechecking algorithm. The new algorithm will make Flow more reliable and predicatable.

Reviewed By: evanyeung

Differential Revision: D37360113

fbshipit-source-id: 870bcfe680542b3861fefbaf372db0ae8b32cbf3
2022-06-22 18:46:51 -07:00
Joshua Gross 777a92de2f Work around some Views not using ThemedReactContext
Summary:
ThemedReactContext should be what is stored as the context on all RN views, but some legacy components use other things like an Activity.

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D37356865

fbshipit-source-id: bc914cd06a8846037506a50f254995a6e10c8a9c
2022-06-22 14:28:08 -07:00
Yann Pringault 97291bfa31 fix(eslint-config): switch to new babel parser (#34020)
Summary:
[`babel-eslint`](https://github.com/babel/babel-eslint) is deprecated now. We should use the new Babel parser.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[General] [Fixed] - Use new Babel parser instead of deprecated one

Pull Request resolved: https://github.com/facebook/react-native/pull/34020

Test Plan: Ensure lint is working as expected.

Reviewed By: cortinico

Differential Revision: D37239826

Pulled By: jacdebug

fbshipit-source-id: f5fa5d7f829d6d3ae5cffd855ed6c8542c7d46de
2022-06-21 21:04:42 -07:00
Simek 1999191881 Update CONTRIBUTING.md, replace wiki links (#34035)
Summary:
This PR is a follow up for the contributing content move on the website:
* https://github.com/facebook/react-native-website/pull/3120

It replaces most of the CONTRIBUTING file content with a reference to the contributing overview page on the website, which has been based off the content of this file.

Additionally I have searched thought the code for the wiki links and replaces theme with the correct website links. There was an instance where comment was referring to an old and removed a while ago wiki page, so I just get rid of this link.

## Changelog

[Internal] [Chore] - Update CONTRIBUTING.md, replace wiki links

Pull Request resolved: https://github.com/facebook/react-native/pull/34035

Test Plan: N/A

Reviewed By: lunaleaps

Differential Revision: D37318814

Pulled By: cortinico

fbshipit-source-id: d3f5e5c5bd477c0de5c4f0f1d5de81f464b9f5b4
2022-06-21 19:30:23 -07:00
Paige Sun c2949bd511 Enable absolute bridgeless with REACT_NATIVE_FORCE_NEW_ARCHITECTURE flag on Wilde
Summary: Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D37269572

fbshipit-source-id: ba9ecea2d81075a7ce79e26040924d04b170bf46
2022-06-21 18:55:29 -07:00
Vincent Riemer c25c4abe4a Add detail property to the PointerEvent object
Summary: Changelog: [iOS][Internal] Add detail property to the PointerEvent interface

Reviewed By: necolas

Differential Revision: D37117932

fbshipit-source-id: a5f1c6386d2521e22651453efeffe2005e4a8b6e
2022-06-21 14:05:44 -07:00
Vincent Riemer 27c004745b Add tiltX/tiltY properties to PointerEvent object
Summary: Changelog: [iOS][Internal] - Add tiltX/tiltY properties to the PointerEvent interface

Reviewed By: necolas

Differential Revision: D37117909

fbshipit-source-id: 277d1296b16bbf729dbc32f385634752fd145c8f
2022-06-21 14:05:44 -07:00
fortmarek d27c8cf02d Prepare Changelog for 0.69.0 (#33730)
Summary:
## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[Internal] - Changelog for 0.69.0

Pull Request resolved: https://github.com/facebook/react-native/pull/33730

Reviewed By: lunaleaps

Differential Revision: D36007445

Pulled By: cortinico

fbshipit-source-id: adb9070a83b992f7138e93710a0508be59f07832
2022-06-21 13:59:00 -07:00
Joshua Gross 0724ed0552 Fix crashes in ReactTextView View recycling
Summary:
Fix crashes that can occur on older versions of Android due to not-yet-implemented APIs.

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D37321713

fbshipit-source-id: a27aaf4b28e19a86f4cb10808162102177b9f306
2022-06-21 13:27:03 -07:00
Luis Santana 68f3a42fc7 bump RTC-Folly to 2021.07.22 (#33841)
Summary:
Bumping RTC-Folly version used to address CVE-2022-24440.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[General][Security] - Bump RTC-Folly to 2021-07-22

Pull Request resolved: https://github.com/facebook/react-native/pull/33841

Reviewed By: Andjeliko, philIip

Differential Revision: D36425598

Pulled By: cortinico

fbshipit-source-id: d38c5f020dbecf794b10f12ed2da30e1825071af
2022-06-21 12:36:43 -07:00
Pieter De Baets 6fcb878a89 Back out "fixed SDK issue while uploading app in debug scheme"
Summary:
Original commit changeset: 78387999f94e

Original Phabricator Diff: D34392529 (086c13dd5f)

Backing this out because it breaks univeral hot reload support. We should probably find a way to support this *without* relying on swizzling. This was originally backed out it because it was blocking app store submission, but this is gated by `RN_DEV` so should never be included in a release build.

Changelog:
[General][Removed] - The diffs renames the required variable which was causing conflicts in names with Apple core SDK's

Reviewed By: cipolleschi

Differential Revision: D37311377

fbshipit-source-id: 18abb1b53a5be054098cd3717705ea5086c4f595
2022-06-21 10:48:14 -07:00
Jordan Brown e5f7e4022a Deploy 0.180.1 to xplat
Summary: Changelog: [Internal]

Reviewed By: SamChou19815

Differential Revision: D37313175

fbshipit-source-id: 3a8507a4914bcafb1ec84ed260d67cd28bba9169
2022-06-21 09:08:35 -07:00
Ramanpreet Nara 8dded42b68 Make ScrollView sticky headers work w/o dispatching RCTEventEmitter.receiveEvent
Summary:
# Context
ScrollView sticky headers rely on this bit of code to work:

```
AnimatedImplementation.attachNativeEvent(
  this._scrollViewRef,
  'onScroll',
  [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}],
);
```

What this code means:

When the ScrollView host component receives the "onScroll" event, assign event.nativeEvent.contentOffSet.y to the this._scrollAnimatedValue AnimatedValue.

How this subscription mechanism is set up:

NativeAnimatedTurboModule subscribes to events dispatched by RCTEventDispatcher sendEvent. Then, whenever RCTEventEmitter sendEvent executes, NativeAnimatedTurboModule also updates the AnimatedValue for that event.

# Problem
Previously, in bridgeless, we started dispatching RCTScrollView via the RCTEventDispatcher sendEvent to update the AnimatedValue for ScrollView. This meant that we started dispatching the onScroll event to JavaScript via RCTEventEmitter.receiveEvent JSModule, which isn't supported in the Fabric renderer.

With this diff, we dialed back that solution. Instead of (1) notifying NativeAnimatedTurboModule and (2) sending the onScroll event to JavaScript, we're only doing (1) (i.e: notifying NativeAnimatedTurboModule).

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D37257719

fbshipit-source-id: 7dea3cf8b9ae78f6b0fd40414b8f224d43367a5a
2022-06-21 07:36:01 -07:00
Kudo Chien f97c6a5b49 Fix broken use_frameworks from React-bridging (#34011)
Summary:
`use_frameworks!` is broken again in react-native 0.69 because React-bridging. in the `use_frameworks!` mode, header structures are flattened, so `#include <react/bridging/CallbackWrapper.h>` is not reachable to the header. to somehow workaround the issue without touch React-bridging imports, the pr do these things:

- use `header_mappings_dir` to keep `react/bridging` header structure
- because the header structure is not default framework header structure, explicitly `HEADER_SEARCH_PATHS` is necessary.
- forward declare `CallbackWrapper` and use it internally in ReactCommon. so that we don't need to add `HEADER_SEARCH_PATHS` for React-bridging to every pods depending on `ReactCommon/turbomodule/core`, e.g. React-RCTSettings.podspec.

## Changelog

[iOS] [Fixed] - Fix use_frameworks! for 0.69

Pull Request resolved: https://github.com/facebook/react-native/pull/34011

Test Plan:
```sh
$ npx react-native init RN069 --version next
# add `use_frameworks!` to ios/Podsfile
# comment out use_flipper!() in ios/Podfile
# patch node_modules/react-native with these changes
$ yarn ios
```

Reviewed By: cortinico, cipolleschi

Differential Revision: D37169699

Pulled By: dmitryrykun

fbshipit-source-id: 309c55f1c611a2fc3902a83e8af814daaf2af6a0
2022-06-21 02:56:42 -07:00
Kudo Chien 79baca678a Fix RCT-Folly build error when use_frameworks! and hermes are both enabled (#34030)
Summary:
This PR is fixing the build errors on iOS when `use_frameworks!` and `:hermes_enabled` are both enabled. There are two errors:

- fmt/compile.h include not found: This PR adds fmt in header search paths.
- undefined symbols `_jump_fcontext` and `_make_fcontext` from boost. the two symbols are actually not be unused. because to generate the shared library in dynamic framework mode, LTO (Link-Time-Optimization) is not as powerful as generating a single executable.

## Changelog

[iOS] [Fixed] - Fix RCT-Folly build error when use_frameworks! and hermes are both enabled

Pull Request resolved: https://github.com/facebook/react-native/pull/34030

Test Plan:
- CI passed

-
```
$ npx react-native init RN069 --version next
# edit RN069/ios/Podfile to enable use_frameworks! and hermes_enabled
# patch node_modules/react-native from both https://github.com/facebook/react-native/issues/34011 and this prs' patch
$ pod install
$ yarn ios
```

Reviewed By: cortinico

Differential Revision: D37284084

Pulled By: dmitryrykun

fbshipit-source-id: 923fa03d7844d1d227880919c8b2c8614c848d59
2022-06-20 17:23:23 -07:00
Tim Yung e5c5dcd9e2 RN: Rewrite EventEmitter
Summary:
Rewrites `EventEmitter` as a simple, type-safe abstraction with a minimal interface.

The public interface of `EventEmitter` is unchanged. This rewrite was made possible only after deprecating and removing public methods that imposed restrictions on implementation details (e.g. deleting `removeListener`).

However, this includes a subtle breaking change that makes it behave the same as `EventEmitter` in Node.js and `EventTarget` in the DOM. The set of listeners being notified by `emit` will no longer be influenced by changes made during the course of notifying the existing listeners.

Changelog:
[General][Changed] - `EventEmitter#emit` now freezes the set of listeners before iterating over them, meaning listeners that are added or removed will not affect that iteration.

Reviewed By: javache

Differential Revision: D22153962

fbshipit-source-id: 81b87113590dee0296eff61374bf732171855453
2022-06-18 08:23:32 -07:00
Kacie Bawiec 4bb551d018 Back out "TalkBack support for ScrollView accessibility announcements (list and grid) - Javascript Only Changes"
Summary:
Original commit changeset: 3765213c5d8b

Original Phabricator Diff: D37189197 (2d5882132f)

Changelog: [Internal]

Reviewed By: bvanderhoof

Differential Revision: D37260990

fbshipit-source-id: bfcb10f2d5a2a1427b72a10ef380df194b041ba0
2022-06-17 22:08:57 -07:00
fabriziobertoglio1987 2d5882132f TalkBack support for ScrollView accessibility announcements (list and grid) - Javascript Only Changes (#33180)
Summary:
This is the Javascript-only changes from D34518929 (dd6325bafe), split out for push safety. Original summary and test plan below:

This issue fixes [30977][17] . The Pull Request was previously published by [intergalacticspacehighway][13] with [31666][19].
The solution consists of:
1. Adding Javascript logic in the [FlatList][14], SectionList, VirtualizedList components to provide accessibility information (row and column position) for each cell in the method [renderItem][20] as a fourth parameter [accessibilityCollectionItem][21]. The information is saved on the native side in the AccessibilityNodeInfo and announced by TalkBack when changing row, column, or page ([video example][12]). The prop accessibilityCollectionItem is available in the View component which wraps each FlatList cell.
2. Adding Java logic in [ReactScrollView.java][16] and HorizontalScrollView to announce pages with TalkBack when scrolling up/down. The missing AOSP logic in [ScrollView.java][10] (see also the [GridView][11] example) is responsible for announcing Page Scrolling with TalkBack.

Relevant Links:
x [Additional notes on this PR][18]
x [discussion on the additional container View around each FlatList cell][22]
x [commit adding prop getCellsInItemCount to VirtualizedList][23]

## Changelog

[Android] [Added] - Accessibility announcement for list and grid in FlatList

Pull Request resolved: https://github.com/facebook/react-native/pull/33180

Test Plan:
[1]. TalkBack announces pages and cells with Horizontal Flatlist in the Paper Renderer ([link][1])
[2]. TalkBack announces pages and cells with Vertical Flatlist in the Paper Renderer ([link][2])
[3]. `FlatList numColumns={undefined}` Should not trigger Runtime Error NoSuchKey exception columnCount when enabling TalkBack. ([link][3])
[4]. TalkBack announces pages and cells with Nested Horizontal Flatlist in the rn-tester app ([link][4])

[1]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050452894
[2]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050462465
[3]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1032340879
[4]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050618308
[10]:1ac46f932e/core/java/android/widget/AdapterView.java (L1027-L1029) "GridView.java method responsible for calling setFromIndex and setToIndex"
[11]:https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1042518901 "test case on Android GridView"
[12]:https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050452894 "TalkBack announces pages and cells with Horizontal Flatlist in the Paper Renderer"
[13]:https://github.com/intergalacticspacehighway "github intergalacticspacehighway"
[14]:80acf523a4/Libraries/Lists/FlatList.js (L617-L636) "FlatList accessibilityCollectionItem"
[16]:5706bd7d3e/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java (L183-L184) "logic added to ReactScrollView.java"
[17]: https://github.com/facebook/react-native/issues/30977
[18]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6
[19]: https://github.com/facebook/react-native/pull/31666
[20]: https://reactnative.dev/docs/next/flatlist#required-renderitem "FlatList renderItem documentation"
[21]: 75147359c5 "commit that introduces fourth param accessibilityCollectionItem in callback renderItem"
[22]: https://github.com/facebook/react-native/pull/33180#discussion_r826748664 "discussion on the additional container View around each FlatList cell"
[23]: d50fd1a681 "commit adding prop getCellsInItemCount to VirtualizedList"

Reviewed By: kacieb

Differential Revision: D37189197

Pulled By: blavalla

fbshipit-source-id: 3765213c5d8bfde56e0e5f155cdd899c368512e7
2022-06-17 17:59:51 -07:00
Riccardo Cipolleschi 71da21243c Move New Architecture setup to `new_architecture.rb` file (#33990)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/33990

This diff moves the setting of some CPP flags from the main React native pods file to a dedicated file.

It also introduces some tests and it improves the Test Mocks we have

## Changelog
[iOS][Changed] - Move the `modify_flags_for_new_architecture` method to separate ruby file

Reviewed By: cortinico

Differential Revision: D37040927

fbshipit-source-id: 037ddaf123d01f3a2fd622b8a0cd10535da70b92
2022-06-17 17:11:51 -07:00
David 5854b11bf9 Add ability to pass ItemSeparatorComponent as React Element (#32748)
Summary:
Currently `ListHeaderComponent` & `ListFooterComponent` allow to use React Componetn & Elemelen

```tsx
<FlatList
  ListHeaderComponent={<View />} // valid
  ListHeaderComponent={View}     // valid
/>
```

But when you try to pass `ItemSeparatorComponent` as React Element it will throw an error

```tsx
<FlatList
  ItemSeparatorComponent={View}     // ok
  ItemSeparatorComponent={<View />} /* not valid:
    Error: Element type is invalid: expected a string (for built-in components) or a class/function
    (for composite components) but got: object.
    Check the render method of `CellRenderer`.
  */
/>
```

So, this PR adds this ability

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[General] [Changed] - Add ability to pass `ItemSeparatorComponent` as React Element

Pull Request resolved: https://github.com/facebook/react-native/pull/32748

Test Plan: ...

Reviewed By: lyahdav

Differential Revision: D37227719

Pulled By: cortinico

fbshipit-source-id: 1c4943fa9d42bf5e61fbd999d1f5be46b51ecb14
2022-06-17 16:28:03 -07:00
Ramanpreet Nara 168f020d5e Unbreak SurfaceRegistry users in bridge mode
Summary: Changelog: [Internal]

Reviewed By: nlutsenko

Differential Revision: D37250414

fbshipit-source-id: be3b98ba661c6f267d0d0dcac8d816584ef58c51
2022-06-17 15:06:31 -07:00
Alpha Shuro 4a7e4b9ca6 fix (glog script): remove invalid param from sed (#33967)
Summary:
This is what I had to do locally to fix https://github.com/facebook/react-native/issues/33966

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[iOS] [Fixed] - Fix sed error when installing `glog`

Pull Request resolved: https://github.com/facebook/react-native/pull/33967

Test Plan:
After this, `pod install` installed `glog` successfully

<img width="255" alt="image" src="https://user-images.githubusercontent.com/8580352/172226617-6fe8c3df-1629-42e9-95a4-a9c0ebe675a8.png">

Reviewed By: cortinico

Differential Revision: D36943821

Pulled By: charlesbdudley

fbshipit-source-id: 8f6aa64089b22d23f8c4a015ff30a3789e612b4e
2022-06-17 11:58:08 -07:00
Joshua Gross a291819b5c Fix View Recycling crash on older Android OSes
Summary:
Fixes a trivial crash that occurs when running View Recycling on pre-Android P devices.

Changelog: [Internal]

Reviewed By: bvanderhoof

Differential Revision: D37242858

fbshipit-source-id: 74f3912d60799172c47c67a87f662b4ff8fb1e35
2022-06-17 11:08:02 -07:00
Geraint White b5ff26b0b9 fix(jest): make assetFileTransformer return an object (#33756)
Summary:
Fixes https://github.com/facebook/react-native/issues/33751
Relates to https://github.com/facebook/react-native/issues/33576

Jest 28 removed support for returning a string in the process method of a transformer (https://jestjs.io/docs/upgrading-to-jest28#transformer).

This PR changes assetFileTransformer to return an object instead of a string.

## Changelog

[Internal] [Fixed] - Return object from assetFileTransformer

Pull Request resolved: https://github.com/facebook/react-native/pull/33756

Test Plan: Tests pass with Jest 28 when this change is made.

Reviewed By: cipolleschi

Differential Revision: D37242038

Pulled By: cortinico

fbshipit-source-id: d8a5054f5378183f644cd1458785084b26782193
2022-06-17 10:27:47 -07:00
Ramanpreet Nara ea29ae1ceb SurfaceRegistryBinding: Display RedBox when RN$SurfaceRegistry isn't available
Summary:
SurfaceRegistryBinding::startSurface [checks whether global.RN$SurfaceRegistry binding is installed](https://www.internalfb.com/code/fbsource/[7040bef7d4fe43298c5f9dc1fef10f47ec396e79]/xplat/js/react-native-github/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.cpp?lines=28-29). If not, control flow goes directly into the bridge path: [callFunctionOnModule](https://www.internalfb.com/code/fbsource/[7040bef7d4fe43298c5f9dc1fef10f47ec396e79]/xplat/js/react-native-github/ReactCommon/react/renderer/uimanager/SurfaceRegistryBinding.cpp?lines=40-46). callMethodOfModule [react_native_asserts, if the requested callable JS module isn't available](https://www.internalfb.com/code/fbsource/[7040bef7d4fe43298c5f9dc1fef10f47ec396e79]/xplat/js/react-native-github/ReactCommon/react/renderer/uimanager/bindingUtils.cpp?lines=29) on the batched bridge. This crashes the app.

We could make this error experience better:
1. We shouldn't crash the app.
2. We should fail fast, and produce an error message that is more descriptive of the actual cause of the error.
3. We can leverage the RedBox infra to display this error on the screen.

## Fixes
This diff modifies the gating inside SurfaceRegistryBinding. Now, in bridgeless mode, if global.RN$SurfaceRegistry isn't instaled, we'll display a RedBox instead, that shows what the error is.

Changelog: [Internal]

Reviewed By: sshic

Differential Revision: D37223640

fbshipit-source-id: 8fbf57f5d9cf359046dc94f0a5f7d66624caee4e
2022-06-17 04:34:59 -07:00
Ramanpreet Nara 4967e50989 Make LogBox render through SurfaceRegistry
Summary:
LogBox was using AppRegistry to render on to the screen. Switch LogBox over to using SurfaceRegistry instead.

Changelog: [Internal]

Reviewed By: sshic

Differential Revision: D37223641

fbshipit-source-id: 59001ad290c1e2c2f14828d38a96f48bd1ab39ca
2022-06-17 04:34:59 -07:00
Jack Worden 56051caac5 Back out "React Native sync for revisions d300ceb...256aefb"
Summary:
Original commit changeset: 4c0afc95abe8

Original Phabricator Diff: D37155957 (d1321d88bd)

See attached UBN task for more details, I am reverting the whole diff now while investigating the root cause.

Changelog:
[General][Changed] - Revert "React Native sync for revisions d300ceb...256aefb"

jest_e2e[run_all_tests]

=== update
klein did a bisect for S276290, it seems Original Phabricator Diff: D37155957 (d1321d88bd) is the blame diff.
jackworden also has verified backout can fix it for both ios and android.

Reviewed By: ahujap-fb, kacieb

Differential Revision: D37205394

fbshipit-source-id: 600e6593532da064631c016aace317932f290c67
2022-06-17 03:13:14 -07:00
Tim Shamilov d881c87231 add file and blob globals to eslint config (#31293)
Summary:
The eslint community config does not have the File and Blob polyfills in `globals` which have been part of the Javascript implementation for ~3 years. They were added to the Javascript API in https://github.com/facebook/react-native/issues/11573 by satya164.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[General] [Fixed] - Added File and Blob globals to eslint community config

Pull Request resolved: https://github.com/facebook/react-native/pull/31293

Test Plan:
Evidence these globals exist:
1. https://github.com/facebook/react-native/issues/11573
2. Executed the following:
<img width="421" alt="Screen Shot 2021-04-02 at 12 08 50 PM" src="https://user-images.githubusercontent.com/3495974/113432946-466ae280-93ac-11eb-899c-3ca124e0af84.png">
<img width="317" alt="Screen Shot 2021-04-02 at 12 11 56 PM" src="https://user-images.githubusercontent.com/3495974/113433156-a82b4c80-93ac-11eb-99dc-0840d5ad9078.png">

3. Receive in console:
<img width="603" alt="Screen Shot 2021-04-02 at 12 09 59 PM" src="https://user-images.githubusercontent.com/3495974/113432996-5da9d000-93ac-11eb-81c6-88e6b059c733.png">
<img width="599" alt="Screen Shot 2021-04-02 at 12 12 27 PM" src="https://user-images.githubusercontent.com/3495974/113433174-b711ff00-93ac-11eb-8820-67039696f6ce.png">

Evidence the PR works: the globals in the PR identical to the others in the eslint community config that they are in

Reviewed By: cipolleschi

Differential Revision: D37214364

Pulled By: cortinico

fbshipit-source-id: 71b9dec8d222a057c54f6cde6c6d8e85dd25f6f9
2022-06-16 18:32:37 -07:00
Ramanpreet Nara 83f13e15c6 Bridgeless mode: Stop register JSTimers as callable JavaScript module
Summary:
We do not need to register JSTimers as a callable JavaScript module in bridgeless mode.

How we know bridgeless mode doesn't use JSTimers: [xbgs JSTimers](https://fburl.com/code/clbz47j5)

## Details: iOS
JSTimers is only called into [by RCTCxxBridge](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/xplat/js/react-native-github/React/CxxBridge/RCTCxxBridge.mm?lines=1471), and [RCTTiming.mm, which uses the RCTBridge](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/xplat/js/react-native-github/React/CoreModules/RCTTiming.mm?lines=23%2C241%2C264). RCTBridge is unavailable in bridgeless mode.

## Details: Android
JSTimers is only called into [by TimingModule, inside its BridgeTimerExecutor](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/xplat/js/react-native-github/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java?lines=31%2C40%2C49). This BridgeTimerExecutor is [passed to TimingModule's JavaTimerManager](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/xplat/js/react-native-github/ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java?lines=61-66).

The Bridgeless React instance on Android **does not** use this TimingModule, or this BridgeTimerExecutor. Instead, the Bridgeless React instance [creates its own JavaTimerManager](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/fbandroid/java/com/facebook/venice/ReactInstance.java?lines=118-123), [in C++](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/fbandroid/java/com/facebook/venice/ReactInstance.java?lines=117%2C121%2C382), that [implements the callTimers APIs in C++](https://www.internalfb.com/code/fbsource/[88911d726fb4413765903c32a9077cd662ee7b6e]/fbandroid/java/com/facebook/venice/jni/JJSTimerExecutor.cpp?lines=18-22). Therefore, in Bridgeless mode, the React instance calls into TimerManager to execute timers, whereas in Bridge mode, TimingModule calls into JSTimers to call timers. Hence, JSTimers should also not be used in bridgeless mode.

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D37208873

fbshipit-source-id: ef6ebe0e8a9fcbcc1f8403ed40ff94ec00b2beac
2022-06-16 17:59:40 -07:00
fabriziobertoglio1987 105a2397b6 TalkBack support for ScrollView accessibility announcements (list and grid) - JAVA ONLY CHANGES (#33180)
Summary:
This is the Java-only changes from D34518929 (dd6325bafe), split out for push safety. Original summary and test plan below:

This issue fixes [30977][17] . The Pull Request was previously published by [intergalacticspacehighway][13] with [31666][19].
The solution consists of:
1. Adding Javascript logic in the [FlatList][14], SectionList, VirtualizedList components to provide accessibility information (row and column position) for each cell in the method [renderItem][20] as a fourth parameter [accessibilityCollectionItem][21]. The information is saved on the native side in the AccessibilityNodeInfo and announced by TalkBack when changing row, column, or page ([video example][12]). The prop accessibilityCollectionItem is available in the View component which wraps each FlatList cell.
2. Adding Java logic in [ReactScrollView.java][16] and HorizontalScrollView to announce pages with TalkBack when scrolling up/down. The missing AOSP logic in [ScrollView.java][10] (see also the [GridView][11] example) is responsible for announcing Page Scrolling with TalkBack.

Relevant Links:
x [Additional notes on this PR][18]
x [discussion on the additional container View around each FlatList cell][22]
x [commit adding prop getCellsInItemCount to VirtualizedList][23]

## Changelog

[Android] [Added] - Accessibility announcement for list and grid in FlatList

Pull Request resolved: https://github.com/facebook/react-native/pull/33180

Test Plan:
[1]. TalkBack announces pages and cells with Horizontal Flatlist in the Paper Renderer ([link][1])
[2]. TalkBack announces pages and cells with Vertical Flatlist in the Paper Renderer ([link][2])
[3]. `FlatList numColumns={undefined}` Should not trigger Runtime Error NoSuchKey exception columnCount when enabling TalkBack. ([link][3])
[4]. TalkBack announces pages and cells with Nested Horizontal Flatlist in the rn-tester app ([link][4])

[1]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050452894
[2]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050462465
[3]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1032340879
[4]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050618308
[10]:1ac46f932e/core/java/android/widget/AdapterView.java (L1027-L1029) "GridView.java method responsible for calling setFromIndex and setToIndex"
[11]:https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1042518901 "test case on Android GridView"
[12]:https://github.com/fabriziobertoglio1987/react-native-notes/issues/6#issuecomment-1050452894 "TalkBack announces pages and cells with Horizontal Flatlist in the Paper Renderer"
[13]:https://github.com/intergalacticspacehighway "github intergalacticspacehighway"
[14]:80acf523a4/Libraries/Lists/FlatList.js (L617-L636) "FlatList accessibilityCollectionItem"
[16]:5706bd7d3e/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java (L183-L184) "logic added to ReactScrollView.java"
[17]: https://github.com/facebook/react-native/issues/30977
[18]: https://github.com/fabriziobertoglio1987/react-native-notes/issues/6
[19]: https://github.com/facebook/react-native/pull/31666
[20]: https://reactnative.dev/docs/next/flatlist#required-renderitem "FlatList renderItem documentation"
[21]: 75147359c5 "commit that introduces fourth param accessibilityCollectionItem in callback renderItem"
[22]: https://github.com/facebook/react-native/pull/33180#discussion_r826748664 "discussion on the additional container View around each FlatList cell"
[23]: d50fd1a681 "commit adding prop getCellsInItemCount to VirtualizedList"

Reviewed By: kacieb

Differential Revision: D37186697

Pulled By: blavalla

fbshipit-source-id: 7bb95274326ded417c6f1365cc8633391f589d1a
2022-06-16 16:33:24 -07:00
Vincent Riemer 8cf57a5bdd Add width/height properties to PointerEvent object
Summary: Changelog: [iOS][Internal] Add width/height properties to the PointerEvent object

Reviewed By: kacieb

Differential Revision: D37116854

fbshipit-source-id: 686266d480bb2ee1d2b6696d80ad42865fa2111c
2022-06-16 13:05:54 -07:00
Vincent Riemer 033ffcc14b Remove unecessary PointerEvent attributes
Summary: Changelog: [iOS][Internal] Remove unecessary PointerEvent attributes

Reviewed By: kacieb

Differential Revision: D37115465

fbshipit-source-id: 079a297d1ce5b3d2c6766036a111c73bd75535f1
2022-06-16 13:05:54 -07:00
Brad Zacher 7b0ba6d94f switch from babel-eslint to hermes-eslint for flow code
Summary:
`hermes-eslint` is built by Meta to work with the latest Flow code.
It follows the latest ESLint standards and AST, and has a true scope analyser to ensure best compatibility with core ESLint rules.

Reviewed By: motiz88

Differential Revision: D37181192

fbshipit-source-id: 1f59e01f306792e67a4977435c5c77e0000d960a
2022-06-16 10:12:58 -07:00
Joshua Gross 577582e230 Hook up CPP props parsing and Android ViewRecycling feature flags on Android
Summary:
Hook up feature flags.

Changelog: [Internal]

Reviewed By: cortinico, ryancat

Differential Revision: D37166366

fbshipit-source-id: 440acba9ee85a9ced64cd880d915044de7619584
2022-06-15 23:37:34 -07:00
Joshua Gross 63ddfa02ee Update iOS offine mirrors for RN-Tester on top of D37051020
Summary:
Just bumping the offline mirrors for iOS

Changelog:
[Internal] [Changed] - Update iOS offine mirrors for RN-Tester

Reviewed By: cortinico

Differential Revision: D37187562

fbshipit-source-id: 4ede8413f98afa4694984baf06349f4330304798
2022-06-15 23:37:34 -07:00
Joshua Gross af1eae9ea3 New Props parsing infrastructure for perf improvements: visitor pattern vs random-map-access pattern (BaseTextProps and derived props)
Summary:
See commentary at top of stack.

Changelog: [Added][Fabric] New API for efficient props construction

Reviewed By: javache

Differential Revision: D37051020

fbshipit-source-id: 643e433c0d0590cfcd17bc7a43d105bed6ff12ef
2022-06-15 23:37:34 -07:00
Joshua Gross 2ab585ac26 New Props parsing infrastructure for perf improvements: visitor pattern vs random-map-access pattern (ScrollViewProps)
Summary:
See commentary at top of stack.

Changelog: [Added][Fabric] New API for efficient props construction

Reviewed By: javache

Differential Revision: D37050961

fbshipit-source-id: 170a09c08d7406b6aac51d7e78cf295a72fdcf91
2022-06-15 23:37:34 -07:00
Joshua Gross 9f8c45deb7 New Props parsing infrastructure for perf improvements: visitor pattern vs random-map-access pattern (YogaLayoutableShadowNode / YGStyle)
Summary:
See commentary at top of stack.

Changelog: [Added][Fabric] New API for efficient props construction

Reviewed By: javache

Differential Revision: D37050376

fbshipit-source-id: 2bea35a6d604704cf430bd3b2914988227d1abf8
2022-06-15 23:37:34 -07:00
Joshua Gross 47280de85e New Props parsing infrastructure for perf improvements: visitor pattern vs random-map-access pattern (ViewProps, minus YogaLayoutableShadowNode)
Summary:
Perf numbers for this stack are given in terms of before-stack and after-stack, but the changes are split up for ease of review, and also to show that this migration CAN happen per-component and is 100% opt-in. Most existing C++ components do not /need/ to change at all.

# Problem Statement

During certain renders (select critical scenarios in specific products), UIManagerBinding::createNode time takes over 50% of JS thread CPU time. This could be higher or lower depending on the specific product and interaction, but overall createNode takes a lot of CPU time. The question is: can we improve this? What is the minimal overhead needed?

The vast, vast majority of time is taken up by prop parsing (specifically, converting JS values across the JSI into concrete values on the C++ props structs). Other methods like appendChild, etc, do not take up a significant amount of time; so we conclude that createNode is special, and the JSI itself, or calling into C++, is not the problem. Props parsing is the perf problem.

Can we improve it? (Spoiler: yes)

# How does props parsing work today?

Today, props parsing works as follows:

1. The ConcreteComponentDescriptor will construct a RawPropsParser (one per component /type/, per application: so one for View, one for Image, one for Text... etc)
2. Once per component type per application, ConcreteComponentDescriptor will call "prepare" on the RawPropsParser with an empty, default-constructed ConcreteProps struct. This ConcreteProps struct will cause RawProps.at(field) for every single field.
3. Based on the RawProps::at calls in part 2, RawPropsParser constructs a Map from props string names (width, height, position, etc) to a position within a "value index" array.
4. The above is what happens before any actual props are parsed; and the RawPropsParser is now ready to parse actual Props.
5. When props are actually being parsed from a JSI dictionary, we now have two phases:
  1. The RawPropsParser `preparse`s the RawProps, by iterating over the JSI map and filling in two additional data structures: a linear list of RawValues, and a mapping from the ValueIndex array (`keyIndexToValueIndex_`; see step 3) to a value's position in the values list (`value_` in RawPropsParser/RawProps);
  2. The ConcretePropT constructor is called, which is the same as in step 2/3, which calls `fieldValue = rawProps.at("fieldName")` repeatedly.
  3. For each `at` call, the RawProps will look up a prop name in the Map constructed in step 3, and either return an empty value, or map the key name to the `keyIndexToValueIndex_` array, which maps to a value in `values_`, which is then returned and further parsed.

So, a few things that become clear with the current architecture:

1. Complexity is a property of the number of /possible/ props that /can/ be parsed, not what is actually used in product code. This violates the "only pay for what you use" principal. If you have `<View opacity={0.5} />`, the ViewProps constructor will request ~170 properties, not 1!
2. There's a lot of pre-parsing which isn't free
3. The levels of indirection aren't free, and make cache misses more likely and pipelining is more challenging
4. The levels of indirection also require more memory - minor, but not free

# How can we improve it?

The goal is to improve props parsing with minimal or zero impact on backwards-compability. We should be able to migrate over components when it's clear there's a performance issue, without requiring everything gets migrated over at once. This both (1) helps us prove out the new architecture, (2) derisks the project, (3) gives us time, internally and externally, to perfect the APIs and gradually migrate everything over before deleting the old infrastructure code entirely.

Thus, the goal is to do something that introduces a zero-cost abstraction. This isn't entirely possible in practice, and in fact this method slightly regresses components that do not use the new architecture /at all/, while dramatically improving migrated components and causing the impact of the /old/ architecture to be minimal.

# Solution

1. We still keep the existing system in place entirely.
2. After Props are constructed (see ConcreteComponentDescriptor changes) we iterate over all the /values/ set from JS, and call PropsT::setProp. Incidentally, this allows us to easily reuse the same prop for multiple values for "free", which was expensive in the old system.
3. It's worth noting that this makes a Props struct "less immutable" than it was before, and essentially now we have a "builder pattern" for Props. (If we really wanted to, we could still require a single constructor for Props, and then actually use an intermediate PropsBuilder to accumulate values - but I don't think this overhead would be worth for the conceptual "immutability" win, and instead a "Construct/Set/Seal" model works fine, and we still have all the same guarantees of immutability after the parsing phase)

# Implementation Details
# How to properly construct a single Prop value

Minor detail: parsing a single prop is a 3-step process. We imagine two scenarios: (1) Creating a new ShadowNode/Props A from nothing/void, so the previous Props value is just the default constructor. (2) Cloning a ShadowNode A->B and therefore Props A must be copied to Props B before parsing.

We will denote this as a clone from A->B, where A may or may not be a previous node or a default-constructed Props node; and imagine in particular that we're setting the "opacity" value for PropsB.

We must first (1) copy a value over from the previous version of the Props struct, so B.opacity = A.opacity; (2) Determine if opacity has been set from JS. If so, and there is a value, B.opacity = parse(JSValue). (3) If JS has passed in a value for the prop, BUT the value is `null`, it means that JS is resetting or deleting the prop, so we must set it BACK to the default. In this case we set PropsB.opacity = DefaultConstructedProps.opacity.

We must take care in general to ensure that the correct behavior is achieved here, which should help to explain some of the code below.

## String comparisons vs hash comparisons

In the previous system, a RawPropsKey is three `const char*` strings, concatenated together repeatedly /at runtime/. In practice, the ONLY reason we have the prefix, name, suffix Key structure is for the templated prop parsing in ViewProps and YogaStyableProps - that's it. It's not used anywhere else. Further, the key {"margin", "Left", "Width"} is identical to the key {"marginLeftWidth", null, null} and we don't do anything fancy with matching prefixes before comparing the whole string, or similar. Before comparison, keys are concatenated into a single string and then we use `strcmp`. The performance of this isn't terrible, but it's nonzero overhead.

I think we can do better and it's sufficient to compare hashed string values; even better, we can construct most of these /at compile time/ using constexpr, and using `switch` statements guarantee no hash collisions within a single Props struct (it's possible there's a collision between Props.cpp and ViewProps.cpp, for example, since they're different switch statements). We may eventually want to be more robust against has collisions; I personally don't find the risk to be too great, hash collisions with these keys are exceedingly unlikely (or maybe I just like to live dangerously). Thus, at runtime, each setProp requires computing a single hash for the value coming from JS, and then int comparisons with a bunch of pre-compiled values.

If we want to be really paranoid, we could be robust to hash collisions by doing `switch COMPILED_HASH("opacity"): if (strcmp(strFromJs, "opacity") == 0)`. I'm happy to do this if there's enough concern.

## Macros

Yuck! I'm using lots of C preprocessor macros. In general I found this way, way easier in reducing code and (essentially) doing codegen for me vs templated code for the switch cases and hashing prop names at compile-time. Maybe there's a better way.

Changelog: [Added][Fabric] New API for efficient props construction

Reviewed By: javache

Differential Revision: D37050215

fbshipit-source-id: d2dcd351a93b9715cfeb5197eb0d6f9194ec6eb9
2022-06-15 23:37:34 -07:00
Dustin Shahidehpour dbe6fab063 Switch module codegen to use yarn_workspace_binary. (#34015)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/34015

I noticed this was a very slow part of my build because each instance of the binary would run its own yarn install. Instead use the yarn_workspace approach to share a single yarn setup.
Changelog: [Internal]

Reviewed By: IanChilds

Differential Revision: D37178005

fbshipit-source-id: cba51e168c5a2f2ee6468acb8c144db4ad352d95
2022-06-15 13:12:14 -07:00