Compare commits

...
Author SHA1 Message Date
Distiller d71ba2da34 [0.72.0-rc.3] Bump version numbers 2023-05-11 14:36:11 +00:00
Lorenzo Sciandra 9c18ad85c7 revert type bump in template 2023-05-11 11:21:17 +01:00
Riccardo Cipolleschi e1b175f137 bumped packages versions
#publish-packages-to-npm
2023-05-11 10:02:56 +01:00
Riccardo Cipolleschi 9cf1918d0d [LOCAL] bump metro to 0.76.4 and CLI to 11.2.3 2023-05-11 10:00:38 +01:00
Samuel Susla ca17733e2f Update scheduler package (#37295)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37295

changelog: [internal]

Update scheduler package. It will use the native scheduler if available.

Reviewed By: cortinico, cipolleschi

Differential Revision: D45634886

fbshipit-source-id: f169a1e9ab12399a0e0d7bc5e9a19c27944db1d0
2023-05-11 09:53:50 +01:00
Lorenzo Sciandra 0471f9b70f bumped packages versions
#publish-packages-to-npm
2023-05-10 17:38:08 +01:00
Lorenzo Sciandra 935d90023e [LOCAL] bump metro to 0.76.3 and CLI to 11.2.2 2023-05-10 17:37:42 +01:00
Lorenzo Sciandra eca45c28c3 bumped packages versions
#publish-packages-to-npm
2023-05-10 15:59:38 +01:00
Lorenzo Sciandra ab3fe91e9e empty commit to trigger a new patch for metro-config 2023-05-10 15:59:26 +01:00
Douglas Lowder e217b7f513 Read Maven group from GROUP property (#37204)
Summary:
The [React Native TV repo](https://github.com/react-native-tvos/react-native-tvos) shares most of the same Android code as the core repo. Beginning in 0.71, it needs to also publish Android Maven artifacts for the `react-android` and `hermes-android` libraries.

In order to avoid conflicts, it needs to publish the artifacts to a different group name. However, `react-native-gradle-plugin` uses a hardcoded group name (`com.facebook.react`).

Solution: read the group name from the existing `GROUP` property in `ReactAndroid/gradle.properties`.

## Changelog:

[Android] [Fixed] - read GROUP name in gradle-plugin dependency code

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

Test Plan:
- Android unit tests have been added for the new code and new method in `DependencyUtils.kt`.
- Existing tests should pass
- The new code defaults to the correct group (`com.facebook.react`) so no functional change is expected in the core repo.

Reviewed By: luluwu2032

Differential Revision: D45576700

Pulled By: cortinico

fbshipit-source-id: 6297ab515b4bdbb17024989c7d3035b0a2ded0ae

# Conflicts:
#	packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt
2023-05-10 15:53:35 +01:00
Max Metral 2bba1e325b Fix Flipper by moving FB_SONARKIT_ENABLED to RCTAppDelegate (#37240)
Summary:
An out-of-the-box react-native init project no longer enables Flipper properly as of 0.72.0-rc1.

## Changelog:

[IOS] [FIXED] Fix Flipper by moving podfile modification of preprocessor def `FB_SONARKIT_ENABLED` from React-Core to React-RCTAppDelegate where it is now used.

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

Test Plan: Generated an app and verified Flipper cannot see the app. Made the modification and generated another app and verified Flipper now sees it and can enable plugins. Verified that runtime (non-test) use of FB_SONARKIT_ENABLED is limited to Libraries/AppDelegate in this project.

Reviewed By: dmytrorykun

Differential Revision: D45563282

Pulled By: cipolleschi

fbshipit-source-id: d760c5ae123cc7c967b19c6c626801d6db28d052
2023-05-10 15:52:46 +01:00
Riccardo Cipolleschi 1ea2c9bad9 Revert ENABLE_HERMES_PROFILER flag in cocoapods (#37228)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37228

As discussed offline, the current approach for the Hermes profiler is not the right one.

I'm partially reverting [the commit](https://github.com/facebook/react-native/commit/dce9d8d5de381fe53760ddda0d6cbbdfb5be00e4) which introduced it.

The commit did also a bit of refactoring to improve the quality of the cocoapods scripts we would like to keep.

## Changelog:
[iOS][Removed] - Remove support of Hermes profiler as that's not the right approach.

Reviewed By: cortinico

Differential Revision: D45527507

fbshipit-source-id: acea5f8b610d8b67ee7a6a91993bb8e4592d093f
2023-05-10 15:52:39 +01:00
Samuel Susla 166cc09d75 Cancel image download when ImageRequest changes (#37223)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37223

changelog: [internal]

Cancel image download when image source changes or <ImageView /> is recycled.

bypass-github-export-checks

Reviewed By: javache

Differential Revision: D45524686

fbshipit-source-id: 515a153ddb214fdce51ff29243b68c5fd5479c64
2023-05-10 15:52:33 +01:00
Samuel Susla 9d5ca3647a Delete ImageRequest::~ImageRequest (#37222)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37222

changelog: [internal]

User defined destructor does not make sense here. ImageRequest is owned by ImageState, which is owned by ImageShadowNode. ImageShadowNode requires garbage collection from the runtime to be destroyed. Calling cancel in dtor is not deterministic and that is undesired.

bypass-github-export-checks

Reviewed By: javache

Differential Revision: D45524705

fbshipit-source-id: 410def2100f479b68682620b2c43071fdfb86715
2023-05-10 15:52:26 +01:00
Samuel Susla 8d6d34644a Move cancelRequest_ in move ctor in ImageRequest (#37221)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37221

changelog: [internal]

Add missing cancelRequest_ std::move.

bypass-github-export-checks

Reviewed By: javache, cortinico

Differential Revision: D45524704

fbshipit-source-id: 1dd0d627549dab353872654d78f7b59d1b2d7174
2023-05-10 15:52:17 +01:00
Distiller 9cb7b44d4c [0.72.0-rc.2] Bump version numbers 2023-05-04 12:16:25 +00:00
Nicola Corti 5d7c34c3c4 [LOCAL] Do not run Buck OSS on release branches (#37251) 2023-05-04 12:40:52 +01:00
Lorenzo Sciandra 138cb9187e [LOCAL] fix version of metro config 2023-05-04 12:17:40 +01:00
Lorenzo Sciandra d9d7286e8a [LOCAL] bump CLI to 11.2.1 2023-05-04 10:32:41 +01:00
Lorenzo Sciandra a0cb168aa0 Merge pull request #37230 from facebook/cipolleschi/fix_reading_hermes_tag 2023-05-03 16:05:59 +01:00
Lorenzo Sciandra 840db2122a Merge pull request #37203 from lunaleaps/revert-insets 2023-05-03 16:05:47 +01:00
Riccardo Cipolleschi 49d2009add Pass the file that needs to be read 2023-05-03 16:01:27 +01:00
Alex Hunt 738e01430a Set dev menu title to "React Native Dev Menu", add JS executor description (#37195)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37195

Updates the Dev Menu header on Android.

- Small alignment related to D44872456.
- Add subheading label showing current JS executor description (matching iOS) (note: on Android this is unformatted (but informative), e.g. `JSIExecutor+HermesRuntime`).

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D45142924

fbshipit-source-id: 5c95fc85e6d3b6879287440f76165b02957283e5
2023-05-03 15:08:58 +01:00
Dmitry Rykun 8de71e58b6 Make sure that hermes-engine is updated with cocoapods. (#37148)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37148

This should fix https://github.com/facebook/react-native/issue/36945, which is also causing annoyance when doing the releases

## Changelog:
[iOS][Changed] - Use contents of sdks/.hermesversion to let cocoapods recognize Hermes updates.

Reviewed By: cipolleschi

Differential Revision: D45394241

fbshipit-source-id: 972fbee8f954b90f7087bb232f922761c1639e06
2023-05-03 15:08:48 +01:00
Nicola Corti 34d7d016b4 Remove unnecessary files in RN-Tester (#37152)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37152

Those files are unncessary and can be removed from RNTester.
* Proguard file is empty
* Signing config is unnecessary and we can use the debug one also for release.

Changelog:
[Internal] [Changed] - Remove unnecessary files in RN-Tester

Reviewed By: hoxyq

Differential Revision: D45399388

fbshipit-source-id: fd1c6cccaef668e688a699e31045bdc8103ea98e
2023-05-03 15:08:41 +01:00
Nicola Corti bbecf516c0 Re-enable newArch on RN-Tester
Summary:
I accidentally turned off New Architecture on RN-Tester while shipping the Fabric Interop. This reverts it.

Changelog:
[Internal] [Changed] - Re-enable newArch on RN-Tester

Reviewed By: cipolleschi

Differential Revision: D45398914

fbshipit-source-id: 2c36f3d0440f147189de644821e1704c00353bac
2023-05-03 15:08:34 +01:00
Nicola Corti 1c09228161 Do not explicitely depend on androidx.swiperefreshlayout:swiperefreshlayout (#37139)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37139

This dependency is unnecessary. React Native already exposes a `api` dependency on
`androidx.swiperefreshlayout:swiperefreshlayout` so every consumer will also get it.

This is just another line in the template we can effectively remove.

Changelog:
[Android] [Changed] - Do not explicitely depend on androidx.swiperefreshlayout:swiperefreshlayout

Reviewed By: cipolleschi

Differential Revision: D45390819

fbshipit-source-id: cce34c6a09100d36ee5eb003bb30323f64f0bb9c
2023-05-03 15:08:27 +01:00
Nicola Corti fed80ad8c3 Add support for Events on the Fabric Interop Layer (#37059)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37059

This diff introduces InteropEventEmitter, a re-implementation of RCTEventEmitter that works with Fabric and allows to support events on the Fabric Interop for Android.
Thanks to this, users can keep on calling `getJSModule(RCTEventEmitter.class).receiveEvent(...)` in their legacy ViewManagers and they will be using the EventDispatcher
under the hood to dispatch events.

The logic is enabled only if the `unstable_useFabricInterop` flag is turned on. I've turned this on for the template setup and for RN Tester.

On top of this, this diff takes care also of event name "normalization".
On Fabric, all the events needs to be registered with a "top" prefix. With this diff, we'll be adding the "top" prefix at registration time, if the user hasn't added them.
This allows to use legacy ViewManagers on Fabric without having to ask users to change their event name.

Changelog:
[Android] [Added] - Add support for Events on the Fabric Interop Layer

Reviewed By: mdvacca

Differential Revision: D45144246

fbshipit-source-id: 63d4060153907c05977c976379b90574d1f69866
2023-05-03 15:07:02 +01:00
Tim Yung 2fcda359ba RN: Upgrade to deprecated-react-native-prop-types@4.1.0
Summary:
Upgrades React Native to `deprecated-react-native-prop-types@4.1.0`, which includes many of the new prop types in React Native v0.72.

See: https://github.com/facebook/react-native-deprecated-modules/blob/main/deprecated-react-native-prop-types/CHANGELOG.md

Changelog:
[General][Changed] - Upgrade to deprecated-react-native-prop-types@4.1.0

Reviewed By: rickhanlonii

Differential Revision: D45155955

fbshipit-source-id: 36e715c2338b667755bd1e522b7d5a2611103779
2023-05-03 15:06:55 +01:00
Alex Hunt d7af544bb9 Rename "Debug Menu" title to "Dev Menu" on iOS (#36981)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36981

We are (following a quick internal RFC) looking to standardise the term "[in-app] [Developer|Debug] menu" to "Dev Menu" in the React Native Debugging docs (and all docs references). (Indeed, the prevalent existing use in docs was already "Developer menu".) This PR aligns naming in the `RCTDevMenu` component on iOS.

See also https://github.com/facebook/react-native-website/pull/3692.

Changelog:
[iOS][Changed] - Rename "Debug Menu" title to "Dev Menu"

Reviewed By: christophpurrer

Differential Revision: D44872456

fbshipit-source-id: c222bb2c551a4f434a1dc0efbb8d4f75c785aa11
2023-05-03 15:06:19 +01:00
Lorenzo Sciandra dd89bfb254 [LOCAL] add missing types requirement 2023-05-03 15:04:51 +01:00
Nick Gerleman 414c015da3 Bump @tsconfig/react-native to 3.0.0 (#36957)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36957

Fixes https://github.com/facebook/react-native/issues/36830

This bumps the version of tsconfig/react-native to inform TypeScript of more libraries provided by Hermes/React Native. See https://github.com/tsconfig/bases/commit/eee5f19ce8c6a9a8d8baed5ce42588b95262b1a8.

I did the search off of current Hermes/RN main branch, but I think the new config should be valid as far back as 0.71. It doesn't make sense to change the new app template for an old version though, so instead I think we should include this new version in 0.72.

Changelog:
[General][Changed] - Bump tsconfig/react-native to 3.0.0

Reviewed By: cortinico

Differential Revision: D45085932

fbshipit-source-id: 448f1103ef13f76fa95884f790a3cccd9ff75b2f

# Conflicts:
#	packages/react-native/template/package.json
2023-05-03 15:03:30 +01:00
Dmitry Rykun c1c8a30cc8 Do not send extra onChangeText even wnen instantianting multiline TextView (#36930)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36930

This diff fixes https://github.com/facebook/react-native/issues/36494

Now this code matches its [Fabric counterpart](https://github.com/facebook/react-native/commit/7b4889937ceb0eccdbb62a610b58525c29928be7).

There is also one extra check that `_lastStringStateWasUpdatedWith != nil`. With that in place we don't send extra `onChangeText` event when `attributedText` is assigned for the first time on TextView construction.

Changelog: [IOS][Fixed] - Do not send extra onChangeText even wnen instantianting multiline TextView

Reviewed By: sammy-SC

Differential Revision: D45049135

fbshipit-source-id: 62fa281308b9d2e0a807d024f08d8a214bd99b5e
2023-05-03 15:02:11 +01:00
Nick Gerleman bab46dd321 Export EmitterSubscription TypeScript Type (#36632)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36632

Discovered when bumping the RN documentation to typecheck against 0.72, https://github.com/facebook/react-native/pull/36109 removed the `EmitterSubscription` type which should be kept public.

Changelog:
[General][Fixed] -  Export EmitterSubscription TypeScript Type

Reviewed By: cortinico

Differential Revision: D44375081

fbshipit-source-id: c8dbd5694d3a728a0a2091210894d27c9d84a012
2023-05-03 15:02:02 +01:00
Janic Duplessis 37abba0193 Add fabric support for maintainVisibleContentPosition on Android (#35994)
Summary:
Implement a few missing bits for `maintainVisibleContentPosition` to work with fabric. The main thing needed is to add 2 fabric renderer listener methods to allow to hook into specific parts of the rendering process. We need some code to execute before view updates are executed and after view updates are executed. The current methods that are exposed do not work for this case. `willDispatchViewUpdates` is called from JS thread, and there doesn't seem to be a way to add UI blocks that will be executed at the right time like we do in paper. `didDispatchMountItems` is called for every frame which we don't want and will cause lots of overhead.

After that we simply need to call the right methods in the new renderer listener methods.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[ANDROID] [ADDED] - Add fabric support for maintainVisibleContentPosition on Android

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->

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

Test Plan: Tested in RN tester maintainVisibleContentPosition example on Android with fabric enabled.

Reviewed By: cipolleschi

Differential Revision: D44131763

Pulled By: cortinico

fbshipit-source-id: 32c0b5867d460537b18a70d472fd58052da6cf80
2023-05-03 15:01:44 +01:00
Luna Wei 08fc618b77 Revert "feat: Add Fabric implementation of inset logical properties (#35692)"
This reverts commit 9669c10afc.
2023-05-02 14:22:55 -07:00
Alex HuntandDeepak Jacob c068efcdae [0.72] Bump Metro to 0.76.2, cherry pick Metro config updates (#36976)
Co-authored-by: Deepak Jacob <deepakjacob@meta.com>
2023-04-21 10:50:47 +01:00
Lorenzo Sciandra 51de9e1ad6 [LOCAL] update podlock post release to fix CI 2023-04-11 12:14:51 +01:00
Distiller 30b5de04d6 [0.72.0-rc.1] Bump version numbers 2023-04-05 12:16:48 +00:00
Nicola Corti f3b71f4843 Fix a crash new app template when createRootView is invoked with null bundle (#36796)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36796

As the title says, this fixes a instacrash on template when `createRootView` is invoked with
a bundle being null. The crash was happening as the parameter, despite being not used, is
specified as `Bundle` and is not nullable. When the Java caller passes `null`, the app crashes.

Changelog:
[Android] [Fixed] - Fix a crash new app template when `createRootView` is invoked with null bundle

Reviewed By: cipolleschi

Differential Revision: D44668305

fbshipit-source-id: 1150ddac26f19765e7340878c8850d8462c6f3fd
2023-04-04 18:36:28 +01:00
Lorenzo Sciandra c92bb3c526 [LOCAL] bump CLI to 11.1.1 2023-04-04 11:50:51 +01:00
Samuel Susla 921bbb6cf1 Correct offset when drawing text to TextStorage coordinate system. (#36771)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36771

Changelog: [internal]

Previously, when `NSTextStorage` was cached, we were not accounting for case where text which was aligned to centre or left, was used to size its container.
The result was that it was painted outside of its container, therefore invisible. To fix this, we adjust the offset to make sure text is painted correctly.

This bug only happens if:
- Text is not aligned to left in right to left writing system.
- The canvas where text is drawn is not stretched to full width of its parent.
- The offset needs to be large enough for this to matter, otherwise the text is just slightly off.
- Because of the caching mechanism, it had to be a piece of text that was rendered before. Otherwise it would work.

This complexity is worth the trouble to avoid invalidation of layout inside NSTextContainer, which is expensive.

Reviewed By: cipolleschi

Differential Revision: D44624085

fbshipit-source-id: 1bb8ef88933a49b478a2606dba6bf16b4e728b2b
2023-04-03 15:19:06 +01:00
Samuel Susla 6d6b6a8345 Only create NSAttributedString if NSTextStorage is nil (#36773)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36773

Changelog: [internal]

Do not construct `NSAttributedString` if `NSTextStorage` exists. Creating `NSAttributedString` is expensive and it isn't needed to measure text if `NSTextStorage` `exists`

Reviewed By: cipolleschi

Differential Revision: D44620292

fbshipit-source-id: 0827c514e40fcbd9626d2b7d7b6d28a3332d9aa1
2023-04-03 15:19:06 +01:00
Samuel Susla 614e4109bf Extract NSTextStorage measure into a helper method (#36772)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36772

changelog: [internal]

Move NSTextStorage into a private method.

Reviewed By: cipolleschi

Differential Revision: D44620262

fbshipit-source-id: 4855879f3c3a09b2f352ab84c906c7bd106aebda
2023-04-03 15:19:06 +01:00
Riccardo Cipolleschi d3c94b42f4 Fix Cocoapods for Xcode 14.3.0 (#36759)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36759

On Thursday the 30th, Apple Released Xcode 14.3.0.
This Version of Xcode enforce some version checks for which React-Codegen, which supported iOS 11 as minimum supported version, could not be build anymore.

This change ensue that React-Codegen is always aligned to the min version supported by React Native.
Plus, it moves CircleCI's Xcode to 14.3.0, to keep this problem in Check.

While working on this, I figured that, with the monorepo, Ruby tests stopped working because they were in the wrong folder: I moved them in the right one.

## Changelog:
[iOS][Fixed] - Make React Native build with Xcode 14.3.0 and fix tests

Reviewed By: blakef

Differential Revision: D44605617

fbshipit-source-id: 3ec1f5b36858ef07d9f713d74eb411a1edcccd45
2023-04-03 15:19:06 +01:00
Lorenzo Sciandra e795b534aa fix(metro-config): fix and realign the situation for metro config for 0.72 (#36746) 2023-03-31 17:44:20 +01:00
Ruslan Lesiutin 68cd44be07 Merge pull request #36573 from hoxyq/hoxyq/cherry-pick-ci-scripts-changes-to-0.72-stable
RN [refactor]: bump and realign package versions by running a single …
2023-03-31 15:53:15 +01:00
Ruslan Lesiutin a469927c16 RN [refactor]: bump and realign package versions by running a single script
Summary:
Changelog: [Internal]

Okay, so before the monorepo migration we had to use two scripts separately:
1. Bumping every package with `npm run bump-all-updated-packages`
2. Aligning other packages versions with `npm run align-package-versions`

The reason for it is that *before the monorepo* in a release branch cutoff process we had a step, which was removing `workspaces` keyword from `react-native` package. Without this keyword all new versions of packages will be resolved from npm (where they will be not available yet, because we have to publish them prior to it)

This is not the case for our current setup, and we can actually bump packages versions and they will be resolved as a workspaces successfully

Differential Revision: D44261057

fbshipit-source-id: 6095209c8183f6d84e2697fda2e9a21f8a57f73e
2023-03-31 13:44:43 +01:00
Alex Hunt c5f18de6a2 Update template metro.config.js, remove transitive metro dep from main package (#36723)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36723

Changelog: [Internal]

Reviewed By: hoxyq

Differential Revision: D44542544

fbshipit-source-id: 70807edc8a183c28e1f0018a5426f4f2e29580a0
2023-03-31 11:34:47 +01:00
Nicola Corti 1199e4764d Add examples of Direct Manipulation in Fabric Intrerop (#36724)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36724

Similarly to iOS, this adds some examples of direct manipulation on Android using
all the various methods.

Changelog:
[Internal] [Changed] - Add examples of Direct Manipulation in Fabric Intrerop

Reviewed By: cipolleschi

Differential Revision: D44541437

fbshipit-source-id: b6e10ac0a815f41ff3c980236b7d8c6937e92065
2023-03-31 11:33:01 +01:00
Nicola Corti cb30323f04 Add example for dispatchViewManagerCommand on Fabric Interop (#36725)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36725

This diff adds an example of using `dispatchViewManagerCommand` for the Fabric Intreop on Android.

Changelog:
[Android] [Added] - Add example for dispatchViewManagerCommand on Fabric Interop

Reviewed By: cipolleschi

Differential Revision: D44540951

fbshipit-source-id: 85bc65ad0eb3a951fbb37d61ca26532ec3cc53b7
2023-03-31 11:32:52 +01:00
Nicola Corti 5299c60bdc Add Fabric Interop event example (#36692)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36692

Similar to the iOS counterpart,
this changes adds an example to RNTester to verify that the Interop Layer can process bubbling events in Fabric as it used to do in Paper.

Changelog:
[Internal] [Changed] - Add Fabric Interop event example

Reviewed By: cipolleschi

Differential Revision: D44467555

fbshipit-source-id: 1f1af27583c402641c549bc2926a64469dcd7b3f
2023-03-31 11:32:09 +01:00
Nicola Corti 341cda45ee Add Fabric Interop constants example (#36693)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36693

Similar to #36417, this changes adds an example to RNTester to verify that the Interop Layer can process constants in Fabric as it used to do in Paper for Android.

Changelog:
[Android] [Added] - Add Fabric Interop constants example

Reviewed By: cipolleschi

Differential Revision: D44466391

fbshipit-source-id: 74e654319b93e60b415297dcdddc98eb100913df
2023-03-31 11:31:46 +01:00
Alex Hunt 0026f73360 Remove 'import' from default Package Exports conditions (#955)
Summary:
X-link: https://github.com/facebook/metro/pull/955

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

Changelog:
[General][Changed] - Default condition set for experimental Package Exports is now `['require', 'react-native']`

The [Exports RFC](https://github.com/react-native-community/discussions-and-proposals/blob/main/proposals/0534-metro-package-exports-support.md) had assumed that supporting the `"import"` condition was a syntax-only difference, given we are not in a Node.js environment — and so was worthwhile to support for maximal ecosystem compatibility.

{F915841105}

This assumption is similar to [`--moduleResolution bundler` in TypeScript 5.0](https://github.com/microsoft/TypeScript/pull/51669):

> bundlers and runtimes that include a range of Node-like resolution features and ESM syntax, but do not enforce the strict resolution rules that accompany ES modules in Node or in the browser
> -- https://github.com/microsoft/TypeScript/pull/51669#issue-1467004047

However, robhogan has rightly pointed out that **we should not do this!**

- ESM (once transpiled) is **not** simply a stricter subset of in-scope features supported by CJS. For example, it supports top-level async, which would be breaking at runtime.
- We recently made the same change for our Jest environment:
    - https://github.com/facebook/react-native/commit/681d7f8113d2b5e9d6966255ee6c72b50a7d488a

As such, we are erring on the side of correctness and supporting only `['require', 'react-native']` in our defaults. At runtime, all code run by React Native is anticipated to be CommonJS. `"exports"` will instead allow React Native to correctly select the CommonJS versions of modules from all npm packages.

Metro changelog: [Experimental] Package Exports `unstable_conditionNames` now defaults to `['require']`

Reviewed By: robhogan

Differential Revision: D44303559

fbshipit-source-id: 0077e547e7775e53d1e4e9c3a9d01347f4fb7d4a
2023-03-31 11:28:56 +01:00
Lorenzo Sciandra 392a843494 [LOCAL] fix e2e local testing script post metro-config 2023-03-30 17:50:42 +01:00
Lorenzo Sciandra 8beed6ad08 [LOCAL] need to be in the rn-tester folder the whole time when testing rn-tester 2023-03-30 17:02:02 +01:00
Riccardo Cipolleschi a9ec217117 Fix RNTester in main (#36686)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36686

After the recent changes of Metro and Metro-Config, we need to update the path used to load the bundle in RNTester

## Changelog:
[General][Fixed] - Use the right path to load RNTester bundle

Reviewed By: cortinico

Differential Revision: D44465418

fbshipit-source-id: 96170194579792f9a5d8a141328d43e45a4db973
2023-03-30 16:56:24 +01:00
Lorenzo Sciandra d0699dc428 [LOCAL] bump CLI to 11.0.1 2023-03-30 16:47:26 +01:00
Lorenzo Sciandra 73837a72f6 [LOCAL] bump js-polyfills and virtualized-lists 2023-03-30 13:54:18 +01:00
Lorenzo Sciandra 8a493af0b9 bumped packages versions
#publish-packages-to-npm
2023-03-30 13:49:52 +01:00
Nicola Corti 7b2cff831e Re-enable Fabric in the default app template/RN-Tester (#36717)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36717

After D43711737 landed, it turns out that Fabric is always disabled for both
RN-Tester and new app from template (so for 0.72 also RC0).
The reason is that a new method `createRootView(Bundle)` was introduced inside
`ReactActivityDelegate`. Both RN Tester and the template were using the
old `createRootView()` method which is not called anymore at this stage
(should potentially be deprecated?).

This diff fixes it by overriding both method inside `DefaultReactActivityDelegate`
so that both methods are setting the Fabric renderer.

Changelog:
[Android] [Fixed] - Re-enable Fabric in the default app template/RN-Tester

Reviewed By: cipolleschi

Differential Revision: D44536222

fbshipit-source-id: d22a0c522f011a8fe4d27b5d8f2fcf5dd13c3058
2023-03-30 13:49:30 +01:00
Riccardo Cipolleschi 6070b58a96 Add Examples for Direct Manipulation in the Interop Layer (#36610)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36610

This change add to RNTester examples of a legacy Native Component, loaded in the New Architecture through the Interop Layer, that uses the APIs described in the [Direct Manipulation](https://reactnative.dev/docs/direct-manipulation) sectioon of the website.

[iOS][Added] - Added examples of direct manipulation

Reviewed By: sammy-SC

Differential Revision: D43978674

fbshipit-source-id: 1cbc56f28034f84f309166e3e392ad97a8164e64
2023-03-30 11:11:06 +01:00
Riccardo Cipolleschi 3e079f0802 Make UIManager.dispatchViewManagerCommand work in Fabric through Interop Layer (#36578)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36578

This change brings to the Fabric Interop Layer the possibility to directly call native methods on the View Manager, something that was not possible before and that we can use to simplify the migration to the New Architecture.

[iOS][Added] - Native Components can now call native methods in Fabric when they are loaded through the Interop Layer

Reviewed By: sammy-SC

Differential Revision: D43945278

fbshipit-source-id: fe67ac85a5d0db3747105f56700d1dbba7ada5f1
2023-03-30 11:10:18 +01:00
fortmarek 18137348ee Use packaged react-native in test-e2e-local script (#36703)
Summary:
The current `test-e2e-local` script had two bugs:
- On [this](https://github.com/facebook/react-native/blob/c1c22ebacc4097ce56f19385161ebb23ee1624b3/scripts/test-e2e-local.js#L219) line we were initializing a new RN project with the packed `react-native` created [here](https://github.com/facebook/react-native/blob/c1c22ebacc4097ce56f19385161ebb23ee1624b3/scripts/test-e2e-local.js#L211)
- We were updating the local RN version after running `npm pack` [here](https://github.com/facebook/react-native/blob/c1c22ebacc4097ce56f19385161ebb23ee1624b3/scripts/test-e2e-local.js#L214). This meant that the version inside the packaged `react-native-xyz.tgz` was not updated since we ran `pack` before updating it. This was fine since the `init` command was using the local `react-native` repository instead of the packed version.

## Changelog:

[INTERNAL] [FIXED] - Use packaged react-native in test-e2e-local script
<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[INTERNAL] [FIXED] - Use packaged react-native in test-e2e-local script

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->

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

Test Plan:
- Run `yarn test-e2e-local -t RNTestProject -p Android`. The command should succeed.

I am not completely sure how to double check that we are using the packed version. Locally, I have a `fsmonitor--daemon.ipc` in my `react-native/.git` that can't be copied. The `.git` folder would be copied only when `cli.js init` was called with the whole repository  – which is how I found out about the issue in the first place.

Reviewed By: hoxyq

Differential Revision: D44504599

Pulled By: cipolleschi

fbshipit-source-id: e57e2858bab46d4f978eed3cbaf3e504138594b8
2023-03-30 10:52:54 +01:00
Nicola Corti 14794a9946 Fix the setup to allow the build-from-source on host projects (#36702)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36702

With the monorepo changes we broke the build from source for users.
This fixes it so that folks can just follow the guide:
https://reactnative.dev/contributing/how-to-build-from-source

Changelog:
[Android] [Fixed] - Fix the setup to allow the build-from-source on host projects

Reviewed By: cipolleschi

Differential Revision: D44502428

fbshipit-source-id: 3ad8fb114f5e2f7ffdf6fffa617ceaa45334f5f3
2023-03-29 17:39:30 +01:00
Nick Gerleman eae08663fe Mimimize EditText Spans 9/9: Remove addSpansForMeasurement() (#36575)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36575

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

D23670779 addedd a previous mechanism to add spans for measurement caching, like we needed to do as part of this change. It is called in more specific cases (e.g. when there is a text hint but no text), but it edits the live EditText spannable instead of the cache copy, and does not handle nested text at all.

We are already adding spans back to the input after this, behind everything else, and can replace it with the code we have been adding.

Changelog:
[Android][Fixed] - Mimimize EditText Spans 9/9: Remove `addSpansForMeasurement()`

Reviewed By: javache

Differential Revision: D44298159

fbshipit-source-id: 1af44a39de7550b7e66e45db9ebc3523ae9ff002
2023-03-29 15:48:03 +01:00
Nick Gerleman 1ebe10a4e5 Minimize EditText Spans 8/9: CustomStyleSpan (#36577)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36577

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This change allows us to strip CustomStyleSpan. We already set all but `fontVariant` on the underlying EditText, so we just need to route that through as well.

Note that because this span is non-parcelable, it is seemingly not subject to the buggy behavior on Samsung devices of infinitely cloning the spans, but non-parcelable spans have different issues on the devices (they disappear), so moving `fontVariant` to the top-level makes sense here.

Changelog:
[Android][Fixed] - Minimize EditText Spans 8/N: CustomStyleSpan

Reviewed By: javache

Differential Revision: D44297384

fbshipit-source-id: ed4c000e961dd456a2a8f4397e27c23a87defb6e
2023-03-29 15:47:56 +01:00
Nick Gerleman 1fc7693205 Minimize EditText Spans 7/9: Avoid temp list (#36576)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36576

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This change addresses some minor CR feedback and removes the temporary list of spans in favor of applying them directly.

Changelog:
[Internal]

Reviewed By: javache

Differential Revision: D44295190

fbshipit-source-id: bd784e2c514301d45d0bacd8ee6de5c512fc565c
2023-03-29 15:47:50 +01:00
Nick Gerleman 4e24223550 Minimize EditText Spans 6/9: letterSpacing (#36548)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36548

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This change lets us set `letterSpacing` on the EditText instead of using our custom span.

Changelog:
[Android][Fixed] - Minimize EditText Spans 6/N: letterSpacing

Reviewed By: rshest

Differential Revision: D44240777

fbshipit-source-id: 9bd10c3261257037d8cacf37971011aaa94d1a77
2023-03-29 15:47:44 +01:00
Nick Gerleman 536ee8ba4c Minimize EditText Spans 5/9: Strikethrough and Underline (#36544)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36544

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This change makes us apply strikethrough and underline as paint flags to the underlying EditText, instead of just the spans. We then opt ReactUnderlineSpan and ReactStrikethroughSpan into being strippable.

This does actually create visual behavior changes, where child text will inherit any underline or strikethrough of the root EditText (including if the child specifies `textDecorationLine: "none"`. The new behavior is consistent with both iOS and web though, so it seems like more of a bugfix than a regression.

Changelog:
[Android][Fixed] - Minimize Spans 5/N: Strikethrough and Underline

Reviewed By: rshest

Differential Revision: D44240778

fbshipit-source-id: d564dfc0121057a5e3b09bb71b8f5662e28be17e
2023-03-29 15:47:37 +01:00
Nick Gerleman 3447fea075 Minimize EditText Spans 4/9: ReactForegroundColorSpan (#36545)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36545

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This adds ReactForegroundColorSpan to the list of spans eligible to be stripped.

Changelog:
[Android][Fixed] - Minimize Spans 4/N: ReactForegroundColorSpan

Reviewed By: javache

Differential Revision: D44240780

fbshipit-source-id: d86939cc2d7ed9116a4167026c7d48928fc51757
2023-03-29 15:47:15 +01:00
Nick Gerleman ea09a4701d Minimize EditText Spans 3/9: ReactBackgroundColorSpan (#36547)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36547

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This adds `ReactBackgroundColorSpan` to the list of spans eligible to be stripped.

Changelog:
[Android][Fixed] - Minimize Spans 3/N: ReactBackgroundColorSpan

Reviewed By: javache

Differential Revision: D44240782

fbshipit-source-id: 2ded1a1687a41cf6d5f83e89ffadd2d932089969
2023-03-29 15:47:02 +01:00
Nick Gerleman cffdad69c3 Minimize EditText Spans 2/9: Make stripAttributeEquivalentSpans generic (#36546)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36546

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

This change generalizes `stripAttributeEquivalentSpans()` to allow plugging in different spans.

Changelog:
[Internal]

Reviewed By: rshest

Differential Revision: D44240781

fbshipit-source-id: 89005266020f216368e9ad9ce382699bd8db85a8
2023-03-29 15:46:54 +01:00
Nick Gerleman a0a81a400b Minimize EditText Spans 1/9: Fix precedence (#36543)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36543

This is part of a series of changes to minimize the number of spans committed to EditText, as a mitigation for platform issues on Samsung devices. See this [GitHub thread]( https://github.com/facebook/react-native/issues/35936#issuecomment-1411437789) for greater context on the platform behavior.

We cache the backing EditText span on text change to later measure. To measure outside of a TextInput we need to restore any spans we removed. Spans may overlap, so base attributes should be behind everything else.

The logic here for dealing with precedence is incorrect, and we should instead accomplish this by twiddling with the `SPAN_PRIORITY` bits.

Changelog:
[Android][Fixed] - Minimize Spans 1/N: Fix precedence

Reviewed By: javache

Differential Revision: D44240779

fbshipit-source-id: f731b353587888faad946b8cf1e868095cdeced3
2023-03-29 15:46:46 +01:00
Nick Gerleman b6291aacf8 Bail on realizing region around last focused cell if we don't know where it is (#36541)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36541

We only know where the last focused cell lives after it is rendered. Apart from dead refs handled in D43835135, this means items added or removed before the focused cell will lead to a stale last index for the next state update.

We don't have a good way to correlate cells after data change. This effects the implementation for [`maintainVisibleContentPosition`](https://github.com/facebook/react-native/pull/35993) as well, but needs some thought on the right way to handle it. For now, we bail when we don't know where the last focused cell lives.

Changelog:
[General][Fixed] - Bail on realizing region around last focused cell if we don't know where it is

Reviewed By: yungsters

Differential Revision: D44221162

fbshipit-source-id: 8fc7e726fe13c62b98870600563857bb89290280
2023-03-29 15:46:33 +01:00
Ruslan Lesiutin 7700d7fd78 fix: update paths in React-rncore.podspec (#36571)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36571

Changelog: [Internal]

The problem is related to the way we use `js_srcs_dir` & `output_dir` options, one requires just relative path from current ruby script, other requires relative path from iOS root project (where the Podfile located)

output_dir was introduced in D43304641
resulted into the issue, described in https://discord.com/channels/514829729862516747/1087736932953509958

allow-large-files

Reviewed By: cipolleschi

Differential Revision: D44294112

fbshipit-source-id: 47fcf510e203d0880e1f92ab6ead09f4b79cb4dd
2023-03-29 15:45:54 +01:00
Shivam Shashank 2443677fe0 Support to enable/disable Fabric in ReactFragment (#36263)
Summary:
New Architecture Support missing in React Native Fragment, added same.

Changelog:
[Android] [Added] - Support to enable/disable Fabric in ReactFragment

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

Test Plan:
<details>
  <summary>Kotlin Code Snippet to test:</summary>
  <p>

```kotlin
supportFragmentManager
  .beginTransaction()
  .add(android.R.id.content,
     ReactFragment.Builder()
       .setComponentName("componentName")
       .setFabricEnabled(true)
       .build())
  .commit()
```

  </p>
</details>

Reviewed By: mdvacca

Differential Revision: D43701078

Pulled By: cortinico

fbshipit-source-id: 659ed2b4cf6619c6d64b803a198a93ff84b574fe
2023-03-29 15:45:44 +01:00
Samuel Susla 7c9f3ab437 Patch setNativeProps in OSS build
Summary:
changelog: [internal]

`setNativeProps` have been implemented in Fabric but require a React change to be accessible from JavaScript components. For React sync to be imported in OSS builds, React needs to have have a new release in NPM.
To work around this limitation, I manually copied over lines of code that glue together setNativeProps to OSS build.

Reviewed By: cortinico, cipolleschi

Differential Revision: D44216496

fbshipit-source-id: b34b598c1a317bdc03cc5a4cadb3f7c610059709
2023-03-29 15:45:36 +01:00
David Vacca f5fbda5e46 Improve caching of Text per shadow Node
Summary:
This diff optimizes text measurement by adding a layer of caching per shadow node.
When ReactFeatureFlags.enableTextMeasureCachePerShadowNode is enabled, we will cache and reused measurements per shadow node.
This optimization showed a 2x improvement on text rendearing when a screen contains a big amount of text components.

Changelog: [Internal] Internal

Reviewed By: sammy-SC

Differential Revision: D44221170

fbshipit-source-id: c3e7ba1ad216929826a99585874981717c90e13b
2023-03-29 15:45:27 +01:00
Samuel Susla 05ba16aa3d Enable NSTextStorage caching in OSS
Summary:
changelog: [internal]

Turn on NSTextStorage in OSS.

Reviewed By: cipolleschi

Differential Revision: D44216186

fbshipit-source-id: 7f08291dc0bc1237e72dd96235f76ed90361826b
2023-03-29 15:45:17 +01:00
9ffe82edd3 Port changes from main into Stable to make the CI green (#36665)
Co-authored-by: Riccardo Cipolleschi <cipolleschi@fb.com>
Co-authored-by: Alex Hunt <alexeh@meta.com>
resolved: https://github.com/facebook/react-native/pull/36502
2023-03-28 22:32:42 +01:00
Riccardo CipolleschiandRiccardo Cipolleschi 6e04b2a717 Restore object with prerelease as string to unblock 0.72 (#36657)
Co-authored-by: Riccardo Cipolleschi <cipolleschi@fb.com>
2023-03-27 18:22:25 +01:00
Rob Hogan fecfd04d89 [0.72-stable] Fix localhost references in yarn.lock (#36661) 2023-03-27 17:40:32 +01:00
Riccardo CipolleschiandRiccardo Cipolleschi a4e390a188 Revert Changes to Libraries/Utilities to fix prerelease type (#36655)
Co-authored-by: Riccardo Cipolleschi <cipolleschi@fb.com>
2023-03-27 16:48:42 +01:00
Riccardo CipolleschiandRiccardo Cipolleschi 17a96158aa Downgrade CLI to alpha.0 to get Metro working again in CI (#36654)
Co-authored-by: Riccardo Cipolleschi <cipolleschi@fb.com>
2023-03-27 16:48:20 +01:00
Ruslan Lesiutin 73f37b14d6 fix: format template location following prettier rules (#36651) 2023-03-27 15:11:26 +01:00
Riccardo CipolleschiandRiccardo Cipolleschi aff2e93576 Fix platform Typings (#36650)
Co-authored-by: Riccardo Cipolleschi <cipolleschi@fb.com>
2023-03-27 15:10:49 +01:00
Lorenzo Sciandra 8a5ddb92f1 [LOCAL] bump hermes in RNTester podfile 2023-03-21 15:01:22 +00:00
Lorenzo Sciandra f9b3835f1e fix script 2023-03-21 13:54:54 +00:00
Distiller 2c6edee68e [0.72.0-rc.0] Bump version numbers 2023-03-20 15:38:47 +00:00
Luna Wei f40f8f9ad2 fixed cwd for publish-npm script 2023-03-20 15:24:58 +00:00
Luna Wei c05d19102c Use new package versions 2023-03-20 15:21:00 +00:00
Luna Wei dad96696b7 Fix align-package-version path 2023-03-20 15:20:20 +00:00
Luna Wei 6d2805bf85 bumped packages versions
#publish-packages-to-npm
2023-03-20 15:12:12 +00:00
Luna Wei c2b182f9f5 Set Hermes version 2023-03-20 15:05:51 +00:00
124 changed files with 2874 additions and 2040 deletions
-5
View File
@@ -37,11 +37,6 @@ ADD scripts /app/scripts
WORKDIR /app
RUN scripts/buck/buck_fetch.sh
RUN buck build packages/react-native/ReactAndroid/src/main/java/com/facebook/react
RUN buck build packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell
ADD . /app
RUN yarn
+2 -57
View File
@@ -46,7 +46,7 @@ references:
# Dependency Anchors
# -------------------------
dependency_versions:
xcode_version: &xcode_version "14.2.0"
xcode_version: &xcode_version "14.3.0"
nodelts_image: &nodelts_image "cimg/node:18.12.1"
nodeprevlts_image: &nodeprevlts_image "cimg/node:16.18.1"
@@ -620,7 +620,7 @@ jobs:
- run:
name: Run Ruby Tests
command: |
cd scripts
cd packages/react-native/scripts
sh run_ruby_tests.sh
- run_yarn
- *attach_hermes_workspace
@@ -719,60 +719,6 @@ jobs:
- store_test_results:
path: ./reports/junit
# -------------------------
# JOBS: Test Buck
# -------------------------
test_buck:
executor: reactnativeandroid
environment:
KOTLIN_HOME=packages/react-native/third-party/kotlin
steps:
- checkout
- setup_artifacts
- run_yarn
- run:
name: Download Dependencies Using Buck
command: ./scripts/buck/buck_fetch.sh
- run:
name: Build & Test React Native using Buck
command: |
buck build packages/react-native/ReactAndroid/src/main/java/com/facebook/react
buck build packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell
- run:
name: Run Tests - Android Unit Tests with Buck
command: buck test packages/react-native/ReactAndroid/src/test/... --config build.threads=$BUILD_THREADS --xml ./reports/buck/all-results-raw.xml
- run:
name: Build JavaScript Bundle for instrumentation tests
working_directory: ~/react-native/packages/react-native
command: node cli.js bundle --max-workers 2 --platform android --dev true --entry-file ReactAndroid/src/androidTest/js/TestBundle.js --bundle-output ReactAndroid/src/androidTest/assets/AndroidTestBundle.js
- run:
name: Build Tests - Android Instrumentation Tests with Buck
# Here, just build the instrumentation tests. There is a known issue with installing the APK to android-21+ emulator.
command: |
if [[ ! -e packages/react-native/ReactAndroid/src/androidTest/assets/AndroidTestBundle.js ]]; then
echo "JavaScript bundle missing, cannot run instrumentation tests. Verify Build JavaScript Bundle step completed successfully."; exit 1;
fi
source scripts/android-setup.sh && NO_BUCKD=1 scripts/retry3 timeout 300 buck build packages/react-native/ReactAndroid/src/androidTest/buck-runner:instrumentation-tests --config build.threads=$BUILD_THREADS
- run:
name: Collect Test Results
command: |
find . -type f -regex ".*/build/test-results/debug/.*xml" -exec cp {} ./reports/build/ \;
find . -type f -regex ".*/outputs/androidTest-results/connected/.*xml" -exec cp {} ./reports/outputs/ \;
find . -type f -regex ".*/buck-out/gen/packages/react-native/ReactAndroid/src/test/.*/.*xml" -exec cp {} ./reports/buck/ \;
if [ -f ~/react-native/reports/buck/all-results-raw.xml ]; then
~/react-native/scripts/circleci/buckToJunit/buckToJunit.sh ~/react-native/reports/buck/all-results-raw.xml ~/react-native/reports/junit/results.xml
fi
when: always
- store_test_results:
path: ./reports/junit
# -------------------------
# JOBS: Test Android
# -------------------------
@@ -1694,7 +1640,6 @@ workflows:
architecture: ["NewArch", "OldArch"]
jsengine: ["Hermes", "JSC"]
flavor: ["Debug", "Release"]
- test_buck
- test_ios_template:
requires:
- build_npm_package
+8 -8
View File
@@ -3,22 +3,22 @@ GEM
specs:
CFPropertyList (3.0.6)
rexml
activesupport (7.0.4.2)
activesupport (7.0.4.3)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
addressable (2.8.1)
addressable (2.8.4)
public_suffix (>= 2.0.2, < 6.0)
algoliasearch (1.27.5)
httpclient (~> 2.8, >= 2.8.3)
json (>= 1.5.1)
atomos (0.1.3)
claide (1.1.0)
cocoapods (1.12.0)
cocoapods (1.12.1)
addressable (~> 2.8)
claide (>= 1.0.2, < 2.0)
cocoapods-core (= 1.12.0)
cocoapods-core (= 1.12.1)
cocoapods-deintegrate (>= 1.0.3, < 2.0)
cocoapods-downloader (>= 1.6.0, < 2.0)
cocoapods-plugins (>= 1.0.0, < 2.0)
@@ -33,7 +33,7 @@ GEM
nap (~> 1.0)
ruby-macho (>= 2.3.0, < 3.0)
xcodeproj (>= 1.21.0, < 2.0)
cocoapods-core (1.12.0)
cocoapods-core (1.12.1)
activesupport (>= 5.0, < 8)
addressable (~> 2.8)
algoliasearch (~> 1.0)
@@ -62,7 +62,7 @@ GEM
fuzzy_match (2.0.4)
gh_inspector (1.1.3)
httpclient (2.8.3)
i18n (1.12.0)
i18n (1.13.0)
concurrent-ruby (~> 1.0)
json (2.6.3)
minitest (5.18.0)
@@ -93,7 +93,7 @@ DEPENDENCIES
cocoapods (~> 1.12)
RUBY VERSION
ruby 3.2.0p0
ruby 3.0.5p211
BUNDLED WITH
2.4.7
2.4.10
+6 -6
View File
@@ -40,8 +40,7 @@
"test-ios": "./scripts/objc-test.sh test",
"test-typescript": "dtslint packages/react-native/types",
"test-typescript-offline": "dtslint --localTs node_modules/typescript/lib packages/react-native/types",
"bump-all-updated-packages": "node ./scripts/monorepo/bump-all-updated-packages",
"align-package-versions": "node ./scripts/monorepo/align-package-versions.js"
"bump-all-updated-packages": "node ./scripts/monorepo/bump-all-updated-packages"
},
"workspaces": [
"packages/*"
@@ -57,10 +56,11 @@
"@definitelytyped/dtslint": "^0.0.127",
"@jest/create-cache-key-function": "^29.2.1",
"@reactions/component": "^2.0.2",
"@react-native/metro-config": "^0.72.5",
"@types/react": "^18.0.18",
"@typescript-eslint/parser": "^5.30.5",
"async": "^3.2.2",
"babel-plugin-transform-flow-enums":"^0.0.2",
"babel-plugin-transform-flow-enums": "^0.0.2",
"clang-format": "^1.8.0",
"connect": "^3.6.5",
"coveralls": "^3.1.1",
@@ -84,9 +84,9 @@
"jest": "^29.2.1",
"jest-junit": "^10.0.0",
"jscodeshift": "^0.14.0",
"metro-babel-register": "0.75.1",
"metro-memory-fs": "0.75.1",
"metro-react-native-babel-transformer": "0.75.1",
"metro-babel-register": "0.76.4",
"metro-memory-fs": "0.76.4",
"metro-react-native-babel-transformer": "0.76.4",
"mkdirp": "^0.5.1",
"mock-fs": "^5.1.4",
"prettier": "^2.4.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@react-native/eslint-plugin-specs",
"version": "0.72.2",
"version": "0.72.3",
"description": "ESLint rules to validate NativeModule and Component Specs",
"main": "index.js",
"repository": {
+82
View File
@@ -0,0 +1,82 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @noformat
*/
/*:: import type {MetroConfig} from 'metro-config'; */
const {mergeConfig} = require('metro-config');
const INTERNAL_CALLSITES_REGEX = new RegExp(
[
'/Libraries/Renderer/implementations/.+\\.js$',
'/Libraries/BatchedBridge/MessageQueue\\.js$',
'/Libraries/YellowBox/.+\\.js$',
'/Libraries/LogBox/.+\\.js$',
'/Libraries/Core/Timers/.+\\.js$',
'/Libraries/WebSocket/.+\\.js$',
'/Libraries/vendor/.+\\.js$',
'/node_modules/react-devtools-core/.+\\.js$',
'/node_modules/react-refresh/.+\\.js$',
'/node_modules/scheduler/.+\\.js$',
'/node_modules/event-target-shim/.+\\.js$',
'/node_modules/invariant/.+\\.js$',
'/node_modules/react-native/index.js$',
'/metro-runtime/.+\\.js$',
'^\\[native code\\]$',
].join('|'),
);
/**
* Get the base Metro configuration for a React Native project.
*/
function getDefaultConfig(
projectRoot /*: string */
) /*: MetroConfig */ {
return {
resolver: {
resolverMainFields: ['react-native', 'browser', 'main'],
platforms: ['android', 'ios'],
unstable_conditionNames: ['require', 'import', 'react-native'],
},
serializer: {
getPolyfills: () => require('@react-native/js-polyfills')(),
},
server: {
port: Number(process.env.RCT_METRO_PORT) || 8081,
},
symbolicator: {
customizeFrame: (frame /*: $ReadOnly<{file: ?string, ...}>*/) => {
const collapse = Boolean(
frame.file && INTERNAL_CALLSITES_REGEX.test(frame.file),
);
return {collapse};
},
},
transformer: {
allowOptionalDependencies: true,
assetRegistryPath: 'react-native/Libraries/Image/AssetRegistry',
asyncRequireModulePath: require.resolve(
'metro-runtime/src/modules/asyncRequire',
),
babelTransformerPath: require.resolve(
'metro-react-native-babel-transformer',
),
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
watchFolders: [],
};
}
module.exports = {getDefaultConfig, mergeConfig};
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@react-native/metro-config",
"version": "0.72.5",
"description": "Metro configuration for React Native.",
"repository": {
"type": "git",
"url": "git@github.com:facebook/react-native.git",
"directory": "packages/metro-config"
},
"license": "MIT",
"exports": "./index.js",
"dependencies": {
"@react-native/js-polyfills": "^0.72.1",
"metro-config": "0.76.4",
"metro-react-native-babel-transformer": "0.76.4",
"metro-runtime": "0.76.4"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@react-native/codegen",
"version": "0.72.3",
"version": "0.72.4",
"description": "⚛️ Code generation tools for React Native",
"homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen",
"repository": {
@@ -1,6 +1,6 @@
{
"name": "@react-native/gradle-plugin",
"version": "0.72.5",
"version": "0.72.7",
"description": "⚛️ Gradle Plugin for React Native",
"homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin",
"repository": {
@@ -18,7 +18,7 @@ import com.facebook.react.utils.AgpConfiguratorUtils.configureDevPorts
import com.facebook.react.utils.BackwardCompatUtils.configureBackwardCompatibilityReactMap
import com.facebook.react.utils.DependencyUtils.configureDependencies
import com.facebook.react.utils.DependencyUtils.configureRepositories
import com.facebook.react.utils.DependencyUtils.readVersionString
import com.facebook.react.utils.DependencyUtils.readVersionAndGroupStrings
import com.facebook.react.utils.JsonUtils
import com.facebook.react.utils.NdkConfiguratorUtils.configureReactNativeNdk
import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson
@@ -54,8 +54,10 @@ class ReactPlugin : Plugin<Project> {
project.afterEvaluate {
val reactNativeDir = extension.reactNativeDir.get().asFile
val propertiesFile = File(reactNativeDir, "ReactAndroid/gradle.properties")
val versionString = readVersionString(propertiesFile)
configureDependencies(project, versionString)
val versionAndGroupStrings = readVersionAndGroupStrings(propertiesFile)
val versionString = versionAndGroupStrings.first
val groupString = versionAndGroupStrings.second
configureDependencies(project, versionString, groupString)
configureRepositories(project, reactNativeDir)
}
@@ -13,6 +13,8 @@ import java.util.*
import org.gradle.api.Project
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
internal const val DEFAULT_GROUP_STRING = "com.facebook.react"
internal object DependencyUtils {
/**
@@ -46,7 +48,11 @@ internal object DependencyUtils {
* - Forcing the react-android/hermes-android version to the one specified in the package.json
* - Substituting `react-native` with `react-android` and `hermes-engine` with `hermes-android`.
*/
fun configureDependencies(project: Project, versionString: String) {
fun configureDependencies(
project: Project,
versionString: String,
groupString: String = DEFAULT_GROUP_STRING
) {
if (versionString.isBlank()) return
project.rootProject.allprojects { eachProject ->
eachProject.configurations.all { configuration ->
@@ -56,32 +62,36 @@ internal object DependencyUtils {
// implementation("com.facebook.react:react-native:+") and resolve the right dependency.
configuration.resolutionStrategy.dependencySubstitution {
it.substitute(it.module("com.facebook.react:react-native"))
.using(it.module("com.facebook.react:react-android:${versionString}"))
.using(it.module("${groupString}:react-android:${versionString}"))
.because(
"The react-native artifact was deprecated in favor of react-android due to https://github.com/facebook/react-native/issues/35210.")
it.substitute(it.module("com.facebook.react:hermes-engine"))
.using(it.module("com.facebook.react:hermes-android:${versionString}"))
.using(it.module("${groupString}:hermes-android:${versionString}"))
.because(
"The hermes-engine artifact was deprecated in favor of hermes-android due to https://github.com/facebook/react-native/issues/35210.")
}
configuration.resolutionStrategy.force(
"com.facebook.react:react-android:${versionString}",
"com.facebook.react:hermes-android:${versionString}",
"${groupString}:react-android:${versionString}",
"${groupString}:hermes-android:${versionString}",
)
}
}
}
fun readVersionString(propertiesFile: File): String {
fun readVersionAndGroupStrings(propertiesFile: File): Pair<String, String> {
val reactAndroidProperties = Properties()
propertiesFile.inputStream().use { reactAndroidProperties.load(it) }
val versionString = reactAndroidProperties["VERSION_NAME"] as? String ?: ""
val versionStringFromFile = reactAndroidProperties["VERSION_NAME"] as? String ?: ""
// If on a nightly, we need to fetch the -SNAPSHOT artifact from Sonatype.
return if (versionString.startsWith("0.0.0")) {
"$versionString-SNAPSHOT"
} else {
versionString
}
val versionString =
if (versionStringFromFile.startsWith("0.0.0")) {
"$versionStringFromFile-SNAPSHOT"
} else {
versionStringFromFile
}
// Returns Maven group for repos using different group for Maven artifacts
val groupString = reactAndroidProperties["GROUP"] as? String ?: DEFAULT_GROUP_STRING
return Pair(versionString, groupString)
}
fun Project.mavenRepoFromUrl(url: String): MavenArtifactRepository =
@@ -12,7 +12,7 @@ import com.facebook.react.utils.DependencyUtils.configureDependencies
import com.facebook.react.utils.DependencyUtils.configureRepositories
import com.facebook.react.utils.DependencyUtils.mavenRepoFromURI
import com.facebook.react.utils.DependencyUtils.mavenRepoFromUrl
import com.facebook.react.utils.DependencyUtils.readVersionString
import com.facebook.react.utils.DependencyUtils.readVersionAndGroupStrings
import java.net.URI
import org.gradle.api.artifacts.repositories.MavenArtifactRepository
import org.gradle.testfixtures.ProjectBuilder
@@ -226,6 +226,24 @@ class DependencyUtilsTest {
assertTrue(libForcedModules.any { it.toString() == "com.facebook.react:hermes-android:1.2.3" })
}
@Test
fun configureDependencies_withVersionStringAndGroupString_appliesOnAllProjects() {
val rootProject = ProjectBuilder.builder().build()
val appProject = ProjectBuilder.builder().withName("app").withParent(rootProject).build()
val libProject = ProjectBuilder.builder().withName("lib").withParent(rootProject).build()
appProject.plugins.apply("com.android.application")
libProject.plugins.apply("com.android.library")
configureDependencies(appProject, "1.2.3", "io.github.test")
val appForcedModules = appProject.configurations.first().resolutionStrategy.forcedModules
val libForcedModules = libProject.configurations.first().resolutionStrategy.forcedModules
assertTrue(appForcedModules.any { it.toString() == "io.github.test:react-android:1.2.3" })
assertTrue(appForcedModules.any { it.toString() == "io.github.test:hermes-android:1.2.3" })
assertTrue(libForcedModules.any { it.toString() == "io.github.test:react-android:1.2.3" })
assertTrue(libForcedModules.any { it.toString() == "io.github.test:hermes-android:1.2.3" })
}
@Test
fun readVersionString_withCorrectVersionString_returnsIt() {
val propertiesFile =
@@ -238,7 +256,7 @@ class DependencyUtilsTest {
.trimIndent())
}
val versionString = readVersionString(propertiesFile)
val versionString = readVersionAndGroupStrings(propertiesFile).first
assertEquals("1000.0.0", versionString)
}
@@ -255,7 +273,7 @@ class DependencyUtilsTest {
.trimIndent())
}
val versionString = readVersionString(propertiesFile)
val versionString = readVersionAndGroupStrings(propertiesFile).first
assertEquals("0.0.0-20221101-2019-cfe811ab1-SNAPSHOT", versionString)
}
@@ -271,7 +289,7 @@ class DependencyUtilsTest {
.trimIndent())
}
val versionString = readVersionString(propertiesFile)
val versionString = readVersionAndGroupStrings(propertiesFile).first
assertEquals("", versionString)
}
@@ -287,10 +305,43 @@ class DependencyUtilsTest {
.trimIndent())
}
val versionString = readVersionString(propertiesFile)
val versionString = readVersionAndGroupStrings(propertiesFile).first
assertEquals("", versionString)
}
@Test
fun readGroupString_withCorrectGroupString_returnsIt() {
val propertiesFile =
tempFolder.newFile("gradle.properties").apply {
writeText(
"""
GROUP=io.github.test
ANOTHER_PROPERTY=true
"""
.trimIndent())
}
val groupString = readVersionAndGroupStrings(propertiesFile).second
assertEquals("io.github.test", groupString)
}
@Test
fun readGroupString_withEmptyGroupString_returnsDefault() {
val propertiesFile =
tempFolder.newFile("gradle.properties").apply {
writeText(
"""
ANOTHER_PROPERTY=true
"""
.trimIndent())
}
val groupString = readVersionAndGroupStrings(propertiesFile).second
assertEquals("com.facebook.react", groupString)
}
@Test
fun mavenRepoFromUrl_worksCorrectly() {
val process = createProject()
@@ -46,13 +46,6 @@ const ReactNativeStyleAttributes: {[string]: AnyAttributeType, ...} = {
flexWrap: true,
gap: true,
height: true,
inset: true,
insetBlock: true,
insetBlockEnd: true,
insetBlockStart: true,
insetInline: true,
insetInlineEnd: true,
insetInlineStart: true,
justifyContent: true,
left: true,
margin: true,
+3 -3
View File
@@ -10,8 +10,8 @@
*/
exports.version = {
major: 1000,
minor: 0,
major: 0,
minor: 72,
patch: 0,
prerelease: null,
prerelease: 'rc.3',
};
@@ -39,8 +39,12 @@ exports.checkVersions = function checkVersions(): void {
}
};
// Note: in OSS, the prerelease version is usually 0.Y.0-rc.W, so it is a string and not a number
// Then we need to keep supporting that object shape.
function _formatVersion(
version: (typeof Platform)['constants']['reactNativeVersion'],
version:
| (typeof Platform)['constants']['reactNativeVersion']
| {major: number, minor: number, patch: number, prerelease: ?string},
): string {
return (
`${version.major}.${version.minor}.${version.patch}` +
@@ -258,14 +258,6 @@ const validAttributesForNonEventProps = {
top: true,
bottom: true,
inset: true,
insetBlock: true,
insetBlockEnd: true,
insetBlockStart: true,
insetInline: true,
insetInlineEnd: true,
insetInlineStart: true,
position: true,
style: ReactNativeStyleAttributes,
@@ -236,14 +236,6 @@ const validAttributesForNonEventProps = {
bottom: true,
left: true,
inset: true,
insetBlock: true,
insetBlockEnd: true,
insetBlockStart: true,
insetInline: true,
insetInlineEnd: true,
insetInlineStart: true,
width: true,
height: true,
+27 -1
View File
@@ -9,7 +9,6 @@
*/
import type {RootTag} from '../Types/RootTagTypes';
import type {Spec as FabricUIManagerSpec} from './FabricUIManager';
import type {Spec} from './NativeUIManager';
import {getFabricUIManager} from './FabricUIManager';
@@ -175,6 +174,33 @@ const UIManager = {
);
}
},
dispatchViewManagerCommand(
reactTag: number,
commandName: number | string,
commandArgs: any[],
) {
if (isFabricReactTag(reactTag)) {
const FabricUIManager = nullthrows(getFabricUIManager());
const shadowNode =
FabricUIManager.findShadowNodeByTag_DEPRECATED(reactTag);
if (shadowNode) {
// Transform the accidental CommandID into a CommandName which is the stringified number.
// The interop layer knows how to convert this number into the right method name.
// Stringify a string is a no-op, so it's safe.
commandName = `${commandName}`;
FabricUIManager.dispatchCommand(shadowNode, commandName, commandArgs);
}
} else {
UIManagerImpl.dispatchViewManagerCommand(
reactTag,
// We have some legacy components that are actually already using strings. ¯\_(ツ)_/¯
// $FlowFixMe[incompatible-call]
commandName,
commandArgs,
);
}
},
};
module.exports = UIManager;
@@ -3419,6 +3419,23 @@ function mountSafeCallback_NOT_REALLY_SAFE(context, callback) {
return callback.apply(context, arguments);
};
}
function warnForStyleProps(props, validAttributes) {
{
for (var key in validAttributes.style) {
if (!(validAttributes[key] || props[key] === undefined)) {
error(
"You are setting the style `{ %s" +
": ... }` as a prop. You " +
"should nest it in a style object. " +
"E.g. `{ style: { %s" +
": ... } }`",
key,
key
);
}
}
}
}
// Modules provided by RN:
var emptyObject = {};
@@ -5100,7 +5117,8 @@ var _nativeFabricUIManage = nativeFabricUIManager,
FabricDefaultPriority = _nativeFabricUIManage.unstable_DefaultEventPriority,
FabricDiscretePriority = _nativeFabricUIManage.unstable_DiscreteEventPriority,
fabricGetCurrentEventPriority =
_nativeFabricUIManage.unstable_getCurrentEventPriority;
_nativeFabricUIManage.unstable_getCurrentEventPriority,
_setNativeProps = _nativeFabricUIManage.setNativeProps;
var getViewConfigForType =
ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get; // Counter for uniquely identifying views.
// % 10 === 1 means it is a rootTag.
@@ -5199,10 +5217,15 @@ var ReactFabricHostComponent = /*#__PURE__*/ (function() {
_proto.setNativeProps = function setNativeProps(nativeProps) {
{
error("Warning: setNativeProps is not currently supported in Fabric");
warnForStyleProps(nativeProps, this.viewConfig.validAttributes);
}
return;
var updatePayload = create(nativeProps, this.viewConfig.validAttributes);
var stateNode = this._internalInstanceHandle.stateNode;
if (stateNode != null && updatePayload != null) {
_setNativeProps(stateNode.node, updatePayload);
}
}; // This API (addEventListener, removeEventListener) attempts to adhere to the
// w3 Level2 Events spec as much as possible, treating HostComponent as a DOM node.
//
@@ -1922,6 +1922,7 @@ var _nativeFabricUIManage = nativeFabricUIManager,
FabricDiscretePriority = _nativeFabricUIManage.unstable_DiscreteEventPriority,
fabricGetCurrentEventPriority =
_nativeFabricUIManage.unstable_getCurrentEventPriority,
_setNativeProps = _nativeFabricUIManage.setNativeProps,
getViewConfigForType =
ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get,
nextReactTag = 2;
@@ -1979,7 +1980,18 @@ var ReactFabricHostComponent = (function() {
);
}
};
_proto.setNativeProps = function() {};
_proto.setNativeProps = function(nativeProps) {
nativeProps = diffProperties(
null,
emptyObject,
nativeProps,
this.viewConfig.validAttributes
);
var stateNode = this._internalInstanceHandle.stateNode;
null != stateNode &&
null != nativeProps &&
_setNativeProps(stateNode.node, nativeProps);
};
_proto.addEventListener_unstable = function(eventType, listener, options) {
if ("string" !== typeof eventType)
throw Error("addEventListener_unstable eventType must be a string");
@@ -1981,6 +1981,7 @@ var _nativeFabricUIManage = nativeFabricUIManager,
FabricDiscretePriority = _nativeFabricUIManage.unstable_DiscreteEventPriority,
fabricGetCurrentEventPriority =
_nativeFabricUIManage.unstable_getCurrentEventPriority,
_setNativeProps = _nativeFabricUIManage.setNativeProps,
getViewConfigForType =
ReactNativePrivateInterface.ReactNativeViewConfigRegistry.get,
nextReactTag = 2;
@@ -2038,7 +2039,18 @@ var ReactFabricHostComponent = (function() {
);
}
};
_proto.setNativeProps = function() {};
_proto.setNativeProps = function(nativeProps) {
nativeProps = diffProperties(
null,
emptyObject,
nativeProps,
this.viewConfig.validAttributes
);
var stateNode = this._internalInstanceHandle.stateNode;
null != stateNode &&
null != nativeProps &&
_setNativeProps(stateNode.node, nativeProps);
};
_proto.addEventListener_unstable = function(eventType, listener, options) {
if ("string" !== typeof eventType)
throw Error("addEventListener_unstable eventType must be a string");
@@ -69,13 +69,6 @@ export interface FlexStyle {
flexShrink?: number | undefined;
flexWrap?: 'wrap' | 'nowrap' | 'wrap-reverse' | undefined;
height?: DimensionValue | undefined;
inset?: DimensionValue | undefined;
insetBlock?: DimensionValue | undefined;
insetBlockEnd?: DimensionValue | undefined;
insetBlockStart?: DimensionValue | undefined;
insetInline?: DimensionValue | undefined;
insetInlineEnd?: DimensionValue | undefined;
insetInlineStart?: DimensionValue | undefined;
justifyContent?:
| 'flex-start'
| 'flex-end'
@@ -134,80 +134,6 @@ type ____LayoutStyle_Internal = $ReadOnly<{
*/
top?: DimensionValue,
/** `inset` is a shorthand that corresponds to the top, right, bottom, and/or left properties.
*
* It works similarly to `inset` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset
* for more details of how `inset` affects layout.
*/
inset?: DimensionValue,
/** `insetBlock` is a shorthand that corresponds to the `insetBlockStart` and `insetBlockEnd` properties.
*
* It works similarly to `inset-block` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block
* for more details of how `inset-block` affects layout.
*/
insetBlock?: DimensionValue,
/** `insetBlockEnd` is a logical property that sets the length that an
* element is offset in the block direction from its ending edge.
*
* It works similarly to `inset-block-end` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-end
* for more details of how `inset-block-end` affects layout.
*/
insetBlockEnd?: DimensionValue,
/** `insetBlockStart` is a logical property that sets the length that an
* element is offset in the block direction from its starting edge.
*
* It works similarly to `inset-block-start` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-block-start
* for more details of how `inset-block-start` affects layout.
*/
insetBlockStart?: DimensionValue,
/** `insetInline` is a shorthand that corresponds to the `insetInlineStart` and `insetInlineEnd` properties.
*
* It works similarly to `inset-inline` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline
* for more details of how `inset-inline` affects layout.
*/
insetInline?: DimensionValue,
/** `insetInlineEnd` is a logical property that sets the length that an
* element is offset in the starting inline direction.
*
* It works similarly to `inset-inline-end` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-end
* for more details of how `inset-inline-end` affects layout.
*/
insetInlineEnd?: DimensionValue,
/** `insetInlineStart` is a logical property that sets the length that an
* element is offset in the starting inline direction.
*
* It works similarly to `inset-inline-start` in CSS, but in React Native you
* must use points or percentages. Ems and other units are not supported.
*
* See https://developer.mozilla.org/en-US/docs/Web/CSS/inset-inline-start
* for more details of how `inset-inline-start` affects layout.
*/
insetInlineStart?: DimensionValue,
/** `minWidth` is the minimum width for this component, in logical pixels.
*
* It works similarly to `min-width` in CSS, but in React Native you
@@ -256,21 +256,21 @@ static void *TextFieldSelectionObservingContext = &TextFieldSelectionObservingCo
- (void)textViewDidChange:(__unused UITextView *)textView
{
if (_ignoreNextTextInputCall && [_lastStringStateWasUpdatedWith isEqual:_backedTextInputView.attributedText]) {
if (_ignoreNextTextInputCall) {
_ignoreNextTextInputCall = NO;
return;
}
_lastStringStateWasUpdatedWith = _backedTextInputView.attributedText;
_textDidChangeIsComing = NO;
[_backedTextInputView.textInputDelegate textInputDidChange];
}
- (void)textViewDidChangeSelection:(__unused UITextView *)textView
{
if (![_lastStringStateWasUpdatedWith isEqual:_backedTextInputView.attributedText]) {
if (_lastStringStateWasUpdatedWith && ![_lastStringStateWasUpdatedWith isEqual:_backedTextInputView.attributedText]) {
[self textViewDidChange:_backedTextInputView];
_ignoreNextTextInputCall = YES;
}
_lastStringStateWasUpdatedWith = _backedTextInputView.attributedText;
[self textViewProbablyDidChangeSelection];
}
@@ -21,10 +21,10 @@ NSDictionary* RCTGetReactNativeVersion(void)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^(void){
__rnVersion = @{
RCTVersionMajor: @(1000),
RCTVersionMinor: @(0),
RCTVersionMajor: @(0),
RCTVersionMinor: @(72),
RCTVersionPatch: @(0),
RCTVersionPrerelease: [NSNull null],
RCTVersionPrerelease: @"rc.3",
};
});
return __rnVersion;
@@ -428,10 +428,10 @@ RCT_EXPORT_METHOD(show)
? UIAlertControllerStyleActionSheet
: UIAlertControllerStyleAlert;
NSString *debugMenuType = self.bridge ? @"Bridge" : @"Bridgeless";
NSString *debugMenuTitle = [NSString stringWithFormat:@"React Native Debug Menu (%@)", debugMenuType];
NSString *devMenuType = self.bridge ? @"Bridge" : @"Bridgeless";
NSString *devMenuTitle = [NSString stringWithFormat:@"React Native Dev Menu (%@)", devMenuType];
_actionSheet = [UIAlertController alertControllerWithTitle:debugMenuTitle message:description preferredStyle:style];
_actionSheet = [UIAlertController alertControllerWithTitle:devMenuTitle message:description preferredStyle:style];
NSArray<RCTDevMenuItem *> *items = [self _menuItemsToPresent];
for (RCTDevMenuItem *item in items) {
@@ -14,6 +14,7 @@
#import <react/renderer/components/image/ImageComponentDescriptor.h>
#import <react/renderer/components/image/ImageEventEmitter.h>
#import <react/renderer/components/image/ImageProps.h>
#import <react/renderer/core/CoreFeatures.h>
#import <react/renderer/imagemanager/ImageRequest.h>
#import <react/renderer/imagemanager/RCTImagePrimitivesConversions.h>
@@ -97,8 +98,18 @@ using namespace facebook::react;
- (void)_setStateAndResubscribeImageResponseObserver:(ImageShadowNode::ConcreteState::Shared const &)state
{
if (_state) {
auto &observerCoordinator = _state->getData().getImageRequest().getObserverCoordinator();
auto const &imageRequest = _state->getData().getImageRequest();
auto &observerCoordinator = imageRequest.getObserverCoordinator();
observerCoordinator.removeObserver(_imageResponseObserverProxy);
if (CoreFeatures::cancelImageDownloadsOnRecycle) {
// Cancelling image request because we are no longer observing it.
// This is not 100% correct place to do this because we may want to
// re-create RCTImageComponentView with the same image and if it
// was cancelled before downloaded, download is not resumed.
// This will only become issue if we decouple life cycle of a
// ShadowNode from ComponentView, which is not something we do now.
imageRequest.cancel();
}
}
_state = state;
@@ -50,7 +50,7 @@
- (void)handleCommand:(NSString *)commandName args:(NSArray *)args
{
[_coordinator handleCommand:commandName args:args reactTag:_tag];
[_coordinator handleCommand:commandName args:args reactTag:_tag paperView:self.paperView];
}
@end
@@ -285,6 +285,10 @@ static BackgroundExecutor RCTGetBackgroundExecutor()
CoreFeatures::cacheNSTextStorage = true;
}
if (reactNativeConfig && reactNativeConfig->getBool("react_fabric:cancel_image_downloads_on_recycle")) {
CoreFeatures::cancelImageDownloadsOnRecycle = true;
}
auto componentRegistryFactory =
[factory = wrapManagedObject(_mountingManager.componentViewRegistry.componentViewFactory)](
EventDispatcher::Weak const &eventDispatcher, ContextContainer::Shared const &contextContainer) {
@@ -1,4 +1,4 @@
VERSION_NAME=1000.0.0
VERSION_NAME=0.72.0-rc.3
GROUP=com.facebook.react
# JVM Versions
@@ -11,6 +11,7 @@ import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
@@ -33,6 +34,8 @@ public class ReactDelegate {
private ReactNativeHost mReactNativeHost;
private boolean mFabricEnabled = false;
public ReactDelegate(
Activity activity,
ReactNativeHost reactNativeHost,
@@ -45,6 +48,20 @@ public class ReactDelegate {
mReactNativeHost = reactNativeHost;
}
public ReactDelegate(
Activity activity,
ReactNativeHost reactNativeHost,
@Nullable String appKey,
@Nullable Bundle launchOptions,
boolean fabricEnabled) {
mActivity = activity;
mMainComponentName = appKey;
mLaunchOptions = composeLaunchOptions(launchOptions);
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
mReactNativeHost = reactNativeHost;
mFabricEnabled = fabricEnabled;
}
public void onHostResume() {
if (getReactNativeHost().hasInstance()) {
if (mActivity instanceof DefaultHardwareBackBtnHandler) {
@@ -109,7 +126,9 @@ public class ReactDelegate {
}
protected ReactRootView createRootView() {
return new ReactRootView(mActivity);
ReactRootView reactRootView = new ReactRootView(mActivity);
reactRootView.setIsFabric(isFabricEnabled());
return reactRootView;
}
/**
@@ -144,4 +163,24 @@ public class ReactDelegate {
public ReactInstanceManager getReactInstanceManager() {
return getReactNativeHost().getReactInstanceManager();
}
/**
* Override this method if you wish to selectively toggle Fabric for a specific surface. This will
* also control if Concurrent Root (React 18) should be enabled or not.
*
* @return true if Fabric is enabled for this Activity, false otherwise.
*/
protected boolean isFabricEnabled() {
return mFabricEnabled;
}
private @NonNull Bundle composeLaunchOptions(Bundle composedLaunchOptions) {
if (isFabricEnabled()) {
if (composedLaunchOptions == null) {
composedLaunchOptions = new Bundle();
}
composedLaunchOptions.putBoolean("concurrentRoot", true);
}
return composedLaunchOptions;
}
}
@@ -16,6 +16,7 @@ import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.facebook.react.modules.core.PermissionAwareActivity;
@@ -29,6 +30,7 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
protected static final String ARG_COMPONENT_NAME = "arg_component_name";
protected static final String ARG_LAUNCH_OPTIONS = "arg_launch_options";
protected static final String ARG_FABRIC_ENABLED = "arg_fabric_enabled";
private ReactDelegate mReactDelegate;
@@ -40,13 +42,16 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
/**
* @param componentName The name of the react native component
* @param fabricEnabled Flag to enable Fabric for ReactFragment
* @return A new instance of fragment ReactFragment.
*/
private static ReactFragment newInstance(String componentName, Bundle launchOptions) {
private static ReactFragment newInstance(
String componentName, Bundle launchOptions, Boolean fabricEnabled) {
ReactFragment fragment = new ReactFragment();
Bundle args = new Bundle();
args.putString(ARG_COMPONENT_NAME, componentName);
args.putBundle(ARG_LAUNCH_OPTIONS, launchOptions);
args.putBoolean(ARG_FABRIC_ENABLED, fabricEnabled);
fragment.setArguments(args);
return fragment;
}
@@ -57,15 +62,18 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
super.onCreate(savedInstanceState);
String mainComponentName = null;
Bundle launchOptions = null;
Boolean fabricEnabled = null;
if (getArguments() != null) {
mainComponentName = getArguments().getString(ARG_COMPONENT_NAME);
launchOptions = getArguments().getBundle(ARG_LAUNCH_OPTIONS);
fabricEnabled = getArguments().getBoolean(ARG_FABRIC_ENABLED);
}
if (mainComponentName == null) {
throw new IllegalStateException("Cannot loadApp if component name is null");
}
mReactDelegate =
new ReactDelegate(getActivity(), getReactNativeHost(), mainComponentName, launchOptions);
new ReactDelegate(
getActivity(), getReactNativeHost(), mainComponentName, launchOptions, fabricEnabled);
}
/**
@@ -85,7 +93,7 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mReactDelegate.loadApp();
return mReactDelegate.getReactRootView();
}
@@ -140,7 +148,7 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (mPermissionListener != null
&& mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
@@ -170,12 +178,14 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
/** Builder class to help instantiate a ReactFragment */
public static class Builder {
String mComponentName;
Bundle mLaunchOptions;
@Nullable String mComponentName;
@Nullable Bundle mLaunchOptions;
@Nullable Boolean mFabricEnabled;
public Builder() {
mComponentName = null;
mLaunchOptions = null;
mFabricEnabled = null;
}
/**
@@ -201,7 +211,12 @@ public class ReactFragment extends Fragment implements PermissionAwareActivity {
}
public ReactFragment build() {
return ReactFragment.newInstance(mComponentName, mLaunchOptions);
return ReactFragment.newInstance(mComponentName, mLaunchOptions, mFabricEnabled);
}
public Builder setFabricEnabled(boolean fabricEnabled) {
mFabricEnabled = fabricEnabled;
return this;
}
}
}
@@ -295,6 +295,16 @@ public class NativeAnimatedModule extends NativeAnimatedModuleSpec
mCurrentFrameNumber++;
}
@Override
public void willMountItems(UIManager uiManager) {
// noop
}
@Override
public void didMountItems(UIManager uiManager) {
// noop
}
// For FabricUIManager only
@Override
@UiThread
@@ -21,6 +21,7 @@ import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.react.bridge.interop.InteropModuleRegistry;
import com.facebook.react.bridge.queue.MessageQueueThread;
import com.facebook.react.bridge.queue.ReactQueueConfiguration;
import com.facebook.react.common.LifecycleState;
@@ -69,6 +70,8 @@ public class ReactContext extends ContextWrapper {
private @Nullable JSExceptionHandler mJSExceptionHandler;
private @Nullable JSExceptionHandler mExceptionHandlerWrapper;
private @Nullable WeakReference<Activity> mCurrentActivity;
private @Nullable InteropModuleRegistry mInteropModuleRegistry;
private boolean mIsInitialized = false;
public ReactContext(Context base) {
@@ -93,6 +96,7 @@ public class ReactContext extends ContextWrapper {
ReactQueueConfiguration queueConfig = catalystInstance.getReactQueueConfiguration();
initializeMessageQueueThreads(queueConfig);
initializeInteropModules();
}
/** Initialize message queue threads using a ReactQueueConfiguration. */
@@ -120,6 +124,14 @@ public class ReactContext extends ContextWrapper {
mIsInitialized = true;
}
protected void initializeInteropModules() {
mInteropModuleRegistry = new InteropModuleRegistry();
}
protected void initializeInteropModules(ReactContext reactContext) {
mInteropModuleRegistry = reactContext.mInteropModuleRegistry;
}
public void resetPerfStats() {
if (mNativeModulesMessageQueueThread != null) {
mNativeModulesMessageQueueThread.resetPerfStats();
@@ -163,6 +175,10 @@ public class ReactContext extends ContextWrapper {
}
throw new IllegalStateException(EARLY_JS_ACCESS_EXCEPTION_MESSAGE);
}
if (mInteropModuleRegistry != null
&& mInteropModuleRegistry.shouldReturnInteropModule(jsInterface)) {
return mInteropModuleRegistry.getInteropModule(jsInterface);
}
return mCatalystInstance.getJSModule(jsInterface);
}
@@ -546,4 +562,17 @@ public class ReactContext extends ContextWrapper {
Assertions.assertNotNull(mCatalystInstance).registerSegment(segmentId, path);
Assertions.assertNotNull(callback).invoke();
}
/**
* Register a {@link JavaScriptModule} within the Interop Layer so that can be consumed whenever
* getJSModule is invoked.
*
* <p>This method is internal to React Native and should not be used externally.
*/
public <T extends JavaScriptModule> void internal_registerInteropModule(
Class<T> interopModuleInterface, Object interopModule) {
if (mInteropModuleRegistry != null) {
mInteropModuleRegistry.registerInteropModule(interopModuleInterface, interopModule);
}
}
}
@@ -12,10 +12,33 @@ public interface UIManagerListener {
/**
* Called right before view updates are dispatched at the end of a batch. This is useful if a
* module needs to add UIBlocks to the queue before it is flushed.
*
* <p>This is called by Paper only.
*/
void willDispatchViewUpdates(UIManager uiManager);
/* Called right after view updates are dispatched for a frame. */
/**
* Called on UIThread right before view updates are executed.
*
* <p>This is called by Fabric only.
*/
void willMountItems(UIManager uiManager);
/**
* Called on UIThread right after view updates are executed.
*
* <p>This is called by Fabric only.
*/
void didMountItems(UIManager uiManager);
/**
* Called on UIThread right after view updates are dispatched for a frame. Note that this will be
* called for every frame even if there are no updates.
*
* <p>This is called by Fabric only.
*/
void didDispatchMountItems(UIManager uiManager);
/* Called right after scheduleMountItems is called in Fabric, after a new tree is committed. */
/**
* Called right after scheduleMountItems is called in Fabric, after a new tree is committed.
*
* <p>This is called by Fabric only.
*/
void didScheduleMountItems(UIManager uiManager);
}
@@ -0,0 +1,56 @@
/*
* 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.
*/
package com.facebook.react.bridge.interop;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.config.ReactFeatureFlags;
import java.util.HashMap;
/**
* A utility class that takes care of returning {@link JavaScriptModule} which are used for the
* Fabric Interop Layer. This allows us to override the returned classes once the user is invoking
* `ReactContext.getJsModule()`.
*
* <p>Currently we only support a `RCTEventEmitter` re-implementation, being `InteropEventEmitter`
* but this class can support other re-implementation in the future.
*/
public class InteropModuleRegistry {
@SuppressWarnings("rawtypes")
private final HashMap<Class, Object> supportedModules;
public InteropModuleRegistry() {
this.supportedModules = new HashMap<>();
}
public <T extends JavaScriptModule> boolean shouldReturnInteropModule(Class<T> requestedModule) {
return checkReactFeatureFlagsConditions() && supportedModules.containsKey(requestedModule);
}
@Nullable
public <T extends JavaScriptModule> T getInteropModule(Class<T> requestedModule) {
if (checkReactFeatureFlagsConditions()) {
//noinspection unchecked
return (T) supportedModules.get(requestedModule);
} else {
return null;
}
}
public <T extends JavaScriptModule> void registerInteropModule(
Class<T> interopModuleInterface, Object interopModule) {
if (checkReactFeatureFlagsConditions()) {
supportedModules.put(interopModuleInterface, interopModule);
}
}
private boolean checkReactFeatureFlagsConditions() {
return ReactFeatureFlags.enableFabricRenderer && ReactFeatureFlags.unstable_useFabricInterop;
}
}
@@ -34,6 +34,14 @@ public class ReactFeatureFlags {
*/
public static volatile boolean enableFabricRenderer = false;
/**
* Should this application enable the Fabric Interop Layer for Android? If yes, the application
* will behave so that it can accept non-Fabric components and render them on Fabric. This toggle
* is controlling extra logic such as custom event dispatching that are needed for the Fabric
* Interop Layer to work correctly.
*/
public static volatile boolean unstable_useFabricInterop = false;
/**
* Feature flag to enable the new bridgeless architecture. Note: Enabling this will force enable
* the following flags: `useTurboModules` & `enableFabricRenderer`.
@@ -75,6 +83,9 @@ public class ReactFeatureFlags {
/** Feature Flag to enable the pending event queue in fabric before mounting views */
public static boolean enableFabricPendingEventQueue = false;
/** Feature Flag to enable caching mechanism of text measurement at shadow node level */
public static boolean enableTextMeasureCachePerShadowNode = false;
/**
* Feature flag that controls how turbo modules are exposed to JS
*
@@ -31,6 +31,7 @@ object DefaultNewArchitectureEntryPoint {
) {
ReactFeatureFlags.useTurboModules = turboModulesEnabled
ReactFeatureFlags.enableFabricRenderer = fabricEnabled
ReactFeatureFlags.unstable_useFabricInterop = fabricEnabled
this.privateFabricEnabled = fabricEnabled
this.privateTurboModulesEnabled = turboModulesEnabled
@@ -7,6 +7,7 @@
package com.facebook.react.defaults
import android.os.Bundle
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.ReactRootView
@@ -43,4 +44,7 @@ open class DefaultReactActivityDelegate(
override fun createRootView(): ReactRootView =
ReactRootView(context).apply { setIsFabric(fabricEnabled) }
override fun createRootView(bundle: Bundle?): ReactRootView =
ReactRootView(context).apply { setIsFabric(fabricEnabled) }
}
@@ -24,6 +24,7 @@ import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
@@ -553,17 +554,30 @@ public abstract class DevSupportManagerBase implements DevSupportManager {
return;
}
final TextView textView = new TextView(getApplicationContext());
textView.setText("React Native DevMenu (" + getUniqueTag() + ")");
textView.setPadding(0, 50, 0, 0);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.BLACK);
textView.setTextSize(17);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
final LinearLayout header = new LinearLayout(getApplicationContext());
header.setOrientation(LinearLayout.VERTICAL);
final TextView title = new TextView(getApplicationContext());
title.setText("React Native Dev Menu (" + getUniqueTag() + ")");
title.setPadding(0, 50, 0, 0);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.DKGRAY);
title.setTextSize(16);
title.setTypeface(title.getTypeface(), Typeface.BOLD);
final TextView jsExecutorLabel = new TextView(getApplicationContext());
jsExecutorLabel.setText(getJSExecutorDescription());
jsExecutorLabel.setPadding(0, 20, 0, 0);
jsExecutorLabel.setGravity(Gravity.CENTER);
jsExecutorLabel.setTextColor(Color.GRAY);
jsExecutorLabel.setTextSize(14);
header.addView(title);
header.addView(jsExecutorLabel);
mDevOptionsDialog =
new AlertDialog.Builder(context)
.setCustomTitle(textView)
.setCustomTitle(header)
.setItems(
options.keySet().toArray(new String[0]),
new DialogInterface.OnClickListener() {
@@ -587,6 +601,10 @@ public abstract class DevSupportManagerBase implements DevSupportManager {
}
}
private String getJSExecutorDescription() {
return "Running " + getReactInstanceDevHelper().getJavaScriptExecutorFactory().toString();
}
/**
* {@link ReactInstanceDevCommandsHandler} is responsible for enabling/disabling dev support when
* a React view is attached/detached or when application state changes (e.g. the application is
@@ -56,6 +56,7 @@ import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.fabric.events.EventBeatManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.events.FabricEventEmitter;
import com.facebook.react.fabric.interop.InteropEventEmitter;
import com.facebook.react.fabric.mounting.MountItemDispatcher;
import com.facebook.react.fabric.mounting.MountingManager;
import com.facebook.react.fabric.mounting.SurfaceMountingManager;
@@ -81,6 +82,7 @@ import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.react.uimanager.events.EventCategoryDef;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.EventDispatcherImpl;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.react.views.text.TextLayoutManager;
import com.facebook.react.views.text.TextLayoutManagerMapBuffer;
import java.util.HashMap;
@@ -390,6 +392,11 @@ public class FabricUIManager implements UIManager, LifecycleEventListener {
ReactMarker.addFabricListener(mDevToolsReactPerfLogger);
}
if (ReactFeatureFlags.unstable_useFabricInterop) {
InteropEventEmitter interopEventEmitter = new InteropEventEmitter(mReactApplicationContext);
mReactApplicationContext.internal_registerInteropModule(
RCTEventEmitter.class, interopEventEmitter);
}
}
// This is called on the JS thread (see CatalystInstanceImpl).
@@ -1171,6 +1178,20 @@ public class FabricUIManager implements UIManager, LifecycleEventListener {
}
private class MountItemDispatchListener implements MountItemDispatcher.ItemDispatchListener {
@Override
public void willMountItems() {
for (UIManagerListener listener : mListeners) {
listener.willMountItems(FabricUIManager.this);
}
}
@Override
public void didMountItems() {
for (UIManagerListener listener : mListeners) {
listener.didMountItems(FabricUIManager.this);
}
}
@Override
public void didDispatchMountItems() {
for (UIManagerListener listener : mListeners) {
@@ -0,0 +1,41 @@
/*
* 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.
*/
package com.facebook.react.fabric.interop;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.events.Event;
/**
* An {@link Event} class used by the {@link InteropEventEmitter}. This class is just holding the
* event name and the data which is received by the `receiveEvent` method and will be passed over
* the the {@link com.facebook.react.uimanager.events.EventDispatcher}
*/
class InteropEvent extends Event<InteropEvent> {
private final String mName;
private final WritableMap mEventData;
InteropEvent(String name, @Nullable WritableMap eventData, int surfaceId, int viewTag) {
super(surfaceId, viewTag);
mName = name;
mEventData = eventData;
}
@Override
public String getEventName() {
return mName;
}
@Override
@VisibleForTesting
public WritableMap getEventData() {
return mEventData;
}
}
@@ -0,0 +1,65 @@
/*
* 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.
*/
package com.facebook.react.fabric.interop;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.RCTEventEmitter;
/**
* A reimplementation of {@link RCTEventEmitter} which is using a {@link EventDispatcher} under the
* hood.
*
* <p>On Fabric, you're supposed to use {@link EventDispatcher} to dispatch events. However, we
* provide an interop layer for non-Fabric migrated components.
*
* <p>This instance will be returned if the user is invoking `context.getJsModule(RCTEventEmitter)
* and is providing support for the `receiveEvent` method, so that non-Fabric ViewManagers can
* continue to deliver events also when Fabric is turned on.
*/
public class InteropEventEmitter implements RCTEventEmitter {
private final ReactContext mReactContext;
private @Nullable EventDispatcher mEventDispatcherOverride;
public InteropEventEmitter(ReactContext reactContext) {
mReactContext = reactContext;
}
@Override
public void receiveEvent(int targetReactTag, String eventName, @Nullable WritableMap eventData) {
EventDispatcher dispatcher;
if (mEventDispatcherOverride != null) {
dispatcher = mEventDispatcherOverride;
} else {
dispatcher = UIManagerHelper.getEventDispatcherForReactTag(mReactContext, targetReactTag);
}
int surfaceId = UIManagerHelper.getSurfaceId(mReactContext);
if (dispatcher != null) {
dispatcher.dispatchEvent(new InteropEvent(eventName, eventData, surfaceId, targetReactTag));
}
}
@Override
public void receiveTouches(
String eventName, WritableArray touches, WritableArray changedIndices) {
throw new UnsupportedOperationException(
"EventEmitter#receiveTouches is not supported by the Fabric Interop Layer");
}
@VisibleForTesting
void overrideEventDispatcher(EventDispatcher eventDispatcherOverride) {
mEventDispatcherOverride = eventDispatcherOverride;
}
}
@@ -193,6 +193,8 @@ public class MountItemDispatcher {
return false;
}
mItemDispatchListener.willMountItems();
// As an optimization, execute all ViewCommands first
// This should be:
// 1) Performant: ViewCommands are often a replacement for SetNativeProps, which we've always
@@ -299,6 +301,9 @@ public class MountItemDispatcher {
}
mBatchedExecutionTime += SystemClock.uptimeMillis() - batchedExecutionStartTime;
}
mItemDispatchListener.didMountItems();
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
return true;
@@ -415,6 +420,10 @@ public class MountItemDispatcher {
}
public interface ItemDispatchListener {
void willMountItems();
void didMountItems();
void didDispatchMountItems();
}
}
@@ -15,8 +15,8 @@ import java.util.Map;
public class ReactNativeVersion {
public static final Map<String, Object> VERSION = MapBuilder.<String, Object>of(
"major", 1000,
"minor", 0,
"major", 0,
"minor", 72,
"patch", 0,
"prerelease", null);
"prerelease", "rc.3");
}
@@ -50,6 +50,7 @@ public class ThemedReactContext extends ReactContext {
if (reactApplicationContext.hasCatalystInstance()) {
initializeWithInstance(reactApplicationContext.getCatalystInstance());
}
initializeInteropModules(reactApplicationContext);
mReactApplicationContext = reactApplicationContext;
mModuleName = moduleName;
mSurfaceId = surfaceId;
@@ -10,11 +10,15 @@ package com.facebook.react.uimanager;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.systrace.SystraceMessage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Helps generate constants map for {@link UIManagerModule} by collecting and merging constants from
@@ -113,6 +117,13 @@ import java.util.Map;
Map viewManagerBubblingEvents = viewManager.getExportedCustomBubblingEventTypeConstants();
if (viewManagerBubblingEvents != null) {
if (ReactFeatureFlags.enableFabricRenderer && ReactFeatureFlags.unstable_useFabricInterop) {
// For Fabric, events needs to be fired with a "top" prefix.
// For the sake of Fabric Interop, here we normalize events adding "top" in their
// name if the user hasn't provided it.
normalizeEventTypes(viewManagerBubblingEvents);
}
recursiveMerge(cumulativeBubblingEventTypes, viewManagerBubblingEvents);
recursiveMerge(viewManagerBubblingEvents, defaultBubblingEvents);
viewManagerConstants.put(BUBBLING_EVENTS_KEY, viewManagerBubblingEvents);
@@ -145,6 +156,27 @@ import java.util.Map;
return viewManagerConstants;
}
@VisibleForTesting
/* package */ static void normalizeEventTypes(Map events) {
if (events == null) {
return;
}
Set<String> keysToNormalize = new HashSet<>();
for (Object key : events.keySet()) {
if (key instanceof String) {
String keyString = (String) key;
if (!keyString.startsWith("top")) {
keysToNormalize.add(keyString);
}
}
}
for (String oldKey : keysToNormalize) {
Object value = events.get(oldKey);
String newKey = "top" + oldKey.substring(0, 1).toUpperCase() + oldKey.substring(1);
events.put(newKey, value);
}
}
/** Merges {@param source} map into {@param dest} map recursively */
private static void recursiveMerge(@Nullable Map dest, @Nullable Map source) {
if (dest == null || source == null || source.isEmpty()) {
@@ -18,6 +18,7 @@ import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UIManagerListener;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.common.UIManagerType;
import com.facebook.react.uimanager.common.ViewUtil;
import com.facebook.react.views.scroll.ReactScrollViewHelper.HasSmoothScroll;
import com.facebook.react.views.view.ReactViewGroup;
@@ -89,6 +90,14 @@ public class MaintainVisibleScrollPositionHelper<ScrollViewT extends ViewGroup &
* been updated.
*/
public void updateScrollPosition() {
// On Fabric this will be called internally in `didMountItems`.
if (ViewUtil.getUIManagerType(mScrollView.getId()) == UIManagerType.FABRIC) {
return;
}
updateScrollPositionInternal();
}
private void updateScrollPositionInternal() {
if (mConfig == null || mFirstVisibleView == null || mPrevFirstVisibleFrame == null) {
return;
}
@@ -169,6 +178,16 @@ public class MaintainVisibleScrollPositionHelper<ScrollViewT extends ViewGroup &
});
}
@Override
public void willMountItems(UIManager uiManager) {
computeTargetView();
}
@Override
public void didMountItems(UIManager uiManager) {
updateScrollPositionInternal();
}
@Override
public void didDispatchMountItems(UIManager uiManager) {
// noop
@@ -37,6 +37,10 @@ public class CustomLetterSpacingSpan extends MetricAffectingSpan implements Reac
apply(paint);
}
public float getSpacing() {
return mLetterSpacing;
}
private void apply(TextPaint paint) {
if (!Float.isNaN(mLetterSpacing)) {
paint.setLetterSpacing(mLetterSpacing);
@@ -71,6 +71,10 @@ public class CustomStyleSpan extends MetricAffectingSpan implements ReactSpan {
return mFontFamily;
}
public @Nullable String getFontFeatureSettings() {
return mFeatureSettings;
}
private static void apply(
Paint paint,
int style,
@@ -31,8 +31,6 @@ public class ReactTextUpdate {
private final int mSelectionEnd;
private final int mJustificationMode;
public boolean mContainsMultipleFragments;
/**
* @deprecated Use a non-deprecated constructor for ReactTextUpdate instead. This one remains
* because it's being used by a unit test that isn't currently open source.
@@ -142,13 +140,11 @@ public class ReactTextUpdate {
int jsEventCounter,
int textAlign,
int textBreakStrategy,
int justificationMode,
boolean containsMultipleFragments) {
int justificationMode) {
ReactTextUpdate reactTextUpdate =
new ReactTextUpdate(
text, jsEventCounter, false, textAlign, textBreakStrategy, justificationMode);
reactTextUpdate.mContainsMultipleFragments = containsMultipleFragments;
return reactTextUpdate;
}
@@ -11,6 +11,8 @@ import static com.facebook.react.uimanager.UIManagerHelper.getReactContext;
import static com.facebook.react.views.text.TextAttributeProps.UNSET;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
@@ -50,15 +52,19 @@ import com.facebook.react.views.text.CustomLetterSpacingSpan;
import com.facebook.react.views.text.CustomLineHeightSpan;
import com.facebook.react.views.text.CustomStyleSpan;
import com.facebook.react.views.text.ReactAbsoluteSizeSpan;
import com.facebook.react.views.text.ReactBackgroundColorSpan;
import com.facebook.react.views.text.ReactForegroundColorSpan;
import com.facebook.react.views.text.ReactSpan;
import com.facebook.react.views.text.ReactStrikethroughSpan;
import com.facebook.react.views.text.ReactTextUpdate;
import com.facebook.react.views.text.ReactTypefaceUtils;
import com.facebook.react.views.text.ReactUnderlineSpan;
import com.facebook.react.views.text.TextAttributes;
import com.facebook.react.views.text.TextInlineImageSpan;
import com.facebook.react.views.text.TextLayoutManager;
import com.facebook.react.views.view.ReactViewBackgroundManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* A wrapper around the EditText that lets us better control what happens when an EditText gets
@@ -82,7 +88,6 @@ public class ReactEditText extends AppCompatEditText
// *TextChanged events should be triggered. This is less expensive than removing the text
// listeners and adding them back again after the text change is completed.
protected boolean mIsSettingTextFromJS;
protected boolean mIsSettingTextFromCacheUpdate = false;
private int mDefaultGravityHorizontal;
private int mDefaultGravityVertical;
@@ -362,7 +367,7 @@ public class ReactEditText extends AppCompatEditText
}
super.onSelectionChanged(selStart, selEnd);
if (!mIsSettingTextFromCacheUpdate && mSelectionWatcher != null && hasFocus()) {
if (mSelectionWatcher != null && hasFocus()) {
mSelectionWatcher.onSelectionChanged(selStart, selEnd);
}
}
@@ -512,6 +517,14 @@ public class ReactEditText extends AppCompatEditText
}
}
@Override
public void setFontFeatureSettings(String fontFeatureSettings) {
if (!Objects.equals(fontFeatureSettings, getFontFeatureSettings())) {
super.setFontFeatureSettings(fontFeatureSettings);
mTypefaceDirty = true;
}
}
public void maybeUpdateTypeface() {
if (!mTypefaceDirty) {
return;
@@ -523,6 +536,17 @@ public class ReactEditText extends AppCompatEditText
ReactTypefaceUtils.applyStyles(
getTypeface(), mFontStyle, mFontWeight, mFontFamily, getContext().getAssets());
setTypeface(newTypeface);
// Match behavior of CustomStyleSpan and enable SUBPIXEL_TEXT_FLAG when setting anything
// nonstandard
if (mFontStyle != UNSET
|| mFontWeight != UNSET
|| mFontFamily != null
|| getFontFeatureSettings() != null) {
setPaintFlags(getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
} else {
setPaintFlags(getPaintFlags() & (~Paint.SUBPIXEL_TEXT_FLAG));
}
}
// VisibleForTesting from {@link TextInputEventsTestCase}.
@@ -584,10 +608,8 @@ public class ReactEditText extends AppCompatEditText
SpannableStringBuilder spannableStringBuilder =
new SpannableStringBuilder(reactTextUpdate.getText());
manageSpans(spannableStringBuilder, reactTextUpdate.mContainsMultipleFragments);
// Mitigation for https://github.com/facebook/react-native/issues/35936 (S318090)
stripAttributeEquivalentSpans(spannableStringBuilder);
manageSpans(spannableStringBuilder);
stripStyleEquivalentSpans(spannableStringBuilder);
mContainsImages = reactTextUpdate.containsImages();
@@ -615,7 +637,7 @@ public class ReactEditText extends AppCompatEditText
}
// Update cached spans (in Fabric only).
updateCachedSpannable(false);
updateCachedSpannable();
}
/**
@@ -624,8 +646,7 @@ public class ReactEditText extends AppCompatEditText
* will adapt to the new text, hence why {@link SpannableStringBuilder#replace} never removes
* them.
*/
private void manageSpans(
SpannableStringBuilder spannableStringBuilder, boolean skipAddSpansForMeasurements) {
private void manageSpans(SpannableStringBuilder spannableStringBuilder) {
Object[] spans = getText().getSpans(0, length(), Object.class);
for (int spanIdx = 0; spanIdx < spans.length; spanIdx++) {
Object span = spans[spanIdx];
@@ -653,58 +674,170 @@ public class ReactEditText extends AppCompatEditText
spannableStringBuilder.setSpan(span, spanStart, spanEnd, spanFlags);
}
}
// In Fabric only, apply necessary styles to entire span
// If the Spannable was constructed from multiple fragments, we don't apply any spans that could
// impact the whole Spannable, because that would override "local" styles per-fragment
if (!skipAddSpansForMeasurements) {
addSpansForMeasurement(getText());
}
}
private void stripAttributeEquivalentSpans(SpannableStringBuilder sb) {
// We have already set a font size on the EditText itself. We can safely remove sizing spans
// which are the same as the set font size, and not otherwise overlapped.
final int effectiveFontSize = mTextAttributes.getEffectiveFontSize();
ReactAbsoluteSizeSpan[] spans = sb.getSpans(0, sb.length(), ReactAbsoluteSizeSpan.class);
// TODO: Replace with Predicate<T> and lambdas once Java 8 builds in OSS
interface SpanPredicate<T> {
boolean test(T span);
}
outerLoop:
for (ReactAbsoluteSizeSpan span : spans) {
ReactAbsoluteSizeSpan[] overlappingSpans =
sb.getSpans(sb.getSpanStart(span), sb.getSpanEnd(span), ReactAbsoluteSizeSpan.class);
/**
* Remove spans from the SpannableStringBuilder which can be represented by TextAppearance
* attributes on the underlying EditText. This works around instability on Samsung devices with
* the presence of spans https://github.com/facebook/react-native/issues/35936 (S318090)
*/
private void stripStyleEquivalentSpans(SpannableStringBuilder sb) {
stripSpansOfKind(
sb,
ReactAbsoluteSizeSpan.class,
new SpanPredicate<ReactAbsoluteSizeSpan>() {
@Override
public boolean test(ReactAbsoluteSizeSpan span) {
return span.getSize() == mTextAttributes.getEffectiveFontSize();
}
});
for (ReactAbsoluteSizeSpan overlappingSpan : overlappingSpans) {
if (span.getSize() != effectiveFontSize) {
continue outerLoop;
}
stripSpansOfKind(
sb,
ReactBackgroundColorSpan.class,
new SpanPredicate<ReactBackgroundColorSpan>() {
@Override
public boolean test(ReactBackgroundColorSpan span) {
return span.getBackgroundColor() == mReactBackgroundManager.getBackgroundColor();
}
});
stripSpansOfKind(
sb,
ReactForegroundColorSpan.class,
new SpanPredicate<ReactForegroundColorSpan>() {
@Override
public boolean test(ReactForegroundColorSpan span) {
return span.getForegroundColor() == getCurrentTextColor();
}
});
stripSpansOfKind(
sb,
ReactStrikethroughSpan.class,
new SpanPredicate<ReactStrikethroughSpan>() {
@Override
public boolean test(ReactStrikethroughSpan span) {
return (getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) != 0;
}
});
stripSpansOfKind(
sb,
ReactUnderlineSpan.class,
new SpanPredicate<ReactUnderlineSpan>() {
@Override
public boolean test(ReactUnderlineSpan span) {
return (getPaintFlags() & Paint.UNDERLINE_TEXT_FLAG) != 0;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
stripSpansOfKind(
sb,
CustomLetterSpacingSpan.class,
new SpanPredicate<CustomLetterSpacingSpan>() {
@Override
public boolean test(CustomLetterSpacingSpan span) {
return span.getSpacing() == mTextAttributes.getEffectiveLetterSpacing();
}
});
}
stripSpansOfKind(
sb,
CustomStyleSpan.class,
new SpanPredicate<CustomStyleSpan>() {
@Override
public boolean test(CustomStyleSpan span) {
return span.getStyle() == mFontStyle
&& Objects.equals(span.getFontFamily(), mFontFamily)
&& span.getWeight() == mFontWeight
&& Objects.equals(span.getFontFeatureSettings(), getFontFeatureSettings());
}
});
}
private <T> void stripSpansOfKind(
SpannableStringBuilder sb, Class<T> clazz, SpanPredicate<T> shouldStrip) {
T[] spans = sb.getSpans(0, sb.length(), clazz);
for (T span : spans) {
if (shouldStrip.test(span)) {
sb.removeSpan(span);
}
sb.removeSpan(span);
}
}
private void unstripAttributeEquivalentSpans(
SpannableStringBuilder workingText, Spannable originalText) {
// We must add spans back for Fabric to be able to measure, at lower precedence than any
// existing spans. Remove all spans, add the attributes, then re-add the spans over
workingText.append(originalText);
/**
* Copy styles represented as attributes to the underlying span, for later measurement or other
* usage outside the ReactEditText.
*/
private void addSpansFromStyleAttributes(SpannableStringBuilder workingText) {
int spanFlags = Spannable.SPAN_INCLUSIVE_INCLUSIVE;
for (Object span : workingText.getSpans(0, workingText.length(), Object.class)) {
workingText.removeSpan(span);
}
// Set all bits for SPAN_PRIORITY so that this span has the highest possible priority
// (least precedence). This ensures the span is behind any overlapping spans.
spanFlags |= Spannable.SPAN_PRIORITY;
workingText.setSpan(
new ReactAbsoluteSizeSpan(mTextAttributes.getEffectiveFontSize()),
0,
workingText.length(),
Spanned.SPAN_INCLUSIVE_INCLUSIVE);
spanFlags);
for (Object span : originalText.getSpans(0, originalText.length(), Object.class)) {
workingText.setSpan(
new ReactForegroundColorSpan(getCurrentTextColor()), 0, workingText.length(), spanFlags);
int backgroundColor = mReactBackgroundManager.getBackgroundColor();
if (backgroundColor != Color.TRANSPARENT) {
workingText.setSpan(
span,
originalText.getSpanStart(span),
originalText.getSpanEnd(span),
originalText.getSpanFlags(span));
new ReactBackgroundColorSpan(backgroundColor), 0, workingText.length(), spanFlags);
}
if ((getPaintFlags() & Paint.STRIKE_THRU_TEXT_FLAG) != 0) {
workingText.setSpan(new ReactStrikethroughSpan(), 0, workingText.length(), spanFlags);
}
if ((getPaintFlags() & Paint.UNDERLINE_TEXT_FLAG) != 0) {
workingText.setSpan(new ReactUnderlineSpan(), 0, workingText.length(), spanFlags);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
float effectiveLetterSpacing = mTextAttributes.getEffectiveLetterSpacing();
if (!Float.isNaN(effectiveLetterSpacing)) {
workingText.setSpan(
new CustomLetterSpacingSpan(effectiveLetterSpacing),
0,
workingText.length(),
spanFlags);
}
}
if (mFontStyle != UNSET
|| mFontWeight != UNSET
|| mFontFamily != null
|| getFontFeatureSettings() != null) {
workingText.setSpan(
new CustomStyleSpan(
mFontStyle,
mFontWeight,
getFontFeatureSettings(),
mFontFamily,
getContext().getAssets()),
0,
workingText.length(),
spanFlags);
}
float lineHeight = mTextAttributes.getEffectiveLineHeight();
if (!Float.isNaN(lineHeight)) {
workingText.setSpan(new CustomLineHeightSpan(lineHeight), 0, workingText.length(), spanFlags);
}
}
@@ -724,73 +857,6 @@ public class ReactEditText extends AppCompatEditText
return true;
}
// This is hacked in for Fabric. When we delete non-Fabric code, we might be able to simplify or
// clean this up a bit.
private void addSpansForMeasurement(Spannable spannable) {
if (!mFabricViewStateManager.hasStateWrapper()) {
return;
}
boolean originalDisableTextDiffing = mDisableTextDiffing;
mDisableTextDiffing = true;
int start = 0;
int end = spannable.length();
// Remove duplicate spans we might add here
Object[] spans = spannable.getSpans(0, length(), Object.class);
for (Object span : spans) {
int spanFlags = spannable.getSpanFlags(span);
boolean isInclusive =
(spanFlags & Spanned.SPAN_INCLUSIVE_INCLUSIVE) == Spanned.SPAN_INCLUSIVE_INCLUSIVE
|| (spanFlags & Spanned.SPAN_INCLUSIVE_EXCLUSIVE) == Spanned.SPAN_INCLUSIVE_EXCLUSIVE;
if (isInclusive
&& span instanceof ReactSpan
&& spannable.getSpanStart(span) == start
&& spannable.getSpanEnd(span) == end) {
spannable.removeSpan(span);
}
}
List<TextLayoutManager.SetSpanOperation> ops = new ArrayList<>();
if (!Float.isNaN(mTextAttributes.getLetterSpacing())) {
ops.add(
new TextLayoutManager.SetSpanOperation(
start, end, new CustomLetterSpacingSpan(mTextAttributes.getLetterSpacing())));
}
ops.add(
new TextLayoutManager.SetSpanOperation(
start, end, new ReactAbsoluteSizeSpan((int) mTextAttributes.getEffectiveFontSize())));
if (mFontStyle != UNSET || mFontWeight != UNSET || mFontFamily != null) {
ops.add(
new TextLayoutManager.SetSpanOperation(
start,
end,
new CustomStyleSpan(
mFontStyle,
mFontWeight,
null, // TODO: do we need to support FontFeatureSettings / fontVariant?
mFontFamily,
getReactContext(ReactEditText.this).getAssets())));
}
if (!Float.isNaN(mTextAttributes.getEffectiveLineHeight())) {
ops.add(
new TextLayoutManager.SetSpanOperation(
start, end, new CustomLineHeightSpan(mTextAttributes.getEffectiveLineHeight())));
}
int priority = 0;
for (TextLayoutManager.SetSpanOperation op : ops) {
// Actual order of calling {@code execute} does NOT matter,
// but the {@code priority} DOES matter.
op.execute(spannable, priority);
priority++;
}
mDisableTextDiffing = originalDisableTextDiffing;
}
protected boolean showSoftKeyboard() {
return mInputMethodManager.showSoftInput(this, 0);
}
@@ -1060,7 +1126,9 @@ public class ReactEditText extends AppCompatEditText
float effectiveLetterSpacing = mTextAttributes.getEffectiveLetterSpacing();
if (!Float.isNaN(effectiveLetterSpacing)) {
setLetterSpacing(effectiveLetterSpacing);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setLetterSpacing(effectiveLetterSpacing);
}
}
}
@@ -1075,7 +1143,7 @@ public class ReactEditText extends AppCompatEditText
* TextLayoutManager.java with some very minor modifications. There's some duplication between
* here and TextLayoutManager, so there might be an opportunity for refactor.
*/
private void updateCachedSpannable(boolean resetStyles) {
private void updateCachedSpannable() {
// Noops in non-Fabric
if (mFabricViewStateManager == null || !mFabricViewStateManager.hasStateWrapper()) {
return;
@@ -1085,12 +1153,6 @@ public class ReactEditText extends AppCompatEditText
return;
}
if (resetStyles) {
mIsSettingTextFromCacheUpdate = true;
addSpansForMeasurement(getText());
mIsSettingTextFromCacheUpdate = false;
}
Editable currentText = getText();
boolean haveText = currentText != null && currentText.length() > 0;
@@ -1132,8 +1194,7 @@ public class ReactEditText extends AppCompatEditText
// ...
// - android.app.Activity.dispatchKeyEvent (Activity.java:3447)
try {
Spannable text = (Spannable) currentText.subSequence(0, currentText.length());
unstripAttributeEquivalentSpans(sb, text);
sb.append(currentText.subSequence(0, currentText.length()));
} catch (IndexOutOfBoundsException e) {
ReactSoftExceptionLogger.logSoftException(TAG, e);
}
@@ -1149,11 +1210,9 @@ public class ReactEditText extends AppCompatEditText
// Measure something so we have correct height, even if there's no string.
sb.append("I");
}
// Make sure that all text styles are applied when we're measurable the hint or "blank" text
addSpansForMeasurement(sb);
}
addSpansFromStyleAttributes(sb);
TextLayoutManager.setCachedSpannabledForTag(getId(), sb);
}
@@ -1168,7 +1227,7 @@ public class ReactEditText extends AppCompatEditText
private class TextWatcherDelegator implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (!mIsSettingTextFromCacheUpdate && !mIsSettingTextFromJS && mListeners != null) {
if (!mIsSettingTextFromJS && mListeners != null) {
for (TextWatcher listener : mListeners) {
listener.beforeTextChanged(s, start, count, after);
}
@@ -1182,23 +1241,20 @@ public class ReactEditText extends AppCompatEditText
TAG, "onTextChanged[" + getId() + "]: " + s + " " + start + " " + before + " " + count);
}
if (!mIsSettingTextFromCacheUpdate) {
if (!mIsSettingTextFromJS && mListeners != null) {
for (TextWatcher listener : mListeners) {
listener.onTextChanged(s, start, before, count);
}
if (!mIsSettingTextFromJS && mListeners != null) {
for (TextWatcher listener : mListeners) {
listener.onTextChanged(s, start, before, count);
}
updateCachedSpannable(
!mIsSettingTextFromJS && !mIsSettingTextFromState && start == 0 && before == 0);
}
updateCachedSpannable();
onContentSizeChange();
}
@Override
public void afterTextChanged(Editable s) {
if (!mIsSettingTextFromCacheUpdate && !mIsSettingTextFromJS && mListeners != null) {
if (!mIsSettingTextFromJS && mListeners != null) {
for (TextWatcher listener : mListeners) {
listener.afterTextChanged(s);
}
@@ -13,6 +13,7 @@ import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.BlendMode;
import android.graphics.BlendModeColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
@@ -68,6 +69,7 @@ import com.facebook.react.views.text.DefaultStyleValuesUtil;
import com.facebook.react.views.text.ReactBaseTextShadowNode;
import com.facebook.react.views.text.ReactTextUpdate;
import com.facebook.react.views.text.ReactTextViewManagerCallback;
import com.facebook.react.views.text.ReactTypefaceUtils;
import com.facebook.react.views.text.TextAttributeProps;
import com.facebook.react.views.text.TextInlineImageSpan;
import com.facebook.react.views.text.TextLayoutManager;
@@ -412,6 +414,11 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
view.setFontStyle(fontStyle);
}
@ReactProp(name = ViewProps.FONT_VARIANT)
public void setFontVariant(ReactEditText view, @Nullable ReadableArray fontVariant) {
view.setFontFeatureSettings(ReactTypefaceUtils.parseFontVariant(fontVariant));
}
@ReactProp(name = ViewProps.INCLUDE_FONT_PADDING, defaultBoolean = true)
public void setIncludeFontPadding(ReactEditText view, boolean includepad) {
view.setIncludeFontPadding(includepad);
@@ -935,6 +942,20 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
view.setAutoFocus(autoFocus);
}
@ReactProp(name = ViewProps.TEXT_DECORATION_LINE)
public void setTextDecorationLine(ReactEditText view, @Nullable String textDecorationLineString) {
view.setPaintFlags(
view.getPaintFlags() & ~(Paint.STRIKE_THRU_TEXT_FLAG | Paint.UNDERLINE_TEXT_FLAG));
for (String token : textDecorationLineString.split(" ")) {
if (token.equals("underline")) {
view.setPaintFlags(view.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
} else if (token.equals("line-through")) {
view.setPaintFlags(view.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
}
@ReactPropGroup(
names = {
ViewProps.BORDER_WIDTH,
@@ -1329,9 +1350,6 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
TextLayoutManager.getOrCreateSpannableForText(
view.getContext(), attributedString, mReactTextViewManagerCallback);
boolean containsMultipleFragments =
attributedString.getArray("fragments").toArrayList().size() > 1;
int textBreakStrategy =
TextAttributeProps.getTextBreakStrategy(
paragraphAttributes.getString(ViewProps.TEXT_BREAK_STRATEGY));
@@ -1344,8 +1362,7 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
TextAttributeProps.getTextAlignment(
props, TextLayoutManager.isRTL(attributedString), view.getGravityHorizontal()),
textBreakStrategy,
TextAttributeProps.getJustificationMode(props, currentJustificationMode),
containsMultipleFragments);
TextAttributeProps.getJustificationMode(props, currentJustificationMode));
}
public Object getReactTextUpdate(ReactEditText view, ReactStylesDiffMap props, MapBuffer state) {
@@ -1366,9 +1383,6 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
TextLayoutManagerMapBuffer.getOrCreateSpannableForText(
view.getContext(), attributedString, mReactTextViewManagerCallback);
boolean containsMultipleFragments =
attributedString.getMapBuffer(TextLayoutManagerMapBuffer.AS_KEY_FRAGMENTS).getCount() > 1;
int textBreakStrategy =
TextAttributeProps.getTextBreakStrategy(
paragraphAttributes.getString(TextLayoutManagerMapBuffer.PA_KEY_TEXT_BREAK_STRATEGY));
@@ -1381,7 +1395,6 @@ public class ReactTextInputManager extends BaseViewManager<ReactEditText, Layout
TextAttributeProps.getTextAlignment(
props, TextLayoutManagerMapBuffer.isRTL(attributedString), view.getGravityHorizontal()),
textBreakStrategy,
TextAttributeProps.getJustificationMode(props, currentJustificationMode),
containsMultipleFragments);
TextAttributeProps.getJustificationMode(props, currentJustificationMode));
}
}
@@ -19,6 +19,7 @@ public class ReactViewBackgroundManager {
private @Nullable ReactViewBackgroundDrawable mReactBackgroundDrawable;
private View mView;
private int mColor = Color.TRANSPARENT;
public ReactViewBackgroundManager(View view) {
this.mView = view;
@@ -56,6 +57,10 @@ public class ReactViewBackgroundManager {
}
}
public int getBackgroundColor() {
return mColor;
}
public void setBorderWidth(int position, float width) {
getOrCreateReactViewBackground().setBorderWidth(position, width);
}
@@ -429,6 +429,9 @@ void Binding::installFabricUIManager(
"CalculateTransformedFramesEnabled",
getFeatureFlagValue("calculateTransformedFramesEnabled"));
CoreFeatures::cacheLastTextMeasurement =
getFeatureFlagValue("enableTextMeasureCachePerShadowNode");
// Props setter pattern feature
CoreFeatures::enablePropIteratorSetter =
getFeatureFlagValue("enableCppPropsIteratorSetter");
@@ -0,0 +1,23 @@
/*
* 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.
*/
package com.facebook.react.bridge.interop;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
public class FakeRCTEventEmitter implements RCTEventEmitter {
@Override
public void receiveEvent(int targetReactTag, String eventName, @Nullable WritableMap event) {}
@Override
public void receiveTouches(
String eventName, WritableArray touches, WritableArray changedIndices) {}
}
@@ -0,0 +1,92 @@
/*
* 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.
*/
package com.facebook.react.bridge.interop;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.modules.core.JSTimers;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import org.junit.Before;
import org.junit.Test;
public class InteropModuleRegistryTest {
InteropModuleRegistry underTest;
@Before
public void setup() {
underTest = new InteropModuleRegistry();
}
@Test
public void shouldReturnInteropModule_withFabricDisabled_returnsFalse() {
ReactFeatureFlags.enableFabricRenderer = false;
assertFalse(underTest.shouldReturnInteropModule(RCTEventEmitter.class));
}
@Test
public void shouldReturnInteropModule_withFabricInteropDisabled_returnsFalse() {
ReactFeatureFlags.enableFabricRenderer = true;
ReactFeatureFlags.unstable_useFabricInterop = false;
assertFalse(underTest.shouldReturnInteropModule(RCTEventEmitter.class));
}
@Test
public void shouldReturnInteropModule_withUnregisteredClass_returnsFalse() {
ReactFeatureFlags.enableFabricRenderer = true;
ReactFeatureFlags.unstable_useFabricInterop = true;
assertFalse(underTest.shouldReturnInteropModule(JSTimers.class));
}
@Test
public void shouldReturnInteropModule_withRegisteredClass_returnsTrue() {
ReactFeatureFlags.enableFabricRenderer = true;
ReactFeatureFlags.unstable_useFabricInterop = true;
underTest.registerInteropModule(RCTEventEmitter.class, new FakeRCTEventEmitter());
assertTrue(underTest.shouldReturnInteropModule(RCTEventEmitter.class));
}
@Test
public void getInteropModule_withRegisteredClassAndInvalidFlags_returnsNull() {
ReactFeatureFlags.enableFabricRenderer = false;
ReactFeatureFlags.unstable_useFabricInterop = false;
underTest.registerInteropModule(RCTEventEmitter.class, new FakeRCTEventEmitter());
RCTEventEmitter interopModule = underTest.getInteropModule(RCTEventEmitter.class);
assertNull(interopModule);
}
@Test
public void getInteropModule_withRegisteredClassAndValidFlags_returnsInteropModule() {
ReactFeatureFlags.enableFabricRenderer = true;
ReactFeatureFlags.unstable_useFabricInterop = true;
underTest.registerInteropModule(RCTEventEmitter.class, new FakeRCTEventEmitter());
RCTEventEmitter interopModule = underTest.getInteropModule(RCTEventEmitter.class);
assertTrue(interopModule instanceof FakeRCTEventEmitter);
}
@Test
public void getInteropModule_withUnregisteredClass_returnsNull() {
ReactFeatureFlags.enableFabricRenderer = true;
ReactFeatureFlags.unstable_useFabricInterop = true;
JSTimers missingModule = underTest.getInteropModule(JSTimers.class);
assertNull(missingModule);
}
}
@@ -0,0 +1,55 @@
/*
* 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.
*/
package com.facebook.react.fabric.interop;
import com.facebook.react.uimanager.events.BatchEventDispatchedListener;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.EventDispatcherListener;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.facebook.react.uimanager.events.RCTModernEventEmitter;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("rawtypes")
public class FakeEventDispatcher implements EventDispatcher {
List<Event> recordedDispatchedEvents = new ArrayList<>();
@Override
public void dispatchEvent(Event event) {
recordedDispatchedEvents.add(event);
}
@Override
public void dispatchAllEvents() {}
@Override
public void addListener(EventDispatcherListener listener) {}
@Override
public void removeListener(EventDispatcherListener listener) {}
@Override
public void addBatchEventDispatchedListener(BatchEventDispatchedListener listener) {}
@Override
public void removeBatchEventDispatchedListener(BatchEventDispatchedListener listener) {}
@Override
public void registerEventEmitter(int uiManagerType, RCTEventEmitter eventEmitter) {}
@Override
public void registerEventEmitter(int uiManagerType, RCTModernEventEmitter eventEmitter) {}
@Override
public void unregisterEventEmitter(int uiManagerType) {}
@Override
public void onCatalystInstanceDestroyed() {}
}
@@ -0,0 +1,66 @@
/*
* 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.
*/
package com.facebook.react.fabric.interop;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
@RunWith(RobolectricTestRunner.class)
public class InteropEventEmitterTest {
ReactContext mReactContext;
FakeEventDispatcher mEventDispatcher;
@Before
public void setup() {
mReactContext = new ReactApplicationContext(RuntimeEnvironment.application);
mEventDispatcher = new FakeEventDispatcher();
}
@Test
public void receiveEvent_dispatchesCorrectly() {
InteropEventEmitter eventEmitter = new InteropEventEmitter(mReactContext);
eventEmitter.overrideEventDispatcher(mEventDispatcher);
eventEmitter.receiveEvent(42, "onTest", null);
assertEquals(1, mEventDispatcher.recordedDispatchedEvents.size());
assertEquals("onTest", mEventDispatcher.recordedDispatchedEvents.get(0).getEventName());
assertEquals(InteropEvent.class, mEventDispatcher.recordedDispatchedEvents.get(0).getClass());
}
@Test
public void receiveEvent_dataIsPreserved() {
InteropEventEmitter eventEmitter = new InteropEventEmitter(mReactContext);
eventEmitter.overrideEventDispatcher(mEventDispatcher);
WritableMap eventData = JavaOnlyMap.of("color", "indigo");
eventEmitter.receiveEvent(42, "onTest", eventData);
InteropEvent event = (InteropEvent) mEventDispatcher.recordedDispatchedEvents.get(0);
WritableMap dispatchedEventData = event.getEventData();
assertNotNull(dispatchedEventData);
assertEquals("indigo", dispatchedEventData.getString("color"));
}
@Test(expected = UnsupportedOperationException.class)
public void receiveTouches_isNotSupported() {
InteropEventEmitter eventEmitter = new InteropEventEmitter(mReactContext);
eventEmitter.receiveTouches("a touch", null, null);
}
}
@@ -0,0 +1,89 @@
/*
* 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.
*/
package com.facebook.react.uimanager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.facebook.react.common.MapBuilder;
import java.util.Map;
import org.junit.Test;
public class UIManagerModuleConstantsHelperTest {
@Test
public void normalizeEventTypes_withNull_doesNothing() {
UIManagerModuleConstantsHelper.normalizeEventTypes(null);
}
@Test
public void normalizeEventTypes_withEmptyMap_doesNothing() {
Map<Object, Object> emptyMap = MapBuilder.builder().build();
UIManagerModuleConstantsHelper.normalizeEventTypes(emptyMap);
assertTrue(emptyMap.isEmpty());
}
@Test
public void normalizeEventTypes_withOnEvent_doesNormalize() {
Map<Object, Object> onClickMap = MapBuilder.builder().put("onClick", "¯\\_(ツ)_/¯").build();
UIManagerModuleConstantsHelper.normalizeEventTypes(onClickMap);
assertTrue(onClickMap.containsKey("topOnClick"));
assertTrue(onClickMap.containsKey("onClick"));
}
@Test
public void normalizeEventTypes_withTopEvent_doesNormalize() {
Map<Object, Object> onClickMap = MapBuilder.builder().put("topOnClick", "¯\\_(ツ)_/¯").build();
UIManagerModuleConstantsHelper.normalizeEventTypes(onClickMap);
assertTrue(onClickMap.containsKey("topOnClick"));
assertFalse(onClickMap.containsKey("onClick"));
}
@SuppressWarnings("unchecked")
@Test
public void normalizeEventTypes_withNestedObjects_doesNotLoseThem() {
Map<String, Object> nestedObjects =
MapBuilder.<String, Object>builder()
.put(
"onColorChanged",
MapBuilder.of(
"phasedRegistrationNames",
MapBuilder.of(
"bubbled", "onColorChanged", "captured", "onColorChangedCapture")))
.build();
UIManagerModuleConstantsHelper.normalizeEventTypes(nestedObjects);
assertTrue(nestedObjects.containsKey("topOnColorChanged"));
Map<String, Object> innerMap = (Map<String, Object>) nestedObjects.get("topOnColorChanged");
assertNotNull(innerMap);
assertTrue(innerMap.containsKey("phasedRegistrationNames"));
Map<String, Object> innerInnerMap =
(Map<String, Object>) innerMap.get("phasedRegistrationNames");
assertNotNull(innerInnerMap);
assertEquals("onColorChanged", innerInnerMap.get("bubbled"));
assertEquals("onColorChangedCapture", innerInnerMap.get("captured"));
assertTrue(nestedObjects.containsKey("onColorChanged"));
innerMap = (Map<String, Object>) nestedObjects.get("topOnColorChanged");
assertNotNull(innerMap);
assertTrue(innerMap.containsKey("phasedRegistrationNames"));
innerInnerMap = (Map<String, Object>) innerMap.get("phasedRegistrationNames");
assertNotNull(innerInnerMap);
assertEquals("onColorChanged", innerInnerMap.get("bubbled"));
assertEquals("onColorChangedCapture", innerInnerMap.get("captured"));
}
}
@@ -16,7 +16,15 @@ else
source[:tag] = "v#{version}"
end
react_native_path = ".."
# We are using two different paths for react native because of the way how js_srcs_dir and output_dir options are used
# output_dir option usage was introduced in https://github.com/facebook/react-native/pull/36210
# React-rncore.podspec is the only podspec in the project that uses this option
# We should rethink this approach in T148704916
# Relative path to react native from iOS project root (e.g. <ios-project-root>/../node_modules/react-native)
react_native_dependency_path = ENV['REACT_NATIVE_PATH']
# Relative path to react native from current podspec
react_native_sources_path = '..'
Pod::Spec.new do |s|
s.name = "React-rncore"
@@ -33,10 +41,10 @@ Pod::Spec.new do |s|
use_react_native_codegen!(s, {
:react_native_path => react_native_path,
:js_srcs_dir => "#{react_native_path}/Libraries",
:react_native_path => react_native_sources_path,
:js_srcs_dir => "#{react_native_sources_path}/Libraries",
:library_name => "rncore",
:library_type => "components",
:output_dir => "#{react_native_path}/react-native/ReactCommon"
:output_dir => "#{react_native_dependency_path}/ReactCommon"
})
end
@@ -15,10 +15,10 @@
namespace facebook::react {
constexpr struct {
int32_t Major = 1000;
int32_t Minor = 0;
int32_t Major = 0;
int32_t Minor = 72;
int32_t Patch = 0;
std::string_view Prerelease = "";
std::string_view Prerelease = "rc.3";
} ReactNativeVersion;
} // namespace facebook::react
@@ -24,6 +24,9 @@ bool EmptyReactNativeConfig::getBool(const std::string &param) const {
if (param == "react_fabric:enabled_layout_animations_ios") {
return true;
}
if (param == "react_fabric:enable_nstextstorage_caching") {
return true;
}
return false;
}
@@ -33,7 +33,10 @@ typedef void (^InterceptorBlock)(std::string eventName, folly::dynamic event);
- (NSString *)componentViewName;
- (void)handleCommand:(NSString *)commandName args:(NSArray *)args reactTag:(NSInteger)tag;
- (void)handleCommand:(NSString *)commandName
args:(NSArray *)args
reactTag:(NSInteger)tag
paperView:(UIView *)paperView;
@end
@@ -100,13 +100,23 @@ using namespace facebook::react;
return RCTDropReactPrefixes(_componentData.name);
}
- (void)handleCommand:(NSString *)commandName args:(NSArray *)args reactTag:(NSInteger)tag
- (void)handleCommand:(NSString *)commandName
args:(NSArray *)args
reactTag:(NSInteger)tag
paperView:(nonnull UIView *)paperView
{
Class managerClass = _componentData.managerClass;
[self _lookupModuleMethodsIfNecessary];
RCTModuleData *moduleData = [_bridge.batchedBridge moduleDataForName:RCTBridgeModuleNameForClass(managerClass)];
id<RCTBridgeMethod> method;
if ([commandName isKindOfClass:[NSNumber class]]) {
// We can't use `[NSString intValue]` as "0" is a valid command,
// but also a falsy value. [NSNumberFormatter numberFromString] returns a
// `NSNumber *` which is NULL when it's to be NULL
// and it points to 0 when the string is @"0" (not a falsy value).
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
if ([commandName isKindOfClass:[NSNumber class]] || [formatter numberFromString:commandName] != NULL) {
method = moduleData ? moduleData.methods[[commandName intValue]] : _moduleMethods[[commandName intValue]];
} else if ([commandName isKindOfClass:[NSString class]]) {
method = moduleData ? moduleData.methodsByName[commandName] : _moduleMethodsByName[commandName];
@@ -121,12 +131,14 @@ using namespace facebook::react;
NSArray *newArgs = [@[ [NSNumber numberWithInteger:tag] ] arrayByAddingObjectsFromArray:args];
if (_bridge) {
[self _addViewToRegistry:paperView withTag:tag];
[_bridge.batchedBridge
dispatchBlock:^{
[method invokeWithBridge:self->_bridge module:self->_componentData.manager arguments:newArgs];
[self->_bridge.uiManager setNeedsLayout];
}
queue:RCTGetUIManagerQueue()];
[self _removeViewFromRegistryWithTag:tag];
} else {
// TODO T86826778 - Figure out which queue this should be dispatched to.
[method invokeWithBridge:nil module:self->_componentData.manager arguments:newArgs];
@@ -134,6 +146,41 @@ using namespace facebook::react;
}
#pragma mark - Private
- (void)_addViewToRegistry:(UIView *)view withTag:(NSInteger)tag
{
[self _addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
if ([viewRegistry objectForKey:@(tag)] != NULL) {
return;
}
NSMutableDictionary<NSNumber *, UIView *> *mutableViewRegistry =
(NSMutableDictionary<NSNumber *, UIView *> *)viewRegistry;
[mutableViewRegistry setObject:view forKey:@(tag)];
}];
}
- (void)_removeViewFromRegistryWithTag:(NSInteger)tag
{
[self _addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
if ([viewRegistry objectForKey:@(tag)] == NULL) {
return;
}
NSMutableDictionary<NSNumber *, UIView *> *mutableViewRegistry =
(NSMutableDictionary<NSNumber *, UIView *> *)viewRegistry;
[mutableViewRegistry removeObjectForKey:@(tag)];
}];
}
- (void)_addUIBlock:(RCTViewManagerUIBlock)block
{
__weak __typeof__(self) weakSelf = self;
[_bridge.batchedBridge
dispatchBlock:^{
__typeof__(self) strongSelf = weakSelf;
[strongSelf->_bridge.uiManager addUIBlock:block];
}
queue:RCTGetUIManagerQueue()];
}
// This is copy-pasta from RCTModuleData.
- (void)_lookupModuleMethodsIfNecessary
@@ -15,6 +15,19 @@ TextMeasurement ParagraphLayoutManager::measure(
AttributedString const &attributedString,
ParagraphAttributes const &paragraphAttributes,
LayoutConstraints layoutConstraints) const {
bool cacheLastTextMeasurement = CoreFeatures::cacheLastTextMeasurement;
if (cacheLastTextMeasurement &&
(layoutConstraints.maximumSize.width == availableWidth_ ||
layoutConstraints.maximumSize.width ==
cachedTextMeasurement_.size.width)) {
/* Yoga has requested measurement for this size before. Let's use cached
* value. `TextLayoutManager` might not have cached this because it could be
* using different width to generate cache key. This happens because Yoga
* switches between available width and exact width but since we already
* know exact width, it is wasteful to calculate it again.
*/
return cachedTextMeasurement_;
}
if (CoreFeatures::cacheNSTextStorage) {
size_t newHash = folly::hash::hash_combine(
0,
@@ -28,11 +41,23 @@ TextMeasurement ParagraphLayoutManager::measure(
}
}
return textLayoutManager_->measure(
AttributedStringBox(attributedString),
paragraphAttributes,
layoutConstraints,
hostTextStorage_);
if (cacheLastTextMeasurement) {
cachedTextMeasurement_ = textLayoutManager_->measure(
AttributedStringBox(attributedString),
paragraphAttributes,
layoutConstraints,
hostTextStorage_);
availableWidth_ = layoutConstraints.maximumSize.width;
return cachedTextMeasurement_;
} else {
return textLayoutManager_->measure(
AttributedStringBox(attributedString),
paragraphAttributes,
layoutConstraints,
hostTextStorage_);
}
}
LinesMeasurements ParagraphLayoutManager::measureLines(
@@ -54,6 +54,18 @@ class ParagraphLayoutManager {
std::shared_ptr<TextLayoutManager const> mutable textLayoutManager_{};
std::shared_ptr<void> mutable hostTextStorage_{};
/* The width Yoga set as maximum width.
* Yoga sometimes calls measure twice with two
* different maximum width. One if available space.
* The other one is exact space needed for the string.
* This happens when node is dirtied but its size is not affected.
* To deal with this inefficiency, we cache `TextMeasurement` for each
* `ParagraphShadowNode`. If Yoga tries to re-measure with available width
* or exact width, we provide it with the cached value.
*/
Float mutable availableWidth_{};
TextMeasurement mutable cachedTextMeasurement_{};
size_t mutable hash_{};
};
} // namespace facebook::react
@@ -369,21 +369,6 @@ void YogaLayoutableShadowNode::updateYogaProps() {
YGStyle result{baseStyle};
// Aliases with precedence
if (!props.inset.isUndefined()) {
result.position()[YGEdgeAll] = props.inset;
}
if (!props.insetBlock.isUndefined()) {
result.position()[YGEdgeVertical] = props.insetBlock;
}
if (!props.insetInline.isUndefined()) {
result.position()[YGEdgeHorizontal] = props.insetInline;
}
if (!props.insetInlineEnd.isUndefined()) {
result.position()[YGEdgeEnd] = props.insetInlineEnd;
}
if (!props.insetInlineStart.isUndefined()) {
result.position()[YGEdgeStart] = props.insetInlineStart;
}
if (!props.marginInline.isUndefined()) {
result.margin()[YGEdgeHorizontal] = props.marginInline;
}
@@ -410,12 +395,6 @@ void YogaLayoutableShadowNode::updateYogaProps() {
}
// Aliases without precedence
if (CompactValue(result.position()[YGEdgeBottom]).isUndefined()) {
result.position()[YGEdgeBottom] = props.insetBlockEnd;
}
if (CompactValue(result.position()[YGEdgeTop]).isUndefined()) {
result.position()[YGEdgeTop] = props.insetBlockStart;
}
if (CompactValue(result.margin()[YGEdgeTop]).isUndefined()) {
result.margin()[YGEdgeTop] = props.marginBlockStart;
}
@@ -136,13 +136,6 @@ void YogaStylableProps::setProp(
static const auto defaults = YogaStylableProps{};
// Aliases
RAW_SET_PROP_SWITCH_CASE(inset, "inset");
RAW_SET_PROP_SWITCH_CASE(insetBlock, "insetBlock");
RAW_SET_PROP_SWITCH_CASE(insetBlockEnd, "insetBlockEnd");
RAW_SET_PROP_SWITCH_CASE(insetBlockStart, "insetBlockStart");
RAW_SET_PROP_SWITCH_CASE(insetInline, "insetInline");
RAW_SET_PROP_SWITCH_CASE(insetInlineEnd, "insetInlineEnd");
RAW_SET_PROP_SWITCH_CASE(insetInlineStart, "insetInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInline, "marginInline");
RAW_SET_PROP_SWITCH_CASE(marginInlineStart, "marginInlineStart");
RAW_SET_PROP_SWITCH_CASE(marginInlineEnd, "marginInlineEnd");
@@ -242,48 +235,6 @@ void YogaStylableProps::convertRawPropAliases(
const PropsParserContext &context,
YogaStylableProps const &sourceProps,
RawProps const &rawProps) {
inset = convertRawProp(
context,
rawProps,
"inset",
sourceProps.inset,
CompactValue::ofUndefined());
insetBlock = convertRawProp(
context,
rawProps,
"insetBlock",
sourceProps.insetBlock,
CompactValue::ofUndefined());
insetBlockEnd = convertRawProp(
context,
rawProps,
"insetBlockEnd",
sourceProps.insetBlockEnd,
CompactValue::ofUndefined());
insetBlockStart = convertRawProp(
context,
rawProps,
"insetBlockStart",
sourceProps.insetBlockStart,
CompactValue::ofUndefined());
insetInline = convertRawProp(
context,
rawProps,
"insetInline",
sourceProps.insetInline,
CompactValue::ofUndefined());
insetInlineEnd = convertRawProp(
context,
rawProps,
"insetInlineEnd",
sourceProps.insetInlineEnd,
CompactValue::ofUndefined());
insetInlineStart = convertRawProp(
context,
rawProps,
"insetInlineStart",
sourceProps.insetInlineStart,
CompactValue::ofUndefined());
marginInline = convertRawProp(
context,
rawProps,
@@ -43,11 +43,6 @@ class YogaStylableProps : public Props {
// Duplicates of existing properties with different names, taking
// precedence. E.g. "marginBlock" instead of "marginVertical"
CompactValue inset;
CompactValue insetInline;
CompactValue insetInlineEnd;
CompactValue insetInlineStart;
CompactValue marginInline;
CompactValue marginInlineStart;
CompactValue marginInlineEnd;
@@ -61,10 +56,6 @@ class YogaStylableProps : public Props {
// BlockEnd/BlockStart map to top/bottom (no writing mode), but we preserve
// Yoga's precedence and prefer specific edges (e.g. top) to ones which are
// flow relative (e.g. blockStart).
CompactValue insetBlock;
CompactValue insetBlockEnd;
CompactValue insetBlockStart;
CompactValue marginBlockStart;
CompactValue marginBlockEnd;
@@ -15,6 +15,8 @@ bool CoreFeatures::enableMapBuffer = false;
bool CoreFeatures::blockPaintForUseLayoutEffect = false;
bool CoreFeatures::useNativeState = false;
bool CoreFeatures::cacheNSTextStorage = false;
bool CoreFeatures::cacheLastTextMeasurement = false;
bool CoreFeatures::cancelImageDownloadsOnRecycle = false;
} // namespace react
} // namespace facebook
@@ -39,6 +39,15 @@ class CoreFeatures {
// creating it twice. Once when measuring text and once when rendering it.
// This flag caches it inside ParagraphState.
static bool cacheNSTextStorage;
// Yoga might measure multiple times the same Text with the same constraints
// This flag enables a caching mechanism to avoid subsequents measurements
// of the same Text with the same constrainst.
static bool cacheLastTextMeasurement;
// Fabric was not cancelling image downloads when <ImageView /> was removed
// from view hierarchy. This feature flag enables this feature.
static bool cancelImageDownloadsOnRecycle;
};
} // namespace react
@@ -35,20 +35,24 @@ class ImageRequest final {
/*
* The move constructor.
*/
ImageRequest(ImageRequest &&other) noexcept;
ImageRequest(ImageRequest &&other) noexcept = default;
/*
* `ImageRequest` does not support copying by design.
*/
ImageRequest(const ImageRequest &other) = delete;
~ImageRequest();
/**
* Set cancelation function.
*/
void setCancelationFunction(std::function<void(void)> cancelationFunction);
/*
* Calls cancel function if one is defined. Should be when downloading
* image isn't needed anymore. E.g. <ImageView /> was removed.
*/
void cancel() const;
/*
* Returns the Image Source associated with the request.
*/
@@ -18,17 +18,6 @@ ImageRequest::ImageRequest(
// Not implemented.
}
ImageRequest::ImageRequest(ImageRequest &&other) noexcept
: imageSource_(std::move(other.imageSource_)),
telemetry_(std::move(other.telemetry_)),
coordinator_(std::move(other.coordinator_)) {
// Not implemented.
}
ImageRequest::~ImageRequest() {
// Not implemented.
}
const ImageResponseObserverCoordinator &ImageRequest::getObserverCoordinator()
const {
// Not implemented
@@ -17,27 +17,17 @@ ImageRequest::ImageRequest(
coordinator_ = std::make_shared<ImageResponseObserverCoordinator>();
}
ImageRequest::ImageRequest(ImageRequest &&other) noexcept
: imageSource_(std::move(other.imageSource_)),
telemetry_(std::move(other.telemetry_)),
coordinator_(std::move(other.coordinator_)) {
other.coordinator_ = nullptr;
other.cancelRequest_ = nullptr;
other.telemetry_ = nullptr;
other.imageSource_ = {};
}
ImageRequest::~ImageRequest() {
if (cancelRequest_) {
cancelRequest_();
}
}
void ImageRequest::setCancelationFunction(
std::function<void(void)> cancelationFunction) {
cancelRequest_ = cancelationFunction;
}
void ImageRequest::cancel() const {
if (cancelRequest_) {
cancelRequest_();
}
}
const ImageSource &ImageRequest::getImageSource() const {
return imageSource_;
}
@@ -12,6 +12,7 @@
#include <react/common/mapbuffer/JReadableMapBuffer.h>
#include <react/jni/ReadableNativeMap.h>
#include <react/renderer/attributedstring/conversions.h>
#include <react/renderer/core/CoreFeatures.h>
#include <react/renderer/core/conversions.h>
#include <react/renderer/mapbuffer/MapBuffer.h>
#include <react/renderer/mapbuffer/MapBufferBuilder.h>
@@ -146,7 +147,10 @@ Size measureAndroidComponentMapBuffer(
TextLayoutManager::TextLayoutManager(
const ContextContainer::Shared &contextContainer)
: contextContainer_(contextContainer),
measureCache_(kSimpleThreadSafeCacheSizeCap) {}
measureCache_(
CoreFeatures::cacheLastTextMeasurement
? 8096
: kSimpleThreadSafeCacheSizeCap) {}
void *TextLayoutManager::getNativeTextLayoutManager() const {
return self_;
@@ -52,47 +52,9 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
textStorage = [self _textStorageForNSAttributesString:attributedString
paragraphAttributes:paragraphAttributes
size:maximumSize];
} else {
textStorage.layoutManagers.firstObject.textContainers.firstObject.size = maximumSize;
}
NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
[layoutManager ensureLayoutForTextContainer:textContainer];
CGSize size = [layoutManager usedRectForTextContainer:textContainer].size;
size = (CGSize){RCTCeilPixelValue(size.width), RCTCeilPixelValue(size.height)};
__block auto attachments = TextMeasurement::Attachments{};
[textStorage
enumerateAttribute:NSAttachmentAttributeName
inRange:NSMakeRange(0, textStorage.length)
options:0
usingBlock:^(NSTextAttachment *attachment, NSRange range, BOOL *stop) {
if (!attachment) {
return;
}
CGSize attachmentSize = attachment.bounds.size;
CGRect glyphRect = [layoutManager boundingRectForGlyphRange:range inTextContainer:textContainer];
UIFont *font = [textStorage attribute:NSFontAttributeName atIndex:range.location effectiveRange:nil];
CGRect frame = {
{glyphRect.origin.x,
glyphRect.origin.y + glyphRect.size.height - attachmentSize.height + font.descender},
attachmentSize};
auto rect = facebook::react::Rect{
facebook::react::Point{frame.origin.x, frame.origin.y},
facebook::react::Size{frame.size.width, frame.size.height}};
attachments.push_back(TextMeasurement::Attachment{rect, false});
}];
return TextMeasurement{{size.width, size.height}, attachments};
return [self _measureTextStorage:textStorage];
}
- (TextMeasurement)measureAttributedString:(AttributedString)attributedString
@@ -100,10 +62,14 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
layoutConstraints:(LayoutConstraints)layoutConstraints
textStorage:(NSTextStorage *_Nullable)textStorage
{
return [self measureNSAttributedString:[self _nsAttributedStringFromAttributedString:attributedString]
paragraphAttributes:paragraphAttributes
layoutConstraints:layoutConstraints
textStorage:textStorage];
if (textStorage) {
return [self _measureTextStorage:textStorage];
} else {
return [self measureNSAttributedString:[self _nsAttributedStringFromAttributedString:attributedString]
paragraphAttributes:paragraphAttributes
layoutConstraints:layoutConstraints
textStorage:nil];
}
}
- (void)drawAttributedString:(AttributedString)attributedString
@@ -111,13 +77,33 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
frame:(CGRect)frame
textStorage:(NSTextStorage *_Nullable)textStorage
{
BOOL createdStorageForFrame = NO;
if (!textStorage) {
textStorage = [self textStorageForAttributesString:attributedString
paragraphAttributes:paragraphAttributes
size:frame.size];
createdStorageForFrame = YES;
}
NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
CGPoint origin = frame.origin;
if (!createdStorageForFrame) {
CGRect rect = [layoutManager usedRectForTextContainer:textContainer];
static auto threshold = 1.0 / RCTScreenScale() + 0.01; // Size of a pixel plus some small threshold.
// `rect`'s width is stored in double precesion.
// `frame`'s width is also in double precesion but was stored as float in Yoga previously, precesion was lost.
if (std::abs(RCTCeilPixelValue(rect.size.width) - frame.size.width) < threshold) {
// `textStorage` passed to this method was used to calculate size of frame. If that's the case, it's
// width is the same as frame's width. Origin must be adjusted, otherwise glyhps will be painted in wrong
// place.
// We could create new `NSTextStorage` for the specific frame, but that is expensive.
origin.x -= RCTCeilPixelValue(rect.origin.x);
}
}
#if TARGET_OS_MACCATALYST
CGContextRef context = UIGraphicsGetCurrentContext();
@@ -126,8 +112,8 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
#endif
NSRange glyphRange = [layoutManager glyphRangeForTextContainer:textContainer];
[layoutManager drawBackgroundForGlyphRange:glyphRange atPoint:frame.origin];
[layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:frame.origin];
[layoutManager drawBackgroundForGlyphRange:glyphRange atPoint:origin];
[layoutManager drawGlyphsForGlyphRange:glyphRange atPoint:origin];
#if TARGET_OS_MACCATALYST
CGContextRestoreGState(context);
@@ -178,35 +164,6 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
return paragraphLines;
}
- (NSTextStorage *)_textStorageForNSAttributesString:(NSAttributedString *)attributedString
paragraphAttributes:(ParagraphAttributes)paragraphAttributes
size:(CGSize)size
{
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
textContainer.lineFragmentPadding = 0.0; // Note, the default value is 5.
textContainer.lineBreakMode = paragraphAttributes.maximumNumberOfLines > 0
? RCTNSLineBreakModeFromEllipsizeMode(paragraphAttributes.ellipsizeMode)
: NSLineBreakByClipping;
textContainer.maximumNumberOfLines = paragraphAttributes.maximumNumberOfLines;
NSLayoutManager *layoutManager = [NSLayoutManager new];
layoutManager.usesFontLeading = NO;
[layoutManager addTextContainer:textContainer];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
[textStorage addLayoutManager:layoutManager];
if (paragraphAttributes.adjustsFontSizeToFit) {
CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) ? paragraphAttributes.minimumFontSize : 4.0;
CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) ? paragraphAttributes.maximumFontSize : 96.0;
[textStorage scaleFontSizeToFitSize:size minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize];
}
return textStorage;
}
- (NSTextStorage *)textStorageForAttributesString:(AttributedString)attributedString
paragraphAttributes:(ParagraphAttributes)paragraphAttributes
size:(CGSize)size
@@ -246,15 +203,6 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
return nil;
}
- (NSAttributedString *)_nsAttributedStringFromAttributedString:(AttributedString)attributedString
{
auto sharedNSAttributedString = _cache.get(attributedString, [](AttributedString attributedString) {
return wrapManagedObject(RCTNSAttributedStringFromAttributedString(attributedString));
});
return unwrapManagedObject(sharedNSAttributedString);
}
- (void)getRectWithAttributedString:(AttributedString)attributedString
paragraphAttributes:(ParagraphAttributes)paragraphAttributes
enumerateAttribute:(NSString *)enumerateAttribute
@@ -294,4 +242,85 @@ static NSLineBreakMode RCTNSLineBreakModeFromEllipsizeMode(EllipsizeMode ellipsi
}];
}
#pragma mark - Private
- (NSTextStorage *)_textStorageForNSAttributesString:(NSAttributedString *)attributedString
paragraphAttributes:(ParagraphAttributes)paragraphAttributes
size:(CGSize)size
{
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
textContainer.lineFragmentPadding = 0.0; // Note, the default value is 5.
textContainer.lineBreakMode = paragraphAttributes.maximumNumberOfLines > 0
? RCTNSLineBreakModeFromEllipsizeMode(paragraphAttributes.ellipsizeMode)
: NSLineBreakByClipping;
textContainer.maximumNumberOfLines = paragraphAttributes.maximumNumberOfLines;
NSLayoutManager *layoutManager = [NSLayoutManager new];
layoutManager.usesFontLeading = NO;
[layoutManager addTextContainer:textContainer];
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributedString];
[textStorage addLayoutManager:layoutManager];
if (paragraphAttributes.adjustsFontSizeToFit) {
CGFloat minimumFontSize = !isnan(paragraphAttributes.minimumFontSize) ? paragraphAttributes.minimumFontSize : 4.0;
CGFloat maximumFontSize = !isnan(paragraphAttributes.maximumFontSize) ? paragraphAttributes.maximumFontSize : 96.0;
[textStorage scaleFontSizeToFitSize:size minimumFontSize:minimumFontSize maximumFontSize:maximumFontSize];
}
return textStorage;
}
- (NSAttributedString *)_nsAttributedStringFromAttributedString:(AttributedString)attributedString
{
auto sharedNSAttributedString = _cache.get(attributedString, [](AttributedString attributedString) {
return wrapManagedObject(RCTNSAttributedStringFromAttributedString(attributedString));
});
return unwrapManagedObject(sharedNSAttributedString);
}
- (TextMeasurement)_measureTextStorage:(NSTextStorage *)textStorage
{
NSLayoutManager *layoutManager = textStorage.layoutManagers.firstObject;
NSTextContainer *textContainer = layoutManager.textContainers.firstObject;
[layoutManager ensureLayoutForTextContainer:textContainer];
CGSize size = [layoutManager usedRectForTextContainer:textContainer].size;
size = (CGSize){RCTCeilPixelValue(size.width), RCTCeilPixelValue(size.height)};
__block auto attachments = TextMeasurement::Attachments{};
[textStorage
enumerateAttribute:NSAttachmentAttributeName
inRange:NSMakeRange(0, textStorage.length)
options:0
usingBlock:^(NSTextAttachment *attachment, NSRange range, BOOL *stop) {
if (!attachment) {
return;
}
CGSize attachmentSize = attachment.bounds.size;
CGRect glyphRect = [layoutManager boundingRectForGlyphRange:range inTextContainer:textContainer];
UIFont *font = [textStorage attribute:NSFontAttributeName atIndex:range.location effectiveRange:nil];
CGRect frame = {
{glyphRect.origin.x,
glyphRect.origin.y + glyphRect.size.height - attachmentSize.height + font.descender},
attachmentSize};
auto rect = facebook::react::Rect{
facebook::react::Point{frame.origin.x, frame.origin.y},
facebook::react::Size{frame.size.width, frame.size.height}};
attachments.push_back(TextMeasurement::Attachment{rect, false});
}];
return TextMeasurement{{size.width, size.height}, attachments};
}
@end
+17
View File
@@ -1 +1,18 @@
/*
* 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.
*/
// This is the top level build.gradle.kts file used when the users
// is doing a build from source. It's triggered as the user
// will add an `includeBuild(../node_modules/react-native)` in
// their settings.gradle.kts file.
// More on this here: https://reactnative.dev/contributing/how-to-build-from-source
plugins {
id("com.android.library") version "7.4.2" apply false
id("com.android.application") version "7.4.2" apply false
id("de.undercouch.download") version "5.0.1" apply false
kotlin("android") version "1.7.22" apply false
}
+1
View File
@@ -0,0 +1 @@
android.useAndroidX=true
+5 -5
View File
@@ -9,14 +9,15 @@
'use strict';
const {getDefaultConfig} = require('@react-native/metro-config');
const {mergeConfig} = require('metro-config');
const path = require('path');
const getPolyfills = require('./rn-get-polyfills');
/**
* This cli config is needed for development purposes, e.g. for running
* integration tests during local development or on CI services.
*/
module.exports = {
const config = {
// Make Metro able to resolve required packages that might be imported from /packages/react-native
watchFolders: [
path.resolve(__dirname, '../../node_modules'),
@@ -31,7 +32,6 @@ module.exports = {
'react-native': __dirname,
},
},
serializer: {
getPolyfills,
},
};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);
+12 -12
View File
@@ -1,6 +1,6 @@
{
"name": "react-native",
"version": "1000.0.0",
"version": "0.72.0-rc.3",
"bin": "./cli.js",
"description": "A framework for building native apps using React",
"license": "MIT",
@@ -79,27 +79,27 @@
},
"dependencies": {
"@jest/create-cache-key-function": "^29.2.1",
"@react-native-community/cli": "11.0.0-alpha.2",
"@react-native-community/cli-platform-android": "11.0.0-alpha.2",
"@react-native-community/cli-platform-ios": "11.0.0-alpha.2",
"@react-native-community/cli": "11.2.3",
"@react-native-community/cli-platform-android": "11.2.3",
"@react-native-community/cli-platform-ios": "11.2.3",
"@react-native/assets-registry": "^0.72.0",
"@react-native/codegen": "^0.72.3",
"@react-native/gradle-plugin": "^0.72.5",
"@react-native/codegen": "^0.72.4",
"@react-native/gradle-plugin": "^0.72.7",
"@react-native/js-polyfills": "^0.72.1",
"@react-native/normalize-colors": "^0.72.0",
"@react-native/virtualized-lists": "^0.72.2",
"@react-native/virtualized-lists": "^0.72.4",
"abort-controller": "^3.0.0",
"anser": "^1.4.9",
"base64-js": "^1.1.2",
"deprecated-react-native-prop-types": "^4.0.0",
"deprecated-react-native-prop-types": "4.1.0",
"event-target-shim": "^5.0.1",
"flow-enums-runtime": "^0.0.5",
"invariant": "^2.2.4",
"jest-environment-node": "^29.2.1",
"jsc-android": "^250231.0.0",
"memoize-one": "^5.0.0",
"metro-runtime": "0.75.1",
"metro-source-map": "0.75.1",
"metro-runtime": "0.76.4",
"metro-source-map": "0.76.4",
"mkdirp": "^0.5.1",
"nullthrows": "^1.1.1",
"pretty-format": "^26.5.2",
@@ -108,7 +108,7 @@
"react-refresh": "^0.4.0",
"react-shallow-renderer": "^16.15.0",
"regenerator-runtime": "^0.13.2",
"scheduler": "^0.23.0",
"scheduler": "0.24.0-canary-efb381bbf-20230505",
"stacktrace-parser": "^0.1.10",
"use-sync-external-store": "^1.0.0",
"whatwg-fetch": "^3.0.0",
@@ -133,4 +133,4 @@
}
]
}
}
}
@@ -15,6 +15,14 @@ require_relative "./test_utils/CodegenUtilsMock.rb"
require_relative "./test_utils/CodegenScriptPhaseExtractorMock.rb"
require_relative "./test_utils/FileUtilsMock.rb"
# mocking the min_ios_version_supported function
# as it is not possible to require the original react_native_pod
# without incurring in circular deps
# TODO: move `min_ios_version_supported` to utils.rb
def min_ios_version_supported
return '12.4'
end
class CodegenUtilsTests < Test::Unit::TestCase
:base_path
@@ -527,7 +535,7 @@ class CodegenUtilsTests < Test::Unit::TestCase
'source' => { :git => '' },
'header_mappings_dir' => './',
'platforms' => {
'ios' => '11.0',
'ios' => '12.4',
},
'source_files' => "**/*.{h,mm,cpp}",
'pod_target_xcconfig' => {
@@ -82,7 +82,7 @@ class FlipperTests < Test::Unit::TestCase
assert_equal(config.build_settings['SWIFT_VERSION'], '4.1')
end
reactCore_target = installer.target_with_name("React-Core")
reactCore_target = installer.target_with_name("React-RCTAppDelegate")
reactCore_target.build_configurations.each do |config|
if config.name == 'Debug' || config.name == 'CustomConfig' then
assert_equal(config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'], ['$(inherited)', 'FB_SONARKIT_ENABLED=1'])
@@ -144,6 +144,14 @@ class FlipperTests < Test::Unit::TestCase
BuildConfigurationMock.new("Release", is_debug: false),
BuildConfigurationMock.new("CustomConfig", is_debug: true),
]
),
TargetMock.new(
"React-RCTAppDelegate",
[
BuildConfigurationMock.new("Debug", is_debug: true),
BuildConfigurationMock.new("Release", is_debug: false),
BuildConfigurationMock.new("CustomConfig", is_debug: true),
]
)
]
)
@@ -105,7 +105,9 @@ class JSEngineTests < Test::Unit::TestCase
assert_equal($podInvocation["React-jsi"][:path], "../../ReactCommon/jsi")
assert_equal($podInvocation["React-hermes"][:path], "../../ReactCommon/hermes")
assert_equal($podInvocation["libevent"][:version], "~> 2.1.12")
assert_equal($podInvocation["hermes-engine"][:podspec], "../../sdks/hermes/hermes-engine.podspec")
hermes_engine_pod_invocation = $podInvocation["hermes-engine"]
assert_equal(hermes_engine_pod_invocation[:podspec], "../../sdks/hermes-engine/hermes-engine.podspec")
assert_equal(hermes_engine_pod_invocation[:tag], "")
end
def test_setupHermes_installsPods_installsFabricSubspecWhenFabricEnabled
@@ -118,7 +120,9 @@ class JSEngineTests < Test::Unit::TestCase
# Assert
assert_equal($podInvocationCount, 4)
assert_equal($podInvocation["React-jsi"][:path], "../../ReactCommon/jsi")
assert_equal($podInvocation["hermes-engine"][:podspec], "../../sdks/hermes/hermes-engine.podspec")
hermes_engine_pod_invocation = $podInvocation["hermes-engine"]
assert_equal(hermes_engine_pod_invocation[:podspec], "../../sdks/hermes-engine/hermes-engine.podspec")
assert_equal(hermes_engine_pod_invocation[:tag], "")
assert_equal($podInvocation["React-hermes"][:path], "../../ReactCommon/hermes")
assert_equal($podInvocation["libevent"][:version], "~> 2.1.12")
end
@@ -26,7 +26,7 @@ def podSpy_cleanUp
$podInvocationCount = 0
end
def pod(name, version = nil, path: nil, configurations: nil, modular_headers: nil, podspec: nil)
def pod(name, version = nil, path: nil, configurations: nil, modular_headers: nil, podspec: nil, tag: nil)
$podInvocationCount += 1
params = {}
if version != nil then params[:version] = version end
@@ -34,5 +34,6 @@ def pod(name, version = nil, path: nil, configurations: nil, modular_headers: ni
if configurations != nil then params[:configurations] = configurations end
if modular_headers != nil then params[:modular_headers] = modular_headers end
if podspec != nil then params[:podspec] = podspec end
if tag != nil then params[:tag] = tag end
$podInvocation[name] = params
end
@@ -677,74 +677,6 @@ class UtilsTests < Test::Unit::TestCase
assert_equal(config.build_settings["OTHER_CFLAGS"], "$(inherited)")
end
end
# ============================= #
# Test - Enable Hermes Profiler #
# ============================= #
def test_enableHermesProfiler_whenEnableHermesProfileIsTrue_setsFlagsInRelease
# Arrange
first_target = prepare_target("FirstTarget")
second_target = prepare_target("SecondTarget")
third_target = prepare_target("ThirdTarget", "com.apple.product-type.bundle")
user_project_mock = UserProjectMock.new("a/path", [
prepare_config("Debug"),
prepare_config("Release"),
],
:native_targets => [
first_target,
second_target
]
)
pods_projects_mock = PodsProjectMock.new([third_target], {"hermes-engine" => {}})
installer = InstallerMock.new(pods_projects_mock, [
AggregatedProjectMock.new(user_project_mock)
])
# Act
ReactNativePodsUtils.enable_hermes_profiler(installer, enable_hermes_profiler: true)
# Assert
installer.target_installation_results.pod_target_installation_results.each do |pod_name, target_installation_result|
target_installation_result.native_target.build_configurations.each do |config|
if config.name != "Release"
assert_nil(config.build_settings["OTHER_CFLAGS"])
else
assert_equal(config.build_settings["OTHER_CFLAGS"], "$(inherited) -DRCT_REMOTE_PROFILE=1")
end
end
end
end
def test_enableHermesProfiler_whenEnableHermesProfileIsFalse_doesNothing
# Arrange
first_target = prepare_target("FirstTarget")
second_target = prepare_target("SecondTarget")
third_target = prepare_target("ThirdTarget", "com.apple.product-type.bundle")
user_project_mock = UserProjectMock.new("a/path", [
prepare_config("Debug"),
prepare_config("Release"),
],
:native_targets => [
first_target,
second_target
]
)
pods_projects_mock = PodsProjectMock.new([third_target], {"hermes-engine" => {}})
installer = InstallerMock.new(pods_projects_mock, [
AggregatedProjectMock.new(user_project_mock)
])
# Act
ReactNativePodsUtils.enable_hermes_profiler(installer)
# Assert
installer.target_installation_results.pod_target_installation_results.each do |pod_name, target_installation_result|
target_installation_result.native_target.build_configurations.each do |config|
assert_nil(config.build_settings["OTHER_CFLAGS"])
end
end
end
end
# ===== #
@@ -111,7 +111,7 @@ class CodegenUtils
'source' => { :git => '' },
'header_mappings_dir' => './',
'platforms' => {
'ios' => '11.0',
'ios' => min_ios_version_supported,
},
'source_files' => "**/*.{h,mm,cpp}",
'pod_target_xcconfig' => {
@@ -77,8 +77,8 @@ def flipper_post_install(installer)
end
end
# Enable flipper for React-Core Debug configuration
if target.name == 'React-Core'
# Enable flipper for React-RCTAppDelegate Debug configuration
if target.name == 'React-RCTAppDelegate'
target.build_configurations.each do |config|
if config.debug?
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = ['$(inherited)', 'FB_SONARKIT_ENABLED=1']
@@ -30,7 +30,12 @@ def setup_hermes!(react_native_path: "../node_modules/react-native", fabric_enab
abort unless prep_status == 0
pod 'React-jsi', :path => "#{react_native_path}/ReactCommon/jsi"
pod 'hermes-engine', :podspec => "#{react_native_path}/sdks/hermes/hermes-engine.podspec"
# This `:tag => hermestag` below is only to tell CocoaPods to update hermes-engine when React Native version changes.
# We have custom logic to compute the source for hermes-engine. See sdks/hermes-engine/*
hermestag_file = File.join(react_native_path, "sdks", ".hermesversion")
hermestag = File.exist?(hermestag_file) ? File.read(hermestag_file).strip : ''
pod 'hermes-engine', :podspec => "#{react_native_path}/sdks/hermes-engine/hermes-engine.podspec", :tag => hermestag
pod 'React-hermes', :path => "#{react_native_path}/ReactCommon/hermes"
pod 'libevent', '~> 2.1.12'
end
@@ -220,13 +220,6 @@ class ReactNativePodsUtils
end
end
def self.enable_hermes_profiler(installer, enable_hermes_profiler: false)
return if !enable_hermes_profiler
Pod::UI.puts "[Hermes Profiler] Enable Hermes Sample profiler"
self.add_compiler_flag_to_pods(installer, "-DRCT_REMOTE_PROFILE=1", configuration: "Release")
end
# ========= #
# Utilities #
# ========= #
@@ -222,11 +222,10 @@ end
# - mac_catalyst_enabled: whether we are running the Pod on a Mac Catalyst project or not.
# - enable_hermes_profiler: whether the hermes profiler should be turned on in Release mode
def react_native_post_install(
installer, react_native_path = "../node_modules/react-native",
mac_catalyst_enabled: false,
enable_hermes_profiler: false
installer,
react_native_path = "../node_modules/react-native",
mac_catalyst_enabled: false
)
enable_hermes_profiler = enable_hermes_profiler || ENV["ENABLE_HERMES_PROFILER"] == "1"
ReactNativePodsUtils.turn_off_resource_bundle_react_core(installer)
ReactNativePodsUtils.apply_mac_catalyst_patches(installer) if mac_catalyst_enabled
@@ -242,13 +241,11 @@ def react_native_post_install(
ReactNativePodsUtils.update_search_paths(installer)
ReactNativePodsUtils.set_node_modules_user_settings(installer, react_native_path)
ReactNativePodsUtils.apply_flags_for_fabric(installer, fabric_enabled: fabric_enabled)
ReactNativePodsUtils.enable_hermes_profiler(installer, enable_hermes_profiler: enable_hermes_profiler)
NewArchitectureHelper.set_clang_cxx_language_standard_if_needed(installer)
is_new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == "1"
NewArchitectureHelper.modify_flags_for_new_architecture(installer, is_new_arch_enabled)
Pod::UI.puts "Pod install took #{Time.now.to_i - $START_TIME} [s] to run".green
end
@@ -0,0 +1 @@
hermes-2023-03-20-RNv0.72.0-49794cfc7c81fb8f69fd60c3bbf85a7480cc5a77
+30
View File
@@ -1 +1,31 @@
/*
* 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.
*/
// This is the settings.gradle.kts file used when the users
// is doing a build from source. It's triggered as the user
// will add an `includeBuild(../node_modules/react-native)` in
// their settings.gradle.kts file.
// More on this here: https://reactnative.dev/contributing/how-to-build-from-source
pluginManagement {
repositories {
mavenCentral()
google()
gradlePluginPortal()
}
}
rootProject.name = "react-native-github"
include(":packages:react-native:ReactAndroid")
project(":packages:react-native:ReactAndroid").projectDir = file("ReactAndroid/")
include(":packages:react-native:ReactAndroid:hermes-engine")
project(":packages:react-native:ReactAndroid:hermes-engine").projectDir =
file("ReactAndroid/hermes-engine/")
@@ -1,3 +1,10 @@
/*
* 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.
*/
apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
@@ -107,8 +114,6 @@ dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.squareup.okhttp3', module:'okhttp'
+10 -16
View File
@@ -1,17 +1,11 @@
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* @format
*/
const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
/**
* Metro configuration
* https://facebook.github.io/metro/docs/configuration
*
* @type {import('metro-config').MetroConfig}
*/
const config = {};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);
+5 -3
View File
@@ -11,20 +11,22 @@
},
"dependencies": {
"react": "18.2.0",
"react-native": "1000.0.0"
"react-native": "0.72.0-rc.3"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.12.5",
"@react-native/eslint-config": "^0.72.1",
"@tsconfig/react-native": "^2.0.2",
"@react-native/metro-config": "^0.72.5",
"@tsconfig/react-native": "^3.0.0",
"@types/metro-config": "^0.76.3",
"@types/react": "^18.0.24",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.2.1",
"eslint": "^8.19.0",
"jest": "^29.2.1",
"metro-react-native-babel-preset": "0.75.1",
"metro-react-native-babel-preset": "0.76.4",
"prettier": "^2.4.1",
"react-test-renderer": "18.2.0",
"typescript": "4.8.4"
@@ -40,6 +40,8 @@ import {
DrawerLayoutAndroid,
DrawerSlideEvent,
DynamicColorIOS,
EmitterSubscription,
EventSubscription,
FlatList,
FlatListProps,
GestureResponderEvent,
+4
View File
@@ -147,6 +147,10 @@ export * from '../Libraries/Utilities/Platform';
export * from '../Libraries/Vibration/Vibration';
export * from '../Libraries/YellowBox/YellowBoxDeprecated';
export * from '../Libraries/vendor/core/ErrorUtils';
export {
EmitterSubscription,
EventSubscription,
} from '../Libraries/vendor/emitter/EventEmitter';
export * from './public/DeprecatedPropertiesAlias';
export * from './public/Insets';
@@ -30,9 +30,41 @@ RCT_REMAP_VIEW_PROPERTY(opacity, alpha, CGFloat)
RCT_EXPORT_VIEW_PROPERTY(onColorChanged, RCTBubblingEventBlock)
RCT_CUSTOM_VIEW_PROPERTY(cornerRadius, CGFloat, RNTLegacyView)
{
view.clipsToBounds = true;
NSNumber *cornerRadius = (NSNumber *)json;
view.layer.cornerRadius = [cornerRadius floatValue];
}
RCT_EXPORT_METHOD(changeBackgroundColor : (nonnull NSNumber *)reactTag color : (NSString *)color)
{
[self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
UIView *view = viewRegistry[reactTag];
if (!view || ![view isKindOfClass:[RNTLegacyView class]]) {
RCTLogError(@"Cannot find RNTLegacyView with tag #%@", reactTag);
return;
}
unsigned rgbValue = 0;
NSString *colorString = [NSString stringWithCString:std::string([color UTF8String]).c_str()
encoding:[NSString defaultCStringEncoding]];
NSScanner *scanner = [NSScanner scannerWithString:colorString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
UIColor *newColor = [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0
green:((rgbValue & 0xFF00) >> 8) / 255.0
blue:(rgbValue & 0xFF) / 255.0
alpha:1.0];
view.backgroundColor = newColor;
}];
}
- (UIView *)view
{
RNTLegacyView *view = [[RNTLegacyView alloc] init];
view.backgroundColor = UIColor.redColor;
return view;
}

Some files were not shown because too many files have changed in this diff Show More