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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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