From 880e8893800860a572f2f58473ca328c67cce045 Mon Sep 17 00:00:00 2001 From: Paige Sun Date: Mon, 24 Oct 2022 04:35:28 -0700 Subject: [PATCH 001/169] Drop `using namespace` in .h files Summary: using namespace in header file is a bad practice due to many reasons as well as discouraged by -Wheader-hygiene compiler flag which is default for many apps https://stackoverflow.com/questions/5849457/using-namespace-in-c-headers https://stackoverflow.com/questions/223021/whats-the-scope-of-the-using-declaration-in-c Changelog: [Internal] Drop `using namespace` in .h files. Reviewed By: christophpurrer Differential Revision: D40628064 fbshipit-source-id: 8a032f3ab0321a531e26bd88656ad9a65b6d5154 --- Libraries/Blob/RCTBlobCollector.h | 2 - .../Mounting/RCTComponentViewFactory.mm | 1 + .../react/renderer/core/tests/TestComponent.h | 6 +- .../ios/RCTImagePrimitivesConversions.h | 30 +++++----- .../ios/RCTTextPrimitivesConversions.h | 57 ++++++++++--------- 5 files changed, 48 insertions(+), 48 deletions(-) diff --git a/Libraries/Blob/RCTBlobCollector.h b/Libraries/Blob/RCTBlobCollector.h index fdd68112d6820a..4d0166aab7db94 100644 --- a/Libraries/Blob/RCTBlobCollector.h +++ b/Libraries/Blob/RCTBlobCollector.h @@ -7,8 +7,6 @@ #import -using namespace facebook; - @class RCTBlobManager; namespace facebook { diff --git a/React/Fabric/Mounting/RCTComponentViewFactory.mm b/React/Fabric/Mounting/RCTComponentViewFactory.mm index a4b271674ac896..0d8e15cebc2a7b 100644 --- a/React/Fabric/Mounting/RCTComponentViewFactory.mm +++ b/React/Fabric/Mounting/RCTComponentViewFactory.mm @@ -39,6 +39,7 @@ #import +using namespace facebook; using namespace facebook::react; // Allow JS runtime to register native components as needed. For static view configs. diff --git a/ReactCommon/react/renderer/core/tests/TestComponent.h b/ReactCommon/react/renderer/core/tests/TestComponent.h index 0e9931cc46aea5..a0c97b9c320b2b 100644 --- a/ReactCommon/react/renderer/core/tests/TestComponent.h +++ b/ReactCommon/react/renderer/core/tests/TestComponent.h @@ -18,13 +18,13 @@ #include #include -using namespace facebook::react; - /** * This defines a set of TestComponent classes: Props, ShadowNode, * ComponentDescriptor. To be used for testing purpose. */ +namespace facebook::react { + class TestState { public: int number; @@ -75,3 +75,5 @@ class TestComponentDescriptor public: using ConcreteComponentDescriptor::ConcreteComponentDescriptor; }; + +} // namespace facebook::react diff --git a/ReactCommon/react/renderer/imagemanager/platform/ios/RCTImagePrimitivesConversions.h b/ReactCommon/react/renderer/imagemanager/platform/ios/RCTImagePrimitivesConversions.h index d72e61c63f0afb..b5f61f8a4eed6f 100644 --- a/ReactCommon/react/renderer/imagemanager/platform/ios/RCTImagePrimitivesConversions.h +++ b/ReactCommon/react/renderer/imagemanager/platform/ios/RCTImagePrimitivesConversions.h @@ -10,43 +10,41 @@ #import #import -using namespace facebook::react; - -inline static UIViewContentMode RCTContentModeFromImageResizeMode(ImageResizeMode imageResizeMode) +inline static UIViewContentMode RCTContentModeFromImageResizeMode(facebook::react::ImageResizeMode imageResizeMode) { switch (imageResizeMode) { - case ImageResizeMode::Cover: + case facebook::react::ImageResizeMode::Cover: return UIViewContentModeScaleAspectFill; - case ImageResizeMode::Contain: + case facebook::react::ImageResizeMode::Contain: return UIViewContentModeScaleAspectFit; - case ImageResizeMode::Stretch: + case facebook::react::ImageResizeMode::Stretch: return UIViewContentModeScaleToFill; - case ImageResizeMode::Center: + case facebook::react::ImageResizeMode::Center: return UIViewContentModeCenter; - case ImageResizeMode::Repeat: + case facebook::react::ImageResizeMode::Repeat: // Repeat resize mode is handled by the UIImage. Use scale to fill // so the repeated image fills the UIImageView. return UIViewContentModeScaleToFill; } } -inline std::string toString(const ImageResizeMode &value) +inline std::string toString(const facebook::react::ImageResizeMode &value) { switch (value) { - case ImageResizeMode::Cover: + case facebook::react::ImageResizeMode::Cover: return "cover"; - case ImageResizeMode::Contain: + case facebook::react::ImageResizeMode::Contain: return "contain"; - case ImageResizeMode::Stretch: + case facebook::react::ImageResizeMode::Stretch: return "stretch"; - case ImageResizeMode::Center: + case facebook::react::ImageResizeMode::Center: return "center"; - case ImageResizeMode::Repeat: + case facebook::react::ImageResizeMode::Repeat: return "repeat"; } } -inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) +inline static NSURL *NSURLFromImageSource(const facebook::react::ImageSource &imageSource) { // `NSURL` has a history of crashing with bad input, so let's be safe. @try { @@ -92,7 +90,7 @@ inline static NSURL *NSURLFromImageSource(const ImageSource &imageSource) } } -inline static NSURLRequest *NSURLRequestFromImageSource(const ImageSource &imageSource) +inline static NSURLRequest *NSURLRequestFromImageSource(const facebook::react::ImageSource &imageSource) { NSURL *url = NSURLFromImageSource(imageSource); diff --git a/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h b/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h index 7cba9d5d0f3fb3..1921d1ca1cffed 100644 --- a/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h +++ b/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTTextPrimitivesConversions.h @@ -10,50 +10,50 @@ #include #include -using namespace facebook::react; - -inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment(TextAlignment textAlignment) +inline static NSTextAlignment RCTNSTextAlignmentFromTextAlignment(facebook::react::TextAlignment textAlignment) { switch (textAlignment) { - case TextAlignment::Natural: + case facebook::react::TextAlignment::Natural: return NSTextAlignmentNatural; - case TextAlignment::Left: + case facebook::react::TextAlignment::Left: return NSTextAlignmentLeft; - case TextAlignment::Right: + case facebook::react::TextAlignment::Right: return NSTextAlignmentRight; - case TextAlignment::Center: + case facebook::react::TextAlignment::Center: return NSTextAlignmentCenter; - case TextAlignment::Justified: + case facebook::react::TextAlignment::Justified: return NSTextAlignmentJustified; } } -inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection(WritingDirection writingDirection) +inline static NSWritingDirection RCTNSWritingDirectionFromWritingDirection( + facebook::react::WritingDirection writingDirection) { switch (writingDirection) { - case WritingDirection::Natural: + case facebook::react::WritingDirection::Natural: return NSWritingDirectionNatural; - case WritingDirection::LeftToRight: + case facebook::react::WritingDirection::LeftToRight: return NSWritingDirectionLeftToRight; - case WritingDirection::RightToLeft: + case facebook::react::WritingDirection::RightToLeft: return NSWritingDirectionRightToLeft; } } -inline static NSLineBreakStrategy RCTNSLineBreakStrategyFromLineBreakStrategy(LineBreakStrategy lineBreakStrategy) +inline static NSLineBreakStrategy RCTNSLineBreakStrategyFromLineBreakStrategy( + facebook::react::LineBreakStrategy lineBreakStrategy) { switch (lineBreakStrategy) { - case LineBreakStrategy::None: + case facebook::react::LineBreakStrategy::None: return NSLineBreakStrategyNone; - case LineBreakStrategy::PushOut: + case facebook::react::LineBreakStrategy::PushOut: return NSLineBreakStrategyPushOut; - case LineBreakStrategy::HangulWordPriority: + case facebook::react::LineBreakStrategy::HangulWordPriority: if (@available(iOS 14.0, *)) { return NSLineBreakStrategyHangulWordPriority; } else { return NSLineBreakStrategyNone; } - case LineBreakStrategy::Standard: + case facebook::react::LineBreakStrategy::Standard: if (@available(iOS 14.0, *)) { return NSLineBreakStrategyStandard; } else { @@ -62,38 +62,39 @@ inline static NSLineBreakStrategy RCTNSLineBreakStrategyFromLineBreakStrategy(Li } } -inline static RCTFontStyle RCTFontStyleFromFontStyle(FontStyle fontStyle) +inline static RCTFontStyle RCTFontStyleFromFontStyle(facebook::react::FontStyle fontStyle) { switch (fontStyle) { - case FontStyle::Normal: + case facebook::react::FontStyle::Normal: return RCTFontStyleNormal; - case FontStyle::Italic: + case facebook::react::FontStyle::Italic: return RCTFontStyleItalic; - case FontStyle::Oblique: + case facebook::react::FontStyle::Oblique: return RCTFontStyleOblique; } } -inline static RCTFontVariant RCTFontVariantFromFontVariant(FontVariant fontVariant) +inline static RCTFontVariant RCTFontVariantFromFontVariant(facebook::react::FontVariant fontVariant) { return (RCTFontVariant)fontVariant; } -inline static NSUnderlineStyle RCTNSUnderlineStyleFromTextDecorationStyle(TextDecorationStyle textDecorationStyle) +inline static NSUnderlineStyle RCTNSUnderlineStyleFromTextDecorationStyle( + facebook::react::TextDecorationStyle textDecorationStyle) { switch (textDecorationStyle) { - case TextDecorationStyle::Solid: + case facebook::react::TextDecorationStyle::Solid: return NSUnderlineStyleSingle; - case TextDecorationStyle::Double: + case facebook::react::TextDecorationStyle::Double: return NSUnderlineStyleDouble; - case TextDecorationStyle::Dashed: + case facebook::react::TextDecorationStyle::Dashed: return NSUnderlinePatternDash | NSUnderlineStyleSingle; - case TextDecorationStyle::Dotted: + case facebook::react::TextDecorationStyle::Dotted: return NSUnderlinePatternDot | NSUnderlineStyleSingle; } } -inline static UIColor *RCTUIColorFromSharedColor(const SharedColor &sharedColor) +inline static UIColor *RCTUIColorFromSharedColor(const facebook::react::SharedColor &sharedColor) { if (!sharedColor) { return nil; From 9a87db266a231635918c87ee96fbd28696c81638 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Mon, 24 Oct 2022 05:58:05 -0700 Subject: [PATCH 002/169] Remove initialProps handling for legacy createAnimatedComponent Summary: Changelog: [Internal] Remove additional Animated logic under Fabric that's no longer required Reviewed By: jehartzog Differential Revision: D40513977 fbshipit-source-id: 1e96366377ca4c3bf032d830b5641ab658462ce8 --- Libraries/Animated/createAnimatedComponent.js | 14 +------------ Libraries/Animated/nodes/AnimatedProps.js | 14 ++----------- Libraries/Animated/nodes/AnimatedStyle.js | 21 +++++-------------- 3 files changed, 8 insertions(+), 41 deletions(-) diff --git a/Libraries/Animated/createAnimatedComponent.js b/Libraries/Animated/createAnimatedComponent.js index 5ee706d64f2b4b..fb64ba05ffd375 100644 --- a/Libraries/Animated/createAnimatedComponent.js +++ b/Libraries/Animated/createAnimatedComponent.js @@ -53,7 +53,6 @@ function createAnimatedComponent( _prevComponent: any; _propsAnimated: AnimatedProps; _eventDetachers: Array = []; - _initialAnimatedProps: Object; // Only to be used in this file, and only in Fabric. _animatedComponentId: string = `${animatedComponentNextId++}:animatedComponent`; @@ -199,18 +198,7 @@ function createAnimatedComponent( }); render(): React.Node { - // When rendering in Fabric and an AnimatedValue is used, we keep track of - // the initial value of that Value, to avoid additional prop updates when - // this component re-renders - const initialPropsIfFabric = this._isFabric() - ? this._initialAnimatedProps - : null; - - const animatedProps = - this._propsAnimated.__getValue(initialPropsIfFabric) || {}; - if (!this._initialAnimatedProps) { - this._initialAnimatedProps = animatedProps; - } + const animatedProps = this._propsAnimated.__getValue() || {}; const {style = {}, ...props} = animatedProps; const {style: passthruStyle = {}, ...passthruProps} = diff --git a/Libraries/Animated/nodes/AnimatedProps.js b/Libraries/Animated/nodes/AnimatedProps.js index dbbb8a7ac32538..ef15cdf13120f6 100644 --- a/Libraries/Animated/nodes/AnimatedProps.js +++ b/Libraries/Animated/nodes/AnimatedProps.js @@ -36,22 +36,12 @@ export default class AnimatedProps extends AnimatedNode { this._callback = callback; } - __getValue(initialProps: ?Object): Object { + __getValue(): Object { const props: {[string]: any | ((...args: any) => void)} = {}; for (const key in this._props) { const value = this._props[key]; if (value instanceof AnimatedNode) { - // During initial render we want to use the initial value of both natively and non-natively - // driven nodes. On subsequent renders, we cannot use the value of natively driven nodes - // as they may not be up to date, so we use the initial value to ensure that values of - // native animated nodes do not impact rerenders. - if (value instanceof AnimatedStyle) { - props[key] = value.__getValue(initialProps?.style); - } else if (!initialProps || !value.__isNative) { - props[key] = value.__getValue(); - } else if (initialProps.hasOwnProperty(key)) { - props[key] = initialProps[key]; - } + props[key] = value.__getValue(); } else if (value instanceof AnimatedEvent) { props[key] = value.__getHandler(); } else { diff --git a/Libraries/Animated/nodes/AnimatedStyle.js b/Libraries/Animated/nodes/AnimatedStyle.js index b523b41ba6e1ba..7cb11bb1b55679 100644 --- a/Libraries/Animated/nodes/AnimatedStyle.js +++ b/Libraries/Animated/nodes/AnimatedStyle.js @@ -34,26 +34,15 @@ export default class AnimatedStyle extends AnimatedWithChildren { } // Recursively get values for nested styles (like iOS's shadowOffset) - _walkStyleAndGetValues( - style: any, - initialStyle: ?Object, - ): {[string]: any | {...}} { + _walkStyleAndGetValues(style: any): {[string]: any | {...}} { const updatedStyle: {[string]: any | {...}} = {}; for (const key in style) { const value = style[key]; if (value instanceof AnimatedNode) { - // During initial render we want to use the initial value of both natively and non-natively - // driven nodes. On subsequent renders, we cannot use the value of natively driven nodes - // as they may not be up to date, so we use the initial value to ensure that values of - // native animated nodes do not impact rerenders. - if (!initialStyle || !value.__isNative) { - updatedStyle[key] = value.__getValue(); - } else if (initialStyle.hasOwnProperty(key)) { - updatedStyle[key] = initialStyle[key]; - } + updatedStyle[key] = value.__getValue(); } else if (value && !Array.isArray(value) && typeof value === 'object') { // Support animating nested values (for example: shadowOffset.height) - updatedStyle[key] = this._walkStyleAndGetValues(value, initialStyle); + updatedStyle[key] = this._walkStyleAndGetValues(value); } else { updatedStyle[key] = value; } @@ -61,8 +50,8 @@ export default class AnimatedStyle extends AnimatedWithChildren { return updatedStyle; } - __getValue(initialStyle: ?Object): Object { - return this._walkStyleAndGetValues(this._style, initialStyle); + __getValue(): Object { + return this._walkStyleAndGetValues(this._style); } // Recursively get animated values for nested styles (like iOS's shadowOffset) From 074e3f00093d3ba5e1cfe0132e3d3b46c53c2904 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 07:00:36 -0700 Subject: [PATCH 003/169] RNGP - Introduce the BundleAndHermesCTask Summary: This is part of a series of tasks to make the React Native Gradle Plugin (RNGP) variant-aware. Here I'm creating a new task BundleAndHermesCTask that is variant-aware. Historically we had problems with the Bundle and the Hermes task being separated and overriding their own output. Consolidating those two steps in a single one will make it easier to support seaprate variants. I'm going to use this task in a subsequent diff. Changelog: [Internal] [Changed] - RNGP - Introduce the BundleAndHermesCTask Reviewed By: cipolleschi Differential Revision: D40633108 fbshipit-source-id: 89f6d32ef219626ed5d4c5a0b8ac804c6704b2d6 --- .../facebook/react/tasks/BundleHermesCTask.kt | 185 ++++++++++ .../com/facebook/react/utils/TaskUtils.kt | 5 +- .../react/tasks/BundleHermesCTaskTest.kt | 315 ++++++++++++++++++ .../com/facebook/react/utils/TaskUtilsTest.kt | 6 + 4 files changed, 510 insertions(+), 1 deletion(-) create mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt create mode 100644 packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt new file mode 100644 index 00000000000000..c1dfb58fd13688 --- /dev/null +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt @@ -0,0 +1,185 @@ +/* + * 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.tasks + +import com.facebook.react.utils.detectOSAwareHermesCommand +import com.facebook.react.utils.moveTo +import com.facebook.react.utils.windowsAwareCommandLine +import java.io.File +import org.gradle.api.DefaultTask +import org.gradle.api.file.ConfigurableFileTree +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.RegularFileProperty +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.tasks.* + +abstract class BundleHermesCTask : DefaultTask() { + + init { + group = "react" + } + + @get:Internal abstract val root: DirectoryProperty + + @get:InputFiles + val sources: ConfigurableFileTree = + project.fileTree(root) { + it.include("**/*.js") + it.include("**/*.jsx") + it.include("**/*.ts") + it.include("**/*.tsx") + it.exclude("**/android/**/*") + it.exclude("**/ios/**/*") + it.exclude("**/build/**/*") + it.exclude("**/node_modules/**/*") + } + + @get:Input abstract val nodeExecutableAndArgs: ListProperty + + @get:Input abstract val cliPath: Property + + @get:Input abstract val composeSourceMapsPath: Property + + @get:Input abstract val bundleCommand: Property + + @get:InputFile abstract val entryFile: RegularFileProperty + + @get:InputFile @get:Optional abstract val bundleConfig: RegularFileProperty + + @get:Input abstract val bundleAssetName: Property + + @get:Input abstract val minifyEnabled: Property + + @get:Input abstract val hermesEnabled: Property + + @get:Input abstract val devEnabled: Property + + @get:Input abstract val extraPackagerArgs: ListProperty + + @get:Input abstract val hermesCommand: Property + + @get:Input abstract val hermesFlags: ListProperty + + @get:OutputDirectory abstract val jsBundleDir: DirectoryProperty + + @get:OutputDirectory abstract val resourcesDir: DirectoryProperty + + @get:OutputDirectory abstract val jsIntermediateSourceMapsDir: RegularFileProperty + + @get:OutputDirectory abstract val jsSourceMapsDir: DirectoryProperty + + @TaskAction + fun run() { + jsBundleDir.get().asFile.mkdirs() + resourcesDir.get().asFile.mkdirs() + jsIntermediateSourceMapsDir.get().asFile.mkdirs() + jsSourceMapsDir.get().asFile.mkdirs() + val bundleAssetFilename = bundleAssetName.get() + + val bundleFile = File(jsBundleDir.get().asFile, bundleAssetFilename) + val packagerSourceMap = resolvePackagerSourceMapFile(bundleAssetFilename) + + val bundleCommand = getBundleCommand(bundleFile, packagerSourceMap) + runCommand(bundleCommand) + + if (hermesEnabled.get()) { + val detectedHermesCommand = detectOSAwareHermesCommand(root.get().asFile, hermesCommand.get()) + val bytecodeTempFile = File("${bundleFile}.hbc") + val outputSourceMap = resolveOutputSourceMap(bundleAssetFilename) + val compilerSourceMap = resolveCompilerSourceMap(bundleAssetFilename) + + val hermesCommand = getHermescCommand(detectedHermesCommand, bundleFile, packagerSourceMap) + runCommand(hermesCommand) + bytecodeTempFile.moveTo(bundleFile) + + if (hermesFlags.get().contains("-output-source-map")) { + val hermesTempSourceMapFile = File("$bytecodeTempFile.map") + hermesTempSourceMapFile.moveTo(compilerSourceMap) + val composeSourceMapsCommand = + getComposeSourceMapsCommand(packagerSourceMap, compilerSourceMap, outputSourceMap) + runCommand(composeSourceMapsCommand) + } + } + } + + internal fun resolvePackagerSourceMapFile(bundleAssetName: String) = + if (hermesEnabled.get()) { + File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.packager.map") + } else { + resolveOutputSourceMap(bundleAssetName) + } + + internal fun resolveOutputSourceMap(bundleAssetName: String) = + File(jsSourceMapsDir.get().asFile, "$bundleAssetName.map") + + internal fun resolveCompilerSourceMap(bundleAssetName: String) = + File(jsIntermediateSourceMapsDir.get().asFile, "$bundleAssetName.compiler.map") + + private fun runCommand(command: List) { + project.exec { + it.workingDir(root.get().asFile) + it.commandLine(command) + } + } + + internal fun getBundleCommand(bundleFile: File, sourceMapFile: File): List = + windowsAwareCommandLine( + buildList { + addAll(nodeExecutableAndArgs.get()) + add(cliPath.get()) + add(bundleCommand.get()) + add("--platform") + add("android") + add("--dev") + add(devEnabled.get().toString()) + add("--reset-cache") + add("--entry-file") + add(entryFile.get().asFile.toString()) + add("--bundle-output") + add(bundleFile.toString()) + add("--assets-dest") + add(resourcesDir.get().asFile.toString()) + add("--sourcemap-output") + add(sourceMapFile.toString()) + if (bundleConfig.isPresent) { + add("--config") + add(bundleConfig.get().asFile.absolutePath) + } + add("--minify") + add(minifyEnabled.get().toString()) + addAll(extraPackagerArgs.get()) + add("--verbose") + }) + + internal fun getHermescCommand( + hermesCommand: String, + bundleFile: File, + outputFile: File + ): List = + windowsAwareCommandLine( + hermesCommand, + "-emit-binary", + "-out", + outputFile.absolutePath, + bundleFile.absolutePath, + *hermesFlags.get().toTypedArray()) + + internal fun getComposeSourceMapsCommand( + packagerSourceMap: File, + compilerSourceMap: File, + outputSourceMap: File + ): List = + windowsAwareCommandLine( + *nodeExecutableAndArgs.get().toTypedArray(), + composeSourceMapsPath.get(), + packagerSourceMap.toString(), + compilerSourceMap.toString(), + "-o", + outputSourceMap.toString()) +} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt index fd557079f59dd5..df99d06e47bc26 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/TaskUtils.kt @@ -8,10 +8,13 @@ package com.facebook.react.utils internal fun windowsAwareCommandLine(vararg args: Any): List = + windowsAwareCommandLine(args.toList()) + +internal fun windowsAwareCommandLine(args: List): List = if (Os.isWindows()) { listOf("cmd", "/c") + args } else { - args.toList() + args } internal fun windowsAwareBashCommandLine( diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt new file mode 100644 index 00000000000000..8a180e1080d1b4 --- /dev/null +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt @@ -0,0 +1,315 @@ +/* + * 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.tasks + +import com.facebook.react.tests.OsRule +import com.facebook.react.tests.createTestTask +import java.io.File +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class BundleHermesCTaskTest { + + @get:Rule val tempFolder = TemporaryFolder() + + @get:Rule val osRule = OsRule() + + @Test + fun bundleTask_groupIsSetCorrectly() { + val task = createTestTask {} + assertEquals("react", task.group) + } + + @Test + fun bundleTask_inputFiles_areSetCorrectly() { + val rootDir = + tempFolder.newFolder("js").apply { + File(this, "file.js").createNewFile() + File(this, "file.jsx").createNewFile() + File(this, "file.ts").createNewFile() + File(this, "file.tsx").createNewFile() + } + + val task = createTestTask { it.root.set(rootDir) } + + assertEquals(4, task.sources.files.size) + assertEquals( + setOf( + File(rootDir, "file.js"), + File(rootDir, "file.jsx"), + File(rootDir, "file.ts"), + File(rootDir, "file.tsx")), + task.sources.files) + } + + @Test + fun bundleTask_inputFilesInExcludedPath_areExcluded() { + fun File.createFileAndPath() { + parentFile.mkdirs() + createNewFile() + } + + val rootDir = + tempFolder.newFolder("js").apply { + File(this, "afolder/includedfile.js").createFileAndPath() + // Those files should be excluded due to their filepath + File(this, "android/excludedfile.js").createFileAndPath() + File(this, "ios/excludedfile.js").createFileAndPath() + File(this, "build/excludedfile.js").createFileAndPath() + File(this, "node_modules/react-native/excludedfile.js").createFileAndPath() + } + + val task = createTestTask { it.root.set(rootDir) } + + assertEquals( + setOf( + "**/android/**/*", + "**/ios/**/*", + "**/build/**/*", + "**/node_modules/**/*", + ), + task.sources.excludes) + assertEquals(1, task.sources.files.size) + assertEquals(setOf(File(rootDir, "afolder/includedfile.js")), task.sources.files) + } + + @Test + fun bundleTask_staticInputs_areSetCorrectly() { + val task = + createTestTask { + it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) + it.cliPath.set("../node_modules/react-native/cli.js") + it.composeSourceMapsPath.set( + "../node_modules/react-native/scripts/compose-source-maps.js") + it.bundleCommand.set("bundle") + it.bundleAssetName.set("myassetname") + it.minifyEnabled.set(true) + it.hermesEnabled.set(true) + it.devEnabled.set(true) + it.extraPackagerArgs.set(listOf("extra", "arg")) + it.hermesCommand.set("./my-hermesc") + it.hermesFlags.set(listOf("flag1", "flag2")) + } + + assertEquals(listOf("node", "arg1", "arg2"), task.nodeExecutableAndArgs.get()) + assertEquals("../node_modules/react-native/cli.js", task.cliPath.get()) + assertEquals( + "../node_modules/react-native/scripts/compose-source-maps.js", + task.composeSourceMapsPath.get()) + assertEquals("bundle", task.bundleCommand.get()) + assertEquals("myassetname", task.bundleAssetName.get()) + assertTrue(task.minifyEnabled.get()) + assertTrue(task.hermesEnabled.get()) + assertTrue(task.devEnabled.get()) + assertEquals(listOf("extra", "arg"), task.extraPackagerArgs.get()) + assertEquals("./my-hermesc", task.hermesCommand.get()) + assertEquals(listOf("flag1", "flag2"), task.hermesFlags.get()) + } + + @Test + fun bundleTask_filesInput_areSetCorrectly() { + val entryFile = tempFolder.newFile("entry.js") + val jsBundleDir = tempFolder.newFolder("jsbundle") + val resourcesDir = tempFolder.newFolder("resources") + val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") + val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") + val bundleConfig = tempFolder.newFile("bundle.config") + + val task = + createTestTask { + it.entryFile.set(entryFile) + it.jsBundleDir.set(jsBundleDir) + it.resourcesDir.set(resourcesDir) + it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) + it.jsSourceMapsDir.set(jsSourceMapsDir) + it.bundleConfig.set(bundleConfig) + } + + assertEquals(entryFile, task.entryFile.get().asFile) + assertEquals(jsBundleDir, task.jsBundleDir.get().asFile) + assertEquals(resourcesDir, task.resourcesDir.get().asFile) + assertEquals(jsIntermediateSourceMapsDir, task.jsIntermediateSourceMapsDir.get().asFile) + assertEquals(jsSourceMapsDir, task.jsSourceMapsDir.get().asFile) + assertEquals(bundleConfig, task.bundleConfig.get().asFile) + } + + @Test + fun resolvePackagerSourceMapFile_withHermesEnabled_returnsCorrectFile() { + val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") + val bundleAssetName = "myassetname" + val task = + createTestTask { + it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) + it.hermesEnabled.set(true) + it.bundleAssetName.set(bundleAssetName) + } + + assertEquals( + File(jsIntermediateSourceMapsDir, "myassetname.packager.map"), + task.resolvePackagerSourceMapFile(bundleAssetName)) + } + + @Test + fun resolvePackagerSourceMapFile_withHermesDisabled_returnsCorrectFile() { + val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") + val bundleAssetName = "myassetname" + val task = + createTestTask { + it.jsSourceMapsDir.set(jsSourceMapsDir) + it.hermesEnabled.set(false) + } + + assertEquals( + File(jsSourceMapsDir, "myassetname.map"), + task.resolvePackagerSourceMapFile(bundleAssetName)) + } + + @Test + fun resolveOutputSourceMap_returnsCorrectFile() { + val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") + val bundleAssetName = "myassetname" + val task = createTestTask { it.jsSourceMapsDir.set(jsSourceMapsDir) } + + assertEquals( + File(jsSourceMapsDir, "myassetname.map"), task.resolveOutputSourceMap(bundleAssetName)) + } + + @Test + fun resolveCompilerSourceMap_returnsCorrectFile() { + val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") + val bundleAssetName = "myassetname" + val task = + createTestTask { + it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) + } + + assertEquals( + File(jsIntermediateSourceMapsDir, "myassetname.compiler.map"), + task.resolveCompilerSourceMap(bundleAssetName)) + } + + @Test + fun getBundleCommand_returnsCorrectCommand() { + val entryFile = tempFolder.newFile("index.js") + val bundleFile = tempFolder.newFile("bundle.js") + val sourceMapFile = tempFolder.newFile("bundle.js.map") + val resourcesDir = tempFolder.newFolder("res") + val bundleConfig = tempFolder.newFile("bundle.config") + val task = + createTestTask { + it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) + it.cliPath.set("../node_modules/react-native/cli.js") + it.bundleCommand.set("bundle") + it.devEnabled.set(true) + it.entryFile.set(entryFile) + it.resourcesDir.set(resourcesDir) + it.bundleConfig.set(bundleConfig) + it.minifyEnabled.set(true) + it.extraPackagerArgs.set(listOf("--read-global-cache")) + } + + val bundleCommand = task.getBundleCommand(bundleFile, sourceMapFile) + + assertEquals("node", bundleCommand[0]) + assertEquals("arg1", bundleCommand[1]) + assertEquals("arg2", bundleCommand[2]) + assertEquals("../node_modules/react-native/cli.js", bundleCommand[3]) + assertEquals("bundle", bundleCommand[4]) + assertEquals("--platform", bundleCommand[5]) + assertEquals("android", bundleCommand[6]) + assertEquals("--dev", bundleCommand[7]) + assertEquals("true", bundleCommand[8]) + assertEquals("--reset-cache", bundleCommand[9]) + assertEquals("--entry-file", bundleCommand[10]) + assertEquals(entryFile.absolutePath, bundleCommand[11]) + assertEquals("--bundle-output", bundleCommand[12]) + assertEquals(bundleFile.absolutePath, bundleCommand[13]) + assertEquals("--assets-dest", bundleCommand[14]) + assertEquals(resourcesDir.absolutePath, bundleCommand[15]) + assertEquals("--sourcemap-output", bundleCommand[16]) + assertEquals(sourceMapFile.absolutePath, bundleCommand[17]) + assertEquals("--config", bundleCommand[18]) + assertEquals(bundleConfig.absolutePath, bundleCommand[19]) + assertEquals("--minify", bundleCommand[20]) + assertEquals("true", bundleCommand[21]) + assertEquals("--read-global-cache", bundleCommand[22]) + assertEquals("--verbose", bundleCommand[23]) + assertEquals(24, bundleCommand.size) + } + + @Test + fun getBundleCommand_withoutConfig_returnsCommandWithoutConfig() { + val entryFile = tempFolder.newFile("index.js") + val bundleFile = tempFolder.newFile("bundle.js") + val sourceMapFile = tempFolder.newFile("bundle.js.map") + val resourcesDir = tempFolder.newFolder("res") + val task = + createTestTask { + it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) + it.cliPath.set("../node_modules/react-native/cli.js") + it.bundleCommand.set("bundle") + it.devEnabled.set(true) + it.entryFile.set(entryFile) + it.resourcesDir.set(resourcesDir) + it.minifyEnabled.set(true) + it.extraPackagerArgs.set(listOf("--read-global-cache")) + } + + val bundleCommand = task.getBundleCommand(bundleFile, sourceMapFile) + + assertTrue("--config" !in bundleCommand) + } + + @Test + fun getHermescCommand_returnsCorrectCommand() { + val customHermesc = "hermesc" + val bundleFile = tempFolder.newFile("bundle.js") + val outputFile = tempFolder.newFile("bundle.js.packager.map") + val task = + createTestTask { it.hermesFlags.set(listOf("my-custom-hermes-flag")) } + + val hermesCommand = task.getHermescCommand(customHermesc, bundleFile, outputFile) + + assertEquals(customHermesc, hermesCommand[0]) + assertEquals("-emit-binary", hermesCommand[1]) + assertEquals("-out", hermesCommand[2]) + assertEquals(outputFile.absolutePath, hermesCommand[3]) + assertEquals(bundleFile.absolutePath, hermesCommand[4]) + assertEquals("my-custom-hermes-flag", hermesCommand[5]) + assertEquals(6, hermesCommand.size) + } + + @Test + fun getComposeSourceMapsCommand_returnsCorrectCommand() { + val packagerMap = tempFolder.newFile("bundle.js.packager.map") + val compilerMap = tempFolder.newFile("bundle.js.compiler.map") + val outputMap = tempFolder.newFile("bundle.js.map") + val task = + createTestTask { + it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) + it.composeSourceMapsPath.set( + "../node_modules/react-native/scripts/compose-source-maps.js") + } + + val composeSourcemapCommand = + task.getComposeSourceMapsCommand(packagerMap, compilerMap, outputMap) + + assertEquals("node", composeSourcemapCommand[0]) + assertEquals("arg1", composeSourcemapCommand[1]) + assertEquals("arg2", composeSourcemapCommand[2]) + assertEquals( + "../node_modules/react-native/scripts/compose-source-maps.js", composeSourcemapCommand[3]) + assertEquals(packagerMap.absolutePath, composeSourcemapCommand[4]) + assertEquals(compilerMap.absolutePath, composeSourcemapCommand[5]) + assertEquals("-o", composeSourcemapCommand[6]) + assertEquals(outputMap.absolutePath, composeSourcemapCommand[7]) + assertEquals(8, composeSourcemapCommand.size) + } +} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt index a1534d365998fe..cafbba6f7afd90 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/TaskUtilsTest.kt @@ -24,6 +24,12 @@ class TaskUtilsTest { assertTrue(windowsAwareCommandLine().isEmpty()) } + @Test + fun windowsAwareCommandLine_withList_isEqualAsVararg() { + assertEquals( + windowsAwareCommandLine(listOf("a", "b", "c")), windowsAwareCommandLine("a", "b", "c")) + } + @Test @WithOs(OS.MAC) fun windowsAwareCommandLine_onMac_returnsTheList() { From 41fec07e2062e83ff5a8236fd625328d8648e4e5 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 07:00:36 -0700 Subject: [PATCH 004/169] RNGP - Top level property enableHermes -> hermesEnabled Summary: This is part of a series of tasks to make the React Native Gradle Plugin (RNGP) variant-aware. Here I'm renaming the top level property to enable hermes from `enableHermes` to `hermesEnabled`. We have a bunch of other properties which are called *Enabled. This one was following a different convention. I'm retaining the backward compatibility for users using `project.ext.react.enableHermes` so this is not going to be a breakign change. Changelog: [Internal] [Changed] - RNGP - Top level property enableHermes -> hermesEnabled Reviewed By: cipolleschi Differential Revision: D40633109 fbshipit-source-id: 9d7efad6cb3bb382d1beb56966795a3f42bdaae6 --- .../main/kotlin/com/facebook/react/utils/ProjectUtils.kt | 4 ++-- .../kotlin/com/facebook/react/utils/ProjectUtilsTest.kt | 6 +++--- packages/rn-tester/android/app/gradle.properties | 2 ++ 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt index 17a0982ad83b1f..f70e14cbccabde 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt @@ -19,8 +19,8 @@ internal object ProjectUtils { internal val Project.isHermesEnabled: Boolean get() = - if (project.hasProperty("enableHermes")) { - project.property("enableHermes").toString().lowercase().toBooleanStrictOrNull() ?: true + if (project.hasProperty("hermesEnabled")) { + project.property("hermesEnabled").toString().lowercase().toBooleanStrictOrNull() ?: true } else if (project.extensions.extraProperties.has("react")) { @Suppress("UNCHECKED_CAST") val reactMap = project.extensions.extraProperties.get("react") as? Map diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt index 495715416f7608..c41cc65a27ccf5 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt @@ -50,21 +50,21 @@ class ProjectUtilsTest { @Test fun isNewArchEnabled_withDisabledViaProperty_returnsFalse() { val project = createProject() - project.extensions.extraProperties.set("enableHermes", "false") + project.extensions.extraProperties.set("hermesEnabled", "false") assertFalse(project.isHermesEnabled) } @Test fun isHermesEnabled_withEnabledViaProperty_returnsTrue() { val project = createProject() - project.extensions.extraProperties.set("enableHermes", "true") + project.extensions.extraProperties.set("hermesEnabled", "true") assertTrue(project.isHermesEnabled) } @Test fun isHermesEnabled_withInvalidViaProperty_returnsTrue() { val project = createProject() - project.extensions.extraProperties.set("enableHermes", "¯\\_(ツ)_/¯") + project.extensions.extraProperties.set("hermesEnabled", "¯\\_(ツ)_/¯") assertTrue(project.isHermesEnabled) } diff --git a/packages/rn-tester/android/app/gradle.properties b/packages/rn-tester/android/app/gradle.properties index 159049803a664d..18b9871789b1b0 100644 --- a/packages/rn-tester/android/app/gradle.properties +++ b/packages/rn-tester/android/app/gradle.properties @@ -14,3 +14,5 @@ FLIPPER_VERSION=0.125.0 # RN-Tester is building with NewArch always enabled newArchEnabled=true +# RN-Tester is running with Hermes enabled and filtering variants with enableHermesOnlyInVariants +hermesEnabled=true From 56d8c23f7b09feac03b22980552b7c061c76accc Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 07:00:36 -0700 Subject: [PATCH 005/169] RNGP - Introduce enableCodegenInApps Summary: This is part of a series of tasks to make the React Native Gradle Plugin (RNGP) variant-aware. Historically we used to enable the codegen only for library modules. This is not working well for apps like RN Tester which don't have library modules but are running the codegen. Therefore I'm introducing the `enableCodegenInApps` that is allowing apps to turn off the codegen if needed. Changelog: [Internal] [Changed] - RNGP - Introduce enableCodegenInApps Reviewed By: cipolleschi Differential Revision: D40633106 fbshipit-source-id: dc2ae9bbfe5b7940f9e9fe505ab2198a42c8a3f6 --- .../com/facebook/react/ReactExtension.kt | 7 +++ .../kotlin/com/facebook/react/ReactPlugin.kt | 54 +++++++++---------- packages/rn-tester/android/app/build.gradle | 1 + 3 files changed, 33 insertions(+), 29 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt index 6c09759a0819c8..a2bfff06b0d656 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt @@ -221,4 +221,11 @@ abstract class ReactExtension @Inject constructor(project: Project) { */ val codegenJavaPackageName: Property = objects.property(String::class.java).convention("com.facebook.fbreact.specs") + + /** + * Toggles the Codegen for App modules. By default we enable the codegen only for library modules. + * If you want to enable codegen in your app, you will have to set this to true. Default: false + */ + val enableCodegenInApps: Property = + objects.property(Boolean::class.java).convention(false) } diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt index 034a6be090f8f2..5ca275ea050186 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt @@ -9,7 +9,6 @@ package com.facebook.react import com.android.build.api.variant.AndroidComponentsExtension import com.android.build.gradle.AppExtension -import com.android.build.gradle.LibraryExtension import com.android.build.gradle.internal.tasks.factory.dependsOn import com.facebook.react.tasks.BuildCodegenCLITask import com.facebook.react.tasks.GenerateCodegenArtifactsTask @@ -21,7 +20,6 @@ import com.facebook.react.utils.NdkConfiguratorUtils.configureReactNativeNdk import com.facebook.react.utils.findPackageJsonFile import java.io.File import kotlin.system.exitProcess -import org.gradle.api.Action import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task @@ -31,8 +29,25 @@ class ReactPlugin : Plugin { override fun apply(project: Project) { checkJvmVersion(project) val extension = project.extensions.create("react", ReactExtension::class.java, project) - applyAppPlugin(project, extension) - applyCodegenPlugin(project, extension) + + // App Only Configuration + project.pluginManager.withPlugin("com.android.application") { + configureReactNativeNdk(project, extension) + configureBuildConfigFields(project) + configureDevPorts(project) + + project.afterEvaluate { + project.extensions.getByType(AppExtension::class.java).applicationVariants.all { + project.configureReactTasks(variant = it, config = extension) + } + } + configureCodegen(project, extension, isLibrary = false) + } + + // Library Only Configuration + project.pluginManager.withPlugin("com.android.library") { + configureCodegen(project, extension, isLibrary = true) + } } private fun checkJvmVersion(project: Project) { @@ -54,30 +69,12 @@ class ReactPlugin : Plugin { } } - private fun applyAppPlugin(project: Project, config: ReactExtension) { - project.pluginManager.withPlugin("com.android.application") { - configureReactNativeNdk(project, config) - configureBuildConfigFields(project) - configureDevPorts(project) - project.afterEvaluate { - val isAndroidLibrary = project.plugins.hasPlugin("com.android.library") - val variants = - if (isAndroidLibrary) { - project.extensions.getByType(LibraryExtension::class.java).libraryVariants - } else { - project.extensions.getByType(AppExtension::class.java).applicationVariants - } - variants.all { project.configureReactTasks(variant = it, config = config) } - } - } - } - /** * A plugin to enable react-native-codegen in Gradle environment. See the Gradle API docs for more * information: https://docs.gradle.org/current/javadoc/org/gradle/api/Project.html */ @Suppress("UnstableApiUsage") - private fun applyCodegenPlugin(project: Project, extension: ReactExtension) { + private fun configureCodegen(project: Project, extension: ReactExtension, isLibrary: Boolean) { // First, we set up the output dir for the codegen. val generatedSrcDir = File(project.buildDir, "generated/source/codegen") @@ -86,6 +83,7 @@ class ReactPlugin : Plugin { it.codegenDir.set(extension.codegenDir) val bashWindowsHome = project.findProperty("REACT_WINDOWS_BASH") as String? it.bashWindowsHome.set(bashWindowsHome) + it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } } // We create the task to produce schema from JS files. @@ -96,6 +94,7 @@ class ReactPlugin : Plugin { it.nodeExecutableAndArgs.set(extension.nodeExecutableAndArgs) it.codegenDir.set(extension.codegenDir) it.generatedSrcDir.set(generatedSrcDir) + it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } // We're reading the package.json at configuration time to properly feed // the `jsRootDir` @Input property of this task. Therefore, the @@ -123,6 +122,7 @@ class ReactPlugin : Plugin { it.packageJsonFile.set(findPackageJsonFile(project, extension)) it.codegenJavaPackageName.set(extension.codegenJavaPackageName) it.libraryName.set(extension.libraryName) + it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } } // We update the android configuration to include the generated sources. @@ -133,12 +133,8 @@ class ReactPlugin : Plugin { ext.sourceSets.getByName("main").java.srcDir(File(generatedSrcDir, "java")) } - // `preBuild` is one of the base tasks automatically registered by Gradle. + // `preBuild` is one of the base tasks automatically registered by AGP. // This will invoke the codegen before compiling the entire project. - val androidPluginHandler = Action { _: Plugin<*> -> - project.tasks.named("preBuild", Task::class.java).dependsOn(generateCodegenArtifactsTask) - } - project.plugins.withId("com.android.application", androidPluginHandler) - project.plugins.withId("com.android.library", androidPluginHandler) + project.tasks.named("preBuild", Task::class.java).dependsOn(generateCodegenArtifactsTask) } } diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index e80589e004d32b..a7f7e9100fe0be 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -88,6 +88,7 @@ react { // Codegen Configs reactNativeDir = rootDir codegenDir = new File(rootDir, "node_modules/react-native-codegen") + enableCodegenInApps = true } /** From 2cc2ca1d1cd5d15ba6eef50d20ee546134f1b9c6 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 07:00:36 -0700 Subject: [PATCH 006/169] RNGP - Automatically Configure Dependencies for ReactNative & Hermes Summary: This is part of a series of tasks to make the React Native Gradle Plugin (RNGP) variant-aware. I'm extending RNGP to do autoconfiguration of dependencies for React Native and Hermes Engine using the Utils classes which were introduced before. Changelog: [Internal] [Changed] - RNGP - Automatically Configure Dependencies for ReactNative & Hermes Reviewed By: cipolleschi Differential Revision: D40633487 fbshipit-source-id: d4240987a9400fff2ec2aff2d13afc5b24778598 --- .../src/main/kotlin/com/facebook/react/ReactPlugin.kt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt index 5ca275ea050186..c40f1491269ca7 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt @@ -15,6 +15,9 @@ import com.facebook.react.tasks.GenerateCodegenArtifactsTask import com.facebook.react.tasks.GenerateCodegenSchemaTask import com.facebook.react.utils.AgpConfiguratorUtils.configureBuildConfigFields import com.facebook.react.utils.AgpConfiguratorUtils.configureDevPorts +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.JsonUtils import com.facebook.react.utils.NdkConfiguratorUtils.configureReactNativeNdk import com.facebook.react.utils.findPackageJsonFile @@ -32,6 +35,14 @@ class ReactPlugin : Plugin { // App Only Configuration project.pluginManager.withPlugin("com.android.application") { + project.afterEvaluate { + val reactNativeDir = extension.reactNativeDir.get().asFile + val propertiesFile = File(reactNativeDir, "ReactAndroid/gradle.properties") + val versionString = readVersionString(propertiesFile) + configureDependencies(project, versionString) + configureRepositories(project, reactNativeDir) + } + configureReactNativeNdk(project, extension) configureBuildConfigFields(project) configureDevPorts(project) From 8ad86c70b6341f2e8bd40f5ba86f1a0d451008b0 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 07:00:36 -0700 Subject: [PATCH 007/169] RNGP - Add Variant Support (#35063) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35063 This is part of a series of tasks to make the React Native Gradle Plugin (RNGP) variant-aware. Here I'm add Variant support to RNGP via the Variant API from AGP 7.x A short summary of changes: - I've pushed a number of breaking changes to ReactExtension (we should document them in the release notes). Specifically I've removed properties which I believe were unnecessary and confusing - I've removed all the extra logic to do the .so cleanups and use the new tasks that use the Artifacts API - I've introduced only a `debuggableVariants` to make all the decisions for the bundling and minification which should be sufficient for users - I've removed all the funcional interfaces are replaced them with lists as they're easy to handle and understand for users. Changelog: [Android] [Changed] - Added Flavor Support to React Native Gradle Plugin (RNGP) Reviewed By: cipolleschi Differential Revision: D40335028 fbshipit-source-id: d9ac1437de8a27db2e93df15b13772b221e036b2 --- .../com/facebook/react/ReactExtension.kt | 105 ++----- .../kotlin/com/facebook/react/ReactPlugin.kt | 7 +- .../com/facebook/react/TaskConfiguration.kt | 293 +++++------------- .../react/tasks/BundleJsAndAssetsTask.kt | 73 ----- .../facebook/react/tasks/HermesBinaryTask.kt | 77 ----- packages/rn-tester/android/app/build.gradle | 7 +- 6 files changed, 96 insertions(+), 466 deletions(-) delete mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleJsAndAssetsTask.kt delete mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/HermesBinaryTask.kt diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt index a2bfff06b0d656..4e7573876540cf 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt @@ -7,15 +7,12 @@ package com.facebook.react -import com.android.build.gradle.api.BaseVariant import com.facebook.react.utils.projectPathToLibraryName -import java.io.File import javax.inject.Inject import org.gradle.api.Project import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.MapProperty import org.gradle.api.provider.Property abstract class ReactExtension @Inject constructor(project: Project) { @@ -54,10 +51,10 @@ abstract class ReactExtension @Inject constructor(project: Project) { val bundleCommand: Property = objects.property(String::class.java).convention("bundle") /** - * Custom configuration for the [bundleCommand]. If provided it will be passed over with a + * Custom configuration file for the [bundleCommand]. If provided, it will be passed over with a * `--config` flag to the bundle command. */ - val bundleConfig: Property = objects.property(String::class.java) + val bundleConfig: RegularFileProperty = objects.fileProperty() /** * The Bundle Asset name. This name will be used also for deriving other bundle outputs such as @@ -69,69 +66,24 @@ abstract class ReactExtension @Inject constructor(project: Project) { objects.property(String::class.java).convention("index.android.bundle") /** - * Variant Name to File destination map that allows to specify where is the resource dir for a - * specific variant. If a value is supplied, the plugin will copy the bundled resource for that - * variant from `generated/res/react/` into the custom specified location. Default: {} + * Toggles the .so Cleanup step. If enabled, we will clean up all the unnecessary files before the + * bundle task. If disabled, the developers will have to manually cleanup the files. Default: true */ - val resourcesDir: MapProperty = - objects.mapProperty(String::class.java, File::class.java).convention(emptyMap()) - - /** - * Variant Name to File destination map that allows to specify where is the asset dir for a - * specific variant. If a value is supplied, the plugin will copy the bundled JS for that variant - * from `generated/assets/react/` into the custom specified location. Default: {} - */ - val jsBundleDir: MapProperty = - objects.mapProperty(String::class.java, File::class.java).convention(emptyMap()) - - /** ANT-style excludes for the bundle command. Default: ["android / **", "ios / **"] */ - val inputExcludes: ListProperty = - objects.listProperty(String::class.java).convention(listOf("android/**", "ios/**")) - - /** - * Toggles the VM Cleanup step. If enabled, before the bundle task we will clean up all the - * unnecessary files. If disabled, the developers will have to manually cleanup the files. - * Default: true - */ - val enableVmCleanup: Property = objects.property(Boolean::class.java).convention(true) + val enableSoCleanup: Property = objects.property(Boolean::class.java).convention(true) /** Extra args that will be passed to the [bundleCommand] Default: [] */ val extraPackagerArgs: ListProperty = objects.listProperty(String::class.java).convention(emptyList()) /** - * Allows to disable dev mode for certain variants. That's useful if you have a production variant - * (say `canary`) where you don't want dev mode to be enabled. Default: [] - */ - val devDisabledInVariants: ListProperty = - objects.listProperty(String::class.java).convention(emptyList()) - - /** - * Functional interface to disable dev mode only on specific [BaseVariant] Default: will check - * [devDisabledInVariants] or return True for Release variants and False for Debug variants. - */ - var disableDevForVariant: (BaseVariant) -> Boolean = { variant -> - variant.name in devDisabledInVariants.get() || variant.isRelease - } - - /** - * Variant Name to Boolean map that allows to toggle the bundle command for a specific variant. - * Default: {} - */ - // todo maybe lambda as for hermes? - val bundleIn: MapProperty = - objects.mapProperty(String::class.java, Boolean::class.java).convention(emptyMap()) - - /** - * Functional interface to toggle the bundle command only on specific [BaseVariant] Default: will - * check [bundleIn] or return True for Release variants and False for Debug variants. + * Allows to specify the debuggable variants (by default just 'debug'). Variants in this list + * will: + * - Not be bundled (the bundle file will not be created and won't be copied over). + * - Have the Hermes Debug flags set. That's useful if you have another variant (say `canary`) + * where you want dev mode to be enabled. Default: ['debug'] */ - var bundleForVariant: (BaseVariant) -> Boolean = { variant -> - if (bundleIn.getting(variant.name).isPresent) bundleIn.getting(variant.name).get() - else if (bundleIn.getting(variant.buildType.name).isPresent) - bundleIn.getting(variant.buildType.name).get() - else variant.isRelease - } + val debuggableVariants: ListProperty = + objects.listProperty(String::class.java).convention(listOf("debug")) /** Hermes Config */ @@ -141,35 +93,18 @@ abstract class ReactExtension @Inject constructor(project: Project) { */ val hermesCommand: Property = objects.property(String::class.java).convention("") - /** Toggle Hermes for the whole build. Default: false */ - val enableHermes: Property = objects.property(Boolean::class.java).convention(false) - /** - * Functional interface to selectively enabled Hermes only on specific [BaseVariant] Default: will - * return [enableHermes] for all the variants. - */ - var enableHermesForVariant: (BaseVariant) -> Boolean = { enableHermes.get() } - - /** - * Functional interface specify flags for Hermes on specific [BaseVariant] Default: will return - * [hermesFlagsRelease] for Release variants and [hermesFlagsDebug] for Debug variants. - */ - var hermesFlagsForVariant: (BaseVariant) -> List = { variant -> - if (variant.isRelease) hermesFlagsRelease.get() else hermesFlagsDebug.get() - } - - /** - * Functional interface to delete debug files only on specific [BaseVariant] Default: will return - * True for Release variants and False for Debug variants. + * Whether to enable Hermes only on certain variants. If specified as a non-empty list, hermesc + * and the .so cleanup for Hermes will be executed only for variants in this list. An empty list + * assumes you're either using Hermes for all variants or not (see [enableHermes]). + * + * Default: [] */ - var deleteDebugFilesForVariant: (BaseVariant) -> Boolean = { variant -> variant.isRelease } - - /** Flags to pass to Hermes for Debug variants. Default: [] */ - val hermesFlagsDebug: ListProperty = + val enableHermesOnlyInVariants: ListProperty = objects.listProperty(String::class.java).convention(emptyList()) - /** Flags to pass to Hermes for Release variants. Default: ["-O", "-output-source-map"] */ - val hermesFlagsRelease: ListProperty = + /** Flags to pass to Hermesc. Default: ["-O", "-output-source-map"] */ + val hermesFlags: ListProperty = objects.listProperty(String::class.java).convention(listOf("-O", "-output-source-map")) /** diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt index c40f1491269ca7..24790daa83c565 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt @@ -8,7 +8,6 @@ package com.facebook.react import com.android.build.api.variant.AndroidComponentsExtension -import com.android.build.gradle.AppExtension import com.android.build.gradle.internal.tasks.factory.dependsOn import com.facebook.react.tasks.BuildCodegenCLITask import com.facebook.react.tasks.GenerateCodegenArtifactsTask @@ -47,10 +46,8 @@ class ReactPlugin : Plugin { configureBuildConfigFields(project) configureDevPorts(project) - project.afterEvaluate { - project.extensions.getByType(AppExtension::class.java).applicationVariants.all { - project.configureReactTasks(variant = it, config = extension) - } + project.extensions.getByType(AndroidComponentsExtension::class.java).onVariants { variant -> + project.configureReactTasks(variant = variant, config = extension) } configureCodegen(project, extension, isLibrary = false) } diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt index bba9e91f959c11..4ec27e9f559d94 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt @@ -7,246 +7,95 @@ package com.facebook.react -import com.android.build.gradle.api.ApplicationVariant -import com.android.build.gradle.api.BaseVariant -import com.android.build.gradle.api.LibraryVariant -import com.android.build.gradle.internal.tasks.factory.dependsOn -import com.facebook.react.tasks.BundleJsAndAssetsTask -import com.facebook.react.tasks.HermesBinaryTask +import com.android.build.api.artifact.SingleArtifact +import com.android.build.api.variant.Variant +import com.facebook.react.tasks.BundleHermesCTask +import com.facebook.react.tasks.NativeLibraryAabCleanupTask +import com.facebook.react.tasks.NativeLibraryApkCleanupTask +import com.facebook.react.utils.ProjectUtils.isHermesEnabled import com.facebook.react.utils.detectedCliPath import com.facebook.react.utils.detectedEntryFile import java.io.File import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.api.tasks.Copy -import org.gradle.api.tasks.TaskProvider -private const val REACT_GROUP = "react" - -@Suppress("SpreadOperator") -internal fun Project.configureReactTasks(variant: BaseVariant, config: ReactExtension) { +@Suppress("SpreadOperator", "UnstableApiUsage") +internal fun Project.configureReactTasks(variant: Variant, config: ReactExtension) { val targetName = variant.name.replaceFirstChar { it.uppercase() } - val targetPath = variant.dirName + val targetPath = variant.name // React js bundle directories - val jsBundleDir = File(buildDir, "generated/assets/react/$targetPath") val resourcesDir = File(buildDir, "generated/res/react/$targetPath") - - val bundleAssetName = config.bundleAssetName.get() - val jsBundleFile = File(jsBundleDir, bundleAssetName) + // Bundle: generated/assets/react/path/index.android.bundle + val jsBundleDir = File(buildDir, "generated/assets/react/$targetPath") + // Sourcemap: generated/sourcemaps/react/path/index.android.bundle.map val jsSourceMapsDir = File(buildDir, "generated/sourcemaps/react/$targetPath") + // Intermediate packager: intermediates/sourcemaps/react/path/index.android.bundle.packager.map + // Intermediate compiler: intermediates/sourcemaps/react/path/index.android.bundle.compiler.map val jsIntermediateSourceMapsDir = File(buildDir, "intermediates/sourcemaps/react/$targetPath") - val jsPackagerSourceMapFile = File(jsIntermediateSourceMapsDir, "${bundleAssetName}.packager.map") - val jsCompilerSourceMapFile = File(jsIntermediateSourceMapsDir, "${bundleAssetName}.compiler.map") - val jsOutputSourceMapFile = File(jsSourceMapsDir, "${bundleAssetName}.map") // Additional node and packager commandline arguments - val nodeExecutableAndArgs = config.nodeExecutableAndArgs.get() val cliPath = detectedCliPath(project.projectDir, config) - val execCommand = nodeExecutableAndArgs + cliPath - val enableHermes = config.enableHermesForVariant(variant) - val cleanup = config.deleteDebugFilesForVariant(variant) - val bundleEnabled = config.bundleForVariant(variant) - - val bundleTask = - tasks.register("createBundle${targetName}JsAndAssets", BundleJsAndAssetsTask::class.java) { - it.group = REACT_GROUP - it.description = "create JS bundle and assets for $targetName." - - it.reactRoot = config.root.get().asFile - it.sources = - fileTree(config.root) { fileTree -> fileTree.setExcludes(config.inputExcludes.get()) } - it.execCommand = execCommand - it.bundleCommand = config.bundleCommand.get() - it.devEnabled = !config.disableDevForVariant(variant) - it.entryFile = detectedEntryFile(config) - - val extraArgs = mutableListOf() - - if (config.bundleConfig.isPresent) { - extraArgs.add("--config") - extraArgs.add(config.bundleConfig.get()) - } - - // Hermes doesn't require JS minification. - if (enableHermes && !it.devEnabled) { - extraArgs.add("--minify") - extraArgs.add("false") - } - - extraArgs.addAll(config.extraPackagerArgs.get()) - - it.extraArgs = extraArgs - - it.jsBundleDir = jsBundleDir - it.jsBundleFile = jsBundleFile - it.resourcesDir = resourcesDir - it.jsIntermediateSourceMapsDir = jsIntermediateSourceMapsDir - it.jsSourceMapsDir = jsSourceMapsDir - it.jsSourceMapsFile = if (enableHermes) jsPackagerSourceMapFile else jsOutputSourceMapFile - - it.enabled = bundleEnabled - } - - val hermesTask = - tasks.register("emit${targetName}HermesResources", HermesBinaryTask::class.java) { - it.group = REACT_GROUP - it.description = "bundle hermes resources for $targetName" - - it.root = config.root.get().asFile - it.hermesCommand = config.hermesCommand.get() - it.hermesFlags = config.hermesFlagsForVariant(variant) - it.jsBundleFile = jsBundleFile - it.composeSourceMapsCommand = nodeExecutableAndArgs + config.composeSourceMapsPath.get() - it.jsPackagerSourceMapFile = jsPackagerSourceMapFile - it.jsCompilerSourceMapFile = jsCompilerSourceMapFile - it.jsOutputSourceMapFile = jsOutputSourceMapFile - - it.dependsOn(bundleTask) - - it.enabled = bundleEnabled && enableHermes - } - - val aggregatedBundleTask = - tasks.register("bundle${targetName}JsAndAssets") { - it.group = REACT_GROUP - it.description = "bundle JS and resources for $targetName" - - it.dependsOn(bundleTask, hermesTask) - - // this was exposed before, do we still need it? - it.extensions.extraProperties["generatedResFolders"] = files(resourcesDir).builtBy(it) - it.extensions.extraProperties["generatedAssetsFolders"] = files(jsBundleDir).builtBy(it) - } - - val generatedResFolders = files(resourcesDir).builtBy(aggregatedBundleTask) - - // Android configuration - variant.registerGeneratedResFolders(generatedResFolders) - - val packageTask: TaskProvider? = - when (variant) { - is ApplicationVariant -> variant.packageApplicationProvider - is LibraryVariant -> variant.packageLibraryProvider - else -> tasks.named("package$targetName") + val enableHermesInProject = project.isHermesEnabled + val enableHermesInThisVariant = + if (config.enableHermesOnlyInVariants.get().isNotEmpty()) { + config.enableHermesOnlyInVariants.get().contains(variant.name) && enableHermesInProject + } else { + enableHermesInProject } - val stripDebugSymbolsTask: TaskProvider? = tasks.named("strip${targetName}DebugSymbols") - val mergeNativeLibsTask: TaskProvider? = tasks.named("merge${targetName}NativeLibs") - - val mergeResourcesTask = variant.mergeResourcesProvider - val mergeAssetsTask = variant.mergeAssetsProvider - val preBundleTask = tasks.named("build${targetName}PreBundle") - - val resourcesDirConfigValue = config.resourcesDir.getting(variant.name) - if (resourcesDirConfigValue.isPresent) { - val currentCopyResTask = - tasks.register("copy${targetName}BundledResources", Copy::class.java) { - it.group = "react" - it.description = "copy bundled resources into custom location for $targetName." - - it.from(resourcesDir) - it.into(file(resourcesDirConfigValue.get())) - - it.dependsOn(bundleTask) - - it.enabled = bundleEnabled + val isDebuggableVariant = + config.debuggableVariants.get().any { it.equals(variant.name, ignoreCase = true) } + + if (!isDebuggableVariant) { + val bundleTask = + tasks.register("createBundle${targetName}JsAndAssets", BundleHermesCTask::class.java) { + it.root.set(config.root) + it.nodeExecutableAndArgs.set(config.nodeExecutableAndArgs) + it.cliPath.set(cliPath) + it.bundleCommand.set(config.bundleCommand) + it.entryFile.set(detectedEntryFile(config)) + it.extraPackagerArgs.set(config.extraPackagerArgs) + it.bundleConfig.set(config.bundleConfig) + it.bundleAssetName.set(config.bundleAssetName) + it.jsBundleDir.set(jsBundleDir) + it.resourcesDir.set(resourcesDir) + it.hermesEnabled.set(enableHermesInThisVariant) + it.minifyEnabled.set(!enableHermesInThisVariant) + it.devEnabled.set(false) + it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) + it.jsSourceMapsDir.set(jsSourceMapsDir) + it.hermesCommand.set(config.hermesCommand) + it.hermesFlags.set(config.hermesFlags) + it.composeSourceMapsPath.set(config.composeSourceMapsPath) } - - packageTask?.dependsOn(currentCopyResTask) - preBundleTask.dependsOn(currentCopyResTask) + variant.sources.res?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::resourcesDir) + variant.sources.assets?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::jsBundleDir) } - packageTask?.configure { - if (config.enableVmCleanup.get()) { - val libDir = "$buildDir/intermediates/transforms/" - val targetVariant = ".*/transforms/[^/]*/${variant.name}/.*".toRegex() - it.doFirst { cleanupVMFiles(libDir, targetVariant, enableHermes, cleanup) } - } + if (config.enableSoCleanup.get()) { + val nativeLibraryApkCleanupTask = + project.tasks.register( + "nativeLibrary${targetName}ApkCleanup", NativeLibraryApkCleanupTask::class.java) { + it.debuggableVariant.set(isDebuggableVariant) + it.enableHermes.set(enableHermesInThisVariant) + } + val nativeLibraryBundleCleanupTask = + project.tasks.register( + "nativeLibrary${targetName}BundleCleanup", NativeLibraryAabCleanupTask::class.java) { + it.debuggableVariant.set(isDebuggableVariant) + it.enableHermes.set(enableHermesInThisVariant) + } + + variant.artifacts + .use(nativeLibraryApkCleanupTask) + .wiredWithDirectories( + NativeLibraryApkCleanupTask::inputApkDirectory, + NativeLibraryApkCleanupTask::outputApkDirectory) + .toTransform(SingleArtifact.APK) + variant.artifacts + .use(nativeLibraryBundleCleanupTask) + .wiredWithFiles( + NativeLibraryAabCleanupTask::inputBundle, NativeLibraryAabCleanupTask::outputBundle) + .toTransform(SingleArtifact.BUNDLE) } - - stripDebugSymbolsTask?.configure { - if (config.enableVmCleanup.get()) { - val libDir = "$buildDir/intermediates/stripped_native_libs/${variant.name}/out/lib/" - val targetVariant = ".*/stripped_native_libs/${variant.name}/out/lib/.*".toRegex() - it.doLast { cleanupVMFiles(libDir, targetVariant, enableHermes, cleanup) } - } - } - - mergeNativeLibsTask?.configure { - if (config.enableVmCleanup.get()) { - val libDir = "$buildDir/intermediates/merged_native_libs/${variant.name}/out/lib/" - val targetVariant = ".*/merged_native_libs/${variant.name}/out/lib/.*".toRegex() - it.doLast { cleanupVMFiles(libDir, targetVariant, enableHermes, cleanup) } - } - } - - val currentAssetsCopyTask = - tasks.register("copy${targetName}BundledJs", Copy::class.java) { - it.group = "react" - it.description = "copy bundled JS into $targetName." - - it.from(jsBundleDir) - - val jsBundleDirConfigValue = config.jsBundleDir.getting(targetName) - if (jsBundleDirConfigValue.isPresent) { - it.into(jsBundleDirConfigValue.get()) - } else { - it.into(mergeAssetsTask.map { mergeFoldersTask -> mergeFoldersTask.outputDir.get() }) - // Workaround for Android Gradle Plugin 7.3 asset directory - it.into("$buildDir/intermediates/assets/${variant.name}") - } - - it.dependsOn(mergeAssetsTask) - - it.enabled = bundleEnabled - } - - // mergeResources task runs before the bundle file is copied to the intermediate asset directory - // from Android plugin 4.1+. - // This ensures to copy the bundle file before mergeResources task starts - mergeResourcesTask.dependsOn(currentAssetsCopyTask) - packageTask?.dependsOn(currentAssetsCopyTask) - preBundleTask.dependsOn(currentAssetsCopyTask) } - -private fun Project.cleanupVMFiles( - libDir: String, - targetVariant: Regex, - enableHermes: Boolean, - cleanup: Boolean -) { - // Delete the VM related libraries that this build doesn't need. - // The application can manage this manually by setting 'enableVmCleanup: false' - // - // This should really be done by packaging all Hermes related libs into - // two separate HermesDebug and HermesRelease AARs, but until then we'll - // kludge it by deleting the .so files out of the /transforms/ directory. - fileTree(libDir) { - if (enableHermes) { - // For Hermes, delete all the libjsc* files - it.include("**/libjsc*.so") - - if (cleanup) { - // Reduce size by deleting the debugger/inspector - it.include("**/libhermes-executor-debug.so") - } else { - // Release libs take precedence and must be removed - // to allow debugging - it.include("**/libhermes-executor-release.so") - } - } else { - // For JSC, delete all the libhermes* files - it.include("**/libhermes*.so") - } - } - .visit { visit -> - val path = visit.file.absolutePath.replace(File.separatorChar, '/') - if (path.matches(targetVariant) && visit.file.isFile) { - visit.file.delete() - } - } -} - -internal val BaseVariant.isRelease: Boolean - get() = name.lowercase().contains("release") diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleJsAndAssetsTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleJsAndAssetsTask.kt deleted file mode 100644 index 2e1a0b8be81900..00000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleJsAndAssetsTask.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.utils.recreateDir -import com.facebook.react.utils.windowsAwareCommandLine -import java.io.File -import org.gradle.api.file.FileTree -import org.gradle.api.tasks.* - -abstract class BundleJsAndAssetsTask : Exec() { - - @get:Internal lateinit var reactRoot: File - - @get:InputFiles - @Suppress("UNUSED") // used to invalidate caches - lateinit var sources: FileTree - - @get:Input lateinit var execCommand: List - @get:Input lateinit var bundleCommand: String - @get:Input var devEnabled: Boolean = true - @get:InputFile lateinit var entryFile: File - @get:Input var extraArgs: List = emptyList() - - @get:OutputDirectory lateinit var jsBundleDir: File - @get:OutputFile lateinit var jsBundleFile: File - @get:OutputDirectory lateinit var resourcesDir: File - @get:OutputDirectory lateinit var jsIntermediateSourceMapsDir: File - @get:OutputDirectory lateinit var jsSourceMapsDir: File - @get:OutputFile lateinit var jsSourceMapsFile: File - - override fun exec() { - cleanOutputDirectories() - configureBundleCommand() - super.exec() - } - - private fun cleanOutputDirectories() { - jsBundleDir.recreateDir() - resourcesDir.recreateDir() - jsIntermediateSourceMapsDir.recreateDir() - jsSourceMapsDir.recreateDir() - } - - private fun configureBundleCommand() { - workingDir(reactRoot) - - @Suppress("SpreadOperator") - commandLine( - windowsAwareCommandLine( - *execCommand.toTypedArray(), - bundleCommand, - "--platform", - "android", - "--dev", - devEnabled, - "--reset-cache", - "--entry-file", - entryFile, - "--bundle-output", - jsBundleFile, - "--assets-dest", - resourcesDir, - "--sourcemap-output", - jsSourceMapsFile, - *extraArgs.toTypedArray())) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/HermesBinaryTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/HermesBinaryTask.kt deleted file mode 100644 index 3f9e635973847e..00000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/HermesBinaryTask.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.utils.detectOSAwareHermesCommand -import com.facebook.react.utils.moveTo -import com.facebook.react.utils.windowsAwareCommandLine -import java.io.File -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.TaskAction - -open class HermesBinaryTask : DefaultTask() { - - @get:Internal internal lateinit var root: File - - @get:Input internal lateinit var hermesCommand: String - @get:Input internal var hermesFlags: List = emptyList() - @get:InputFile internal lateinit var jsBundleFile: File - - @get:Input internal lateinit var composeSourceMapsCommand: List - @get:InputFile internal lateinit var jsPackagerSourceMapFile: File - - @get:OutputFile internal lateinit var jsCompilerSourceMapFile: File - @get:OutputFile internal lateinit var jsOutputSourceMapFile: File - - @TaskAction - fun run() { - val detectedHermesCommand = detectOSAwareHermesCommand(root, hermesCommand) - val bytecodeTempFile = File("$jsBundleFile.hbc") - emitHermesBinary(hermesCommand = detectedHermesCommand, outputFile = bytecodeTempFile) - bytecodeTempFile.moveTo(jsBundleFile) - - if (hermesFlags.contains("-output-source-map")) { - val hermesTempSourceMapFile = File("$bytecodeTempFile.map") - hermesTempSourceMapFile.moveTo(jsCompilerSourceMapFile) - composeSourceMaps() - } - } - - private fun emitHermesBinary(hermesCommand: String, outputFile: File) { - project.exec { - @Suppress("SpreadOperator") - it.commandLine( - windowsAwareCommandLine( - hermesCommand, - "-emit-binary", - "-out", - outputFile, - jsBundleFile, - *hermesFlags.toTypedArray())) - } - } - - private fun composeSourceMaps() { - project.exec { - it.workingDir(root) - - @Suppress("SpreadOperator") - it.commandLine( - windowsAwareCommandLine( - *composeSourceMapsCommand.toTypedArray(), - jsPackagerSourceMapFile, - jsCompilerSourceMapFile, - "-o", - jsOutputSourceMapFile)) - } - } -} diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index a7f7e9100fe0be..e0fc0dcf655e8c 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -80,10 +80,10 @@ react { bundleAssetName = "RNTesterApp.android.bundle" entryFile = file("../../js/RNTesterApp.android.js") root = file("../../") - inputExcludes = ["android/**", "./**", ".gradle/**"] composeSourceMapsPath = "$rootDir/scripts/compose-source-maps.js" hermesCommand = "$rootDir/ReactAndroid/hermes-engine/build/hermes/bin/hermesc" - enableHermesForVariant { def v -> v.name.contains("hermes") } + debuggableVariants = ["hermesDebug", "jscDebug"] + enableHermesOnlyInVariants = ["hermesDebug", "hermesRelease"] // Codegen Configs reactNativeDir = rootDir @@ -228,6 +228,5 @@ android { afterEvaluate { // As we're consuming Hermes from source, we want to make sure // `hermesc` is built before we actually invoke the `emit*HermesResource` task - emitHermesDebugHermesResources.dependsOn(":ReactAndroid:hermes-engine:buildHermes") - emitHermesReleaseHermesResources.dependsOn(":ReactAndroid:hermes-engine:buildHermes") + createBundleHermesReleaseJsAndAssets.dependsOn(":ReactAndroid:hermes-engine:buildHermes") } From 20718e6b8ce4f5c3a8393067d5e8eb0da910751c Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Mon, 24 Oct 2022 08:38:47 -0700 Subject: [PATCH 008/169] feat: Add role prop to Text component (#34976) Summary: As pointed out by necolas on https://github.com/facebook/react-native/issues/34424#issuecomment-1261482517 we forgot we add the `role` prop mapping to the `Text` component. This PR adds a new `role` prop to `Text`, mapping the web `role` values to the already existing `accessibilityRole` prop and moves the `roleToAccessibilityRoleMapping` to a common file that can be imported by both the `Text` and `View` components as requested on https://github.com/facebook/react-native/issues/34424. This PR also updates the RNTester AcessebilityExample to include a test using this new prop. ## Changelog [General] [Added] - Add role prop to Text component Pull Request resolved: https://github.com/facebook/react-native/pull/34976 Test Plan: 1. Open the RNTester app and navigate to the Accessibility Example page 2. Test the `role` prop through the `Text with role = heading` section Reviewed By: yungsters Differential Revision: D40596039 Pulled By: jacdebug fbshipit-source-id: f72f02e8bd32169423ea517ad18b598b52257b17 --- Libraries/Components/View/View.js | 71 +------- .../Components/View/ViewAccessibility.d.ts | 71 ++++++++ Libraries/Text/Text.js | 9 ++ Libraries/Text/TextProps.js | 6 + Libraries/Utilities/AcessibilityMapping.js | 152 ++++++++++++++++++ .../Accessibility/AccessibilityExample.js | 4 + 6 files changed, 244 insertions(+), 69 deletions(-) create mode 100644 Libraries/Utilities/AcessibilityMapping.js diff --git a/Libraries/Components/View/View.js b/Libraries/Components/View/View.js index 129f50d36e2d95..8ef1f814a312fb 100644 --- a/Libraries/Components/View/View.js +++ b/Libraries/Components/View/View.js @@ -12,6 +12,7 @@ import type {ViewProps} from './ViewPropTypes'; import flattenStyle from '../../StyleSheet/flattenStyle'; import TextAncestor from '../../Text/TextAncestor'; +import {getAccessibilityRoleFromRole} from '../../Utilities/AcessibilityMapping'; import ViewNativeComponent from './ViewNativeComponent'; import * as React from 'react'; @@ -80,74 +81,6 @@ const View: React.AbstractComponent< text: ariaValueText ?? accessibilityValue?.text, }; - // Map role values to AccessibilityRole values - const roleToAccessibilityRoleMapping = { - alert: 'alert', - alertdialog: undefined, - application: undefined, - article: undefined, - banner: undefined, - button: 'button', - cell: undefined, - checkbox: 'checkbox', - columnheader: undefined, - combobox: 'combobox', - complementary: undefined, - contentinfo: undefined, - definition: undefined, - dialog: undefined, - directory: undefined, - document: undefined, - feed: undefined, - figure: undefined, - form: undefined, - grid: 'grid', - group: undefined, - heading: 'header', - img: 'image', - link: 'link', - list: 'list', - listitem: undefined, - log: undefined, - main: undefined, - marquee: undefined, - math: undefined, - menu: 'menu', - menubar: 'menubar', - menuitem: 'menuitem', - meter: undefined, - navigation: undefined, - none: 'none', - note: undefined, - presentation: 'none', - progressbar: 'progressbar', - radio: 'radio', - radiogroup: 'radiogroup', - region: undefined, - row: undefined, - rowgroup: undefined, - rowheader: undefined, - scrollbar: 'scrollbar', - searchbox: 'search', - separator: undefined, - slider: 'adjustable', - spinbutton: 'spinbutton', - status: undefined, - summary: 'summary', - switch: 'switch', - tab: 'tab', - table: undefined, - tablist: 'tablist', - tabpanel: undefined, - term: undefined, - timer: 'timer', - toolbar: 'toolbar', - tooltip: undefined, - tree: undefined, - treegrid: undefined, - treeitem: undefined, - }; - const flattenedStyle = flattenStyle(style); const newPointerEvents = flattenedStyle?.pointerEvents || pointerEvents; @@ -162,7 +95,7 @@ const View: React.AbstractComponent< focusable={tabIndex !== undefined ? !tabIndex : focusable} accessibilityState={_accessibilityState} accessibilityRole={ - role ? roleToAccessibilityRoleMapping[role] : accessibilityRole + role ? getAccessibilityRoleFromRole(role) : accessibilityRole } accessibilityElementsHidden={ ariaHidden ?? accessibilityElementsHidden diff --git a/Libraries/Components/View/ViewAccessibility.d.ts b/Libraries/Components/View/ViewAccessibility.d.ts index a9ff8baa374686..8f530a78c19848 100644 --- a/Libraries/Components/View/ViewAccessibility.d.ts +++ b/Libraries/Components/View/ViewAccessibility.d.ts @@ -101,6 +101,11 @@ export interface AccessibilityProps 'aria-live'?: ('polite' | 'assertive' | 'off') | undefined; 'aria-modal'?: boolean | undefined; + + /** + * Indicates to accessibility services to treat UI component like a specific role. + */ + role?: Role; } export type AccessibilityActionInfo = Readonly<{ @@ -286,3 +291,69 @@ export interface AccessibilityPropsIOS { */ accessibilityIgnoresInvertColors?: boolean | undefined; } + +export type Role = + | 'alert' + | 'alertdialog' + | 'application' + | 'article' + | 'banner' + | 'button' + | 'cell' + | 'checkbox' + | 'columnheader' + | 'combobox' + | 'complementary' + | 'contentinfo' + | 'definition' + | 'dialog' + | 'directory' + | 'document' + | 'feed' + | 'figure' + | 'form' + | 'grid' + | 'group' + | 'heading' + | 'img' + | 'link' + | 'list' + | 'listitem' + | 'log' + | 'main' + | 'marquee' + | 'math' + | 'menu' + | 'menubar' + | 'menuitem' + | 'meter' + | 'navigation' + | 'none' + | 'note' + | 'presentation' + | 'progressbar' + | 'radio' + | 'radiogroup' + | 'region' + | 'row' + | 'rowgroup' + | 'rowheader' + | 'scrollbar' + | 'searchbox' + | 'separator' + | 'slider' + | 'spinbutton' + | 'status' + | 'summary' + | 'switch' + | 'tab' + | 'table' + | 'tablist' + | 'tabpanel' + | 'term' + | 'timer' + | 'toolbar' + | 'tooltip' + | 'tree' + | 'treegrid' + | 'treeitem'; diff --git a/Libraries/Text/Text.js b/Libraries/Text/Text.js index ac427bf8c736ae..2470a3c2627bc6 100644 --- a/Libraries/Text/Text.js +++ b/Libraries/Text/Text.js @@ -15,6 +15,7 @@ import usePressability from '../Pressability/usePressability'; import flattenStyle from '../StyleSheet/flattenStyle'; import processColor from '../StyleSheet/processColor'; import StyleSheet from '../StyleSheet/StyleSheet'; +import {getAccessibilityRoleFromRole} from '../Utilities/AcessibilityMapping'; import Platform from '../Utilities/Platform'; import TextAncestor from './TextAncestor'; import {NativeText, NativeVirtualText} from './TextNativeComponent'; @@ -34,6 +35,7 @@ const Text: React.AbstractComponent< const { accessible, accessibilityLabel, + accessibilityRole, allowFontScaling, 'aria-busy': ariaBusy, 'aria-checked': ariaChecked, @@ -55,6 +57,7 @@ const Text: React.AbstractComponent< onResponderTerminationRequest, onStartShouldSetResponder, pressRetentionOffset, + role, suppressHighlighting, ...restProps } = props; @@ -223,6 +226,9 @@ const Text: React.AbstractComponent< accessibilityState={_accessibilityState} {...eventHandlersForText} accessibilityLabel={ariaLabel ?? accessibilityLabel} + accessibilityRole={ + role ? getAccessibilityRoleFromRole(role) : accessibilityRole + } isHighlighted={isHighlighted} isPressable={isPressable} selectable={_selectable} @@ -246,6 +252,9 @@ const Text: React.AbstractComponent< } accessibilityLabel={ariaLabel ?? accessibilityLabel} accessibilityState={nativeTextAccessibilityState} + accessibilityRole={ + role ? getAccessibilityRoleFromRole(role) : accessibilityRole + } allowFontScaling={allowFontScaling !== false} ellipsizeMode={ellipsizeMode ?? 'tail'} isHighlighted={isHighlighted} diff --git a/Libraries/Text/TextProps.js b/Libraries/Text/TextProps.js index 3a927ae48681e4..4ef9e7cec3ce39 100644 --- a/Libraries/Text/TextProps.js +++ b/Libraries/Text/TextProps.js @@ -15,6 +15,7 @@ import type { AccessibilityActionInfo, AccessibilityRole, AccessibilityState, + Role, } from '../Components/View/ViewAccessibility'; import type {TextStyleProp} from '../StyleSheet/StyleSheet'; import type { @@ -176,6 +177,11 @@ export type TextProps = $ReadOnly<{| */ pressRetentionOffset?: ?PressRetentionOffset, + /** + * Indicates to accessibility services to treat UI component like a specific role. + */ + role?: ?Role, + /** * Lets the user select text. * diff --git a/Libraries/Utilities/AcessibilityMapping.js b/Libraries/Utilities/AcessibilityMapping.js new file mode 100644 index 00000000000000..8db68118821dd8 --- /dev/null +++ b/Libraries/Utilities/AcessibilityMapping.js @@ -0,0 +1,152 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +'use strict'; + +import type { + AccessibilityRole, + Role, +} from '../Components/View/ViewAccessibility'; + +// Map role values to AccessibilityRole values +export function getAccessibilityRoleFromRole(role: Role): ?AccessibilityRole { + switch (role) { + case 'alert': + return 'alert'; + case 'alertdialog': + return undefined; + case 'application': + return undefined; + case 'article': + return undefined; + case 'banner': + return undefined; + case 'button': + return 'button'; + case 'cell': + return undefined; + case 'checkbox': + return 'checkbox'; + case 'columnheader': + return undefined; + case 'combobox': + return 'combobox'; + case 'complementary': + return undefined; + case 'contentinfo': + return undefined; + case 'definition': + return undefined; + case 'dialog': + return undefined; + case 'directory': + return undefined; + case 'document': + return undefined; + case 'feed': + return undefined; + case 'figure': + return undefined; + case 'form': + return undefined; + case 'grid': + return 'grid'; + case 'group': + return undefined; + case 'heading': + return 'header'; + case 'img': + return 'image'; + case 'link': + return 'link'; + case 'list': + return 'list'; + case 'listitem': + return undefined; + case 'log': + return undefined; + case 'main': + return undefined; + case 'marquee': + return undefined; + case 'math': + return undefined; + case 'menu': + return 'menu'; + case 'menubar': + return 'menubar'; + case 'menuitem': + return 'menuitem'; + case 'meter': + return undefined; + case 'navigation': + return undefined; + case 'none': + return 'none'; + case 'note': + return undefined; + case 'presentation': + return 'none'; + case 'progressbar': + return 'progressbar'; + case 'radio': + return 'radio'; + case 'radiogroup': + return 'radiogroup'; + case 'region': + return undefined; + case 'row': + return undefined; + case 'rowgroup': + return undefined; + case 'rowheader': + return undefined; + case 'scrollbar': + return 'scrollbar'; + case 'searchbox': + return 'search'; + case 'separator': + return undefined; + case 'slider': + return 'adjustable'; + case 'spinbutton': + return 'spinbutton'; + case 'status': + return undefined; + case 'summary': + return 'summary'; + case 'switch': + return 'switch'; + case 'tab': + return 'tab'; + case 'table': + return undefined; + case 'tablist': + return 'tablist'; + case 'tabpanel': + return undefined; + case 'term': + return undefined; + case 'timer': + return 'timer'; + case 'toolbar': + return 'toolbar'; + case 'tooltip': + return undefined; + case 'tree': + return undefined; + case 'treegrid': + return undefined; + case 'treeitem': + return undefined; + } + + return undefined; +} diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js index 9efdbfdb2da011..c552f75699656a 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js @@ -157,6 +157,10 @@ class AccessibilityExample extends React.Component<{}> { This is a title. + + This is a title. + + Alert.alert('Link has been clicked!')} From 9a43e53a0674cf8e6f2e0f297adb0a21ad8831d8 Mon Sep 17 00:00:00 2001 From: Donald Webster Date: Mon, 24 Oct 2022 08:56:55 -0700 Subject: [PATCH 009/169] Revert D40613108: 4/n Display a RedBox with the JS stack (instead of native stack) when an unhandled JS exceptions occurs - Try 2 Differential Revision: D40613108 (https://github.com/facebook/react-native/commit/5449148482271d60c87f6e5fa4483e69d4410320) Original commit changeset: f36c3b39a216 Original Phabricator Diff: D40613108 (https://github.com/facebook/react-native/commit/5449148482271d60c87f6e5fa4483e69d4410320) fbshipit-source-id: 079deac137610eeebd231bd97930efda6b284fff --- BUCK | 1 - React/CxxBridge/RCTCxxBridge.mm | 20 +++++------ React/CxxModule/RCTCxxUtils.mm | 36 ++++--------------- ReactCommon/React-Fabric.podspec | 2 ++ ReactCommon/jserrorhandler/BUCK | 6 ++-- ReactCommon/jserrorhandler/JsErrorHandler.cpp | 8 ++--- ReactCommon/jserrorhandler/JsErrorHandler.h | 3 -- .../React-jserrorhandler.podspec | 36 ------------------- packages/rn-tester/Podfile.lock | 9 +---- scripts/react_native_pods.rb | 2 -- 10 files changed, 26 insertions(+), 97 deletions(-) delete mode 100644 ReactCommon/jserrorhandler/React-jserrorhandler.podspec diff --git a/BUCK b/BUCK index 5b5223eaed0025..e1b1e68844cbd7 100644 --- a/BUCK +++ b/BUCK @@ -197,7 +197,6 @@ rn_xplat_cxx_library2( visibility = ["PUBLIC"], deps = [ "//xplat/folly:dynamic", - react_native_xplat_target("jserrorhandler:jserrorhandler"), ], ) diff --git a/React/CxxBridge/RCTCxxBridge.mm b/React/CxxBridge/RCTCxxBridge.mm index b8fd6f44608722..047a7c2c4eb4c1 100644 --- a/React/CxxBridge/RCTCxxBridge.mm +++ b/React/CxxBridge/RCTCxxBridge.mm @@ -1137,7 +1137,10 @@ - (void)handleError:(NSError *)error // In state 3: do nothing. if (self->_valid && !self->_loading) { - [self showJsError:error onRedBox:self.redBox]; + if ([error userInfo][RCTJSRawStackTraceKey]) { + [self.redBox showErrorMessage:[error localizedDescription] withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; + } + RCTFatal(error); // RN will stop, but let the rest of the app keep going. @@ -1168,20 +1171,15 @@ - (void)handleError:(NSError *)error [[NSNotificationCenter defaultCenter] postNotificationName:RCTJavaScriptDidFailToLoadNotification object:self->_parentBridge userInfo:@{@"bridge" : self, @"error" : error}]; - [self showJsError:error onRedBox:redBox]; + + if ([error userInfo][RCTJSRawStackTraceKey]) { + [redBox showErrorMessage:[error localizedDescription] withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; + } + RCTFatal(error); }); } -- (void)showJsError:(NSError *)error onRedBox:(RCTRedBox *)redbox -{ - if ([error userInfo][RCTJSStackTraceKey]) { - [redbox showErrorMessage:[error localizedDescription] withStack:[error userInfo][RCTJSStackTraceKey]]; - } else if ([error userInfo][RCTJSRawStackTraceKey]) { - [redbox showErrorMessage:[error localizedDescription] withRawStack:[error userInfo][RCTJSRawStackTraceKey]]; - } -} - RCT_NOT_IMPLEMENTED(-(instancetype)initWithDelegate : (__unused id)delegate bundleURL : (__unused NSURL *)bundleURL moduleProvider diff --git a/React/CxxModule/RCTCxxUtils.mm b/React/CxxModule/RCTCxxUtils.mm index a4df6eacc99f40..03f0ad0c83d8df 100644 --- a/React/CxxModule/RCTCxxUtils.mm +++ b/React/CxxModule/RCTCxxUtils.mm @@ -7,9 +7,6 @@ #import "RCTCxxUtils.h" -#include - -#import #import #import #import @@ -23,6 +20,8 @@ namespace facebook { namespace react { +using facebook::jsi::JSError; + std::vector> createNativeModules(NSArray *modules, RCTBridge *bridge, const std::shared_ptr &instance) { @@ -43,34 +42,13 @@ static NSError *errorWithException(const std::exception &e) { - NSString *msg; + NSString *msg = @(e.what()); NSMutableDictionary *errorInfo = [NSMutableDictionary dictionary]; - const auto *jsError = dynamic_cast(&e); - if (jsError && RCTGetParseUnhandledJSErrorStackNatively()) { - MapBuffer errorMap = JsErrorHandler::parseErrorStack(*jsError, true, false); - - NSString *message = [NSString stringWithCString:errorMap.getString(JSErrorHandlerKey::kErrorMessage).c_str() - encoding:[NSString defaultCStringEncoding]]; - auto frames = errorMap.getMapBufferList(JSErrorHandlerKey::kAllStackFrames); - NSMutableArray *stack = [[NSMutableArray alloc] init]; - for (auto const &mapBuffer : frames) { - NSDictionary *frame = @{ - @"file" : [NSString stringWithCString:mapBuffer.getString(JSErrorHandlerKey::kFrameFileName).c_str() - encoding:[NSString defaultCStringEncoding]], - @"methodName" : [NSString stringWithCString:mapBuffer.getString(JSErrorHandlerKey::kFrameMethodName).c_str() - encoding:[NSString defaultCStringEncoding]], - @"lineNumber" : [NSNumber numberWithInt:mapBuffer.getInt(JSErrorHandlerKey::kFrameLineNumber)], - @"column" : [NSNumber numberWithInt:mapBuffer.getInt(JSErrorHandlerKey::kFrameColumnNumber)], - }; - [stack addObject:frame]; - } - - msg = [@"Unhandled JS Exception: " stringByAppendingString:message]; - errorInfo[RCTJSStackTraceKey] = stack; - errorInfo[RCTJSRawStackTraceKey] = @(e.what()); - } else { - msg = @(e.what()); + const auto *jsError = dynamic_cast(&e); + if (jsError) { + errorInfo[RCTJSRawStackTraceKey] = @(jsError->getStack().c_str()); + msg = [@"Unhandled JS Exception: " stringByAppendingString:msg]; } NSError *nestedError; diff --git a/ReactCommon/React-Fabric.podspec b/ReactCommon/React-Fabric.podspec index b9a13624a51b3e..c28eee60d06fbe 100644 --- a/ReactCommon/React-Fabric.podspec +++ b/ReactCommon/React-Fabric.podspec @@ -254,6 +254,8 @@ Pod::Spec.new do |s| end s.subspec "mapbuffer" do |ss| + ss.dependency folly_dep_name, folly_version + ss.compiler_flags = folly_compiler_flags ss.source_files = "react/renderer/mapbuffer/**/*.{m,mm,cpp,h}" ss.exclude_files = "react/renderer/mapbuffer/tests" ss.header_dir = "react/renderer/mapbuffer" diff --git a/ReactCommon/jserrorhandler/BUCK b/ReactCommon/jserrorhandler/BUCK index 8ece978f3326c3..9edd6729f64e64 100644 --- a/ReactCommon/jserrorhandler/BUCK +++ b/ReactCommon/jserrorhandler/BUCK @@ -4,8 +4,8 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "react_nat rn_xplat_cxx_library( name = "jserrorhandler", srcs = glob(["*.cpp"]), - header_namespace = "jserrorhandler", - exported_headers = ["JsErrorHandler.h"], + header_namespace = "", + exported_headers = {"JsErrorHandler/JsErrorHandler.h": "JsErrorHandler.h"}, compiler_flags = [ "-fexceptions", "-frtti", @@ -22,6 +22,8 @@ rn_xplat_cxx_library( "PUBLIC", ], deps = [ + "//xplat/folly:dynamic", + "//xplat/folly:json", "//xplat/jsi:jsi", react_native_xplat_target("react/renderer/mapbuffer:mapbuffer"), ], diff --git a/ReactCommon/jserrorhandler/JsErrorHandler.cpp b/ReactCommon/jserrorhandler/JsErrorHandler.cpp index be74dc5da2b8fe..0902e68b2b1644 100644 --- a/ReactCommon/jserrorhandler/JsErrorHandler.cpp +++ b/ReactCommon/jserrorhandler/JsErrorHandler.cpp @@ -17,10 +17,8 @@ namespace react { using facebook::react::JSErrorHandlerKey; -MapBuffer JsErrorHandler::parseErrorStack( - const jsi::JSError &error, - bool isFatal, - bool isHermes) { +static MapBuffer +parseErrorStack(const jsi::JSError &error, bool isFatal, bool isHermes) { /** * This parses the different stack traces and puts them into one format * This borrows heavily from TraceKit (https://github.com/occ/TraceKit) @@ -101,7 +99,7 @@ JsErrorHandler::~JsErrorHandler() {} void JsErrorHandler::handleJsError(const jsi::JSError &error, bool isFatal) { // TODO: Current error parsing works and is stable. Can investigate using // REGEX_HERMES to get additional Hermes data, though it requires JS setup. - MapBuffer errorMap = JsErrorHandler::parseErrorStack(error, isFatal, false); + MapBuffer errorMap = parseErrorStack(error, isFatal, false); _jsErrorHandlingFunc(std::move(errorMap)); } diff --git a/ReactCommon/jserrorhandler/JsErrorHandler.h b/ReactCommon/jserrorhandler/JsErrorHandler.h index ca5af45425b17e..90383e17ca7dd8 100644 --- a/ReactCommon/jserrorhandler/JsErrorHandler.h +++ b/ReactCommon/jserrorhandler/JsErrorHandler.h @@ -26,9 +26,6 @@ class JsErrorHandler { public: using JsErrorHandlingFunc = std::function; - static MapBuffer - parseErrorStack(const jsi::JSError &error, bool isFatal, bool isHermes); - JsErrorHandler(JsErrorHandlingFunc jsErrorHandlingFunc); ~JsErrorHandler(); diff --git a/ReactCommon/jserrorhandler/React-jserrorhandler.podspec b/ReactCommon/jserrorhandler/React-jserrorhandler.podspec deleted file mode 100644 index cfb7594ee2a3f0..00000000000000 --- a/ReactCommon/jserrorhandler/React-jserrorhandler.podspec +++ /dev/null @@ -1,36 +0,0 @@ -# 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. - -require "json" - -package = JSON.parse(File.read(File.join(__dir__, "..", "..", "package.json"))) -version = package['version'] - -source = { :git => 'https://github.com/facebook/react-native.git' } -if version == '1000.0.0' - # This is an unpublished version, use the latest commit hash of the react-native repo, which we’re presumably in. - source[:commit] = `git rev-parse HEAD`.strip if system("git rev-parse --git-dir > /dev/null 2>&1") -else - source[:tag] = "v#{version}" -end - -Pod::Spec.new do |s| - s.name = "React-jserrorhandler" - s.version = version - s.summary = "-" # TODO - s.homepage = "https://reactnative.dev/" - s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4", :tvos => "12.4" } - s.public_header_files = [ "JsErrorHandler.h" ] - s.source = source - s.source_files = "*.{cpp,h}" - s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "" } - s.header_dir = "jserrorhandler" - - s.dependency "React-jsi", version - s.dependency "React-Fabric/mapbuffer", version - -end diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index 336f7d517072b1..fedd81b021de81 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -620,9 +620,6 @@ PODS: - React-jsiexecutor (= 1000.0.0) - React-jsinspector (= 1000.0.0) - React-perflogger (= 1000.0.0) - - React-jserrorhandler (1000.0.0): - - React-Fabric/mapbuffer (= 1000.0.0) - - React-jsi (= 1000.0.0) - React-jsi (1000.0.0): - hermes-engine - React-jsidynamic (1000.0.0): @@ -799,7 +796,6 @@ DEPENDENCIES: - React-Fabric (from `../../ReactCommon`) - React-graphics (from `../../ReactCommon/react/renderer/graphics`) - React-hermes (from `../../ReactCommon/hermes`) - - React-jserrorhandler (from `../../ReactCommon/jserrorhandler`) - React-jsi (from `../../ReactCommon/jsi`) - React-jsidynamic (from `../../ReactCommon/jsi`) - React-jsiexecutor (from `../../ReactCommon/jsiexecutor`) @@ -883,8 +879,6 @@ EXTERNAL SOURCES: :path: "../../ReactCommon/react/renderer/graphics" React-hermes: :path: "../../ReactCommon/hermes" - React-jserrorhandler: - :path: "../../ReactCommon/jserrorhandler" React-jsi: :path: "../../ReactCommon/jsi" React-jsidynamic: @@ -964,10 +958,9 @@ SPEC CHECKSUMS: React-Core: 3965263aa4b4e1ebf7b4fdb50d2f49ce7bf28f63 React-CoreModules: 675170bccf156da3a3348e04e2036ce401b2010d React-cxxreact: 7276467c246302fedf598cc40d7003896ddb20ba - React-Fabric: e177589b59ae3ae3dd3340190adcde9cf01ebceb + React-Fabric: 141459e61c825acf02d26ece099acbd9cbd87b99 React-graphics: 5ccc9cc0d91794fd42bc1c693e9aea207554bbef React-hermes: 0a5145bae4207edf0def8e28fbcb6a8fd6e806c2 - React-jserrorhandler: f0e756378ad46f5f3448f097a736eb5249de262b React-jsi: c24dbcfdf7ea075138b73372387c7f17c0db56ef React-jsidynamic: 2b14ac1b6d3a1b7daa1e5a424b98de87da981698 React-jsiexecutor: 14e899380e3fe9ca74c4e19727540a03e7574721 diff --git a/scripts/react_native_pods.rb b/scripts/react_native_pods.rb index ad2a01478450e9..73b44c12bab708 100644 --- a/scripts/react_native_pods.rb +++ b/scripts/react_native_pods.rb @@ -101,8 +101,6 @@ def use_react_native! ( else setup_jsc!(:react_native_path => prefix, :fabric_enabled => fabric_enabled) end - pod 'React-jserrorhandler', :path => "#{prefix}/ReactCommon/jserrorhandler" - pod 'React-jsidynamic', :path => "#{prefix}/ReactCommon/jsi" pod 'React-jsiexecutor', :path => "#{prefix}/ReactCommon/jsiexecutor" pod 'React-jsinspector', :path => "#{prefix}/ReactCommon/jsinspector" From 421bf983ed63bb2383a17805f0346de862d106e8 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Mon, 24 Oct 2022 09:24:44 -0700 Subject: [PATCH 010/169] Unbreak test_android by passing the correct file to hermesc (#35067) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35067 I accidentally broke test_android by landing a diff without waiting for the full CI output. Changelog: [Internal] [Fixed] - Unbreak test_android by passing the correct file to hermesc Reviewed By: cipolleschi Differential Revision: D40638239 fbshipit-source-id: 1d03106f3b144f537265910df095a6023b181d85 --- .../com/facebook/react/tasks/BundleHermesCTask.kt | 14 +++++++------- .../facebook/react/tasks/BundleHermesCTaskTest.kt | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt index c1dfb58fd13688..66490377b0212c 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt @@ -90,16 +90,16 @@ abstract class BundleHermesCTask : DefaultTask() { if (hermesEnabled.get()) { val detectedHermesCommand = detectOSAwareHermesCommand(root.get().asFile, hermesCommand.get()) - val bytecodeTempFile = File("${bundleFile}.hbc") + val bytecodeFile = File("${bundleFile}.hbc") val outputSourceMap = resolveOutputSourceMap(bundleAssetFilename) val compilerSourceMap = resolveCompilerSourceMap(bundleAssetFilename) - val hermesCommand = getHermescCommand(detectedHermesCommand, bundleFile, packagerSourceMap) + val hermesCommand = getHermescCommand(detectedHermesCommand, bytecodeFile, bundleFile) runCommand(hermesCommand) - bytecodeTempFile.moveTo(bundleFile) + bytecodeFile.moveTo(bundleFile) if (hermesFlags.get().contains("-output-source-map")) { - val hermesTempSourceMapFile = File("$bytecodeTempFile.map") + val hermesTempSourceMapFile = File("$bytecodeFile.map") hermesTempSourceMapFile.moveTo(compilerSourceMap) val composeSourceMapsCommand = getComposeSourceMapsCommand(packagerSourceMap, compilerSourceMap, outputSourceMap) @@ -159,14 +159,14 @@ abstract class BundleHermesCTask : DefaultTask() { internal fun getHermescCommand( hermesCommand: String, - bundleFile: File, - outputFile: File + bytecodeFile: File, + bundleFile: File ): List = windowsAwareCommandLine( hermesCommand, "-emit-binary", "-out", - outputFile.absolutePath, + bytecodeFile.absolutePath, bundleFile.absolutePath, *hermesFlags.get().toTypedArray()) diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt index 8a180e1080d1b4..d8563d663a9d97 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt @@ -270,17 +270,17 @@ class BundleHermesCTaskTest { @Test fun getHermescCommand_returnsCorrectCommand() { val customHermesc = "hermesc" + val bytecodeFile = tempFolder.newFile("bundle.js.hbc") val bundleFile = tempFolder.newFile("bundle.js") - val outputFile = tempFolder.newFile("bundle.js.packager.map") val task = createTestTask { it.hermesFlags.set(listOf("my-custom-hermes-flag")) } - val hermesCommand = task.getHermescCommand(customHermesc, bundleFile, outputFile) + val hermesCommand = task.getHermescCommand(customHermesc, bytecodeFile, bundleFile) assertEquals(customHermesc, hermesCommand[0]) assertEquals("-emit-binary", hermesCommand[1]) assertEquals("-out", hermesCommand[2]) - assertEquals(outputFile.absolutePath, hermesCommand[3]) + assertEquals(bytecodeFile.absolutePath, hermesCommand[3]) assertEquals(bundleFile.absolutePath, hermesCommand[4]) assertEquals("my-custom-hermes-flag", hermesCommand[5]) assertEquals(6, hermesCommand.size) From f8cd9f187dd6b6e3cf412e9115d3893352e825b4 Mon Sep 17 00:00:00 2001 From: Rui Ying Date: Mon, 24 Oct 2022 10:43:02 -0700 Subject: [PATCH 011/169] Fix ReactAndroid not found in rn-tester build (#35058) Summary: I tried to build the source locally to test changes with `rn-tester`. However, the gradle build failed due to "./ReactAndroid/gradle.properties (No such file or directory)". I believe this error was introduced by https://github.com/facebook/react-native/commit/3d05bac5872b42a5f412ec9042ce5be0b5d5b8d3. ## Changelog [Internal] [Fixed] - Fix ReactAndroid not found in rn-tester build Pull Request resolved: https://github.com/facebook/react-native/pull/35058 Test Plan: - Clone the react-native repo. - Run `cd packages/rn-tester`. - Run `yarn install-android-jsc` and encounter the error. - Apply the fix. - Run `yarn install-android-jsc` and build succeeds. Reviewed By: cipolleschi Differential Revision: D40639856 Pulled By: cortinico fbshipit-source-id: 58b51bcad0af7a21cac032c98484c5942a203e4c --- build.gradle.kts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 9d7ebb8e964aa1..10a5f82e65f9c0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,7 +9,9 @@ plugins { id("io.github.gradle-nexus.publish-plugin") version "1.1.0" } val reactAndroidProperties = java.util.Properties() -File("./ReactAndroid/gradle.properties").inputStream().use { reactAndroidProperties.load(it) } +File("$rootDir/ReactAndroid/gradle.properties").inputStream().use { + reactAndroidProperties.load(it) +} version = if (project.hasProperty("isNightly") && From 52d37aa4037c62a1f3586a808e6077659b61292c Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 24 Oct 2022 10:44:39 -0700 Subject: [PATCH 012/169] Back out "add oncall annotation for BUCK files in xplat based on supermodule information - /home/s2shi/tmp/xplat_buck_oncall/xplat_buck_batch10" (#35064) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35064 Original commit changeset: 0fb0db845c04 Original Phabricator Diff: D40610875 (https://github.com/facebook/react-native/commit/d941940b4ce7ed9030be4f72980fb45d9b62365d) Open source is using BUCK 1 which does not seem to have the `oncall` directive. Backing it out because it is breaking the external CI. ## Changelog [internal] Reviewed By: cortinico Differential Revision: D40635873 fbshipit-source-id: 79ebd4db0972520fcca6ccb8c1725657a8ef7949 --- Libraries/FBLazyVector/BUCK | 2 -- Libraries/RCTRequired/BUCK | 2 -- React/CoreModules/BUCK | 2 -- .../androidTest/java/com/facebook/react/testing/network/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/debug/holder/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/debug/tags/BUCK | 2 -- .../src/main/java/com/facebook/hermes/instrumentation/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/animated/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/bridge/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/common/BUCK | 2 -- .../src/main/java/com/facebook/react/common/mapbuffer/BUCK | 2 -- .../src/main/java/com/facebook/react/common/network/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/config/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/devsupport/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/fabric/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/jscexecutor/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/jstasks/BUCK | 2 -- .../src/main/java/com/facebook/react/module/annotations/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/module/model/BUCK | 2 -- .../src/main/java/com/facebook/react/module/processing/BUCK | 2 -- .../main/java/com/facebook/react/modules/accessibilityinfo/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/appearance/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/appregistry/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/appstate/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/modules/blob/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/bundleloader/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/camera/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/clipboard/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/common/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/modules/core/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/debug/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/deviceinfo/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/dialog/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/fabric/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/fresco/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/i18nmanager/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/image/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/intent/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/network/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/permissions/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/share/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/sound/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/statusbar/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/storage/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/systeminfo/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/toast/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/vibration/BUCK | 2 -- .../src/main/java/com/facebook/react/modules/websocket/BUCK | 2 -- .../src/main/java/com/facebook/react/packagerconnection/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/processing/BUCK | 2 -- .../src/main/java/com/facebook/react/reactperflogger/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/shell/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/surface/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/touch/BUCK | 2 -- .../src/main/java/com/facebook/react/turbomodule/core/BUCK | 2 -- .../java/com/facebook/react/turbomodule/core/interfaces/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/uimanager/BUCK | 2 -- .../src/main/java/com/facebook/react/uimanager/annotations/BUCK | 2 -- .../src/main/java/com/facebook/react/uimanager/common/BUCK | 2 -- .../src/main/java/com/facebook/react/uimanager/util/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/util/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/common/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/image/BUCK | 2 -- .../src/main/java/com/facebook/react/views/imagehelper/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/scroll/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/text/BUCK | 2 -- .../main/java/com/facebook/react/views/text/frescosupport/BUCK | 2 -- .../src/main/java/com/facebook/react/views/textinput/BUCK | 2 -- .../main/java/com/facebook/react/views/unimplementedview/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/view/BUCK | 2 -- ReactAndroid/src/main/jni/react/cxxcomponents/BUCK | 2 -- ReactAndroid/src/main/jni/react/hermes/instrumentation/BUCK | 2 -- ReactAndroid/src/main/jni/react/jni/BUCK | 2 -- ReactAndroid/src/main/jni/react/mapbuffer/BUCK | 2 -- ReactAndroid/src/main/jni/react/reactnativeblob/BUCK | 2 -- ReactAndroid/src/main/jni/react/reactperflogger/BUCK | 2 -- ReactAndroid/src/main/jni/react/turbomodule/BUCK | 2 -- ReactAndroid/src/main/jni/react/uimanager/BUCK | 2 -- ReactCommon/butter/BUCK | 2 -- ReactCommon/callinvoker/BUCK | 2 -- ReactCommon/cxxreact/BUCK | 2 -- ReactCommon/jsi/BUCK | 2 -- ReactCommon/jsiexecutor/BUCK | 2 -- ReactCommon/jsinspector/BUCK | 2 -- ReactCommon/logger/BUCK | 2 -- ReactCommon/react/config/BUCK | 2 -- ReactCommon/react/debug/BUCK | 2 -- ReactCommon/react/nativemodule/core/BUCK | 2 -- ReactCommon/react/nativemodule/samples/BUCK | 2 -- ReactCommon/react/renderer/componentregistry/BUCK | 2 -- ReactCommon/react/renderer/componentregistry/native/BUCK | 2 -- ReactCommon/react/renderer/components/text/BUCK | 2 -- ReactCommon/react/renderer/components/textinput/BUCK | 2 -- .../react/renderer/components/textinput/iostextinput/BUCK | 2 -- ReactCommon/react/renderer/leakchecker/BUCK | 2 -- ReactCommon/react/renderer/scheduler/BUCK | 2 -- ReactCommon/react/renderer/textlayoutmanager/BUCK | 2 -- ReactCommon/react/test_utils/BUCK | 2 -- ReactCommon/react/utils/BUCK | 2 -- ReactCommon/reactperflogger/BUCK | 2 -- ReactCommon/runtimeexecutor/BUCK | 2 -- packages/assets/BUCK | 2 -- packages/normalize-color/BUCK | 2 -- packages/polyfills/BUCK | 2 -- 105 files changed, 210 deletions(-) diff --git a/Libraries/FBLazyVector/BUCK b/Libraries/FBLazyVector/BUCK index 99929e4d46f00f..56dd699d6b992b 100644 --- a/Libraries/FBLazyVector/BUCK +++ b/Libraries/FBLazyVector/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "fb_apple_library") -oncall("react_native") - fb_apple_library( name = "FBLazyVector", exported_headers = [ diff --git a/Libraries/RCTRequired/BUCK b/Libraries/RCTRequired/BUCK index a5db549357e581..579d95beecdff1 100644 --- a/Libraries/RCTRequired/BUCK +++ b/Libraries/RCTRequired/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "fb_apple_library") -oncall("react_native") - fb_apple_library( name = "RCTRequired", exported_headers = [ diff --git a/React/CoreModules/BUCK b/React/CoreModules/BUCK index eec68bbf1692b4..5608bacdaea311 100644 --- a/React/CoreModules/BUCK +++ b/React/CoreModules/BUCK @@ -5,8 +5,6 @@ load( "react_module_plugin_providers", ) -oncall("react_native") - rn_apple_library( name = "CoreModulesApple", srcs = glob( diff --git a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/BUCK b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/BUCK index c3b6363a70b559..5572ae6a5561aa 100644 --- a/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/BUCK +++ b/ReactAndroid/src/androidTest/java/com/facebook/react/testing/network/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "network", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/debug/holder/BUCK b/ReactAndroid/src/main/java/com/facebook/debug/holder/BUCK index 0a5eaa63f34a55..0b84d157401198 100644 --- a/ReactAndroid/src/main/java/com/facebook/debug/holder/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/debug/holder/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "holder", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/debug/tags/BUCK b/ReactAndroid/src/main/java/com/facebook/debug/tags/BUCK index e449f8032b9b64..407456dfcddfed 100644 --- a/ReactAndroid/src/main/java/com/facebook/debug/tags/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/debug/tags/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "tags", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/hermes/instrumentation/BUCK b/ReactAndroid/src/main/java/com/facebook/hermes/instrumentation/BUCK index b7cfdf5d10b5a2..ece68a4cdd3c6e 100644 --- a/ReactAndroid/src/main/java/com/facebook/hermes/instrumentation/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/hermes/instrumentation/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "instrumentation", srcs = ["HermesMemoryDumper.java"], diff --git a/ReactAndroid/src/main/java/com/facebook/react/BUCK b/ReactAndroid/src/main/java/com/facebook/react/BUCK index ede86fec92e36c..dd21088699dab5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "react", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/BUCK b/ReactAndroid/src/main/java/com/facebook/react/animated/BUCK index 7f51dccee1cd53..247fccb64aaed4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "animated", srcs = glob([ diff --git a/ReactAndroid/src/main/java/com/facebook/react/bridge/BUCK b/ReactAndroid/src/main/java/com/facebook/react/bridge/BUCK index 315a045f48050f..b5dcea61633656 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/bridge/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/bridge/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "IS_OSS_BUILD", "react_native_dep", "react_native_target", "react_native_tests_target", "rn_android_library") -oncall("react_native") - INTERFACES = [ "Dynamic.java", "ReadableMap.java", diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/BUCK b/ReactAndroid/src/main/java/com/facebook/react/common/BUCK index 1268d4f807a6bf..77d911b93b425d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/common/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "HERMES_BYTECODE_VERSION", "react_native_dep", "rn_android_build_config", "rn_android_library") -oncall("react_native") - SUB_PROJECTS = [ "network/**/*", "mapbuffer/**/*", diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/BUCK b/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/BUCK index aa4ed9ad5f3c9f..21e704ce9605a7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "FBJNI_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "mapbuffer", srcs = glob([ diff --git a/ReactAndroid/src/main/java/com/facebook/react/common/network/BUCK b/ReactAndroid/src/main/java/com/facebook/react/common/network/BUCK index d7817fa31c1c04..102eae06fefb11 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/common/network/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/common/network/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "network", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/config/BUCK b/ReactAndroid/src/main/java/com/facebook/react/config/BUCK index 29f8c231c7e9db..959e44f7c85617 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/config/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/config/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "config", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BUCK b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BUCK index de9a6d9b70fab5..a00fc846a71955 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "devsupport", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/fabric/BUCK b/ReactAndroid/src/main/java/com/facebook/react/fabric/BUCK index 1dc2d9a9c4cc41..a311acbbcadf9f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/fabric/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/fabric/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "IS_OSS_BUILD", "YOGA_TARGET", "react_native_android_toplevel_dep", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - # TODO(T115916830): Remove when Kotlin files are used in this module KOTLIN_STDLIB_DEPS = [react_native_android_toplevel_dep("third-party/kotlin:kotlin-stdlib")] if IS_OSS_BUILD else [] diff --git a/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/BUCK b/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/BUCK index b7ef581f6f7e4d..bae4c2c5df0b74 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/jscexecutor/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "jscexecutor", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/jstasks/BUCK b/ReactAndroid/src/main/java/com/facebook/react/jstasks/BUCK index 5fd73b3a91a62b..953751ea32f1f0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/jstasks/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/jstasks/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "jstasks", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/BUCK b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/BUCK index 54bd6828af7677..a2320c0e97461c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/annotations/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/module/annotations/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "annotations", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/model/BUCK b/ReactAndroid/src/main/java/com/facebook/react/module/model/BUCK index 67ee72228b593c..263a790af22473 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/model/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/module/model/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "model", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/module/processing/BUCK b/ReactAndroid/src/main/java/com/facebook/react/module/processing/BUCK index cdf48d510721a3..486997e369d2a6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/module/processing/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/module/processing/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_java_annotation_processor", "rn_java_library") -oncall("react_native") - rn_java_annotation_processor( name = "processing", does_not_affect_abi = True, diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/BUCK index 8cbae4d1a89536..6d272ba2cd6ac9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/accessibilityinfo/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "accessibilityinfo", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/appearance/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/appearance/BUCK index fec14cb1350156..4cb4e081946767 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/appearance/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/appearance/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "appearance", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/BUCK index 25639d99b925fa..194cad5d24da87 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/appregistry/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "appregistry", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/BUCK index 72323c056d305d..3b32ccead2992a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/appstate/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "appstate", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BUCK index acaa4f9c97b0b3..ead9c5351070da 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "blob", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/bundleloader/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/bundleloader/BUCK index 2325769945b172..6e0fc1d216b047 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/bundleloader/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/bundleloader/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "bundleloader", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/BUCK index 5753b6f509e478..6489f72dd6d029 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/camera/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/camera/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "camera", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/BUCK index 8965aaa0413a3c..232b7b914af167 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/clipboard/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "clipboard", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/common/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/common/BUCK index 3862f6c110b793..c7f0867606b8c0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/common/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/common/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "common", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/core/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/core/BUCK index 7ea06bc3e4b50a..adfb5a46fc1582 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/core/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/core/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "core", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/BUCK index 8769faeda3ce78..a0f564e9d97eaf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/debug/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/debug/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "debug", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/BUCK index e0de17cf2a816b..cd88a53d271375 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "deviceinfo", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/BUCK index c0d7a604d4023d..926bd99ad3dc34 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/dialog/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "dialog", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/BUCK index ccbb18cca8f892..6366cd9f500baa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fabric/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "fabric", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/BUCK index 5b6ecb6cc89003..e274463a9507c4 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/fresco/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "fresco", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/BUCK index 672667b8d797fe..f10162658bdfdd 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "i18nmanager", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/image/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/image/BUCK index c463166d52b267..b396cabccea98d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/image/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/image/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "image", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/intent/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/intent/BUCK index 3a53b5567e1826..a72f21ee44619e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/intent/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/intent/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "intent", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/network/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/network/BUCK index 55290e7ade6cef..c4bb1d902ba04d 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/network/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/network/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "network", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/BUCK index a997b8fff1b518..6f0db9877bd6f8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/permissions/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "permissions", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/share/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/share/BUCK index 4d7cefd4cadad0..0bcc6be310e062 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/share/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/share/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "share", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/sound/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/sound/BUCK index 0d2ed9fa83d5fa..68266a144f1dd5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/sound/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/sound/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "sound", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/BUCK index 146c556c68f1d2..bdba39328924f6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "statusbar", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK index d52d26ba344cfd..7df1b3640bf9ce 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "storage", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/BUCK index 878d5ecb2eaccb..e35b947dbc09b2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "systeminfo", srcs = [ diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/toast/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/toast/BUCK index c830f4315f6c19..d1660ab7f20dc3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/toast/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/toast/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "toast", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/BUCK index 7761698a7cc85c..f584ea54ef8b20 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/vibration/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "vibration", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/BUCK index 63083c5b446ea9..cd32f6785935a5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "websocket", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/BUCK b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/BUCK index 7c9b51c4b6d041..53f9c52773026a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/packagerconnection/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "packagerconnection", srcs = glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/processing/BUCK b/ReactAndroid/src/main/java/com/facebook/react/processing/BUCK index f937fb5ae711b4..07c545a4a9ca16 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/processing/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/processing/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_java_annotation_processor", "rn_java_library") -oncall("react_native") - rn_java_annotation_processor( name = "processing", does_not_affect_abi = True, diff --git a/ReactAndroid/src/main/java/com/facebook/react/reactperflogger/BUCK b/ReactAndroid/src/main/java/com/facebook/react/reactperflogger/BUCK index eb5715a3195457..af677fa38cc4c0 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/reactperflogger/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/reactperflogger/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "reactperflogger", srcs = glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK index d03e81fc95dd83..c79b69687e0654 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "shell", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/surface/BUCK b/ReactAndroid/src/main/java/com/facebook/react/surface/BUCK index 2ea662eeb0b119..fbf785ccfce054 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/surface/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/surface/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "surface", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/touch/BUCK b/ReactAndroid/src/main/java/com/facebook/react/touch/BUCK index 83ba9a2fbd0444..e8949030a88133 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/touch/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/touch/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "touch", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/BUCK b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/BUCK index 5a4c09a6cc5fcd..6fd897c5e74785 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "core", srcs = glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/BUCK b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/BUCK index 45b0de7e26766c..1a1285b362454a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/interfaces/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "interfaces", srcs = glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/BUCK b/ReactAndroid/src/main/java/com/facebook/react/uimanager/BUCK index b629b99105910e..021331bddff184 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - INTERFACES_FILES = [ "BaseViewManagerDelegate.java", "BaseViewManagerInterface.java", diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/BUCK b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/BUCK index 9980355dce4dac..74f9d99132977e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "annotations", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/BUCK b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/BUCK index b1230bebfebdd6..8820a30d24aeb6 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/common/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "common", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/BUCK b/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/BUCK index ceb9b15b5bfc1d..67849ff191f742 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/util/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "util", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/util/BUCK b/ReactAndroid/src/main/java/com/facebook/react/util/BUCK index 1b1faa7f200983..bfcbd4be218f98 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/util/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/util/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "util", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/common/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/common/BUCK index 14b805cf824824..4a06ec1e4293bc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/common/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/common/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "common", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/image/BUCK index c2f3133701835b..f4a3f14b2020c7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - IMAGE_EVENT_FILES = [ "ImageLoadEvent.java", ] diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/BUCK index cc001f893611b4..ed0986c2e1e3c5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "rn_android_library") -oncall("react_native") - rn_android_library( name = "imagehelper", srcs = glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/BUCK index 1f9811cd71e22c..4a3644e5adfd1b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/scroll/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/scroll/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "scroll", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/text/BUCK index aeefdaeac365cb..c7513327f39a09 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "IS_OSS_BUILD", "YOGA_TARGET", "react_native_android_toplevel_dep", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - # TODO(T115916830): Remove when Kotlin files are used in this module KOTLIN_STDLIB_DEPS = [react_native_android_toplevel_dep("third-party/kotlin:kotlin-stdlib")] if IS_OSS_BUILD else [] diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/BUCK index e0b5eed9e58555..e48762cb597ef9 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/text/frescosupport/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "frescosupport", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/BUCK index 53fec8343d373e..233f1e12611afa 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/textinput/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/textinput/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "IS_OSS_BUILD", "YOGA_TARGET", "react_native_android_toplevel_dep", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - # TODO(T115916830): Remove when Kotlin files are used in this module KOTLIN_STDLIB_DEPS = [react_native_android_toplevel_dep("third-party/kotlin:kotlin-stdlib")] if IS_OSS_BUILD else [] diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/BUCK index d30c24c96a6635..5efd187e053e8f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/unimplementedview/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "unimplementedview", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/view/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/view/BUCK index adde8d19cf5001..2db76a78180d4e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/view/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/view/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "view", srcs = glob([ diff --git a/ReactAndroid/src/main/jni/react/cxxcomponents/BUCK b/ReactAndroid/src/main/jni/react/cxxcomponents/BUCK index b4e2a24b880acf..3c51f2f3f16d26 100644 --- a/ReactAndroid/src/main/jni/react/cxxcomponents/BUCK +++ b/ReactAndroid/src/main/jni/react/cxxcomponents/BUCK @@ -8,8 +8,6 @@ load( "subdir_glob", ) -oncall("react_native") - rn_xplat_cxx_library( name = "components", srcs = glob( diff --git a/ReactAndroid/src/main/jni/react/hermes/instrumentation/BUCK b/ReactAndroid/src/main/jni/react/hermes/instrumentation/BUCK index 56c3f96b64fb12..f2c0e6ef2ef519 100644 --- a/ReactAndroid/src/main/jni/react/hermes/instrumentation/BUCK +++ b/ReactAndroid/src/main/jni/react/hermes/instrumentation/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_target", "react_native_xplat_dep", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "jni_hermes_samplingprofiler", srcs = [ diff --git a/ReactAndroid/src/main/jni/react/jni/BUCK b/ReactAndroid/src/main/jni/react/jni/BUCK index b320137ff6f973..5ce1930b4e22e1 100644 --- a/ReactAndroid/src/main/jni/react/jni/BUCK +++ b/ReactAndroid/src/main/jni/react/jni/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "IS_OSS_BUILD", "react_native_target", "react_native_xplat_dep", "react_native_xplat_target", "rn_xplat_cxx_library") -oncall("react_native") - EXPORTED_HEADERS = [ "CxxModuleWrapper.h", "CxxModuleWrapperBase.h", diff --git a/ReactAndroid/src/main/jni/react/mapbuffer/BUCK b/ReactAndroid/src/main/jni/react/mapbuffer/BUCK index b12a088a4212d3..d211b7cdfe4246 100644 --- a/ReactAndroid/src/main/jni/react/mapbuffer/BUCK +++ b/ReactAndroid/src/main/jni/react/mapbuffer/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_xplat_target", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = glob(["**/*.cpp"]), diff --git a/ReactAndroid/src/main/jni/react/reactnativeblob/BUCK b/ReactAndroid/src/main/jni/react/reactnativeblob/BUCK index a4e2679c87e709..3ef04910b81609 100644 --- a/ReactAndroid/src/main/jni/react/reactnativeblob/BUCK +++ b/ReactAndroid/src/main/jni/react/reactnativeblob/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_target", "react_native_xplat_dep", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = glob(["*.cpp"]), diff --git a/ReactAndroid/src/main/jni/react/reactperflogger/BUCK b/ReactAndroid/src/main/jni/react/reactperflogger/BUCK index e31315690887e7..8421b1b3860e6d 100644 --- a/ReactAndroid/src/main/jni/react/reactperflogger/BUCK +++ b/ReactAndroid/src/main/jni/react/reactperflogger/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_xplat_target", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = [ diff --git a/ReactAndroid/src/main/jni/react/turbomodule/BUCK b/ReactAndroid/src/main/jni/react/turbomodule/BUCK index b87daf1c2ed87b..e546b70a044399 100644 --- a/ReactAndroid/src/main/jni/react/turbomodule/BUCK +++ b/ReactAndroid/src/main/jni/react/turbomodule/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_target", "react_native_xplat_shared_library_target", "react_native_xplat_target", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = [ diff --git a/ReactAndroid/src/main/jni/react/uimanager/BUCK b/ReactAndroid/src/main/jni/react/uimanager/BUCK index df2e81d4f1fb07..c554a6dbdefd82 100644 --- a/ReactAndroid/src/main/jni/react/uimanager/BUCK +++ b/ReactAndroid/src/main/jni/react/uimanager/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_target", "react_native_xplat_target", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = glob(["*.cpp"]), diff --git a/ReactCommon/butter/BUCK b/ReactCommon/butter/BUCK index d13dc2638e71c8..58c92e8f7a26fe 100644 --- a/ReactCommon/butter/BUCK +++ b/ReactCommon/butter/BUCK @@ -10,8 +10,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/callinvoker/BUCK b/ReactCommon/callinvoker/BUCK index ebafca366b8024..dda5b563bcd5da 100644 --- a/ReactCommon/callinvoker/BUCK +++ b/ReactCommon/callinvoker/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "callinvoker", srcs = glob(["**/*.cpp"]), diff --git a/ReactCommon/cxxreact/BUCK b/ReactCommon/cxxreact/BUCK index d5648bc04bb6c1..c22ce5b7d065c1 100644 --- a/ReactCommon/cxxreact/BUCK +++ b/ReactCommon/cxxreact/BUCK @@ -1,8 +1,6 @@ load("@fbsource//tools/build_defs:glob_defs.bzl", "subdir_glob") load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "get_android_inspector_flags", "get_apple_compiler_flags", "get_apple_inspector_flags", "get_preprocessor_flags_for_build_mode", "react_native_xplat_target", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "module", header_namespace = "", diff --git a/ReactCommon/jsi/BUCK b/ReactCommon/jsi/BUCK index 371ddd6d5aa51a..2d5e68fe3de0b6 100644 --- a/ReactCommon/jsi/BUCK +++ b/ReactCommon/jsi/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "APPLE", "IOS", "MACOSX", "react_native_xplat_dep", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "jsi", srcs = [ diff --git a/ReactCommon/jsiexecutor/BUCK b/ReactCommon/jsiexecutor/BUCK index bf234313b2be46..8b1abbf9ba505e 100644 --- a/ReactCommon/jsiexecutor/BUCK +++ b/ReactCommon/jsiexecutor/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "cxx_library", "react_native_xplat_dep", "react_native_xplat_target") -oncall("react_native") - cxx_library( name = "jsiexecutor", srcs = [ diff --git a/ReactCommon/jsinspector/BUCK b/ReactCommon/jsinspector/BUCK index c726b478810b9f..6045c8797a9399 100644 --- a/ReactCommon/jsinspector/BUCK +++ b/ReactCommon/jsinspector/BUCK @@ -2,8 +2,6 @@ load("@fbsource//tools/build_defs:glob_defs.bzl", "subdir_glob") load("@fbsource//tools/build_defs:platform_defs.bzl", "ANDROID", "APPLE", "CXX", "FBCODE", "WINDOWS") load("//tools/build_defs/oss:rn_defs.bzl", "get_hermes_shared_library_preprocessor_flags", "rn_xplat_cxx_library") -oncall("react_native") - EXPORTED_HEADERS = [ "InspectorInterfaces.h", ] diff --git a/ReactCommon/logger/BUCK b/ReactCommon/logger/BUCK index 92cfe2920eee92..7446aa16294286 100644 --- a/ReactCommon/logger/BUCK +++ b/ReactCommon/logger/BUCK @@ -2,8 +2,6 @@ load("@fbsource//tools/build_defs:glob_defs.bzl", "subdir_glob") load("@fbsource//tools/build_defs:platform_defs.bzl", "ANDROID", "APPLE", "CXX", "FBCODE", "WINDOWS") load("//tools/build_defs/oss:rn_defs.bzl", "rn_xplat_cxx_library") -oncall("react_native") - EXPORTED_HEADERS = [ "react_native_log.h", ] diff --git a/ReactCommon/react/config/BUCK b/ReactCommon/react/config/BUCK index 5a8ef35a94868b..3e7e3ae6d36174 100644 --- a/ReactCommon/react/config/BUCK +++ b/ReactCommon/react/config/BUCK @@ -3,8 +3,6 @@ load("@fbsource//tools/build_defs:platform_defs.bzl", "ANDROID", "APPLE", "CXX") load("@fbsource//tools/build_defs/apple:flag_defs.bzl", "flags", "get_preprocessor_flags_for_build_mode", "get_static_library_ios_flags") load("@fbsource//tools/build_defs/oss:rn_defs.bzl", "get_apple_inspector_flags", "rn_xplat_cxx_library") -oncall("react_native") - APPLE_COMPILER_FLAGS = flags.get_flag_value( get_static_library_ios_flags(), "compiler_flags", diff --git a/ReactCommon/react/debug/BUCK b/ReactCommon/react/debug/BUCK index 6d2492732a94d4..20c7a930f8c50e 100644 --- a/ReactCommon/react/debug/BUCK +++ b/ReactCommon/react/debug/BUCK @@ -10,8 +10,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/nativemodule/core/BUCK b/ReactCommon/react/nativemodule/core/BUCK index a60ba026ea9459..9de875edcb6542 100644 --- a/ReactCommon/react/nativemodule/core/BUCK +++ b/ReactCommon/react/nativemodule/core/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "FBJNI_TARGET", "get_objc_arc_preprocessor_flags", "get_preprocessor_flags_for_build_mode", "get_static_library_ios_flags", "react_native_target", "react_native_xplat_shared_library_target", "react_native_xplat_target", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "core", srcs = glob( diff --git a/ReactCommon/react/nativemodule/samples/BUCK b/ReactCommon/react/nativemodule/samples/BUCK index cdd9f104c5902e..2285cf02648ade 100644 --- a/ReactCommon/react/nativemodule/samples/BUCK +++ b/ReactCommon/react/nativemodule/samples/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "FBJNI_TARGET", "get_objc_arc_preprocessor_flags", "get_preprocessor_flags_for_build_mode", "get_static_library_ios_flags", "react_native_dep", "react_native_target", "react_native_xplat_target", "rn_android_library", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "samples", srcs = glob( diff --git a/ReactCommon/react/renderer/componentregistry/BUCK b/ReactCommon/react/renderer/componentregistry/BUCK index fb502f8bab4fb3..b1fdde2b635711 100644 --- a/ReactCommon/react/renderer/componentregistry/BUCK +++ b/ReactCommon/react/renderer/componentregistry/BUCK @@ -11,8 +11,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/componentregistry/native/BUCK b/ReactCommon/react/renderer/componentregistry/native/BUCK index 0046ddb684826b..de356fba9fa71b 100644 --- a/ReactCommon/react/renderer/componentregistry/native/BUCK +++ b/ReactCommon/react/renderer/componentregistry/native/BUCK @@ -10,8 +10,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/text/BUCK b/ReactCommon/react/renderer/components/text/BUCK index 9934179513a104..27bc1edacc8537 100644 --- a/ReactCommon/react/renderer/components/text/BUCK +++ b/ReactCommon/react/renderer/components/text/BUCK @@ -13,8 +13,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/textinput/BUCK b/ReactCommon/react/renderer/components/textinput/BUCK index 86439ae1d67167..c8e70cd050b5cc 100644 --- a/ReactCommon/react/renderer/components/textinput/BUCK +++ b/ReactCommon/react/renderer/components/textinput/BUCK @@ -13,8 +13,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/textinput/iostextinput/BUCK b/ReactCommon/react/renderer/components/textinput/iostextinput/BUCK index 1826dcd8e5bdb7..28b6cf40d8289b 100644 --- a/ReactCommon/react/renderer/components/textinput/iostextinput/BUCK +++ b/ReactCommon/react/renderer/components/textinput/iostextinput/BUCK @@ -12,8 +12,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/leakchecker/BUCK b/ReactCommon/react/renderer/leakchecker/BUCK index 251f1f27896956..826a1b8d6f1dd6 100644 --- a/ReactCommon/react/renderer/leakchecker/BUCK +++ b/ReactCommon/react/renderer/leakchecker/BUCK @@ -11,8 +11,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/scheduler/BUCK b/ReactCommon/react/renderer/scheduler/BUCK index 1cac72d2d00b3d..bdd6089460515c 100644 --- a/ReactCommon/react/renderer/scheduler/BUCK +++ b/ReactCommon/react/renderer/scheduler/BUCK @@ -11,8 +11,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/textlayoutmanager/BUCK b/ReactCommon/react/renderer/textlayoutmanager/BUCK index 1f7bff221afaff..c4e3be0d401ac9 100644 --- a/ReactCommon/react/renderer/textlayoutmanager/BUCK +++ b/ReactCommon/react/renderer/textlayoutmanager/BUCK @@ -14,8 +14,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/test_utils/BUCK b/ReactCommon/react/test_utils/BUCK index a03df5c1464fd0..3a2521ae60e320 100644 --- a/ReactCommon/react/test_utils/BUCK +++ b/ReactCommon/react/test_utils/BUCK @@ -11,8 +11,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/utils/BUCK b/ReactCommon/react/utils/BUCK index 46bad34d27d372..e29248a92859f4 100644 --- a/ReactCommon/react/utils/BUCK +++ b/ReactCommon/react/utils/BUCK @@ -12,8 +12,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/reactperflogger/BUCK b/ReactCommon/reactperflogger/BUCK index d9139a0eef9fd4..554de6133701c9 100644 --- a/ReactCommon/reactperflogger/BUCK +++ b/ReactCommon/reactperflogger/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "APPLE", "CXX", "rn_xplat_cxx_library") -oncall("react_native") - rn_xplat_cxx_library( name = "reactperflogger", srcs = glob(["**/*.cpp"]), diff --git a/ReactCommon/runtimeexecutor/BUCK b/ReactCommon/runtimeexecutor/BUCK index 817f8986e9c6f7..caec10316e6e68 100644 --- a/ReactCommon/runtimeexecutor/BUCK +++ b/ReactCommon/runtimeexecutor/BUCK @@ -9,8 +9,6 @@ load( "rn_xplat_cxx_library", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/packages/assets/BUCK b/packages/assets/BUCK index 6cfc5d65e51d92..df68edf8b3a969 100644 --- a/packages/assets/BUCK +++ b/packages/assets/BUCK @@ -1,8 +1,6 @@ load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") load("@fbsource//xplat/js:JS_DEFS.bzl", "rn_library") -oncall("react_native") - rn_library( name = "assets", labels = [ diff --git a/packages/normalize-color/BUCK b/packages/normalize-color/BUCK index 8faba2eac921c0..faaff9e880b021 100644 --- a/packages/normalize-color/BUCK +++ b/packages/normalize-color/BUCK @@ -1,8 +1,6 @@ load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") load("@fbsource//xplat/js:JS_DEFS.bzl", "rn_library") -oncall("react_native") - rn_library( name = "normalize-color", labels = [ diff --git a/packages/polyfills/BUCK b/packages/polyfills/BUCK index 48e41fd9ad8bef..88ffc9513eee78 100644 --- a/packages/polyfills/BUCK +++ b/packages/polyfills/BUCK @@ -1,8 +1,6 @@ load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") load("@fbsource//xplat/js:JS_DEFS.bzl", "relative_path_to_js_root", "rn_library") -oncall("react_native") - yarn_workspace( name = "yarn-workspace", srcs = glob( From c63882238bc6b052109b1250e8bc5ef7de92bc53 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 24 Oct 2022 10:44:39 -0700 Subject: [PATCH 013/169] Back out "add oncall annotation for BUCK files in xplat based on supermodule information - /home/s2shi/tmp/xplat_buck_oncall/xplat_buck_2nd_batch00" (#35065) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35065 Original commit changeset: ac76ea701e3d Original Phabricator Diff: D40611860 (https://github.com/facebook/react-native/commit/860b4d914407ef11d0d5de80e5add275f83de3fd) Open source is using BUCK 1 which does not seem to have the `oncall` directive. Backing it out because it is breaking the external CI. ## Changelog [internal] Reviewed By: cortinico Differential Revision: D40637084 fbshipit-source-id: 2be7296f859412210afe981adf500ab6540f7ee8 --- IntegrationTests/BUCK | 2 -- ReactAndroid/src/androidTest/js/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/modal/BUCK | 2 -- .../src/main/java/com/facebook/react/views/progressbar/BUCK | 2 -- ReactAndroid/src/main/java/com/facebook/react/views/slider/BUCK | 2 -- .../src/main/java/com/facebook/react/views/swiperefresh/BUCK | 2 -- .../src/main/java/com/facebook/react/views/switchview/BUCK | 2 -- ReactAndroid/src/main/jni/react/fabric/BUCK | 2 -- ReactCommon/react/renderer/components/inputaccessory/BUCK | 2 -- .../react/renderer/components/legacyviewmanagerinterop/BUCK | 2 -- ReactCommon/react/renderer/components/modal/BUCK | 2 -- ReactCommon/react/renderer/components/progressbar/BUCK | 2 -- ReactCommon/react/renderer/components/safeareaview/BUCK | 2 -- ReactCommon/react/renderer/components/slider/BUCK | 2 -- ReactCommon/react/renderer/components/switch/BUCK | 2 -- 16 files changed, 32 deletions(-) diff --git a/IntegrationTests/BUCK b/IntegrationTests/BUCK index 6ae65ac68a2eac..0ac92a5c69e38a 100644 --- a/IntegrationTests/BUCK +++ b/IntegrationTests/BUCK @@ -4,8 +4,6 @@ load("@fbsource//tools/build_defs/oss:metro_defs.bzl", "rn_library") # This file was generated by running # js1 build buckfiles -oncall("react_native") - rn_library( name = "IntegrationTests", srcs = js_library_glob( diff --git a/ReactAndroid/src/androidTest/js/BUCK b/ReactAndroid/src/androidTest/js/BUCK index d5a0d0c4f0176f..c7b68b54681994 100644 --- a/ReactAndroid/src/androidTest/js/BUCK +++ b/ReactAndroid/src/androidTest/js/BUCK @@ -4,8 +4,6 @@ load("//tools/build_defs/oss:metro_defs.bzl", "rn_library") # This file was generated by running # js1 build buckfiles -oncall("react_native") - rn_library( name = "js", srcs = js_library_glob( diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK index 7103f892da3208..9677362369c1ca 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "drawer", srcs = glob(["**/*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/modal/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/modal/BUCK index 3ab01fb07b0bde..4418ccfcfe588b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/modal/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/modal/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "modal", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/BUCK index 94e61b2b3d7024..52d4b639706aed 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/progressbar/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "progressbar", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/slider/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/slider/BUCK index 68fcd2b701a154..e402f20b8b6d86 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/slider/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/slider/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "slider", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/BUCK index 8892b1249fe8e9..a1fe56f942e591 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/swiperefresh/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "swiperefresh", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/BUCK index fa4b172a597c8d..ad8db8e74eaef8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/switchview/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/switchview/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "YOGA_TARGET", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") -oncall("react_native") - rn_android_library( name = "switchview", srcs = glob(["*.java"]), diff --git a/ReactAndroid/src/main/jni/react/fabric/BUCK b/ReactAndroid/src/main/jni/react/fabric/BUCK index 141ff37cef94ea..b8e6516cb04470 100644 --- a/ReactAndroid/src/main/jni/react/fabric/BUCK +++ b/ReactAndroid/src/main/jni/react/fabric/BUCK @@ -1,7 +1,5 @@ load("//tools/build_defs/oss:rn_defs.bzl", "ANDROID", "FBJNI_TARGET", "react_native_target", "react_native_xplat_target", "rn_xplat_cxx_library", "subdir_glob") -oncall("react_native") - rn_xplat_cxx_library( name = "jni", srcs = glob(["*.cpp"]), diff --git a/ReactCommon/react/renderer/components/inputaccessory/BUCK b/ReactCommon/react/renderer/components/inputaccessory/BUCK index e009e4bacf6143..33df142a8c6a39 100644 --- a/ReactCommon/react/renderer/components/inputaccessory/BUCK +++ b/ReactCommon/react/renderer/components/inputaccessory/BUCK @@ -9,8 +9,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/legacyviewmanagerinterop/BUCK b/ReactCommon/react/renderer/components/legacyviewmanagerinterop/BUCK index d6177292f603de..5e0a1f46189463 100644 --- a/ReactCommon/react/renderer/components/legacyviewmanagerinterop/BUCK +++ b/ReactCommon/react/renderer/components/legacyviewmanagerinterop/BUCK @@ -9,8 +9,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/modal/BUCK b/ReactCommon/react/renderer/components/modal/BUCK index c482946bfb4b10..c95a9146013603 100644 --- a/ReactCommon/react/renderer/components/modal/BUCK +++ b/ReactCommon/react/renderer/components/modal/BUCK @@ -12,8 +12,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/progressbar/BUCK b/ReactCommon/react/renderer/components/progressbar/BUCK index 1a27e387cb1715..1cbc166b322c60 100644 --- a/ReactCommon/react/renderer/components/progressbar/BUCK +++ b/ReactCommon/react/renderer/components/progressbar/BUCK @@ -14,8 +14,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/safeareaview/BUCK b/ReactCommon/react/renderer/components/safeareaview/BUCK index 53162f8fd7d8e3..544c8c8c9e53dd 100644 --- a/ReactCommon/react/renderer/components/safeareaview/BUCK +++ b/ReactCommon/react/renderer/components/safeareaview/BUCK @@ -9,8 +9,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/slider/BUCK b/ReactCommon/react/renderer/components/slider/BUCK index 1ef1f24b16fc74..7cc3f2f6849f02 100644 --- a/ReactCommon/react/renderer/components/slider/BUCK +++ b/ReactCommon/react/renderer/components/slider/BUCK @@ -14,8 +14,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( diff --git a/ReactCommon/react/renderer/components/switch/BUCK b/ReactCommon/react/renderer/components/switch/BUCK index d9205017cf2c6d..881670fdbdab4d 100644 --- a/ReactCommon/react/renderer/components/switch/BUCK +++ b/ReactCommon/react/renderer/components/switch/BUCK @@ -13,8 +13,6 @@ load( "subdir_glob", ) -oncall("react_native") - APPLE_COMPILER_FLAGS = get_apple_compiler_flags() rn_xplat_cxx_library( From cd020bd7f49f0c733c9b340fcc995397ac4ce5c9 Mon Sep 17 00:00:00 2001 From: Jonathan Keljo Date: Mon, 24 Oct 2022 14:15:15 -0700 Subject: [PATCH 014/169] supermodule:xplat/default/public.hermes Reviewed By: jsendros Differential Revision: D40368129 fbshipit-source-id: 6d33c06be2ed14f80f45c1945358428eac8a32e7 --- ReactCommon/hermes/inspector/BUCK | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ReactCommon/hermes/inspector/BUCK b/ReactCommon/hermes/inspector/BUCK index 3314f69aabd820..53bbdb2d023195 100644 --- a/ReactCommon/hermes/inspector/BUCK +++ b/ReactCommon/hermes/inspector/BUCK @@ -48,7 +48,7 @@ fb_xplat_cxx_library( exported_headers = CHROME_EXPORTED_HEADERS, compiler_flags = CFLAGS_BY_MODE[hermes_build_mode()], fbobjc_header_path_prefix = "hermes/inspector/chrome", - labels = ["supermodule:xplat/default/public.hermes"], + labels = [], macosx_tests_override = [], platforms = (ANDROID, APPLE, CXX, FBCODE, WINDOWS), tests = [":chrome-tests"], @@ -116,7 +116,7 @@ fb_xplat_cxx_library( "//fbandroid/libraries/fbjni:fbjni", ], fbobjc_header_path_prefix = "hermes/inspector/detail", - labels = ["supermodule:xplat/default/public.hermes"], + labels = [], macosx_tests_override = [], platforms = (ANDROID, APPLE, CXX, FBCODE, WINDOWS), tests = [":detail-tests"], @@ -192,7 +192,7 @@ fb_xplat_cxx_library( cxx_tests = [":inspector-tests"], exported_preprocessor_flags = get_hermes_shared_library_preprocessor_flags(), fbobjc_header_path_prefix = "hermes/inspector", - labels = ["supermodule:xplat/default/public.hermes"], + labels = [], macosx_tests_override = [], platforms = (ANDROID, APPLE, CXX, FBCODE, WINDOWS), visibility = [ From 2b348fe00939b87bdcfb342c8134bdd6e2e4ed94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Mon, 24 Oct 2022 15:52:42 -0700 Subject: [PATCH 015/169] Update RNTester bundle identifier Summary: Change RNTester bundle identifier to match Meta's provisioning profiles. Changelog: [Internal] Reviewed By: cortinico Differential Revision: D40532706 fbshipit-source-id: efcd524eb1630a522bcb8a4875a3eed02b5b5e13 --- .../rn-tester/RNTesterPods.xcodeproj/project.pbxproj | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj index 94a995f90f7861..73488e795ff4e0 100644 --- a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj +++ b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj @@ -836,7 +836,7 @@ "-framework", "\"JavaScriptCore\"", ); - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.react.uiapp; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTester.localDevelopment; PRODUCT_NAME = RNTester; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -868,7 +868,7 @@ "-framework", "\"JavaScriptCore\"", ); - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.react.uiapp; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTester.localDevelopment; PRODUCT_NAME = RNTester; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -1068,7 +1068,7 @@ "-DFB_SONARKIT_ENABLED=1", ); OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -DFB_SONARKIT_ENABLED"; - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.RNTesterUnitTests; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTesterUnitTests; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -1105,7 +1105,7 @@ "-DFB_SONARKIT_ENABLED=1", ); OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -DFB_SONARKIT_ENABLED"; - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.RNTesterUnitTests; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTesterUnitTests; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -1142,7 +1142,7 @@ "-DFB_SONARKIT_ENABLED=1", ); OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -DFB_SONARKIT_ENABLED"; - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.RNTesterIntegrationTests; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTesterIntegrationTests; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/RNTester.app/RNTester"; @@ -1176,7 +1176,7 @@ "-DFB_SONARKIT_ENABLED=1", ); OTHER_SWIFT_FLAGS = "$(inherited) -Xcc -DFB_SONARKIT_ENABLED"; - PRODUCT_BUNDLE_IDENTIFIER = com.facebook.RNTesterIntegrationTests; + PRODUCT_BUNDLE_IDENTIFIER = com.meta.RNTesterIntegrationTests; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/RNTester.app/RNTester"; From 1bb5cca72df2200be63c0e3e2c1d456577d936f9 Mon Sep 17 00:00:00 2001 From: Phillip Pan Date: Mon, 24 Oct 2022 17:49:41 -0700 Subject: [PATCH 016/169] fix typo in LeakChecker Summary: Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D40654731 fbshipit-source-id: c72c217244d4a0d4a0467085ff604460219ade60 --- ReactCommon/react/renderer/leakchecker/LeakChecker.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ReactCommon/react/renderer/leakchecker/LeakChecker.cpp b/ReactCommon/react/renderer/leakchecker/LeakChecker.cpp index 59c93a27747794..fa7909e88e2ef9 100644 --- a/ReactCommon/react/renderer/leakchecker/LeakChecker.cpp +++ b/ReactCommon/react/renderer/leakchecker/LeakChecker.cpp @@ -26,14 +26,14 @@ void LeakChecker::stopSurface(SurfaceId surfaceId) { if (previouslyStoppedSurface_ > 0) { // Dispatch the check onto JavaScript thread to make sure all other // cleanup code has had chance to run. - runtimeExecutor_([previouslySoppedSurface = previouslyStoppedSurface_, + runtimeExecutor_([previouslyStoppedSurface = previouslyStoppedSurface_, this](jsi::Runtime &runtime) { runtime.instrumentation().collectGarbage("LeakChecker"); // For now check the previous surface because React uses double // buffering which keeps the surface that was just stopped in // memory. This is a documented problem in the last point of // https://github.com/facebook/react/issues/16087 - checkSurfaceForLeaks(previouslySoppedSurface); + checkSurfaceForLeaks(previouslyStoppedSurface); }); } From 428feb2f76c55d6ae5914b019095cd835aa514b0 Mon Sep 17 00:00:00 2001 From: Jan Kassens Date: Mon, 24 Oct 2022 20:16:57 -0700 Subject: [PATCH 017/169] fix crash when converting symbol or BigInt to dynamic Summary: Throws a JS error instead of crashing Hermes with an invariant when trying to convert a JS symbol or BigInt to a folly::dynamic value. Changelog: [General][Fixed] - Fixed crash when converting JS symbol to folly::dynamic Reviewed By: javache Differential Revision: D40444164 fbshipit-source-id: 37df8059b2eb425563f30cf1e9c0436e8d665b34 --- ReactCommon/jsi/jsi/JSIDynamic.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ReactCommon/jsi/jsi/JSIDynamic.cpp b/ReactCommon/jsi/jsi/JSIDynamic.cpp index 4464cc3b62f952..02f112c0e0ca09 100644 --- a/ReactCommon/jsi/jsi/JSIDynamic.cpp +++ b/ReactCommon/jsi/jsi/JSIDynamic.cpp @@ -129,8 +129,7 @@ void dynamicFromValueShallow( output = value.getNumber(); } else if (value.isString()) { output = value.getString(runtime).utf8(runtime); - } else { - CHECK(value.isObject()); + } else if (value.isObject()) { Object obj = value.getObject(runtime); if (obj.isArray(runtime)) { output = folly::dynamic::array(); @@ -140,6 +139,12 @@ void dynamicFromValueShallow( output = folly::dynamic::object(); } stack.emplace_back(&output, std::move(obj)); + } else if (value.isBigInt()) { + throw JSError(runtime, "JS BigInts are not convertible to dynamic"); + } else if (value.isSymbol()) { + throw JSError(runtime, "JS Symbols are not convertible to dynamic"); + } else { + throw JSError(runtime, "Value is not convertible to dynamic"); } } From 6a3bfa7a62fdf690eafb20a761052f187df64872 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 25 Oct 2022 02:31:10 -0700 Subject: [PATCH 018/169] Bump NDK to 23 and fbjni to 0.3.0 (#35066) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35066 This just bumps the NDK version used inside the template to be 23. We can't merge this as it is but we have to wait for a bump of the Docker image for Android. Changelog: [Android] [Changed] - Bump NDK to 23 allow-large-files Reviewed By: cipolleschi Differential Revision: D40637103 fbshipit-source-id: e637140cbe6052e94a6efedf12f4b5b81b90a7eb --- ReactAndroid/gradle.properties | 2 +- ReactAndroid/hermes-engine/build.gradle | 2 +- template/android/build.gradle | 9 ++------- 3 files changed, 4 insertions(+), 9 deletions(-) diff --git a/ReactAndroid/gradle.properties b/ReactAndroid/gradle.properties index e66d35b65f04e7..557a5f07e5363e 100644 --- a/ReactAndroid/gradle.properties +++ b/ReactAndroid/gradle.properties @@ -7,7 +7,7 @@ ANDROIDX_AUTOFILL_VERSION=1.1.0 ANDROIDX_TEST_VERSION=1.1.0 ANDROIDX_TRACING_VERSION=1.1.0 ASSERTJ_VERSION=3.21.0 -FBJNI_VERSION=0.2.2 +FBJNI_VERSION=0.3.0 FRESCO_VERSION=2.5.0 INFER_ANNOTATIONS_VERSION=0.18.0 JAVAX_INJECT_VERSION=1 diff --git a/ReactAndroid/hermes-engine/build.gradle b/ReactAndroid/hermes-engine/build.gradle index d7d38e9ea1b489..9ab86d50d1f601 100644 --- a/ReactAndroid/hermes-engine/build.gradle +++ b/ReactAndroid/hermes-engine/build.gradle @@ -195,7 +195,7 @@ android { } dependencies { - implementation("com.facebook.fbjni:fbjni:0.2.2") + implementation("com.facebook.fbjni:fbjni:0.3.0") implementation("com.facebook.soloader:soloader:0.10.4") implementation("com.facebook.yoga:proguard-annotations:1.19.0") implementation("androidx.annotation:annotation:1.3.0") diff --git a/template/android/build.gradle b/template/android/build.gradle index 30133c1d5b3a46..bfa9a2b429203b 100644 --- a/template/android/build.gradle +++ b/template/android/build.gradle @@ -7,13 +7,8 @@ buildscript { compileSdkVersion = 31 targetSdkVersion = 31 - if (System.properties['os.arch'] == "aarch64") { - // For M1 Users we need to use the NDK 24 which added support for aarch64 - ndkVersion = "24.0.8215888" - } else { - // Otherwise we default to the side-by-side NDK version from AGP. - ndkVersion = "21.4.7075529" - } + // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP. + ndkVersion = "23.1.7779620" } repositories { google() From c419b4fa0c764b49fece60843c2ba7443a2f4a2b Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 25 Oct 2022 03:24:38 -0700 Subject: [PATCH 019/169] Bump react-native-gradle-plugin to 0.71.5 Summary: Bumping RNGP to make sure all the changes are available for 0.71 I've also removed the caret from react-native's package.json as I don't want .5 to be used by template tests yet. The Android template needs to be updated in order to use that version of the Gradle plugin. Changelog: [Internal] [Changed] - Bump react-native-gradle-plugin to 0.71.5 Reviewed By: cipolleschi Differential Revision: D40642114 fbshipit-source-id: 70359efc3d2300e9c04c1b361c45061fd1c2931b --- package.json | 2 +- packages/react-native-gradle-plugin/package.json | 2 +- yarn.lock | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 02db1eb56c2b6f..a56cc7d09200ae 100644 --- a/package.json +++ b/package.json @@ -131,7 +131,7 @@ "pretty-format": "^26.5.2", "promise": "^8.2.0", "react-devtools-core": "^4.26.1", - "react-native-gradle-plugin": "^0.71.4", + "react-native-gradle-plugin": "0.71.4", "react-refresh": "^0.4.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 1d39d26aa985f9..1c2e37efa949bd 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "react-native-gradle-plugin", - "version": "0.71.4", + "version": "0.71.5", "description": "⚛️ Gradle Plugin for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", "repository": { diff --git a/yarn.lock b/yarn.lock index 740f4c15920f8f..5173fb435f26bc 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7960,6 +7960,11 @@ react-is@^17.0.1: resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== +react-native-gradle-plugin@0.71.4: + version "0.71.4" + resolved "https://registry.yarnpkg.com/react-native-gradle-plugin/-/react-native-gradle-plugin-0.71.4.tgz#dd000c1539e0ce465237637d3e16fe619cd84467" + integrity sha512-5izzWXIlr5DL5+cx3a6oSA4cgSCw9Kv7WQjHqLxV2I1fSfzjzEdYTaDfrNjdcy71BHeeUB6BEyl70yXpjkCkdA== + react-refresh@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.4.0.tgz#d421f9bd65e0e4b9822a399f14ac56bda9c92292" From 5940d25cc184241ed77aca85c62f4ee071210d9b Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Tue, 25 Oct 2022 05:01:19 -0700 Subject: [PATCH 020/169] Create the Parser interface (#35036) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35036 This diff is the base to create a polimorphic behavior for TypeScript and Flow parser. This type will allow to share a lot of code between the parsers and also to keep their differences a part. It will be the base diff/PR for further tasks in the Codegen umbrella Issue ## Changelog: [General][Added] - Parser interface to divide parser logic. Reviewed By: cortinico Differential Revision: D40548707 fbshipit-source-id: e632ba52b00b43e50306e3a792a841e72e8c07f4 --- .../src/parsers/errors.js | 15 ++++++------ .../src/parsers/flow/modules/index.js | 5 +++- .../src/parsers/flow/parser.js | 23 ++++++++++++++++++ .../src/parsers/parser.js | 24 +++++++++++++++++++ .../src/parsers/typescript/modules/index.js | 7 ++++-- .../src/parsers/typescript/parser.js | 22 +++++++++++++++++ 6 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 packages/react-native-codegen/src/parsers/flow/parser.js create mode 100644 packages/react-native-codegen/src/parsers/parser.js create mode 100644 packages/react-native-codegen/src/parsers/typescript/parser.js diff --git a/packages/react-native-codegen/src/parsers/errors.js b/packages/react-native-codegen/src/parsers/errors.js index 4882a9bdb43ac6..3b85694a504f99 100644 --- a/packages/react-native-codegen/src/parsers/errors.js +++ b/packages/react-native-codegen/src/parsers/errors.js @@ -11,7 +11,7 @@ 'use strict'; const invariant = require('invariant'); - +import type {Parser} from './parser'; export type ParserType = 'Flow' | 'TypeScript'; class ParserError extends Error { @@ -110,23 +110,22 @@ class UnsupportedTypeAnnotationParserError extends ParserError { } class UnsupportedGenericParserError extends ParserError { - +genericName: string; + // +genericName: string; constructor( nativeModuleName: string, genericTypeAnnotation: $FlowFixMe, - language: ParserType, + parser: Parser, ) { - const genericName = - language === 'TypeScript' - ? genericTypeAnnotation.typeName.name - : genericTypeAnnotation.id.name; + const genericName = parser.nameForGenericTypeAnnotation( + genericTypeAnnotation, + ); super( nativeModuleName, genericTypeAnnotation, `Unrecognized generic type '${genericName}' in NativeModule spec.`, ); - this.genericName = genericName; + // this.genericName = genericName; } } diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 9e9f3e6abe3ddb..914bb27128bcff 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -81,7 +81,10 @@ const { throwIfMoreThanOneModuleInterfaceParserError, } = require('../../error-utils'); +const {FlowParser} = require('../parser.js'); + const language = 'Flow'; +const parser = new FlowParser(); function translateArrayTypeAnnotation( hasteModuleName: string, @@ -276,7 +279,7 @@ function translateTypeAnnotation( throw new UnsupportedGenericParserError( hasteModuleName, typeAnnotation, - language, + parser, ); } } diff --git a/packages/react-native-codegen/src/parsers/flow/parser.js b/packages/react-native-codegen/src/parsers/flow/parser.js new file mode 100644 index 00000000000000..47481c90378365 --- /dev/null +++ b/packages/react-native-codegen/src/parsers/flow/parser.js @@ -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. + * + * @flow strict + * @format + */ + +'use strict'; + +import type {Parser} from '../parser'; + +class FlowParser implements Parser { + nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { + return typeAnnotation.id.name; + } +} + +module.exports = { + FlowParser, +}; diff --git a/packages/react-native-codegen/src/parsers/parser.js b/packages/react-native-codegen/src/parsers/parser.js new file mode 100644 index 00000000000000..e98b67872b2343 --- /dev/null +++ b/packages/react-native-codegen/src/parsers/parser.js @@ -0,0 +1,24 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +'use strict'; + +/** + * This is the main interface for Parsers of various languages. + * It exposes all the methods that contain language-specific logic. + */ +export interface Parser { + /** + * Given a type annotation for a generic type, it returns the type name. + * @parameter typeAnnotation: the annotation for a type in the AST. + * @returns: the name of the type. + */ + nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string; +} diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 448ff4388ab11e..3c26d7ab84d0df 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -80,7 +80,10 @@ const { throwIfUnsupportedFunctionReturnTypeAnnotationParserError, } = require('../../error-utils'); +const {TypeScriptParser} = require('../parser'); + const language = 'TypeScript'; +const parser = new TypeScriptParser(); function translateArrayTypeAnnotation( hasteModuleName: string, @@ -205,7 +208,7 @@ function translateTypeAnnotation( throw new UnsupportedGenericParserError( hasteModuleName, typeAnnotation, - language, + parser, ); } } @@ -290,7 +293,7 @@ function translateTypeAnnotation( throw new UnsupportedGenericParserError( hasteModuleName, typeAnnotation, - language, + parser, ); } } diff --git a/packages/react-native-codegen/src/parsers/typescript/parser.js b/packages/react-native-codegen/src/parsers/typescript/parser.js new file mode 100644 index 00000000000000..1c9db6d8d175e2 --- /dev/null +++ b/packages/react-native-codegen/src/parsers/typescript/parser.js @@ -0,0 +1,22 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +'use strict'; + +import type {Parser} from '../parser'; + +class TypeScriptParser implements Parser { + nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { + return typeAnnotation.typeName.name; + } +} +module.exports = { + TypeScriptParser, +}; From e9b89b5ff2b0085128bec2879d761352747d6714 Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Tue, 25 Oct 2022 05:51:25 -0700 Subject: [PATCH 021/169] Respect prop Text.allowFontScaling when sizing text Summary: changelog: [iOS][Fixed] Fix Text.allowFontScaling prop in the new architecture Reviewed By: javache Differential Revision: D40643536 fbshipit-source-id: 1fb77b226089ce5e9ffc642b1d9a3de266d202c3 --- .../textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm b/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm index 1194d476cbc34d..7f5117040cc1a2 100644 --- a/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm +++ b/ReactCommon/react/renderer/textlayoutmanager/platform/ios/RCTAttributedTextUtils.mm @@ -71,7 +71,8 @@ inline static UIFontWeight RCTUIFontWeightFromInteger(NSInteger fontWeight) fontProperties.weight = textAttributes.fontWeight.has_value() ? RCTUIFontWeightFromInteger((NSInteger)textAttributes.fontWeight.value()) : NAN; - fontProperties.sizeMultiplier = textAttributes.fontSizeMultiplier; + fontProperties.sizeMultiplier = + textAttributes.allowFontScaling.value_or(true) ? textAttributes.fontSizeMultiplier : 1; return RCTFontWithFontProperties(fontProperties); } From 745f3ee8c571560406629bc7af3cf4914ef1b211 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Tue, 25 Oct 2022 08:27:47 -0700 Subject: [PATCH 022/169] react-native-code-gen Add Enum Type support for iOS/Android TurboModules Summary: Adding enum support to Android/iOS generated code Changelog: [General][Added] - react-native-code-gen Add Enum Type support for iOS/Android TurboModules Reviewed By: javache Differential Revision: D38967241 fbshipit-source-id: d8bb3019dab198e16905a6422e877cd751119122 --- .../modules/GenerateModuleJavaSpec.js | 27 +++++++++++ .../modules/GenerateModuleJniCpp.js | 33 +++++++++++++ .../GenerateModuleObjCpp/StructCollector.js | 4 +- .../header/serializeConstantsStruct.js | 22 +++++++++ .../header/serializeRegularStruct.js | 22 +++++++++ .../GenerateModuleObjCpp/serializeMethod.js | 33 +++++++++++++ .../modules/__test_fixtures__/fixtures.js | 36 ++++++++++++++ .../GenerateModuleCpp-test.js.snap | 4 ++ .../GenerateModuleH-test.js.snap | 9 ++++ .../GenerateModuleHObjCpp-test.js.snap | 3 ++ .../GenerateModuleJavaSpec-test.js.snap | 4 ++ .../GenerateModuleJniCpp-test.js.snap | 6 +++ .../GenerateModuleMm-test.js.snap | 7 +++ .../modules/__test_fixtures__/fixtures.js | 23 ++++++++- .../module-parser-snapshot-test.js.snap | 47 ++++++++++++++++++- .../src/parsers/flow/modules/index.js | 1 - .../modules/__test_fixtures__/fixtures.js | 25 +++++++++- ...script-module-parser-snapshot-test.js.snap | 47 ++++++++++++++++++- .../src/parsers/typescript/modules/index.js | 1 - 19 files changed, 347 insertions(+), 7 deletions(-) diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js index cfcf87c0597e44..0b807bbbfa966e 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js @@ -138,6 +138,15 @@ function translateFunctionParamToJavaType( return !isRequired ? 'Double' : 'double'; case 'BooleanTypeAnnotation': return !isRequired ? 'Boolean' : 'boolean'; + case 'EnumDeclaration': + switch (realTypeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return !isRequired ? 'Double' : 'double'; + case 'StringTypeAnnotation': + return wrapIntoNullableIfNeeded('String'); + default: + throw new Error(createErrorMessage(realTypeAnnotation.type)); + } case 'ObjectTypeAnnotation': imports.add('com.facebook.react.bridge.ReadableMap'); if (typeAnnotation.type === 'TypeAliasTypeAnnotation') { @@ -213,6 +222,15 @@ function translateFunctionReturnTypeToJavaType( return nullable ? 'Double' : 'double'; case 'BooleanTypeAnnotation': return nullable ? 'Boolean' : 'boolean'; + case 'EnumDeclaration': + switch (realTypeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return nullable ? 'Double' : 'double'; + case 'StringTypeAnnotation': + return wrapIntoNullableIfNeeded('String'); + default: + throw new Error(createErrorMessage(realTypeAnnotation.type)); + } case 'ObjectTypeAnnotation': imports.add('com.facebook.react.bridge.WritableMap'); return wrapIntoNullableIfNeeded('WritableMap'); @@ -269,6 +287,15 @@ function getFalsyReturnStatementFromReturnType( return nullable ? 'return null;' : 'return 0;'; case 'BooleanTypeAnnotation': return nullable ? 'return null;' : 'return false;'; + case 'EnumDeclaration': + switch (realTypeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return nullable ? 'return null;' : 'return 0;'; + case 'StringTypeAnnotation': + return nullable ? 'return null;' : 'return "";'; + default: + throw new Error(createErrorMessage(realTypeAnnotation.type)); + } case 'StringTypeAnnotation': return nullable ? 'return null;' : 'return "";'; case 'ObjectTypeAnnotation': diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js index 2703c2517227ad..891f4fa6103790 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js @@ -154,6 +154,17 @@ function translateReturnTypeToKind( return 'StringKind'; case 'BooleanTypeAnnotation': return 'BooleanKind'; + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return 'NumberKind'; + case 'StringTypeAnnotation': + return 'StringKind'; + default: + throw new Error( + `Unknown enum prop type for returning value, found: ${realTypeAnnotation.type}"`, + ); + } case 'NumberTypeAnnotation': return 'NumberKind'; case 'DoubleTypeAnnotation': @@ -212,6 +223,17 @@ function translateParamTypeToJniType( return 'Ljava/lang/String;'; case 'BooleanTypeAnnotation': return !isRequired ? 'Ljava/lang/Boolean;' : 'Z'; + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return !isRequired ? 'Ljava/lang/Double;' : 'D'; + case 'StringTypeAnnotation': + return 'Ljava/lang/String;'; + default: + throw new Error( + `Unknown enum prop type for method arg, found: ${realTypeAnnotation.type}"`, + ); + } case 'NumberTypeAnnotation': return !isRequired ? 'Ljava/lang/Double;' : 'D'; case 'DoubleTypeAnnotation': @@ -267,6 +289,17 @@ function translateReturnTypeToJniType( return 'Ljava/lang/String;'; case 'BooleanTypeAnnotation': return nullable ? 'Ljava/lang/Boolean;' : 'Z'; + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return nullable ? 'Ljava/lang/Double;' : 'D'; + case 'StringTypeAnnotation': + return 'Ljava/lang/String;'; + default: + throw new Error( + `Unknown enum prop type for method return type, found: ${realTypeAnnotation.type}"`, + ); + } case 'NumberTypeAnnotation': return nullable ? 'Ljava/lang/Double;' : 'D'; case 'DoubleTypeAnnotation': diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js index d3926812c3bd0d..ef7af6ae44a13e 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js @@ -19,6 +19,7 @@ import type { NativeModuleDoubleTypeAnnotation, NativeModuleFloatTypeAnnotation, NativeModuleBooleanTypeAnnotation, + NativeModuleEnumDeclaration, NativeModuleGenericObjectTypeAnnotation, ReservedTypeAnnotation, NativeModuleTypeAliasTypeAnnotation, @@ -63,6 +64,7 @@ export type StructTypeAnnotation = | NativeModuleDoubleTypeAnnotation | NativeModuleFloatTypeAnnotation | NativeModuleBooleanTypeAnnotation + | NativeModuleEnumDeclaration | NativeModuleGenericObjectTypeAnnotation | ReservedTypeAnnotation | NativeModuleTypeAliasTypeAnnotation @@ -113,7 +115,7 @@ class StructCollector { return wrapNullable(nullable, typeAnnotation); } case 'EnumDeclaration': - throw new Error('Enum types are unsupported in structs'); + return wrapNullable(nullable, typeAnnotation); case 'MixedTypeAnnotation': throw new Error('Mixed types are unsupported in structs'); case 'UnionTypeAnnotation': diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js index d030fdcf442a9a..0fa67683e66215 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js @@ -104,6 +104,17 @@ function toObjCType( return wrapOptional('double'); case 'BooleanTypeAnnotation': return wrapOptional('bool'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return wrapOptional('double'); + case 'StringTypeAnnotation': + return 'NSString *'; + default: + throw new Error( + `Couldn't convert enum into ObjC type: ${typeAnnotation.type}"`, + ); + } case 'GenericObjectTypeAnnotation': return isRequired ? 'id ' : 'id _Nullable '; case 'ArrayTypeAnnotation': @@ -171,6 +182,17 @@ function toObjCValue( return wrapPrimitive('double'); case 'BooleanTypeAnnotation': return wrapPrimitive('BOOL'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return wrapPrimitive('double'); + case 'StringTypeAnnotation': + return value; + default: + throw new Error( + `Couldn't convert enum into ObjC value: ${typeAnnotation.type}"`, + ); + } case 'GenericObjectTypeAnnotation': return value; case 'ArrayTypeAnnotation': diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js index 9cc4aee79ab486..e6c73c73388892 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js @@ -95,6 +95,17 @@ function toObjCType( return wrapOptional('double'); case 'BooleanTypeAnnotation': return wrapOptional('bool'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return wrapOptional('double'); + case 'StringTypeAnnotation': + return 'NSString *'; + default: + throw new Error( + `Couldn't convert enum into ObjC type: ${typeAnnotation.type}"`, + ); + } case 'GenericObjectTypeAnnotation': return isRequired ? 'id ' : 'id _Nullable'; case 'ArrayTypeAnnotation': @@ -161,6 +172,17 @@ function toObjCValue( return RCTBridgingTo('Double'); case 'BooleanTypeAnnotation': return RCTBridgingTo('Bool'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return RCTBridgingTo('Double'); + case 'StringTypeAnnotation': + return RCTBridgingTo('String'); + default: + throw new Error( + `Couldn't convert enum into ObjC value: ${typeAnnotation.type}"`, + ); + } case 'GenericObjectTypeAnnotation': return value; case 'ArrayTypeAnnotation': diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js index 91bcba56ec2ef9..ea84c731b2c653 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js @@ -271,6 +271,17 @@ function getParamObjCType( return notStruct(notRequired ? 'NSNumber *' : 'double'); case 'BooleanTypeAnnotation': return notStruct(notRequired ? 'NSNumber *' : 'BOOL'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return notStruct(notRequired ? 'NSNumber *' : 'double'); + case 'StringTypeAnnotation': + return notStruct(wrapIntoNullableIfNeeded('NSString *')); + default: + throw new Error( + `Unsupported enum type for param "${paramName}" in ${methodName}. Found: ${typeAnnotation.type}`, + ); + } case 'GenericObjectTypeAnnotation': return notStruct(wrapIntoNullableIfNeeded('NSDictionary *')); default: @@ -335,6 +346,17 @@ function getReturnObjCType( return wrapIntoNullableIfNeeded('NSNumber *'); case 'BooleanTypeAnnotation': return wrapIntoNullableIfNeeded('NSNumber *'); + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return wrapIntoNullableIfNeeded('NSNumber *'); + case 'StringTypeAnnotation': + return wrapIntoNullableIfNeeded('NSString *'); + default: + throw new Error( + `Unsupported enum return type for ${methodName}. Found: ${typeAnnotation.type}`, + ); + } case 'GenericObjectTypeAnnotation': return wrapIntoNullableIfNeeded('NSDictionary *'); default: @@ -380,6 +402,17 @@ function getReturnJSType( return 'BooleanKind'; case 'GenericObjectTypeAnnotation': return 'ObjectKind'; + case 'EnumDeclaration': + switch (typeAnnotation.memberType) { + case 'NumberTypeAnnotation': + return 'NumberKind'; + case 'StringTypeAnnotation': + return 'StringKind'; + default: + throw new Error( + `Unsupported return type for ${methodName}. Found: ${typeAnnotation.type}`, + ); + } default: (typeAnnotation.type: | 'EnumDeclaration' diff --git a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js index b9064512c97052..991d76f2dd7456 100644 --- a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js @@ -275,6 +275,42 @@ const SIMPLE_NATIVE_MODULES: SchemaType = { ], }, }, + { + name: 'getEnums', + optional: false, + typeAnnotation: { + type: 'FunctionTypeAnnotation', + returnTypeAnnotation: { + type: 'StringTypeAnnotation', + }, + params: [ + { + name: 'enumInt', + optional: false, + typeAnnotation: { + type: 'EnumDeclaration', + memberType: 'NumberTypeAnnotation', + }, + }, + { + name: 'enumFloat', + optional: false, + typeAnnotation: { + type: 'EnumDeclaration', + memberType: 'NumberTypeAnnotation', + }, + }, + { + name: 'enumString', + optional: false, + typeAnnotation: { + type: 'EnumDeclaration', + memberType: 'StringTypeAnnotation', + }, + }, + ], + }, + }, ], }, moduleNames: ['SampleTurboModule'], diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap index 2dd9ca5ce68405..7446e0559ce36e 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap @@ -337,6 +337,9 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithC static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise(rt, args[0].asBool()); } +static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { + return static_cast(&turboModule)->getEnums(rt, args[0].asNumber(), args[1].asNumber(), args[2].asString(rt)); +} NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared_ptr jsInvoker) : TurboModule(\\"SampleTurboModule\\", jsInvoker) { @@ -351,6 +354,7 @@ NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue}; methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback}; methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise}; + methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums}; } diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap index 461e34715e676e..63d09d5948b265 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap @@ -668,6 +668,7 @@ public: virtual jsi::Object getValue(jsi::Runtime &rt, double x, jsi::String y, jsi::Object z) = 0; virtual void getValueWithCallback(jsi::Runtime &rt, jsi::Function callback) = 0; virtual jsi::Value getValueWithPromise(jsi::Runtime &rt, bool error) = 0; + virtual jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) = 0; }; @@ -777,6 +778,14 @@ private: return bridging::callFromJs( rt, &T::getValueWithPromise, jsInvoker_, instance_, std::move(error)); } + jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) override { + static_assert( + bridging::getParameterCount(&T::getEnums) == 4, + \\"Expected getEnums(...) to have 4 parameters\\"); + + return bridging::callFromJs( + rt, &T::getEnums, jsInvoker_, instance_, std::move(enumInt), std::move(enumFloat), std::move(enumString)); + } private: T *instance_; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap index 07ab8ba9129c19..119fb989e7a102 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap @@ -933,6 +933,9 @@ namespace JS { - (void)getValueWithPromise:(BOOL)error resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject; +- (NSString *)getEnums:(double)enumInt + enumFloat:(double)enumFloat + enumString:(NSString *)enumString; - (facebook::react::ModuleConstants)constantsToExport; - (facebook::react::ModuleConstants)getConstants; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap index 3fec5218b9ffa3..4d41e02ccd04f8 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap @@ -376,6 +376,10 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo @ReactMethod @DoNotStrip public abstract void getValueWithPromise(boolean error, Promise promise); + + @ReactMethod(isBlockingSynchronousMethod = true) + @DoNotStrip + public abstract String getEnums(double enumInt, double enumFloat, String enumString); } ", } diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap index 9d771b73dddaa2..3fdf54878310b0 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap @@ -384,6 +384,11 @@ static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getVal return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getValueWithPromise\\", \\"(ZLcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); } +static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + static jmethodID cachedMethodId = nullptr; + return static_cast(turboModule).invokeJavaMethod(rt, StringKind, \\"getEnums\\", \\"(DDLjava/lang/String;)Ljava/lang/String;\\", args, count, cachedMethodId); +} + NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboModule::InitParams ¶ms) : JavaTurboModule(params) { methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants}; @@ -397,6 +402,7 @@ NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboMo methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getValue}; methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback}; methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; + methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; } std::shared_ptr simple_native_modules_ModuleProvider(const std::string &moduleName, const JavaTurboModule::InitParams ¶ms) { diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap index 3b2acb73c23930..d4b708e3d9023d 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap @@ -453,6 +453,10 @@ namespace facebook { return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); } + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getEnums\\", @selector(getEnums:enumFloat:enumString:), args, count); + } + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { return static_cast(turboModule).invokeObjCMethod(rt, ObjectKind, \\"getConstants\\", @selector(getConstants), args, count); } @@ -490,6 +494,9 @@ namespace facebook { methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; + methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; + + methodMap_[\\"getConstants\\"] = MethodMetadata {0, __hostFunction_NativeSampleTurboModuleSpecJSI_getConstants}; } diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js index 2d73c47301050d..50e4e18aa4c2c6 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js @@ -569,8 +569,29 @@ const IOS_ONLY_NATIVE_MODULE = ` import type {TurboModule} from '../RCTExport'; import * as TurboModuleRegistry from '../TurboModuleRegistry'; +export enum Quality { + SD, + HD, +} + +export enum Resolution { + Low = 720, + High = 1080, +} + +export enum Floppy { + LowDensity = 0.72, + HighDensity = 1.44, +} + +export enum StringOptions { + One = 'one', + Two = 'two', + Three = 'three', +} + export interface Spec extends TurboModule { - // no methods + +getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; } export default TurboModuleRegistry.getEnforcing('SampleTurboModuleIOS'); diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap index bf9ab323ea9d52..e73868dc872a3c 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap +++ b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap @@ -205,7 +205,52 @@ exports[`RN Codegen Flow Parser can generate fixture IOS_ONLY_NATIVE_MODULE 1`] 'type': 'NativeModule', 'aliases': {}, 'spec': { - 'properties': [] + 'properties': [ + { + 'name': 'getEnums', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'StringTypeAnnotation' + }, + 'params': [ + { + 'name': 'quality', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'StringTypeAnnotation' + } + }, + { + 'name': 'resolution', + 'optional': true, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'NumberTypeAnnotation' + } + }, + { + 'name': 'floppy', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'NumberTypeAnnotation' + } + }, + { + 'name': 'stringOptions', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'StringTypeAnnotation' + } + } + ] + } + } + ] }, 'moduleNames': [ 'SampleTurboModuleIOS' diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 914bb27128bcff..747f9162c2823b 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -252,7 +252,6 @@ function translateTypeAnnotation( default: { const maybeEumDeclaration = types[typeAnnotation.id.name]; if ( - cxxOnly && maybeEumDeclaration && maybeEumDeclaration.type === 'EnumDeclaration' ) { diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js index 61ad3642e6d232..02a2ae68b98a14 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js @@ -588,7 +588,30 @@ const IOS_ONLY_NATIVE_MODULE = ` import type {TurboModule} from 'react-native/Libraries/TurboModule/RCTExport'; import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry'; -export interface Spec extends TurboModule {} +export enum Quality { + SD, + HD, +} + +export enum Resolution { + Low = 720, + High = 1080, +} + +export enum Floppy { + LowDensity = 0.72, + HighDensity = 1.44, +} + +export enum StringOptions { + One = 'one', + Two = 'two', + Three = 'three', +} + +export interface Spec extends TurboModule { + readonly getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; +} export default TurboModuleRegistry.getEnforcing( 'SampleTurboModuleIOS', diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap index 03a0b11a41f1ab..6b4ff88450528a 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap @@ -203,7 +203,52 @@ exports[`RN Codegen TypeScript Parser can generate fixture IOS_ONLY_NATIVE_MODUL 'type': 'NativeModule', 'aliases': {}, 'spec': { - 'properties': [] + 'properties': [ + { + 'name': 'getEnums', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'StringTypeAnnotation' + }, + 'params': [ + { + 'name': 'quality', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'StringTypeAnnotation' + } + }, + { + 'name': 'resolution', + 'optional': true, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'NumberTypeAnnotation' + } + }, + { + 'name': 'floppy', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'NumberTypeAnnotation' + } + }, + { + 'name': 'stringOptions', + 'optional': false, + 'typeAnnotation': { + 'type': 'EnumDeclaration', + 'memberType': 'StringTypeAnnotation' + } + } + ] + } + } + ] }, 'moduleNames': [ 'SampleTurboModuleIOS' diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 3c26d7ab84d0df..097a505f8898a8 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -264,7 +264,6 @@ function translateTypeAnnotation( default: { const maybeEumDeclaration = types[typeAnnotation.typeName.name]; if ( - cxxOnly && maybeEumDeclaration && maybeEumDeclaration.type === 'TSEnumDeclaration' ) { From 68983b6631dae1e6ab14dd5be2f8e3ab55be7183 Mon Sep 17 00:00:00 2001 From: Marshall Roch Date: Tue, 25 Oct 2022 11:07:40 -0700 Subject: [PATCH 023/169] fix some flow reference-before-declaration errors Summary: The `typeof X` type annotation now respects the initialization state of `X`: if `X` hasn't been declared it will be an error to get its type. Changelog: [Internal] Reviewed By: jbrown215 Differential Revision: D40638870 fbshipit-source-id: 57459dec30ec5b87397365a709f2d846c87e378a --- .../rn-tester/js/examples/ScrollView/ScrollViewExample.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js b/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js index 47797bdbe2279e..33f467a492311b 100644 --- a/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js +++ b/packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js @@ -62,9 +62,9 @@ class EnableDisableList extends React.Component<{}, {scrollEnabled: boolean}> { let AppendingListItemCount = 6; class AppendingList extends React.Component< {}, - {items: Array>}, + {items: Array>>}, > { - state: {items: Array>} = { + state: {items: Array>>} = { items: [...Array(AppendingListItemCount)].map((_, ii) => ( )), From af6aafff90c4d40abfe160c4cfc8e1ae8fa0d956 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 25 Oct 2022 11:29:40 -0700 Subject: [PATCH 024/169] Deprecate react.gradle Summary: With RNGP we can now deprecate react.gradle I'll create a page on the website to describe what is the migration strategy here, but users should be fine by just replacing `apply from react.gradle` with `apply plugin: com.facebook.react`. Changelog: [Android] [Removed] - Deprecate react.gradle Reviewed By: cipolleschi Differential Revision: D40675546 fbshipit-source-id: a50348791d669df1ed9e0470a6664e291c1a4584 --- react.gradle | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/react.gradle b/react.gradle index 4cba94bd95dd82..da5505975a0c78 100644 --- a/react.gradle +++ b/react.gradle @@ -7,6 +7,24 @@ import org.apache.tools.ant.taskdefs.condition.Os import org.gradle.internal.jvm.Jvm +import org.gradle.internal.logging.text.StyledTextOutput +import org.gradle.internal.logging.text.StyledTextOutputFactory +import org.gradle.internal.logging.text.StyledTextOutput.Style + +def out = services.get(StyledTextOutputFactory).create("ouput") +out.style(Style.Info) + .text('##############################') + .text('\n\n') + .text('Using react.gradle in your project is deprecated! You should move to "apply plugin: com.facebook.react"') + .text('\n') + .text('react.gradle is going to be removed in a future React Native project and your project will not build anymore.') + .text('\n') + .text('You can use the template as a reference:') + .text('\n') + .text('https://github.com/facebook/react-native/blob/main/template/android/app/build.gradle') + .text('\n\n') + .text('##############################') + .println('') def config = project.hasProperty("react") ? project.react : [:]; From 3b0c65583d0703a0efed0f7f77981b113c08b43a Mon Sep 17 00:00:00 2001 From: Ethan Zhu Date: Tue, 25 Oct 2022 11:45:17 -0700 Subject: [PATCH 025/169] Suppress `useNativeDriver` is not supported warning Summary: Changelog: [Internal] - Suppress unnecessary warning for native module in jest tests Reviewed By: yungsters Differential Revision: D40653968 fbshipit-source-id: ff3d894c36a18943a7b3fd061f52b65685a481a6 --- Libraries/Animated/NativeAnimatedHelper.js | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/Libraries/Animated/NativeAnimatedHelper.js b/Libraries/Animated/NativeAnimatedHelper.js index a9ad27424dc294..e0c91788c4b830 100644 --- a/Libraries/Animated/NativeAnimatedHelper.js +++ b/Libraries/Animated/NativeAnimatedHelper.js @@ -527,15 +527,17 @@ function shouldUseNativeDriver( } if (config.useNativeDriver === true && !NativeAnimatedModule) { - if (!_warnedMissingNativeAnimated) { - console.warn( - 'Animated: `useNativeDriver` is not supported because the native ' + - 'animated module is missing. Falling back to JS-based animation. To ' + - 'resolve this, add `RCTAnimation` module to this app, or remove ' + - '`useNativeDriver`. ' + - 'Make sure to run `bundle exec pod install` first. Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md', - ); - _warnedMissingNativeAnimated = true; + if (process.env.NODE_ENV !== 'test') { + if (!_warnedMissingNativeAnimated) { + console.warn( + 'Animated: `useNativeDriver` is not supported because the native ' + + 'animated module is missing. Falling back to JS-based animation. To ' + + 'resolve this, add `RCTAnimation` module to this app, or remove ' + + '`useNativeDriver`. ' + + 'Make sure to run `bundle exec pod install` first. Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md', + ); + _warnedMissingNativeAnimated = true; + } } return false; } From 1d6b732496f396217e4dcb1c5861713b8d9cbcc7 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Tue, 25 Oct 2022 12:32:30 -0700 Subject: [PATCH 026/169] react-native bridging > Add support for std::set Summary: There are use cases in which we want to pass a set of unique elements from C++ to JS and back. We can do this simple by re-using a plain JS array for these purposes. Changelog: [Internal][Added] react-native bridging > Add support for std::set Reviewed By: cipolleschi Differential Revision: D40668244 fbshipit-source-id: d06603440569e5f760c2859a54cf6e4232c7d97a --- ReactCommon/react/bridging/Array.h | 19 +++++++++++++++++++ .../react/bridging/tests/BridgingTest.cpp | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/ReactCommon/react/bridging/Array.h b/ReactCommon/react/bridging/Array.h index 330e2e1a4f8b6f..af36c392d06af7 100644 --- a/ReactCommon/react/bridging/Array.h +++ b/ReactCommon/react/bridging/Array.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -105,4 +106,22 @@ struct Bridging> } }; +template +struct Bridging> : array_detail::BridgingDynamic> { + static std::set fromJs( + facebook::jsi::Runtime &rt, + const jsi::Array &array, + const std::shared_ptr &jsInvoker) { + size_t length = array.length(rt); + + std::set set; + for (size_t i = 0; i < length; i++) { + set.insert( + bridging::fromJs(rt, array.getValueAtIndex(rt, i), jsInvoker)); + } + + return set; + } +}; + } // namespace facebook::react diff --git a/ReactCommon/react/bridging/tests/BridgingTest.cpp b/ReactCommon/react/bridging/tests/BridgingTest.cpp index 0e2a99d38f3b72..a1f50fec988833 100644 --- a/ReactCommon/react/bridging/tests/BridgingTest.cpp +++ b/ReactCommon/react/bridging/tests/BridgingTest.cpp @@ -431,6 +431,8 @@ TEST_F(BridgingTest, supportTest) { EXPECT_TRUE((bridging::supportsFromJs)); EXPECT_TRUE((bridging::supportsFromJs)); EXPECT_TRUE((bridging::supportsFromJs)); + EXPECT_TRUE((bridging::supportsFromJs, jsi::Array>)); + EXPECT_TRUE((bridging::supportsFromJs, jsi::Array &>)); EXPECT_TRUE((bridging::supportsFromJs, jsi::Array>)); EXPECT_TRUE((bridging::supportsFromJs, jsi::Array &>)); EXPECT_TRUE( @@ -453,6 +455,8 @@ TEST_F(BridgingTest, supportTest) { EXPECT_FALSE((bridging::supportsFromJs)); EXPECT_FALSE((bridging::supportsFromJs)); EXPECT_FALSE((bridging::supportsFromJs)); + EXPECT_FALSE((bridging::supportsFromJs, jsi::String>)); + EXPECT_FALSE((bridging::supportsFromJs, jsi::String &>)); EXPECT_FALSE((bridging::supportsFromJs, jsi::String>)); EXPECT_FALSE((bridging::supportsFromJs, jsi::String &>)); @@ -494,6 +498,8 @@ TEST_F(BridgingTest, supportTest) { EXPECT_TRUE((bridging::supportsToJs)); EXPECT_TRUE((bridging::supportsToJs)); EXPECT_TRUE((bridging::supportsToJs)); + EXPECT_TRUE((bridging::supportsToJs>)); + EXPECT_TRUE((bridging::supportsToJs, jsi::Array>)); EXPECT_TRUE((bridging::supportsToJs>)); EXPECT_TRUE((bridging::supportsToJs, jsi::Array>)); EXPECT_TRUE((bridging::supportsToJs>)); From c96c76eb9107ea92ff6dc2dcec114f3bd57102bd Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 25 Oct 2022 13:13:14 -0700 Subject: [PATCH 027/169] Update the template to use RNGP (#35075) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35075 This diff updates the New App template for Android to use the React Native Gradle Plugin. With this we can: 1. Get rid of all the C++ code. 2. Remove a lot of New Architecture logic in the build.gradle 3. Reuse the prebuilts of React Native/Hermes via prefab Changelog: [Android] [Changed] - Update the template to use RNGP Reviewed By: cipolleschi Differential Revision: D40673732 fbshipit-source-id: 70935248993d1e24904c982e75f12ad580faa9d8 --- .circleci/config.yml | 13 +- ReactAndroid/publish.gradle | 5 + build.gradle.kts | 10 +- package.json | 2 +- .../react-native-gradle-plugin/package.json | 2 +- .../react/utils/NdkConfiguratorUtils.kt | 137 ++++++++++-------- scripts/release-utils.js | 15 +- template/android/app/build.gradle | 71 +-------- .../android/app/src/main/jni/CMakeLists.txt | 7 - template/android/app/src/main/jni/OnLoad.cpp | 50 ------- template/android/build.gradle | 9 +- template/android/settings.gradle | 7 - yarn.lock | 5 - 13 files changed, 107 insertions(+), 226 deletions(-) delete mode 100644 template/android/app/src/main/jni/CMakeLists.txt delete mode 100644 template/android/app/src/main/jni/OnLoad.cpp diff --git a/.circleci/config.yml b/.circleci/config.yml index 49c899f1571d18..e45bc414d7d8f1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -805,7 +805,9 @@ jobs: - run: name: Build the template application for << parameters.flavor >> with New Architecture set to << parameters.newarchitecture >>, and using the << parameters.jsengine>> JS engine. - command: cd /tmp/$PROJECT_NAME/android/ && ./gradlew assemble<< parameters.flavor >> -PnewArchEnabled=<< parameters.newarchitecture >> + command: | + cd /tmp/$PROJECT_NAME/android/ + ./gradlew assemble<< parameters.flavor >> -PnewArchEnabled=<< parameters.newarchitecture >> -PREACT_NATIVE_MAVEN_LOCAL_REPO=/root/react-native/maven-local # ------------------------- # JOBS: Test iOS Template @@ -1443,6 +1445,15 @@ jobs: command: zip -r /tmp/hermes-native-symbols.zip ~/react-native/ReactAndroid/hermes-engine/build/intermediates/cmake/ - store_artifacts: path: /tmp/hermes-native-symbols.zip + - run: + name: Zip Maven Artifacts from /tmp/maven-local + command: zip -r /tmp/maven-local.zip /tmp/maven-local + - store_artifacts: + path: /tmp/maven-local.zip + - persist_to_workspace: + root: /tmp + paths: + - maven-local # START: Commitlies # Provide a react-native package for this commit as a Circle CI release artifact. diff --git a/ReactAndroid/publish.gradle b/ReactAndroid/publish.gradle index b2f25b38cbc106..637a0074663be8 100644 --- a/ReactAndroid/publish.gradle +++ b/ReactAndroid/publish.gradle @@ -14,6 +14,7 @@ def signingPwd = findProperty("SIGNING_PWD") def reactAndroidProjectDir = project(':ReactAndroid').projectDir def androidOutputUrl = "file://${reactAndroidProjectDir}/../android" +def mavenTempLocalUrl = "file:///tmp/maven-local" publishing { publications { @@ -68,6 +69,10 @@ publishing { name = "npm" url = androidOutputUrl } + maven { + name = "mavenTempLocal" + url = mavenTempLocalUrl + } } if (signingKey && signingPwd) { diff --git a/build.gradle.kts b/build.gradle.kts index 10a5f82e65f9c0..44ad75737b158f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -115,11 +115,11 @@ tasks.register("publishAllInsideNpmPackage") { dependsOn(":ReactAndroid:hermes-engine:installArchives") } -tasks.register("publishAllToMavenLocal") { - description = "Publish all the artifacts to be available inside Maven Local." - dependsOn(":ReactAndroid:publishToMavenLocal") - dependsOn(":ReactAndroid:external-artifacts:publishToMavenLocal") - dependsOn(":ReactAndroid:hermes-engine:publishToMavenLocal") +tasks.register("publishAllToMavenTempLocal") { + description = "Publish all the artifacts to be available inside a Maven Local repository on /tmp." + dependsOn(":ReactAndroid:publishAllPublicationsToMavenTempLocalRepository") + // We don't publish the external-artifacts to Maven Local as CircleCI is using it via workspace. + dependsOn(":ReactAndroid:hermes-engine:publishAllPublicationsToMavenTempLocalRepository") } tasks.register("publishAllToSonatype") { diff --git a/package.json b/package.json index a56cc7d09200ae..4115a071bc472e 100644 --- a/package.json +++ b/package.json @@ -131,7 +131,7 @@ "pretty-format": "^26.5.2", "promise": "^8.2.0", "react-devtools-core": "^4.26.1", - "react-native-gradle-plugin": "0.71.4", + "react-native-gradle-plugin": "^0.71.6", "react-refresh": "^0.4.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 1c2e37efa949bd..89f4f18111bdbc 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "react-native-gradle-plugin", - "version": "0.71.5", + "version": "0.71.6", "description": "⚛️ Gradle Plugin for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", "repository": { diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt index df09d4efcd35fa..9bec0e3bc2a9c2 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt @@ -16,75 +16,84 @@ import org.gradle.api.Project internal object NdkConfiguratorUtils { @Suppress("UnstableApiUsage") fun configureReactNativeNdk(project: Project, extension: ReactExtension) { - if (!project.isNewArchEnabled) { - return - } project.pluginManager.withPlugin("com.android.application") { project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> - // We enable prefab so users can consume .so/headers from ReactAndroid and hermes-engine - // .aar - ext.buildFeatures.prefab = true + if (!project.isNewArchEnabled) { + // For Old Arch, we set a pickFirst only on libraries that we know are + // clashing with our direct dependencies (FBJNI, Flipper and Hermes). + ext.packagingOptions.jniLibs.pickFirsts.addAll( + listOf( + "**/libfbjni.so", + "**/libc++_shared.so", + )) + } else { + // We enable prefab so users can consume .so/headers from ReactAndroid and hermes-engine + // .aar + ext.buildFeatures.prefab = true - // We set some packagingOptions { pickFirst ... } for our users for libraries we own. - ext.packagingOptions.jniLibs.pickFirsts.addAll( - listOf( - // Hermes & JSC are provided by AAR dependencies we pre-bundle. - "**/libhermes.so", - "**/libjsc.so", - // This is the .so provided by FBJNI via prefab - "**/libfbjni.so", - // Those are prefab libraries we distribute via ReactAndroid - // Due to a bug in AGP, they fire a warning on console as both the JNI - // and the prefab .so files gets considered. See more on: - "**/libfabricjni.so", - "**/libfolly_runtime.so", - "**/libglog.so", - "**/libjsi.so", - "**/libreact_codegen_rncore.so", - "**/libreact_debug.so", - "**/libreact_nativemodule_core.so", - "**/libreact_newarchdefaults.so", - "**/libreact_render_componentregistry.so", - "**/libreact_render_core.so", - "**/libreact_render_debug.so", - "**/libreact_render_graphics.so", - "**/libreact_render_mapbuffer.so", - "**/librrc_view.so", - "**/libruntimeexecutor.so", - "**/libturbomodulejsijni.so", - "**/libyoga.so", - // AGP will give priority of libc++_shared coming from App modules. - "**/libc++_shared.so", - )) + // We set some packagingOptions { pickFirst ... } for our users for libraries we own. + ext.packagingOptions.jniLibs.pickFirsts.addAll( + listOf( + // Hermes & JSC are provided by AAR dependencies we pre-bundle. + "**/libhermes.so", + "**/libjsc.so", + // This is the .so provided by FBJNI via prefab + "**/libfbjni.so", + // Those are prefab libraries we distribute via ReactAndroid + // Due to a bug in AGP, they fire a warning on console as both the JNI + // and the prefab .so files gets considered. See more on: + "**/libfabricjni.so", + "**/libfolly_runtime.so", + "**/libglog.so", + "**/libjsi.so", + "**/libreact_codegen_rncore.so", + "**/libreact_debug.so", + "**/libreact_nativemodule_core.so", + "**/libreact_newarchdefaults.so", + "**/libreact_render_componentregistry.so", + "**/libreact_render_core.so", + "**/libreact_render_debug.so", + "**/libreact_render_graphics.so", + "**/libreact_render_imagemanager.so", + "**/libreact_render_mapbuffer.so", + "**/librrc_image.so", + "**/librrc_view.so", + "**/libruntimeexecutor.so", + "**/libturbomodulejsijni.so", + "**/libyoga.so", + // AGP will give priority of libc++_shared coming from App modules. + "**/libc++_shared.so", + )) - // If the user has not provided a CmakeLists.txt path, let's provide - // the default one from the framework - if (ext.externalNativeBuild.cmake.path == null) { - ext.externalNativeBuild.cmake.path = - File( - extension.reactNativeDir.get().asFile, - "cmake-utils/default-app-setup/CMakeLists.txt") - } + // If the user has not provided a CmakeLists.txt path, let's provide + // the default one from the framework + if (ext.externalNativeBuild.cmake.path == null) { + ext.externalNativeBuild.cmake.path = + File( + extension.reactNativeDir.get().asFile, + "ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt") + } - // Parameters should be provided in an additive manner (do not override what - // the user provided, but allow for sensible defaults). - val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments - if ("-DGENERATED_SRC_DIR" !in cmakeArgs) { - cmakeArgs.add("-DGENERATED_SRC_DIR=${File(project.buildDir, "generated/source")}") - } - if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") - } - if ("-DREACT_ANDROID_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") - } - if ("-DREACT_ANDROID_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_BUILD_DIR=${extension.reactNativeDir.file("ReactAndroid/build").get().asFile}") - } - if ("-DANDROID_STL" !in cmakeArgs) { - cmakeArgs.add("-DANDROID_STL=c++_shared") + // Parameters should be provided in an additive manner (do not override what + // the user provided, but allow for sensible defaults). + val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments + if ("-DGENERATED_SRC_DIR" !in cmakeArgs) { + cmakeArgs.add("-DGENERATED_SRC_DIR=${File(project.buildDir, "generated/source")}") + } + if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { + cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") + } + if ("-DREACT_ANDROID_DIR" !in cmakeArgs) { + cmakeArgs.add( + "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") + } + if ("-DREACT_ANDROID_BUILD_DIR" !in cmakeArgs) { + cmakeArgs.add( + "-DREACT_ANDROID_BUILD_DIR=${extension.reactNativeDir.file("ReactAndroid/build").get().asFile}") + } + if ("-DANDROID_STL" !in cmakeArgs) { + cmakeArgs.add("-DANDROID_STL=c++_shared") + } } } } diff --git a/scripts/release-utils.js b/scripts/release-utils.js index f095530a957c93..801afc93852f9d 100644 --- a/scripts/release-utils.js +++ b/scripts/release-utils.js @@ -33,15 +33,8 @@ function saveFilesToRestore(tmpPublishingFolder) { function generateAndroidArtifacts(releaseVersion, tmpPublishingFolder) { // -------- Generating Android Artifacts - env.REACT_NATIVE_SKIP_PREFAB = true; - if (exec('./gradlew :ReactAndroid:installArchives').code) { - echo('Could not generate artifacts'); - exit(1); - } - - // -------- Generating the Hermes Engine Artifacts - env.REACT_NATIVE_HERMES_SKIP_PREFAB = true; - if (exec('./gradlew :ReactAndroid:hermes-engine:installArchives').code) { + echo('Generating Android artifacts inside /tmp/maven-local'); + if (exec('./gradlew publishAllToMavenTempLocal').code) { echo('Could not generate artifacts'); exit(1); } @@ -63,12 +56,12 @@ function generateAndroidArtifacts(releaseVersion, tmpPublishingFolder) { if ( !test( '-e', - `./android/com/facebook/react/react-native/${releaseVersion}/${name}`, + `/tmp/maven-local/com/facebook/react/react-native/${releaseVersion}/${name}`, ) ) { echo( `Failing as expected file: \n\ - android/com/facebook/react/react-native/${releaseVersion}/${name}\n\ + /tmp/maven-local/com/facebook/react/react-native/${releaseVersion}/${name}\n\ was not correctly generated.`, ); exit(1); diff --git a/template/android/app/build.gradle b/template/android/app/build.gradle index 3a23b468c2d9f4..1a56feaba4970a 100644 --- a/template/android/app/build.gradle +++ b/template/android/app/build.gradle @@ -1,7 +1,7 @@ apply plugin: "com.android.application" +apply plugin: "com.facebook.react" import com.android.build.OutputFile -import org.apache.tools.ant.taskdefs.condition.Os /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets @@ -82,8 +82,6 @@ project.ext.react = [ enableHermes: true, // clean and rebuild if changing ] -apply from: "../../node_modules/react-native/react.gradle" - /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices @@ -140,40 +138,6 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" - buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() - - if (isNewArchitectureEnabled()) { - // We configure the CMake build only if you decide to opt-in for the New Architecture. - externalNativeBuild { - cmake { - arguments "-DPROJECT_BUILD_DIR=$buildDir", - "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid", - "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build", - "-DANDROID_STL=c++_shared" - } - } - if (!enableSeparateBuildPerCPUArchitecture) { - ndk { - abiFilters (*reactNativeArchitectures()) - } - } - } - } - - if (isNewArchitectureEnabled()) { - // We configure the CMake build only if you decide to opt-in for the New Architecture. - externalNativeBuild { - cmake { - path "$projectDir/src/main/jni/CMakeLists.txt" - } - } - buildFeatures { - prefab true - } - } - packagingOptions { - pickFirst '**/libc++_shared.so' - pickFirst '**/libfbjni.so' } splits { @@ -225,10 +189,10 @@ android { dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) - //noinspection GradleDynamicVersion - implementation "com.facebook.react:react-native:+" // From node_modules + // The version of react-native is set by the React Native Gradle Plugin + implementation("com.facebook.react:react-native") - implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" + implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0") debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { @@ -237,35 +201,10 @@ dependencies { debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") if (enableHermes) { - //noinspection GradleDynamicVersion - implementation("com.facebook.react:hermes-engine:+") // From node_modules + implementation("com.facebook.react:hermes-engine") } else { implementation jscFlavor } } -if (isNewArchitectureEnabled()) { - // If new architecture is enabled, we let you build RN from source - // Otherwise we fallback to a prebuilt .aar bundled in the NPM package. - // This will be applied to all the imported transitive dependency. - configurations.all { - resolutionStrategy.dependencySubstitution { - substitute(module("com.facebook.react:react-native")) - .using(project(":ReactAndroid")) - .because("On New Architecture we're building React Native from source") - substitute(module("com.facebook.react:hermes-engine")) - .using(project(":ReactAndroid:hermes-engine")) - .because("On New Architecture we're building Hermes from source") - } - } -} - apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) - -def isNewArchitectureEnabled() { - // To opt-in for the New Architecture, you can either: - // - Set `newArchEnabled` to true inside the `gradle.properties` file - // - Invoke gradle with `-newArchEnabled=true` - // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true` - return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" -} diff --git a/template/android/app/src/main/jni/CMakeLists.txt b/template/android/app/src/main/jni/CMakeLists.txt deleted file mode 100644 index 25c9c208afbcd4..00000000000000 --- a/template/android/app/src/main/jni/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.13) - -# Define the library name here. -project(appmodules) - -# This file includes all the necessary to let you build your application with the New Architecture. -include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake) diff --git a/template/android/app/src/main/jni/OnLoad.cpp b/template/android/app/src/main/jni/OnLoad.cpp deleted file mode 100644 index 117fad7d6454a6..00000000000000 --- a/template/android/app/src/main/jni/OnLoad.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include -#include -#include -#include - -namespace facebook { -namespace react { - -void registerComponents( - std::shared_ptr registry) { - // Custom Fabric Components go here. You can register custom - // components coming from your App or from 3rd party libraries here. - // - // providerRegistry->add(concreteComponentDescriptorProvider< - // AocViewerComponentDescriptor>()); - - // By default we just use the components autolinked by RN CLI - rncli_registerProviders(registry); -} - -std::shared_ptr provideModules( - const std::string &name, - const JavaTurboModule::InitParams ¶ms) { - // Here you can provide your own module provider for TurboModules coming from - // either your application or from external libraries. The approach to follow - // is similar to the following (for a library called `samplelibrary`): - // - // auto module = samplelibrary_ModuleProvider(moduleName, params); - // if (module != nullptr) { - // return module; - // } - // return rncore_ModuleProvider(moduleName, params); - - // By default we just use the module providers autolinked by RN CLI - return rncli_ModuleProvider(name, params); -} - -} // namespace react -} // namespace facebook - -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) { - return facebook::jni::initialize(vm, [] { - facebook::react::DefaultTurboModuleManagerDelegate:: - moduleProvidersFromEntryPoint = &facebook::react::provideModules; - facebook::react::DefaultComponentsRegistry:: - registerComponentDescriptorsFromEntryPoint = - &facebook::react::registerComponents; - }); -} diff --git a/template/android/build.gradle b/template/android/build.gradle index bfa9a2b429203b..a893c5e2e8f3c9 100644 --- a/template/android/build.gradle +++ b/template/android/build.gradle @@ -17,7 +17,6 @@ buildscript { dependencies { classpath("com.android.tools.build:gradle:7.3.0") classpath("com.facebook.react:react-native-gradle-plugin") - classpath("de.undercouch:gradle-download-task:5.0.1") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } @@ -33,13 +32,7 @@ allprojects { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } - mavenCentral { - // We don't want to fetch react-native from Maven Central as there are - // older versions over there. - content { - excludeGroup "com.facebook.react" - } - } + mavenCentral() google() maven { url 'https://www.jitpack.io' } } diff --git a/template/android/settings.gradle b/template/android/settings.gradle index bd838b9c306d59..ab284c3a6bd22f 100644 --- a/template/android/settings.gradle +++ b/template/android/settings.gradle @@ -2,10 +2,3 @@ rootProject.name = 'HelloWorld' apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' includeBuild('../node_modules/react-native-gradle-plugin') - -if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { - include(":ReactAndroid") - project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') - include(":ReactAndroid:hermes-engine") - project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine') -} diff --git a/yarn.lock b/yarn.lock index 5173fb435f26bc..740f4c15920f8f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7960,11 +7960,6 @@ react-is@^17.0.1: resolved "https://registry.yarnpkg.com/react-is/-/react-is-17.0.2.tgz#e691d4a8e9c789365655539ab372762b0efb54f0" integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w== -react-native-gradle-plugin@0.71.4: - version "0.71.4" - resolved "https://registry.yarnpkg.com/react-native-gradle-plugin/-/react-native-gradle-plugin-0.71.4.tgz#dd000c1539e0ce465237637d3e16fe619cd84467" - integrity sha512-5izzWXIlr5DL5+cx3a6oSA4cgSCw9Kv7WQjHqLxV2I1fSfzjzEdYTaDfrNjdcy71BHeeUB6BEyl70yXpjkCkdA== - react-refresh@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.4.0.tgz#d421f9bd65e0e4b9822a399f14ac56bda9c92292" From 8b8a5e06ce68ff75efaf767208ad100e6ea75324 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Tue, 25 Oct 2022 13:20:03 -0700 Subject: [PATCH 028/169] Bump the Android Docker image to 6.0 (for NDK 23) (#35079) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35079 This bumps the Docker image for React Native Android to 6.0 shipping the NDK 23 with it, finalizing all the work needed to support NDK 23. Changelog: [Internal] [Changed] - Bump the Android Docker image to 6.0 (for NDK 23) Reviewed By: cipolleschi Differential Revision: D40675449 fbshipit-source-id: 5fb53080ce796263cd592dbc489743e6295060ba --- .circleci/Dockerfiles/Dockerfile.android | 2 +- .circleci/config.yml | 10 +--------- package.json | 2 +- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/.circleci/Dockerfiles/Dockerfile.android b/.circleci/Dockerfiles/Dockerfile.android index 74e062c88cc5c8..ab2752fdac9439 100644 --- a/.circleci/Dockerfiles/Dockerfile.android +++ b/.circleci/Dockerfiles/Dockerfile.android @@ -14,7 +14,7 @@ # and build a Android application that can be used to run the # tests specified in the scripts/ directory. # -FROM reactnativecommunity/react-native-android:5.4 +FROM reactnativecommunity/react-native-android:6.0 LABEL Description="React Native Android Test Image" LABEL maintainer="Héctor Ramos " diff --git a/.circleci/config.yml b/.circleci/config.yml index e45bc414d7d8f1..b3ee733c859655 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -102,7 +102,7 @@ executors: reactnativeandroid: <<: *defaults docker: - - image: reactnativecommunity/react-native-android:5.4 + - image: reactnativecommunity/react-native-android:6.0 resource_class: "xlarge" environment: - TERM: "dumb" @@ -669,10 +669,6 @@ jobs: buck build ReactAndroid/src/main/java/com/facebook/react buck build ReactAndroid/src/main/java/com/facebook/react/shell - - run: - name: Validate Android Test Environment - command: ./scripts/validate-android-test-env.sh - - run: name: Run Tests - Android Unit Tests with Buck command: buck test ReactAndroid/src/test/... --config build.threads=$BUILD_THREADS --xml ./reports/buck/all-results-raw.xml @@ -718,10 +714,6 @@ jobs: - setup_artifacts - run_yarn - - run: - name: Validate Android SDK Install - command: ./scripts/validate-android-sdk.sh - # Starting emulator in advance as it takes some time to boot. - run: name: Create Android Virtual Device diff --git a/package.json b/package.json index 4115a071bc472e..c0c3eb4cd0d845 100644 --- a/package.json +++ b/package.json @@ -86,7 +86,7 @@ "prettier": "prettier --write \"./**/*.{js,md,yml,ts,tsx}\"", "format-check": "prettier --list-different \"./**/*.{js,md,yml,ts,tsx}\"", "update-lock": "npx yarn-deduplicate", - "docker-setup-android": "docker pull reactnativecommunity/react-native-android:5.2", + "docker-setup-android": "docker pull reactnativecommunity/react-native-android:6.0", "docker-build-android": "docker build -t reactnativeci/android -f .circleci/Dockerfiles/Dockerfile.android .", "test-android-run-instrumentation": "docker run --cap-add=SYS_ADMIN -it reactnativeci/android bash .circleci/Dockerfiles/scripts/run-android-docker-instrumentation-tests.sh", "test-android-run-unit": "docker run --cap-add=SYS_ADMIN -it reactnativeci/android bash .circleci/Dockerfiles/scripts/run-android-docker-unit-tests.sh", From fd917481463bf6ba9c4e14919250aec2ffad2c2f Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Tue, 25 Oct 2022 14:15:42 -0700 Subject: [PATCH 029/169] Fix deadlock in RCTLoggingTests Summary: Some portions of continuous test runs RNTesterIntegrationTests will hang for an hour when running in Sandcastle without outputting anything. Locally debugging, I see a deadlock waiting on a semaphore, where the test assumed an extraneous symbolication warning would be fired. This change makes it so that we only look for the extraneous messages if we haven't already seen the target message, since they do not seem to show up in local testing. I also added assertions per semaphore that the log statement is propagated within a still very gracious 10 seconds. This means we still can see what tests are running/failing if this test has issues, instead of a deadlocked test runner with no output. Changelog: [Internal][Fixed] - Fix deadlock in RCTLoggingTests Reviewed By: cipolleschi Differential Revision: D40667275 fbshipit-source-id: ab78f3c2ef47e2fd740b1dad2a65912e9542301d --- .../RCTLoggingTests.m | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m b/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m index cb151181c92fff..7cf83c2a0168e5 100644 --- a/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m +++ b/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m @@ -11,6 +11,9 @@ #import #import +// Time to wait for an expected log statement to show before failing the test +const int64_t LOGGER_TIMEOUT = 10 * NSEC_PER_SEC; + @interface RCTLoggingTests : XCTestCase @end @@ -71,41 +74,50 @@ - (void)tearDown - (void)testLogging { + intptr_t waitRet = 0; + // First queue the marker and spin until it happens to be logged. // This is to ensure we skip all of the other messages, that were logged earlier. NSString *const LogMarker = @"===LOG_MARKER==="; [_bridge enqueueJSCall:@"LoggingTestModule.logToConsole" args:@[ LogMarker ]]; + do { - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); - } while (![_lastLogMessage isEqualToString:LogMarker]); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for log marker"); + } while (waitRet == 0 && ![_lastLogMessage isEqualToString:LogMarker]); [_bridge enqueueJSCall:@"LoggingTestModule.logToConsole" args:@[ @"Invoking console.log" ]]; - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for logToConsole"); XCTAssertEqual(_lastLogLevel, RCTLogLevelInfo); XCTAssertEqual(_lastLogSource, RCTLogSourceJavaScript); XCTAssertEqualObjects(_lastLogMessage, @"Invoking console.log"); [_bridge enqueueJSCall:@"LoggingTestModule.warning" args:@[ @"Generating warning" ]]; - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for warning"); XCTAssertEqual(_lastLogLevel, RCTLogLevelWarning); XCTAssertEqual(_lastLogSource, RCTLogSourceJavaScript); XCTAssertEqualObjects(_lastLogMessage, @"Generating warning"); [_bridge enqueueJSCall:@"LoggingTestModule.invariant" args:@[ @"Invariant failed" ]]; - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for invariant"); XCTAssertEqual(_lastLogLevel, RCTLogLevelError); XCTAssertEqual(_lastLogSource, RCTLogSourceJavaScript); XCTAssertTrue([_lastLogMessage containsString:@"Invariant Violation: Invariant failed"]); [_bridge enqueueJSCall:@"LoggingTestModule.logErrorToConsole" args:@[ @"Invoking console.error" ]]; - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for logErrorToConsole"); - // For local bundles, we'll first get a warning about symbolication - if ([_bridge.bundleURL isFileURL]) { - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + // For local bundles, we may first get a warning about symbolication + if (![_lastLogMessage isEqualToString:@"Invoking console.error"]) { + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for logErrorToConsole #2"); } XCTAssertEqual(_lastLogLevel, RCTLogLevelError); @@ -113,11 +125,13 @@ - (void)testLogging XCTAssertEqualObjects(_lastLogMessage, @"Invoking console.error"); [_bridge enqueueJSCall:@"LoggingTestModule.throwError" args:@[ @"Throwing an error" ]]; - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for throwError"); - // For local bundles, we'll first get a warning about symbolication - if ([_bridge.bundleURL isFileURL]) { - dispatch_semaphore_wait(_logSem, DISPATCH_TIME_FOREVER); + // For local bundles, we may first get a warning about symbolication + if (![_lastLogMessage isEqualToString:@"Error: Throwing an error"]) { + waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); + XCTAssertEqual(waitRet, 0, @"Timed out waiting for throwError #2"); } XCTAssertEqual(_lastLogLevel, RCTLogLevelError); From 02e4fcd825fecc78ce2c93a1e3a9ba2b232c573b Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Tue, 25 Oct 2022 14:40:08 -0700 Subject: [PATCH 030/169] Add enum example to Android/iOS rn-tester TurboModule Summary: Add enum example to Android/iOS rn-tester TurboModule Changelog: [General][Added] - Add enum example to Android/iOS rn-tester TurboModule Reviewed By: javache Differential Revision: D40619020 fbshipit-source-id: a113c5c78bcff3275e80d11bce8d0e6421b0b97d --- .flowconfig | 1 + .flowconfig.android | 1 + BUCK | 1 + .../samples/NativeSampleTurboModule.js | 6 ++++++ .../NativeSampleTurboCxxModuleSpecJSI.cpp | 12 ++++++++++++ .../NativeSampleTurboCxxModuleSpecJSI.h | 1 + .../samples/ReactCommon/SampleTurboCxxModule.cpp | 4 ++++ .../samples/ReactCommon/SampleTurboCxxModule.h | 1 + .../android/NativeSampleTurboModuleSpec.java | 3 +++ .../android/ReactCommon/SampleTurboModuleSpec.cpp | 15 +++++++++++++++ .../platform/android/SampleTurboModule.java | 8 ++++++++ .../platform/ios/RCTNativeSampleTurboModuleSpec.h | 1 + .../ios/RCTNativeSampleTurboModuleSpec.mm | 11 +++++++++++ .../samples/platform/ios/RCTSampleTurboModule.mm | 5 +++++ .../ios/SampleTurboCxxModuleLegacyImpl.cpp | 10 ++++++++++ .../platform/ios/SampleTurboCxxModuleLegacyImpl.h | 1 + package.json | 1 + .../TurboModule/SampleTurboModuleExample.js | 7 +++++++ yarn.lock | 5 +++++ 19 files changed, 94 insertions(+) diff --git a/.flowconfig b/.flowconfig index 50a3f7adab9a29..34038826acc5d1 100644 --- a/.flowconfig +++ b/.flowconfig @@ -30,6 +30,7 @@ flow/ [options] emoji=true +enums=true exact_by_default=true exact_empty_objects=true diff --git a/.flowconfig.android b/.flowconfig.android index fc7429f32705d4..b084ed5e33ae9b 100644 --- a/.flowconfig.android +++ b/.flowconfig.android @@ -30,6 +30,7 @@ flow/ [options] emoji=true +enums=true exact_by_default=true exact_empty_objects=true diff --git a/BUCK b/BUCK index e1b1e68844cbd7..1f6e1b80d64dcf 100644 --- a/BUCK +++ b/BUCK @@ -743,6 +743,7 @@ rn_library( "//xplat/js:node_modules__anser", "//xplat/js:node_modules__base64_19js", "//xplat/js:node_modules__event_19target_19shim", + "//xplat/js:node_modules__flow_19enums_19runtime", "//xplat/js:node_modules__invariant", "//xplat/js:node_modules__memoize_19one", "//xplat/js:node_modules__nullthrows", diff --git a/Libraries/TurboModule/samples/NativeSampleTurboModule.js b/Libraries/TurboModule/samples/NativeSampleTurboModule.js index 813f2cbf5c367f..89d16f03625f43 100644 --- a/Libraries/TurboModule/samples/NativeSampleTurboModule.js +++ b/Libraries/TurboModule/samples/NativeSampleTurboModule.js @@ -13,6 +13,11 @@ import type {RootTag, TurboModule} from '../RCTExport'; import * as TurboModuleRegistry from '../TurboModuleRegistry'; +export enum EnumInt { + A = 23, + B = 42, +} + export interface Spec extends TurboModule { // Exported methods. +getConstants: () => {| @@ -22,6 +27,7 @@ export interface Spec extends TurboModule { |}; +voidFunc: () => void; +getBool: (arg: boolean) => boolean; + +getEnum?: (arg: EnumInt) => EnumInt; +getNumber: (arg: number) => number; +getString: (arg: string) => string; +getArray: (arg: Array) => Array; diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp index d45de55ac6a8a6..4a40f935c880dd 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp @@ -31,6 +31,16 @@ static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool( ->getBool(rt, args[0].getBool())); } +static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum( + jsi::Runtime &rt, + TurboModule &turboModule, + const jsi::Value *args, + size_t count) { + return jsi::Value( + static_cast(&turboModule) + ->getEnum(rt, args[0].getNumber())); +} + static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber( jsi::Runtime &rt, TurboModule &turboModule, @@ -119,6 +129,8 @@ NativeSampleTurboCxxModuleSpecJSI::NativeSampleTurboCxxModuleSpecJSI( 0, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_voidFunc}; methodMap_["getBool"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool}; + methodMap_["getEnum"] = MethodMetadata{ + 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum}; methodMap_["getNumber"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber}; methodMap_["getString"] = MethodMetadata{ diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h index 400ee7e3d692a8..2b4b342586c975 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h @@ -23,6 +23,7 @@ class JSI_EXPORT NativeSampleTurboCxxModuleSpecJSI : public TurboModule { public: virtual void voidFunc(jsi::Runtime &rt) = 0; virtual bool getBool(jsi::Runtime &rt, bool arg) = 0; + virtual double getEnum(jsi::Runtime &rt, double arg) = 0; virtual double getNumber(jsi::Runtime &rt, double arg) = 0; virtual jsi::String getString(jsi::Runtime &rt, const jsi::String &arg) = 0; virtual jsi::Array getArray(jsi::Runtime &rt, const jsi::Array &arg) = 0; diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp index a3d04f9438dfb6..9b3fff0c6850b1 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp @@ -26,6 +26,10 @@ bool SampleTurboCxxModule::getBool(jsi::Runtime &rt, bool arg) { return arg; } +double SampleTurboCxxModule::getEnum(jsi::Runtime &rt, double arg) { + return arg; +} + double SampleTurboCxxModule::getNumber(jsi::Runtime &rt, double arg) { return arg; } diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h index 5c41f71ae4f9e6..8d397ae5a641eb 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h @@ -25,6 +25,7 @@ class SampleTurboCxxModule : public NativeSampleTurboCxxModuleSpecJSI { void voidFunc(jsi::Runtime &rt) override; bool getBool(jsi::Runtime &rt, bool arg) override; + double getEnum(jsi::Runtime &rt, double arg) override; double getNumber(jsi::Runtime &rt, double arg) override; jsi::String getString(jsi::Runtime &rt, const jsi::String &arg) override; jsi::Array getArray(jsi::Runtime &rt, const jsi::Array &arg) override; diff --git a/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java b/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java index 1dd66decb687e9..d3e50a5a3d68bf 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java +++ b/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java @@ -66,6 +66,9 @@ public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { @ReactMethod(isBlockingSynchronousMethod = true) public abstract boolean getBool(boolean arg); + @ReactMethod(isBlockingSynchronousMethod = true) + public abstract double getEnum(double arg); + protected abstract Map getTypedExportedConstants(); @Override diff --git a/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp b/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp index d8001bfb178b9e..b0a9b0786feb8a 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp +++ b/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp @@ -36,6 +36,18 @@ __hostFunction_NativeSampleTurboModuleSpecJSI_getBool( rt, BooleanKind, "getBool", "(Z)Z", args, count, cachedMethodId); } +static facebook::jsi::Value +__hostFunction_NativeSampleTurboModuleSpecJSI_getEnum( + facebook::jsi::Runtime &rt, + TurboModule &turboModule, + const facebook::jsi::Value *args, + size_t count) { + static jmethodID cachedMethodId = nullptr; + return static_cast(turboModule) + .invokeJavaMethod( + rt, NumberKind, "getEnum", "(D)D", args, count, cachedMethodId); +} + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber( facebook::jsi::Runtime &rt, @@ -195,6 +207,9 @@ NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI( methodMap_["getBool"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; + methodMap_["getEnum"] = + MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum}; + methodMap_["getNumber"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; diff --git a/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java b/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java index 84a0f6dd086981..73a1ac70c7f22c 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java +++ b/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java @@ -48,6 +48,14 @@ public boolean getBool(boolean arg) { return arg; } + @DoNotStrip + @SuppressWarnings("unused") + @Override + public double getEnum(double arg) { + log("getEnum", arg, arg); + return arg; + } + @Override protected Map getTypedExportedConstants() { Map result = new HashMap<>(); diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h index ab91dbeaf893e1..9f75fdc612efac 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h @@ -22,6 +22,7 @@ - (void)voidFunc; - (NSNumber *)getBool:(BOOL)arg; +- (NSNumber *)getEnum:(double)arg; - (NSNumber *)getNumber:(double)arg; - (NSString *)getString:(NSString *)arg; - (NSArray> *)getArray:(NSArray *)arg; diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm index d3edbda6813242..79feb93cca7297 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm @@ -30,6 +30,16 @@ .invokeObjCMethod(rt, BooleanKind, "getBool", @selector(getBool:), args, count); } +static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum( + facebook::jsi::Runtime &rt, + TurboModule &turboModule, + const facebook::jsi::Value *args, + size_t count) +{ + return static_cast(turboModule) + .invokeObjCMethod(rt, NumberKind, "getEnum", @selector(getEnum:), args, count); +} + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber( facebook::jsi::Runtime &rt, TurboModule &turboModule, @@ -136,6 +146,7 @@ { methodMap_["voidFunc"] = MethodMetadata{0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; methodMap_["getBool"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; + methodMap_["getEnum"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum}; methodMap_["getNumber"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; methodMap_["getString"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getString}; methodMap_["getArray"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArray}; diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm b/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm index 11e57479cf6dfa..c3176f386c32f3 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm @@ -74,6 +74,11 @@ - (NSDictionary *)constantsToExport return @(arg); } +RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSNumber *, getEnum : (double)arg) +{ + return @(arg); +} + RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSNumber *, getNumber : (double)arg) { return @(arg); diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp index e46412e86b6137..5b90e17106dd0b 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp +++ b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp @@ -39,6 +39,12 @@ std::vector SampleTurboCxxModuleLegacyImpl::getMethods() { return getBool(xplat::jsArgAsBool(args, 0)); }, CxxModule::SyncTag), + CxxModule::Method( + "getEnum", + [this](folly::dynamic args) { + return getEnum(xplat::jsArgAsDouble(args, 0)); + }, + CxxModule::SyncTag), CxxModule::Method( "getNumber", [this](folly::dynamic args) { @@ -114,6 +120,10 @@ bool SampleTurboCxxModuleLegacyImpl::getBool(bool arg) { return arg; } +double SampleTurboCxxModuleLegacyImpl::getEnum(double arg) { + return arg; +} + double SampleTurboCxxModuleLegacyImpl::getNumber(double arg) { return arg; } diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h index d09e688b2cdd4f..b360a02d24f3df 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h +++ b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h @@ -27,6 +27,7 @@ class SampleTurboCxxModuleLegacyImpl // API void voidFunc(); bool getBool(bool arg); + double getEnum(double arg); double getNumber(double arg); std::string getString(const std::string &arg); folly::dynamic getArray(const folly::dynamic &arg); diff --git a/package.json b/package.json index c0c3eb4cd0d845..bbced7a34aabc1 100644 --- a/package.json +++ b/package.json @@ -119,6 +119,7 @@ "anser": "^1.4.9", "base64-js": "^1.1.2", "event-target-shim": "^5.0.1", + "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", "jest-environment-node": "^29.2.1", "jsc-android": "^250230.2.1", diff --git a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js index 01f7a2c7000799..3c341eb0253abf 100644 --- a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js @@ -9,6 +9,7 @@ */ import NativeSampleTurboModule from 'react-native/Libraries/TurboModule/samples/NativeSampleTurboModule'; +import {EnumInt} from 'react-native/Libraries/TurboModule/samples/NativeSampleTurboModule'; import type {RootTag} from 'react-native/Libraries/ReactNative/RootTag'; import { StyleSheet, @@ -57,6 +58,10 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { getConstants: () => NativeSampleTurboModule.getConstants(), voidFunc: () => NativeSampleTurboModule.voidFunc(), getBool: () => NativeSampleTurboModule.getBool(true), + getEnum: () => + NativeSampleTurboModule.getEnum + ? NativeSampleTurboModule.getEnum(EnumInt.A) + : null, getNumber: () => NativeSampleTurboModule.getNumber(99.95), getString: () => NativeSampleTurboModule.getString('Hello'), getArray: () => @@ -80,6 +85,7 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { | 'callback' | 'getArray' | 'getBool' + | 'getEnum' | 'getConstants' | 'getNumber' | 'getObject' @@ -120,6 +126,7 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { | 'callback' | 'getArray' | 'getBool' + | 'getEnum' | 'getConstants' | 'getNumber' | 'getObject' diff --git a/yarn.lock b/yarn.lock index 740f4c15920f8f..e135844fa43317 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4909,6 +4909,11 @@ flow-bin@^0.190.1: resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.190.1.tgz#59ccbc9aaa2515fe32acc66117a05e7ef6a11061" integrity sha512-5c9/6eEkMTTfdNuK2WwssrKfsUXKMUXlZVJZnrlWiqJpDSVc70/Smwyi9sXict9k/oq0f+Mo5wVH0d7peBYREg== +flow-enums-runtime@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/flow-enums-runtime/-/flow-enums-runtime-0.0.6.tgz#5bb0cd1b0a3e471330f4d109039b7eba5cb3e787" + integrity sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw== + flow-parser@0.*, flow-parser@^0.185.0: version "0.185.0" resolved "https://registry.yarnpkg.com/flow-parser/-/flow-parser-0.185.0.tgz#56bde60805bad19b2934ebfc50c9485e5c5424f9" From adaa4fe71e83ce049705444ccd0c4259d68f9266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Tue, 25 Oct 2022 16:25:20 -0700 Subject: [PATCH 031/169] trivial: display target name in CocoaPods output Summary: Without this, the CocoaPods output would display multiple "Building RNTester..." logs. With these changes, we make it clear that these are separate targets that are being configured. Changelog: [internal] Reviewed By: mdvacca, cipolleschi Differential Revision: D40656813 fbshipit-source-id: a317112e804d08b9e64e2d62e8b27e4045b317b0 --- packages/rn-tester/Podfile | 10 +++++----- packages/rn-tester/Podfile.lock | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/rn-tester/Podfile b/packages/rn-tester/Podfile index 386a55c6e09131..45ff904de3b762 100644 --- a/packages/rn-tester/Podfile +++ b/packages/rn-tester/Podfile @@ -15,7 +15,7 @@ if USE_FRAMEWORKS use_frameworks! end -def pods(options = {}, use_flipper: !IN_CI && !USE_FRAMEWORKS) +def pods(target_name, options = {}, use_flipper: !IN_CI && !USE_FRAMEWORKS) project 'RNTesterPods.xcodeproj' fabric_enabled = true @@ -23,7 +23,7 @@ def pods(options = {}, use_flipper: !IN_CI && !USE_FRAMEWORKS) # Hermes is now enabled by default. # The following line will only disable Hermes if the USE_HERMES envvar is SET to a value other than 1 (e.g. USE_HERMES=0). hermes_enabled = !ENV.has_key?('USE_HERMES') || ENV['USE_HERMES'] == '1' - puts "Building RNTester with Fabric #{fabric_enabled ? "enabled" : "disabled"}.#{hermes_enabled ? " Using Hermes engine." : ""}" + puts "Configuring #{target_name} with Fabric #{fabric_enabled ? "enabled" : "disabled"}.#{hermes_enabled ? " Using Hermes engine." : ""}" if ENV['RCT_NEW_ARCH_ENABLED'] == '1' # Custom fabric component is only supported when using codegen discovery. @@ -51,16 +51,16 @@ def pods(options = {}, use_flipper: !IN_CI && !USE_FRAMEWORKS) end target 'RNTester' do - pods() + pods('RNTester') end target 'RNTesterUnitTests' do - pods() + pods('RNTesterUnitTests') pod 'React-RCTTest', :path => "./RCTTest" end target 'RNTesterIntegrationTests' do - pods() + pods('RNTesterIntegrationTests') pod 'React-RCTTest', :path => "./RCTTest" end diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index fedd81b021de81..ae0be30952fbb1 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -945,7 +945,7 @@ SPEC CHECKSUMS: FlipperKit: cbdee19bdd4e7f05472a66ce290f1b729ba3cb86 fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 glog: 04b94705f318337d7ead9e6d17c019bd9b1f6b1b - hermes-engine: 2c30267d0c2771edc2d369ac694d45f1278ab08b + hermes-engine: 05624e18294fd8279bb718e95d5bf2be311667ec libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c RCT-Folly: 0080d0a6ebf2577475bda044aa59e2ca1f909cda @@ -988,6 +988,6 @@ SPEC CHECKSUMS: Yoga: 1b1a12ff3d86a10565ea7cbe057d42f5e5fb2a07 YogaKit: f782866e155069a2cca2517aafea43200b01fd5a -PODFILE CHECKSUM: e86c02825ce4e267e6fb3975bae791feb32a94a0 +PODFILE CHECKSUM: 20298ecd3f30aa788ad491637e593ed0d8c100ca COCOAPODS: 1.11.3 From 0fac9817df403e31d8256befe52409c948614706 Mon Sep 17 00:00:00 2001 From: Robert Balicki Date: Tue, 25 Oct 2022 21:01:25 -0700 Subject: [PATCH 032/169] Support persisted settings in Android + iOS (#34964) Summary: * Add a DevToolsSettingsManager, which has android and iOS variants, which uses a new TM (Android) or takes advantage of the Settings TM (iOS) to get/set console patch settings * This is backed by either the existing Settings module (iOS) or a new Java TM, which uses the SharedPreferences AP ## Testing Manual testing ## Changelog [General] [Added] - Add DevToolsSettingsManager Pull Request resolved: https://github.com/facebook/react-native/pull/34964 Test Plan: * Extensive manual testing Reviewed By: NickGerleman Differential Revision: D40333083 Pulled By: rbalicki2 fbshipit-source-id: f3816e3bd7dea3086f6f2269c3a099af14aebb3b --- Libraries/Core/setUpReactDevTools.js | 2 + .../DevToolsSettingsManager.android.js | 13 +++++ .../DevToolsSettingsManager.ios.js | 33 +++++++++++++ .../NativeDevToolsSettingsManager.js | 22 +++++++++ React/CoreModules/BUCK | 1 + .../src/main/java/com/facebook/react/BUCK | 1 + .../react/modules/devtoolssettings/BUCK | 28 +++++++++++ .../DevToolsSettingsManagerModule.java | 49 +++++++++++++++++++ .../main/java/com/facebook/react/shell/BUCK | 1 + .../react/shell/MainReactPackage.java | 7 ++- .../test/java/com/facebook/react/modules/BUCK | 1 + 11 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.android.js create mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js create mode 100644 Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js create mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK create mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java diff --git a/Libraries/Core/setUpReactDevTools.js b/Libraries/Core/setUpReactDevTools.js index be647e33b4d2ca..ecdd14a44a65e4 100644 --- a/Libraries/Core/setUpReactDevTools.js +++ b/Libraries/Core/setUpReactDevTools.js @@ -62,6 +62,7 @@ if (__DEV__) { }); const ReactNativeStyleAttributes = require('../Components/View/ReactNativeStyleAttributes'); + const devToolsSettingsManager = require('../DevToolsSettings/DevToolsSettingsManager'); reactDevTools.connectToDevTools({ isAppActive, @@ -70,6 +71,7 @@ if (__DEV__) { ReactNativeStyleAttributes, ), websocket: ws, + devToolsSettingsManager, }); } }; diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js new file mode 100644 index 00000000000000..262aafbcb0d69b --- /dev/null +++ b/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js @@ -0,0 +1,13 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import NativeDevToolsSettingsManager from './NativeDevToolsSettingsManager'; + +module.exports = NativeDevToolsSettingsManager; diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js new file mode 100644 index 00000000000000..fdc61730166bf4 --- /dev/null +++ b/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {Spec} from './NativeDevToolsSettingsManager'; + +import Settings from '../Settings/Settings'; + +const CONSOLE_PATCH_SETTINGS_KEY = 'ReactDevTools::ConsolePatchSettings'; + +const DevToolsSettingsManager = { + setConsolePatchSettings: (newConsolePatchSettings: string) => { + Settings.set({ + [CONSOLE_PATCH_SETTINGS_KEY]: newConsolePatchSettings, + }); + }, + getConsolePatchSettings: () => { + const value = Settings.get(CONSOLE_PATCH_SETTINGS_KEY); + if (typeof value === 'string') { + // $FlowFixMe[unclear-type] + return ((value: any): string); + } + return null; + }, +}; + +module.exports = (DevToolsSettingsManager: Spec); diff --git a/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js b/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js new file mode 100644 index 00000000000000..904e8d6701c756 --- /dev/null +++ b/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js @@ -0,0 +1,22 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import type {TurboModule} from '../TurboModule/RCTExport'; + +import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; + +export interface Spec extends TurboModule { + +setConsolePatchSettings: (newConsolePatchSettings: string) => void; + +getConsolePatchSettings: () => ?string; +} + +export default (TurboModuleRegistry.get( + 'DevToolsSettingsManager', +): ?Spec); diff --git a/React/CoreModules/BUCK b/React/CoreModules/BUCK index 5608bacdaea311..eda0220f3bd7df 100644 --- a/React/CoreModules/BUCK +++ b/React/CoreModules/BUCK @@ -137,6 +137,7 @@ rn_apple_library( "//xplat/js/react-native-github:FBReactNativeSpecApple", "//xplat/js/react-native-github:RCTLinkingApple", "//xplat/js/react-native-github:RCTPushNotificationApple", + "//xplat/js/react-native-github:RCTSettingsApple", "//xplat/js/react-native-github:ReactInternalApple", ], ) diff --git a/ReactAndroid/src/main/java/com/facebook/react/BUCK b/ReactAndroid/src/main/java/com/facebook/react/BUCK index dd21088699dab5..08f8c1176bc528 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/BUCK @@ -41,6 +41,7 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/appearance:appearance"), react_native_target("java/com/facebook/react/modules/bundleloader:bundleloader"), react_native_target("java/com/facebook/react/modules/debug:debug"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/fabric:fabric"), react_native_target("java/com/facebook/react/modules/debug:interfaces"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK new file mode 100644 index 00000000000000..50f0d888a9cdf4 --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK @@ -0,0 +1,28 @@ +load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") + +rn_android_library( + name = "devtoolssettings", + srcs = glob(["**/*.java"]), + autoglob = False, + labels = [ + "pfh:ReactNative_CommonInfrastructurePlaceholder", + "supermodule:xplat/default/public.react_native.infra", + ], + language = "JAVA", + provided_deps = [ + react_native_dep("third-party/android/androidx:annotation"), + ], + visibility = [ + "PUBLIC", + ], + deps = [ + react_native_dep("libraries/fbcore/src/main/java/com/facebook/common/logging:logging"), + react_native_dep("third-party/java/infer-annotations:infer-annotations"), + react_native_dep("third-party/java/jsr-305:jsr-305"), + react_native_target("java/com/facebook/react/bridge:bridge"), + react_native_target("java/com/facebook/react/common:common"), + react_native_target("java/com/facebook/react/module/annotations:annotations"), + react_native_target("java/com/facebook/react/modules/core:core"), + ], + exported_deps = [react_native_root_target(":FBReactNativeSpec")], +) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java new file mode 100644 index 00000000000000..0164de2788292f --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java @@ -0,0 +1,49 @@ +/* + * 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.modules.devtoolssettings; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import androidx.annotation.Nullable; +import com.facebook.fbreact.specs.NativeDevToolsSettingsManagerSpec; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.module.annotations.ReactModule; + +@ReactModule(name = DevToolsSettingsManagerModule.NAME) +public class DevToolsSettingsManagerModule extends NativeDevToolsSettingsManagerSpec { + public static final String NAME = "DevToolsSettingsManager"; + + private static final String SHARED_PREFERENCES_PREFIX = "ReactNative__DevToolsSettings"; + private static final String KEY_CONSOLE_PATCH_SETTINGS = "ConsolePatchSettings"; + + private final SharedPreferences mSharedPreferences; + + public DevToolsSettingsManagerModule(ReactApplicationContext reactContext) { + super(reactContext); + mSharedPreferences = + reactContext.getSharedPreferences(SHARED_PREFERENCES_PREFIX, Context.MODE_PRIVATE); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public @Nullable String getConsolePatchSettings() { + return mSharedPreferences.getString(KEY_CONSOLE_PATCH_SETTINGS, null); + } + + @Override + public void setConsolePatchSettings(String newSettings) { + Editor editor = mSharedPreferences.edit(); + editor.putString(KEY_CONSOLE_PATCH_SETTINGS, newSettings); + editor.apply(); + } +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK index c79b69687e0654..f1ee669920aa9f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK @@ -37,6 +37,7 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/clipboard:clipboard"), react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/fresco:fresco"), react_native_target("java/com/facebook/react/modules/i18nmanager:i18nmanager"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index 6fc4a536e2b1f7..e9c0297a529a65 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -23,6 +23,7 @@ import com.facebook.react.modules.blob.FileReaderModule; import com.facebook.react.modules.camera.ImageStoreManager; import com.facebook.react.modules.clipboard.ClipboardModule; +import com.facebook.react.modules.devtoolssettings.DevToolsSettingsManagerModule; import com.facebook.react.modules.dialog.DialogModule; import com.facebook.react.modules.fresco.FrescoModule; import com.facebook.react.modules.i18nmanager.I18nManagerModule; @@ -145,6 +146,8 @@ public MainReactPackage(MainPackageConfig config) { return new VibrationModule(context); case WebSocketModule.NAME: return new WebSocketModule(context); + case DevToolsSettingsManagerModule.NAME: + return new DevToolsSettingsManagerModule(context); default: return null; } @@ -185,7 +188,8 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { Class.forName("com.facebook.react.shell.MainReactPackage$$ReactModuleInfoProvider"); return (ReactModuleInfoProvider) reactModuleInfoProviderClass.newInstance(); } catch (ClassNotFoundException e) { - // In OSS case, the annotation processor does not run. We fall back on creating this byhand + // In the OSS case, the annotation processor does not run. We fall back to creating this by + // hand Class[] moduleList = new Class[] { AccessibilityInfoModule.class, @@ -204,6 +208,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { NativeAnimatedModule.class, NetworkingModule.class, PermissionsModule.class, + DevToolsSettingsManagerModule.class, ShareModule.class, StatusBarModule.class, SoundManagerModule.class, diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK index 7ab27c360a9714..d8581c32d5dd90 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK @@ -34,6 +34,7 @@ rn_robolectric_test( react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/network:network"), react_native_target("java/com/facebook/react/modules/share:share"), From b655e69bad674019e5f2dd5e3d7726c80fc9f818 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 26 Oct 2022 01:43:19 -0700 Subject: [PATCH 033/169] Fix RCTLoggingTests in OSS (#35085) Summary: fd917481463bf6ba9c4e14919250aec2ffad2c2f added a condition not to pump an extra message when we didn't see symbolication warnings (which do not seem to show up in a stock internal build), but I missed that the test specific to RCTLogLevelError checked for string containment instead of equality, and the last assertion we process on log level is incorrect in OSS as a result. Changelog: [Internal][Fixed] - Fix RCTLoggingTests in OSS Pull Request resolved: https://github.com/facebook/react-native/pull/35085 Test Plan: `test_ios-Hermes` passes again in OSS: https://github.com/facebook/react-native/pull/35085 (JSC and Android failures look unrelated) RCTLoggingTests still pass running `buck test //xplat/js/react-native-github/packages/rn-tester:RNTesterIntegrationTests` Reviewed By: rshest Differential Revision: D40699773 Pulled By: NickGerleman fbshipit-source-id: 5acc8ec2b26a1f9acac2f070b85f1d65ee15a011 --- packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m b/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m index 7cf83c2a0168e5..5aa954c70e70be 100644 --- a/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m +++ b/packages/rn-tester/RNTesterIntegrationTests/RCTLoggingTests.m @@ -129,7 +129,7 @@ - (void)testLogging XCTAssertEqual(waitRet, 0, @"Timed out waiting for throwError"); // For local bundles, we may first get a warning about symbolication - if (![_lastLogMessage isEqualToString:@"Error: Throwing an error"]) { + if (![_lastLogMessage containsString:@"Error: Throwing an error"]) { waitRet = dispatch_semaphore_wait(_logSem, dispatch_time(DISPATCH_TIME_NOW, LOGGER_TIMEOUT)); XCTAssertEqual(waitRet, 0, @"Timed out waiting for throwError #2"); } From c868d5b26c5d680603d3f653de9277124c1b539b Mon Sep 17 00:00:00 2001 From: Marco Fiorito Date: Wed, 26 Oct 2022 03:21:04 -0700 Subject: [PATCH 034/169] refactor(rn tester app): change activity indicator to hooks (#35071) Summary: This pull request migrates the activity indicator example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate ActivityIndicator to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/35071 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: jacdebug Differential Revision: D40698379 Pulled By: NickGerleman fbshipit-source-id: 08b275fcc4e3a10b5872e0031fa2ecce5360a7b9 --- .../ActivityIndicatorExample.js | 57 ++++++++----------- 1 file changed, 23 insertions(+), 34 deletions(-) diff --git a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js index 188302df2f78c2..7be8bc4a5dd5f3 100644 --- a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js +++ b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js @@ -10,46 +10,35 @@ import type {Node} from 'React'; import {ActivityIndicator, StyleSheet, View} from 'react-native'; -import React, {Component} from 'react'; +import React, {useState, useCallback, useRef, useEffect} from 'react'; -type State = {|animating: boolean|}; -type Props = $ReadOnly<{||}>; -type Timer = TimeoutID; +function ToggleAnimatingActivityIndicator() { + const timer = useRef(); -class ToggleAnimatingActivityIndicator extends Component { - _timer: Timer; + const [animating, setAnimating] = useState(true); - constructor(props: Props) { - super(props); - this.state = { - animating: true, - }; - } - - componentDidMount() { - this.setToggleTimeout(); - } + const setToggleTimeout = useCallback(() => { + timer.current = setTimeout(() => { + setAnimating(currentState => !currentState); + setToggleTimeout(); + }, 2000); + }, []); - componentWillUnmount() { - clearTimeout(this._timer); - } + useEffect(() => { + setToggleTimeout(); - setToggleTimeout() { - this._timer = setTimeout(() => { - this.setState({animating: !this.state.animating}); - this.setToggleTimeout(); - }, 2000); - } + return () => { + clearTimeout(timer.current); + }; + }, [timer, setToggleTimeout]); - render(): Node { - return ( - - ); - } + return ( + + ); } const styles = StyleSheet.create({ From d0599ac56bc18d1db09ac857056affa7b793b2c7 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Wed, 26 Oct 2022 06:30:14 -0700 Subject: [PATCH 035/169] Back out "Add enum example to Android/iOS rn-tester TurboModule" (#35089) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35089 Changelog: [General][Fixed] - Back out "Add enum example to Android/iOS rn-tester TurboModule" This broke the rn-tester adding due to an invalid flow-enum setup. Needs further investigation Reviewed By: cipolleschi Differential Revision: D40714320 fbshipit-source-id: 9831276762f90df0ffaca3304382fe5925009343 --- .flowconfig | 1 - .flowconfig.android | 1 - BUCK | 1 - .../samples/NativeSampleTurboModule.js | 6 ------ .../NativeSampleTurboCxxModuleSpecJSI.cpp | 12 ------------ .../NativeSampleTurboCxxModuleSpecJSI.h | 1 - .../samples/ReactCommon/SampleTurboCxxModule.cpp | 4 ---- .../samples/ReactCommon/SampleTurboCxxModule.h | 1 - .../android/NativeSampleTurboModuleSpec.java | 3 --- .../android/ReactCommon/SampleTurboModuleSpec.cpp | 15 --------------- .../platform/android/SampleTurboModule.java | 8 -------- .../platform/ios/RCTNativeSampleTurboModuleSpec.h | 1 - .../ios/RCTNativeSampleTurboModuleSpec.mm | 11 ----------- .../samples/platform/ios/RCTSampleTurboModule.mm | 5 ----- .../ios/SampleTurboCxxModuleLegacyImpl.cpp | 10 ---------- .../platform/ios/SampleTurboCxxModuleLegacyImpl.h | 1 - package.json | 1 - .../TurboModule/SampleTurboModuleExample.js | 7 ------- yarn.lock | 5 ----- 19 files changed, 94 deletions(-) diff --git a/.flowconfig b/.flowconfig index 34038826acc5d1..50a3f7adab9a29 100644 --- a/.flowconfig +++ b/.flowconfig @@ -30,7 +30,6 @@ flow/ [options] emoji=true -enums=true exact_by_default=true exact_empty_objects=true diff --git a/.flowconfig.android b/.flowconfig.android index b084ed5e33ae9b..fc7429f32705d4 100644 --- a/.flowconfig.android +++ b/.flowconfig.android @@ -30,7 +30,6 @@ flow/ [options] emoji=true -enums=true exact_by_default=true exact_empty_objects=true diff --git a/BUCK b/BUCK index 1f6e1b80d64dcf..e1b1e68844cbd7 100644 --- a/BUCK +++ b/BUCK @@ -743,7 +743,6 @@ rn_library( "//xplat/js:node_modules__anser", "//xplat/js:node_modules__base64_19js", "//xplat/js:node_modules__event_19target_19shim", - "//xplat/js:node_modules__flow_19enums_19runtime", "//xplat/js:node_modules__invariant", "//xplat/js:node_modules__memoize_19one", "//xplat/js:node_modules__nullthrows", diff --git a/Libraries/TurboModule/samples/NativeSampleTurboModule.js b/Libraries/TurboModule/samples/NativeSampleTurboModule.js index 89d16f03625f43..813f2cbf5c367f 100644 --- a/Libraries/TurboModule/samples/NativeSampleTurboModule.js +++ b/Libraries/TurboModule/samples/NativeSampleTurboModule.js @@ -13,11 +13,6 @@ import type {RootTag, TurboModule} from '../RCTExport'; import * as TurboModuleRegistry from '../TurboModuleRegistry'; -export enum EnumInt { - A = 23, - B = 42, -} - export interface Spec extends TurboModule { // Exported methods. +getConstants: () => {| @@ -27,7 +22,6 @@ export interface Spec extends TurboModule { |}; +voidFunc: () => void; +getBool: (arg: boolean) => boolean; - +getEnum?: (arg: EnumInt) => EnumInt; +getNumber: (arg: number) => number; +getString: (arg: string) => string; +getArray: (arg: Array) => Array; diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp index 4a40f935c880dd..d45de55ac6a8a6 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.cpp @@ -31,16 +31,6 @@ static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool( ->getBool(rt, args[0].getBool())); } -static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum( - jsi::Runtime &rt, - TurboModule &turboModule, - const jsi::Value *args, - size_t count) { - return jsi::Value( - static_cast(&turboModule) - ->getEnum(rt, args[0].getNumber())); -} - static jsi::Value __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber( jsi::Runtime &rt, TurboModule &turboModule, @@ -129,8 +119,6 @@ NativeSampleTurboCxxModuleSpecJSI::NativeSampleTurboCxxModuleSpecJSI( 0, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_voidFunc}; methodMap_["getBool"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getBool}; - methodMap_["getEnum"] = MethodMetadata{ - 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getEnum}; methodMap_["getNumber"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboCxxModuleSpecJSI_getNumber}; methodMap_["getString"] = MethodMetadata{ diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h index 2b4b342586c975..400ee7e3d692a8 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/NativeSampleTurboCxxModuleSpecJSI.h @@ -23,7 +23,6 @@ class JSI_EXPORT NativeSampleTurboCxxModuleSpecJSI : public TurboModule { public: virtual void voidFunc(jsi::Runtime &rt) = 0; virtual bool getBool(jsi::Runtime &rt, bool arg) = 0; - virtual double getEnum(jsi::Runtime &rt, double arg) = 0; virtual double getNumber(jsi::Runtime &rt, double arg) = 0; virtual jsi::String getString(jsi::Runtime &rt, const jsi::String &arg) = 0; virtual jsi::Array getArray(jsi::Runtime &rt, const jsi::Array &arg) = 0; diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp index 9b3fff0c6850b1..a3d04f9438dfb6 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.cpp @@ -26,10 +26,6 @@ bool SampleTurboCxxModule::getBool(jsi::Runtime &rt, bool arg) { return arg; } -double SampleTurboCxxModule::getEnum(jsi::Runtime &rt, double arg) { - return arg; -} - double SampleTurboCxxModule::getNumber(jsi::Runtime &rt, double arg) { return arg; } diff --git a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h index 8d397ae5a641eb..5c41f71ae4f9e6 100644 --- a/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h +++ b/ReactCommon/react/nativemodule/samples/ReactCommon/SampleTurboCxxModule.h @@ -25,7 +25,6 @@ class SampleTurboCxxModule : public NativeSampleTurboCxxModuleSpecJSI { void voidFunc(jsi::Runtime &rt) override; bool getBool(jsi::Runtime &rt, bool arg) override; - double getEnum(jsi::Runtime &rt, double arg) override; double getNumber(jsi::Runtime &rt, double arg) override; jsi::String getString(jsi::Runtime &rt, const jsi::String &arg) override; jsi::Array getArray(jsi::Runtime &rt, const jsi::Array &arg) override; diff --git a/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java b/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java index d3e50a5a3d68bf..1dd66decb687e9 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java +++ b/ReactCommon/react/nativemodule/samples/platform/android/NativeSampleTurboModuleSpec.java @@ -66,9 +66,6 @@ public NativeSampleTurboModuleSpec(ReactApplicationContext reactContext) { @ReactMethod(isBlockingSynchronousMethod = true) public abstract boolean getBool(boolean arg); - @ReactMethod(isBlockingSynchronousMethod = true) - public abstract double getEnum(double arg); - protected abstract Map getTypedExportedConstants(); @Override diff --git a/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp b/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp index b0a9b0786feb8a..d8001bfb178b9e 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp +++ b/ReactCommon/react/nativemodule/samples/platform/android/ReactCommon/SampleTurboModuleSpec.cpp @@ -36,18 +36,6 @@ __hostFunction_NativeSampleTurboModuleSpecJSI_getBool( rt, BooleanKind, "getBool", "(Z)Z", args, count, cachedMethodId); } -static facebook::jsi::Value -__hostFunction_NativeSampleTurboModuleSpecJSI_getEnum( - facebook::jsi::Runtime &rt, - TurboModule &turboModule, - const facebook::jsi::Value *args, - size_t count) { - static jmethodID cachedMethodId = nullptr; - return static_cast(turboModule) - .invokeJavaMethod( - rt, NumberKind, "getEnum", "(D)D", args, count, cachedMethodId); -} - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber( facebook::jsi::Runtime &rt, @@ -207,9 +195,6 @@ NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI( methodMap_["getBool"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; - methodMap_["getEnum"] = - MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum}; - methodMap_["getNumber"] = MethodMetadata{ 1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; diff --git a/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java b/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java index 73a1ac70c7f22c..84a0f6dd086981 100644 --- a/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java +++ b/ReactCommon/react/nativemodule/samples/platform/android/SampleTurboModule.java @@ -48,14 +48,6 @@ public boolean getBool(boolean arg) { return arg; } - @DoNotStrip - @SuppressWarnings("unused") - @Override - public double getEnum(double arg) { - log("getEnum", arg, arg); - return arg; - } - @Override protected Map getTypedExportedConstants() { Map result = new HashMap<>(); diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h index 9f75fdc612efac..ab91dbeaf893e1 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.h @@ -22,7 +22,6 @@ - (void)voidFunc; - (NSNumber *)getBool:(BOOL)arg; -- (NSNumber *)getEnum:(double)arg; - (NSNumber *)getNumber:(double)arg; - (NSString *)getString:(NSString *)arg; - (NSArray> *)getArray:(NSArray *)arg; diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm index 79feb93cca7297..d3edbda6813242 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTNativeSampleTurboModuleSpec.mm @@ -30,16 +30,6 @@ .invokeObjCMethod(rt, BooleanKind, "getBool", @selector(getBool:), args, count); } -static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum( - facebook::jsi::Runtime &rt, - TurboModule &turboModule, - const facebook::jsi::Value *args, - size_t count) -{ - return static_cast(turboModule) - .invokeObjCMethod(rt, NumberKind, "getEnum", @selector(getEnum:), args, count); -} - static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber( facebook::jsi::Runtime &rt, TurboModule &turboModule, @@ -146,7 +136,6 @@ { methodMap_["voidFunc"] = MethodMetadata{0, __hostFunction_NativeSampleTurboModuleSpecJSI_voidFunc}; methodMap_["getBool"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getBool}; - methodMap_["getEnum"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnum}; methodMap_["getNumber"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getNumber}; methodMap_["getString"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getString}; methodMap_["getArray"] = MethodMetadata{1, __hostFunction_NativeSampleTurboModuleSpecJSI_getArray}; diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm b/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm index c3176f386c32f3..11e57479cf6dfa 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm +++ b/ReactCommon/react/nativemodule/samples/platform/ios/RCTSampleTurboModule.mm @@ -74,11 +74,6 @@ - (NSDictionary *)constantsToExport return @(arg); } -RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSNumber *, getEnum : (double)arg) -{ - return @(arg); -} - RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSNumber *, getNumber : (double)arg) { return @(arg); diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp index 5b90e17106dd0b..e46412e86b6137 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp +++ b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.cpp @@ -39,12 +39,6 @@ std::vector SampleTurboCxxModuleLegacyImpl::getMethods() { return getBool(xplat::jsArgAsBool(args, 0)); }, CxxModule::SyncTag), - CxxModule::Method( - "getEnum", - [this](folly::dynamic args) { - return getEnum(xplat::jsArgAsDouble(args, 0)); - }, - CxxModule::SyncTag), CxxModule::Method( "getNumber", [this](folly::dynamic args) { @@ -120,10 +114,6 @@ bool SampleTurboCxxModuleLegacyImpl::getBool(bool arg) { return arg; } -double SampleTurboCxxModuleLegacyImpl::getEnum(double arg) { - return arg; -} - double SampleTurboCxxModuleLegacyImpl::getNumber(double arg) { return arg; } diff --git a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h index b360a02d24f3df..d09e688b2cdd4f 100644 --- a/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h +++ b/ReactCommon/react/nativemodule/samples/platform/ios/SampleTurboCxxModuleLegacyImpl.h @@ -27,7 +27,6 @@ class SampleTurboCxxModuleLegacyImpl // API void voidFunc(); bool getBool(bool arg); - double getEnum(double arg); double getNumber(double arg); std::string getString(const std::string &arg); folly::dynamic getArray(const folly::dynamic &arg); diff --git a/package.json b/package.json index bbced7a34aabc1..c0c3eb4cd0d845 100644 --- a/package.json +++ b/package.json @@ -119,7 +119,6 @@ "anser": "^1.4.9", "base64-js": "^1.1.2", "event-target-shim": "^5.0.1", - "flow-enums-runtime": "^0.0.6", "invariant": "^2.2.4", "jest-environment-node": "^29.2.1", "jsc-android": "^250230.2.1", diff --git a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js index 3c341eb0253abf..01f7a2c7000799 100644 --- a/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js +++ b/packages/rn-tester/js/examples/TurboModule/SampleTurboModuleExample.js @@ -9,7 +9,6 @@ */ import NativeSampleTurboModule from 'react-native/Libraries/TurboModule/samples/NativeSampleTurboModule'; -import {EnumInt} from 'react-native/Libraries/TurboModule/samples/NativeSampleTurboModule'; import type {RootTag} from 'react-native/Libraries/ReactNative/RootTag'; import { StyleSheet, @@ -58,10 +57,6 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { getConstants: () => NativeSampleTurboModule.getConstants(), voidFunc: () => NativeSampleTurboModule.voidFunc(), getBool: () => NativeSampleTurboModule.getBool(true), - getEnum: () => - NativeSampleTurboModule.getEnum - ? NativeSampleTurboModule.getEnum(EnumInt.A) - : null, getNumber: () => NativeSampleTurboModule.getNumber(99.95), getString: () => NativeSampleTurboModule.getString('Hello'), getArray: () => @@ -85,7 +80,6 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { | 'callback' | 'getArray' | 'getBool' - | 'getEnum' | 'getConstants' | 'getNumber' | 'getObject' @@ -126,7 +120,6 @@ class SampleTurboModuleExample extends React.Component<{||}, State> { | 'callback' | 'getArray' | 'getBool' - | 'getEnum' | 'getConstants' | 'getNumber' | 'getObject' diff --git a/yarn.lock b/yarn.lock index e135844fa43317..740f4c15920f8f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4909,11 +4909,6 @@ flow-bin@^0.190.1: resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.190.1.tgz#59ccbc9aaa2515fe32acc66117a05e7ef6a11061" integrity sha512-5c9/6eEkMTTfdNuK2WwssrKfsUXKMUXlZVJZnrlWiqJpDSVc70/Smwyi9sXict9k/oq0f+Mo5wVH0d7peBYREg== -flow-enums-runtime@^0.0.6: - version "0.0.6" - resolved "https://registry.yarnpkg.com/flow-enums-runtime/-/flow-enums-runtime-0.0.6.tgz#5bb0cd1b0a3e471330f4d109039b7eba5cb3e787" - integrity sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw== - flow-parser@0.*, flow-parser@^0.185.0: version "0.185.0" resolved "https://registry.yarnpkg.com/flow-parser/-/flow-parser-0.185.0.tgz#56bde60805bad19b2934ebfc50c9485e5c5424f9" From 8422c5315caf5cf696791a5ad49ed0fbd37ef9df Mon Sep 17 00:00:00 2001 From: Lorenzo Sciandra Date: Wed, 26 Oct 2022 06:42:50 -0700 Subject: [PATCH 036/169] chore(deps): add wanted dependencies to remove yarn warnings (#35088) Summary: I wanted to start working on a thing but this barrage of warnings was very annoying so ended up doing this instead: a very small PR to take care of some warnings during yarn install. It doesn't change anything (the versions are the ones already used all around the repo), just makes yarn happier. Also, while doing that I found a dependency that was lying there unused for 2 years so took care of it. ## Changelog [General] [Fixed] - add wanted dependencies to remove yarn warnings Pull Request resolved: https://github.com/facebook/react-native/pull/35088 Test Plan: ### Before Screenshot 2022-10-26 at 10 53 32 ### After Screenshot 2022-10-26 at 10 52 19 Reviewed By: jacdebug Differential Revision: D40716713 Pulled By: robhogan fbshipit-source-id: eeb95a91c6cdf37edfe868fefe4ba04aebe500ec --- packages/hermes-inspector-msggen/package.json | 1 + packages/react-native-bots/package.json | 1 + packages/react-native-codegen/package.json | 1 + repo-config/package.json | 1 - yarn.lock | 4 ---- 5 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index cd9d385f72fa4a..68b2d0f949ce02 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -18,6 +18,7 @@ }, "devDependencies": { "@babel/cli": "^7.14.0", + "@babel/core": "^7.14.0", "@babel/preset-env": "^7.14.0", "@babel/preset-flow": "^7.14.0", "jest": "^29.2.1" diff --git a/packages/react-native-bots/package.json b/packages/react-native-bots/package.json index 563c64e5a5749f..a4a01050722809 100644 --- a/packages/react-native-bots/package.json +++ b/packages/react-native-bots/package.json @@ -5,6 +5,7 @@ "devDependencies": { "@seadub/danger-plugin-eslint": "^3.0.2", "danger": "^11.0.2", + "eslint": "^8.19.0", "lodash.includes": "^4.3.0", "minimatch": "^3.0.4" }, diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 99bb30580ae3bb..6a25c97458b303 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -33,6 +33,7 @@ "@babel/plugin-transform-async-to-generator": "^7.0.0", "@babel/plugin-transform-destructuring": "^7.0.0", "@babel/plugin-transform-flow-strip-types": "^7.0.0", + "@babel/preset-env": "^7.14.0", "chalk": "^4.0.0", "glob": "^7.1.1", "invariant": "^2.2.4", diff --git a/repo-config/package.json b/repo-config/package.json index 80b534f72751a0..33c5ddd27c021b 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -16,7 +16,6 @@ "@definitelytyped/dtslint": "^0.0.127", "@react-native-community/eslint-plugin": "*", "@react-native/eslint-plugin-specs": "^0.71.0", - "@reactions/component": "^2.0.2", "@types/react": "^18.0.18", "@typescript-eslint/parser": "^5.30.5", "async": "^3.2.2", diff --git a/yarn.lock b/yarn.lock index 740f4c15920f8f..729de3ecd729d8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2637,10 +2637,6 @@ prompts "^2.4.0" semver "^6.3.0" -"@reactions/component@^2.0.2": - version "2.0.2" - resolved "https://registry.yarnpkg.com/@reactions/component/-/component-2.0.2.tgz#40f8c1c2c37baabe57a0c944edb9310dc1ec6642" - "@seadub/danger-plugin-eslint@^3.0.2": version "3.0.2" resolved "https://registry.yarnpkg.com/@seadub/danger-plugin-eslint/-/danger-plugin-eslint-3.0.2.tgz#9a51d9f1a103a274264c30212234001de0b417c1" From cf5addf423b346dd43204f676c42f0a428f9af9c Mon Sep 17 00:00:00 2001 From: Benny Singer Date: Wed, 26 Oct 2022 07:22:28 -0700 Subject: [PATCH 037/169] Revert D40716713: chore(deps): add wanted dependencies to remove yarn warnings Differential Revision: D40716713 (https://github.com/facebook/react-native/commit/8422c5315caf5cf696791a5ad49ed0fbd37ef9df) Original commit changeset: eeb95a91c6cd Original Phabricator Diff: D40716713 (https://github.com/facebook/react-native/commit/8422c5315caf5cf696791a5ad49ed0fbd37ef9df) fbshipit-source-id: e85f111e7da0381e09f8a23d3bd0d553b3a7c4a9 --- packages/hermes-inspector-msggen/package.json | 1 - packages/react-native-bots/package.json | 1 - packages/react-native-codegen/package.json | 1 - repo-config/package.json | 1 + yarn.lock | 4 ++++ 5 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index 68b2d0f949ce02..cd9d385f72fa4a 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -18,7 +18,6 @@ }, "devDependencies": { "@babel/cli": "^7.14.0", - "@babel/core": "^7.14.0", "@babel/preset-env": "^7.14.0", "@babel/preset-flow": "^7.14.0", "jest": "^29.2.1" diff --git a/packages/react-native-bots/package.json b/packages/react-native-bots/package.json index a4a01050722809..563c64e5a5749f 100644 --- a/packages/react-native-bots/package.json +++ b/packages/react-native-bots/package.json @@ -5,7 +5,6 @@ "devDependencies": { "@seadub/danger-plugin-eslint": "^3.0.2", "danger": "^11.0.2", - "eslint": "^8.19.0", "lodash.includes": "^4.3.0", "minimatch": "^3.0.4" }, diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 6a25c97458b303..99bb30580ae3bb 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -33,7 +33,6 @@ "@babel/plugin-transform-async-to-generator": "^7.0.0", "@babel/plugin-transform-destructuring": "^7.0.0", "@babel/plugin-transform-flow-strip-types": "^7.0.0", - "@babel/preset-env": "^7.14.0", "chalk": "^4.0.0", "glob": "^7.1.1", "invariant": "^2.2.4", diff --git a/repo-config/package.json b/repo-config/package.json index 33c5ddd27c021b..80b534f72751a0 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -16,6 +16,7 @@ "@definitelytyped/dtslint": "^0.0.127", "@react-native-community/eslint-plugin": "*", "@react-native/eslint-plugin-specs": "^0.71.0", + "@reactions/component": "^2.0.2", "@types/react": "^18.0.18", "@typescript-eslint/parser": "^5.30.5", "async": "^3.2.2", diff --git a/yarn.lock b/yarn.lock index 729de3ecd729d8..740f4c15920f8f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2637,6 +2637,10 @@ prompts "^2.4.0" semver "^6.3.0" +"@reactions/component@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@reactions/component/-/component-2.0.2.tgz#40f8c1c2c37baabe57a0c944edb9310dc1ec6642" + "@seadub/danger-plugin-eslint@^3.0.2": version "3.0.2" resolved "https://registry.yarnpkg.com/@seadub/danger-plugin-eslint/-/danger-plugin-eslint-3.0.2.tgz#9a51d9f1a103a274264c30212234001de0b417c1" From 925e81ab86c9807b66d405d914e857b978b194fd Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Wed, 26 Oct 2022 08:17:49 -0700 Subject: [PATCH 038/169] Rewrite of ScrollViewStickyHeader for concurrent rendering Summary: changelog: [general][Added] - Concurrent rendering safe implementation of ScrollViewStickyHeader This is a re-land of ScrollViewStickyHeader from Kacie Bawiec. Reviewed By: yungsters Differential Revision: D40380217 fbshipit-source-id: 60dc86086a4d9d97eef71c4ed2e26536f7e72889 --- .../ScrollView/ScrollViewStickyHeader.js | 507 +++++++++--------- 1 file changed, 241 insertions(+), 266 deletions(-) diff --git a/Libraries/Components/ScrollView/ScrollViewStickyHeader.js b/Libraries/Components/ScrollView/ScrollViewStickyHeader.js index 4a445dc53d562b..6b42d2e63dad2a 100644 --- a/Libraries/Components/ScrollView/ScrollViewStickyHeader.js +++ b/Libraries/Components/ScrollView/ScrollViewStickyHeader.js @@ -4,28 +4,24 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @flow + * @flow strict-local * @format */ import type {LayoutEvent} from '../../Types/CoreEventTypes'; -import AnimatedImplementation from '../../Animated/AnimatedImplementation'; -import AnimatedAddition from '../../Animated/nodes/AnimatedAddition'; -import AnimatedDiffClamp from '../../Animated/nodes/AnimatedDiffClamp'; -import AnimatedNode from '../../Animated/nodes/AnimatedNode'; +import Animated from '../../Animated/Animated'; import StyleSheet from '../../StyleSheet/StyleSheet'; import Platform from '../../Utilities/Platform'; -import View from '../View/View'; +import useMergeRefs from '../../Utilities/useMergeRefs'; import * as React from 'react'; - -const AnimatedView = AnimatedImplementation.createAnimatedComponent(View); +import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; export type Props = $ReadOnly<{ - children?: React.Element, + children?: React.Element<$FlowFixMe>, nextHeaderLayoutY: ?number, onLayout: (event: LayoutEvent) => void, - scrollAnimatedValue: AnimatedImplementation.Value, + scrollAnimatedValue: Animated.Value, // Will cause sticky headers to stick at the bottom of the ScrollView instead // of the top. inverted: ?boolean, @@ -35,291 +31,270 @@ export type Props = $ReadOnly<{ hiddenOnScroll?: ?boolean, }>; -type State = { - measured: boolean, - layoutY: number, - layoutHeight: number, - nextHeaderLayoutY: ?number, - translateY: ?number, +type Instance = { + ...React.ElementRef, + setNextHeaderY: number => void, ... }; -class ScrollViewStickyHeader extends React.Component { - state: State = { - measured: false, - layoutY: 0, - layoutHeight: 0, - nextHeaderLayoutY: this.props.nextHeaderLayoutY, - translateY: null, - }; - - _translateY: ?AnimatedNode = null; - _shouldRecreateTranslateY: boolean = true; - _haveReceivedInitialZeroTranslateY: boolean = true; - _ref: any; // TODO T53738161: flow type this, and the whole file +const ScrollViewStickyHeaderWithForwardedRef: React.AbstractComponent< + Props, + Instance, +> = React.forwardRef(function ScrollViewStickyHeader(props, forwardedRef) { + const { + inverted, + scrollViewHeight, + hiddenOnScroll, + scrollAnimatedValue, + nextHeaderLayoutY: _nextHeaderLayoutY, + } = props; - // Fabric-only: - _timer: ?TimeoutID; - _animatedValueListenerId: string; - _animatedValueListener: (valueObject: $ReadOnly<{|value: number|}>) => void; - _debounceTimeout: number = Platform.OS === 'android' ? 15 : 64; + const [measured, setMeasured] = useState(false); + const [layoutY, setLayoutY] = useState(0); + const [layoutHeight, setLayoutHeight] = useState(0); + const [translateY, setTranslateY] = useState(null); + const [nextHeaderLayoutY, setNextHeaderLayoutY] = + useState(_nextHeaderLayoutY); + const [isFabric, setIsFabric] = useState(false); - setNextHeaderY: (y: number) => void = (y: number): void => { - this._shouldRecreateTranslateY = true; - this.setState({nextHeaderLayoutY: y}); + const callbackRef = (ref: Instance | null): void => { + if (ref == null) { + return; + } + ref.setNextHeaderY = value => { + setNextHeaderLayoutY(value); + }; + // Avoid dot notation because at Meta, private properties are obfuscated. + // $FlowFixMe[prop-missing] + const _internalInstanceHandler = ref['_internalInstanceHandle']; // eslint-disable-line dot-notation + setIsFabric(Boolean(_internalInstanceHandler?.stateNode?.canonical)); }; + const ref: (React.ElementRef | null) => void = + // $FlowFixMe[incompatible-type] - Ref is mutated by `callbackRef`. + useMergeRefs(callbackRef, forwardedRef); - componentWillUnmount() { - if (this._translateY != null && this._animatedValueListenerId != null) { - this._translateY.removeListener(this._animatedValueListenerId); - } - if (this._timer) { - clearTimeout(this._timer); - } - } + const offset = useMemo( + () => + hiddenOnScroll === true + ? Animated.diffClamp( + scrollAnimatedValue + .interpolate({ + extrapolateLeft: 'clamp', + inputRange: [layoutY, layoutY + 1], + outputRange: ([0, 1]: Array), + }) + .interpolate({ + inputRange: [0, 1], + outputRange: ([0, -1]: Array), + }), + -layoutHeight, + 0, + ) + : null, + [scrollAnimatedValue, layoutHeight, layoutY, hiddenOnScroll], + ); - UNSAFE_componentWillReceiveProps(nextProps: Props) { - if ( - nextProps.scrollViewHeight !== this.props.scrollViewHeight || - nextProps.scrollAnimatedValue !== this.props.scrollAnimatedValue || - nextProps.inverted !== this.props.inverted - ) { - this._shouldRecreateTranslateY = true; - } - } + const [animatedTranslateY, setAnimatedTranslateY] = useState( + () => { + const inputRange: Array = [-1, 0]; + const outputRange: Array = [0, 0]; + const initialTranslateY = scrollAnimatedValue.interpolate({ + inputRange, + outputRange, + }); - updateTranslateListener( - translateY: AnimatedNode, - isFabric: boolean, - offset: AnimatedDiffClamp | null, - ) { - if (this._translateY != null && this._animatedValueListenerId != null) { - this._translateY.removeListener(this._animatedValueListenerId); - } - offset - ? (this._translateY = new AnimatedAddition(translateY, offset)) - : (this._translateY = translateY); + if (offset != null) { + return Animated.add(initialTranslateY, offset); + } + return initialTranslateY; + }, + ); - this._shouldRecreateTranslateY = false; + const _haveReceivedInitialZeroTranslateY = useRef(true); + const _timer = useRef(null); - if (!isFabric) { - return; + useEffect(() => { + if (translateY !== 0 && translateY != null) { + _haveReceivedInitialZeroTranslateY.current = false; } + }, [translateY]); - if (!this._animatedValueListener) { - // This is called whenever the (Interpolated) Animated Value - // updates, which is several times per frame during scrolling. - // To ensure that the Fabric ShadowTree has the most recent - // translate style of this node, we debounce the value and then - // pass it through to the underlying node during render. - // This is: - // 1. Only an issue in Fabric. - // 2. Worse in Android than iOS. In Android, but not iOS, you - // can touch and move your finger slightly and still trigger - // a "tap" event. In iOS, moving will cancel the tap in - // both Fabric and non-Fabric. On Android when you move - // your finger, the hit-detection moves from the Android - // platform to JS, so we need the ShadowTree to have knowledge - // of the current position. - this._animatedValueListener = ({value}) => { - // When the AnimatedInterpolation is recreated, it always initializes - // to a value of zero and emits a value change of 0 to its listeners. - if (value === 0 && !this._haveReceivedInitialZeroTranslateY) { - this._haveReceivedInitialZeroTranslateY = true; - return; - } - if (this._timer) { - clearTimeout(this._timer); + // This is called whenever the (Interpolated) Animated Value + // updates, which is several times per frame during scrolling. + // To ensure that the Fabric ShadowTree has the most recent + // translate style of this node, we debounce the value and then + // pass it through to the underlying node during render. + // This is: + // 1. Only an issue in Fabric. + // 2. Worse in Android than iOS. In Android, but not iOS, you + // can touch and move your finger slightly and still trigger + // a "tap" event. In iOS, moving will cancel the tap in + // both Fabric and non-Fabric. On Android when you move + // your finger, the hit-detection moves from the Android + // platform to JS, so we need the ShadowTree to have knowledge + // of the current position. + const animatedValueListener = useCallback( + ({value}) => { + const _debounceTimeout: number = Platform.OS === 'android' ? 15 : 64; + // When the AnimatedInterpolation is recreated, it always initializes + // to a value of zero and emits a value change of 0 to its listeners. + if (value === 0 && !_haveReceivedInitialZeroTranslateY.current) { + _haveReceivedInitialZeroTranslateY.current = true; + return; + } + if (_timer.current != null) { + clearTimeout(_timer.current); + } + _timer.current = setTimeout(() => { + if (value !== translateY) { + setTranslateY(value); } - this._timer = setTimeout(() => { - if (value !== this.state.translateY) { - this.setState({ - translateY: value, - }); - } - }, this._debounceTimeout); - }; - } - if (this.state.translateY !== 0 && this.state.translateY != null) { - this._haveReceivedInitialZeroTranslateY = false; - } - this._animatedValueListenerId = translateY.addListener( - this._animatedValueListener, - ); - } + }, _debounceTimeout); + }, + [translateY], + ); - _onLayout = (event: any) => { - const layoutY = event.nativeEvent.layout.y; - const layoutHeight = event.nativeEvent.layout.height; - const measured = true; + useEffect(() => { + const inputRange: Array = [-1, 0]; + const outputRange: Array = [0, 0]; - if ( - layoutY !== this.state.layoutY || - layoutHeight !== this.state.layoutHeight || - measured !== this.state.measured - ) { - this._shouldRecreateTranslateY = true; + if (measured) { + if (inverted === true) { + // The interpolation looks like: + // - Negative scroll: no translation + // - `stickStartPoint` is the point at which the header will start sticking. + // It is calculated using the ScrollView viewport height so it is a the bottom. + // - Headers that are in the initial viewport will never stick, `stickStartPoint` + // will be negative. + // - From 0 to `stickStartPoint` no translation. This will cause the header + // to scroll normally until it reaches the top of the scroll view. + // - From `stickStartPoint` to when the next header y hits the bottom edge of the header: translate + // equally to scroll. This will cause the header to stay at the top of the scroll view. + // - Past the collision with the next header y: no more translation. This will cause the + // header to continue scrolling up and make room for the next sticky header. + // In the case that there is no next header just translate equally to + // scroll indefinitely. + if (scrollViewHeight != null) { + const stickStartPoint = layoutY + layoutHeight - scrollViewHeight; + if (stickStartPoint > 0) { + inputRange.push(stickStartPoint); + outputRange.push(0); + inputRange.push(stickStartPoint + 1); + outputRange.push(1); + // If the next sticky header has not loaded yet (probably windowing) or is the last + // we can just keep it sticked forever. + const collisionPoint = + (nextHeaderLayoutY || 0) - layoutHeight - scrollViewHeight; + if (collisionPoint > stickStartPoint) { + inputRange.push(collisionPoint, collisionPoint + 1); + outputRange.push( + collisionPoint - stickStartPoint, + collisionPoint - stickStartPoint, + ); + } + } + } + } else { + // The interpolation looks like: + // - Negative scroll: no translation + // - From 0 to the y of the header: no translation. This will cause the header + // to scroll normally until it reaches the top of the scroll view. + // - From header y to when the next header y hits the bottom edge of the header: translate + // equally to scroll. This will cause the header to stay at the top of the scroll view. + // - Past the collision with the next header y: no more translation. This will cause the + // header to continue scrolling up and make room for the next sticky header. + // In the case that there is no next header just translate equally to + // scroll indefinitely. + inputRange.push(layoutY); + outputRange.push(0); + // If the next sticky header has not loaded yet (probably windowing) or is the last + // we can just keep it sticked forever. + const collisionPoint = (nextHeaderLayoutY || 0) - layoutHeight; + if (collisionPoint >= layoutY) { + inputRange.push(collisionPoint, collisionPoint + 1); + outputRange.push(collisionPoint - layoutY, collisionPoint - layoutY); + } else { + inputRange.push(layoutY + 1); + outputRange.push(1); + } + } } - this.setState({ - measured, - layoutY, - layoutHeight, + let newAnimatedTranslateY: Animated.Node = scrollAnimatedValue.interpolate({ + inputRange, + outputRange, }); - this.props.onLayout(event); - const child = React.Children.only(this.props.children); - if (child.props.onCellLayout) { - child.props.onCellLayout(event, child.props.cellKey, child.props.index); - } else if (child.props.onLayout) { - child.props.onLayout(event); + if (offset != null) { + newAnimatedTranslateY = Animated.add(newAnimatedTranslateY, offset); } - }; - /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ - _setComponentRef = ref => { - this._ref = ref; - }; + // add the event listener + let animatedListenerId; + if (isFabric) { + animatedListenerId = newAnimatedTranslateY.addListener( + animatedValueListener, + ); + } - render(): React.Node { - // Fabric Detection - const isFabric = !!( - // An internal transform mangles variables with leading "_" as private. - // eslint-disable-next-line dot-notation - (this._ref && this._ref['_internalInstanceHandle']?.stateNode?.canonical) - ); - // Initially and in the case of updated props or layout, we - // recreate this interpolated value. Otherwise, we do not recreate - // when there are state changes. - if (this._shouldRecreateTranslateY) { - const {inverted, scrollViewHeight} = this.props; - const {measured, layoutHeight, layoutY, nextHeaderLayoutY} = this.state; - const inputRange: Array = [-1, 0]; - const outputRange: Array = [0, 0]; + setAnimatedTranslateY(newAnimatedTranslateY); - if (measured) { - if (inverted) { - // The interpolation looks like: - // - Negative scroll: no translation - // - `stickStartPoint` is the point at which the header will start sticking. - // It is calculated using the ScrollView viewport height so it is a the bottom. - // - Headers that are in the initial viewport will never stick, `stickStartPoint` - // will be negative. - // - From 0 to `stickStartPoint` no translation. This will cause the header - // to scroll normally until it reaches the top of the scroll view. - // - From `stickStartPoint` to when the next header y hits the bottom edge of the header: translate - // equally to scroll. This will cause the header to stay at the top of the scroll view. - // - Past the collision with the next header y: no more translation. This will cause the - // header to continue scrolling up and make room for the next sticky header. - // In the case that there is no next header just translate equally to - // scroll indefinitely. - if (scrollViewHeight != null) { - const stickStartPoint = layoutY + layoutHeight - scrollViewHeight; - if (stickStartPoint > 0) { - inputRange.push(stickStartPoint); - outputRange.push(0); - inputRange.push(stickStartPoint + 1); - outputRange.push(1); - // If the next sticky header has not loaded yet (probably windowing) or is the last - // we can just keep it sticked forever. - const collisionPoint = - (nextHeaderLayoutY || 0) - layoutHeight - scrollViewHeight; - if (collisionPoint > stickStartPoint) { - inputRange.push(collisionPoint, collisionPoint + 1); - outputRange.push( - collisionPoint - stickStartPoint, - collisionPoint - stickStartPoint, - ); - } - } - } - } else { - // The interpolation looks like: - // - Negative scroll: no translation - // - From 0 to the y of the header: no translation. This will cause the header - // to scroll normally until it reaches the top of the scroll view. - // - From header y to when the next header y hits the bottom edge of the header: translate - // equally to scroll. This will cause the header to stay at the top of the scroll view. - // - Past the collision with the next header y: no more translation. This will cause the - // header to continue scrolling up and make room for the next sticky header. - // In the case that there is no next header just translate equally to - // scroll indefinitely. - inputRange.push(layoutY); - outputRange.push(0); - // If the next sticky header has not loaded yet (probably windowing) or is the last - // we can just keep it sticked forever. - const collisionPoint = (nextHeaderLayoutY || 0) - layoutHeight; - if (collisionPoint >= layoutY) { - inputRange.push(collisionPoint, collisionPoint + 1); - outputRange.push( - collisionPoint - layoutY, - collisionPoint - layoutY, - ); - } else { - inputRange.push(layoutY + 1); - outputRange.push(1); - } - } + // clean up the event listener and timer + return () => { + if (animatedListenerId) { + newAnimatedTranslateY.removeListener(animatedListenerId); + } + if (_timer.current != null) { + clearTimeout(_timer.current); } + }; + }, [nextHeaderLayoutY, measured, layoutHeight, layoutY, scrollViewHeight, scrollAnimatedValue, inverted, offset, animatedValueListener, isFabric]); - this.updateTranslateListener( - this.props.scrollAnimatedValue.interpolate({ - inputRange, - outputRange, - }), - isFabric, - this.props.hiddenOnScroll - ? new AnimatedDiffClamp( - this.props.scrollAnimatedValue - .interpolate({ - extrapolateLeft: 'clamp', - inputRange: [layoutY, layoutY + 1], - outputRange: [0, 1], - }) - .interpolate({ - inputRange: [0, 1], - outputRange: [0, -1], - }), - -this.state.layoutHeight, - 0, - ) - : null, - ); + const _onLayout = (event: LayoutEvent) => { + setLayoutY(event.nativeEvent.layout.y); + setLayoutHeight(event.nativeEvent.layout.height); + setMeasured(true); + + props.onLayout(event); + const child = React.Children.only(props.children); + if (child.props.onLayout) { + child.props.onLayout(event); } + }; - const child = React.Children.only(this.props.children); + const child = React.Children.only(props.children); - // TODO T68319535: remove this if NativeAnimated is rewritten for Fabric - const passthroughAnimatedPropExplicitValues = - isFabric && this.state.translateY != null - ? { - style: {transform: [{translateY: this.state.translateY}]}, - } - : null; + // TODO T68319535: remove this if NativeAnimated is rewritten for Fabric + const passthroughAnimatedPropExplicitValues = + isFabric && translateY != null + ? { + style: {transform: [{translateY: translateY}]}, + } + : null; - return ( - - {React.cloneElement(child, { - style: styles.fill, // We transfer the child style to the wrapper. - onLayout: undefined, // we call this manually through our this._onLayout - })} - - ); - } -} + return ( + /* $FlowFixMe[prop-missing] passthroughAnimatedPropExplicitValues isn't properly + included in the Animated.View flow type. */ + + {React.cloneElement(child, { + style: styles.fill, // We transfer the child style to the wrapper. + onLayout: undefined, // we call this manually through our this._onLayout + })} + + ); +}); const styles = StyleSheet.create({ header: { @@ -331,4 +306,4 @@ const styles = StyleSheet.create({ }, }); -module.exports = ScrollViewStickyHeader; +export default ScrollViewStickyHeaderWithForwardedRef; From cba56eadd273a11d3d7c14ac4b31f1c050ce710a Mon Sep 17 00:00:00 2001 From: dhruvtailor7 Date: Wed, 26 Oct 2022 10:02:01 -0700 Subject: [PATCH 039/169] Extract `getConfigType` function to `parsers/utils.js` (#35035) Summary: This PR is part of https://github.com/facebook/react-native/issues/34872. This PR contains two changes, extracting the visitor object and then factoring out the `getConfigType()` function to the `parsers/utils.js` file. Then we can reuse the same function in both flow and typescript by passing the extracted visitor object. ## Changelog [Internal] [Changed] - Extract visitor object in the same file and factor out `getConfigType()` to `parsers/utils.js`. Pull Request resolved: https://github.com/facebook/react-native/pull/35035 Test Plan: Output of `yarn jest react-native-codegen` ensures all passed test cases Reviewed By: cortinico Differential Revision: D40548855 Pulled By: cipolleschi fbshipit-source-id: 310b8565322a4e4800a3fffc67479a9dfa45d620 --- .../src/parsers/flow/index.js | 40 +++++-------------- .../src/parsers/typescript/index.js | 40 +++++-------------- .../react-native-codegen/src/parsers/utils.js | 31 ++++++++++++++ 3 files changed, 51 insertions(+), 60 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/flow/index.js b/packages/react-native-codegen/src/parsers/flow/index.js index 3b835f7747289f..af7309229a2da7 100644 --- a/packages/react-native-codegen/src/parsers/flow/index.js +++ b/packages/react-native-codegen/src/parsers/flow/index.js @@ -15,52 +15,32 @@ import type {SchemaType} from '../../CodegenSchema.js'; // $FlowFixMe[untyped-import] there's no flowtype flow-parser const flowParser = require('flow-parser'); const fs = require('fs'); -const {visit, buildSchemaFromConfigType} = require('../utils'); +const {buildSchemaFromConfigType, getConfigType} = require('../utils'); const {buildComponentSchema} = require('./components'); const {wrapComponentSchema} = require('./components/schema'); const {buildModuleSchema} = require('./modules'); const {isModuleRegistryCall} = require('./utils'); -function getConfigType( - // TODO(T71778680): Flow-type this node. - ast: $FlowFixMe, -): 'module' | 'component' | 'none' { - let isComponent = false; - let isModule = false; - - visit(ast, { - CallExpression(node) { +function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { + return { + CallExpression(node: $FlowFixMe) { if ( node.callee.type === 'Identifier' && node.callee.name === 'codegenNativeComponent' ) { - isComponent = true; + infoMap.isComponent = true; } if (isModuleRegistryCall(node)) { - isModule = true; + infoMap.isModule = true; } }, - InterfaceExtends(node) { + InterfaceExtends(node: $FlowFixMe) { if (node.id.name === 'TurboModule') { - isModule = true; + infoMap.isModule = true; } }, - }); - - if (isModule && isComponent) { - throw new Error( - 'Found type extending "TurboModule" and exported "codegenNativeComponent" declaration in one file. Split them into separated files.', - ); - } - - if (isModule) { - return 'module'; - } else if (isComponent) { - return 'component'; - } else { - return 'none'; - } + }; } function buildSchema(contents: string, filename: ?string): SchemaType { @@ -73,7 +53,7 @@ function buildSchema(contents: string, filename: ?string): SchemaType { } const ast = flowParser.parse(contents, {enums: true}); - const configType = getConfigType(ast); + const configType = getConfigType(ast, Visitor); return buildSchemaFromConfigType( configType, diff --git a/packages/react-native-codegen/src/parsers/typescript/index.js b/packages/react-native-codegen/src/parsers/typescript/index.js index c65cc538b14696..2c6c1d4625e58d 100644 --- a/packages/react-native-codegen/src/parsers/typescript/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/index.js @@ -14,59 +14,39 @@ import type {SchemaType} from '../../CodegenSchema.js'; const babelParser = require('@babel/parser'); const fs = require('fs'); -const {visit, buildSchemaFromConfigType} = require('../utils'); +const {buildSchemaFromConfigType, getConfigType} = require('../utils'); const {buildComponentSchema} = require('./components'); const {wrapComponentSchema} = require('./components/schema'); const {buildModuleSchema} = require('./modules'); const {isModuleRegistryCall} = require('./utils'); -function getConfigType( - // TODO(T108222691): Use flow-types for @babel/parser - ast: $FlowFixMe, -): 'module' | 'component' | 'none' { - let isComponent = false; - let isModule = false; - - visit(ast, { - CallExpression(node) { +function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { + return { + CallExpression(node: $FlowFixMe) { if ( node.callee.type === 'Identifier' && node.callee.name === 'codegenNativeComponent' ) { - isComponent = true; + infoMap.isComponent = true; } if (isModuleRegistryCall(node)) { - isModule = true; + infoMap.isModule = true; } }, - TSInterfaceDeclaration(node) { + TSInterfaceDeclaration(node: $FlowFixMe) { if ( Array.isArray(node.extends) && node.extends.some( extension => extension.expression.name === 'TurboModule', ) ) { - isModule = true; + infoMap.isModule = true; } }, - }); - - if (isModule && isComponent) { - throw new Error( - 'Found type extending "TurboModule" and exported "codegenNativeComponent" declaration in one file. Split them into separated files.', - ); - } - - if (isModule) { - return 'module'; - } else if (isComponent) { - return 'component'; - } else { - return 'none'; - } + }; } function buildSchema(contents: string, filename: ?string): SchemaType { @@ -83,7 +63,7 @@ function buildSchema(contents: string, filename: ?string): SchemaType { plugins: ['typescript'], }).program; - const configType = getConfigType(ast); + const configType = getConfigType(ast, Visitor); return buildSchemaFromConfigType( configType, diff --git a/packages/react-native-codegen/src/parsers/utils.js b/packages/react-native-codegen/src/parsers/utils.js index 49ed1a1dba433c..a6fad22822e208 100644 --- a/packages/react-native-codegen/src/parsers/utils.js +++ b/packages/react-native-codegen/src/parsers/utils.js @@ -185,7 +185,38 @@ function buildSchemaFromConfigType( } } +function getConfigType( + // TODO(T71778680): Flow-type this node. + ast: $FlowFixMe, + Visitor: ({isComponent: boolean, isModule: boolean}) => { + [type: string]: (node: $FlowFixMe) => void, + }, +): 'module' | 'component' | 'none' { + let infoMap = { + isComponent: false, + isModule: false, + }; + + visit(ast, Visitor(infoMap)); + + const {isModule, isComponent} = infoMap; + if (isModule && isComponent) { + throw new Error( + 'Found type extending "TurboModule" and exported "codegenNativeComponent" declaration in one file. Split them into separated files.', + ); + } + + if (isModule) { + return 'module'; + } else if (isComponent) { + return 'component'; + } else { + return 'none'; + } +} + module.exports = { + getConfigType, extractNativeModuleName, createParserErrorCapturer, verifyPlatforms, From 0627cd69cd39a9f88df24e4d8d883e552d88dfe8 Mon Sep 17 00:00:00 2001 From: youedd Date: Wed, 26 Oct 2022 10:02:01 -0700 Subject: [PATCH 040/169] Refactor translate UniontypeAnnotation (#35050) Summary: Part of https://github.com/facebook/react-native/issues/34872 > [Assigned to youedd] This task is more advanced than the others Create a function to unify the [unionType](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/flow/modules/index.js#L372-L396) and the [TSUnionType](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/typescript/modules/index.js#L407-L431). This task may share some logic from the previous task. The function should accept a ParserType parameter to implement the proper logic to extract the memberType variable. Ideally, we should create a couple of supporting functions to implement those logics. ## Changelog [Internal] [Changed] - Refactor translate UniontypeAnnotation Pull Request resolved: https://github.com/facebook/react-native/pull/35050 Test Plan: `yarn jest react-native-codegen` ![image](https://user-images.githubusercontent.com/19575877/197334084-2daeed7e-8e87-4140-b8c3-07f2de3f0496.png) Reviewed By: cortinico Differential Revision: D40637299 Pulled By: cipolleschi fbshipit-source-id: 1490001a3398c3af79d465c40de3c3687f058523 --- .../parsers/__tests__/parsers-commons-test.js | 436 +++++++++++++++++- .../src/parsers/errors.js | 4 +- .../src/parsers/flow/modules/index.js | 30 +- .../src/parsers/parsers-commons.js | 58 ++- .../src/parsers/typescript/modules/index.js | 31 +- 5 files changed, 509 insertions(+), 50 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js index 35b1173c931341..0aab57937641d9 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js @@ -12,12 +12,15 @@ 'use-strict'; import {assertGenericTypeAnnotationHasExactlyOneTypeParameter} from '../parsers-commons'; - +import type {ParserType} from '../errors'; const { wrapNullable, unwrapNullable, emitMixedTypeAnnotation, + emitUnionTypeAnnotation, } = require('../parsers-commons.js'); +const {UnsupportedUnionTypeAnnotationParserError} = require('../errors'); +import type {UnionTypeAnnotationMemberType} from '../../CodegenSchema'; describe('wrapNullable', () => { describe('when nullable is true', () => { @@ -230,3 +233,434 @@ describe('emitMixedTypeAnnotation', () => { }); }); }); + +describe('emitUnionTypeAnnotation', () => { + const hasteModuleName = 'SampleTurboModule'; + + describe('when language is flow', () => { + const language: ParserType = 'Flow'; + + describe('when members type is numeric', () => { + const typeAnnotation = { + type: 'UnionTypeAnnotation', + types: [ + {type: 'NumberLiteralTypeAnnotation'}, + {type: 'NumberLiteralTypeAnnotation'}, + ], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'NumberTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'NumberTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is string', () => { + const typeAnnotation = { + type: 'UnionTypeAnnotation', + types: [ + {type: 'StringLiteralTypeAnnotation'}, + {type: 'StringLiteralTypeAnnotation'}, + ], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'StringTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'StringTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is object', () => { + const typeAnnotation = { + type: 'UnionTypeAnnotation', + types: [{type: 'ObjectTypeAnnotation'}, {type: 'ObjectTypeAnnotation'}], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'ObjectTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'ObjectTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is mixed', () => { + const typeAnnotation = { + type: 'UnionTypeAnnotation', + types: [ + {type: 'NumberLiteralTypeAnnotation'}, + {type: 'StringLiteralTypeAnnotation'}, + {type: 'ObjectTypeAnnotation'}, + ], + }; + const unionTypes: UnionTypeAnnotationMemberType[] = [ + 'NumberTypeAnnotation', + 'StringTypeAnnotation', + 'ObjectTypeAnnotation', + ]; + describe('when nullable is true', () => { + it('throws an excpetion', () => { + const expected = new UnsupportedUnionTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + unionTypes, + language, + ); + + expect(() => { + emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + }).toThrow(expected); + }); + }); + + describe('when nullable is false', () => { + it('throws an excpetion', () => { + const expected = new UnsupportedUnionTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + unionTypes, + language, + ); + + expect(() => { + emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + }).toThrow(expected); + }); + }); + }); + }); + + describe('when language is typescript', () => { + const language: ParserType = 'TypeScript'; + + describe('when members type is numeric', () => { + const typeAnnotation = { + type: 'TSUnionType', + types: [ + { + type: 'TSLiteralType', + literal: {type: 'NumericLiteral'}, + }, + { + type: 'TSLiteralType', + literal: {type: 'NumericLiteral'}, + }, + ], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'NumberTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'NumberTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is string', () => { + const typeAnnotation = { + type: 'TSUnionType', + types: [ + { + type: 'TSLiteralType', + literal: {type: 'StringLiteral'}, + }, + { + type: 'TSLiteralType', + literal: {type: 'StringLiteral'}, + }, + ], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'StringTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'StringTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is object', () => { + const typeAnnotation = { + type: 'TSUnionType', + types: [ + { + type: 'TSLiteralType', + }, + { + type: 'TSLiteralType', + }, + ], + }; + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'UnionTypeAnnotation', + memberType: 'ObjectTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + + const expected = { + type: 'UnionTypeAnnotation', + memberType: 'ObjectTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); + + describe('when members type is mixed', () => { + const typeAnnotation = { + type: 'TSUnionType', + types: [ + { + type: 'TSLiteralType', + literal: {type: 'NumericLiteral'}, + }, + { + type: 'TSLiteralType', + literal: {type: 'StringLiteral'}, + }, + { + type: 'TSLiteralType', + }, + ], + }; + const unionTypes = [ + 'NumberTypeAnnotation', + 'StringTypeAnnotation', + 'ObjectTypeAnnotation', + ]; + describe('when nullable is true', () => { + it('throws an excpetion', () => { + const expected = new UnsupportedUnionTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + unionTypes, + language, + ); + + expect(() => { + emitUnionTypeAnnotation( + true, + hasteModuleName, + typeAnnotation, + language, + ); + }).toThrow(expected); + }); + }); + + describe('when nullable is false', () => { + it('throws an excpetion', () => { + const expected = new UnsupportedUnionTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + unionTypes, + language, + ); + + expect(() => { + emitUnionTypeAnnotation( + false, + hasteModuleName, + typeAnnotation, + language, + ); + }).toThrow(expected); + }); + }); + }); + }); +}); diff --git a/packages/react-native-codegen/src/parsers/errors.js b/packages/react-native-codegen/src/parsers/errors.js index 3b85694a504f99..eab2dd36324af0 100644 --- a/packages/react-native-codegen/src/parsers/errors.js +++ b/packages/react-native-codegen/src/parsers/errors.js @@ -10,6 +10,8 @@ 'use strict'; +import type {UnionTypeAnnotationMemberType} from '../CodegenSchema'; + const invariant = require('invariant'); import type {Parser} from './parser'; export type ParserType = 'Flow' | 'TypeScript'; @@ -308,7 +310,7 @@ class UnsupportedUnionTypeAnnotationParserError extends ParserError { constructor( nativeModuleName: string, arrayElementTypeAST: $FlowFixMe, - types: string[], + types: UnionTypeAnnotationMemberType[], language: ParserType, ) { super( diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 747f9162c2823b..8cfd853d4fcbb2 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -38,6 +38,7 @@ const { wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, + emitUnionTypeAnnotation, } = require('../../parsers-commons'); const { emitBoolean, @@ -375,29 +376,12 @@ function translateTypeAnnotation( } case 'UnionTypeAnnotation': { if (cxxOnly) { - // Remap literal names - const unionTypes = typeAnnotation.types - .map( - item => - item.type - .replace('NumberLiteralTypeAnnotation', 'NumberTypeAnnotation') - .replace('StringLiteralTypeAnnotation', 'StringTypeAnnotation'), - // ObjectAnnotation is already 'correct' - ) - .filter((value, index, self) => self.indexOf(value) === index); - // Only support unionTypes of the same kind - if (unionTypes.length > 1) { - throw new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - } - return wrapNullable(nullable, { - type: 'UnionTypeAnnotation', - memberType: unionTypes[0], - }); + return emitUnionTypeAnnotation( + nullable, + hasteModuleName, + typeAnnotation, + language, + ); } // Fallthrough } diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js index 73b5061f0a9b80..eda3b3ef2990d3 100644 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ b/packages/react-native-codegen/src/parsers/parsers-commons.js @@ -16,8 +16,13 @@ import type { NativeModuleTypeAnnotation, Nullable, NativeModuleMixedTypeAnnotation, + UnionTypeAnnotationMemberType, + NativeModuleUnionTypeAnnotation, } from '../CodegenSchema.js'; -const {IncorrectlyParameterizedGenericParserError} = require('./errors'); +const { + IncorrectlyParameterizedGenericParserError, + UnsupportedUnionTypeAnnotationParserError, +} = require('./errors'); import type {ParserType} from './errors'; const invariant = require('invariant'); @@ -100,10 +105,61 @@ function emitMixedTypeAnnotation( }); } +function remapUnionTypeAnnotationMemberNames( + types: $FlowFixMe, + language: ParserType, +): UnionTypeAnnotationMemberType[] { + const remapLiteral = (item: $FlowFixMe) => { + if (language === 'Flow') { + return item.type + .replace('NumberLiteralTypeAnnotation', 'NumberTypeAnnotation') + .replace('StringLiteralTypeAnnotation', 'StringTypeAnnotation'); + } + + return item.literal + ? item.literal.type + .replace('NumericLiteral', 'NumberTypeAnnotation') + .replace('StringLiteral', 'StringTypeAnnotation') + : 'ObjectTypeAnnotation'; + }; + + return types + .map(remapLiteral) + .filter((value, index, self) => self.indexOf(value) === index); +} + +function emitUnionTypeAnnotation( + nullable: boolean, + hasteModuleName: string, + typeAnnotation: $FlowFixMe, + language: ParserType, +): Nullable { + const unionTypes = remapUnionTypeAnnotationMemberNames( + typeAnnotation.types, + language, + ); + + // Only support unionTypes of the same kind + if (unionTypes.length > 1) { + throw new UnsupportedUnionTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + unionTypes, + language, + ); + } + + return wrapNullable(nullable, { + type: 'UnionTypeAnnotation', + memberType: unionTypes[0], + }); +} + module.exports = { wrapModuleSchema, unwrapNullable, wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, + emitUnionTypeAnnotation, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 097a505f8898a8..9c6f6080faa54e 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -38,6 +38,7 @@ const { wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, + emitUnionTypeAnnotation, } = require('../../parsers-commons'); const { emitBoolean, @@ -60,7 +61,6 @@ const { UnsupportedTypeAnnotationParserError, UnsupportedFunctionParamTypeAnnotationParserError, UnsupportedEnumDeclarationParserError, - UnsupportedUnionTypeAnnotationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, IncorrectModuleRegistryCallArgumentTypeParserError, } = require('../../errors.js'); @@ -390,29 +390,12 @@ function translateTypeAnnotation( } case 'TSUnionType': { if (cxxOnly) { - // Remap literal names - const unionTypes = typeAnnotation.types - .map(item => - item.literal - ? item.literal.type - .replace('NumericLiteral', 'NumberTypeAnnotation') - .replace('StringLiteral', 'StringTypeAnnotation') - : 'ObjectTypeAnnotation', - ) - .filter((value, index, self) => self.indexOf(value) === index); - // Only support unionTypes of the same kind - if (unionTypes.length > 1) { - throw new UnsupportedUnionTypeAnnotationParserError( - hasteModuleName, - typeAnnotation, - unionTypes, - language, - ); - } - return wrapNullable(nullable, { - type: 'UnionTypeAnnotation', - memberType: unionTypes[0], - }); + return emitUnionTypeAnnotation( + nullable, + hasteModuleName, + typeAnnotation, + language, + ); } // Fallthrough } From 7d61b9d81a2b99b50a00ecd5f8ac91f85cdce8ce Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 26 Oct 2022 10:41:02 -0700 Subject: [PATCH 041/169] RNGP - Remove enableCodegenInApps and infer it from package.json (#35083) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35083 We don't need to `enableCodegenInApps` keys but we can instead rely on the existence of the `codegenConfig` key inside the `package.json` to decide if Codegen should run in App modules or not. Changelog: [Internal] [Changed] - RNGP - Remove enableCodegenInApps and infer it from package.json Reviewed By: cipolleschi Differential Revision: D40687079 fbshipit-source-id: cd4a6c67caa19c1d199ae75388a0551339f876a0 --- .../com/facebook/react/ReactExtension.kt | 7 --- .../kotlin/com/facebook/react/ReactPlugin.kt | 17 +++-- .../com/facebook/react/utils/PathUtils.kt | 14 +++++ .../com/facebook/react/utils/ProjectUtils.kt | 11 ++++ .../com/facebook/react/utils/PathUtilsTest.kt | 57 +++++++++++++++++ .../facebook/react/utils/ProjectUtilsTest.kt | 62 +++++++++++++++++++ packages/rn-tester/android/app/build.gradle | 1 - 7 files changed, 157 insertions(+), 12 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt index 4e7573876540cf..08350da88d90ae 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt @@ -156,11 +156,4 @@ abstract class ReactExtension @Inject constructor(project: Project) { */ val codegenJavaPackageName: Property = objects.property(String::class.java).convention("com.facebook.fbreact.specs") - - /** - * Toggles the Codegen for App modules. By default we enable the codegen only for library modules. - * If you want to enable codegen in your app, you will have to set this to true. Default: false - */ - val enableCodegenInApps: Property = - objects.property(Boolean::class.java).convention(false) } diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt index 24790daa83c565..8538eaa9941d48 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactPlugin.kt @@ -19,6 +19,7 @@ import com.facebook.react.utils.DependencyUtils.configureRepositories import com.facebook.react.utils.DependencyUtils.readVersionString import com.facebook.react.utils.JsonUtils import com.facebook.react.utils.NdkConfiguratorUtils.configureReactNativeNdk +import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson import com.facebook.react.utils.findPackageJsonFile import java.io.File import kotlin.system.exitProcess @@ -91,7 +92,11 @@ class ReactPlugin : Plugin { it.codegenDir.set(extension.codegenDir) val bashWindowsHome = project.findProperty("REACT_WINDOWS_BASH") as String? it.bashWindowsHome.set(bashWindowsHome) - it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } + + // Please note that appNeedsCodegen is triggering a read of the package.json at + // configuration time as we need to feed the onlyIf condition of this task. + // Therefore, the appNeedsCodegen needs to be invoked inside this lambda. + it.onlyIf { isLibrary || project.needsCodegenFromPackageJson(extension) } } // We create the task to produce schema from JS files. @@ -102,10 +107,9 @@ class ReactPlugin : Plugin { it.nodeExecutableAndArgs.set(extension.nodeExecutableAndArgs) it.codegenDir.set(extension.codegenDir) it.generatedSrcDir.set(generatedSrcDir) - it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } // We're reading the package.json at configuration time to properly feed - // the `jsRootDir` @Input property of this task. Therefore, the + // the `jsRootDir` @Input property of this task & the onlyIf. Therefore, the // parsePackageJson should be invoked inside this lambda. val packageJson = findPackageJsonFile(project, extension) val parsedPackageJson = packageJson?.let { JsonUtils.fromCodegenJson(it) } @@ -116,6 +120,7 @@ class ReactPlugin : Plugin { } else { it.jsRootDir.set(extension.jsRootDir) } + it.onlyIf { isLibrary || project.needsCodegenFromPackageJson(parsedPackageJson) } } // We create the task to generate Java code from schema. @@ -130,7 +135,11 @@ class ReactPlugin : Plugin { it.packageJsonFile.set(findPackageJsonFile(project, extension)) it.codegenJavaPackageName.set(extension.codegenJavaPackageName) it.libraryName.set(extension.libraryName) - it.onlyIf { isLibrary || extension.enableCodegenInApps.get() } + + // Please note that appNeedsCodegen is triggering a read of the package.json at + // configuration time as we need to feed the onlyIf condition of this task. + // Therefore, the appNeedsCodegen needs to be invoked inside this lambda. + it.onlyIf { isLibrary || project.needsCodegenFromPackageJson(extension) } } // We update the android configuration to include the generated sources. diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt index b7e039909ea10d..41130173edafff 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt @@ -10,6 +10,7 @@ package com.facebook.react.utils import com.facebook.react.ReactExtension +import com.facebook.react.model.ModelPackageJson import java.io.File import org.gradle.api.Project @@ -206,6 +207,19 @@ internal fun findPackageJsonFile(project: Project, extension: ReactExtension): F extension.root.file("package.json").orNull?.asFile } +/** + * Function to look for the `package.json` and parse it. It returns a [ModelPackageJson] if found or + * null others. + * + * Please note that this function access the [ReactExtension] field properties and calls .get() on + * them, so calling this during apply() of the ReactPlugin is not recommended. It should be invoked + * inside lazy lambdas or at execution time. + */ +internal fun readPackageJsonFile(project: Project, extension: ReactExtension): ModelPackageJson? { + val packageJson = findPackageJsonFile(project, extension) + return packageJson?.let { JsonUtils.fromCodegenJson(it) } +} + private const val HERMESC_IN_REACT_NATIVE_DIR = "node_modules/react-native/sdks/hermesc/%OS-BIN%/" private const val HERMESC_BUILT_FROM_SOURCE_DIR = "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/" diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt index f70e14cbccabde..c18946a0cd0e2c 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/ProjectUtils.kt @@ -7,6 +7,8 @@ package com.facebook.react.utils +import com.facebook.react.ReactExtension +import com.facebook.react.model.ModelPackageJson import org.gradle.api.Project internal object ProjectUtils { @@ -32,4 +34,13 @@ internal object ProjectUtils { } else { HERMES_FALLBACK } + + internal fun Project.needsCodegenFromPackageJson(extension: ReactExtension): Boolean { + val parsedPackageJson = readPackageJsonFile(this, extension) + return needsCodegenFromPackageJson(parsedPackageJson) + } + + internal fun Project.needsCodegenFromPackageJson(model: ModelPackageJson?): Boolean { + return model?.codegenConfig != null + } } diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt index 784d596a89d326..b0f7474cd23a40 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt @@ -13,6 +13,7 @@ import com.facebook.react.tests.OS import com.facebook.react.tests.OsRule import com.facebook.react.tests.WithOs import java.io.File +import java.io.FileNotFoundException import org.gradle.testfixtures.ProjectBuilder import org.junit.Assert.* import org.junit.Assume.assumeTrue @@ -299,4 +300,60 @@ class PathUtilsTest { assertEquals(localFile, findPackageJsonFile(project, extension)) } + + @Test(expected = FileNotFoundException::class) + fun readPackageJsonFile_withMissingFile_returnsNull() { + val moduleFolder = tempFolder.newFolder("awesome-module") + val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() + project.plugins.apply("com.android.library") + project.plugins.apply("com.facebook.react") + val extension = + project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } + + val actual = readPackageJsonFile(project, extension) + + assertNull(actual) + } + + @Test + fun readPackageJsonFile_withFileConfiguredInExtension_andMissingCodegenConfig_returnsNullCodegenConfig() { + val moduleFolder = tempFolder.newFolder("awesome-module") + File(moduleFolder, "package.json").apply { writeText("{}") } + val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() + project.plugins.apply("com.android.library") + project.plugins.apply("com.facebook.react") + val extension = + project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } + + val actual = readPackageJsonFile(project, extension) + + assertNotNull(actual) + assertNull(actual!!.codegenConfig) + } + + @Test + fun readPackageJsonFile_withFileConfiguredInExtension_andHavingCodegenConfig_returnsValidCodegenConfig() { + val moduleFolder = tempFolder.newFolder("awesome-module") + File(moduleFolder, "package.json").apply { + writeText( + // language=json + """ + { + "name": "a-library", + "codegenConfig": {} + } + """ + .trimIndent()) + } + val project = ProjectBuilder.builder().withProjectDir(moduleFolder).build() + project.plugins.apply("com.android.library") + project.plugins.apply("com.facebook.react") + val extension = + project.extensions.getByType(ReactExtension::class.java).apply { root.set(moduleFolder) } + + val actual = readPackageJsonFile(project, extension) + + assertNotNull(actual) + assertNotNull(actual!!.codegenConfig) + } } diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt index c41cc65a27ccf5..d918c285d1cf39 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/ProjectUtilsTest.kt @@ -7,15 +7,24 @@ package com.facebook.react.utils +import com.facebook.react.TestReactExtension +import com.facebook.react.model.ModelCodegenConfig +import com.facebook.react.model.ModelPackageJson import com.facebook.react.tests.createProject import com.facebook.react.utils.ProjectUtils.isHermesEnabled import com.facebook.react.utils.ProjectUtils.isNewArchEnabled +import com.facebook.react.utils.ProjectUtils.needsCodegenFromPackageJson +import java.io.File import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder class ProjectUtilsTest { + @get:Rule val tempFolder = TemporaryFolder() + @Test fun isNewArchEnabled_returnsFalseByDefault() { assertFalse(createProject().isNewArchEnabled) @@ -99,4 +108,57 @@ class ProjectUtilsTest { project.extensions.extraProperties.set("react", extMap) assertTrue(project.isHermesEnabled) } + + @Test + fun needsCodegenFromPackageJson_withCodegenConfigInPackageJson_returnsTrue() { + val project = createProject() + val extension = TestReactExtension(project) + File(tempFolder.root, "package.json").apply { + writeText( + // language=json + """ + { + "name": "a-library", + "codegenConfig": {} + } + """ + .trimIndent()) + } + extension.root.set(tempFolder.root) + assertTrue(project.needsCodegenFromPackageJson(extension)) + } + + @Test + fun needsCodegenFromPackageJson_withMissingCodegenConfigInPackageJson_returnsFalse() { + val project = createProject() + val extension = TestReactExtension(project) + File(tempFolder.root, "package.json").apply { + writeText( + // language=json + """ + { + "name": "a-library" + } + """ + .trimIndent()) + } + extension.root.set(tempFolder.root) + assertFalse(project.needsCodegenFromPackageJson(extension)) + } + + @Test + fun needsCodegenFromPackageJson_withCodegenConfigInModel_returnsTrue() { + val project = createProject() + val model = ModelPackageJson(ModelCodegenConfig(null, null, null, null)) + + assertTrue(project.needsCodegenFromPackageJson(model)) + } + + @Test + fun needsCodegenFromPackageJson_withMissingCodegenConfigInModel_returnsFalse() { + val project = createProject() + val model = ModelPackageJson(null) + + assertFalse(project.needsCodegenFromPackageJson(model)) + } } diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index e0fc0dcf655e8c..c26d4444cf3030 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -88,7 +88,6 @@ react { // Codegen Configs reactNativeDir = rootDir codegenDir = new File(rootDir, "node_modules/react-native-codegen") - enableCodegenInApps = true } /** From 2ff08e8bd8b1303f1ef6f3052031c3a216565053 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 26 Oct 2022 10:46:39 -0700 Subject: [PATCH 042/169] RNGP - Do the .so cleanup using pickFirst and exclude (#35093) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35093 It turns out that using the Artifacts API to manipulate the APK to remove .so has unintended side effects and is causing the `installDebug` and `installRelease` commands to fail. I've resorted to register a packaging option for each variant to make sure we include only the correct artifacts we want. This should fix the current startup crash that is experienced on main. Changelog: [Android] [Fixed] - RNGP - Do the .so cleanup using pickFirst and exclude Reviewed By: cipolleschi Differential Revision: D40722285 fbshipit-source-id: 982e1e9c474522fc4419c969ede5ee14e5404f3a --- .../com/facebook/react/TaskConfiguration.kt | 48 ++--- .../tasks/NativeLibraryAabCleanupTask.kt | 40 ---- .../tasks/NativeLibraryApkCleanupTask.kt | 41 ---- .../react/utils/NdkConfiguratorUtils.kt | 204 +++++++++++------- .../facebook/react/utils/SoCleanerUtils.kt | 58 ----- .../tasks/NativeLibraryAabCleanupTaskTest.kt | 165 -------------- .../tasks/NativeLibraryApkCleanupTaskTest.kt | 59 ----- .../react/utils/NdkConfiguratorUtilsTest.kt | 88 ++++++++ .../react/utils/SoCleanerUtilsTest.kt | 189 ---------------- 9 files changed, 231 insertions(+), 661 deletions(-) delete mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTask.kt delete mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTask.kt delete mode 100644 packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/SoCleanerUtils.kt delete mode 100644 packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTaskTest.kt delete mode 100644 packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTaskTest.kt create mode 100644 packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt delete mode 100644 packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/SoCleanerUtilsTest.kt diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt index 4ec27e9f559d94..757c80e99e18c1 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt @@ -7,11 +7,10 @@ package com.facebook.react -import com.android.build.api.artifact.SingleArtifact import com.android.build.api.variant.Variant import com.facebook.react.tasks.BundleHermesCTask -import com.facebook.react.tasks.NativeLibraryAabCleanupTask -import com.facebook.react.tasks.NativeLibraryApkCleanupTask +import com.facebook.react.utils.NdkConfiguratorUtils.configureJsEnginePackagingOptions +import com.facebook.react.utils.NdkConfiguratorUtils.configureNewArchPackagingOptions import com.facebook.react.utils.ProjectUtils.isHermesEnabled import com.facebook.react.utils.detectedCliPath import com.facebook.react.utils.detectedEntryFile @@ -36,16 +35,20 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio // Additional node and packager commandline arguments val cliPath = detectedCliPath(project.projectDir, config) - val enableHermesInProject = project.isHermesEnabled - val enableHermesInThisVariant = + val isHermesEnabledInProject = project.isHermesEnabled + val isHermesEnabledInThisVariant = if (config.enableHermesOnlyInVariants.get().isNotEmpty()) { - config.enableHermesOnlyInVariants.get().contains(variant.name) && enableHermesInProject + config.enableHermesOnlyInVariants.get().contains(variant.name) && isHermesEnabledInProject } else { - enableHermesInProject + isHermesEnabledInProject } val isDebuggableVariant = config.debuggableVariants.get().any { it.equals(variant.name, ignoreCase = true) } + configureNewArchPackagingOptions(project, variant) + configureJsEnginePackagingOptions( + config, variant, isHermesEnabledInThisVariant, isDebuggableVariant) + if (!isDebuggableVariant) { val bundleTask = tasks.register("createBundle${targetName}JsAndAssets", BundleHermesCTask::class.java) { @@ -59,8 +62,8 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio it.bundleAssetName.set(config.bundleAssetName) it.jsBundleDir.set(jsBundleDir) it.resourcesDir.set(resourcesDir) - it.hermesEnabled.set(enableHermesInThisVariant) - it.minifyEnabled.set(!enableHermesInThisVariant) + it.hermesEnabled.set(isHermesEnabledInThisVariant) + it.minifyEnabled.set(!isHermesEnabledInThisVariant) it.devEnabled.set(false) it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) it.jsSourceMapsDir.set(jsSourceMapsDir) @@ -71,31 +74,4 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio variant.sources.res?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::resourcesDir) variant.sources.assets?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::jsBundleDir) } - - if (config.enableSoCleanup.get()) { - val nativeLibraryApkCleanupTask = - project.tasks.register( - "nativeLibrary${targetName}ApkCleanup", NativeLibraryApkCleanupTask::class.java) { - it.debuggableVariant.set(isDebuggableVariant) - it.enableHermes.set(enableHermesInThisVariant) - } - val nativeLibraryBundleCleanupTask = - project.tasks.register( - "nativeLibrary${targetName}BundleCleanup", NativeLibraryAabCleanupTask::class.java) { - it.debuggableVariant.set(isDebuggableVariant) - it.enableHermes.set(enableHermesInThisVariant) - } - - variant.artifacts - .use(nativeLibraryApkCleanupTask) - .wiredWithDirectories( - NativeLibraryApkCleanupTask::inputApkDirectory, - NativeLibraryApkCleanupTask::outputApkDirectory) - .toTransform(SingleArtifact.APK) - variant.artifacts - .use(nativeLibraryBundleCleanupTask) - .wiredWithFiles( - NativeLibraryAabCleanupTask::inputBundle, NativeLibraryAabCleanupTask::outputBundle) - .toTransform(SingleArtifact.BUNDLE) - } } diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTask.kt deleted file mode 100644 index 9e46e419d93d59..00000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTask.kt +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.utils.SoCleanerUtils -import org.gradle.api.DefaultTask -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.TaskAction - -abstract class NativeLibraryAabCleanupTask : DefaultTask() { - - @get:InputFile abstract val inputBundle: RegularFileProperty - - @get:OutputFile abstract val outputBundle: RegularFileProperty - - @get:Input abstract val enableHermes: Property - - @get:Input abstract val debuggableVariant: Property - - @TaskAction - fun run() { - val inputBundleFile = inputBundle.get().asFile - val outputBundleFile = outputBundle.get().asFile - SoCleanerUtils.clean( - input = inputBundleFile, - prefix = "base/lib", - enableHermes = enableHermes.get(), - debuggableVariant = debuggableVariant.get()) - inputBundleFile.copyTo(outputBundleFile, overwrite = true) - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTask.kt deleted file mode 100644 index 8c0064d473933e..00000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTask.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.utils.SoCleanerUtils -import org.gradle.api.DefaultTask -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputDirectory -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.TaskAction - -abstract class NativeLibraryApkCleanupTask : DefaultTask() { - - @get:InputDirectory abstract val inputApkDirectory: DirectoryProperty - - @get:OutputDirectory abstract val outputApkDirectory: DirectoryProperty - - @get:Input abstract val enableHermes: Property - - @get:Input abstract val debuggableVariant: Property - - @TaskAction - fun run() { - inputApkDirectory.get().asFile.walk().forEach { - if (it.name.endsWith(".apk")) { - SoCleanerUtils.clean( - input = it, - prefix = "lib/", - enableHermes = enableHermes.get(), - debuggableVariant = debuggableVariant.get()) - } - } - } -} diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt index 9bec0e3bc2a9c2..d081afbfcf0284 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt @@ -8,6 +8,7 @@ package com.facebook.react.utils import com.android.build.api.variant.AndroidComponentsExtension +import com.android.build.api.variant.Variant import com.facebook.react.ReactExtension import com.facebook.react.utils.ProjectUtils.isNewArchEnabled import java.io.File @@ -19,83 +20,140 @@ internal object NdkConfiguratorUtils { project.pluginManager.withPlugin("com.android.application") { project.extensions.getByType(AndroidComponentsExtension::class.java).finalizeDsl { ext -> if (!project.isNewArchEnabled) { - // For Old Arch, we set a pickFirst only on libraries that we know are - // clashing with our direct dependencies (FBJNI, Flipper and Hermes). - ext.packagingOptions.jniLibs.pickFirsts.addAll( - listOf( - "**/libfbjni.so", - "**/libc++_shared.so", - )) - } else { - // We enable prefab so users can consume .so/headers from ReactAndroid and hermes-engine - // .aar - ext.buildFeatures.prefab = true - - // We set some packagingOptions { pickFirst ... } for our users for libraries we own. - ext.packagingOptions.jniLibs.pickFirsts.addAll( - listOf( - // Hermes & JSC are provided by AAR dependencies we pre-bundle. - "**/libhermes.so", - "**/libjsc.so", - // This is the .so provided by FBJNI via prefab - "**/libfbjni.so", - // Those are prefab libraries we distribute via ReactAndroid - // Due to a bug in AGP, they fire a warning on console as both the JNI - // and the prefab .so files gets considered. See more on: - "**/libfabricjni.so", - "**/libfolly_runtime.so", - "**/libglog.so", - "**/libjsi.so", - "**/libreact_codegen_rncore.so", - "**/libreact_debug.so", - "**/libreact_nativemodule_core.so", - "**/libreact_newarchdefaults.so", - "**/libreact_render_componentregistry.so", - "**/libreact_render_core.so", - "**/libreact_render_debug.so", - "**/libreact_render_graphics.so", - "**/libreact_render_imagemanager.so", - "**/libreact_render_mapbuffer.so", - "**/librrc_image.so", - "**/librrc_view.so", - "**/libruntimeexecutor.so", - "**/libturbomodulejsijni.so", - "**/libyoga.so", - // AGP will give priority of libc++_shared coming from App modules. - "**/libc++_shared.so", - )) + // For Old Arch, we don't need to setup the NDK + return@finalizeDsl + } + // We enable prefab so users can consume .so/headers from ReactAndroid and hermes-engine + // .aar + ext.buildFeatures.prefab = true - // If the user has not provided a CmakeLists.txt path, let's provide - // the default one from the framework - if (ext.externalNativeBuild.cmake.path == null) { - ext.externalNativeBuild.cmake.path = - File( - extension.reactNativeDir.get().asFile, - "ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt") - } + // If the user has not provided a CmakeLists.txt path, let's provide + // the default one from the framework + if (ext.externalNativeBuild.cmake.path == null) { + ext.externalNativeBuild.cmake.path = + File( + extension.reactNativeDir.get().asFile, + "ReactAndroid/cmake-utils/default-app-setup/CMakeLists.txt") + } - // Parameters should be provided in an additive manner (do not override what - // the user provided, but allow for sensible defaults). - val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments - if ("-DGENERATED_SRC_DIR" !in cmakeArgs) { - cmakeArgs.add("-DGENERATED_SRC_DIR=${File(project.buildDir, "generated/source")}") - } - if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") - } - if ("-DREACT_ANDROID_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") - } - if ("-DREACT_ANDROID_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_BUILD_DIR=${extension.reactNativeDir.file("ReactAndroid/build").get().asFile}") - } - if ("-DANDROID_STL" !in cmakeArgs) { - cmakeArgs.add("-DANDROID_STL=c++_shared") - } + // Parameters should be provided in an additive manner (do not override what + // the user provided, but allow for sensible defaults). + val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments + if ("-DGENERATED_SRC_DIR" !in cmakeArgs) { + cmakeArgs.add("-DGENERATED_SRC_DIR=${File(project.buildDir, "generated/source")}") + } + if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { + cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") + } + if ("-DREACT_ANDROID_DIR" !in cmakeArgs) { + cmakeArgs.add( + "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") } + if ("-DREACT_ANDROID_BUILD_DIR" !in cmakeArgs) { + cmakeArgs.add( + "-DREACT_ANDROID_BUILD_DIR=${ + extension.reactNativeDir.file("ReactAndroid/build").get().asFile + }") + } + if ("-DANDROID_STL" !in cmakeArgs) { + cmakeArgs.add("-DANDROID_STL=c++_shared") + } + } + } + } + + /** + * This method is used to configure the .so Packaging Options for the given variant. It will make + * sure we specify the correct .pickFirsts for all the .so files we are producing or that we're + * aware of as some of our dependencies are pulling them in. + */ + fun configureNewArchPackagingOptions( + project: Project, + variant: Variant, + ) { + if (!project.isNewArchEnabled) { + // For Old Arch, we set a pickFirst only on libraries that we know are + // clashing with our direct dependencies (FBJNI, Flipper and Hermes). + variant.packaging.jniLibs.pickFirsts.addAll( + listOf( + "**/libfbjni.so", + "**/libc++_shared.so", + )) + } else { + // We set some packagingOptions { pickFirst ... } for our users for libraries we own. + variant.packaging.jniLibs.pickFirsts.addAll( + listOf( + // This is the .so provided by FBJNI via prefab + "**/libfbjni.so", + // Those are prefab libraries we distribute via ReactAndroid + // Due to a bug in AGP, they fire a warning on console as both the JNI + // and the prefab .so files gets considered. See more on: + "**/libfabricjni.so", + "**/libfolly_runtime.so", + "**/libglog.so", + "**/libjsi.so", + "**/libreact_codegen_rncore.so", + "**/libreact_debug.so", + "**/libreact_nativemodule_core.so", + "**/libreact_newarchdefaults.so", + "**/libreact_render_componentregistry.so", + "**/libreact_render_core.so", + "**/libreact_render_debug.so", + "**/libreact_render_graphics.so", + "**/libreact_render_imagemanager.so", + "**/libreact_render_mapbuffer.so", + "**/librrc_image.so", + "**/librrc_view.so", + "**/libruntimeexecutor.so", + "**/libturbomodulejsijni.so", + "**/libyoga.so", + // AGP will give priority of libc++_shared coming from App modules. + "**/libc++_shared.so", + )) + } + } + + /** + * This method is used to configure the .so Cleanup for the given variant. It takes care of + * cleaning up the .so files that are not needed for Hermes or JSC, given a specific variant. + */ + fun configureJsEnginePackagingOptions( + config: ReactExtension, + variant: Variant, + hermesEnabled: Boolean, + debuggableVariant: Boolean + ) { + if (config.enableSoCleanup.get()) { + val (excludes, includes) = getPackagingOptionsForVariant(hermesEnabled, debuggableVariant) + variant.packaging.jniLibs.excludes.addAll(excludes) + variant.packaging.jniLibs.pickFirsts.addAll(includes) + } + } + + fun getPackagingOptionsForVariant( + hermesEnabled: Boolean, + debuggableVariant: Boolean + ): Pair, List> { + val excludes = mutableListOf() + val includes = mutableListOf() + if (hermesEnabled) { + excludes.add("**/libjsc.so") + excludes.add("**/libjscexecutor.so") + includes.add("**/libhermes.so") + if (debuggableVariant) { + excludes.add("**/libhermes-executor-release.so") + includes.add("**/libhermes-executor-debug.so") + } else { + excludes.add("**/libhermes-executor-debug.so") + includes.add("**/libhermes-executor-release.so") } + } else { + excludes.add("**/libhermes.so") + excludes.add("**/libhermes-executor-debug.so") + excludes.add("**/libhermes-executor-release.so") + includes.add("**/libjsc.so") + includes.add("**/libjscexecutor.so") } + return excludes to includes } } diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/SoCleanerUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/SoCleanerUtils.kt deleted file mode 100644 index ece6924d5aab85..00000000000000 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/SoCleanerUtils.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.utils - -import java.io.File -import java.net.URI -import java.nio.file.FileSystem -import java.nio.file.FileSystems -import java.nio.file.Files - -internal object SoCleanerUtils { - - private val zipProperties = mapOf("create" to "false") - - private val archs = listOf("x86", "x86_64", "armeabi-v7a", "arm64-v8a") - - fun clean(input: File, prefix: String, enableHermes: Boolean, debuggableVariant: Boolean) { - val zipDisk: URI = URI.create("jar:file:${input.absolutePath}") - FileSystems.newFileSystem(zipDisk, zipProperties).use { zipfs -> - buildList { - if (enableHermes) { - add("libjsc.so") - add("libjscexecutor.so") - if (debuggableVariant) { - add("libhermes-executor-release.so") - } else { - add("libhermes-executor-debug.so") - } - } else { - add("libhermes.so") - add("libhermes-executor-debug.so") - add("libhermes-executor-release.so") - } - } - .forEach { removeSoFiles(zipfs, prefix, archs, it) } - } - } - - fun removeSoFiles( - zipfs: FileSystem, - prefix: String, - archs: List, - libraryToRemove: String - ) { - archs.forEach { arch -> - try { - Files.delete(zipfs.getPath("$prefix/$arch/$libraryToRemove")) - } catch (e: Exception) { - // File was already missing due to ABI split, nothing to do here. - } - } - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTaskTest.kt deleted file mode 100644 index e48cbda67e6cc8..00000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryAabCleanupTaskTest.kt +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.tests.createTestTask -import com.facebook.react.tests.createZip -import java.io.File -import java.net.URI -import java.nio.file.FileSystems -import java.nio.file.Files.exists -import org.gradle.api.tasks.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class NativeLibraryAabCleanupTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun nativeLibraryAabCleanupTask_withHermesDebug_cleansCorrectly() { - val inputAab = File(tempFolder.root, "input.aab") - val outputAab = File(tempFolder.root, "output.aab") - createZip( - inputAab, - listOf( - "base/lib/x86/libhermes.so", - "base/lib/x86/libhermes-executor-debug.so", - "base/lib/x86/libhermes-executor-release.so", - "base/lib/x86/libjsc.so", - "base/lib/x86/libjscexecutor.so", - )) - val task = - createTestTask { - it.inputBundle.set(inputAab) - it.outputBundle.set(outputAab) - it.enableHermes.set(true) - it.debuggableVariant.set(true) - } - - task.run() - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${inputAab.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertTrue(exists(it.getPath("base/lib/x86/libhermes.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-release.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libjsc.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun nativeLibraryAabCleanupTask_withHermesRelease_cleansCorrectly() { - val inputAab = File(tempFolder.root, "input.aab") - val outputAab = File(tempFolder.root, "output.aab") - createZip( - inputAab, - listOf( - "base/lib/x86/libhermes.so", - "base/lib/x86/libhermes-executor-debug.so", - "base/lib/x86/libhermes-executor-release.so", - "base/lib/x86/libjsc.so", - "base/lib/x86/libjscexecutor.so", - )) - val task = - createTestTask { - it.inputBundle.set(inputAab) - it.outputBundle.set(outputAab) - it.enableHermes.set(true) - it.debuggableVariant.set(false) - } - - task.run() - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${inputAab.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertTrue(exists(it.getPath("base/lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-debug.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libhermes-executor-release.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libjsc.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun nativeLibraryAabCleanupTask_withJscDebug_cleansCorrectly() { - val inputAab = File(tempFolder.root, "input.aab") - val outputAab = File(tempFolder.root, "output.aab") - createZip( - inputAab, - listOf( - "base/lib/x86/libhermes.so", - "base/lib/x86/libhermes-executor-debug.so", - "base/lib/x86/libhermes-executor-release.so", - "base/lib/x86/libjsc.so", - "base/lib/x86/libjscexecutor.so", - )) - val task = - createTestTask { - it.inputBundle.set(inputAab) - it.outputBundle.set(outputAab) - it.enableHermes.set(false) - it.debuggableVariant.set(true) - } - - task.run() - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${inputAab.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertFalse(exists(it.getPath("base/lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-release.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libjsc.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun nativeLibraryAabCleanupTask_withJscRelease_cleansCorrectly() { - val inputAab = File(tempFolder.root, "input.aab") - val outputAab = File(tempFolder.root, "output.aab") - createZip( - inputAab, - listOf( - "base/lib/x86/libhermes.so", - "base/lib/x86/libhermes-executor-debug.so", - "base/lib/x86/libhermes-executor-release.so", - "base/lib/x86/libjsc.so", - "base/lib/x86/libjscexecutor.so", - )) - val task = - createTestTask { - it.inputBundle.set(inputAab) - it.outputBundle.set(outputAab) - it.enableHermes.set(false) - it.debuggableVariant.set(false) - } - - task.run() - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${inputAab.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertFalse(exists(it.getPath("base/lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("base/lib/x86/libhermes-executor-release.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libjsc.so"))) - assertTrue(exists(it.getPath("base/lib/x86/libjscexecutor.so"))) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTaskTest.kt deleted file mode 100644 index 7abc0e6c12161d..00000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/NativeLibraryApkCleanupTaskTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.tasks - -import com.facebook.react.tests.createTestTask -import com.facebook.react.tests.createZip -import java.io.File -import java.net.URI -import java.nio.file.FileSystems -import java.nio.file.Files.exists -import org.gradle.api.tasks.* -import org.junit.Assert.* -import org.junit.Rule -import org.junit.Test -import org.junit.rules.TemporaryFolder - -class NativeLibraryApkCleanupTaskTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun nativeLibraryApkCleanupTask_runWithAppApk() { - val tempApk = File(tempFolder.root, "app.apk") - createZip( - tempApk, - listOf( - "lib/x86/libhermes.so", - "lib/x86/libhermes-executor-debug.so", - "lib/x86/libhermes-executor-release.so", - "lib/x86/libjsc.so", - "lib/x86/libjscexecutor.so", - )) - val task = - createTestTask { - it.inputApkDirectory.set(tempFolder.root) - it.outputApkDirectory.set(tempFolder.root) - it.enableHermes.set(true) - it.debuggableVariant.set(true) - } - - task.run() - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempApk.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertTrue(exists(it.getPath("lib/x86/libhermes.so"))) - assertTrue(exists(it.getPath("lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-release.so"))) - assertFalse(exists(it.getPath("lib/x86/libjsc.so"))) - assertFalse(exists(it.getPath("lib/x86/libjscexecutor.so"))) - } - } -} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt new file mode 100644 index 00000000000000..2d0093c6a565d2 --- /dev/null +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/NdkConfiguratorUtilsTest.kt @@ -0,0 +1,88 @@ +/* + * 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.utils + +import com.facebook.react.utils.NdkConfiguratorUtils.getPackagingOptionsForVariant +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class NdkConfiguratorUtilsTest { + + @Test + fun getPackagingOptionsForVariant_withHermesEnabled_andDebuggableVariant() { + val (excludes, includes) = + getPackagingOptionsForVariant(hermesEnabled = true, debuggableVariant = true) + + assertTrue("**/libjsc.so" in excludes) + assertTrue("**/libjscexecutor.so" in excludes) + assertTrue("**/libhermes-executor-release.so" in excludes) + assertFalse("**/libjsc.so" in includes) + assertFalse("**/libjscexecutor.so" in includes) + assertFalse("**/libhermes-executor-release.so" in includes) + + assertTrue("**/libhermes.so" in includes) + assertTrue("**/libhermes-executor-debug.so" in includes) + assertFalse("**/libhermes.so" in excludes) + assertFalse("**/libhermes-executor-debug.so" in excludes) + } + + @Test + fun getPackagingOptionsForVariant_withHermesEnabled_andNonDebuggableVariant() { + val (excludes, includes) = + getPackagingOptionsForVariant(hermesEnabled = true, debuggableVariant = false) + + assertTrue("**/libjsc.so" in excludes) + assertTrue("**/libjscexecutor.so" in excludes) + assertTrue("**/libhermes-executor-debug.so" in excludes) + assertFalse("**/libjsc.so" in includes) + assertFalse("**/libjscexecutor.so" in includes) + assertFalse("**/libhermes-executor-debug.so" in includes) + + assertTrue("**/libhermes.so" in includes) + assertTrue("**/libhermes-executor-release.so" in includes) + assertFalse("**/libhermes.so" in excludes) + assertFalse("**/libhermes-executor-release.so" in excludes) + } + + @Test + fun getPackagingOptionsForVariant_withHermesDisabled_andDebuggableVariant() { + val (excludes, includes) = + getPackagingOptionsForVariant(hermesEnabled = false, debuggableVariant = true) + + assertTrue("**/libhermes.so" in excludes) + assertTrue("**/libhermes-executor-debug.so" in excludes) + assertTrue("**/libhermes-executor-release.so" in excludes) + assertFalse("**/libhermes.so" in includes) + assertFalse("**/libhermes-executor-debug.so" in includes) + assertFalse("**/libhermes-executor-release.so" in includes) + + assertTrue("**/libjsc.so" in includes) + assertTrue("**/libjscexecutor.so" in includes) + assertFalse("**/libjsc.so" in excludes) + assertFalse("**/libjscexecutor.so" in excludes) + } + + @Test + fun getPackagingOptionsForVariant_withHermesDisabled_andNonDebuggableVariant() { + val (excludes, includes) = + getPackagingOptionsForVariant(hermesEnabled = false, debuggableVariant = false) + + assertTrue("**/libhermes.so" in excludes) + assertTrue("**/libhermes-executor-debug.so" in excludes) + assertTrue("**/libhermes-executor-release.so" in excludes) + assertFalse("**/libhermes.so" in includes) + assertFalse("**/libhermes-executor-debug.so" in includes) + assertFalse("**/libhermes-executor-release.so" in includes) + + assertTrue("**/libjsc.so" in includes) + assertTrue("**/libjscexecutor.so" in includes) + assertFalse("**/libjsc.so" in excludes) + assertFalse("**/libjscexecutor.so" in excludes) + } +} diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/SoCleanerUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/SoCleanerUtilsTest.kt deleted file mode 100644 index 2c887b48facd44..00000000000000 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/SoCleanerUtilsTest.kt +++ /dev/null @@ -1,189 +0,0 @@ -/* - * 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.utils - -import com.facebook.react.tests.createZip -import com.facebook.react.utils.SoCleanerUtils.clean -import com.facebook.react.utils.SoCleanerUtils.removeSoFiles -import java.io.File -import java.net.URI -import java.nio.file.FileSystems -import java.nio.file.Files.* -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Rule -import org.junit.Test -import org.junit.Test.None -import org.junit.rules.TemporaryFolder - -class SoCleanerUtilsTest { - - @get:Rule val tempFolder = TemporaryFolder() - - @Test - fun clean_withEnableHermesAndDebuggableVariant_removesCorrectly() { - val tempZip = - File(tempFolder.root, "app.apk").apply { - createZip( - this, - listOf( - "lib/x86/libhermes.so", - "lib/x86/libhermes-executor-debug.so", - "lib/x86/libhermes-executor-release.so", - "lib/x86/libjsc.so", - "lib/x86/libjscexecutor.so", - )) - } - - clean(tempZip, "lib", enableHermes = true, debuggableVariant = true) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertTrue(exists(it.getPath("lib/x86/libhermes.so"))) - assertTrue(exists(it.getPath("lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-release.so"))) - assertFalse(exists(it.getPath("lib/x86/libjsc.so"))) - assertFalse(exists(it.getPath("lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun clean_withEnableHermesAndNonDebuggableVariant_removesCorrectly() { - val tempZip = - File(tempFolder.root, "app.apk").apply { - createZip( - this, - listOf( - "lib/x86/libhermes.so", - "lib/x86/libhermes-executor-debug.so", - "lib/x86/libhermes-executor-release.so", - "lib/x86/libjsc.so", - "lib/x86/libjscexecutor.so", - )) - } - - clean(tempZip, "lib", enableHermes = true, debuggableVariant = false) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertTrue(exists(it.getPath("lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-debug.so"))) - assertTrue(exists(it.getPath("lib/x86/libhermes-executor-release.so"))) - assertFalse(exists(it.getPath("lib/x86/libjsc.so"))) - assertFalse(exists(it.getPath("lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun clean_withJscAndDebuggableVariant_removesCorrectly() { - val tempZip = - File(tempFolder.root, "app.apk").apply { - createZip( - this, - listOf( - "lib/x86/libhermes.so", - "lib/x86/libhermes-executor-debug.so", - "lib/x86/libhermes-executor-release.so", - "lib/x86/libjsc.so", - "lib/x86/libjscexecutor.so", - )) - } - - clean(tempZip, "lib", enableHermes = false, debuggableVariant = true) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertFalse(exists(it.getPath("lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-release.so"))) - assertTrue(exists(it.getPath("lib/x86/libjsc.so"))) - assertTrue(exists(it.getPath("lib/x86/libjscexecutor.so"))) - } - } - - @Test - fun clean_withJscAndNonDebuggableVariant_removesCorrectly() { - val tempZip = - File(tempFolder.root, "app.apk").apply { - createZip( - this, - listOf( - "lib/x86/libhermes.so", - "lib/x86/libhermes-executor-debug.so", - "lib/x86/libhermes-executor-release.so", - "lib/x86/libjsc.so", - "lib/x86/libjscexecutor.so", - )) - } - - clean(tempZip, "lib", enableHermes = false, debuggableVariant = false) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - fs.use { - assertFalse(exists(it.getPath("lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-debug.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes-executor-release.so"))) - assertTrue(exists(it.getPath("lib/x86/libjsc.so"))) - assertTrue(exists(it.getPath("lib/x86/libjscexecutor.so"))) - } - } - - @Test(expected = None::class) - fun removeSoFiles_withEmptyZip_doesNothing() { - val tempZip = File(tempFolder.root, "app.apk") - createZip(tempZip, emptyList()) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - val archs = listOf("x86") - val libraryToRemove = "libhello.so" - - removeSoFiles(fs, "lib", archs, libraryToRemove) - } - - @Test - fun removeSoFiles_withValidFiles_filtersThemCorrectly() { - val tempZip = File(tempFolder.root, "app.apk") - createZip( - tempZip, - listOf( - "base/lib/x86_64/libhermes.so", - "base/lib/x86/libhermes.so", - "lib/arm64-v8a/libhermes.so", - "lib/armeabi-v7a/libhermes.so", - "lib/x86/libhermes.so", - "lib/x86_64/libhermes.so", - )) - - val fs = - FileSystems.newFileSystem( - URI.create("jar:file:${tempZip.absoluteFile}"), mapOf("create" to "false")) - val archs = listOf("x86", "x86_64") - val libraryToRemove = "libhermes.so" - - removeSoFiles(fs, "lib", archs, libraryToRemove) - - fs.use { - assertTrue(exists(it.getPath("base/lib/x86/libhermes.so"))) - assertTrue(exists(it.getPath("base/lib/x86_64/libhermes.so"))) - assertTrue(exists(it.getPath("lib/arm64-v8a/libhermes.so"))) - assertTrue(exists(it.getPath("lib/armeabi-v7a/libhermes.so"))) - assertFalse(exists(it.getPath("lib/x86/libhermes.so"))) - assertFalse(exists(it.getPath("lib/x86_64/libhermes.so"))) - } - } -} From fae770b9fefebecdc8716947ee4760c687655d22 Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Wed, 26 Oct 2022 11:24:16 -0700 Subject: [PATCH 043/169] InputAccessoryView Summary: Changelog: [Internal] Flow InputAccessoryView Reviewed By: yungsters Differential Revision: D39855166 fbshipit-source-id: 9c389854e6d76a0c0e881190cd1808088de324fd --- .../TextInput/InputAccessoryView.js.flow | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Libraries/Components/TextInput/InputAccessoryView.js.flow diff --git a/Libraries/Components/TextInput/InputAccessoryView.js.flow b/Libraries/Components/TextInput/InputAccessoryView.js.flow new file mode 100644 index 00000000000000..e2245cb84d76ba --- /dev/null +++ b/Libraries/Components/TextInput/InputAccessoryView.js.flow @@ -0,0 +1,25 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @format + */ + +import * as React from 'react'; +import Platform from '../../Utilities/Platform'; +import StyleSheet, { + type ViewStyleProp, + type ColorValue, +} from '../../StyleSheet/StyleSheet'; + +type Props = $ReadOnly<{| + +children: React.Node, + nativeID?: ?string, + style?: ?ViewStyleProp, + backgroundColor?: ?ColorValue, +|}>; + +module.exports = class InputAccessoryView extends React.Component {}; From 7a19af7fb6b3b62fbbd632c6569a4270c604fb86 Mon Sep 17 00:00:00 2001 From: ankit-tailor Date: Wed, 26 Oct 2022 11:47:58 -0700 Subject: [PATCH 044/169] fix: add mixed to aria-checked typings (#34633) Summary: `aria-checked` prop should accept `mixed` as value as given [here](https://www.w3.org/WAI/GL/wiki/Using_WAI-ARIA_aria-checked%3Dmixed) and also [accessibilityState.checked](https://reactnative.dev/docs/accessibility#accessibilitystate) accepts mixed to represent checkboxes. This change refers to issue https://github.com/facebook/react-native/issues/34424 and PR https://github.com/facebook/react-native/pull/34524 ## Changelog [General] [Added] - Added `mixed` value for `aria-checked`. Pull Request resolved: https://github.com/facebook/react-native/pull/34633 Test Plan: ```js Checkbox example ``` Reviewed By: lunaleaps Differential Revision: D39382158 Pulled By: necolas fbshipit-source-id: fa026274111305cc0bcbb42ed974ca1be7d779a5 --- Libraries/Components/Button.js | 2 +- Libraries/Components/Pressable/Pressable.js | 2 +- Libraries/Components/Touchable/TouchableWithoutFeedback.js | 2 +- Libraries/Components/View/ViewAccessibility.d.ts | 2 +- Libraries/Components/View/ViewPropTypes.js | 2 +- Libraries/Text/TextProps.js | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Libraries/Components/Button.js b/Libraries/Components/Button.js index f0758e18a2cd81..0395706d2608a8 100644 --- a/Libraries/Components/Button.js +++ b/Libraries/Components/Button.js @@ -157,7 +157,7 @@ type ButtonProps = $ReadOnly<{| * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', 'aria-disabled'?: ?boolean, 'aria-expanded'?: ?boolean, 'aria-selected'?: ?boolean, diff --git a/Libraries/Components/Pressable/Pressable.js b/Libraries/Components/Pressable/Pressable.js index 976509109f2ef6..187b4c4a5b00f4 100644 --- a/Libraries/Components/Pressable/Pressable.js +++ b/Libraries/Components/Pressable/Pressable.js @@ -65,7 +65,7 @@ type Props = $ReadOnly<{| * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', 'aria-disabled'?: ?boolean, 'aria-expanded'?: ?boolean, 'aria-selected'?: ?boolean, diff --git a/Libraries/Components/Touchable/TouchableWithoutFeedback.js b/Libraries/Components/Touchable/TouchableWithoutFeedback.js index 0fd50298d201ea..70b43370b11f6c 100755 --- a/Libraries/Components/Touchable/TouchableWithoutFeedback.js +++ b/Libraries/Components/Touchable/TouchableWithoutFeedback.js @@ -54,7 +54,7 @@ type Props = $ReadOnly<{| * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', 'aria-disabled'?: ?boolean, 'aria-expanded'?: ?boolean, 'aria-selected'?: ?boolean, diff --git a/Libraries/Components/View/ViewAccessibility.d.ts b/Libraries/Components/View/ViewAccessibility.d.ts index 8f530a78c19848..5fad1607d973cb 100644 --- a/Libraries/Components/View/ViewAccessibility.d.ts +++ b/Libraries/Components/View/ViewAccessibility.d.ts @@ -53,7 +53,7 @@ export interface AccessibilityProps * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: boolean | undefined; - 'aria-checked'?: boolean | undefined; + 'aria-checked'?: boolean | 'mixed' | undefined; 'aria-disabled'?: boolean | undefined; 'aria-expanded'?: boolean | undefined; 'aria-selected'?: boolean | undefined; diff --git a/Libraries/Components/View/ViewPropTypes.js b/Libraries/Components/View/ViewPropTypes.js index 3a88f4ce089dc4..2330f45c0051e0 100644 --- a/Libraries/Components/View/ViewPropTypes.js +++ b/Libraries/Components/View/ViewPropTypes.js @@ -531,7 +531,7 @@ export type ViewProps = $ReadOnly<{| * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', 'aria-disabled'?: ?boolean, 'aria-expanded'?: ?boolean, 'aria-selected'?: ?boolean, diff --git a/Libraries/Text/TextProps.js b/Libraries/Text/TextProps.js index 4ef9e7cec3ce39..abbbd76da14cad 100644 --- a/Libraries/Text/TextProps.js +++ b/Libraries/Text/TextProps.js @@ -86,7 +86,7 @@ export type TextProps = $ReadOnly<{| * see https://reactnative.dev/docs/accessibility#accessibilitystate */ 'aria-busy'?: ?boolean, - 'aria-checked'?: ?boolean, + 'aria-checked'?: ?boolean | 'mixed', 'aria-disabled'?: ?boolean, 'aria-expanded'?: ?boolean, 'aria-selected'?: ?boolean, From 51d14b9dbdba0ae978a61aecdfdce3142482e9f9 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 26 Oct 2022 12:28:44 -0700 Subject: [PATCH 045/169] Revert D40333083: Support persisted settings in Android + iOS Differential Revision: D40333083 (https://github.com/facebook/react-native/commit/0fac9817df403e31d8256befe52409c948614706) Original commit changeset: f3816e3bd7de Original Phabricator Diff: D40333083 (https://github.com/facebook/react-native/commit/0fac9817df403e31d8256befe52409c948614706) fbshipit-source-id: 1a52a06b057c4c0ea6e3e4c3315ba73a883e3579 --- Libraries/Core/setUpReactDevTools.js | 2 - .../DevToolsSettingsManager.android.js | 13 ----- .../DevToolsSettingsManager.ios.js | 33 ------------- .../NativeDevToolsSettingsManager.js | 22 --------- React/CoreModules/BUCK | 1 - .../src/main/java/com/facebook/react/BUCK | 1 - .../react/modules/devtoolssettings/BUCK | 28 ----------- .../DevToolsSettingsManagerModule.java | 49 ------------------- .../main/java/com/facebook/react/shell/BUCK | 1 - .../react/shell/MainReactPackage.java | 7 +-- .../test/java/com/facebook/react/modules/BUCK | 1 - 11 files changed, 1 insertion(+), 157 deletions(-) delete mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.android.js delete mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js delete mode 100644 Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java diff --git a/Libraries/Core/setUpReactDevTools.js b/Libraries/Core/setUpReactDevTools.js index ecdd14a44a65e4..be647e33b4d2ca 100644 --- a/Libraries/Core/setUpReactDevTools.js +++ b/Libraries/Core/setUpReactDevTools.js @@ -62,7 +62,6 @@ if (__DEV__) { }); const ReactNativeStyleAttributes = require('../Components/View/ReactNativeStyleAttributes'); - const devToolsSettingsManager = require('../DevToolsSettings/DevToolsSettingsManager'); reactDevTools.connectToDevTools({ isAppActive, @@ -71,7 +70,6 @@ if (__DEV__) { ReactNativeStyleAttributes, ), websocket: ws, - devToolsSettingsManager, }); } }; diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js deleted file mode 100644 index 262aafbcb0d69b..00000000000000 --- a/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -import NativeDevToolsSettingsManager from './NativeDevToolsSettingsManager'; - -module.exports = NativeDevToolsSettingsManager; diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js deleted file mode 100644 index fdc61730166bf4..00000000000000 --- a/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import type {Spec} from './NativeDevToolsSettingsManager'; - -import Settings from '../Settings/Settings'; - -const CONSOLE_PATCH_SETTINGS_KEY = 'ReactDevTools::ConsolePatchSettings'; - -const DevToolsSettingsManager = { - setConsolePatchSettings: (newConsolePatchSettings: string) => { - Settings.set({ - [CONSOLE_PATCH_SETTINGS_KEY]: newConsolePatchSettings, - }); - }, - getConsolePatchSettings: () => { - const value = Settings.get(CONSOLE_PATCH_SETTINGS_KEY); - if (typeof value === 'string') { - // $FlowFixMe[unclear-type] - return ((value: any): string); - } - return null; - }, -}; - -module.exports = (DevToolsSettingsManager: Spec); diff --git a/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js b/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js deleted file mode 100644 index 904e8d6701c756..00000000000000 --- a/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -import type {TurboModule} from '../TurboModule/RCTExport'; - -import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +setConsolePatchSettings: (newConsolePatchSettings: string) => void; - +getConsolePatchSettings: () => ?string; -} - -export default (TurboModuleRegistry.get( - 'DevToolsSettingsManager', -): ?Spec); diff --git a/React/CoreModules/BUCK b/React/CoreModules/BUCK index eda0220f3bd7df..5608bacdaea311 100644 --- a/React/CoreModules/BUCK +++ b/React/CoreModules/BUCK @@ -137,7 +137,6 @@ rn_apple_library( "//xplat/js/react-native-github:FBReactNativeSpecApple", "//xplat/js/react-native-github:RCTLinkingApple", "//xplat/js/react-native-github:RCTPushNotificationApple", - "//xplat/js/react-native-github:RCTSettingsApple", "//xplat/js/react-native-github:ReactInternalApple", ], ) diff --git a/ReactAndroid/src/main/java/com/facebook/react/BUCK b/ReactAndroid/src/main/java/com/facebook/react/BUCK index 08f8c1176bc528..dd21088699dab5 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/BUCK @@ -41,7 +41,6 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/appearance:appearance"), react_native_target("java/com/facebook/react/modules/bundleloader:bundleloader"), react_native_target("java/com/facebook/react/modules/debug:debug"), - react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/fabric:fabric"), react_native_target("java/com/facebook/react/modules/debug:interfaces"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK deleted file mode 100644 index 50f0d888a9cdf4..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK +++ /dev/null @@ -1,28 +0,0 @@ -load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") - -rn_android_library( - name = "devtoolssettings", - srcs = glob(["**/*.java"]), - autoglob = False, - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - "supermodule:xplat/default/public.react_native.infra", - ], - language = "JAVA", - provided_deps = [ - react_native_dep("third-party/android/androidx:annotation"), - ], - visibility = [ - "PUBLIC", - ], - deps = [ - react_native_dep("libraries/fbcore/src/main/java/com/facebook/common/logging:logging"), - react_native_dep("third-party/java/infer-annotations:infer-annotations"), - react_native_dep("third-party/java/jsr-305:jsr-305"), - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/common:common"), - react_native_target("java/com/facebook/react/module/annotations:annotations"), - react_native_target("java/com/facebook/react/modules/core:core"), - ], - exported_deps = [react_native_root_target(":FBReactNativeSpec")], -) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java deleted file mode 100644 index 0164de2788292f..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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.modules.devtoolssettings; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; -import androidx.annotation.Nullable; -import com.facebook.fbreact.specs.NativeDevToolsSettingsManagerSpec; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.module.annotations.ReactModule; - -@ReactModule(name = DevToolsSettingsManagerModule.NAME) -public class DevToolsSettingsManagerModule extends NativeDevToolsSettingsManagerSpec { - public static final String NAME = "DevToolsSettingsManager"; - - private static final String SHARED_PREFERENCES_PREFIX = "ReactNative__DevToolsSettings"; - private static final String KEY_CONSOLE_PATCH_SETTINGS = "ConsolePatchSettings"; - - private final SharedPreferences mSharedPreferences; - - public DevToolsSettingsManagerModule(ReactApplicationContext reactContext) { - super(reactContext); - mSharedPreferences = - reactContext.getSharedPreferences(SHARED_PREFERENCES_PREFIX, Context.MODE_PRIVATE); - } - - @Override - public String getName() { - return NAME; - } - - @Override - public @Nullable String getConsolePatchSettings() { - return mSharedPreferences.getString(KEY_CONSOLE_PATCH_SETTINGS, null); - } - - @Override - public void setConsolePatchSettings(String newSettings) { - Editor editor = mSharedPreferences.edit(); - editor.putString(KEY_CONSOLE_PATCH_SETTINGS, newSettings); - editor.apply(); - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK index f1ee669920aa9f..c79b69687e0654 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK @@ -37,7 +37,6 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/clipboard:clipboard"), react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), - react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/fresco:fresco"), react_native_target("java/com/facebook/react/modules/i18nmanager:i18nmanager"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index e9c0297a529a65..6fc4a536e2b1f7 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -23,7 +23,6 @@ import com.facebook.react.modules.blob.FileReaderModule; import com.facebook.react.modules.camera.ImageStoreManager; import com.facebook.react.modules.clipboard.ClipboardModule; -import com.facebook.react.modules.devtoolssettings.DevToolsSettingsManagerModule; import com.facebook.react.modules.dialog.DialogModule; import com.facebook.react.modules.fresco.FrescoModule; import com.facebook.react.modules.i18nmanager.I18nManagerModule; @@ -146,8 +145,6 @@ public MainReactPackage(MainPackageConfig config) { return new VibrationModule(context); case WebSocketModule.NAME: return new WebSocketModule(context); - case DevToolsSettingsManagerModule.NAME: - return new DevToolsSettingsManagerModule(context); default: return null; } @@ -188,8 +185,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { Class.forName("com.facebook.react.shell.MainReactPackage$$ReactModuleInfoProvider"); return (ReactModuleInfoProvider) reactModuleInfoProviderClass.newInstance(); } catch (ClassNotFoundException e) { - // In the OSS case, the annotation processor does not run. We fall back to creating this by - // hand + // In OSS case, the annotation processor does not run. We fall back on creating this byhand Class[] moduleList = new Class[] { AccessibilityInfoModule.class, @@ -208,7 +204,6 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { NativeAnimatedModule.class, NetworkingModule.class, PermissionsModule.class, - DevToolsSettingsManagerModule.class, ShareModule.class, StatusBarModule.class, SoundManagerModule.class, diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK index d8581c32d5dd90..7ab27c360a9714 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK @@ -34,7 +34,6 @@ rn_robolectric_test( react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), - react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/network:network"), react_native_target("java/com/facebook/react/modules/share:share"), From 10698418373d053584a9f32dc55d5e492ad643c5 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 26 Oct 2022 13:03:33 -0700 Subject: [PATCH 046/169] Make it easier for user to toggle only Fabric or TurboModules in New Architecture (#35091) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35091 This diff refines the DefaultNewArchitectureEntryPoint to make it easier for user to either turn on Fabric, TurboModules or both. Changelog: [Internal] [Changed] - Make it easier for user to toggle only Fabric or TurboModules in New Architecture Reviewed By: cipolleschi Differential Revision: D40710596 fbshipit-source-id: 236060b2ebccb1bf25e7f5c0fc15f54c5ce5f608 --- .../defaults/DefaultComponentsRegistry.kt | 4 +- .../react/defaults/DefaultNativeEntryPoint.kt | 29 ----------- .../DefaultNewArchitectureEntryPoint.kt | 49 +++++++++++++++++++ .../DefaultTurboModuleManagerDelegate.kt | 4 +- .../react/uiapp/RNTesterActivity.java | 5 +- .../react/uiapp/RNTesterApplication.java | 5 +- .../java/com/helloworld/MainActivity.java | 11 +++-- .../java/com/helloworld/MainApplication.java | 9 ++-- 8 files changed, 67 insertions(+), 49 deletions(-) delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNativeEntryPoint.kt create mode 100644 ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultComponentsRegistry.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultComponentsRegistry.kt index 4eb6401b35b21e..131804140ee901 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultComponentsRegistry.kt +++ b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultComponentsRegistry.kt @@ -15,8 +15,8 @@ import com.facebook.react.fabric.ComponentFactory * A utility class that provides users a ComponentRegistry they can customize with a C++ * implementation of its native methods. * - * This class works together with the [DefaultNativeEntryPoint] and it's C++ implementation is - * hosted inside the React Native framework + * This class works together with the [DefaultNewArchitectureEntryPoint] and it's C++ implementation + * is hosted inside the React Native framework */ @DoNotStrip class DefaultComponentsRegistry diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNativeEntryPoint.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNativeEntryPoint.kt deleted file mode 100644 index 02db04658aed62..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNativeEntryPoint.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.defaults - -import com.facebook.soloader.SoLoader - -/** - * A utility class that serves as an entry point for users to register all the custom Fabric - * Components and Turbo Native Modules. - * - * This class needs to be invoked as `DefaultNativeEntryPoint.load("...")` by passing the name of - * the dynamic library to load. - * - * By default it loads a library called `appmodules`. `appmodules` is a convention used to refer to - * the application dynamic library. If changed here should be updated also inside the template. - */ -object DefaultNativeEntryPoint { - @JvmStatic - @JvmOverloads - fun load(dynamicLibraryName: String = "appmodules") { - SoLoader.loadLibrary("react_newarchdefaults") - SoLoader.loadLibrary(dynamicLibraryName) - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt new file mode 100644 index 00000000000000..f3552517f75b63 --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt @@ -0,0 +1,49 @@ +/* + * 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.defaults + +import com.facebook.react.config.ReactFeatureFlags +import com.facebook.soloader.SoLoader + +/** + * A utility class that serves as an entry point for users setup the New Architecture. + * + * This class needs to be invoked as `DefaultNewArchitectureEntryPoint.load(...)` by passing a + * series of optional parameters. + * + * By default it loads a library called `appmodules`. `appmodules` is a convention used to refer to + * the application dynamic library. If changed here should be updated also inside the template. + * + * By default it also enables both TurboModules, Fabric and Concurrent React (aka React 18) + */ +object DefaultNewArchitectureEntryPoint { + @JvmStatic + @JvmOverloads + fun load( + dynamicLibraryName: String = "appmodules", + turboModulesEnabled: Boolean = true, + fabricEnabled: Boolean = true, + concurrentReactEnabled: Boolean = true + ) { + ReactFeatureFlags.useTurboModules = turboModulesEnabled + ReactFeatureFlags.enableFabricRenderer = fabricEnabled + + this.fabricEnabled = fabricEnabled + this.turboModulesEnabled = turboModulesEnabled + this.concurrentReactEnabled = concurrentReactEnabled + + SoLoader.loadLibrary("react_newarchdefaults") + SoLoader.loadLibrary(dynamicLibraryName) + } + + @JvmStatic var fabricEnabled: Boolean = false + + @JvmStatic var turboModulesEnabled: Boolean = false + + @JvmStatic var concurrentReactEnabled: Boolean = false +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultTurboModuleManagerDelegate.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultTurboModuleManagerDelegate.kt index 714bb654c77c30..ac1fd1a4c7d90c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultTurboModuleManagerDelegate.kt +++ b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultTurboModuleManagerDelegate.kt @@ -17,8 +17,8 @@ import com.facebook.react.bridge.ReactApplicationContext * A utility class that allows you to simplify the setup of a * [ReactPackageTurboModuleManagerDelegate] for new apps in Open Source. * - * This class works together with the [DefaultNativeEntryPoint] and it's C++ implementation is - * hosted inside the React Native framework + * This class works together with the [DefaultNewArchitectureEntryPoint] and it's C++ implementation + * is hosted inside the React Native framework */ class DefaultTurboModuleManagerDelegate private constructor(context: ReactApplicationContext, packages: List) : diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java index 143765e19840fe..da9cba600d30c5 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.java @@ -11,6 +11,7 @@ import androidx.annotation.Nullable; import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactActivityDelegate; public class RNTesterActivity extends ReactActivity { @@ -23,8 +24,8 @@ public RNTesterActivityDelegate(ReactActivity activity, String mainComponentName super( activity, mainComponentName, - true, // fabricEnabled - true // concurrentRootEnabled + DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled + DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled() // concurrentRootEnabled ); this.mActivity = activity; } diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java index cdc5ac628282a9..5012a0e45e4d9d 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java @@ -17,7 +17,7 @@ import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.config.ReactFeatureFlags; -import com.facebook.react.defaults.DefaultNativeEntryPoint; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactNativeHost; import com.facebook.react.module.model.ReactModuleInfo; import com.facebook.react.module.model.ReactModuleInfoProvider; @@ -119,11 +119,10 @@ protected boolean isNewArchEnabled() { @Override public void onCreate() { - ReactFeatureFlags.useTurboModules = true; ReactFontManager.getInstance().addCustomFont(this, "Rubik", R.font.rubik); super.onCreate(); SoLoader.init(this, /* native exopackage */ false); - DefaultNativeEntryPoint.load(); + DefaultNewArchitectureEntryPoint.load(); ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } diff --git a/template/android/app/src/main/java/com/helloworld/MainActivity.java b/template/android/app/src/main/java/com/helloworld/MainActivity.java index d66f035735aa3b..96fcdf2d7caf16 100644 --- a/template/android/app/src/main/java/com/helloworld/MainActivity.java +++ b/template/android/app/src/main/java/com/helloworld/MainActivity.java @@ -2,6 +2,7 @@ import com.facebook.react.ReactActivity; import com.facebook.react.ReactActivityDelegate; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactActivityDelegate; public class MainActivity extends ReactActivity { @@ -17,8 +18,8 @@ protected String getMainComponentName() { /** * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link - * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent Root (aka - * React 18) with two boolean flags. + * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React + * (aka React 18) with two boolean flags. */ @Override protected ReactActivityDelegate createReactActivityDelegate() { @@ -26,9 +27,9 @@ protected ReactActivityDelegate createReactActivityDelegate() { this, getMainComponentName(), // If you opted-in for the New Architecture, we enable the Fabric Renderer. - BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, // fabricEnabled - // If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18). - BuildConfig.IS_NEW_ARCHITECTURE_ENABLED // concurrentRootEnabled + DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled + // If you opted-in for the New Architecture, we enable Concurrent React (i.e. React 18). + DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled() // concurrentRootEnabled ); } } diff --git a/template/android/app/src/main/java/com/helloworld/MainApplication.java b/template/android/app/src/main/java/com/helloworld/MainApplication.java index ccf1addb2b9d9b..be113ec43969fd 100644 --- a/template/android/app/src/main/java/com/helloworld/MainApplication.java +++ b/template/android/app/src/main/java/com/helloworld/MainApplication.java @@ -5,8 +5,7 @@ import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; -import com.facebook.react.config.ReactFeatureFlags; -import com.facebook.react.defaults.DefaultNativeEntryPoint; +import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint; import com.facebook.react.defaults.DefaultReactNativeHost; import com.facebook.soloader.SoLoader; import java.util.List; @@ -50,10 +49,8 @@ public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { - // If you opted-in for the New Architecture, we enable the TurboModule system - // and load the native entry point for this app. - ReactFeatureFlags.useTurboModules = true; - DefaultNativeEntryPoint.load(); + // If you opted-in for the New Architecture, we load the native entry point for this app. + DefaultNewArchitectureEntryPoint.load(); } ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } From 2df63e52f4570f348156bcd47696b8395a73fbc7 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 26 Oct 2022 13:05:03 -0700 Subject: [PATCH 047/169] RNGP - Use the File Api to specify cliPath and remove ComposeSourceMap path (#35092) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35092 As we're close to the cut of the 0.71 branch, I'll take the opportunity to polish our Gradle public API. We're exposing a mixture of Path (String) and File (java.io.File or RegularFileProperty). Here I've moved everything to use File as it's more configurable for the users, specifically if they're using monorepos or other setup. This also allows us to remove the resolution logic for the cliPath. Changelog: [Internal] [Changed] - RNGP - Use the File Api to specify cliPath and remove ComposeSourceMap path Reviewed By: cipolleschi Differential Revision: D40710595 fbshipit-source-id: a17095eebae5123b70fd2b8e3d512656817006ca --- .../com/facebook/react/ReactExtension.kt | 32 +++----- .../com/facebook/react/TaskConfiguration.kt | 10 +-- .../facebook/react/tasks/BundleHermesCTask.kt | 15 ++-- .../com/facebook/react/utils/PathUtils.kt | 56 ++++++-------- .../react/tasks/BundleHermesCTaskTest.kt | 30 ++++---- .../com/facebook/react/utils/PathUtilsTest.kt | 76 +++---------------- packages/rn-tester/android/app/build.gradle | 5 +- 7 files changed, 78 insertions(+), 146 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt index 08350da88d90ae..5dfb3737ee9d3e 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/ReactExtension.kt @@ -28,6 +28,14 @@ abstract class ReactExtension @Inject constructor(project: Project) { val root: DirectoryProperty = objects.directoryProperty().convention(project.rootProject.layout.projectDirectory.dir("../")) + /** + * The path to the react-native NPM package folder. + * + * Default: ${rootProject.dir}/../node_modules/react-native-codegen + */ + val reactNativeDir: DirectoryProperty = + objects.directoryProperty().convention(root.dir("node_modules/react-native")) + /** * The path to the JS entry file. If not specified, the plugin will try to resolve it using a list * of known locations (e.g. `index.android.js`, `index.js`, etc.). @@ -35,10 +43,11 @@ abstract class ReactExtension @Inject constructor(project: Project) { val entryFile: RegularFileProperty = objects.fileProperty() /** - * The path to the React Native CLI. If not specified, the plugin will try to resolve it looking - * for `react-native` CLI inside `node_modules` in [root]. + * The reference to the React Native CLI. If not specified, the plugin will try to resolve it + * looking for `react-native` CLI inside `node_modules` in [root]. */ - val cliPath: Property = objects.property(String::class.java) + val cliFile: RegularFileProperty = + objects.fileProperty().convention(reactNativeDir.file("cli.js")) /** * The path to the Node executable and extra args. By default it assumes that you have `node` @@ -107,15 +116,6 @@ abstract class ReactExtension @Inject constructor(project: Project) { val hermesFlags: ListProperty = objects.listProperty(String::class.java).convention(listOf("-O", "-output-source-map")) - /** - * The path to the Compose Source Map script. Default: - * "node_modules/react-native/scripts/compose-source-maps.js" - */ - val composeSourceMapsPath: Property = - objects - .property(String::class.java) - .convention("node_modules/react-native/scripts/compose-source-maps.js") - /** Codegen Config */ /** @@ -126,14 +126,6 @@ abstract class ReactExtension @Inject constructor(project: Project) { val codegenDir: DirectoryProperty = objects.directoryProperty().convention(root.dir("node_modules/react-native-codegen")) - /** - * The path to the react-native NPM package folder. - * - * Default: ${rootProject.dir}/../node_modules/react-native-codegen - */ - val reactNativeDir: DirectoryProperty = - objects.directoryProperty().convention(root.dir("node_modules/react-native")) - /** * The root directory for all JS files for the app. * diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt index 757c80e99e18c1..bb3699d58df095 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/TaskConfiguration.kt @@ -12,7 +12,7 @@ import com.facebook.react.tasks.BundleHermesCTask import com.facebook.react.utils.NdkConfiguratorUtils.configureJsEnginePackagingOptions import com.facebook.react.utils.NdkConfiguratorUtils.configureNewArchPackagingOptions import com.facebook.react.utils.ProjectUtils.isHermesEnabled -import com.facebook.react.utils.detectedCliPath +import com.facebook.react.utils.detectedCliFile import com.facebook.react.utils.detectedEntryFile import java.io.File import org.gradle.api.Project @@ -32,8 +32,8 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio // Intermediate compiler: intermediates/sourcemaps/react/path/index.android.bundle.compiler.map val jsIntermediateSourceMapsDir = File(buildDir, "intermediates/sourcemaps/react/$targetPath") - // Additional node and packager commandline arguments - val cliPath = detectedCliPath(project.projectDir, config) + // The location of the cli.js file for React Native + val cliFile = detectedCliFile(config) val isHermesEnabledInProject = project.isHermesEnabled val isHermesEnabledInThisVariant = @@ -54,7 +54,7 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio tasks.register("createBundle${targetName}JsAndAssets", BundleHermesCTask::class.java) { it.root.set(config.root) it.nodeExecutableAndArgs.set(config.nodeExecutableAndArgs) - it.cliPath.set(cliPath) + it.cliFile.set(cliFile) it.bundleCommand.set(config.bundleCommand) it.entryFile.set(detectedEntryFile(config)) it.extraPackagerArgs.set(config.extraPackagerArgs) @@ -69,7 +69,7 @@ internal fun Project.configureReactTasks(variant: Variant, config: ReactExtensio it.jsSourceMapsDir.set(jsSourceMapsDir) it.hermesCommand.set(config.hermesCommand) it.hermesFlags.set(config.hermesFlags) - it.composeSourceMapsPath.set(config.composeSourceMapsPath) + it.reactNativeDir.set(config.reactNativeDir) } variant.sources.res?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::resourcesDir) variant.sources.assets?.addGeneratedSourceDirectory(bundleTask, BundleHermesCTask::jsBundleDir) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt index 66490377b0212c..2801d3aea63413 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/BundleHermesCTask.kt @@ -42,9 +42,9 @@ abstract class BundleHermesCTask : DefaultTask() { @get:Input abstract val nodeExecutableAndArgs: ListProperty - @get:Input abstract val cliPath: Property + @get:InputFile abstract val cliFile: RegularFileProperty - @get:Input abstract val composeSourceMapsPath: Property + @get:Internal abstract val reactNativeDir: DirectoryProperty @get:Input abstract val bundleCommand: Property @@ -101,8 +101,12 @@ abstract class BundleHermesCTask : DefaultTask() { if (hermesFlags.get().contains("-output-source-map")) { val hermesTempSourceMapFile = File("$bytecodeFile.map") hermesTempSourceMapFile.moveTo(compilerSourceMap) + + val reactNativeDir = reactNativeDir.get().asFile + val composeScriptFile = File(reactNativeDir, "scripts/compose-source-maps.js") val composeSourceMapsCommand = - getComposeSourceMapsCommand(packagerSourceMap, compilerSourceMap, outputSourceMap) + getComposeSourceMapsCommand( + composeScriptFile, packagerSourceMap, compilerSourceMap, outputSourceMap) runCommand(composeSourceMapsCommand) } } @@ -132,7 +136,7 @@ abstract class BundleHermesCTask : DefaultTask() { windowsAwareCommandLine( buildList { addAll(nodeExecutableAndArgs.get()) - add(cliPath.get()) + add(cliFile.get().asFile.absolutePath) add(bundleCommand.get()) add("--platform") add("android") @@ -171,13 +175,14 @@ abstract class BundleHermesCTask : DefaultTask() { *hermesFlags.get().toTypedArray()) internal fun getComposeSourceMapsCommand( + composeScript: File, packagerSourceMap: File, compilerSourceMap: File, outputSourceMap: File ): List = windowsAwareCommandLine( *nodeExecutableAndArgs.get().toTypedArray(), - composeSourceMapsPath.get(), + composeScript.absolutePath, packagerSourceMap.toString(), compilerSourceMap.toString(), "-o", diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt index 41130173edafff..74fe49ca17a316 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/PathUtils.kt @@ -28,20 +28,16 @@ internal fun detectedEntryFile(config: ReactExtension): File = entryFile = config.entryFile.orNull?.asFile, reactRoot = config.root.get().asFile) /** - * Computes the CLI location for React Native. The Algo follows this order: - * 1. The path provided by the `cliPath` config in the `reactApp` Gradle extension + * Computes the CLI file for React Native. The Algo follows this order: + * 1. The path provided by the `cliFile` config in the `react {}` Gradle extension * 2. The output of `node --print "require.resolve('react-native/cli');"` if not failing. * 3. The `node_modules/react-native/cli.js` file if exists * 4. Fails otherwise */ -internal fun detectedCliPath( - projectDir: File, - config: ReactExtension, -): String = - detectCliPath( - projectDir = projectDir, - reactRoot = config.root.get().asFile, - preconfiguredCliPath = config.cliPath.orNull) +internal fun detectedCliFile(config: ReactExtension): File = + detectCliFile( + reactNativeRoot = config.root.get().asFile, + preconfiguredCliFile = config.cliFile.asFile.orNull) /** * Computes the `hermesc` command location. The Algo follows this order: @@ -64,24 +60,11 @@ private fun detectEntryFile(entryFile: File?, reactRoot: File): File = else -> File(reactRoot, "index.js") } -private fun detectCliPath( - projectDir: File, - reactRoot: File, - preconfiguredCliPath: String? -): String { +private fun detectCliFile(reactNativeRoot: File, preconfiguredCliFile: File?): File { // 1. preconfigured path - if (preconfiguredCliPath != null) { - val preconfiguredCliJsAbsolute = File(preconfiguredCliPath) - if (preconfiguredCliJsAbsolute.exists()) { - return preconfiguredCliJsAbsolute.absolutePath - } - val preconfiguredCliJsRelativeToReactRoot = File(reactRoot, preconfiguredCliPath) - if (preconfiguredCliJsRelativeToReactRoot.exists()) { - return preconfiguredCliJsRelativeToReactRoot.absolutePath - } - val preconfiguredCliJsRelativeToProject = File(projectDir, preconfiguredCliPath) - if (preconfiguredCliJsRelativeToProject.exists()) { - return preconfiguredCliJsRelativeToProject.absolutePath + if (preconfiguredCliFile != null) { + if (preconfiguredCliFile.exists()) { + return preconfiguredCliFile } } @@ -91,27 +74,32 @@ private fun detectCliPath( .exec( arrayOf("node", "--print", "require.resolve('react-native/cli');"), emptyArray(), - reactRoot) + reactNativeRoot) val nodeProcessOutput = nodeProcess.inputStream.use { it.bufferedReader().readText().trim() } if (nodeProcessOutput.isNotEmpty()) { val nodeModuleCliJs = File(nodeProcessOutput) if (nodeModuleCliJs.exists()) { - return nodeModuleCliJs.absolutePath + return nodeModuleCliJs } } // 3. cli.js in the root folder - val rootCliJs = File(reactRoot, "node_modules/react-native/cli.js") + val rootCliJs = File(reactNativeRoot, "node_modules/react-native/cli.js") if (rootCliJs.exists()) { - return rootCliJs.absolutePath + return rootCliJs } error( - "Couldn't determine CLI location. " + - "Please set `project.react.cliPath` to the path of the react-native cli.js file. " + - "This file typically resides in `node_modules/react-native/cli.js`") + """ + Couldn't determine CLI location! + + Please set `react { cliFile = file(...) }` inside your + build.gradle to the path of the react-native cli.js file. + This file typically resides in `node_modules/react-native/cli.js` + """ + .trimIndent()) } /** diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt index d8563d663a9d97..fbe7fed6304946 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/BundleHermesCTaskTest.kt @@ -85,9 +85,6 @@ class BundleHermesCTaskTest { val task = createTestTask { it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.cliPath.set("../node_modules/react-native/cli.js") - it.composeSourceMapsPath.set( - "../node_modules/react-native/scripts/compose-source-maps.js") it.bundleCommand.set("bundle") it.bundleAssetName.set("myassetname") it.minifyEnabled.set(true) @@ -99,10 +96,6 @@ class BundleHermesCTaskTest { } assertEquals(listOf("node", "arg1", "arg2"), task.nodeExecutableAndArgs.get()) - assertEquals("../node_modules/react-native/cli.js", task.cliPath.get()) - assertEquals( - "../node_modules/react-native/scripts/compose-source-maps.js", - task.composeSourceMapsPath.get()) assertEquals("bundle", task.bundleCommand.get()) assertEquals("myassetname", task.bundleAssetName.get()) assertTrue(task.minifyEnabled.get()) @@ -116,28 +109,34 @@ class BundleHermesCTaskTest { @Test fun bundleTask_filesInput_areSetCorrectly() { val entryFile = tempFolder.newFile("entry.js") + val cliFile = tempFolder.newFile("cli.js") val jsBundleDir = tempFolder.newFolder("jsbundle") val resourcesDir = tempFolder.newFolder("resources") val jsIntermediateSourceMapsDir = tempFolder.newFolder("jsIntermediateSourceMaps") val jsSourceMapsDir = tempFolder.newFolder("jsSourceMaps") val bundleConfig = tempFolder.newFile("bundle.config") + val reactNativeDir = tempFolder.newFolder("node_modules/react-native") val task = createTestTask { it.entryFile.set(entryFile) + it.cliFile.set(cliFile) it.jsBundleDir.set(jsBundleDir) it.resourcesDir.set(resourcesDir) it.jsIntermediateSourceMapsDir.set(jsIntermediateSourceMapsDir) it.jsSourceMapsDir.set(jsSourceMapsDir) it.bundleConfig.set(bundleConfig) + it.reactNativeDir.set(reactNativeDir) } assertEquals(entryFile, task.entryFile.get().asFile) + assertEquals(cliFile, task.cliFile.get().asFile) assertEquals(jsBundleDir, task.jsBundleDir.get().asFile) assertEquals(resourcesDir, task.resourcesDir.get().asFile) assertEquals(jsIntermediateSourceMapsDir, task.jsIntermediateSourceMapsDir.get().asFile) assertEquals(jsSourceMapsDir, task.jsSourceMapsDir.get().asFile) assertEquals(bundleConfig, task.bundleConfig.get().asFile) + assertEquals(reactNativeDir, task.reactNativeDir.get().asFile) } @Test @@ -198,6 +197,7 @@ class BundleHermesCTaskTest { @Test fun getBundleCommand_returnsCorrectCommand() { val entryFile = tempFolder.newFile("index.js") + val cliFile = tempFolder.newFile("cli.js") val bundleFile = tempFolder.newFile("bundle.js") val sourceMapFile = tempFolder.newFile("bundle.js.map") val resourcesDir = tempFolder.newFolder("res") @@ -205,7 +205,7 @@ class BundleHermesCTaskTest { val task = createTestTask { it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.cliPath.set("../node_modules/react-native/cli.js") + it.cliFile.set(cliFile) it.bundleCommand.set("bundle") it.devEnabled.set(true) it.entryFile.set(entryFile) @@ -220,7 +220,7 @@ class BundleHermesCTaskTest { assertEquals("node", bundleCommand[0]) assertEquals("arg1", bundleCommand[1]) assertEquals("arg2", bundleCommand[2]) - assertEquals("../node_modules/react-native/cli.js", bundleCommand[3]) + assertEquals(cliFile.absolutePath, bundleCommand[3]) assertEquals("bundle", bundleCommand[4]) assertEquals("--platform", bundleCommand[5]) assertEquals("android", bundleCommand[6]) @@ -247,13 +247,14 @@ class BundleHermesCTaskTest { @Test fun getBundleCommand_withoutConfig_returnsCommandWithoutConfig() { val entryFile = tempFolder.newFile("index.js") + val cliFile = tempFolder.newFile("cli.js") val bundleFile = tempFolder.newFile("bundle.js") val sourceMapFile = tempFolder.newFile("bundle.js.map") val resourcesDir = tempFolder.newFolder("res") val task = createTestTask { it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.cliPath.set("../node_modules/react-native/cli.js") + it.cliFile.set(cliFile) it.bundleCommand.set("bundle") it.devEnabled.set(true) it.entryFile.set(entryFile) @@ -291,21 +292,20 @@ class BundleHermesCTaskTest { val packagerMap = tempFolder.newFile("bundle.js.packager.map") val compilerMap = tempFolder.newFile("bundle.js.compiler.map") val outputMap = tempFolder.newFile("bundle.js.map") + val reactNativeDir = tempFolder.newFolder("node_modules/react-native") + val composeSourceMapsFile = File(reactNativeDir, "scripts/compose-source-maps.js") val task = createTestTask { it.nodeExecutableAndArgs.set(listOf("node", "arg1", "arg2")) - it.composeSourceMapsPath.set( - "../node_modules/react-native/scripts/compose-source-maps.js") } val composeSourcemapCommand = - task.getComposeSourceMapsCommand(packagerMap, compilerMap, outputMap) + task.getComposeSourceMapsCommand(composeSourceMapsFile, packagerMap, compilerMap, outputMap) assertEquals("node", composeSourcemapCommand[0]) assertEquals("arg1", composeSourcemapCommand[1]) assertEquals("arg2", composeSourcemapCommand[2]) - assertEquals( - "../node_modules/react-native/scripts/compose-source-maps.js", composeSourcemapCommand[3]) + assertEquals(composeSourceMapsFile.absolutePath, composeSourcemapCommand[3]) assertEquals(packagerMap.absolutePath, composeSourcemapCommand[4]) assertEquals(compilerMap.absolutePath, composeSourcemapCommand[5]) assertEquals("-o", composeSourcemapCommand[6]) diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt index b0f7474cd23a40..fb230f49551df6 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/PathUtilsTest.kt @@ -59,83 +59,31 @@ class PathUtilsTest { } @Test - fun detectedCliPath_withCliPathFromExtensionAbsolute() { + fun detectedCliPath_withCliPathFromExtensionAndFileExists_returnsIt() { val project = ProjectBuilder.builder().build() + val cliFile = tempFolder.newFile("cli.js").apply { createNewFile() } val extension = TestReactExtension(project) - val expected = - File(project.projectDir, "abs/fake-cli.sh").apply { - parentFile.mkdirs() - writeText("") - } - extension.cliPath.set(project.projectDir.toString() + "/abs/fake-cli.sh") + extension.cliFile.set(cliFile) - val actual = detectedCliPath(project.projectDir, extension) + val actual = detectedCliFile(extension) - assertEquals(expected.toString(), actual) - } - - @Test - fun detectedCliPath_withCliPathFromExtensionInReactFolder() { - val project = ProjectBuilder.builder().build() - val extension = TestReactExtension(project) - val expected = - File(project.projectDir, "/react-root/fake-cli.sh").apply { - parentFile.mkdirs() - writeText("") - } - extension.cliPath.set("fake-cli.sh") - extension.root.set(File(project.projectDir.toString(), "react-root")) - - val actual = detectedCliPath(project.projectDir, extension) - - assertEquals(expected.toString(), actual) - } - - @Test - fun detectedCliPath_withCliPathFromExtensionInProjectFolder() { - val project = ProjectBuilder.builder().build() - val extension = TestReactExtension(project) - val expected = - File(project.projectDir, "fake-cli.sh").apply { - parentFile.mkdirs() - writeText("") - } - extension.cliPath.set("fake-cli.sh") - - val actual = detectedCliPath(project.projectDir, extension) - - assertEquals(expected.toString(), actual) - } - - @Test - fun detectedCliPath_withCliPathFromExtensionInParentFolder() { - val rootProject = ProjectBuilder.builder().build() - val project = ProjectBuilder.builder().withParent(rootProject).build() - project.projectDir.mkdirs() - val extension = TestReactExtension(project) - val expected = File(rootProject.projectDir, "cli-in-root.sh").apply { writeText("#!/bin/bash") } - extension.cliPath.set("../cli-in-root.sh") - - val actual = detectedCliPath(project.projectDir, extension) - - assertEquals(expected.canonicalPath, File(actual).canonicalPath) + assertEquals(cliFile, actual) } @Test fun detectedCliPath_withCliFromNodeModules() { val project = ProjectBuilder.builder().build() val extension = TestReactExtension(project) - val expected = - File(tempFolder.root, "node_modules/react-native/cli.js").apply { - parentFile.mkdirs() - writeText("") - } + File(tempFolder.root, "node_modules/react-native/cli.js").apply { + parentFile.mkdirs() + writeText("") + } val locationToResolveFrom = File(tempFolder.root, "a-subdirectory").apply { mkdirs() } extension.root.set(locationToResolveFrom) - val actual = detectedCliPath(project.projectDir, extension) + val actual = detectedCliFile(extension) - assertEquals(expected.canonicalPath, actual) + assertEquals("", actual.readText()) } @Test(expected = IllegalStateException::class) @@ -143,7 +91,7 @@ class PathUtilsTest { val project = ProjectBuilder.builder().build() val extension = TestReactExtension(project) - detectedCliPath(project.projectDir, extension) + detectedCliFile(extension) } @Test diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index c26d4444cf3030..1bfd0ebc649614 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -76,18 +76,17 @@ plugins { */ react { - cliPath = "../../../../cli.js" + cliFile = file("$rootDir/cli.js") bundleAssetName = "RNTesterApp.android.bundle" entryFile = file("../../js/RNTesterApp.android.js") root = file("../../") - composeSourceMapsPath = "$rootDir/scripts/compose-source-maps.js" hermesCommand = "$rootDir/ReactAndroid/hermes-engine/build/hermes/bin/hermesc" debuggableVariants = ["hermesDebug", "jscDebug"] enableHermesOnlyInVariants = ["hermesDebug", "hermesRelease"] // Codegen Configs reactNativeDir = rootDir - codegenDir = new File(rootDir, "node_modules/react-native-codegen") + codegenDir = file("$rootDir/node_modules/react-native-codegen") } /** From 92d41c5e96b153895b8abdc6e0c7dfe05b6e9437 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 26 Oct 2022 13:05:23 -0700 Subject: [PATCH 048/169] Remove the --dry-run gate from publishing to Sonatype Summary: This remove a flag to effectively go publishing to Sonatype. The idea was to protect us against accidentally publishing a nightly as a stable release. We need to remove this before RC0 Changelog: [Internal] [Changed] - Remove the --dry-run gate from publishing to Sonatype Reviewed By: cipolleschi Differential Revision: D40687038 fbshipit-source-id: e6821905f41899430813f9575f17a5068b05a9bb --- scripts/release-utils.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/scripts/release-utils.js b/scripts/release-utils.js index 801afc93852f9d..57a091029f1aa2 100644 --- a/scripts/release-utils.js +++ b/scripts/release-utils.js @@ -81,10 +81,7 @@ function publishAndroidArtifactsToMaven(isNightly) { if (!isNightly) { // -------- For stable releases, we also need to close and release the staging repository. - // TODO(ncor): Remove the --dry-run before RC0 - if ( - exec('./gradlew closeAndReleaseSonatypeStagingRepository --dry-run').code - ) { + if (exec('./gradlew closeAndReleaseSonatypeStagingRepository').code) { echo( 'Failed to close and release the staging repository on Sonatype (Maven Central)', ); From 279cfec55fdf404fdb9198edbb37d3adfdfb3bf1 Mon Sep 17 00:00:00 2001 From: Andre Date: Wed, 26 Oct 2022 19:59:28 -0700 Subject: [PATCH 049/169] feat: make RCTBlobManager TurboModule-compatible (#35047) Summary: Currently, RCTBlobManager (the native module for Blob support) cannot be loaded on iOS when the new architecture is enabled. ## Changelog [General] [Added] - `BlobModule` to `RCTCoreModulesClassProvider` Pull Request resolved: https://github.com/facebook/react-native/pull/35047 Test Plan: The snippet below can be used to test Blob support with the new architecture enabled. ``` // App.tsx import { useEffect } from 'react'; import { View } from 'react-native'; function uriToBlob(uri: any) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = () => { const blob = xhr.response; resolve(blob); }; xhr.onerror = err => { reject(err); }; xhr.open('GET', uri); xhr.send(); }); } export default function App() { useEffect(() => { uriToBlob('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'); }); return ; } ``` Related issue: https://github.com/facebook/react-native/issues/35042 Reviewed By: NickGerleman Differential Revision: D40716048 Pulled By: cipolleschi fbshipit-source-id: 17643d230fa7ea83baee363d137d51f87818baa8 --- React/CoreModules/CoreModulesPlugins.h | 1 + React/CoreModules/CoreModulesPlugins.mm | 1 + 2 files changed, 2 insertions(+) diff --git a/React/CoreModules/CoreModulesPlugins.h b/React/CoreModules/CoreModulesPlugins.h index 55015a55c1276b..632fd5aeab1ba2 100644 --- a/React/CoreModules/CoreModulesPlugins.h +++ b/React/CoreModules/CoreModulesPlugins.h @@ -54,6 +54,7 @@ Class RCTWebSocketModuleCls(void) __attribute__((used)); Class RCTDevLoadingViewCls(void) __attribute__((used)); Class RCTDevSplitBundleLoaderCls(void) __attribute__((used)); Class RCTEventDispatcherCls(void) __attribute__((used)); +Class RCTBlobManagerCls(void) __attribute__((used)); #ifdef __cplusplus } diff --git a/React/CoreModules/CoreModulesPlugins.mm b/React/CoreModules/CoreModulesPlugins.mm index e74ddb8ee0192d..8915f029c3fb21 100644 --- a/React/CoreModules/CoreModulesPlugins.mm +++ b/React/CoreModules/CoreModulesPlugins.mm @@ -37,6 +37,7 @@ Class RCTCoreModulesClassProvider(const char *name) { {"PerfMonitor", RCTPerfMonitorCls}, {"DevMenu", RCTDevMenuCls}, {"DevSettings", RCTDevSettingsCls}, + {"BlobModule", RCTBlobManagerCls}, {"RedBox", RCTRedBoxCls}, {"LogBox", RCTLogBoxCls}, {"WebSocketExecutor", RCTWebSocketExecutorCls}, From 3982a2c6bd116a6dcc6ee6889e4a246b710b70a7 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 26 Oct 2022 20:09:32 -0700 Subject: [PATCH 050/169] Log Abnormal Closes to Metro Websocket Summary: We are running into a group seeing frequent disconnects from Metro in a specific office. These are surfaced (at least on iOS) as websocket closures, without a prior websocket error. WebSocket closure can be for a variety of reasons, and the spec for a CloseEvent is to include fields `wasClean`, `code`, and `reason`, with `code` having the most well-defined meaning. This change makes it so that we emit extra context when the websocket is closed. That should help inform developers the reason behind any close that may be abnormal. Changelog: [General][Added] - Log Abnormal Closes to Metro Websocket Reviewed By: motiz88 Differential Revision: D40660765 fbshipit-source-id: ef606d8d809af1c697a78eb00cc5666c29a8bca3 --- Libraries/Utilities/HMRClient.js | 18 ++++++++++++++++-- Libraries/WebSocket/WebSocket.js | 9 ++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Libraries/Utilities/HMRClient.js b/Libraries/Utilities/HMRClient.js index 6a56826866e24a..b37f5961d2e0b3 100644 --- a/Libraries/Utilities/HMRClient.js +++ b/Libraries/Utilities/HMRClient.js @@ -241,9 +241,23 @@ Error: ${e.message}`; } }); - client.on('close', data => { + client.on('close', closeEvent => { LoadingView.hide(); - setHMRUnavailableReason('Disconnected from Metro.'); + + // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1 + // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5 + const isNormalOrUnsetCloseReason = + closeEvent.code === 1000 || + closeEvent.code === 1005 || + closeEvent.code == null; + + if (isNormalOrUnsetCloseReason) { + setHMRUnavailableReason('Disconnected from Metro.'); + } else { + setHMRUnavailableReason( + `Disconnected from Metro (${closeEvent.code}: "${closeEvent.reason}").`, + ); + } }); if (isEnabled) { diff --git a/Libraries/WebSocket/WebSocket.js b/Libraries/WebSocket/WebSocket.js index b2093b3af28a4b..3fdde2b3639adf 100644 --- a/Libraries/WebSocket/WebSocket.js +++ b/Libraries/WebSocket/WebSocket.js @@ -43,6 +43,10 @@ const CLOSED = 3; const CLOSE_NORMAL = 1000; +// Abnormal closure where no code is provided in a control frame +// https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5 +const CLOSE_ABNORMAL = 1006; + const WEBSOCKET_EVENTS = ['close', 'error', 'message', 'open']; let nextWebSocketId = 0; @@ -260,6 +264,7 @@ class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) { new WebSocketEvent('close', { code: ev.code, reason: ev.reason, + // TODO: missing `wasClean` (exposed on iOS as `clean` but missing on Android) }), ); this._unregisterEvents(); @@ -277,7 +282,9 @@ class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) { ); this.dispatchEvent( new WebSocketEvent('close', { - message: ev.message, + code: CLOSE_ABNORMAL, + reason: ev.message, + // TODO: Expose `wasClean` }), ); this._unregisterEvents(); From fa2842d113f04c8d33d2f71f43d4232e470b77ac Mon Sep 17 00:00:00 2001 From: Rick Hanlon Date: Wed, 26 Oct 2022 22:03:19 -0700 Subject: [PATCH 051/169] Do not filter errors/warnings from console Summary: ## Overview When I implemented `ignoreLogs` it was originally just to move `console.ignoreYellowBox` over to LogBox. When I did that, I also added filtering for console messages too. My thought process was: Developers probably don't want to configure hiding logs twice, so the LogBox method can handle both. This was a mistake. We should never hide console errors and warnings, because it completely silences important feedback to the users such as deprecation warnings. These issues should be fixed, not silenced, and since adding the silencing behavior it's clear that this feature is being abused to ignore legitimate warnings that need address. Issue #33557 is a great reason why - the correct fix for this is not to ignore the errors, it's to address the deprecation / removal of the API. Allowing an easy `ignoreLog` method to hide the problem made this migration much more painful. Thus, we're reverting back to the pre-logbox behavior of always showing console logs, even if they're ignored by LogBox in the app UI. Hopefully, this results in more of these issue being addressed instead of ignored. Changelog: [General] [Changed] - Do not filter errors/warnings from console Reviewed By: yungsters Differential Revision: D40724661 fbshipit-source-id: de3d2db1b0c32dee96acf92c9b1ca07ba0f4e218 --- Libraries/LogBox/LogBox.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Libraries/LogBox/LogBox.js b/Libraries/LogBox/LogBox.js index 35cd3e32ea2447..a597ca5acf9199 100644 --- a/Libraries/LogBox/LogBox.js +++ b/Libraries/LogBox/LogBox.js @@ -143,6 +143,9 @@ if (__DEV__) { if (LogBoxData.isLogBoxErrorMessage(String(args[0]))) { originalConsoleError(...args); return; + } else { + // Be sure to pass LogBox warnings through. + originalConsoleWarn(...args); } try { @@ -150,9 +153,6 @@ if (__DEV__) { const {category, message, componentStack} = parseLogBoxLog(args); if (!LogBoxData.isMessageIgnored(message.content)) { - // Be sure to pass LogBox warnings through. - originalConsoleWarn(...args); - LogBoxData.addLog({ level: 'warn', category, @@ -205,12 +205,12 @@ if (__DEV__) { args[0] = `Warning: ${filterResult.finalFormat}`; const {category, message, componentStack} = parseLogBoxLog(args); - if (!LogBoxData.isMessageIgnored(message.content)) { - // Interpolate the message so they are formatted for adb and other CLIs. - // This is different than the message.content above because it includes component stacks. - const interpolated = parseInterpolation(args); - originalConsoleError(interpolated.message.content); + // Interpolate the message so they are formatted for adb and other CLIs. + // This is different than the message.content above because it includes component stacks. + const interpolated = parseInterpolation(args); + originalConsoleError(interpolated.message.content); + if (!LogBoxData.isMessageIgnored(message.content)) { LogBoxData.addLog({ level, category, From b966d297245a4c1e2c744cfe571396cfa7e5ffd3 Mon Sep 17 00:00:00 2001 From: Rick Hanlon Date: Wed, 26 Oct 2022 22:03:19 -0700 Subject: [PATCH 052/169] Add back deprecated prop-types Summary: In 2017, React published v15.5 which extracted the built-in `prop types` to a separate package to reflect the fact that not everybody uses them. In 2018, React Native started to remove `PropTypes` from React Native for the same reason. In 0.68 React Native introduced a deprecation warning which notified users that the change was coming, and in 0.69 we removed the PropTypes entirely. The feedback we've received from the community is that there has not been enough time to migrate libraries off of PropTypes. This has resulted in users needing to patch the React Native package `index.js` file directly to add back the PropTypes, instead of migrating off of them. We can empathize with this fix short term (it unblocks the upgrade) but long term this patch will cause users to miss important changes to `index.js`, and add a maintenance cost for users. Part of the reason there was not enough time is that we didn't do a good job surfacing libraries that were using PropTypes. This means, when you got a deprecation warning, it wasn't clear where the source of the usage was (either in your code or in a library). So even if you wanted to migrate, it was difficult to know where to actually make the change. In the next release, we've made it easier to find call sites using deprecated types by [fixing the code frame in errors](https://github.com/react-native-community/cli/pull/1699) reporting in LogBox, and ensuring that [the app doesn't crash without a warning](https://github.com/facebook/react-native/pull/34650). This should make it easier to identify exactly where the deprecated usage is, so you can migrate it. To help users get off of the patch, and allow more time to migrate, we're walking back the removal of PropTypes, and keeping it as a deprecation for a couple more versions. We ask that you either migrate off PropTypes to a type system like TypeScript, or migrate to the `deprecated-react-native-prop-types` package. Once we feel more confident that the community has migrated and will not need to patch React Native in order to fix this issue, we'll remove the PropTypes again. **If you have any trouble finding the source of the PropType usage, please file an issue so we can help track it down with you.** Changelog: [General][Changed] - Add back deprecated PropTypes Reviewed By: yungsters Differential Revision: D40725705 fbshipit-source-id: 8ce61be30343827efd6dc89a012eeef0b6676deb --- BUCK | 1 + Libraries/Components/TextInput/TextInput.js | 7 ++++++ Libraries/Image/Image.android.js | 6 ++++++ Libraries/Image/Image.ios.js | 6 ++++++ Libraries/Text/Text.js | 6 ++++++ index.js | 24 ++++++++++----------- package.json | 1 + yarn.lock | 13 +++++++++-- 8 files changed, 50 insertions(+), 14 deletions(-) diff --git a/BUCK b/BUCK index e1b1e68844cbd7..f6992f1619298c 100644 --- a/BUCK +++ b/BUCK @@ -742,6 +742,7 @@ rn_library( "//xplat/js:node_modules__abort_19controller", "//xplat/js:node_modules__anser", "//xplat/js:node_modules__base64_19js", + "//xplat/js:node_modules__deprecated_19react_19native_19prop_19types", "//xplat/js:node_modules__event_19target_19shim", "//xplat/js:node_modules__invariant", "//xplat/js:node_modules__memoize_19one", diff --git a/Libraries/Components/TextInput/TextInput.js b/Libraries/Components/TextInput/TextInput.js index fa45a7b441e8fb..386e6b87c8822e 100644 --- a/Libraries/Components/TextInput/TextInput.js +++ b/Libraries/Components/TextInput/TextInput.js @@ -1650,6 +1650,13 @@ const ExportedForwardRef: React.AbstractComponent< ); }); +/** + * Switch to `deprecated-react-native-prop-types` for compatibility with future + * releases. This is deprecated and will be removed in the future. + */ +ExportedForwardRef.propTypes = + require('deprecated-react-native-prop-types').TextInputPropTypes; + // $FlowFixMe[prop-missing] ExportedForwardRef.State = { currentlyFocusedInput: TextInputState.currentlyFocusedInput, diff --git a/Libraries/Image/Image.android.js b/Libraries/Image/Image.android.js index 1b552f6720538b..f874c6abc93f02 100644 --- a/Libraries/Image/Image.android.js +++ b/Libraries/Image/Image.android.js @@ -325,6 +325,12 @@ Image.queryCache = queryCache; * comment and run Flow. */ Image.resolveAssetSource = resolveAssetSource; +/** + * Switch to `deprecated-react-native-prop-types` for compatibility with future + * releases. This is deprecated and will be removed in the future. + */ +Image.propTypes = require('deprecated-react-native-prop-types').ImagePropTypes; + const styles = StyleSheet.create({ base: { overflow: 'hidden', diff --git a/Libraries/Image/Image.ios.js b/Libraries/Image/Image.ios.js index 1d9b1f80203d5e..6f1d72fcb5a8c3 100644 --- a/Libraries/Image/Image.ios.js +++ b/Libraries/Image/Image.ios.js @@ -260,6 +260,12 @@ Image.queryCache = queryCache; * delete this comment and run Flow. */ Image.resolveAssetSource = resolveAssetSource; +/** + * Switch to `deprecated-react-native-prop-types` for compatibility with future + * releases. This is deprecated and will be removed in the future. + */ +Image.propTypes = require('deprecated-react-native-prop-types').ImagePropTypes; + const styles = StyleSheet.create({ base: { overflow: 'hidden', diff --git a/Libraries/Text/Text.js b/Libraries/Text/Text.js index 2470a3c2627bc6..1f6524721cc820 100644 --- a/Libraries/Text/Text.js +++ b/Libraries/Text/Text.js @@ -270,6 +270,12 @@ const Text: React.AbstractComponent< Text.displayName = 'Text'; +/** + * Switch to `deprecated-react-native-prop-types` for compatibility with future + * releases. This is deprecated and will be removed in the future. + */ +Text.propTypes = require('deprecated-react-native-prop-types').TextPropTypes; + /** * Returns false until the first time `newValue` is true, after which this will * always return true. This is necessary to lazily initialize `Pressability` so diff --git a/index.js b/index.js index d2d8fd1316d69c..255b3e6af1a43a 100644 --- a/index.js +++ b/index.js @@ -433,44 +433,44 @@ module.exports = { }, // Deprecated Prop Types get ColorPropType(): $FlowFixMe { - invariant( - false, - 'ColorPropType has been removed from React Native, along with all ' + + console.error( + 'ColorPropType will be removed from React Native, along with all ' + 'other PropTypes. We recommend that you migrate away from PropTypes ' + 'and switch to a type system like TypeScript. If you need to ' + 'continue using ColorPropType, migrate to the ' + "'deprecated-react-native-prop-types' package.", ); + return require('deprecated-react-native-prop-types').ColorPropType; }, get EdgeInsetsPropType(): $FlowFixMe { - invariant( - false, - 'EdgeInsetsPropType has been removed from React Native, along with all ' + + console.error( + 'EdgeInsetsPropType will be removed from React Native, along with all ' + 'other PropTypes. We recommend that you migrate away from PropTypes ' + 'and switch to a type system like TypeScript. If you need to ' + 'continue using EdgeInsetsPropType, migrate to the ' + "'deprecated-react-native-prop-types' package.", ); + return require('deprecated-react-native-prop-types').EdgeInsetsPropType; }, get PointPropType(): $FlowFixMe { - invariant( - false, - 'PointPropType has been removed from React Native, along with all ' + + console.error( + 'PointPropType will be removed from React Native, along with all ' + 'other PropTypes. We recommend that you migrate away from PropTypes ' + 'and switch to a type system like TypeScript. If you need to ' + 'continue using PointPropType, migrate to the ' + "'deprecated-react-native-prop-types' package.", ); + return require('deprecated-react-native-prop-types').PointPropType; }, get ViewPropTypes(): $FlowFixMe { - invariant( - false, - 'ViewPropTypes has been removed from React Native, along with all ' + + console.error( + 'ViewPropTypes will be removed from React Native, along with all ' + 'other PropTypes. We recommend that you migrate away from PropTypes ' + 'and switch to a type system like TypeScript. If you need to ' + 'continue using ViewPropTypes, migrate to the ' + "'deprecated-react-native-prop-types' package.", ); + return require('deprecated-react-native-prop-types').ViewPropTypes; }, }; diff --git a/package.json b/package.json index c0c3eb4cd0d845..410e3f812edd3f 100644 --- a/package.json +++ b/package.json @@ -118,6 +118,7 @@ "abort-controller": "^3.0.0", "anser": "^1.4.9", "base64-js": "^1.1.2", + "deprecated-react-native-prop-types": "^2.3.0", "event-target-shim": "^5.0.1", "invariant": "^2.2.4", "jest-environment-node": "^29.2.1", diff --git a/yarn.lock b/yarn.lock index 740f4c15920f8f..fbdd4966d241a6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4145,6 +4145,15 @@ depd@~1.1.2: resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak= +deprecated-react-native-prop-types@^2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/deprecated-react-native-prop-types/-/deprecated-react-native-prop-types-2.3.0.tgz#c10c6ee75ff2b6de94bb127f142b814e6e08d9ab" + integrity sha512-pWD0voFtNYxrVqvBMYf5gq3NA2GCpfodS1yNynTPc93AYA/KEMGeWDqqeUB6R2Z9ZofVhks2aeJXiuQqKNpesA== + dependencies: + "@react-native/normalize-color" "*" + invariant "*" + prop-types "*" + deprecation@^2.0.0, deprecation@^2.3.1: version "2.3.1" resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" @@ -5548,7 +5557,7 @@ interpret@^1.0.0: resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.1.0.tgz#7ed1b1410c6a0e0f78cf95d3b8440c63f78b8614" integrity sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ= -invariant@^2.2.4: +invariant@*, invariant@^2.2.4: version "2.2.4" resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== @@ -7848,7 +7857,7 @@ prompts@^2.0.1, prompts@^2.4.0: kleur "^3.0.3" sisteransi "^1.0.5" -prop-types@^15.8.1: +prop-types@*, prop-types@^15.8.1: version "15.8.1" resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.8.1.tgz#67d87bf1a694f48435cf332c24af10214a3140b5" integrity sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg== From 07252b81f6d13729dc08ac1444bad6581d852ddd Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 03:13:39 -0700 Subject: [PATCH 053/169] Do not import/use the deprecated ReactFlipperPlugin (#35099) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35099 I'm removing the ReactFlipperPlugin from the new app template. That plugin is effectively empty and is a stub + is deprecated so is generating a warning for all the users. Changelog: [Android] [Changed] - Do not import/use the deprecated ReactFlipperPlugin Reviewed By: cipolleschi Differential Revision: D40751984 fbshipit-source-id: 1f1fdf9c7dfccb9e7bbd4c8c2292df71e00c644f --- .../app/src/debug/java/com/helloworld/ReactNativeFlipper.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/template/android/app/src/debug/java/com/helloworld/ReactNativeFlipper.java b/template/android/app/src/debug/java/com/helloworld/ReactNativeFlipper.java index 283027d2df69d5..595dd5831c3801 100644 --- a/template/android/app/src/debug/java/com/helloworld/ReactNativeFlipper.java +++ b/template/android/app/src/debug/java/com/helloworld/ReactNativeFlipper.java @@ -17,7 +17,6 @@ import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin; import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor; import com.facebook.flipper.plugins.network.NetworkFlipperPlugin; -import com.facebook.flipper.plugins.react.ReactFlipperPlugin; import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin; import com.facebook.react.ReactInstanceEventListener; import com.facebook.react.ReactInstanceManager; @@ -35,7 +34,6 @@ public static void initializeFlipper(Context context, ReactInstanceManager react final FlipperClient client = AndroidFlipperClient.getInstance(context); client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults())); - client.addPlugin(new ReactFlipperPlugin()); client.addPlugin(new DatabasesFlipperPlugin(context)); client.addPlugin(new SharedPreferencesFlipperPlugin(context)); client.addPlugin(CrashReporterPlugin.getInstance()); From 1f42ff0815dbf9436904c4a5b1e6975854654172 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 03:33:29 -0700 Subject: [PATCH 054/169] Bump AGP to 7.3.1 (#35100) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35100 That's just a minor bump of AGP before the branch cut. Changelog: [Android] [Changed] - Bump AGP to 7.3.1 allow-large-files Reviewed By: cipolleschi Differential Revision: D40752006 fbshipit-source-id: 4856bc7ca275cf46d3afcc7c24928c5f1d5e6e33 --- build.gradle.kts | 2 +- packages/react-native-gradle-plugin/build.gradle.kts | 2 +- template/android/build.gradle | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 44ad75737b158f..bd1b0dc5ac7f99 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -33,7 +33,7 @@ buildscript { gradlePluginPortal() } dependencies { - classpath("com.android.tools.build:gradle:7.3.0") + classpath("com.android.tools.build:gradle:7.3.1") classpath("de.undercouch:gradle-download-task:5.0.1") } } diff --git a/packages/react-native-gradle-plugin/build.gradle.kts b/packages/react-native-gradle-plugin/build.gradle.kts index f73d4890c8a966..dd9a08ae099193 100644 --- a/packages/react-native-gradle-plugin/build.gradle.kts +++ b/packages/react-native-gradle-plugin/build.gradle.kts @@ -33,7 +33,7 @@ group = "com.facebook.react" dependencies { implementation(gradleApi()) - implementation("com.android.tools.build:gradle:7.3.0") + implementation("com.android.tools.build:gradle:7.3.1") implementation("com.google.code.gson:gson:2.8.9") implementation("com.google.guava:guava:31.0.1-jre") implementation("com.squareup:javapoet:1.13.0") diff --git a/template/android/build.gradle b/template/android/build.gradle index a893c5e2e8f3c9..c6c8e7351ba0eb 100644 --- a/template/android/build.gradle +++ b/template/android/build.gradle @@ -15,7 +15,7 @@ buildscript { mavenCentral() } dependencies { - classpath("com.android.tools.build:gradle:7.3.0") + classpath("com.android.tools.build:gradle:7.3.1") classpath("com.facebook.react:react-native-gradle-plugin") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files From 3f77736e150c380ea8e23497fcc410c60d613151 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 04:10:57 -0700 Subject: [PATCH 055/169] RNGP - Do not set GENERATED_SRC_DIR and REACT_ANDROID_BUILD_DIR (#35101) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35101 Those CMake variables are effectively unused now. They're raising a warning on CMake builds of templates + let's not expose them as we haven't released RNGP yet, before libraries or other tools start relying on them. Changelog: [Internal] [Changed] - RNGP - Do not set GENERATED_SRC_DIR and REACT_ANDROID_BUILD_DIR Reviewed By: cipolleschi Differential Revision: D40751998 fbshipit-source-id: 13f54a6247e4734c21c263f8b1e6b4b9e8ba406c --- .../com/facebook/react/utils/NdkConfiguratorUtils.kt | 9 --------- 1 file changed, 9 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt index d081afbfcf0284..479c3f742eda99 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/NdkConfiguratorUtils.kt @@ -39,9 +39,6 @@ internal object NdkConfiguratorUtils { // Parameters should be provided in an additive manner (do not override what // the user provided, but allow for sensible defaults). val cmakeArgs = ext.defaultConfig.externalNativeBuild.cmake.arguments - if ("-DGENERATED_SRC_DIR" !in cmakeArgs) { - cmakeArgs.add("-DGENERATED_SRC_DIR=${File(project.buildDir, "generated/source")}") - } if ("-DPROJECT_BUILD_DIR" !in cmakeArgs) { cmakeArgs.add("-DPROJECT_BUILD_DIR=${project.buildDir}") } @@ -49,12 +46,6 @@ internal object NdkConfiguratorUtils { cmakeArgs.add( "-DREACT_ANDROID_DIR=${extension.reactNativeDir.file("ReactAndroid").get().asFile}") } - if ("-DREACT_ANDROID_BUILD_DIR" !in cmakeArgs) { - cmakeArgs.add( - "-DREACT_ANDROID_BUILD_DIR=${ - extension.reactNativeDir.file("ReactAndroid/build").get().asFile - }") - } if ("-DANDROID_STL" !in cmakeArgs) { cmakeArgs.add("-DANDROID_STL=c++_shared") } From 2097278d2a91218274cb661ebf37cc8dbb78bf25 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 04:47:25 -0700 Subject: [PATCH 056/169] Update the template to load the correct JS engine at runtime. (#35095) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35095 This change will make sure that we load the correct JS engine at runtime, by using the BuildConfig flag that RNGP sets for us. This will solve a lot of noise in adb logcat for users seeing stacktraces mentioning failing to load `jscexecutor` library. This is also a breaking change, but as the API was not widely used nor advertised in the template, we should be fine by just mentioning this in the release notes. Changelog: [Android] [Changed] - Update the template to load the correct JS engine at runtime Reviewed By: cipolleschi Differential Revision: D40710597 fbshipit-source-id: d59a7a52b22a9bf273ea89094c6620c3ecf6eb00 --- .../react/JSEngineResolutionAlgorithm.java | 18 +++++++++ .../com/facebook/react/JSInterpreter.java | 18 --------- .../react/ReactInstanceManagerBuilder.java | 39 +++++++------------ .../com/facebook/react/ReactNativeHost.java | 8 ++++ .../react/defaults/DefaultReactNativeHost.kt | 24 +++++++++++- packages/rn-tester/android/app/build.gradle | 2 + .../react/uiapp/RNTesterApplication.java | 5 +++ .../java/com/helloworld/MainApplication.java | 5 +++ 8 files changed, 75 insertions(+), 44 deletions(-) create mode 100644 ReactAndroid/src/main/java/com/facebook/react/JSEngineResolutionAlgorithm.java delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/JSInterpreter.java diff --git a/ReactAndroid/src/main/java/com/facebook/react/JSEngineResolutionAlgorithm.java b/ReactAndroid/src/main/java/com/facebook/react/JSEngineResolutionAlgorithm.java new file mode 100644 index 00000000000000..7f33bc78c5a55c --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/JSEngineResolutionAlgorithm.java @@ -0,0 +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. + */ + +package com.facebook.react; + +/** + * An enum that specifies the algorithm to use when loading theJS Engine. {@link #JSC} will load + * JavaScriptCore first and fail if it is not available. {@link #HERMES} will load Hermes first and + * fail if it is not available. + */ +public enum JSEngineResolutionAlgorithm { + JSC, + HERMES +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/JSInterpreter.java b/ReactAndroid/src/main/java/com/facebook/react/JSInterpreter.java deleted file mode 100644 index 7e960263cc55da..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/JSInterpreter.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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; - -/** - * An enum that specifies the JS Engine to be used in the app Old Logic uses the legacy code - * JSC/HERMES loads the respective engine using the revamped logic - */ -public enum JSInterpreter { - OLD_LOGIC, - JSC, - HERMES -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java index 6dcb191808611f..68ac1ed63451e1 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java @@ -14,6 +14,7 @@ import android.app.Application; import android.content.Context; import androidx.annotation.Nullable; +import com.facebook.common.logging.FLog; import com.facebook.hermes.reactexecutor.HermesExecutor; import com.facebook.hermes.reactexecutor.HermesExecutorFactory; import com.facebook.infer.annotation.Assertions; @@ -40,6 +41,8 @@ /** Builder class for {@link ReactInstanceManager} */ public class ReactInstanceManagerBuilder { + private static final String TAG = ReactInstanceManagerBuilder.class.getSimpleName(); + private final List mPackages = new ArrayList<>(); private @Nullable String mJSBundleAssetUrl; @@ -64,7 +67,7 @@ public class ReactInstanceManagerBuilder { private @Nullable Map mCustomPackagerCommandHandlers; private @Nullable ReactPackageTurboModuleManagerDelegate.Builder mTMMDelegateBuilder; private @Nullable SurfaceDelegateFactory mSurfaceDelegateFactory; - private JSInterpreter jsInterpreter = JSInterpreter.OLD_LOGIC; + private JSEngineResolutionAlgorithm jsEngineResolutionAlgorithm = null; /* package protected */ ReactInstanceManagerBuilder() {} @@ -118,28 +121,12 @@ public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader jsBundleLoad } /** - * Sets the jsEngine as JSC or HERMES as per the setJsEngineAsHermes call Uses the enum {@link - * JSInterpreter} - * - * @param jsInterpreter - */ - private void setJSEngine(JSInterpreter jsInterpreter) { - this.jsInterpreter = jsInterpreter; - } - - /** - * Utility setter to set the required JSEngine as HERMES or JSC Defaults to OLD_LOGIC if not - * called by the host app - * - * @param hermesEnabled hermesEnabled = true sets the JS Engine as HERMES and JSC otherwise + * Sets the JS Engine to load as either Hermes or JSC. If not set, the default is JSC with a + * Hermes fallback. */ - public ReactInstanceManagerBuilder setJsEngineAsHermes(boolean hermesEnabled) { - if (hermesEnabled) { - setJSEngine(JSInterpreter.HERMES); - } else { - setJSEngine(JSInterpreter.JSC); - } - return this; + private void setJSEngineResolutionAlgorithm( + @Nullable JSEngineResolutionAlgorithm jsEngineResolutionAlgorithm) { + this.jsEngineResolutionAlgorithm = jsEngineResolutionAlgorithm; } /** @@ -365,7 +352,11 @@ private JavaScriptExecutorFactory getDefaultJSExecutorFactory( // if nothing is specified, use old loading method // else load the required engine - if (jsInterpreter == JSInterpreter.OLD_LOGIC) { + if (jsEngineResolutionAlgorithm == null) { + FLog.w( + TAG, + "You're not setting the JS Engine Resolution Algorithm. " + + "We'll try to load JSC first, and if it fails we'll fallback to Hermes"); try { // If JSC is included, use it as normal initializeSoLoaderIfNecessary(applicationContext); @@ -378,7 +369,7 @@ private JavaScriptExecutorFactory getDefaultJSExecutorFactory( HermesExecutor.loadLibrary(); return new HermesExecutorFactory(); } - } else if (jsInterpreter == JSInterpreter.HERMES) { + } else if (jsEngineResolutionAlgorithm == JSEngineResolutionAlgorithm.HERMES) { HermesExecutor.loadLibrary(); return new HermesExecutorFactory(); } else { diff --git a/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java b/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java index 02a23c36a10bb1..d030019b035373 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java +++ b/ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java @@ -190,4 +190,12 @@ protected String getJSMainModuleName() { * default ones, you'll want to include more packages here. */ protected abstract List getPackages(); + + /** + * Returns the {@link JSEngineResolutionAlgorithm} to be used when loading the JS engine. If null, + * will try to load JSC first and fallback to Hermes if JSC is not available. + */ + protected @Nullable JSEngineResolutionAlgorithm getJSEngineResolutionAlgorithm() { + return null; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt index 9bbaee4ebbfadb..23c0bada20a220 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt +++ b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultReactNativeHost.kt @@ -8,6 +8,7 @@ package com.facebook.react.defaults import android.app.Application +import com.facebook.react.JSEngineResolutionAlgorithm import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackageTurboModuleManagerDelegate import com.facebook.react.bridge.JSIModulePackage @@ -20,8 +21,10 @@ import com.facebook.react.bridge.JSIModulePackage * providing the default TurboModuleManagerDelegateBuilder and the default JSIModulePackage, * provided the name of the dynamic library to load. */ -abstract class DefaultReactNativeHost protected constructor(application: Application) : - ReactNativeHost(application) { +abstract class DefaultReactNativeHost +protected constructor( + application: Application, +) : ReactNativeHost(application) { override fun getReactPackageTurboModuleManagerDelegateBuilder(): ReactPackageTurboModuleManagerDelegate.Builder? = @@ -38,6 +41,13 @@ abstract class DefaultReactNativeHost protected constructor(application: Applica null } + override fun getJSEngineResolutionAlgorithm(): JSEngineResolutionAlgorithm? = + when (isHermesEnabled) { + true -> JSEngineResolutionAlgorithm.HERMES + false -> JSEngineResolutionAlgorithm.JSC + null -> null + } + /** * Returns whether the user wants to use the New Architecture or not. * @@ -48,4 +58,14 @@ abstract class DefaultReactNativeHost protected constructor(application: Applica */ protected open val isNewArchEnabled: Boolean get() = false + + /** + * Returns whether the user wants to use Hermes. + * + * If true, the app will load the Hermes engine, and fail if not found. If false, the app will + * load the JSC engine, and fail if not found. If null, the app will attempt to load JSC first and + * fallback to Hermes if not found. + */ + protected open val isHermesEnabled: Boolean? + get() = null } diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index 1bfd0ebc649614..86d3646ba34ce8 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -138,9 +138,11 @@ android { productFlavors { hermes { dimension "vm" + buildConfigField("boolean", "IS_HERMES_ENABLED_IN_FLAVOR", "true") } jsc { dimension "vm" + buildConfigField("boolean", "IS_HERMES_ENABLED_IN_FLAVOR", "false") } } diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java index 5012a0e45e4d9d..98de09e81c0d7f 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java @@ -115,6 +115,11 @@ public List createViewManagers( protected boolean isNewArchEnabled() { return true; } + + @Override + protected Boolean isHermesEnabled() { + return BuildConfig.IS_HERMES_ENABLED_IN_FLAVOR; + } }; @Override diff --git a/template/android/app/src/main/java/com/helloworld/MainApplication.java b/template/android/app/src/main/java/com/helloworld/MainApplication.java index be113ec43969fd..3227c9e96996bb 100644 --- a/template/android/app/src/main/java/com/helloworld/MainApplication.java +++ b/template/android/app/src/main/java/com/helloworld/MainApplication.java @@ -37,6 +37,11 @@ protected String getJSMainModuleName() { protected boolean isNewArchEnabled() { return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; } + + @Override + protected Boolean isHermesEnabled() { + return BuildConfig.IS_HERMES_ENABLED; + } }; @Override From 475310dbbaec8048411edefc6cdddab330df7966 Mon Sep 17 00:00:00 2001 From: David <4661784+retyui@users.noreply.github.com> Date: Thu, 27 Oct 2022 05:39:36 -0700 Subject: [PATCH 057/169] Add support `Promise.any` out of box (#35080) Summary: `promise` module diff: [`8.2.0...8.3.0`](https://npmfs.com/compare/promise/8.2.0/8.3.0/) - Hermes issue: https://github.com/facebook/hermes/issues/766 ## Changelog [General] [Added] - Added support `Promise.any` Pull Request resolved: https://github.com/facebook/react-native/pull/35080 Test Plan: Release notes [`promise@8.3.0`](https://github.com/then/promise/releases/tag/8.3.0) ```tsx typeof Promise.any // function ``` Reviewed By: cortinico Differential Revision: D40681373 Pulled By: jacdebug fbshipit-source-id: ecd589186483f3aa0f48da28a1f6dfcb1e26c8bc --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 410e3f812edd3f..947f3cb4bb7880 100644 --- a/package.json +++ b/package.json @@ -130,7 +130,7 @@ "mkdirp": "^0.5.1", "nullthrows": "^1.1.1", "pretty-format": "^26.5.2", - "promise": "^8.2.0", + "promise": "^8.3.0", "react-devtools-core": "^4.26.1", "react-native-gradle-plugin": "^0.71.6", "react-refresh": "^0.4.0", diff --git a/yarn.lock b/yarn.lock index fbdd4966d241a6..91f65ddb17e4c2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7842,10 +7842,10 @@ process-nextick-args@~2.0.0: resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" integrity sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw== -promise@^8.2.0: - version "8.2.0" - resolved "https://registry.yarnpkg.com/promise/-/promise-8.2.0.tgz#a1f6280ab67457fbfc8aad2b198c9497e9e5c806" - integrity sha512-+CMAlLHqwRYwBMXKCP+o8ns7DN+xHDUiI+0nArsiJ9y+kJVPLFxEaSw6Ha9s9H0tftxg2Yzl25wqj9G7m5wLZg== +promise@^8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/promise/-/promise-8.3.0.tgz#8cb333d1edeb61ef23869fbb8a4ea0279ab60e0a" + integrity sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg== dependencies: asap "~2.0.6" From ba5454c42134cc09772f024772b19a9990b1fb7f Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 09:52:06 -0700 Subject: [PATCH 058/169] Bump RNGP to 0.71.7 Summary: Just bumping RNGP to make the new sources avialable to the template. Changelog: [Internal] [Changed] - Bump RNGP to 0.71.7 Reviewed By: cipolleschi Differential Revision: D40760927 fbshipit-source-id: 909c88377a231ea6678c6af14c5594fdc4830b79 --- package.json | 2 +- packages/react-native-gradle-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 947f3cb4bb7880..a0f23a916623aa 100644 --- a/package.json +++ b/package.json @@ -132,7 +132,7 @@ "pretty-format": "^26.5.2", "promise": "^8.3.0", "react-devtools-core": "^4.26.1", - "react-native-gradle-plugin": "^0.71.6", + "react-native-gradle-plugin": "^0.71.7", "react-refresh": "^0.4.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 89f4f18111bdbc..0a5919742154a0 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "react-native-gradle-plugin", - "version": "0.71.6", + "version": "0.71.7", "description": "⚛️ Gradle Plugin for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", "repository": { From f550606d4cd9640d87126e72a1a575fd2ecffdea Mon Sep 17 00:00:00 2001 From: Lorenzo Sciandra Date: Thu, 27 Oct 2022 14:09:03 -0700 Subject: [PATCH 059/169] chore(cli, metro): bump cli and metro to latest ahead of 71 (#35107) Summary: Small PR with bump to the new versions of CLI and Metro in preparation of the branch cut for 0.71. While at it, did a cheeky `npx yarn-deduplicate` to clean up a bit the deps. ## Changelog [General] [Changed] - Bump CLI to 10.0.0-alpha.1 and Metro to 0.73.3 Pull Request resolved: https://github.com/facebook/react-native/pull/35107 Test Plan: CI is green Reviewed By: motiz88 Differential Revision: D40762683 Pulled By: huntie fbshipit-source-id: e523a49c78588ca80351f44cb02bcd4c0137475e --- package.json | 12 +- repo-config/package.json | 4 +- template/package.json | 2 +- yarn.lock | 1024 +++++++++++--------------------------- 4 files changed, 302 insertions(+), 740 deletions(-) diff --git a/package.json b/package.json index a0f23a916623aa..30ab12d3bb3146 100644 --- a/package.json +++ b/package.json @@ -109,9 +109,9 @@ }, "dependencies": { "@jest/create-cache-key-function": "^29.2.1", - "@react-native-community/cli": "9.2.1", - "@react-native-community/cli-platform-android": "9.2.1", - "@react-native-community/cli-platform-ios": "9.2.1", + "@react-native-community/cli": "10.0.0-alpha.1", + "@react-native-community/cli-platform-android": "10.0.0-alpha.1", + "@react-native-community/cli-platform-ios": "10.0.0-alpha.1", "@react-native/assets": "1.0.0", "@react-native/normalize-color": "2.0.0", "@react-native/polyfills": "2.0.0", @@ -124,9 +124,9 @@ "jest-environment-node": "^29.2.1", "jsc-android": "^250230.2.1", "memoize-one": "^5.0.0", - "metro-react-native-babel-transformer": "0.72.3", - "metro-runtime": "0.72.3", - "metro-source-map": "0.72.3", + "metro-react-native-babel-transformer": "0.73.3", + "metro-runtime": "0.73.3", + "metro-source-map": "0.73.3", "mkdirp": "^0.5.1", "nullthrows": "^1.1.1", "pretty-format": "^26.5.2", diff --git a/repo-config/package.json b/repo-config/package.json index 80b534f72751a0..28f626ef24c37e 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -41,8 +41,8 @@ "jest": "^29.2.1", "jest-junit": "^10.0.0", "jscodeshift": "^0.13.1", - "metro-babel-register": "0.72.3", - "metro-memory-fs": "0.72.3", + "metro-babel-register": "0.73.3", + "metro-memory-fs": "0.73.3", "mkdirp": "^0.5.1", "prettier": "^2.4.1", "react": "18.2.0", diff --git a/template/package.json b/template/package.json index 8496121f5360e9..af4a7228d099ca 100644 --- a/template/package.json +++ b/template/package.json @@ -20,7 +20,7 @@ "babel-jest": "^29.2.1", "eslint": "^8.19.0", "jest": "^29.2.1", - "metro-react-native-babel-preset": "0.72.3", + "metro-react-native-babel-preset": "0.73.3", "react-test-renderer": "18.2.0" }, "jest": { diff --git a/yarn.lock b/yarn.lock index 91f65ddb17e4c2..705ad189d14877 100644 --- a/yarn.lock +++ b/yarn.lock @@ -33,12 +33,7 @@ dependencies: "@babel/highlight" "^7.18.6" -"@babel/compat-data@^7.13.11", "@babel/compat-data@^7.13.8", "@babel/compat-data@^7.19.1": - version "7.19.1" - resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.19.1.tgz#72d647b4ff6a4f82878d184613353af1dd0290f9" - integrity sha512-72a9ghR0gnESIa7jBN53U32FOVCEoztyIlKaNoU05zRhEecduGK9L9c3ww7Mp06JiR+0ls0GBPFJQwwtjn9ksg== - -"@babel/compat-data@^7.17.7", "@babel/compat-data@^7.18.8", "@babel/compat-data@^7.19.3": +"@babel/compat-data@^7.13.11", "@babel/compat-data@^7.17.7", "@babel/compat-data@^7.18.8", "@babel/compat-data@^7.19.3": version "7.19.3" resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.19.3.tgz#707b939793f867f5a73b2666e6d9a3396eb03151" integrity sha512-prBHMK4JYYK+wDjJF1q99KK4JLL+egWS4nmNqdlMUgCExMZ+iZW0hGhyC3VEbsPjvaN0TBhW//VIFwBrk8sEiw== @@ -82,28 +77,13 @@ "@jridgewell/gen-mapping" "^0.3.2" jsesc "^2.5.1" -"@babel/helper-annotate-as-pure@^7.12.13", "@babel/helper-annotate-as-pure@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.16.7.tgz#bb2339a7534a9c128e3102024c60760a3a7f3862" - integrity sha512-s6t2w/IPQVTAET1HitoowRGXooX8mCgtuP5195wD/QJPV6wYjpujCGF7JuMODVX2ZAJOf1GT6DT9MHEZvLOFSw== - dependencies: - "@babel/types" "^7.16.7" - -"@babel/helper-annotate-as-pure@^7.18.6": +"@babel/helper-annotate-as-pure@^7.12.13", "@babel/helper-annotate-as-pure@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.18.6.tgz#eaa49f6f80d5a33f9a5dd2276e6d6e451be0a6bb" integrity sha512-duORpUiYrEpzKIop6iNbjnwKLAKnJ47csTyRACyEmWj0QdUrm5aqNJGHSSEQSUAvNW0ojX0dOmK9dZduvkfeXA== dependencies: "@babel/types" "^7.18.6" -"@babel/helper-builder-binary-assignment-operator-visitor@^7.12.13": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.12.13.tgz#6bc20361c88b0a74d05137a65cac8d3cbf6f61fc" - integrity sha512-CZOv9tGphhDRlVjVkAgm8Nhklm9RzSmWpX2my+t7Ua/KT616pEzXsQCjinzvkRvHWJ9itO4f296efroX23XCMA== - dependencies: - "@babel/helper-explode-assignable-expression" "^7.12.13" - "@babel/types" "^7.12.13" - "@babel/helper-builder-binary-assignment-operator-visitor@^7.18.6": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.18.9.tgz#acd4edfd7a566d1d51ea975dff38fd52906981bb" @@ -112,17 +92,7 @@ "@babel/helper-explode-assignable-expression" "^7.18.6" "@babel/types" "^7.18.9" -"@babel/helper-compilation-targets@^7.13.0", "@babel/helper-compilation-targets@^7.13.8", "@babel/helper-compilation-targets@^7.19.1": - version "7.19.1" - resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.19.1.tgz#7f630911d83b408b76fe584831c98e5395d7a17c" - integrity sha512-LlLkkqhCMyz2lkQPvJNdIYU7O5YjWRgC2R4omjCTpZd8u8KMQzZvX4qce+/BluN1rcQiV7BoGUpmQ0LeHerbhg== - dependencies: - "@babel/compat-data" "^7.19.1" - "@babel/helper-validator-option" "^7.18.6" - browserslist "^4.21.3" - semver "^6.3.0" - -"@babel/helper-compilation-targets@^7.17.7", "@babel/helper-compilation-targets@^7.18.9", "@babel/helper-compilation-targets@^7.19.0", "@babel/helper-compilation-targets@^7.19.3": +"@babel/helper-compilation-targets@^7.13.0", "@babel/helper-compilation-targets@^7.17.7", "@babel/helper-compilation-targets@^7.18.9", "@babel/helper-compilation-targets@^7.19.0", "@babel/helper-compilation-targets@^7.19.1", "@babel/helper-compilation-targets@^7.19.3": version "7.19.3" resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.19.3.tgz#a10a04588125675d7c7ae299af86fa1b2ee038ca" integrity sha512-65ESqLGyGmLvgR0mst5AdW1FkNlj9rQsCKduzEoEPhBCDFGXvz2jW6bXFG6i0/MrV2s7hhXjjb2yAzcPuQlLwg== @@ -132,20 +102,7 @@ browserslist "^4.21.3" semver "^6.3.0" -"@babel/helper-create-class-features-plugin@^7.16.7": - version "7.16.10" - resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.16.10.tgz#8a6959b9cc818a88815ba3c5474619e9c0f2c21c" - integrity sha512-wDeej0pu3WN/ffTxMNCPW5UCiOav8IcLRxSIyp/9+IF2xJUM9h/OYjg0IJLHaL6F8oU8kqMz9nc1vryXhMsgXg== - dependencies: - "@babel/helper-annotate-as-pure" "^7.16.7" - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-function-name" "^7.16.7" - "@babel/helper-member-expression-to-functions" "^7.16.7" - "@babel/helper-optimise-call-expression" "^7.16.7" - "@babel/helper-replace-supers" "^7.16.7" - "@babel/helper-split-export-declaration" "^7.16.7" - -"@babel/helper-create-class-features-plugin@^7.18.6": +"@babel/helper-create-class-features-plugin@^7.16.7", "@babel/helper-create-class-features-plugin@^7.18.6": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.19.0.tgz#bfd6904620df4e46470bae4850d66be1054c404b" integrity sha512-NRz8DwF4jT3UfrmUoZjd0Uph9HQnP30t7Ash+weACcyNkiYTywpIjDBgReJMKgr+n86sn2nPVVmJ28Dm053Kqw== @@ -158,14 +115,6 @@ "@babel/helper-replace-supers" "^7.18.9" "@babel/helper-split-export-declaration" "^7.18.6" -"@babel/helper-create-regexp-features-plugin@^7.12.13", "@babel/helper-create-regexp-features-plugin@^7.16.7": - version "7.17.0" - resolved "https://registry.yarnpkg.com/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.17.0.tgz#1dcc7d40ba0c6b6b25618997c5dbfd310f186fe1" - integrity sha512-awO2So99wG6KnlE+TPs6rn83gCz5WlEePJDTnLEqbchMVrBeAujURVphRdigsk094VhvZehFoNOihSlcBjwsXA== - dependencies: - "@babel/helper-annotate-as-pure" "^7.16.7" - regexpu-core "^5.0.1" - "@babel/helper-create-regexp-features-plugin@^7.18.6", "@babel/helper-create-regexp-features-plugin@^7.19.0": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.19.0.tgz#7976aca61c0984202baca73d84e2337a5424a41b" @@ -200,18 +149,11 @@ resolve "^1.14.2" semver "^6.1.2" -"@babel/helper-environment-visitor@^7.16.7", "@babel/helper-environment-visitor@^7.18.9": +"@babel/helper-environment-visitor@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz#0c0cee9b35d2ca190478756865bb3528422f51be" integrity sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg== -"@babel/helper-explode-assignable-expression@^7.12.13": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.13.0.tgz#17b5c59ff473d9f956f40ef570cf3a76ca12657f" - integrity sha512-qS0peLTDP8kOisG1blKbaoBg/o9OSa1qoumMjTK5pM+KDTtpxpsiubnCGP34vK8BXGcb2M9eigwgvoJryrzwWA== - dependencies: - "@babel/types" "^7.13.0" - "@babel/helper-explode-assignable-expression@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-explode-assignable-expression/-/helper-explode-assignable-expression-7.18.6.tgz#41f8228ef0a6f1a036b8dfdfec7ce94f9a6bc096" @@ -219,7 +161,7 @@ dependencies: "@babel/types" "^7.18.6" -"@babel/helper-function-name@^7.12.13", "@babel/helper-function-name@^7.16.7", "@babel/helper-function-name@^7.18.9", "@babel/helper-function-name@^7.19.0": +"@babel/helper-function-name@^7.18.9", "@babel/helper-function-name@^7.19.0": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz#941574ed5390682e872e52d3f38ce9d1bef4648c" integrity sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w== @@ -234,13 +176,6 @@ dependencies: "@babel/types" "^7.18.6" -"@babel/helper-member-expression-to-functions@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.16.7.tgz#42b9ca4b2b200123c3b7e726b0ae5153924905b0" - integrity sha512-VtJ/65tYiU/6AbMTDwyoXGPKHgTsfRarivm+YbB5uAzKUyuPjgZSgAFeG87FCigc7KNHu2Pegh1XIT3lXjvz3Q== - dependencies: - "@babel/types" "^7.16.7" - "@babel/helper-member-expression-to-functions@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.18.9.tgz#1531661e8375af843ad37ac692c132841e2fd815" @@ -255,7 +190,7 @@ dependencies: "@babel/types" "^7.18.6" -"@babel/helper-module-transforms@^7.16.7", "@babel/helper-module-transforms@^7.18.6", "@babel/helper-module-transforms@^7.19.0": +"@babel/helper-module-transforms@^7.18.6", "@babel/helper-module-transforms@^7.19.0": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.19.0.tgz#309b230f04e22c58c6a2c0c0c7e50b216d350c30" integrity sha512-3HBZ377Fe14RbLIA+ac3sY4PTgpxHVkFrESaWhoI5PuyXPBBX8+C34qblV9G89ZtycGJCmCI/Ut+VUDK4bltNQ== @@ -269,13 +204,6 @@ "@babel/traverse" "^7.19.0" "@babel/types" "^7.19.0" -"@babel/helper-optimise-call-expression@^7.12.13", "@babel/helper-optimise-call-expression@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.16.7.tgz#a34e3560605abbd31a18546bd2aad3e6d9a174f2" - integrity sha512-EtgBhg7rd/JcnpZFXpBy0ze1YRfdm7BnBX4uKMBd3ixa3RGAE002JZB66FJyNH7g0F38U05pXmA5P8cBh7z+1w== - dependencies: - "@babel/types" "^7.16.7" - "@babel/helper-optimise-call-expression@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.18.6.tgz#9369aa943ee7da47edab2cb4e838acf09d290ffe" @@ -283,25 +211,11 @@ dependencies: "@babel/types" "^7.18.6" -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.13.0", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.16.7", "@babel/helper-plugin-utils@^7.17.12", "@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.8.0": - version "7.18.9" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.18.9.tgz#4b8aea3b069d8cb8a72cdfe28ddf5ceca695ef2f" - integrity sha512-aBXPT3bmtLryXaoJLyYPXPlSD4p1ld9aYeR+sJNOZjJJGiOpb+fKfh3NkcCu7J54nUJwCERPBExCCpyCOHnu/w== - -"@babel/helper-plugin-utils@^7.18.9", "@babel/helper-plugin-utils@^7.19.0", "@babel/helper-plugin-utils@^7.8.3": +"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.13.0", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.16.7", "@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.18.9", "@babel/helper-plugin-utils@^7.19.0", "@babel/helper-plugin-utils@^7.8.0", "@babel/helper-plugin-utils@^7.8.3": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.19.0.tgz#4796bb14961521f0f8715990bee2fb6e51ce21bf" integrity sha512-40Ryx7I8mT+0gaNxm8JGTZFUITNqdLAgdg0hXzeVZxVD6nFsdhQvip6v8dqkRHzsz1VFpFAaOCHNn0vKBL7Czw== -"@babel/helper-remap-async-to-generator@^7.13.0", "@babel/helper-remap-async-to-generator@^7.16.8": - version "7.16.8" - resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.16.8.tgz#29ffaade68a367e2ed09c90901986918d25e57e3" - integrity sha512-fm0gH7Flb8H51LqJHy3HJ3wnE1+qtYR2A99K06ahwrawLdOFsCEWjZOrYricXJHoPSudNKxrMBUPEIPxiIIvBw== - dependencies: - "@babel/helper-annotate-as-pure" "^7.16.7" - "@babel/helper-wrap-function" "^7.16.8" - "@babel/types" "^7.16.8" - "@babel/helper-remap-async-to-generator@^7.18.6", "@babel/helper-remap-async-to-generator@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.18.9.tgz#997458a0e3357080e54e1d79ec347f8a8cd28519" @@ -312,17 +226,6 @@ "@babel/helper-wrap-function" "^7.18.9" "@babel/types" "^7.18.9" -"@babel/helper-replace-supers@^7.12.13", "@babel/helper-replace-supers@^7.13.0", "@babel/helper-replace-supers@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.16.7.tgz#e9f5f5f32ac90429c1a4bdec0f231ef0c2838ab1" - integrity sha512-y9vsWilTNaVnVh6xiJfABzsNpgDPKev9HnAgz6Gb1p6UUwf9NepdlsV7VXGCftJM+jqD5f7JIEubcpLjZj5dBw== - dependencies: - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-member-expression-to-functions" "^7.16.7" - "@babel/helper-optimise-call-expression" "^7.16.7" - "@babel/traverse" "^7.16.7" - "@babel/types" "^7.16.7" - "@babel/helper-replace-supers@^7.18.6", "@babel/helper-replace-supers@^7.18.9": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.19.1.tgz#e1592a9b4b368aa6bdb8784a711e0bcbf0612b78" @@ -334,20 +237,13 @@ "@babel/traverse" "^7.19.1" "@babel/types" "^7.19.0" -"@babel/helper-simple-access@^7.16.7", "@babel/helper-simple-access@^7.18.6": +"@babel/helper-simple-access@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.18.6.tgz#d6d8f51f4ac2978068df934b569f08f29788c7ea" integrity sha512-iNpIgTgyAvDQpDj76POqg+YEt8fPxx3yaNBg3S30dxNKm2SWfYhD0TGrK/Eu9wHpUW63VQU894TsTg+GLbUa1g== dependencies: "@babel/types" "^7.18.6" -"@babel/helper-skip-transparent-expression-wrappers@^7.12.1", "@babel/helper-skip-transparent-expression-wrappers@^7.16.0": - version "7.16.0" - resolved "https://registry.yarnpkg.com/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.16.0.tgz#0ee3388070147c3ae051e487eca3ebb0e2e8bb09" - integrity sha512-+il1gTy0oHwUsBQZyJvukbB4vPMdcYBrFHa0Uc4AizLxbq6BOYC51Rv4tWocX9BLBDLZ4kc6qUFpQ6HRgL+3zw== - dependencies: - "@babel/types" "^7.16.0" - "@babel/helper-skip-transparent-expression-wrappers@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.18.9.tgz#778d87b3a758d90b471e7b9918f34a9a02eb5818" @@ -355,7 +251,7 @@ dependencies: "@babel/types" "^7.18.9" -"@babel/helper-split-export-declaration@^7.12.13", "@babel/helper-split-export-declaration@^7.16.7", "@babel/helper-split-export-declaration@^7.18.6": +"@babel/helper-split-export-declaration@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz#7367949bc75b20c6d5a5d4a97bba2824ae8ef075" integrity sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA== @@ -367,12 +263,7 @@ resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.18.10.tgz#181f22d28ebe1b3857fa575f5c290b1aaf659b56" integrity sha512-XtIfWmeNY3i4t7t4D2t02q50HvqHybPqW2ki1kosnvWCwuCMeo81Jf0gwr85jy/neUdg5XDdeFE/80DXiO+njw== -"@babel/helper-validator-identifier@^7.18.6": - version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.18.6.tgz#9c97e30d31b2b8c72a1d08984f2ca9b574d7a076" - integrity sha512-MmetCkz9ej86nJQV+sFCxoGGrUbU3q02kgLciwkrt9QqEB7cP39oKEY0PakknEO0Gu20SskMRi+AYZ3b1TpN9g== - -"@babel/helper-validator-identifier@^7.19.1": +"@babel/helper-validator-identifier@^7.18.6", "@babel/helper-validator-identifier@^7.19.1": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz#7eea834cf32901ffdc1a7ee555e2f9c27e249ca2" integrity sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w== @@ -382,16 +273,6 @@ resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz#bf0d2b5a509b1f336099e4ff36e1a63aa5db4db8" integrity sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw== -"@babel/helper-wrap-function@^7.16.8": - version "7.16.8" - resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.16.8.tgz#58afda087c4cd235de92f7ceedebca2c41274200" - integrity sha512-8RpyRVIAW1RcDDGTA+GpPAwV22wXCfKOoM9bet6TLkGIFTkRQSkH1nMQ5Yet4MpoXe1ZwHPVtNasc2w0uZMqnw== - dependencies: - "@babel/helper-function-name" "^7.16.7" - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.16.8" - "@babel/types" "^7.16.8" - "@babel/helper-wrap-function@^7.18.9": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.19.0.tgz#89f18335cff1152373222f76a4b37799636ae8b1" @@ -441,16 +322,7 @@ "@babel/helper-skip-transparent-expression-wrappers" "^7.18.9" "@babel/plugin-proposal-optional-chaining" "^7.18.9" -"@babel/plugin-proposal-async-generator-functions@^7.0.0": - version "7.16.8" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.16.8.tgz#3bdd1ebbe620804ea9416706cd67d60787504bc8" - integrity sha512-71YHIvMuiuqWJQkebWJtdhQTfd4Q4mF76q2IX37uZPkG9+olBxsX+rH1vkhFto4UeJZ9dPY2s+mDvhDm1u2BGQ== - dependencies: - "@babel/helper-plugin-utils" "^7.16.7" - "@babel/helper-remap-async-to-generator" "^7.16.8" - "@babel/plugin-syntax-async-generators" "^7.8.4" - -"@babel/plugin-proposal-async-generator-functions@^7.19.1": +"@babel/plugin-proposal-async-generator-functions@^7.0.0", "@babel/plugin-proposal-async-generator-functions@^7.19.1": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.19.1.tgz#34f6f5174b688529342288cd264f80c9ea9fb4a7" integrity sha512-0yu8vNATgLy4ivqMNBIwb1HebCelqN7YX8SL3FDXORv/RqT0zEEWUCH4GH44JsSrvCu6GqnAdR5EBFAPeNBB4Q== @@ -460,15 +332,7 @@ "@babel/helper-remap-async-to-generator" "^7.18.9" "@babel/plugin-syntax-async-generators" "^7.8.4" -"@babel/plugin-proposal-class-properties@^7.0.0", "@babel/plugin-proposal-class-properties@^7.13.0": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.16.7.tgz#925cad7b3b1a2fcea7e59ecc8eb5954f961f91b0" - integrity sha512-IobU0Xme31ewjYOShSIqd/ZGM/r/cuOz2z0MDbNrhF5FW+ZVgi0f2lyeoj9KFPDOAqsYxmLWZte1WOwlvY9aww== - dependencies: - "@babel/helper-create-class-features-plugin" "^7.16.7" - "@babel/helper-plugin-utils" "^7.16.7" - -"@babel/plugin-proposal-class-properties@^7.18.6": +"@babel/plugin-proposal-class-properties@^7.0.0", "@babel/plugin-proposal-class-properties@^7.13.0", "@babel/plugin-proposal-class-properties@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.18.6.tgz#b110f59741895f7ec21a6fff696ec46265c446a3" integrity sha512-cumfXOF0+nzZrrN8Rf0t7M+tF6sZc7vhQwYQck9q1/5w2OExlD+b4v4RpMJFaV1Z7WcDRgO6FqvxqxGlwo+RHQ== @@ -525,15 +389,7 @@ "@babel/helper-plugin-utils" "^7.18.9" "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" -"@babel/plugin-proposal-nullish-coalescing-operator@^7.0.0", "@babel/plugin-proposal-nullish-coalescing-operator@^7.13.8": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.16.7.tgz#141fc20b6857e59459d430c850a0011e36561d99" - integrity sha512-aUOrYU3EVtjf62jQrCj63pYZ7k6vns2h/DQvHPWGmsJRYzWXZ6/AsfgpiRy6XiuIDADhJzP2Q9MwSMKauBQ+UQ== - dependencies: - "@babel/helper-plugin-utils" "^7.16.7" - "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" - -"@babel/plugin-proposal-nullish-coalescing-operator@^7.18.6": +"@babel/plugin-proposal-nullish-coalescing-operator@^7.0.0", "@babel/plugin-proposal-nullish-coalescing-operator@^7.13.8", "@babel/plugin-proposal-nullish-coalescing-operator@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.18.6.tgz#fdd940a99a740e577d6c753ab6fbb43fdb9467e1" integrity sha512-wQxQzxYeJqHcfppzBDnm1yAY0jSRkUXR2z8RePZYrKwMKgMlE8+Z6LUno+bd6LvbGh8Gltvy74+9pIYkr+XkKA== @@ -549,18 +405,7 @@ "@babel/helper-plugin-utils" "^7.18.6" "@babel/plugin-syntax-numeric-separator" "^7.10.4" -"@babel/plugin-proposal-object-rest-spread@^7.0.0": - version "7.13.8" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.13.8.tgz#5d210a4d727d6ce3b18f9de82cc99a3964eed60a" - integrity sha512-DhB2EuB1Ih7S3/IRX5AFVgZ16k3EzfRbq97CxAVI1KSYcW+lexV8VZb7G7L8zuPVSdQMRn0kiBpf/Yzu9ZKH0g== - dependencies: - "@babel/compat-data" "^7.13.8" - "@babel/helper-compilation-targets" "^7.13.8" - "@babel/helper-plugin-utils" "^7.13.0" - "@babel/plugin-syntax-object-rest-spread" "^7.8.3" - "@babel/plugin-transform-parameters" "^7.13.0" - -"@babel/plugin-proposal-object-rest-spread@^7.18.9": +"@babel/plugin-proposal-object-rest-spread@^7.0.0", "@babel/plugin-proposal-object-rest-spread@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.18.9.tgz#f9434f6beb2c8cae9dfcf97d2a5941bbbf9ad4e7" integrity sha512-kDDHQ5rflIeY5xl69CEqGEZ0KY369ehsCIEbTGb4siHG5BE9sga/T0r0OUwyZNLMmZE79E1kbsqAjwFCW4ds6Q== @@ -571,15 +416,7 @@ "@babel/plugin-syntax-object-rest-spread" "^7.8.3" "@babel/plugin-transform-parameters" "^7.18.8" -"@babel/plugin-proposal-optional-catch-binding@^7.0.0": - version "7.13.8" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.13.8.tgz#3ad6bd5901506ea996fc31bdcf3ccfa2bed71107" - integrity sha512-0wS/4DUF1CuTmGo+NiaHfHcVSeSLj5S3e6RivPTg/2k3wOv3jO35tZ6/ZWsQhQMvdgI7CwphjQa/ccarLymHVA== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" - -"@babel/plugin-proposal-optional-catch-binding@^7.18.6": +"@babel/plugin-proposal-optional-catch-binding@^7.0.0", "@babel/plugin-proposal-optional-catch-binding@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-catch-binding/-/plugin-proposal-optional-catch-binding-7.18.6.tgz#f9400d0e6a3ea93ba9ef70b09e72dd6da638a2cb" integrity sha512-Q40HEhs9DJQyaZfUjjn6vE8Cv4GmMHCYuMGIWUnlxH6400VGxOuwWsPt4FxXxJkC/5eOzgn0z21M9gMT4MOhbw== @@ -587,16 +424,7 @@ "@babel/helper-plugin-utils" "^7.18.6" "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" -"@babel/plugin-proposal-optional-chaining@^7.0.0", "@babel/plugin-proposal-optional-chaining@^7.13.12": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.16.7.tgz#7cd629564724816c0e8a969535551f943c64c39a" - integrity sha512-eC3xy+ZrUcBtP7x+sq62Q/HYd674pPTb/77XZMb5wbDPGWIdUbSr4Agr052+zaUPSb+gGRnjxXfKFvx5iMJ+DA== - dependencies: - "@babel/helper-plugin-utils" "^7.16.7" - "@babel/helper-skip-transparent-expression-wrappers" "^7.16.0" - "@babel/plugin-syntax-optional-chaining" "^7.8.3" - -"@babel/plugin-proposal-optional-chaining@^7.18.9": +"@babel/plugin-proposal-optional-chaining@^7.0.0", "@babel/plugin-proposal-optional-chaining@^7.13.12", "@babel/plugin-proposal-optional-chaining@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.18.9.tgz#e8e8fe0723f2563960e4bf5e9690933691915993" integrity sha512-v5nwt4IqBXihxGsW2QmCWMDS3B3bzGIk/EQVZz2ei7f3NJl8NzAJVvUmpDW5q1CRNY+Beb/k58UAH1Km1N411w== @@ -680,14 +508,7 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.3" -"@babel/plugin-syntax-flow@^7.0.0", "@babel/plugin-syntax-flow@^7.17.12", "@babel/plugin-syntax-flow@^7.2.0": - version "7.17.12" - resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.17.12.tgz#23d852902acd19f42923fca9d0f196984d124e73" - integrity sha512-B8QIgBvkIG6G2jgsOHQUist7Sm0EBLDCx8sen072IwqNuzMegZNXrYnSv77cYzA8mLDZAfQYqsLIhimiP1s2HQ== - dependencies: - "@babel/helper-plugin-utils" "^7.17.12" - -"@babel/plugin-syntax-flow@^7.18.6": +"@babel/plugin-syntax-flow@^7.0.0", "@babel/plugin-syntax-flow@^7.18.6", "@babel/plugin-syntax-flow@^7.2.0": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.18.6.tgz#774d825256f2379d06139be0c723c4dd444f3ca1" integrity sha512-LUbR+KNTBWCUAqRG9ex5Gnzu2IOkt8jRJbHHXFT9q+L9zm7M/QQbEqXyw1n1pohYvOyWC8CjeyjrSaIwiYjK7A== @@ -785,30 +606,14 @@ dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-arrow-functions@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.13.0.tgz#10a59bebad52d637a027afa692e8d5ceff5e3dae" - integrity sha512-96lgJagobeVmazXFaDrbmCLQxBysKu7U6Do3mLsx27gf5Dk85ezysrs2BZUpXD703U/Su1xTBDxxar2oa4jAGg== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-arrow-functions@^7.18.6": +"@babel/plugin-transform-arrow-functions@^7.0.0", "@babel/plugin-transform-arrow-functions@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.18.6.tgz#19063fcf8771ec7b31d742339dac62433d0611fe" integrity sha512-9S9X9RUefzrsHZmKMbDXxweEH+YlE8JJEuat9FdvW9Qh1cw7W64jELCtWNkPBPX5En45uy28KGvA/AySqUh8CQ== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-async-to-generator@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.13.0.tgz#8e112bf6771b82bf1e974e5e26806c5c99aa516f" - integrity sha512-3j6E004Dx0K3eGmhxVJxwwI89CTJrce7lg3UrtFuDAVQ/2+SJ/h/aSFOeE6/n0WB1GsOffsJp6MnPQNQ8nmwhg== - dependencies: - "@babel/helper-module-imports" "^7.12.13" - "@babel/helper-plugin-utils" "^7.13.0" - "@babel/helper-remap-async-to-generator" "^7.13.0" - -"@babel/plugin-transform-async-to-generator@^7.18.6": +"@babel/plugin-transform-async-to-generator@^7.0.0", "@babel/plugin-transform-async-to-generator@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.18.6.tgz#ccda3d1ab9d5ced5265fdb13f1882d5476c71615" integrity sha512-ARE5wZLKnTgPW7/1ftQmSi1CmkqqHo2DNmtztFhvgtOWSDfq0Cq9/9L+KnZNYSNrydBekhW3rwShduf59RoXag== @@ -817,48 +622,21 @@ "@babel/helper-plugin-utils" "^7.18.6" "@babel/helper-remap-async-to-generator" "^7.18.6" -"@babel/plugin-transform-block-scoped-functions@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.12.13.tgz#a9bf1836f2a39b4eb6cf09967739de29ea4bf4c4" - integrity sha512-zNyFqbc3kI/fVpqwfqkg6RvBgFpC4J18aKKMmv7KdQ/1GgREapSJAykLMVNwfRGO3BtHj3YQZl8kxCXPcVMVeg== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-block-scoped-functions@^7.18.6": +"@babel/plugin-transform-block-scoped-functions@^7.0.0", "@babel/plugin-transform-block-scoped-functions@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.18.6.tgz#9187bf4ba302635b9d70d986ad70f038726216a8" integrity sha512-ExUcOqpPWnliRcPqves5HJcJOvHvIIWfuS4sroBUenPuMdmW+SMHDakmtS7qOo13sVppmUijqeTv7qqGsvURpQ== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-block-scoping@^7.0.0": - version "7.14.1" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.14.1.tgz#ac1b3a8e3d8cbb31efc6b9be2f74eb9823b74ab2" - integrity sha512-2mQXd0zBrwfp0O1moWIhPpEeTKDvxyHcnma3JATVP1l+CctWBuot6OJG8LQ4DnBj4ZZPSmlb/fm4mu47EOAnVA== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-block-scoping@^7.18.9": +"@babel/plugin-transform-block-scoping@^7.0.0", "@babel/plugin-transform-block-scoping@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.18.9.tgz#f9b7e018ac3f373c81452d6ada8bd5a18928926d" integrity sha512-5sDIJRV1KtQVEbt/EIBwGy4T01uYIo4KRB3VUqzkhrAIOGx7AoctL9+Ux88btY0zXdDyPJ9mW+bg+v+XEkGmtw== dependencies: "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-classes@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.13.0.tgz#0265155075c42918bf4d3a4053134176ad9b533b" - integrity sha512-9BtHCPUARyVH1oXGcSJD3YpsqRLROJx5ZNP6tN5vnk17N0SVf9WCtf8Nuh1CFmgByKKAIMstitKduoCmsaDK5g== - dependencies: - "@babel/helper-annotate-as-pure" "^7.12.13" - "@babel/helper-function-name" "^7.12.13" - "@babel/helper-optimise-call-expression" "^7.12.13" - "@babel/helper-plugin-utils" "^7.13.0" - "@babel/helper-replace-supers" "^7.13.0" - "@babel/helper-split-export-declaration" "^7.12.13" - globals "^11.1.0" - -"@babel/plugin-transform-classes@^7.19.0": +"@babel/plugin-transform-classes@^7.0.0", "@babel/plugin-transform-classes@^7.19.0": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.19.0.tgz#0e61ec257fba409c41372175e7c1e606dc79bb20" integrity sha512-YfeEE9kCjqTS9IitkgfJuxjcEtLUHMqa8yUJ6zdz8vR7hKuo6mOy2C05P0F1tdMmDCeuyidKnlrw/iTppHcr2A== @@ -873,28 +651,14 @@ "@babel/helper-split-export-declaration" "^7.18.6" globals "^11.1.0" -"@babel/plugin-transform-computed-properties@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.13.0.tgz#845c6e8b9bb55376b1fa0b92ef0bdc8ea06644ed" - integrity sha512-RRqTYTeZkZAz8WbieLTvKUEUxZlUTdmL5KGMyZj7FnMfLNKV4+r5549aORG/mgojRmFlQMJDUupwAMiF2Q7OUg== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-computed-properties@^7.18.9": +"@babel/plugin-transform-computed-properties@^7.0.0", "@babel/plugin-transform-computed-properties@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.18.9.tgz#2357a8224d402dad623caf6259b611e56aec746e" integrity sha512-+i0ZU1bCDymKakLxn5srGHrsAPRELC2WIbzwjLhHW9SIE1cPYkLCL0NlnXMZaM1vhfgA2+M7hySk42VBvrkBRw== dependencies: "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-destructuring@^7.0.0": - version "7.13.17" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.13.17.tgz#678d96576638c19d5b36b332504d3fd6e06dea27" - integrity sha512-UAUqiLv+uRLO+xuBKKMEpC+t7YRNVRqBsWWq1yKXbBZBje/t3IXCiSinZhjn/DC3qzBfICeYd2EFGEbHsh5RLA== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-destructuring@^7.18.13": +"@babel/plugin-transform-destructuring@^7.0.0", "@babel/plugin-transform-destructuring@^7.18.13": version "7.18.13" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.18.13.tgz#9e03bc4a94475d62b7f4114938e6c5c33372cbf5" integrity sha512-TodpQ29XekIsex2A+YJPj5ax2plkGa8YYY6mFjCohk/IG9IY42Rtuj1FuDeemfg2ipxIFLzPeA83SIBnlhSIow== @@ -916,14 +680,6 @@ dependencies: "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-exponentiation-operator@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.12.13.tgz#4d52390b9a273e651e4aba6aee49ef40e80cd0a1" - integrity sha512-fbUelkM1apvqez/yYx1/oICVnGo2KM5s63mhGylrmXUxK/IAXSIf87QIxVfZldWf4QsOafY6vV3bX8aMHSvNrA== - dependencies: - "@babel/helper-builder-binary-assignment-operator-visitor" "^7.12.13" - "@babel/helper-plugin-utils" "^7.12.13" - "@babel/plugin-transform-exponentiation-operator@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.18.6.tgz#421c705f4521888c65e91fdd1af951bfefd4dacd" @@ -932,15 +688,7 @@ "@babel/helper-builder-binary-assignment-operator-visitor" "^7.18.6" "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-flow-strip-types@^7.0.0", "@babel/plugin-transform-flow-strip-types@^7.17.12": - version "7.17.12" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.17.12.tgz#5e070f99a4152194bd9275de140e83a92966cab3" - integrity sha512-g8cSNt+cHCpG/uunPQELdq/TeV3eg1OLJYwxypwHtAWo9+nErH3lQx9CSO2uI9lF74A0mR0t4KoMjs1snSgnTw== - dependencies: - "@babel/helper-plugin-utils" "^7.17.12" - "@babel/plugin-syntax-flow" "^7.17.12" - -"@babel/plugin-transform-flow-strip-types@^7.18.6": +"@babel/plugin-transform-flow-strip-types@^7.0.0", "@babel/plugin-transform-flow-strip-types@^7.18.6": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.19.0.tgz#e9e8606633287488216028719638cbbb2f2dde8f" integrity sha512-sgeMlNaQVbCSpgLSKP4ZZKfsJVnFnNQlUSk6gPYzR/q7tzCgQF2t8RBKAP6cKJeZdveei7Q7Jm527xepI8lNLg== @@ -948,29 +696,14 @@ "@babel/helper-plugin-utils" "^7.19.0" "@babel/plugin-syntax-flow" "^7.18.6" -"@babel/plugin-transform-for-of@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.13.0.tgz#c799f881a8091ac26b54867a845c3e97d2696062" - integrity sha512-IHKT00mwUVYE0zzbkDgNRP6SRzvfGCYsOxIRz8KsiaaHCcT9BWIkO+H9QRJseHBLOGBZkHUdHiqj6r0POsdytg== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-for-of@^7.18.8": +"@babel/plugin-transform-for-of@^7.0.0", "@babel/plugin-transform-for-of@^7.18.8": version "7.18.8" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.18.8.tgz#6ef8a50b244eb6a0bdbad0c7c61877e4e30097c1" integrity sha512-yEfTRnjuskWYo0k1mHUqrVWaZwrdq8AYbfrpqULOJOaucGSp4mNMVps+YtA8byoevxS/urwU75vyhQIxcCgiBQ== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-function-name@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.12.13.tgz#bb024452f9aaed861d374c8e7a24252ce3a50051" - integrity sha512-6K7gZycG0cmIwwF7uMK/ZqeCikCGVBdyP2J5SKNCXO5EOHcqi+z7Jwf8AmyDNcBgxET8DrEtCt/mPKPyAzXyqQ== - dependencies: - "@babel/helper-function-name" "^7.12.13" - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-function-name@^7.18.9": +"@babel/plugin-transform-function-name@^7.0.0", "@babel/plugin-transform-function-name@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.18.9.tgz#cc354f8234e62968946c61a46d6365440fc764e0" integrity sha512-WvIBoRPaJQ5yVHzcnJFor7oS5Ls0PYixlTYE63lCj2RtdQEl15M68FXQlxnG6wdraJIXRdR7KI+hQ7q/9QjrCQ== @@ -979,28 +712,14 @@ "@babel/helper-function-name" "^7.18.9" "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-literals@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-literals/-/plugin-transform-literals-7.12.13.tgz#2ca45bafe4a820197cf315794a4d26560fe4bdb9" - integrity sha512-FW+WPjSR7hiUxMcKqyNjP05tQ2kmBCdpEpZHY1ARm96tGQCCBvXKnpjILtDplUnJ/eHZ0lALLM+d2lMFSpYJrQ== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-literals@^7.18.9": +"@babel/plugin-transform-literals@^7.0.0", "@babel/plugin-transform-literals@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-literals/-/plugin-transform-literals-7.18.9.tgz#72796fdbef80e56fba3c6a699d54f0de557444bc" integrity sha512-IFQDSRoTPnrAIrI5zoZv73IFeZu2dhu6irxQjY9rNjTT53VmKg9fenjvoiOWOkJ6mm4jKVPtdMzBY98Fp4Z4cg== dependencies: "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-member-expression-literals@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.12.13.tgz#5ffa66cd59b9e191314c9f1f803b938e8c081e40" - integrity sha512-kxLkOsg8yir4YeEPHLuO2tXP9R/gTjpuTOjshqSpELUN3ZAg2jfDnKUvzzJxObun38sw3wm4Uu69sX/zA7iRvg== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-member-expression-literals@^7.18.6": +"@babel/plugin-transform-member-expression-literals@^7.0.0", "@babel/plugin-transform-member-expression-literals@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.18.6.tgz#ac9fdc1a118620ac49b7e7a5d2dc177a1bfee88e" integrity sha512-qSF1ihLGO3q+/g48k85tUjD033C29TNTVB2paCwZPVmOsjn9pClvYYrM2VeJpBY2bcNkuny0YUyTNRyRxJ54KA== @@ -1016,17 +735,7 @@ "@babel/helper-plugin-utils" "^7.18.6" babel-plugin-dynamic-import-node "^2.3.3" -"@babel/plugin-transform-modules-commonjs@^7.0.0", "@babel/plugin-transform-modules-commonjs@^7.13.8": - version "7.16.8" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.16.8.tgz#cdee19aae887b16b9d331009aa9a219af7c86afe" - integrity sha512-oflKPvsLT2+uKQopesJt3ApiaIS2HW+hzHFcwRNtyDGieAeC/dIHZX8buJQ2J2X1rxGPy4eRcUijm3qcSPjYcA== - dependencies: - "@babel/helper-module-transforms" "^7.16.7" - "@babel/helper-plugin-utils" "^7.16.7" - "@babel/helper-simple-access" "^7.16.7" - babel-plugin-dynamic-import-node "^2.3.3" - -"@babel/plugin-transform-modules-commonjs@^7.18.6": +"@babel/plugin-transform-modules-commonjs@^7.0.0", "@babel/plugin-transform-modules-commonjs@^7.13.8", "@babel/plugin-transform-modules-commonjs@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.18.6.tgz#afd243afba166cca69892e24a8fd8c9f2ca87883" integrity sha512-Qfv2ZOWikpvmedXQJDSbxNqy7Xr/j2Y8/KfijM0iJyKkBTmWuvCA1yeH1yDM7NJhBW/2aXxeucLj6i80/LAJ/Q== @@ -1055,14 +764,7 @@ "@babel/helper-module-transforms" "^7.18.6" "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-named-capturing-groups-regex@^7.0.0": - version "7.16.8" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.16.8.tgz#7f860e0e40d844a02c9dcf9d84965e7dfd666252" - integrity sha512-j3Jw+n5PvpmhRR+mrgIh04puSANCk/T/UA3m3P1MjJkhlK906+ApHhDIqBQDdOgL/r1UYpz4GNclTXxyZrYGSw== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.16.7" - -"@babel/plugin-transform-named-capturing-groups-regex@^7.19.1": +"@babel/plugin-transform-named-capturing-groups-regex@^7.0.0", "@babel/plugin-transform-named-capturing-groups-regex@^7.19.1": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.19.1.tgz#ec7455bab6cd8fb05c525a94876f435a48128888" integrity sha512-oWk9l9WItWBQYS4FgXD4Uyy5kq898lvkXpXQxoJEY1RnvPk4R/Dvu2ebXU9q8lP+rlMwUQTFf2Ok6d78ODa0kw== @@ -1077,15 +779,7 @@ dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-object-super@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.12.13.tgz#b4416a2d63b8f7be314f3d349bd55a9c1b5171f7" - integrity sha512-JzYIcj3XtYspZDV8j9ulnoMPZZnF/Cj0LUxPOjR89BdBVx+zYJI9MdMIlUZjbXDX+6YVeS6I3e8op+qQ3BYBoQ== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - "@babel/helper-replace-supers" "^7.12.13" - -"@babel/plugin-transform-object-super@^7.18.6": +"@babel/plugin-transform-object-super@^7.0.0", "@babel/plugin-transform-object-super@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.18.6.tgz#fb3c6ccdd15939b6ff7939944b51971ddc35912c" integrity sha512-uvGz6zk+pZoS1aTZrOvrbj6Pp/kK2mp45t2B+bTDre2UgsZZ8EZLSJtUg7m/no0zOJUWgFONpB7Zv9W2tSaFlA== @@ -1093,28 +787,14 @@ "@babel/helper-plugin-utils" "^7.18.6" "@babel/helper-replace-supers" "^7.18.6" -"@babel/plugin-transform-parameters@^7.0.0", "@babel/plugin-transform-parameters@^7.13.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.13.0.tgz#8fa7603e3097f9c0b7ca1a4821bc2fb52e9e5007" - integrity sha512-Jt8k/h/mIwE2JFEOb3lURoY5C85ETcYPnbuAJ96zRBzh1XHtQZfs62ChZ6EP22QlC8c7Xqr9q+e1SU5qttwwjw== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-parameters@^7.18.8": +"@babel/plugin-transform-parameters@^7.0.0", "@babel/plugin-transform-parameters@^7.18.8": version "7.18.8" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.18.8.tgz#ee9f1a0ce6d78af58d0956a9378ea3427cccb48a" integrity sha512-ivfbE3X2Ss+Fj8nnXvKJS6sjRG4gzwPMsP+taZC+ZzEGjAYlvENixmt1sZ5Ca6tWls+BlKSGKPJ6OOXvXCbkFg== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-property-literals@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.12.13.tgz#4e6a9e37864d8f1b3bc0e2dce7bf8857db8b1a81" - integrity sha512-nqVigwVan+lR+g8Fj8Exl0UQX2kymtjcWfMOYM1vTYEKujeyv2SkMgazf2qNcK7l4SDiKyTA/nHCPqL4e2zo1A== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-property-literals@^7.18.6": +"@babel/plugin-transform-property-literals@^7.0.0", "@babel/plugin-transform-property-literals@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.18.6.tgz#e22498903a483448e94e032e9bbb9c5ccbfc93a3" integrity sha512-cYcs6qlgafTud3PAzrrRNbQtfpQ8+y/+M5tKmksS9+M1ckbH6kzY8MrexEM9mcA6JDsukE19iIRvAyYl463sMg== @@ -1153,14 +833,7 @@ "@babel/plugin-syntax-jsx" "^7.12.13" "@babel/types" "^7.13.12" -"@babel/plugin-transform-regenerator@^7.0.0": - version "7.13.15" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.13.15.tgz#e5eb28945bf8b6563e7f818945f966a8d2997f39" - integrity sha512-Bk9cOLSz8DiurcMETZ8E2YtIVJbFCPGW28DJWUakmyVWtQSm6Wsf0p4B4BfEr/eL2Nkhe/CICiUiMOCi1TPhuQ== - dependencies: - regenerator-transform "^0.14.2" - -"@babel/plugin-transform-regenerator@^7.18.6": +"@babel/plugin-transform-regenerator@^7.0.0", "@babel/plugin-transform-regenerator@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.18.6.tgz#585c66cb84d4b4bf72519a34cfce761b8676ca73" integrity sha512-poqRI2+qiSdeldcz4wTSTXBRryoq3Gc70ye7m7UD5Ww0nE29IXqMl6r7Nd15WBgRd74vloEMlShtH6CKxVzfmQ== @@ -1187,29 +860,14 @@ babel-plugin-polyfill-regenerator "^0.2.0" semver "^6.3.0" -"@babel/plugin-transform-shorthand-properties@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.12.13.tgz#db755732b70c539d504c6390d9ce90fe64aff7ad" - integrity sha512-xpL49pqPnLtf0tVluuqvzWIgLEhuPpZzvs2yabUHSKRNlN7ScYU7aMlmavOeyXJZKgZKQRBlh8rHbKiJDraTSw== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-shorthand-properties@^7.18.6": +"@babel/plugin-transform-shorthand-properties@^7.0.0", "@babel/plugin-transform-shorthand-properties@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.18.6.tgz#6d6df7983d67b195289be24909e3f12a8f664dc9" integrity sha512-eCLXXJqv8okzg86ywZJbRn19YJHU4XUa55oz2wbHhaQVn/MM+XhukiT7SYqp/7o00dg52Rj51Ny+Ecw4oyoygw== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-spread@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.13.0.tgz#84887710e273c1815ace7ae459f6f42a5d31d5fd" - integrity sha512-V6vkiXijjzYeFmQTr3dBxPtZYLPcUfY34DebOU27jIl2M/Y8Egm52Hw82CSjjPqd54GTlJs5x+CR7HeNr24ckg== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - "@babel/helper-skip-transparent-expression-wrappers" "^7.12.1" - -"@babel/plugin-transform-spread@^7.19.0": +"@babel/plugin-transform-spread@^7.0.0", "@babel/plugin-transform-spread@^7.19.0": version "7.19.0" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.19.0.tgz#dd60b4620c2fec806d60cfaae364ec2188d593b6" integrity sha512-RsuMk7j6n+r752EtzyScnWkQyuJdli6LdO5Klv8Yx0OfPVTcQkIUfS8clx5e9yHXzlnhOZF3CbQ8C2uP5j074w== @@ -1217,28 +875,14 @@ "@babel/helper-plugin-utils" "^7.19.0" "@babel/helper-skip-transparent-expression-wrappers" "^7.18.9" -"@babel/plugin-transform-sticky-regex@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.12.13.tgz#760ffd936face73f860ae646fb86ee82f3d06d1f" - integrity sha512-Jc3JSaaWT8+fr7GRvQP02fKDsYk4K/lYwWq38r/UGfaxo89ajud321NH28KRQ7xy1Ybc0VUE5Pz8psjNNDUglg== - dependencies: - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-sticky-regex@^7.18.6": +"@babel/plugin-transform-sticky-regex@^7.0.0", "@babel/plugin-transform-sticky-regex@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.18.6.tgz#c6706eb2b1524028e317720339583ad0f444adcc" integrity sha512-kfiDrDQ+PBsQDO85yj1icueWMfGfJFKN1KCkndygtu/C9+XUfydLC8Iv5UYJqRwy4zk8EcplRxEOeLyjq1gm6Q== dependencies: "@babel/helper-plugin-utils" "^7.18.6" -"@babel/plugin-transform-template-literals@^7.0.0": - version "7.13.0" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.13.0.tgz#a36049127977ad94438dee7443598d1cefdf409d" - integrity sha512-d67umW6nlfmr1iehCcBv69eSUSySk1EsIS8aTDX4Xo9qajAh6mYtcl4kJrBkGXuxZPEgVr7RVfAvNW6YQkd4Mw== - dependencies: - "@babel/helper-plugin-utils" "^7.13.0" - -"@babel/plugin-transform-template-literals@^7.18.9": +"@babel/plugin-transform-template-literals@^7.0.0", "@babel/plugin-transform-template-literals@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.18.9.tgz#04ec6f10acdaa81846689d63fae117dd9c243a5e" integrity sha512-S8cOWfT82gTezpYOiVaGHrCbhlHgKhQt8XH5ES46P2XWmX92yisoZywf5km75wv5sYcXDUCLMmMxOLCtthDgMA== @@ -1268,15 +912,7 @@ dependencies: "@babel/helper-plugin-utils" "^7.18.9" -"@babel/plugin-transform-unicode-regex@^7.0.0": - version "7.12.13" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.12.13.tgz#b52521685804e155b1202e83fc188d34bb70f5ac" - integrity sha512-mDRzSNY7/zopwisPZ5kM9XKCfhchqIYwAKRERtEnhYscZB79VRekuRSoYbN0+KVe3y8+q1h6A4svXtP7N+UoCA== - dependencies: - "@babel/helper-create-regexp-features-plugin" "^7.12.13" - "@babel/helper-plugin-utils" "^7.12.13" - -"@babel/plugin-transform-unicode-regex@^7.18.6": +"@babel/plugin-transform-unicode-regex@^7.0.0", "@babel/plugin-transform-unicode-regex@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.18.6.tgz#194317225d8c201bbae103364ffe9e2cea36cdca" integrity sha512-gE7A6Lt7YLnNOL3Pb9BNeZvi+d8l7tcRrG4+pwJjK9hD2xX4mEvjlQW60G9EEmfXVYRPv9VRQcyegIVHCql/AA== @@ -1365,16 +1001,7 @@ core-js-compat "^3.25.1" semver "^6.3.0" -"@babel/preset-flow@^7.13.13", "@babel/preset-flow@^7.17.12": - version "7.17.12" - resolved "https://registry.yarnpkg.com/@babel/preset-flow/-/preset-flow-7.17.12.tgz#664a5df59190260939eee862800a255bef3bd66f" - integrity sha512-7QDz7k4uiaBdu7N89VKjUn807pJRXmdirQu0KyR9LXnQrr5Jt41eIMKTS7ljej+H29erwmMrwq9Io9mJHLI3Lw== - dependencies: - "@babel/helper-plugin-utils" "^7.17.12" - "@babel/helper-validator-option" "^7.16.7" - "@babel/plugin-transform-flow-strip-types" "^7.17.12" - -"@babel/preset-flow@^7.14.0": +"@babel/preset-flow@^7.13.13", "@babel/preset-flow@^7.14.0", "@babel/preset-flow@^7.17.12": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/preset-flow/-/preset-flow-7.18.6.tgz#83f7602ba566e72a9918beefafef8ef16d2810cb" integrity sha512-E7BDhL64W6OUqpuyHnSroLnqyRTcG6ZdOBl1OKI/QK/HJfplqK/S3sq1Cckx7oTodJ5yOXyfw7rEADJ6UjoQDQ== @@ -1429,7 +1056,7 @@ dependencies: regenerator-runtime "^0.13.4" -"@babel/template@^7.0.0", "@babel/template@^7.16.7", "@babel/template@^7.18.10", "@babel/template@^7.3.3": +"@babel/template@^7.0.0", "@babel/template@^7.18.10", "@babel/template@^7.3.3": version "7.18.10" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.18.10.tgz#6f9134835970d1dbf0835c0d100c9f38de0c5e71" integrity sha512-TI+rCtooWHr3QJ27kJxfjutghu44DLnasDMwpDqCXVTal9RLp3RSYNh4NdBrRP2cQAoG9A8juOQl6P6oZG4JxA== @@ -1438,7 +1065,7 @@ "@babel/parser" "^7.18.10" "@babel/types" "^7.18.10" -"@babel/traverse@^7.13.0", "@babel/traverse@^7.14.0", "@babel/traverse@^7.16.7", "@babel/traverse@^7.16.8", "@babel/traverse@^7.19.0", "@babel/traverse@^7.19.1", "@babel/traverse@^7.7.2", "@babel/traverse@^7.7.4": +"@babel/traverse@^7.13.0", "@babel/traverse@^7.14.0", "@babel/traverse@^7.19.0", "@babel/traverse@^7.19.1", "@babel/traverse@^7.7.2", "@babel/traverse@^7.7.4": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.19.1.tgz#0fafe100a8c2a603b4718b1d9bf2568d1d193347" integrity sha512-0j/ZfZMxKukDaag2PtOPDbwuELqIar6lLskVPPJDjXMXjfLb1Obo/1yjxIGqqAJrmfaTIY3z2wFLAQ7qSkLsuA== @@ -1454,16 +1081,7 @@ debug "^4.1.0" globals "^11.1.0" -"@babel/types@^7.0.0", "@babel/types@^7.12.13", "@babel/types@^7.13.0", "@babel/types@^7.13.12", "@babel/types@^7.16.0", "@babel/types@^7.16.7", "@babel/types@^7.16.8", "@babel/types@^7.18.10", "@babel/types@^7.18.6", "@babel/types@^7.19.0", "@babel/types@^7.3.0", "@babel/types@^7.3.3": - version "7.19.0" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.19.0.tgz#75f21d73d73dc0351f3368d28db73465f4814600" - integrity sha512-YuGopBq3ke25BVSiS6fgF49Ul9gH1x70Bcr6bqRLjWCkcX8Hre1/5+z+IiWOIerRMSSEfGZVB9z9kyq7wVs9YA== - dependencies: - "@babel/helper-string-parser" "^7.18.10" - "@babel/helper-validator-identifier" "^7.18.6" - to-fast-properties "^2.0.0" - -"@babel/types@^7.18.9", "@babel/types@^7.19.3", "@babel/types@^7.4.4": +"@babel/types@^7.0.0", "@babel/types@^7.13.12", "@babel/types@^7.18.10", "@babel/types@^7.18.6", "@babel/types@^7.18.9", "@babel/types@^7.19.0", "@babel/types@^7.19.3", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.4": version "7.19.3" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.19.3.tgz#fc420e6bbe54880bce6779ffaf315f5e43ec9624" integrity sha512-hGCaQzIY22DJlDh9CH7NOxgKkFjBk0Cw9xDO1Xmh2151ti7wiGfQ3LauXzL4HP1fmFlTX6XjpRETTpUcv7wQLw== @@ -2245,7 +1863,7 @@ "@jridgewell/set-array" "^1.0.0" "@jridgewell/sourcemap-codec" "^1.4.10" -"@jridgewell/gen-mapping@^0.3.2": +"@jridgewell/gen-mapping@^0.3.0", "@jridgewell/gen-mapping@^0.3.2": version "0.3.2" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz#c1aedc61e853f2bb9f5dfe6d4442d3b565b253b9" integrity sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A== @@ -2264,6 +1882,14 @@ resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== +"@jridgewell/source-map@^0.3.2": + version "0.3.2" + resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.2.tgz#f45351aaed4527a298512ec72f81040c998580fb" + integrity sha512-m7O9o2uR8k2ObDysZYzdfhb08VuEml5oWGiosa1VdaPZ/A6QyPkAJuwN0Q1lhULOf6B7MtQmHENS743hWtCrgw== + dependencies: + "@jridgewell/gen-mapping" "^0.3.0" + "@jridgewell/trace-mapping" "^0.3.9" + "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" @@ -2476,42 +2102,42 @@ optionalDependencies: npmlog "2 || ^3.1.0 || ^4.0.0" -"@react-native-community/cli-clean@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-clean/-/cli-clean-9.2.1.tgz#198c5dd39c432efb5374582073065ff75d67d018" - integrity sha512-dyNWFrqRe31UEvNO+OFWmQ4hmqA07bR9Ief/6NnGwx67IO9q83D5PEAf/o96ML6jhSbDwCmpPKhPwwBbsyM3mQ== +"@react-native-community/cli-clean@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-clean/-/cli-clean-10.0.0-alpha.0.tgz#602011486bb002685dec6ca374b703f4ded7bdd5" + integrity sha512-ywRMWf2xfJaIYnMSUu4rOH0QVw6OY5zCzVwSGE5p/iZ2KW7lWcPbq8axhn7VIjUDnwfLgx6AMaGgEX1gqtiFgw== dependencies: - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" execa "^1.0.0" prompts "^2.4.0" -"@react-native-community/cli-config@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-config/-/cli-config-9.2.1.tgz#54eb026d53621ccf3a9df8b189ac24f6e56b8750" - integrity sha512-gHJlBBXUgDN9vrr3aWkRqnYrPXZLztBDQoY97Mm5Yo6MidsEpYo2JIP6FH4N/N2p1TdjxJL4EFtdd/mBpiR2MQ== +"@react-native-community/cli-config@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-config/-/cli-config-10.0.0-alpha.0.tgz#23756eb92d6f93092f98965caf2270264cb4672c" + integrity sha512-X2KdIW81AcXWxOmPugabqVlBUDglAzgHpUI+wGz7StWbjs4+DVBNfA8bNjqDk1VIQXXt1Zmz+B9sJQ12norCMw== dependencies: - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" cosmiconfig "^5.1.0" deepmerge "^3.2.0" glob "^7.1.3" joi "^17.2.1" -"@react-native-community/cli-debugger-ui@^9.0.0": - version "9.0.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-debugger-ui/-/cli-debugger-ui-9.0.0.tgz#ea5c5dad6008bccd840d858e160d42bb2ced8793" - integrity sha512-7hH05ZwU9Tp0yS6xJW0bqcZPVt0YCK7gwj7gnRu1jDNN2kughf6Lg0Ys29rAvtZ7VO1PK5c1O+zs7yFnylQDUA== +"@react-native-community/cli-debugger-ui@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-debugger-ui/-/cli-debugger-ui-10.0.0-alpha.0.tgz#8f6711587f802a4bf6b6f81438a5653ecc010671" + integrity sha512-MdNyZWBEDbYWb7DjWI71hqImtWUDW4O39Cgf7KSU2gs6AmoeGBrP8bIwz07ikqgkEXDRqotqYNXLEAaqJvYibg== dependencies: serve-static "^1.13.1" -"@react-native-community/cli-doctor@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-doctor/-/cli-doctor-9.2.1.tgz#04859a93f0ea87d78cc7050362b6ce2b1c54fd36" - integrity sha512-RpUax0pkKumXJ5hcRG0Qd+oYWsA2RFeMWKY+Npg8q05Cwd1rqDQfWGprkHC576vz26+FPuvwEagoAf6fR2bvJA== +"@react-native-community/cli-doctor@^10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-doctor/-/cli-doctor-10.0.0-alpha.1.tgz#60560778c5e406f693b8d344364404975f044891" + integrity sha512-Nk2r0ltZw7GkuhnUZy3rojMx8jLEryJ2NNyaA7C9ZiUZqyOszg6RkeNORHZSWI0pULzmMF0qYMFBzO6yhkxFTw== dependencies: - "@react-native-community/cli-config" "^9.2.1" - "@react-native-community/cli-platform-ios" "^9.2.1" - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-config" "^10.0.0-alpha.0" + "@react-native-community/cli-platform-ios" "^10.0.0-alpha.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" command-exists "^1.2.8" envinfo "^7.7.2" @@ -2526,23 +2152,23 @@ sudo-prompt "^9.0.0" wcwidth "^1.0.1" -"@react-native-community/cli-hermes@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-hermes/-/cli-hermes-9.2.1.tgz#c4aeadc4aa2b55cd0dd931a1a1c1909fd426f31a" - integrity sha512-723/NMb7egXzJrbWT1uEkN2hOpw+OOtWTG2zKJ3j7KKgUd8u/pP+/z5jO8xVrq+eYJEMjDK0FBEo1Xj7maR4Sw== +"@react-native-community/cli-hermes@^10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-hermes/-/cli-hermes-10.0.0-alpha.1.tgz#f452f4626203cb8542d163c10931f806091bc17f" + integrity sha512-FzxGylY0SLVsckms0aewm18TjSsGzR2zHRmYWLKtxZ4TAf7cA1Ta2QhO5zvCjWhiP0fO6b4nfXC9k+PoFfmWeA== dependencies: - "@react-native-community/cli-platform-android" "^9.2.1" - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-platform-android" "^10.0.0-alpha.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" hermes-profile-transformer "^0.0.6" ip "^1.1.5" -"@react-native-community/cli-platform-android@9.2.1", "@react-native-community/cli-platform-android@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-9.2.1.tgz#cd73cb6bbaeb478cafbed10bd12dfc01b484d488" - integrity sha512-VamCZ8nido3Q3Orhj6pBIx48itORNPLJ7iTfy3nucD1qISEDih3DOzCaQCtmqdEBgUkNkNl0O+cKgq5A3th3Zg== +"@react-native-community/cli-platform-android@10.0.0-alpha.1", "@react-native-community/cli-platform-android@^10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-10.0.0-alpha.1.tgz#6972e206a02ff988e7a3da61cb53bdadd0f568aa" + integrity sha512-scuu+l7r3l7X0vq5TeqdnEG/cMbtq6dQPdCY9bONeEtata1oqCMbG2BwhYAtHzycAeuOGJiB/m/o6beD7+6Wzw== dependencies: - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" execa "^1.0.0" fs-extra "^8.1.0" @@ -2550,40 +2176,40 @@ logkitty "^0.7.1" slash "^3.0.0" -"@react-native-community/cli-platform-ios@9.2.1", "@react-native-community/cli-platform-ios@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-ios/-/cli-platform-ios-9.2.1.tgz#d90740472216ffae5527dfc5f49063ede18a621f" - integrity sha512-dEgvkI6CFgPk3vs8IOR0toKVUjIFwe4AsXFvWWJL5qhrIzW9E5Owi0zPkSvzXsMlfYMbVX0COfVIK539ZxguSg== +"@react-native-community/cli-platform-ios@10.0.0-alpha.1", "@react-native-community/cli-platform-ios@^10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-ios/-/cli-platform-ios-10.0.0-alpha.1.tgz#738c18f37bd036f87a081d1e08524cd0c62464b8" + integrity sha512-G4m2/0lGQPbK6zRA7W7wC3SdP7svPvw8sGBElh4XAry+aJSG/vjFFgDBl6/UwRcEFl42rCwXhyRmbP8uCY7tjw== dependencies: - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" execa "^1.0.0" glob "^7.1.3" ora "^5.4.1" -"@react-native-community/cli-plugin-metro@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-plugin-metro/-/cli-plugin-metro-9.2.1.tgz#0ec207e78338e0cc0a3cbe1b43059c24afc66158" - integrity sha512-byBGBH6jDfUvcHGFA45W/sDwMlliv7flJ8Ns9foCh3VsIeYYPoDjjK7SawE9cPqRdMAD4SY7EVwqJnOtRbwLiQ== +"@react-native-community/cli-plugin-metro@^10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-plugin-metro/-/cli-plugin-metro-10.0.0-alpha.1.tgz#48e815e7e3c057a78ec10c3e7749d946b14d5a7f" + integrity sha512-GGJvPX1NWVMOBBvFh9sIgk6YwIsRno8+X4M5f1VgW7jJ9Q9sRmBa/iTbBL1EPGkO7yzsysUl67p3/UiVe5P/yg== dependencies: - "@react-native-community/cli-server-api" "^9.2.1" - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-server-api" "^10.0.0-alpha.0" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" - metro "0.72.3" - metro-config "0.72.3" - metro-core "0.72.3" - metro-react-native-babel-transformer "0.72.3" - metro-resolver "0.72.3" - metro-runtime "0.72.3" + metro "0.73.3" + metro-config "0.73.3" + metro-core "0.73.3" + metro-react-native-babel-transformer "0.73.3" + metro-resolver "0.73.3" + metro-runtime "0.73.3" readline "^1.3.0" -"@react-native-community/cli-server-api@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-server-api/-/cli-server-api-9.2.1.tgz#41ac5916b21d324bccef447f75600c03b2f54fbe" - integrity sha512-EI+9MUxEbWBQhWw2PkhejXfkcRqPl+58+whlXJvKHiiUd7oVbewFs0uLW0yZffUutt4FGx6Uh88JWEgwOzAdkw== +"@react-native-community/cli-server-api@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-server-api/-/cli-server-api-10.0.0-alpha.0.tgz#046207aada81618c9be93c53066017263cf32d12" + integrity sha512-0Yw45ijtLVfBIMak9vBWr2GYXuBRCRr3CwM46Kpgj8J61NCZUA7OxjxTFViddUWAPvGMhaQn4NtnGkSHKQD4Kg== dependencies: - "@react-native-community/cli-debugger-ui" "^9.0.0" - "@react-native-community/cli-tools" "^9.2.1" + "@react-native-community/cli-debugger-ui" "^10.0.0-alpha.0" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" compression "^1.7.1" connect "^3.6.5" errorhandler "^1.5.0" @@ -2592,10 +2218,10 @@ serve-static "^1.13.1" ws "^7.5.1" -"@react-native-community/cli-tools@^9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-tools/-/cli-tools-9.2.1.tgz#c332324b1ea99f9efdc3643649bce968aa98191c" - integrity sha512-bHmL/wrKmBphz25eMtoJQgwwmeCylbPxqFJnFSbkqJPXQz3ManQ6q/gVVMqFyz7D3v+riaus/VXz3sEDa97uiQ== +"@react-native-community/cli-tools@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-tools/-/cli-tools-10.0.0-alpha.0.tgz#171c40dc81dc238350bf9a5e81673d1a38c88105" + integrity sha512-fZc0UfyNwkd8rBJHzYg+uLUvIdsWwW83c2LGnpmevEfQhe1lV/f4+H+l63JGiB/TJ3ru6RmV6MvrBUgRTfqEEg== dependencies: appdirsjs "^1.2.4" chalk "^4.1.2" @@ -2607,29 +2233,29 @@ semver "^6.3.0" shell-quote "^1.7.3" -"@react-native-community/cli-types@^9.1.0": - version "9.1.0" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-types/-/cli-types-9.1.0.tgz#dcd6a0022f62790fe1f67417f4690db938746aab" - integrity sha512-KDybF9XHvafLEILsbiKwz5Iobd+gxRaPyn4zSaAerBxedug4er5VUWa8Szy+2GeYKZzMh/gsb1o9lCToUwdT/g== +"@react-native-community/cli-types@^10.0.0-alpha.0": + version "10.0.0-alpha.0" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-types/-/cli-types-10.0.0-alpha.0.tgz#9b6929bd8cc6cb4204a780c963c120e0e22a1602" + integrity sha512-Mo31VhKKDIGZw9J8LfOqslKadqUvBRGYcUoTT2H17Eg08VuA2TX/M67d+zuCw5wAmJGmPYx1C4jc0S9Xe45s5Q== dependencies: joi "^17.2.1" -"@react-native-community/cli@9.2.1": - version "9.2.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-9.2.1.tgz#15cc32531fc323d4232d57b1f2d7c571816305ac" - integrity sha512-feMYS5WXXKF4TSWnCXozHxtWq36smyhGaENXlkiRESfYZ1mnCUlPfOanNCAvNvBqdyh9d4o0HxhYKX1g9l6DCQ== - dependencies: - "@react-native-community/cli-clean" "^9.2.1" - "@react-native-community/cli-config" "^9.2.1" - "@react-native-community/cli-debugger-ui" "^9.0.0" - "@react-native-community/cli-doctor" "^9.2.1" - "@react-native-community/cli-hermes" "^9.2.1" - "@react-native-community/cli-plugin-metro" "^9.2.1" - "@react-native-community/cli-server-api" "^9.2.1" - "@react-native-community/cli-tools" "^9.2.1" - "@react-native-community/cli-types" "^9.1.0" +"@react-native-community/cli@10.0.0-alpha.1": + version "10.0.0-alpha.1" + resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-10.0.0-alpha.1.tgz#7a12588beaefda43d8d340b442def8593c651a6b" + integrity sha512-qvxZD5l1ozUxTKkONJAxBimrbWHkPNaBDaXDhNuccrmCkxzCl6Mll+khIPCWsTj5Z6FTxs05zv4wDwaV2umilQ== + dependencies: + "@react-native-community/cli-clean" "^10.0.0-alpha.0" + "@react-native-community/cli-config" "^10.0.0-alpha.0" + "@react-native-community/cli-debugger-ui" "^10.0.0-alpha.0" + "@react-native-community/cli-doctor" "^10.0.0-alpha.1" + "@react-native-community/cli-hermes" "^10.0.0-alpha.1" + "@react-native-community/cli-plugin-metro" "^10.0.0-alpha.1" + "@react-native-community/cli-server-api" "^10.0.0-alpha.0" + "@react-native-community/cli-tools" "^10.0.0-alpha.0" + "@react-native-community/cli-types" "^10.0.0-alpha.0" chalk "^4.1.2" - commander "^9.4.0" + commander "^9.4.1" execa "^1.0.0" find-up "^4.1.0" fs-extra "^8.1.0" @@ -2947,10 +2573,10 @@ acorn-jsx@^5.3.2: resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== -acorn@^8.8.0: - version "8.8.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.0.tgz#88c0187620435c7f6015803f5539dae05a9dbea8" - integrity sha512-QOxyigPVrpZ2GXT+PFyZTl6TtOFc5egxHIP9IlQ+RbupQuX4RkT/Bee4/kQuC02Xkzg84JcT7oLYtDIQxp+v7w== +acorn@^8.5.0, acorn@^8.8.0: + version "8.8.1" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.1.tgz#0a3f9cbecc4ec3bea6f0a80b66ae8dd2da250b73" + integrity sha512-7zFpHzhnqYKrkYdUjF1HI1bzd0VygEGX8lFk4k5zVMqHEoES+P+7TKI+EvLO9WVMJ8eekdO0aDEK044xTXwPPA== agent-base@4, agent-base@^4.3.0: version "4.3.0" @@ -3030,15 +2656,7 @@ ansi-styles@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== -anymatch@^3.0.3: - version "3.1.1" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.1.tgz#c55ecf02185e2469259399310c173ce31233b142" - integrity sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg== - dependencies: - normalize-path "^3.0.0" - picomatch "^2.0.4" - -anymatch@~3.1.2: +anymatch@^3.0.3, anymatch@~3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== @@ -3468,7 +3086,7 @@ braces@^3.0.1, braces@~3.0.2: dependencies: fill-range "^7.0.1" -browserslist@^4.16.3, browserslist@^4.21.3, browserslist@^4.21.4: +browserslist@^4.21.3, browserslist@^4.21.4: version "4.21.4" resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.4.tgz#e7496bbc67b9e39dd0f98565feccdcb0d4ff6987" integrity sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw== @@ -3802,7 +3420,7 @@ command-exists@^1.2.8: resolved "https://registry.yarnpkg.com/command-exists/-/command-exists-1.2.8.tgz#715acefdd1223b9c9b37110a149c6392c2852291" integrity sha512-PM54PkseWbiiD/mMsbvW351/u+dafwTJ0ye2qB60G1aGQP9j3xK2gmMDc+R34L3nDtx4qMCitXT75mkbkGJDLw== -commander@^2.12.1, commander@^2.18.0: +commander@^2.12.1, commander@^2.18.0, commander@^2.20.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== @@ -3812,10 +3430,10 @@ commander@^4.0.1: resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== -commander@^9.4.0: - version "9.4.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.0.tgz#bc4a40918fefe52e22450c111ecd6b7acce6f11c" - integrity sha512-sRPT+umqkz90UA8M1yqYfnHlZA7fF6nSphDtxeywPZ49ysjxDQybzk13CL+mXekDRG92skbcqCLVovuCusNmFw== +commander@^9.4.1: + version "9.4.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-9.4.1.tgz#d1dd8f2ce6faf93147295c0df13c7c21141cfbdd" + integrity sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw== commander@~2.13.0: version "2.13.0" @@ -3894,21 +3512,13 @@ copy-descriptor@^0.1.0: resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= -core-js-compat@^3.25.1: +core-js-compat@^3.25.1, core-js-compat@^3.9.1: version "3.25.5" resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.25.5.tgz#0016e8158c904f7b059486639e6e82116eafa7d9" integrity sha512-ovcyhs2DEBUIE0MGEKHP4olCUW/XYte3Vroyxuh38rD1wAO4dHohsovUC4eAOuzFxE6b+RXvBU3UZ9o0YhUTkA== dependencies: browserslist "^4.21.4" -core-js-compat@^3.9.1: - version "3.10.1" - resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.10.1.tgz#62183a3a77ceeffcc420d907a3e6fc67d9b27f1c" - integrity sha512-ZHQTdTPkqvw2CeHiZC970NNJcnwzT6YIueDMASKt+p3WbZsLXOcoD392SkcWhkC0wBBHhlfhqGKKsNCQUozYtg== - dependencies: - browserslist "^4.16.3" - semver "7.0.0" - core-js-pure@^3.19.0: version "3.19.1" resolved "https://registry.yarnpkg.com/core-js-pure/-/core-js-pure-3.19.1.tgz#edffc1fc7634000a55ba05e95b3f0fe9587a5aa4" @@ -5017,7 +4627,7 @@ fs.realpath@^1.0.0: resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= -fsevents@^2.1.2, fsevents@^2.3.2, fsevents@~2.3.2: +fsevents@^2.3.2, fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== @@ -5168,19 +4778,7 @@ glob-parent@^6.0.1: dependencies: is-glob "^4.0.3" -glob@^7.0.0, glob@^7.1.1, glob@^7.1.3, glob@^7.1.4: - version "7.2.0" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" - integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -glob@^7.2.0: +glob@^7.0.0, glob@^7.1.1, glob@^7.1.3, glob@^7.1.4, glob@^7.2.0: version "7.2.3" resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q== @@ -6854,10 +6452,10 @@ merge2@^1.3.0, merge2@^1.4.1: resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== -metro-babel-register@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-babel-register/-/metro-babel-register-0.72.3.tgz#b204e947a610cb695c19cec44d03bf92f29825c2" - integrity sha512-OqG9rRLBMH7AkQ9Dmw16PfFIEe0ZQug62soZ4BJ0YC3fuYi4xD9WkxuVQeNy9L39Zu0iZUPd5+dXddpKaLxftA== +metro-babel-register@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-babel-register/-/metro-babel-register-0.73.3.tgz#fc5601bbe166efb59d063d8b330de062475c257b" + integrity sha512-uuNoggz/tr5FrG5lbzMHMO5wN0L3BZi/AYC/8oPTbiIJEavZ5ugVaePOoTU04c67KMGgNLIbJESZpLZn/ttN7A== dependencies: "@babel/core" "^7.14.0" "@babel/plugin-proposal-nullish-coalescing-operator" "^7.0.0" @@ -6870,53 +6468,53 @@ metro-babel-register@0.72.3: babel-plugin-replace-ts-export-assignment "^0.0.2" escape-string-regexp "^1.0.5" -metro-babel-transformer@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-babel-transformer/-/metro-babel-transformer-0.72.3.tgz#2c60493a4eb7a8d20cc059f05e0e505dc1684d01" - integrity sha512-PTOR2zww0vJbWeeM3qN90WKENxCLzv9xrwWaNtwVlhcV8/diNdNe82sE1xIxLFI6OQuAVwNMv1Y7VsO2I7Ejrw== +metro-babel-transformer@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-babel-transformer/-/metro-babel-transformer-0.73.3.tgz#13e2e5d7981049f9b4babd6a97e40c8decdf19a8" + integrity sha512-vNNFMxsZn1JasZEk9RlC84KQiei1ecZ3BmRsNCipWN7YMC/SbV8QLMdqhgF8XIfKnZnS6Z2RCFGPYPxu7/9sJA== dependencies: "@babel/core" "^7.14.0" hermes-parser "0.8.0" - metro-source-map "0.72.3" + metro-source-map "0.73.3" nullthrows "^1.1.1" -metro-cache-key@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-cache-key/-/metro-cache-key-0.72.3.tgz#dcc3055b6cb7e35b84b4fe736a148affb4ecc718" - integrity sha512-kQzmF5s3qMlzqkQcDwDxrOaVxJ2Bh6WRXWdzPnnhsq9LcD3B3cYqQbRBS+3tSuXmathb4gsOdhWslOuIsYS8Rg== +metro-cache-key@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-cache-key/-/metro-cache-key-0.73.3.tgz#eabd107ba6274aa9c629a807c9801c914fc1091a" + integrity sha512-LsP8aZr/LJuw428hNAQHKJkL7N3RvYcHcG6kbUXUfRqwOsoE4q6C8kXebtm+5+fbNduNVzHjEBIQM2uFUctMow== -metro-cache@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-cache/-/metro-cache-0.72.3.tgz#fd079f90b12a81dd5f1567c607c13b14ae282690" - integrity sha512-++eyZzwkXvijWRV3CkDbueaXXGlVzH9GA52QWqTgAOgSHYp5jWaDwLQ8qpsMkQzpwSyIF4LLK9aI3eA7Xa132A== +metro-cache@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-cache/-/metro-cache-0.73.3.tgz#172f4a5c88738643f1b11b7593c2edec6882bef6" + integrity sha512-nRLxn1B8J4LxFZo02OCFryalqaJKW1ddAteS5zdSmsJLdaDwvKH+J73Rp/XOR5Puu1A05A7BF4/aYKzwY/HU4A== dependencies: - metro-core "0.72.3" - rimraf "^2.5.4" + metro-core "0.73.3" + rimraf "^3.0.2" -metro-config@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-config/-/metro-config-0.72.3.tgz#c2f1a89537c79cec516b1229aa0550dfa769e2ee" - integrity sha512-VEsAIVDkrIhgCByq8HKTWMBjJG6RlYwWSu1Gnv3PpHa0IyTjKJtB7wC02rbTjSaemcr82scldf2R+h6ygMEvsw== +metro-config@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-config/-/metro-config-0.73.3.tgz#52fbb1b4ecf638fe16d2227535795609e4faf396" + integrity sha512-k1OSBNVe/i+Vm1IPA35qt1eD/3yjtEA0qfzvLeTmuvarE+twBpXupJViKqtfqvo6rldk0VoYX/UlnqzkaJ1hIg== dependencies: cosmiconfig "^5.0.5" jest-validate "^26.5.2" - metro "0.72.3" - metro-cache "0.72.3" - metro-core "0.72.3" - metro-runtime "0.72.3" + metro "0.73.3" + metro-cache "0.73.3" + metro-core "0.73.3" + metro-runtime "0.73.3" -metro-core@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-core/-/metro-core-0.72.3.tgz#e3a276d54ecc8fe667127347a1bfd3f8c0009ccb" - integrity sha512-KuYWBMmLB4+LxSMcZ1dmWabVExNCjZe3KysgoECAIV+wyIc2r4xANq15GhS94xYvX1+RqZrxU1pa0jQ5OK+/6A== +metro-core@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-core/-/metro-core-0.73.3.tgz#dc79fa4abe6a266a4d3b4a2352864f4cb6440298" + integrity sha512-wsW2XyWU9QtWnNMrUIDnoTIKDHBvKa/uupY+91gYV9l6glKboP1F8AD0mpzNwFqOXtx48jm7iDa7xzEY25bgcA== dependencies: lodash.throttle "^4.1.1" - metro-resolver "0.72.3" + metro-resolver "0.73.3" -metro-file-map@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-file-map/-/metro-file-map-0.72.3.tgz#94f6d4969480aa7f47cfe2c5f365ad4e85051f12" - integrity sha512-LhuRnuZ2i2uxkpFsz1XCDIQSixxBkBG7oICAFyLyEMDGbcfeY6/NexphfLdJLTghkaoJR5ARFMiIxUg9fIY/pA== +metro-file-map@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-file-map/-/metro-file-map-0.73.3.tgz#e23b2e4d0cab5271372707ef80c91ad1f3512714" + integrity sha512-t6JrJH4YO8a1Qf+THZ4FCW1NRZ2qSUQb7p42T1Ea1w3C18OnfOg19xZUAiGQ/46FN7ROeZDdE8LLJDPT0s4fzQ== dependencies: abort-controller "^3.0.0" anymatch "^3.0.3" @@ -6929,41 +6527,49 @@ metro-file-map@0.72.3: jest-util "^27.2.0" jest-worker "^27.2.0" micromatch "^4.0.4" + nullthrows "^1.1.1" walker "^1.0.7" optionalDependencies: - fsevents "^2.1.2" + fsevents "^2.3.2" -metro-hermes-compiler@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-hermes-compiler/-/metro-hermes-compiler-0.72.3.tgz#e9ab4d25419eedcc72c73842c8da681a4a7e691e" - integrity sha512-QWDQASMiXNW3j8uIQbzIzCdGYv5PpAX/ZiF4/lTWqKRWuhlkP4auhVY4eqdAKj5syPx45ggpjkVE0p8hAPDZYg== +metro-hermes-compiler@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-hermes-compiler/-/metro-hermes-compiler-0.73.3.tgz#017c200ec0d2585eed19314612fa7a599a935f06" + integrity sha512-9r+dXiIt2k2uYmaNgeJoLJNZ2FnO6ok7pLppnMZIwFUEvOiFpvOBlBIpqOCEzzRh3gLinEtZ0SmRPhDstI+Iog== -metro-inspector-proxy@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-inspector-proxy/-/metro-inspector-proxy-0.72.3.tgz#8d7ff4240fc414af5b72d86dac2485647fc3cf09" - integrity sha512-UPFkaq2k93RaOi+eqqt7UUmqy2ywCkuxJLasQ55+xavTUS+TQSyeTnTczaYn+YKw+izLTLllGcvqnQcZiWYhGw== +metro-inspector-proxy@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-inspector-proxy/-/metro-inspector-proxy-0.73.3.tgz#6ac40f1217fb2ef7fa1331cffe730036dee70b36" + integrity sha512-I3Eixd28uamjbKtO6LB7jlGgdwt8zxBrRznp3qMWL8WZU6gu9TU/SAJa1TnABOK0VwdPmz161fWL/eHBEKZCrg== dependencies: connect "^3.6.5" debug "^2.2.0" ws "^7.5.1" - yargs "^15.3.1" + yargs "^17.5.1" + +metro-memory-fs@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-memory-fs/-/metro-memory-fs-0.73.3.tgz#cd5feba53b77f35c31e530de763c856aa5685d13" + integrity sha512-uE/LLrf+LqsLUunWjSmrnHpdqaO1rTBAN/HExQ16TLwwAEovUF/UKS2CqTp4VEKGwfD/458c6YXL45xxLDOp3g== -metro-memory-fs@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-memory-fs/-/metro-memory-fs-0.72.3.tgz#ed5919d2873b044a8cdea4fe97a76105e9a264ab" - integrity sha512-GNNb6ZHPsV4t6s0senwcdn3W8LF2jniiDBdltghY/xSXSzoDj34hpQyiKYohUBW4y3nrYIXg63ce8198Ep7xOQ== +metro-minify-terser@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-minify-terser/-/metro-minify-terser-0.73.3.tgz#e0d8164a42067bcf8dfe8a066545d080af213bf5" + integrity sha512-EDA+G7WM9ACtlvIc735u002UNedTIKBXx4RaIFFnLbp8Z+0csrTnFY0hsasxwkFR1KcL42TppLiY0L+iO5TuJw== + dependencies: + terser "^5.15.0" -metro-minify-uglify@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-minify-uglify/-/metro-minify-uglify-0.72.3.tgz#a9d4cd27933b29cfe95d8406b40d185567a93d39" - integrity sha512-dPXqtMI8TQcj0g7ZrdhC8X3mx3m3rtjtMuHKGIiEXH9CMBvrET8IwrgujQw2rkPcXiSiX8vFDbGMIlfxefDsKA== +metro-minify-uglify@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-minify-uglify/-/metro-minify-uglify-0.73.3.tgz#9e3438e73208a21e085891d5cdf60c80dd97bbb7" + integrity sha512-ksI9tiXYwFaNPMyuArzD1x5Fz3CNzlI7dL0uqEriDMdVXk5/7FDwi6hV+pAefTxJlTVt9NStDfKyQyj3x8CxJQ== dependencies: uglify-es "^3.1.9" -metro-react-native-babel-preset@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-react-native-babel-preset/-/metro-react-native-babel-preset-0.72.3.tgz#e549199fa310fef34364fdf19bd210afd0c89432" - integrity sha512-uJx9y/1NIqoYTp6ZW1osJ7U5ZrXGAJbOQ/Qzl05BdGYvN1S7Qmbzid6xOirgK0EIT0pJKEEh1s8qbassYZe4cw== +metro-react-native-babel-preset@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-react-native-babel-preset/-/metro-react-native-babel-preset-0.73.3.tgz#c4a0fcae395894ec85e235ec75de88d56f64e291" + integrity sha512-JJ22lR4CVaw3OKTz9YAY/ckymr3DbO+qy/x5kLaF4g0LcvZmhhKfDK+fml577AZU6sKb/CTd0SBwt+VAz+Hu7Q== dependencies: "@babel/core" "^7.14.0" "@babel/plugin-proposal-async-generator-functions" "^7.0.0" @@ -6984,7 +6590,6 @@ metro-react-native-babel-preset@0.72.3: "@babel/plugin-transform-classes" "^7.0.0" "@babel/plugin-transform-computed-properties" "^7.0.0" "@babel/plugin-transform-destructuring" "^7.0.0" - "@babel/plugin-transform-exponentiation-operator" "^7.0.0" "@babel/plugin-transform-flow-strip-types" "^7.0.0" "@babel/plugin-transform-function-name" "^7.0.0" "@babel/plugin-transform-literals" "^7.0.0" @@ -7005,64 +6610,64 @@ metro-react-native-babel-preset@0.72.3: "@babel/template" "^7.0.0" react-refresh "^0.4.0" -metro-react-native-babel-transformer@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-react-native-babel-transformer/-/metro-react-native-babel-transformer-0.72.3.tgz#f8eda8c07c0082cbdbef47a3293edc41587c6b5a" - integrity sha512-Ogst/M6ujYrl/+9mpEWqE3zF7l2mTuftDTy3L8wZYwX1pWUQWQpfU1aJBeWiLxt1XlIq+uriRjKzKoRoIK57EA== +metro-react-native-babel-transformer@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-react-native-babel-transformer/-/metro-react-native-babel-transformer-0.73.3.tgz#a521e5f559cec4ec9b878087e606afbb8e92db2b" + integrity sha512-9cCdN2S+skTx1IT/A+UHteN80eOmgU0ir3E/wWybUbV/zhWtHQjbxBnB+bEbFNRe9Jmk73Ga9pWkCFqO8txwYw== dependencies: "@babel/core" "^7.14.0" babel-preset-fbjs "^3.4.0" hermes-parser "0.8.0" - metro-babel-transformer "0.72.3" - metro-react-native-babel-preset "0.72.3" - metro-source-map "0.72.3" + metro-babel-transformer "0.73.3" + metro-react-native-babel-preset "0.73.3" + metro-source-map "0.73.3" nullthrows "^1.1.1" -metro-resolver@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-resolver/-/metro-resolver-0.72.3.tgz#c64ce160454ac850a15431509f54a587cb006540" - integrity sha512-wu9zSMGdxpKmfECE7FtCdpfC+vrWGTdVr57lDA0piKhZV6VN6acZIvqQ1yZKtS2WfKsngncv5VbB8Y5eHRQP3w== +metro-resolver@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-resolver/-/metro-resolver-0.73.3.tgz#dc21ca03c8aeb0bc05fe4e8c318791e213bde9d7" + integrity sha512-XbiZ22MaFFchaErNfqeW9ZPPRpiQEIylhtlja9/5QzNgAcAWbfIGY0Ok39XyVyWjX4Ab8YAwQUeCqyO48ojzZQ== dependencies: absolute-path "^0.0.0" -metro-runtime@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-runtime/-/metro-runtime-0.72.3.tgz#1485ed7b5f06d09ebb40c83efcf8accc8d30b8b9" - integrity sha512-3MhvDKfxMg2u7dmTdpFOfdR71NgNNo4tzAyJumDVQKwnHYHN44f2QFZQqpPBEmqhWlojNeOxsqFsjYgeyMx6VA== +metro-runtime@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-runtime/-/metro-runtime-0.73.3.tgz#39fde3484342bf4eb8a3ec9bce8bc519e128e1ea" + integrity sha512-ywNq9exXtCiBA/vcmiyuI+sBR3tVMQIkvrmcHJ+cOWf5kl/vBS2FbYimESlMwZKjzH7l07LrQcvAvTn215N9bw== dependencies: "@babel/runtime" "^7.0.0" react-refresh "^0.4.0" -metro-source-map@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-source-map/-/metro-source-map-0.72.3.tgz#5efcf354413804a62ff97864e797f60ef3cc689e" - integrity sha512-eNtpjbjxSheXu/jYCIDrbNEKzMGOvYW6/ePYpRM7gDdEagUOqKOCsi3St8NJIQJzZCsxD2JZ2pYOiomUSkT1yQ== +metro-source-map@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-source-map/-/metro-source-map-0.73.3.tgz#6eaf99ccd98b46f8afd8cb5cbb5e360dcce3836a" + integrity sha512-zOm8Ha0hWiJhI52IcMibdNIS6O3YK6qUnQ7dgZOGvnEWRTfzYlX08yFXwMg91GIdXzxHJE43opcPwSE1RDvoGQ== dependencies: "@babel/traverse" "^7.14.0" "@babel/types" "^7.0.0" invariant "^2.2.4" - metro-symbolicate "0.72.3" + metro-symbolicate "0.73.3" nullthrows "^1.1.1" - ob1 "0.72.3" + ob1 "0.73.3" source-map "^0.5.6" vlq "^1.0.0" -metro-symbolicate@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-symbolicate/-/metro-symbolicate-0.72.3.tgz#093d4f8c7957bcad9ca2ab2047caa90b1ee1b0c1" - integrity sha512-eXG0NX2PJzJ/jTG4q5yyYeN2dr1cUqUaY7worBB0SP5bRWRc3besfb+rXwfh49wTFiL5qR0oOawkU4ZiD4eHXw== +metro-symbolicate@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-symbolicate/-/metro-symbolicate-0.73.3.tgz#2641dd63fc8ef348a3c2bb0fa2f82f1a75d8b96a" + integrity sha512-gOjoQcUFuDl3YKO0D7rcLEDIw331LM+CiKgIzQlZmx7uZimORnt9xf/8P/Ued0y77q8ColuJAVDqp/JirqRfEw== dependencies: invariant "^2.2.4" - metro-source-map "0.72.3" + metro-source-map "0.73.3" nullthrows "^1.1.1" source-map "^0.5.6" through2 "^2.0.1" vlq "^1.0.0" -metro-transform-plugins@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-transform-plugins/-/metro-transform-plugins-0.72.3.tgz#b00e5a9f24bff7434ea7a8e9108eebc8386b9ee4" - integrity sha512-D+TcUvCKZbRua1+qujE0wV1onZvslW6cVTs7dLCyC2pv20lNHjFr1GtW01jN2fyKR2PcRyMjDCppFd9VwDKnSg== +metro-transform-plugins@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-transform-plugins/-/metro-transform-plugins-0.73.3.tgz#cd620058531758665b55427fcb06a3d259086e6c" + integrity sha512-zes8OxN07nLcPq/BD7FgFusoVlVYbmQpdW290SRCsnnQK7ul4amzm9clygX54WYjYm8aHXSEmVrZtd/80Q+rZw== dependencies: "@babel/core" "^7.14.0" "@babel/generator" "^7.14.0" @@ -7070,29 +6675,29 @@ metro-transform-plugins@0.72.3: "@babel/traverse" "^7.14.0" nullthrows "^1.1.1" -metro-transform-worker@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro-transform-worker/-/metro-transform-worker-0.72.3.tgz#bdc6cc708ea114bc085e11d675b8ff626d7e6db7" - integrity sha512-WsuWj9H7i6cHuJuy+BgbWht9DK5FOgJxHLGAyULD5FJdTG9rSMFaHDO5WfC0OwQU5h4w6cPT40iDuEGksM7+YQ== +metro-transform-worker@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro-transform-worker/-/metro-transform-worker-0.73.3.tgz#093735e55e2c3564f560e188ff999d9752fc253d" + integrity sha512-oF/hFX8Oj/PLuacpzWwYTgf0k0vSxI/nlWBPQkAUuW7QYOv7w9WRWRNczl8fbYohr8LU7CbwuQ662DRzzQDrAQ== dependencies: "@babel/core" "^7.14.0" "@babel/generator" "^7.14.0" "@babel/parser" "^7.14.0" "@babel/types" "^7.0.0" babel-preset-fbjs "^3.4.0" - metro "0.72.3" - metro-babel-transformer "0.72.3" - metro-cache "0.72.3" - metro-cache-key "0.72.3" - metro-hermes-compiler "0.72.3" - metro-source-map "0.72.3" - metro-transform-plugins "0.72.3" + metro "0.73.3" + metro-babel-transformer "0.73.3" + metro-cache "0.73.3" + metro-cache-key "0.73.3" + metro-hermes-compiler "0.73.3" + metro-source-map "0.73.3" + metro-transform-plugins "0.73.3" nullthrows "^1.1.1" -metro@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/metro/-/metro-0.72.3.tgz#eb587037d62f48a0c33c8d88f26666b4083bb61e" - integrity sha512-Hb3xTvPqex8kJ1hutQNZhQadUKUwmns/Du9GikmWKBFrkiG3k3xstGAyO5t5rN9JSUEzQT6y9SWzSSOGogUKIg== +metro@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/metro/-/metro-0.73.3.tgz#d1e3bd247468e0293b644bca408265e725d686f9" + integrity sha512-AHjeWI05YyTPaMNAXW4kUDLVr2MPs6DeawofS6CxiWGh2P9aVosC3GPJmXF2fGRW7MKdGvGWIDqUlWJUw8M0CA== dependencies: "@babel/code-frame" "^7.0.0" "@babel/core" "^7.14.0" @@ -7117,33 +6722,34 @@ metro@0.72.3: invariant "^2.2.4" jest-worker "^27.2.0" lodash.throttle "^4.1.1" - metro-babel-transformer "0.72.3" - metro-cache "0.72.3" - metro-cache-key "0.72.3" - metro-config "0.72.3" - metro-core "0.72.3" - metro-file-map "0.72.3" - metro-hermes-compiler "0.72.3" - metro-inspector-proxy "0.72.3" - metro-minify-uglify "0.72.3" - metro-react-native-babel-preset "0.72.3" - metro-resolver "0.72.3" - metro-runtime "0.72.3" - metro-source-map "0.72.3" - metro-symbolicate "0.72.3" - metro-transform-plugins "0.72.3" - metro-transform-worker "0.72.3" + metro-babel-transformer "0.73.3" + metro-cache "0.73.3" + metro-cache-key "0.73.3" + metro-config "0.73.3" + metro-core "0.73.3" + metro-file-map "0.73.3" + metro-hermes-compiler "0.73.3" + metro-inspector-proxy "0.73.3" + metro-minify-terser "0.73.3" + metro-minify-uglify "0.73.3" + metro-react-native-babel-preset "0.73.3" + metro-resolver "0.73.3" + metro-runtime "0.73.3" + metro-source-map "0.73.3" + metro-symbolicate "0.73.3" + metro-transform-plugins "0.73.3" + metro-transform-worker "0.73.3" mime-types "^2.1.27" node-fetch "^2.2.0" nullthrows "^1.1.1" - rimraf "^2.5.4" + rimraf "^3.0.2" serialize-error "^2.1.0" source-map "^0.5.6" strip-ansi "^6.0.0" temp "0.8.3" throat "^5.0.0" ws "^7.5.1" - yargs "^15.3.1" + yargs "^17.5.1" micromatch@^3.1.10: version "3.1.10" @@ -7410,10 +7016,10 @@ oauth-sign@~0.9.0: resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455" integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ== -ob1@0.72.3: - version "0.72.3" - resolved "https://registry.yarnpkg.com/ob1/-/ob1-0.72.3.tgz#fc1efcfe156f12ed23615f2465a796faad8b91e4" - integrity sha512-OnVto25Sj7Ghp0vVm2THsngdze3tVq0LOg9LUHsAVXMecpqOP0Y8zaATW8M9gEgs2lNEAcCqV0P/hlmOPhVRvg== +ob1@0.73.3: + version "0.73.3" + resolved "https://registry.yarnpkg.com/ob1/-/ob1-0.73.3.tgz#36e796fa6fbea4696063cf711fe53505be7bc9a2" + integrity sha512-KpCFQty/eGriUsF3tD4FybV2vsWNzID3Thq/3o0VzXn+rtcQdRk1r6USM5PddWaFjxZqbVXjlr6u7DJGhPz9xw== object-assign@^4.1.0, object-assign@^4.1.1: version "4.1.1" @@ -7734,12 +7340,7 @@ picocolors@^1.0.0: resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== -picomatch@^2.0.4, picomatch@^2.2.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972" - integrity sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw== - -picomatch@^2.2.1: +picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.3: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== @@ -7832,11 +7433,6 @@ prettyjson@^1.2.1: colors "1.4.0" minimist "^1.2.0" -private@^0.1.8: - version "0.1.8" - resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff" - integrity sha512-VvivMrbvd2nKkiG38qjULzlc+4Vx4wm/whI9pQD35YrARNnhxeiRktSOhSukRLFNlzg6Br/cJPet5J/u19r/mg== - process-nextick-args@~2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.0.tgz#a37d732f4271b4ab1ad070d35508e8290788ffaa" @@ -8054,13 +7650,6 @@ rechoir@^0.6.2: dependencies: resolve "^1.1.6" -regenerate-unicode-properties@^10.0.1: - version "10.0.1" - resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-10.0.1.tgz#7f442732aa7934a3740c779bb9b3340dccc1fb56" - integrity sha512-vn5DU6yg6h8hP/2OkQo3K7uVILvY4iu0oI4t3HFa81UPkhGJwkRwM10JEc3upjdhHjs/k8GJY1sRBhk5sr69Bw== - dependencies: - regenerate "^1.4.2" - regenerate-unicode-properties@^10.1.0: version "10.1.0" resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-10.1.0.tgz#7c3192cab6dd24e21cb4461e5ddd7dd24fa8374c" @@ -8078,14 +7667,6 @@ regenerator-runtime@^0.13.2, regenerator-runtime@^0.13.4, regenerator-runtime@^0 resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz#8925742a98ffd90814988d7566ad30ca3b263b52" integrity sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA== -regenerator-transform@^0.14.2: - version "0.14.4" - resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.14.4.tgz#5266857896518d1616a78a0479337a30ea974cc7" - integrity sha512-EaJaKPBI9GvKpvUz2mz4fhx7WPgvwRLY9v3hlNHWmAuJHI13T4nwKnNvm5RWJzEdnI5g5UwtOww+S8IdoUC2bw== - dependencies: - "@babel/runtime" "^7.8.4" - private "^0.1.8" - regenerator-transform@^0.15.0: version "0.15.0" resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.15.0.tgz#cbd9ead5d77fae1a48d957cf889ad0586adb6537" @@ -8115,18 +7696,6 @@ regexpp@^3.2.0: resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2" integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== -regexpu-core@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-5.0.1.tgz#c531122a7840de743dcf9c83e923b5560323ced3" - integrity sha512-CriEZlrKK9VJw/xQGJpQM5rY88BtuL8DM+AEwvcThHilbxiTAy8vq4iJnd2tqq8wLmjbGZzP7ZcKFjbGkmEFrw== - dependencies: - regenerate "^1.4.2" - regenerate-unicode-properties "^10.0.1" - regjsgen "^0.6.0" - regjsparser "^0.8.2" - unicode-match-property-ecmascript "^2.0.0" - unicode-match-property-value-ecmascript "^2.0.0" - regexpu-core@^5.1.0: version "5.2.1" resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-5.2.1.tgz#a69c26f324c1e962e9ffd0b88b055caba8089139" @@ -8139,23 +7708,11 @@ regexpu-core@^5.1.0: unicode-match-property-ecmascript "^2.0.0" unicode-match-property-value-ecmascript "^2.0.0" -regjsgen@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.6.0.tgz#83414c5354afd7d6627b16af5f10f41c4e71808d" - integrity sha512-ozE883Uigtqj3bx7OhL1KNbCzGyW2NQZPl6Hs09WTvCuZD5sTI4JY58bkbQWa/Y9hxIsvJ3M8Nbf7j54IqeZbA== - regjsgen@^0.7.1: version "0.7.1" resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.7.1.tgz#ee5ef30e18d3f09b7c369b76e7c2373ed25546f6" integrity sha512-RAt+8H2ZEzHeYWxZ3H2z6tF18zyyOnlcdaafLrm21Bguj7uZy6ULibiAFdXEtKQY4Sy7wDTwDiOazasMLc4KPA== -regjsparser@^0.8.2: - version "0.8.4" - resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.8.4.tgz#8a14285ffcc5de78c5b95d62bbf413b6bc132d5f" - integrity sha512-J3LABycON/VNEu3abOviqGHuB/LOtOQj8SKmfP9anY5GfAVw/SPjwzSjxGjbZXIxbGfqTHtJw58C2Li/WkStmA== - dependencies: - jsesc "~0.5.0" - regjsparser@^0.9.1: version "0.9.1" resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.9.1.tgz#272d05aa10c7c1f67095b1ff0addae8442fc5709" @@ -8286,7 +7843,7 @@ reusify@^1.0.4: resolved "https://registry.yarnpkg.com/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== -rimraf@2, rimraf@^2.5.4: +rimraf@2: version "2.7.1" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== @@ -8376,11 +7933,6 @@ selenium-webdriver@4.1.2: dependencies: lru-cache "^6.0.0" -semver@7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.0.0.tgz#5f3ca35761e47e05b206c6daff2cf814f0316b8e" - integrity sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A== - semver@^5.3.0, semver@^5.5.0, semver@^5.6.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" @@ -8599,7 +8151,7 @@ source-map-support@0.5.13: buffer-from "^1.0.0" source-map "^0.6.0" -source-map-support@^0.5.16: +source-map-support@^0.5.16, source-map-support@~0.5.20: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== @@ -8942,6 +8494,16 @@ temp@^0.8.4: dependencies: rimraf "~2.6.2" +terser@^5.15.0: + version "5.15.1" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.15.1.tgz#8561af6e0fd6d839669c73b92bdd5777d870ed6c" + integrity sha512-K1faMUvpm/FBxjBXud0LWVAGxmvoPbZbfTCYbSgaaYQaIXI3/TdI7a7ZGA73Zrou6Q8Zmz3oeUTsp/dj+ag2Xw== + dependencies: + "@jridgewell/source-map" "^0.3.2" + acorn "^8.5.0" + commander "^2.20.0" + source-map-support "~0.5.20" + test-exclude@^6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" From 6a43fafd78d581f63c664b9af6d10828ac7f77fa Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 14:40:27 -0700 Subject: [PATCH 060/169] Cleanup the template documentation after RNGP & hermesEnabled to gradle.properties (#35108) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35108 I've rewritten the comment in the android/app/build.gradle. They were really old, contained wrong links and most of the people ignored it. I've also moved the enabling of Hermes to the `gradle.properties` file. RNGP still supports the old method, but we must be sure that we notify library authors if they were reading project.ext.react.enableHermes in the past (also the website needs to be updated). I've also cleaned up the CircleCI setup as now we can specify Hermes enabled/disabled via the CLI (this will also make easier to do e2e testing). Changelog: [Android] [Changed] - Cleanup the template documentation after RNGP & hermesEnabled to gradle.properties Reviewed By: cipolleschi Differential Revision: D40762872 fbshipit-source-id: 2c09245e0a923faac53cc6c8a89e99788ae47f8a --- .circleci/config.yml | 35 ++--- packages/rn-tester/android/app/build.gradle | 132 ++++++----------- scripts/set-rn-engine.js | 53 ------- template/android/app/build.gradle | 155 +++++++------------- template/android/build.gradle | 2 - template/android/gradle.properties | 4 + 6 files changed, 125 insertions(+), 256 deletions(-) delete mode 100755 scripts/set-rn-engine.js diff --git a/.circleci/config.yml b/.circleci/config.yml index b3ee733c859655..71f5f6d2017f58 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -760,9 +760,11 @@ jobs: description: The Android build type. Must be one of "Debug", "Release". type: enum enum: ["Debug", "Release"] - newarchitecture: - type: boolean - default: false + architecture: + default: "OldArch" + description: Which React Native architecture to use. Must be one of "NewArch", "OldArch". + type: enum + enum: [ "NewArch", "OldArch" ] jsengine: default: "Hermes" description: Which JavaScript engine to use. Must be one of "Hermes", "JSC". @@ -775,17 +777,6 @@ jobs: - run_yarn - attach_workspace: at: . - - when: - condition: - equal: ["JSC", << parameters.jsengine >>] - steps: - - run: - name: Set enableHermes in buld.gradle to false - command: | - node ./scripts/set-rn-engine.js -e jsc - echo "Hermes disabled." - grep enableHermes: template/android/app/build.gradle - - run: name: Create Android template project command: | @@ -796,10 +787,20 @@ jobs: yarn - run: - name: Build the template application for << parameters.flavor >> with New Architecture set to << parameters.newarchitecture >>, and using the << parameters.jsengine>> JS engine. + name: Build the template application for << parameters.flavor >> with Architecture set to << parameters.architecture >>, and using the << parameters.jsengine>> JS engine. command: | cd /tmp/$PROJECT_NAME/android/ - ./gradlew assemble<< parameters.flavor >> -PnewArchEnabled=<< parameters.newarchitecture >> -PREACT_NATIVE_MAVEN_LOCAL_REPO=/root/react-native/maven-local + if [[ << parameters.architecture >> == "NewArch" ]]; then + export ORG_GRADLE_PROJECT_newArchEnabled=true + else + export ORG_GRADLE_PROJECT_newArchEnabled=false + fi + if [[ << parameters.jsengine >> == "Hermes" ]]; then + export ORG_GRADLE_PROJECT_hermesEnabled=true + else + export ORG_GRADLE_PROJECT_hermesEnabled=false + fi + ./gradlew assemble<< parameters.flavor >> -PREACT_NATIVE_MAVEN_LOCAL_REPO=/root/react-native/maven-local # ------------------------- # JOBS: Test iOS Template @@ -1602,7 +1603,7 @@ workflows: - build_npm_package matrix: parameters: - newarchitecture: [true, false] + architecture: ["NewArch", "OldArch"] jsengine: ["Hermes", "JSC"] flavor: ["Debug", "Release"] - test_buck diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index 86d3646ba34ce8..c7d5c448d5bd29 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -11,92 +11,57 @@ plugins { } /** - * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets - * and bundleReleaseJsAndAssets). - * These basically call `react-native bundle` with the correct arguments during the Android build - * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the - * bundle directly from the development server. Below you can see all the possible configurations - * and their defaults. If you decide to add a configuration block, make sure to add it before the - * `apply from: "react.gradle"` line. - * - * project.ext.react = [ - * // the name of the generated asset file containing your JS bundle - * bundleAssetName: "index.android.bundle", - * - * // the entry file for bundle generation - * entryFile: "index.android.js", - * - * // whether to bundle JS and assets in debug mode - * bundleInDebug: false, - * - * // whether to bundle JS and assets in release mode - * bundleInRelease: true, - * - * // whether to bundle JS and assets in another build variant (if configured). - * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants - * // The configuration property is in the format 'bundleIn${productFlavor}${buildType}' - * // bundleInFreeDebug: true, - * // bundleInPaidRelease: true, - * // bundleInBeta: true, - * - * // the root of your project, i.e. where "package.json" lives - * root: "../../", - * - * // where to put the JS bundle asset in debug mode - * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", - * - * // where to put the JS bundle asset in release mode - * jsBundleDirRelease: "$buildDir/intermediates/assets/release", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in debug mode - * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in release mode - * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", - * - * // by default the gradle tasks are skipped if none of the JS files or assets change; this means - * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to - * // date; if you have any other folders that you want to ignore for performance reasons (gradle - * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ - * // for example, you might want to remove it from here. - * inputExcludes: ["android/**", "ios/**"], - * - * // Root dir for all JS files for the app. Defaults to `root` above. - * jsRootDir: "../..", - * - * // Enable Fabric at runtime. - * enableFabric: true, - * - * // Java package name to use for any codegen artifacts produced during build time. - * // Defaults to "com.facebook.fbreact.specs". - * codegenJavaPackageName: "com.facebook.fbreact.specs", - * ] + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. */ - react { + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '..' + root = file("../../") + // The folder where the react-native NPM package is. Default is ../node_modules/react-native + reactNativeDir = rootDir + // The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen + codegenDir = file("$rootDir/node_modules/react-native-codegen") + // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js cliFile = file("$rootDir/cli.js") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + debuggableVariants = ["hermesDebug", "jscDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + // + // The command to run when bundling. By default is 'bundle' + // bundleCommand = "ram-bundle" + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle bundleAssetName = "RNTesterApp.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' entryFile = file("../../js/RNTesterApp.android.js") - root = file("../../") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' hermesCommand = "$rootDir/ReactAndroid/hermes-engine/build/hermes/bin/hermesc" - debuggableVariants = ["hermesDebug", "jscDebug"] enableHermesOnlyInVariants = ["hermesDebug", "hermesRelease"] - - // Codegen Configs - reactNativeDir = rootDir - codegenDir = file("$rootDir/node_modules/react-native-codegen") } /** - * Set this to true to create three separate APKs instead of one: - * - A universal APK that works on all devices - * - An APK that only works on ARM devices - * - An APK that only works on x86 devices - * The advantage is the size of the APK is reduced by about 4MB. - * Upload all the APKs to the Play Store and people will download - * the correct one based on the CPU architecture of their device. + * Set this to true to create four separate APKs instead of one, + * one for each native architecture. This is useful if you don't + * use App Bundles (https://developer.android.com/guide/app-bundle/) + * and want to have separate APKs to upload to the Play Store. */ def enableSeparateBuildPerCPUArchitecture = true @@ -106,12 +71,11 @@ def enableSeparateBuildPerCPUArchitecture = true def enableProguardInReleaseBuilds = true /** - * Use the international variant of JavaScriptCore - * This variant includes the ICU i18n library to make APIs like `Date.toLocaleString` - * and `String.localeCompare` work when using with locales other than en-US. - * Note that this variant is about 6MiB larger per architecture than the default. + * The preferred build flavor of JavaScriptCore (JSC) + * For example, to use the international variant, you can use: + * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` */ -def useIntlJsc = false +def jscFlavor = 'org.webkit:android-jsc:+' /** * Architectures to build native code for. @@ -206,11 +170,7 @@ dependencies { debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") - if (useIntlJsc) { - jscImplementation 'org.webkit:android-jsc-intl:+' - } else { - jscImplementation 'org.webkit:android-jsc:+' - } + jscImplementation jscFlavor androidTestImplementation 'junit:junit:4.12' } diff --git a/scripts/set-rn-engine.js b/scripts/set-rn-engine.js deleted file mode 100755 index 52afa5b749dfe8..00000000000000 --- a/scripts/set-rn-engine.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -'use strict'; - -/** - * This script updates the engine used by React Native - */ -const {echo, exec, exit, sed} = require('shelljs'); -const yargs = require('yargs'); - -let argv = yargs.option('e', { - alias: 'engine', - describe: 'Choose an engine', - type: 'string', - choices: ['hermes', 'jsc'], -}).argv; - -const engine = argv.engine; - -if (!engine) { - echo('You must specify an engine using -e'); - exit(1); -} - -// Change the template build.gradle -sed( - '-i', - /enableHermes:.*/, - engine === 'jsc' ? 'enableHermes: false' : 'enableHermes: true', - 'template/android/app/build.gradle', -); - -// Validate the hermes flag has been changed properly -const hermes = - exec( - 'grep enableHermes: template/android/app/build.gradle | awk \'{split($0,a,"[:,]"); print a[2]}\'', - {silent: true}, - ).stdout.trim() === 'true'; - -if ((engine === 'jsc' && hermes) || (engine === 'hermes' && !hermes)) { - echo('Failed to update the engine in template/android/app/build.gradle'); - echo('Fix the issue and try again'); - exit(1); -} - -exit(0); diff --git a/template/android/app/build.gradle b/template/android/app/build.gradle index 1a56feaba4970a..3ba40f561020c5 100644 --- a/template/android/app/build.gradle +++ b/template/android/app/build.gradle @@ -4,123 +4,84 @@ apply plugin: "com.facebook.react" import com.android.build.OutputFile /** - * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets - * and bundleReleaseJsAndAssets). - * These basically call `react-native bundle` with the correct arguments during the Android build - * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the - * bundle directly from the development server. Below you can see all the possible configurations - * and their defaults. If you decide to add a configuration block, make sure to add it before the - * `apply from: "../../node_modules/react-native/react.gradle"` line. - * - * project.ext.react = [ - * // the name of the generated asset file containing your JS bundle - * bundleAssetName: "index.android.bundle", - * - * // the entry file for bundle generation. If none specified and - * // "index.android.js" exists, it will be used. Otherwise "index.js" is - * // default. Can be overridden with ENTRY_FILE environment variable. - * entryFile: "index.android.js", - * - * // https://reactnative.dev/docs/performance#enable-the-ram-format - * bundleCommand: "ram-bundle", - * - * // whether to bundle JS and assets in debug mode - * bundleInDebug: false, - * - * // whether to bundle JS and assets in release mode - * bundleInRelease: true, - * - * // whether to bundle JS and assets in another build variant (if configured). - * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants - * // The configuration property can be in the following formats - * // 'bundleIn${productFlavor}${buildType}' - * // 'bundleIn${buildType}' - * // bundleInFreeDebug: true, - * // bundleInPaidRelease: true, - * // bundleInBeta: true, - * - * // whether to disable dev mode in custom build variants (by default only disabled in release) - * // for example: to disable dev mode in the staging build type (if configured) - * devDisabledInStaging: true, - * // The configuration property can be in the following formats - * // 'devDisabledIn${productFlavor}${buildType}' - * // 'devDisabledIn${buildType}' - * - * // the root of your project, i.e. where "package.json" lives - * root: "../../", - * - * // where to put the JS bundle asset in debug mode - * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", - * - * // where to put the JS bundle asset in release mode - * jsBundleDirRelease: "$buildDir/intermediates/assets/release", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in debug mode - * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", - * - * // where to put drawable resources / React Native assets, e.g. the ones you use via - * // require('./image.png')), in release mode - * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", - * - * // by default the gradle tasks are skipped if none of the JS files or assets change; this means - * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to - * // date; if you have any other folders that you want to ignore for performance reasons (gradle - * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ - * // for example, you might want to remove it from here. - * inputExcludes: ["android/**", "ios/**"], - * - * // override which node gets called and with what additional arguments - * nodeExecutableAndArgs: ["node"], - * - * // supply additional arguments to the packager - * extraPackagerArgs: [] - * ] + * This is the configuration block to customize your React Native Android app. + * By default you don't need to apply any configuration, just uncomment the lines you need. */ - -project.ext.react = [ - enableHermes: true, // clean and rebuild if changing -] +react { + /* Folders */ + // The root of your project, i.e. where "package.json" lives. Default is '..' + // root = file("../") + // The folder where the react-native NPM package is. Default is ../node_modules/react-native + // reactNativeDir = file("../node-modules/react-native") + // The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen + // codegenDir = file("../node-modules/react-native-codegen") + // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js + // cliFile = file("../node_modules/react-native/cli.js") + + /* Variants */ + // The list of variants to that are debuggable. For those we're going to + // skip the bundling of the JS bundle and the assets. By default is just 'debug'. + // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. + // debuggableVariants = ["liteDebug", "prodDebug"] + + /* Bundling */ + // A list containing the node command and its flags. Default is just 'node'. + // nodeExecutableAndArgs = ["node"] + // + // The command to run when bundling. By default is 'bundle' + // bundleCommand = "ram-bundle" + // + // The path to the CLI configuration file. Default is empty. + // bundleConfig = file(../rn-cli.config.js) + // + // The name of the generated asset file containing your JS bundle + // bundleAssetName = "MyApplication.android.bundle" + // + // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' + // entryFile = file("../js/MyApplication.android.js") + // + // A list of extra flags to pass to the 'bundle' commands. + // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle + // extraPackagerArgs = [] + + /* Hermes Commands */ + // The hermes compiler command to run. By default it is 'hermesc' + // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" + // + // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" + // hermesFlags = ["-O", "-output-source-map"] +} /** - * Set this to true to create two separate APKs instead of one: - * - An APK that only works on ARM devices - * - An APK that only works on x86 devices - * The advantage is the size of the APK is reduced by about 4MB. - * Upload all the APKs to the Play Store and people will download - * the correct one based on the CPU architecture of their device. + * Set this to true to create four separate APKs instead of one, + * one for each native architecture. This is useful if you don't + * use App Bundles (https://developer.android.com/guide/app-bundle/) + * and want to have separate APKs to upload to the Play Store. */ def enableSeparateBuildPerCPUArchitecture = false /** - * Run Proguard to shrink the Java bytecode in release builds. + * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** - * The preferred build flavor of JavaScriptCore. + * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that - * give correct results when using with locales other than en-US. Note that + * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** - * Whether to enable the Hermes VM. - * - * This should be set on project.ext.react and that value will be read here. If it is not set - * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode - * and the benefits of using Hermes will therefore be sharply reduced. - */ -def enableHermes = project.ext.react.get("enableHermes", false); - -/** - * Architectures to build native code for. + * Private function to get the list of Native Architectures you want to build. + * This reads the value from reactNativeArchitectures in your gradle.properties + * file and works together with the --active-arch-only flag of react-native run-android. */ def reactNativeArchitectures() { def value = project.getProperties().get("reactNativeArchitectures") @@ -187,8 +148,6 @@ android { } dependencies { - implementation fileTree(dir: "libs", include: ["*.jar"]) - // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-native") @@ -200,7 +159,7 @@ dependencies { } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") - if (enableHermes) { + if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-engine") } else { implementation jscFlavor diff --git a/template/android/build.gradle b/template/android/build.gradle index c6c8e7351ba0eb..c9a672214815b5 100644 --- a/template/android/build.gradle +++ b/template/android/build.gradle @@ -17,8 +17,6 @@ buildscript { dependencies { classpath("com.android.tools.build:gradle:7.3.1") classpath("com.facebook.react:react-native-gradle-plugin") - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files } } diff --git a/template/android/gradle.properties b/template/android/gradle.properties index fa4feae5f19024..e4af465e8a1857 100644 --- a/template/android/gradle.properties +++ b/template/android/gradle.properties @@ -38,3 +38,7 @@ reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 # to write custom TurboModules/Fabric components OR use libraries that # are providing them. newArchEnabled=false + +# Use this property to enable or disable the Hermes JS engine. +# If set to false, you will be using JSC instead. +hermesEnabled=true From 76f70849578c664e9b14d96475e30e179edd7222 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 27 Oct 2022 20:47:44 -0700 Subject: [PATCH 061/169] Gate the Maven Central publishing to 0.x version. (#35109) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35109 This is just a safety check to make sure we don't accidentally publish a 1.x or a 1000.x version on Maven Central by mistake. Changelog: [Internal] [Changed] - Gate the Maven Central publishing to 0.x version. Reviewed By: mdvacca Differential Revision: D40767782 fbshipit-source-id: 58f2906c3b01bfd0fd388a300ba303b289633d4e --- scripts/publish-npm.js | 2 +- scripts/release-utils.js | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/publish-npm.js b/scripts/publish-npm.js index 2b4834e8de0361..25900e6bea89db 100755 --- a/scripts/publish-npm.js +++ b/scripts/publish-npm.js @@ -203,7 +203,7 @@ const isLatest = exitIfNotOnGit( // We first publish on Maven Central all the necessary artifacts. // NPM publishing is done just after. -publishAndroidArtifactsToMaven(nightlyBuild); +publishAndroidArtifactsToMaven(releaseVersion, nightlyBuild); const releaseBranch = `${major}.${minor}-stable`; diff --git a/scripts/release-utils.js b/scripts/release-utils.js index 57a091029f1aa2..0ade67ac98b3b3 100644 --- a/scripts/release-utils.js +++ b/scripts/release-utils.js @@ -69,7 +69,7 @@ function generateAndroidArtifacts(releaseVersion, tmpPublishingFolder) { }); } -function publishAndroidArtifactsToMaven(isNightly) { +function publishAndroidArtifactsToMaven(releaseVersion, isNightly) { // -------- Publish every artifact to Maven Central // The GPG key is base64 encoded on CircleCI let buff = Buffer.from(env.ORG_GRADLE_PROJECT_SIGNING_KEY_ENCODED, 'base64'); @@ -79,7 +79,9 @@ function publishAndroidArtifactsToMaven(isNightly) { exit(1); } - if (!isNightly) { + // We want to gate ourselves against accidentally publishing a 1.x or a 1000.x on + // maven central which will break the semver for our artifacts. + if (!isNightly && releaseVersion.startsWith('0.')) { // -------- For stable releases, we also need to close and release the staging repository. if (exec('./gradlew closeAndReleaseSonatypeStagingRepository').code) { echo( From 089684ee5604a6a2a15a4fc03fe63c73a5de9fd0 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Fri, 28 Oct 2022 02:50:49 -0700 Subject: [PATCH 062/169] Remove remaining TV_OS fragments (#35110) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35110 Changelog: [General][Fixed] Remove remaining TV_OS fragments Reviewed By: shwanton Differential Revision: D40775881 fbshipit-source-id: 122ff8737de35689ee0951b068997ee546c7019c --- ReactCommon/cxxreact/React-cxxreact.podspec | 2 +- ReactCommon/logger/React-logger.podspec | 2 +- ReactCommon/react/renderer/graphics/React-graphics.podspec | 2 +- .../rn-tester/NativeComponentExample/MyNativeView.podspec | 2 +- .../rn-tester/NativeModuleExample/ScreenshotManager.podspec | 2 +- .../RCTTest/FBSnapshotTestCase/FBSnapshotTestController.m | 3 --- packages/rn-tester/RCTTest/RCTTestRunner.m | 4 ---- packages/rn-tester/RCTTest/React-RCTTest.podspec | 2 +- third-party-podspecs/RCT-Folly.podspec | 2 +- third-party-podspecs/boost.podspec | 2 +- 10 files changed, 8 insertions(+), 15 deletions(-) diff --git a/ReactCommon/cxxreact/React-cxxreact.podspec b/ReactCommon/cxxreact/React-cxxreact.podspec index c4498e9d3f1f80..8888f85473345c 100644 --- a/ReactCommon/cxxreact/React-cxxreact.podspec +++ b/ReactCommon/cxxreact/React-cxxreact.podspec @@ -28,7 +28,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.license = package["license"] s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{cpp,h}" s.exclude_files = "SampleCxxModule.*" diff --git a/ReactCommon/logger/React-logger.podspec b/ReactCommon/logger/React-logger.podspec index 62b5148965a7b1..193f42e231576d 100644 --- a/ReactCommon/logger/React-logger.podspec +++ b/ReactCommon/logger/React-logger.podspec @@ -28,7 +28,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.license = package["license"] s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{cpp,h}" s.exclude_files = "SampleCxxModule.*" diff --git a/ReactCommon/react/renderer/graphics/React-graphics.podspec b/ReactCommon/react/renderer/graphics/React-graphics.podspec index 3f7ff0da5be7ba..8c297d76b43ecd 100644 --- a/ReactCommon/react/renderer/graphics/React-graphics.podspec +++ b/ReactCommon/react/renderer/graphics/React-graphics.podspec @@ -27,7 +27,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.license = package["license"] s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.source = source s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags s.source_files = "**/*.{m,mm,cpp,h}" diff --git a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec index 25defc713763ab..3368c3e47c0cc3 100644 --- a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec +++ b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec @@ -17,7 +17,7 @@ Pod::Spec.new do |s| s.description = "my-native-view" s.homepage = "https://github.com/sota000/my-native-view.git" s.license = "MIT" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.compiler_flags = boost_compiler_flags + ' -Wno-nullability-completeness' s.author = "Facebook, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/my-native-view.git", :tag => "#{s.version}" } diff --git a/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec b/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec index 49e75393a61af3..339f68e1d41249 100644 --- a/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec +++ b/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec @@ -14,7 +14,7 @@ Pod::Spec.new do |s| s.description = "ScreenshotManager" s.homepage = "https://github.com/facebook/react-native.git" s.license = "MIT" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.compiler_flags = '-Wno-nullability-completeness' s.author = "Facebook, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/react-native.git", :tag => "#{s.version}" } diff --git a/packages/rn-tester/RCTTest/FBSnapshotTestCase/FBSnapshotTestController.m b/packages/rn-tester/RCTTest/FBSnapshotTestCase/FBSnapshotTestController.m index 3aefe13faf7f2d..48d51fa52990a2 100644 --- a/packages/rn-tester/RCTTest/FBSnapshotTestCase/FBSnapshotTestController.m +++ b/packages/rn-tester/RCTTest/FBSnapshotTestCase/FBSnapshotTestController.m @@ -241,9 +241,6 @@ - (NSString *)_fileNameForSelector:(SEL)selector if ([[UIScreen mainScreen] scale] > 1.0) { fileName = [fileName stringByAppendingFormat:@"@%.fx", [[UIScreen mainScreen] scale]]; } -#if TARGET_OS_TV - fileName = [fileName stringByAppendingString:@"_tvOS"]; -#endif fileName = [fileName stringByAppendingPathExtension:@"png"]; return fileName; } diff --git a/packages/rn-tester/RCTTest/RCTTestRunner.m b/packages/rn-tester/RCTTest/RCTTestRunner.m index 7f95689af57f4d..d373afe1976428 100644 --- a/packages/rn-tester/RCTTest/RCTTestRunner.m +++ b/packages/rn-tester/RCTTest/RCTTestRunner.m @@ -196,11 +196,7 @@ - (void)runTest:(SEL)test RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:moduleName initialProperties:initialProps]; -#if TARGET_OS_TV - rootView.frame = CGRectMake(0, 0, 1920, 1080); // Standard screen size for tvOS -#else rootView.frame = CGRectMake(0, 0, 320, 2000); // Constant size for testing on multiple devices -#endif rootTag = rootView.reactTag; testModule.view = rootView; diff --git a/packages/rn-tester/RCTTest/React-RCTTest.podspec b/packages/rn-tester/RCTTest/React-RCTTest.podspec index f6836ca2fa1e2d..5f6d58f908ecef 100644 --- a/packages/rn-tester/RCTTest/React-RCTTest.podspec +++ b/packages/rn-tester/RCTTest/React-RCTTest.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.license = package["license"] s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4", :tvos => "12.4" } + s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source s.source_files = "**/*.{h,m,mm}" diff --git a/third-party-podspecs/RCT-Folly.podspec b/third-party-podspecs/RCT-Folly.podspec index 02e47ea2585660..ec097f63d102c0 100644 --- a/third-party-podspecs/RCT-Folly.podspec +++ b/third-party-podspecs/RCT-Folly.podspec @@ -152,5 +152,5 @@ Pod::Spec.new do |spec| # Folly has issues when compiled with iOS 10 set as deployment target # See https://github.com/facebook/folly/issues/1470 for details - spec.platforms = { :ios => "9.0", :tvos => "9.0" } + spec.platforms = { :ios => "9.0" } end diff --git a/third-party-podspecs/boost.podspec b/third-party-podspecs/boost.podspec index 2f1fcc4b5ef093..3d9331c95d1217 100644 --- a/third-party-podspecs/boost.podspec +++ b/third-party-podspecs/boost.podspec @@ -14,7 +14,7 @@ Pod::Spec.new do |spec| :sha256 => 'f0397ba6e982c4450f27bf32a2a83292aba035b827a5623a14636ea583318c41' } # Pinning to the same version as React.podspec. - spec.platforms = { :ios => '11.0', :tvos => '11.0' } + spec.platforms = { :ios => '11.0' } spec.requires_arc = false spec.module_name = 'boost' From 3dc7b37cf73fe471db9dc6e432733af2073f0148 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Fri, 28 Oct 2022 04:22:22 -0700 Subject: [PATCH 063/169] Sort parameters in DefaultNewArchitectureEntryPoint (#35115) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35115 When looking at the new entry point I've realized we have the dynamicLibraryName as first parameter. As this API is not released yet, let's move it as last. So users on Java can easily call DefaultNewArchitectureEntryPoint.load(true, true, true) while now they will have to call DefaultNewArchitectureEntryPoint.load("...", true, true, true) Users in Kotlin won't be affected by this. Changelog: [Internal] [Changed] - Sort parameters in DefaultNewArchitectureEntryPoint Reviewed By: cipolleschi Differential Revision: D40793370 fbshipit-source-id: 9dc1569d76a1479a738f8e0f41a4183d7c04538f --- .../react/defaults/DefaultNewArchitectureEntryPoint.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt index f3552517f75b63..28ee848dd75f1f 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt +++ b/ReactAndroid/src/main/java/com/facebook/react/defaults/DefaultNewArchitectureEntryPoint.kt @@ -25,10 +25,10 @@ object DefaultNewArchitectureEntryPoint { @JvmStatic @JvmOverloads fun load( - dynamicLibraryName: String = "appmodules", turboModulesEnabled: Boolean = true, fabricEnabled: Boolean = true, - concurrentReactEnabled: Boolean = true + concurrentReactEnabled: Boolean = true, + dynamicLibraryName: String = "appmodules", ) { ReactFeatureFlags.useTurboModules = turboModulesEnabled ReactFeatureFlags.enableFabricRenderer = fabricEnabled From 44e8462a036b8217344f56310719b13d4a551973 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Fri, 28 Oct 2022 07:17:19 -0700 Subject: [PATCH 064/169] Consume Hermes from Maven in release (#35116) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35116 This diff let release versions of React Native to consume the Hermes tarball from Maven. It is already setup to download proper debug/release version ## Changelog [iOS][Added] - Download Hermes from Maven while for -stables Reviewed By: cortinico Differential Revision: D40794707 fbshipit-source-id: b6fa44a272ca044e1c4057a08accecb2009ad312 --- sdks/hermes-engine/hermes-engine.podspec | 4 +++- sdks/hermes-engine/hermes-utils.rb | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sdks/hermes-engine/hermes-engine.podspec b/sdks/hermes-engine/hermes-engine.podspec index c78269f2a75a4e..810d8ab2a91267 100644 --- a/sdks/hermes-engine/hermes-engine.podspec +++ b/sdks/hermes-engine/hermes-engine.podspec @@ -46,7 +46,9 @@ elsif File.exists?(hermestag_file) && isInCI source[:git] = git source[:tag] = hermestag else - source[:http] = "https://github.com/facebook/react-native/releases/download/v#{version}/hermes-runtime-darwin-#{build_type.to_s}-v#{version}.tar.gz" + # Sample url from Maven: + # https://repo1.maven.org/maven2/com/facebook/react/react-native-artifacts/0.71.0/react-native-artifacts-0.71.0-hermes-ios-debug.tar.gz + source[:http] = "https://repo1.maven.org/maven2/com/facebook/react/react-native-artifacts/#{version}/react-native-artifacts-#{version}-hermes-ios-#{build_type.to_s}.tar.gz" end Pod::Spec.new do |spec| diff --git a/sdks/hermes-engine/hermes-utils.rb b/sdks/hermes-engine/hermes-utils.rb index f16c06231c42fb..08424960110533 100644 --- a/sdks/hermes-engine/hermes-utils.rb +++ b/sdks/hermes-engine/hermes-utils.rb @@ -15,7 +15,6 @@ # - version: the version of React Native that requires the Hermes tarball # Returns: the path to the downloaded Hermes tarball def download_nightly_hermes(react_native_path, version) - # TODO: convert hermes-ios to hermes-ios-debug params = "r=snapshots\&g=com.facebook.react\&a=react-native-artifacts\&c=hermes-ios-debug\&e=tar.gz\&v=#{version}-SNAPSHOT" tarball_url = "http://oss.sonatype.org/service/local/artifact/maven/redirect\?#{params}" From 8c69b6cf781bfdf85cbbd7333bc0a0745d61f411 Mon Sep 17 00:00:00 2001 From: Antoine Doubovetzky Date: Fri, 28 Oct 2022 07:21:15 -0700 Subject: [PATCH 065/169] Extract throwIfUnsupportedFunctionParamTypeAnnotationParserError function (#35057) Summary: This PR is a task from https://github.com/facebook/react-native/issues/34872: > Extract the UnsupportedFunctionParamTypeAnnotationParserError in its own throwing function (if it does not exists already) and reuse that function passing a proper type. Then, refactor the code using a dictionary and avoiding the three different ifs in both parsers. ## Changelog [Internal] [Changed] - Extract the UnsupportedFunctionParamTypeAnnotationParserError in its own throwing function in error-utils Pull Request resolved: https://github.com/facebook/react-native/pull/35057 Reviewed By: lunaleaps Differential Revision: D40721099 Pulled By: cipolleschi fbshipit-source-id: af5e4cd275d0049047d35660559b94a27e660e40 --- .../src/parsers/__tests__/error-utils-test.js | 19 ++++++++++++++ .../src/parsers/error-utils.js | 17 ++++++++++++ .../src/parsers/errors.js | 1 - .../src/parsers/flow/modules/index.js | 22 +++++----------- .../src/parsers/typescript/modules/index.js | 26 +++++++------------ 5 files changed, 53 insertions(+), 32 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js b/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js index 8248eeb2af3ae4..58c4081abdb1f6 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/error-utils-test.js @@ -22,6 +22,7 @@ const { throwIfMoreThanOneModuleInterfaceParserError, throwIfModuleTypeIsUnsupported, throwIfUntypedModule, + throwIfUnsupportedFunctionParamTypeAnnotationParserError, } = require('../error-utils'); const { UnsupportedModulePropertyParserError, @@ -34,6 +35,7 @@ const { UnsupportedFunctionReturnTypeAnnotationParserError, UntypedModuleRegistryCallParserError, MoreThanOneModuleInterfaceParserError, + UnsupportedFunctionParamTypeAnnotationParserError, } = require('../errors'); describe('throwIfModuleInterfaceIsMisnamed', () => { @@ -633,3 +635,20 @@ describe('throwIfMoreThanOneModuleInterfaceParserError', () => { }).toThrow(MoreThanOneModuleInterfaceParserError); }); }); + +describe('throwIfUnsupportedFunctionParamTypeAnnotationParserError', () => { + const nativeModuleName = 'moduleName'; + const languageParamTypeAnnotation = {type: 'VoidTypeAnnotation'}; + const paramName = 'paramName'; + it('throws an UnsupportedFunctionParamTypeAnnotationParserError', () => { + const paramTypeAnnotationType = 'VoidTypeAnnotation'; + expect(() => { + throwIfUnsupportedFunctionParamTypeAnnotationParserError( + nativeModuleName, + languageParamTypeAnnotation, + paramName, + paramTypeAnnotationType, + ); + }).toThrow(UnsupportedFunctionParamTypeAnnotationParserError); + }); +}); diff --git a/packages/react-native-codegen/src/parsers/error-utils.js b/packages/react-native-codegen/src/parsers/error-utils.js index 4bfd2042f6c687..2d53c82c9e6f55 100644 --- a/packages/react-native-codegen/src/parsers/error-utils.js +++ b/packages/react-native-codegen/src/parsers/error-utils.js @@ -10,6 +10,7 @@ 'use strict'; +import type {NativeModuleTypeAnnotation} from '../CodegenSchema'; import type {ParserType} from './errors'; const { @@ -24,6 +25,7 @@ const { UntypedModuleRegistryCallParserError, UnsupportedModulePropertyParserError, MoreThanOneModuleInterfaceParserError, + UnsupportedFunctionParamTypeAnnotationParserError, } = require('./errors.js'); function throwIfModuleInterfaceIsMisnamed( @@ -249,6 +251,20 @@ function throwIfMoreThanOneModuleInterfaceParserError( } } +function throwIfUnsupportedFunctionParamTypeAnnotationParserError( + nativeModuleName: string, + languageParamTypeAnnotation: $FlowFixMe, + paramName: string, + paramTypeAnnotationType: NativeModuleTypeAnnotation['type'], +) { + throw new UnsupportedFunctionParamTypeAnnotationParserError( + nativeModuleName, + languageParamTypeAnnotation, + paramName, + paramTypeAnnotationType, + ); +} + module.exports = { throwIfModuleInterfaceIsMisnamed, throwIfUnsupportedFunctionReturnTypeAnnotationParserError, @@ -261,4 +277,5 @@ module.exports = { throwIfUntypedModule, throwIfModuleTypeIsUnsupported, throwIfMoreThanOneModuleInterfaceParserError, + throwIfUnsupportedFunctionParamTypeAnnotationParserError, }; diff --git a/packages/react-native-codegen/src/parsers/errors.js b/packages/react-native-codegen/src/parsers/errors.js index eab2dd36324af0..363f224764e029 100644 --- a/packages/react-native-codegen/src/parsers/errors.js +++ b/packages/react-native-codegen/src/parsers/errors.js @@ -258,7 +258,6 @@ class UnsupportedFunctionParamTypeAnnotationParserError extends ParserError { flowParamTypeAnnotation: $FlowFixMe, paramName: string, invalidParamType: string, - language: ParserType, ) { super( nativeModuleName, diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 8cfd853d4fcbb2..041257f1aacf83 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -60,7 +60,6 @@ const { UnsupportedArrayElementTypeAnnotationParserError, UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, - UnsupportedFunctionParamTypeAnnotationParserError, UnsupportedEnumDeclarationParserError, UnsupportedUnionTypeAnnotationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, @@ -80,6 +79,7 @@ const { throwIfUntypedModule, throwIfModuleTypeIsUnsupported, throwIfMoreThanOneModuleInterfaceParserError, + throwIfUnsupportedFunctionParamTypeAnnotationParserError, } = require('../../error-utils'); const {FlowParser} = require('../parser.js'); @@ -436,23 +436,15 @@ function translateFunctionTypeAnnotation( ), ); - if (paramTypeAnnotation.type === 'VoidTypeAnnotation') { - throw new UnsupportedFunctionParamTypeAnnotationParserError( + if ( + paramTypeAnnotation.type === 'VoidTypeAnnotation' || + paramTypeAnnotation.type === 'PromiseTypeAnnotation' + ) { + return throwIfUnsupportedFunctionParamTypeAnnotationParserError( hasteModuleName, flowParam.typeAnnotation, paramName, - 'void', - language, - ); - } - - if (paramTypeAnnotation.type === 'PromiseTypeAnnotation') { - throw new UnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - flowParam.typeAnnotation, - paramName, - 'Promise', - language, + paramTypeAnnotation.type, ); } diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 9c6f6080faa54e..c66a01ff46927d 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -26,7 +26,10 @@ import type {ParserErrorCapturer, TypeDeclarationMap} from '../../utils'; import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; const {nullGuard} = require('../../parsers-utils'); -const {throwIfMoreThanOneModuleRegistryCalls} = require('../../error-utils'); +const { + throwIfMoreThanOneModuleRegistryCalls, + throwIfUnsupportedFunctionParamTypeAnnotationParserError, +} = require('../../error-utils'); const {visit} = require('../../utils'); const { resolveTypeAnnotation, @@ -59,7 +62,6 @@ const { UnsupportedArrayElementTypeAnnotationParserError, UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, - UnsupportedFunctionParamTypeAnnotationParserError, UnsupportedEnumDeclarationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, IncorrectModuleRegistryCallArgumentTypeParserError, @@ -450,23 +452,15 @@ function translateFunctionTypeAnnotation( ), ); - if (paramTypeAnnotation.type === 'VoidTypeAnnotation') { - throw new UnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - typeScriptParam.typeAnnotation, - paramName, - 'void', - language, - ); - } - - if (paramTypeAnnotation.type === 'PromiseTypeAnnotation') { - throw new UnsupportedFunctionParamTypeAnnotationParserError( + if ( + paramTypeAnnotation.type === 'VoidTypeAnnotation' || + paramTypeAnnotation.type === 'PromiseTypeAnnotation' + ) { + return throwIfUnsupportedFunctionParamTypeAnnotationParserError( hasteModuleName, typeScriptParam.typeAnnotation, paramName, - 'Promise', - language, + paramTypeAnnotation.type, ); } From d0f94e6c2d9f91ac8ffab5218ed95cac63df09e5 Mon Sep 17 00:00:00 2001 From: Marshall Roch Date: Fri, 28 Oct 2022 08:11:57 -0700 Subject: [PATCH 066/169] Upgrade to Flow 0.191.0 Summary: Changelog: [Internal] Reviewed By: SamChou19815 Differential Revision: D40768442 fbshipit-source-id: a8e4301d731a8be4ce21d19c6276795d1127bd6d --- .flowconfig | 2 +- .flowconfig.android | 2 +- package.json | 2 +- repo-config/package.json | 2 +- template/_flowconfig | 2 +- yarn.lock | 8 ++++---- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.flowconfig b/.flowconfig index 50a3f7adab9a29..31885ce0546457 100644 --- a/.flowconfig +++ b/.flowconfig @@ -74,4 +74,4 @@ untyped-import untyped-type-import [version] -^0.190.1 +^0.191.0 diff --git a/.flowconfig.android b/.flowconfig.android index fc7429f32705d4..fac572dc5e490a 100644 --- a/.flowconfig.android +++ b/.flowconfig.android @@ -74,4 +74,4 @@ untyped-import untyped-type-import [version] -^0.190.1 +^0.191.0 diff --git a/package.json b/package.json index 30ab12d3bb3146..10b7760081a9d1 100644 --- a/package.json +++ b/package.json @@ -143,7 +143,7 @@ "ws": "^6.2.2" }, "devDependencies": { - "flow-bin": "^0.190.1", + "flow-bin": "^0.191.0", "hermes-eslint": "0.8.0", "react": "18.2.0", "react-test-renderer": "^18.2.0" diff --git a/repo-config/package.json b/repo-config/package.json index 28f626ef24c37e..4966d6516ef6a1 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -36,7 +36,7 @@ "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-native": "^4.0.0", "eslint-plugin-relay": "^1.8.3", - "flow-bin": "^0.190.1", + "flow-bin": "^0.191.0", "inquirer": "^7.1.0", "jest": "^29.2.1", "jest-junit": "^10.0.0", diff --git a/template/_flowconfig b/template/_flowconfig index a932669a2e4261..b929e039dc850d 100644 --- a/template/_flowconfig +++ b/template/_flowconfig @@ -60,4 +60,4 @@ untyped-import untyped-type-import [version] -^0.190.1 +^0.191.0 diff --git a/yarn.lock b/yarn.lock index 705ad189d14877..1c950430ef90a6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4523,10 +4523,10 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.2.tgz#64bfed5cb68fe3ca78b3eb214ad97b63bedce561" integrity sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA== -flow-bin@^0.190.1: - version "0.190.1" - resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.190.1.tgz#59ccbc9aaa2515fe32acc66117a05e7ef6a11061" - integrity sha512-5c9/6eEkMTTfdNuK2WwssrKfsUXKMUXlZVJZnrlWiqJpDSVc70/Smwyi9sXict9k/oq0f+Mo5wVH0d7peBYREg== +flow-bin@^0.191.0: + version "0.191.0" + resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.191.0.tgz#9324c9498584b60575fd8d77a2897ee4f384443b" + integrity sha512-IhaDGoOtRDdGUJLjm7KQlHK8BAzOVJmpx+CIR6bCju4pF7zon2v7WNrds5706WZqDE3rD2c8cM4GdhDnIFYXtg== flow-parser@0.*, flow-parser@^0.185.0: version "0.185.0" From 7e8992705a2e5b1721dcb2ffe788342fa6a2f2d0 Mon Sep 17 00:00:00 2001 From: Tianyu Yao Date: Fri, 28 Oct 2022 11:53:51 -0700 Subject: [PATCH 067/169] Use pointer events for hover Summary: Changelog: [Category][Internal] - Uses the new experimental pointer events to enable mouse hover events during element inspection Reviewed By: rbalicki2 Differential Revision: D40705973 fbshipit-source-id: fd0fb4539866dfc13592cfca1a864c2796497dc6 --- Libraries/Inspector/DevtoolsOverlay.js | 81 ++++++++++++++++---------- 1 file changed, 51 insertions(+), 30 deletions(-) diff --git a/Libraries/Inspector/DevtoolsOverlay.js b/Libraries/Inspector/DevtoolsOverlay.js index f98400e93bf299..a4711672f6c5f6 100644 --- a/Libraries/Inspector/DevtoolsOverlay.js +++ b/Libraries/Inspector/DevtoolsOverlay.js @@ -12,6 +12,7 @@ import type {PressEvent} from '../Types/CoreEventTypes'; import type {HostRef} from './getInspectorDataForViewAtPoint'; import View from '../Components/View/View'; +import ReactNativeFeatureFlags from '../ReactNative/ReactNativeFeatureFlags'; import StyleSheet from '../StyleSheet/StyleSheet'; import Dimensions from '../Utilities/Dimensions'; import ElementBox from './ElementBox'; @@ -115,39 +116,33 @@ export default function DevtoolsOverlay({ }; }, []); - const findViewForTouchEvent = useCallback( - (e: PressEvent) => { + const findViewForLocation = useCallback( + (x: number, y: number) => { const agent = devToolsAgentRef.current; if (agent == null) { return; } - const {locationX, locationY} = e.nativeEvent.touches[0]; - getInspectorDataForViewAtPoint( - inspectedView, - locationX, - locationY, - viewData => { - const {touchedViewTag, closestInstance, frame} = viewData; - if (closestInstance != null || touchedViewTag != null) { - if (closestInstance != null) { - // Fabric - agent.selectNode(closestInstance); - } else { - agent.selectNode(findNodeHandle(touchedViewTag)); - } - setInspected({ - frame, - }); - return true; + getInspectorDataForViewAtPoint(inspectedView, x, y, viewData => { + const {touchedViewTag, closestInstance, frame} = viewData; + if (closestInstance != null || touchedViewTag != null) { + if (closestInstance != null) { + // Fabric + agent.selectNode(closestInstance); + } else { + agent.selectNode(findNodeHandle(touchedViewTag)); } - return false; - }, - ); + setInspected({ + frame, + }); + return true; + } + return false; + }); }, [inspectedView], ); - const onResponderRelease = useCallback(() => { + const stopInspecting = useCallback(() => { const agent = devToolsAgentRef.current; if (agent == null) { return; @@ -157,23 +152,49 @@ export default function DevtoolsOverlay({ setInspected(null); }, []); + const onPointerMove = useCallback( + e => { + findViewForLocation(e.nativeEvent.x, e.nativeEvent.y); + }, + [findViewForLocation], + ); + + const onResponderMove = useCallback( + e => { + findViewForLocation( + e.nativeEvent.touches[0].locationX, + e.nativeEvent.touches[0].locationY, + ); + }, + [findViewForLocation], + ); + const shouldSetResponser = useCallback( (e: PressEvent): boolean => { - findViewForTouchEvent(e); + onResponderMove(e); return true; }, - [findViewForTouchEvent], + [onResponderMove], ); let highlight = inspected ? : null; if (isInspecting) { + const events = ReactNativeFeatureFlags.shouldEmitW3CPointerEvents + ? { + onPointerMove, + onPointerDown: onPointerMove, + onPointerUp: stopInspecting, + } + : { + onStartShouldSetResponder: shouldSetResponser, + onResponderMove: onResponderMove, + onResponderRelease: stopInspecting, + }; return ( + style={[styles.inspector, {height: Dimensions.get('window').height}]} + {...events}> {highlight} ); From 281f7a752463bd86c7df9a5a696474e4dc17b92d Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Fri, 28 Oct 2022 12:10:27 -0700 Subject: [PATCH 068/169] Annotate React hooks on xplat Summary: Changelog: [Internal] Reviewed By: pieterv Differential Revision: D40699106 fbshipit-source-id: 236fcd1001e60f508f70a651ca2d0a602b50c19a --- Libraries/Animated/useAnimatedValue.js | 2 +- .../Compatibility/ManyPointersPropertiesExample.js | 2 +- .../PlatformTest/RNTesterPlatformTestResultView.js | 2 +- .../Experimental/PlatformTest/usePlatformTestHarness.js | 4 ++-- .../PointerEventLayoutChangeShouldFirePointerOver.js | 2 +- packages/rn-tester/js/examples/Share/ShareExample.js | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Libraries/Animated/useAnimatedValue.js b/Libraries/Animated/useAnimatedValue.js index 0ee02303b45cfe..0a430ed5c3c071 100644 --- a/Libraries/Animated/useAnimatedValue.js +++ b/Libraries/Animated/useAnimatedValue.js @@ -17,7 +17,7 @@ export default function useAnimatedValue( initialValue: number, config?: ?AnimatedValueConfig, ): Animated.Value { - const ref = useRef(null); + const ref = useRef(null); if (ref.current == null) { ref.current = new Animated.Value(initialValue, config); } diff --git a/packages/rn-tester/js/examples/Experimental/Compatibility/ManyPointersPropertiesExample.js b/packages/rn-tester/js/examples/Experimental/Compatibility/ManyPointersPropertiesExample.js index eddcda5f45dee2..f07df3a3a878e7 100644 --- a/packages/rn-tester/js/examples/Experimental/Compatibility/ManyPointersPropertiesExample.js +++ b/packages/rn-tester/js/examples/Experimental/Compatibility/ManyPointersPropertiesExample.js @@ -20,7 +20,7 @@ const styles = StyleSheet.create({ }); function ManyPointersPropertiesExample(): React.Node { - const [data, setData] = React.useState({}); + const [data, setData] = React.useState<{}>({}); const onPointerMove = (event: PointerEvent) => { const pointerId = event.nativeEvent.pointerId; setData({...data, [pointerId]: event.nativeEvent}); diff --git a/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js b/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js index 7a0b1d53eda466..f46aac110903b3 100644 --- a/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js +++ b/packages/rn-tester/js/examples/Experimental/PlatformTest/RNTesterPlatformTestResultView.js @@ -72,7 +72,7 @@ function FilterModalButton(props: FilterModalProps) { }, []); const onFilterFailStatus = useCallback( - value => { + (value: boolean) => { setFilterFail(value); }, [setFilterFail], diff --git a/packages/rn-tester/js/examples/Experimental/PlatformTest/usePlatformTestHarness.js b/packages/rn-tester/js/examples/Experimental/PlatformTest/usePlatformTestHarness.js index 8c55230414e9f4..b0cd68e06f17f5 100644 --- a/packages/rn-tester/js/examples/Experimental/PlatformTest/usePlatformTestHarness.js +++ b/packages/rn-tester/js/examples/Experimental/PlatformTest/usePlatformTestHarness.js @@ -40,7 +40,7 @@ function constructAsyncTestHook( ) => Array, ) { return (description: string, timeoutMs?: number = 10000) => { - const assertionsRef = useRef([]); + const assertionsRef = useRef>([]); const timeoutIDRef = useRef(null); @@ -148,7 +148,7 @@ export default function usePlatformTestHarness(): PlatformTestHarnessHookResult // we use a basic debouncing logic to minimize the number of re-renders // caused by adding test results const resultQueueRef = useRef>([]); - const schedulerTimeoutIdRef = useRef(null); + const schedulerTimeoutIdRef = useRef(null); const commitResults = useCallback(() => { const queuedResults = resultQueueRef.current; diff --git a/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventLayoutChangeShouldFirePointerOver.js b/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventLayoutChangeShouldFirePointerOver.js index d3ebdcdbf6d8f1..79caf0afcd27dc 100644 --- a/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventLayoutChangeShouldFirePointerOver.js +++ b/packages/rn-tester/js/examples/Experimental/W3CPointerEventPlatformTests/PointerEventLayoutChangeShouldFirePointerOver.js @@ -53,7 +53,7 @@ function PointerEventLayoutShouldFirePointerOverTestCase( const [showBlue, setShowBlue] = useState(false); - const eventListRef = useRef([]); + const eventListRef = useRef>([]); const checkEventSequence = useCallback(() => { testMouseOver.step(({assert_equals}) => { diff --git a/packages/rn-tester/js/examples/Share/ShareExample.js b/packages/rn-tester/js/examples/Share/ShareExample.js index 77963337b28ff1..3b441201fe020e 100644 --- a/packages/rn-tester/js/examples/Share/ShareExample.js +++ b/packages/rn-tester/js/examples/Share/ShareExample.js @@ -79,7 +79,7 @@ const ShareMessageWithTitle = () => { }; const SharedAction = () => { - const [shared, setShared] = React.useState(); + const [shared, setShared] = React.useState(); const sharedAction = async () => { try { From cd25fb324018ed97a42e1d7ec8d923c09eef4f63 Mon Sep 17 00:00:00 2001 From: Lorenzo Sciandra Date: Fri, 28 Oct 2022 13:01:48 -0700 Subject: [PATCH 069/169] chore(deps): add wanted dependencies to remove yarn warnings (#35122) Summary: This is take 2 of this https://github.com/facebook/react-native/pull/35088, see this comment for why https://github.com/facebook/react-native/pull/35088#issuecomment-1295091902 I wanted to start working on a thing but this barrage of warnings was very annoying so ended up doing this instead: a very small PR to take care of some warnings during yarn install. It doesn't change anything (the versions are the ones already used all around the repo), just makes yarn happier. ## Changelog [General] [Fixed] - add wanted dependencies to remove yarn warnings Pull Request resolved: https://github.com/facebook/react-native/pull/35122 Test Plan: ### Before Screenshot 2022-10-26 at 10 53 32 ### After Screenshot 2022-10-26 at 10 52 19 Reviewed By: cortinico Differential Revision: D40804260 Pulled By: rshest fbshipit-source-id: 86af14c885d6d63a0d60bb85f204d17d8757f72a --- packages/hermes-inspector-msggen/package.json | 1 + packages/react-native-bots/package.json | 1 + packages/react-native-codegen/package.json | 1 + 3 files changed, 3 insertions(+) diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index cd9d385f72fa4a..68b2d0f949ce02 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -18,6 +18,7 @@ }, "devDependencies": { "@babel/cli": "^7.14.0", + "@babel/core": "^7.14.0", "@babel/preset-env": "^7.14.0", "@babel/preset-flow": "^7.14.0", "jest": "^29.2.1" diff --git a/packages/react-native-bots/package.json b/packages/react-native-bots/package.json index 563c64e5a5749f..a4a01050722809 100644 --- a/packages/react-native-bots/package.json +++ b/packages/react-native-bots/package.json @@ -5,6 +5,7 @@ "devDependencies": { "@seadub/danger-plugin-eslint": "^3.0.2", "danger": "^11.0.2", + "eslint": "^8.19.0", "lodash.includes": "^4.3.0", "minimatch": "^3.0.4" }, diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 99bb30580ae3bb..6a25c97458b303 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -33,6 +33,7 @@ "@babel/plugin-transform-async-to-generator": "^7.0.0", "@babel/plugin-transform-destructuring": "^7.0.0", "@babel/plugin-transform-flow-strip-types": "^7.0.0", + "@babel/preset-env": "^7.14.0", "chalk": "^4.0.0", "glob": "^7.1.1", "invariant": "^2.2.4", From 38e068abacbddeae13c874ecd629cb81fd12fef3 Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Fri, 28 Oct 2022 13:10:32 -0700 Subject: [PATCH 070/169] Bump CLI to 10.0.0-alpha.2 Summary: Quick update (requested by cortinico) ahead of release 0.71. Note that there was not a new release of `react-native-communiity/cli-platform-ios` in https://github.com/react-native-community/cli/commit/f6f23cca4b4c93030bb05e1fff68bd22ce13baba. Changelog: [General][Changed] - Bump CLI to 10.0.0-alpha.2 Reviewed By: robhogan, cortinico Differential Revision: D40806560 fbshipit-source-id: 5c852a204c3c2d272d0502a34221f24ce7613cb0 --- package.json | 4 ++-- yarn.lock | 28 ++++++++++++++-------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/package.json b/package.json index 10b7760081a9d1..406d52d52ef9ef 100644 --- a/package.json +++ b/package.json @@ -109,8 +109,8 @@ }, "dependencies": { "@jest/create-cache-key-function": "^29.2.1", - "@react-native-community/cli": "10.0.0-alpha.1", - "@react-native-community/cli-platform-android": "10.0.0-alpha.1", + "@react-native-community/cli": "10.0.0-alpha.2", + "@react-native-community/cli-platform-android": "10.0.0-alpha.2", "@react-native-community/cli-platform-ios": "10.0.0-alpha.1", "@react-native/assets": "1.0.0", "@react-native/normalize-color": "2.0.0", diff --git a/yarn.lock b/yarn.lock index 1c950430ef90a6..d7224029f83700 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2152,21 +2152,21 @@ sudo-prompt "^9.0.0" wcwidth "^1.0.1" -"@react-native-community/cli-hermes@^10.0.0-alpha.1": - version "10.0.0-alpha.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-hermes/-/cli-hermes-10.0.0-alpha.1.tgz#f452f4626203cb8542d163c10931f806091bc17f" - integrity sha512-FzxGylY0SLVsckms0aewm18TjSsGzR2zHRmYWLKtxZ4TAf7cA1Ta2QhO5zvCjWhiP0fO6b4nfXC9k+PoFfmWeA== +"@react-native-community/cli-hermes@^10.0.0-alpha.2": + version "10.0.0-alpha.2" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-hermes/-/cli-hermes-10.0.0-alpha.2.tgz#79d9cc0996d0689faa2f3b1a1cfac410ec2c4285" + integrity sha512-rTOZIsp5V5wB1EUFHXpuftuS/bSK9MxNzVJ4180+mp2H8FG+YbWF1T36rHKHsar88zEXdc3enXBindO+6aNhZA== dependencies: - "@react-native-community/cli-platform-android" "^10.0.0-alpha.1" + "@react-native-community/cli-platform-android" "^10.0.0-alpha.2" "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" hermes-profile-transformer "^0.0.6" ip "^1.1.5" -"@react-native-community/cli-platform-android@10.0.0-alpha.1", "@react-native-community/cli-platform-android@^10.0.0-alpha.1": - version "10.0.0-alpha.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-10.0.0-alpha.1.tgz#6972e206a02ff988e7a3da61cb53bdadd0f568aa" - integrity sha512-scuu+l7r3l7X0vq5TeqdnEG/cMbtq6dQPdCY9bONeEtata1oqCMbG2BwhYAtHzycAeuOGJiB/m/o6beD7+6Wzw== +"@react-native-community/cli-platform-android@10.0.0-alpha.2", "@react-native-community/cli-platform-android@^10.0.0-alpha.2": + version "10.0.0-alpha.2" + resolved "https://registry.yarnpkg.com/@react-native-community/cli-platform-android/-/cli-platform-android-10.0.0-alpha.2.tgz#645bfcbd2fbd66c716bedbdc530a20743d07721c" + integrity sha512-vbizdClBYY/rrB5RJwhQ5Q3d8bM0cMVSefsHgeheyo6hIvIOi8GLkNdCutGtAjWq6A0oxOy09Ue+ILpuU+DzpA== dependencies: "@react-native-community/cli-tools" "^10.0.0-alpha.0" chalk "^4.1.2" @@ -2240,16 +2240,16 @@ dependencies: joi "^17.2.1" -"@react-native-community/cli@10.0.0-alpha.1": - version "10.0.0-alpha.1" - resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-10.0.0-alpha.1.tgz#7a12588beaefda43d8d340b442def8593c651a6b" - integrity sha512-qvxZD5l1ozUxTKkONJAxBimrbWHkPNaBDaXDhNuccrmCkxzCl6Mll+khIPCWsTj5Z6FTxs05zv4wDwaV2umilQ== +"@react-native-community/cli@10.0.0-alpha.2": + version "10.0.0-alpha.2" + resolved "https://registry.yarnpkg.com/@react-native-community/cli/-/cli-10.0.0-alpha.2.tgz#1680d0b83d31864b44a1a116852185912a3b87af" + integrity sha512-k0iXCW9roa0AoLToiDy/pt0gpf/HEgQ/6FkSHgY2/rRB48uOnigHwKd+Coh9D7r9zhPYQiLDtlsI2kpVqhfU/A== dependencies: "@react-native-community/cli-clean" "^10.0.0-alpha.0" "@react-native-community/cli-config" "^10.0.0-alpha.0" "@react-native-community/cli-debugger-ui" "^10.0.0-alpha.0" "@react-native-community/cli-doctor" "^10.0.0-alpha.1" - "@react-native-community/cli-hermes" "^10.0.0-alpha.1" + "@react-native-community/cli-hermes" "^10.0.0-alpha.2" "@react-native-community/cli-plugin-metro" "^10.0.0-alpha.1" "@react-native-community/cli-server-api" "^10.0.0-alpha.0" "@react-native-community/cli-tools" "^10.0.0-alpha.0" From 662115077a9d7dab260ec93d89c7ca02145a47f8 Mon Sep 17 00:00:00 2001 From: George Zahariev Date: Fri, 28 Oct 2022 17:40:26 -0700 Subject: [PATCH 071/169] Fix some issues exposed when making function statics sealed Reviewed By: SamChou19815 Differential Revision: D40736389 fbshipit-source-id: a3e1c3f5723081bf76e2dbdb637b4deb7a54e180 --- Libraries/Image/resolveAssetSource.js | 6 ++---- Libraries/Utilities/differ/deepDiffer.js | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/Libraries/Image/resolveAssetSource.js b/Libraries/Image/resolveAssetSource.js index f15395386cd835..8848a0f18c10e4 100644 --- a/Libraries/Image/resolveAssetSource.js +++ b/Libraries/Image/resolveAssetSource.js @@ -105,8 +105,6 @@ function resolveAssetSource(source: any): ?ResolvedAssetSource { return resolver.defaultAsset(); } +resolveAssetSource.pickScale = pickScale; +resolveAssetSource.setCustomSourceTransformer = setCustomSourceTransformer; module.exports = resolveAssetSource; -// $FlowFixMe[prop-missing] -module.exports.pickScale = pickScale; -// $FlowFixMe[prop-missing] -module.exports.setCustomSourceTransformer = setCustomSourceTransformer; diff --git a/Libraries/Utilities/differ/deepDiffer.js b/Libraries/Utilities/differ/deepDiffer.js index e46fd6cad93c39..b0af0244a65487 100644 --- a/Libraries/Utilities/differ/deepDiffer.js +++ b/Libraries/Utilities/differ/deepDiffer.js @@ -97,6 +97,5 @@ const deepDiffer = function ( return false; }; +deepDiffer.unstable_setLogListeners = unstable_setLogListeners; module.exports = deepDiffer; -// $FlowFixMe[prop-missing] -module.exports.unstable_setLogListeners = unstable_setLogListeners; From ec5a4301a3c23af7d1c7f39d13e57be113c84f6a Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Sat, 29 Oct 2022 04:00:24 -0700 Subject: [PATCH 072/169] Separatedly enable TM/Fabric (#35117) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35117 This mimics some behavior we have in Android that allow uesers to turn on selectively TM and Fabric. Notice that if fabric is enabled, TM must be enabled as well, otherwise the app won't work ## Changelog [iOS][Added] - Added the possibility to selectively enable TM and Fabric with the new Architecture Reviewed By: cortinico Differential Revision: D40794328 fbshipit-source-id: b7fc7bb819d05566dcd335832cab224f80b23346 --- Libraries/AppDelegate/RCTAppDelegate.h | 15 ++++++++++++++- Libraries/AppDelegate/RCTAppDelegate.mm | 25 +++++++++++++++++++++++-- React/AppSetup/RCTAppSetupUtils.h | 8 ++++++-- React/AppSetup/RCTAppSetupUtils.mm | 18 ++++++++++-------- packages/rn-tester/Podfile.lock | 2 +- 5 files changed, 54 insertions(+), 14 deletions(-) diff --git a/Libraries/AppDelegate/RCTAppDelegate.h b/Libraries/AppDelegate/RCTAppDelegate.h index dbe3ee973e56db..b8d00bab93e7cd 100644 --- a/Libraries/AppDelegate/RCTAppDelegate.h +++ b/Libraries/AppDelegate/RCTAppDelegate.h @@ -43,6 +43,8 @@ * - (UIViewController *)createRootViewController; * New Architecture: * - (BOOL)concurrentRootEnabled + * - (BOOL)turboModuleEnabled; + * - (BOOL)fabricEnabled; * - (NSDictionary *)prepareInitialProps * - (Class)getModuleClassFromName:(const char *)name * - (std::shared_ptr)getTurboModule:(const std::string &)name @@ -106,12 +108,23 @@ @property (nonatomic, strong) RCTTurboModuleManager *turboModuleManager; @property (nonatomic, strong) RCTSurfacePresenterBridgeAdapter *bridgeAdapter; -/// This method controls whether the `concurrentRoot`feature of React18 is turned on or off. +/// This method controls whether the `concurrentRoot` feature of React18 is turned on or off. /// /// @see: https://reactjs.org/blog/2022/03/29/react-v18.html /// @note: This requires to be rendering on Fabric (i.e. on the New Architecture). /// @return: `true` if the `concurrentRoot` feature is enabled. Otherwise, it returns `false`. - (BOOL)concurrentRootEnabled; +/// This method controls whether the `turboModules` feature of the New Architecture is turned on or off. +/// +/// @note: This is required to be rendering on Fabric (i.e. on the New Architecture). +/// @return: `true` if the Turbo Native Module are enabled. Otherwise, it returns `false`. +- (BOOL)turboModuleEnabled; + +/// This method controls whether the App will use the Fabric renderer of the New Architecture or not. +/// +/// @return: `true` if the Fabric Renderer is enabled. Otherwise, it returns `false`. +- (BOOL)fabricEnabled; + @end #endif diff --git a/Libraries/AppDelegate/RCTAppDelegate.mm b/Libraries/AppDelegate/RCTAppDelegate.mm index d1c30754b1880a..39b29792245fa3 100644 --- a/Libraries/AppDelegate/RCTAppDelegate.mm +++ b/Libraries/AppDelegate/RCTAppDelegate.mm @@ -29,7 +29,12 @@ @implementation RCTAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - RCTAppSetupPrepareApp(application); + BOOL enableTM = NO; +#if RCT_NEW_ARCH_ENABLED + enableTM = self.turboModuleEnabled; +#endif + + RCTAppSetupPrepareApp(application, enableTM); if (!self.bridge) { self.bridge = [self createBridgeWithDelegate:self launchOptions:launchOptions]; @@ -94,7 +99,11 @@ - (UIView *)createRootViewWithBridge:(RCTBridge *)bridge moduleName:(NSString *)moduleName initProps:(NSDictionary *)initProps { - return RCTAppSetupDefaultRootView(bridge, moduleName, initProps); + BOOL enableFabric = NO; +#if RCT_NEW_ARCH_ENABLED + enableFabric = self.fabricEnabled; +#endif + return RCTAppSetupDefaultRootView(bridge, moduleName, initProps, enableFabric); } - (UIViewController *)createRootViewController @@ -138,6 +147,18 @@ - (Class)getModuleClassFromName:(const char *)name return RCTAppSetupDefaultModuleFromClass(moduleClass); } +#pragma mark - New Arch Enabled settings + +- (BOOL)turboModuleEnabled +{ + return YES; +} + +- (BOOL)fabricEnabled +{ + return YES; +} + #endif @end diff --git a/React/AppSetup/RCTAppSetupUtils.h b/React/AppSetup/RCTAppSetupUtils.h index 2611a569294126..06e12d7317c421 100644 --- a/React/AppSetup/RCTAppSetupUtils.h +++ b/React/AppSetup/RCTAppSetupUtils.h @@ -42,7 +42,11 @@ std::unique_ptr RCTAppSetupDefaultJsExecutor RCT_EXTERN_C_BEGIN -void RCTAppSetupPrepareApp(UIApplication *application); -UIView *RCTAppSetupDefaultRootView(RCTBridge *bridge, NSString *moduleName, NSDictionary *initialProperties); +void RCTAppSetupPrepareApp(UIApplication *application, BOOL turboModuleEnabled); +UIView *RCTAppSetupDefaultRootView( + RCTBridge *bridge, + NSString *moduleName, + NSDictionary *initialProperties, + BOOL fabricEnabled); RCT_EXTERN_C_END diff --git a/React/AppSetup/RCTAppSetupUtils.mm b/React/AppSetup/RCTAppSetupUtils.mm index cc9641ca38063a..4d58caebfe2e13 100644 --- a/React/AppSetup/RCTAppSetupUtils.mm +++ b/React/AppSetup/RCTAppSetupUtils.mm @@ -44,26 +44,28 @@ static void InitializeFlipper(UIApplication *application) } #endif -void RCTAppSetupPrepareApp(UIApplication *application) +void RCTAppSetupPrepareApp(UIApplication *application, BOOL turboModuleEnabled) { #ifdef FB_SONARKIT_ENABLED InitializeFlipper(application); #endif #if RCT_NEW_ARCH_ENABLED - RCTEnableTurboModule(YES); + RCTEnableTurboModule(turboModuleEnabled); #endif } -UIView *RCTAppSetupDefaultRootView(RCTBridge *bridge, NSString *moduleName, NSDictionary *initialProperties) +UIView * +RCTAppSetupDefaultRootView(RCTBridge *bridge, NSString *moduleName, NSDictionary *initialProperties, BOOL fabricEnabled) { #if RCT_NEW_ARCH_ENABLED - return [[RCTFabricSurfaceHostingProxyRootView alloc] initWithBridge:bridge - moduleName:moduleName - initialProperties:initialProperties]; -#else - return [[RCTRootView alloc] initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; + if (fabricEnabled) { + return [[RCTFabricSurfaceHostingProxyRootView alloc] initWithBridge:bridge + moduleName:moduleName + initialProperties:initialProperties]; + } #endif + return [[RCTRootView alloc] initWithBridge:bridge moduleName:moduleName initialProperties:initialProperties]; } #if RCT_NEW_ARCH_ENABLED diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index ae0be30952fbb1..fd7b6b9e62e3fa 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -945,7 +945,7 @@ SPEC CHECKSUMS: FlipperKit: cbdee19bdd4e7f05472a66ce290f1b729ba3cb86 fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 glog: 04b94705f318337d7ead9e6d17c019bd9b1f6b1b - hermes-engine: 05624e18294fd8279bb718e95d5bf2be311667ec + hermes-engine: cd15ebd246edff3a995ec666e898dd1cbdcaa10d libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c RCT-Folly: 0080d0a6ebf2577475bda044aa59e2ca1f909cda From cec9a34f6cd2a82bba76e15761da6b588bc3f574 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Sat, 29 Oct 2022 06:35:38 -0700 Subject: [PATCH 073/169] Sets the namespace via Gradle and not via AndroidManifest (#35094) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35094 Currently the build on console is firing this warning: ``` > Task :app:processDebugMainManifest package="com.androidtemplateproject" found in source AndroidManifest.xml: /tmp/AndroidTemplateProject/android/app/src/main/AndroidManifest.xml. Setting the namespace via a source AndroidManifest.xml's package attribute is deprecated. Please instead set the namespace (or testNamespace) in the module's build.gradle file, as described here: https://developer.android.com/studio/build/configure-app-module#set-namespace This migration can be done automatically using the AGP Upgrade Assistant, please refer to https://developer.android.com/studio/build/agp-upgrade-assistant for more information. ``` This diff fixes it so users won't see it anymore on 0.71 Changelog: [Android] [Fixed] - Sets the namespace via Gradle and not via AndroidManifest Reviewed By: cipolleschi Differential Revision: D40724654 fbshipit-source-id: 9b01748a22e9993b60e17bf25acbc68ba8e4eb77 --- packages/rn-tester/android/app/build.gradle | 1 + packages/rn-tester/android/app/src/main/AndroidManifest.xml | 3 +-- template/android/app/build.gradle | 1 + template/android/app/src/main/AndroidManifest.xml | 3 +-- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/rn-tester/android/app/build.gradle b/packages/rn-tester/android/app/build.gradle index c7d5c448d5bd29..4e3ca30c3855d1 100644 --- a/packages/rn-tester/android/app/build.gradle +++ b/packages/rn-tester/android/app/build.gradle @@ -88,6 +88,7 @@ def reactNativeArchitectures() { android { buildToolsVersion = "31.0.0" compileSdkVersion 31 + namespace "com.facebook.react.uiapp" // Used to override the NDK path/version on internal CI or by allowing // users to customize the NDK path/version from their root project (e.g. for M1 support) diff --git a/packages/rn-tester/android/app/src/main/AndroidManifest.xml b/packages/rn-tester/android/app/src/main/AndroidManifest.xml index 5bdcb1a686b3af..640e56c12a6f56 100644 --- a/packages/rn-tester/android/app/src/main/AndroidManifest.xml +++ b/packages/rn-tester/android/app/src/main/AndroidManifest.xml @@ -1,7 +1,6 @@ + xmlns:android="http://schemas.android.com/apk/res/android"> + From 87d65803abb80bbebe2cdce433dd12af75c5195d Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Sat, 29 Oct 2022 06:40:54 -0700 Subject: [PATCH 074/169] chore: Extract codegen case 'Float' into a single emitFloat function (#35124) Summary: ## Summary This PR extracts the content of the codegen case `'Float'` into a single `emitFloat` function inside the `parsers-primitives.js` file and uses it in both Flow and TypeScript parsers as requested on https://github.com/facebook/react-native/issues/34872. This also adds unit tests to the new `emitFloat` function. ## Changelog [Internal] [Changed] - Extract the content of the case 'Float' into a single emitFloat function Pull Request resolved: https://github.com/facebook/react-native/pull/35124 Test Plan: Run `yarn jest react-native-codegen` and ensure CI is green ![image](https://user-images.githubusercontent.com/11707729/198704932-202e2cd7-5b04-4009-b47e-b4999fee6c98.png) Reviewed By: rshest Differential Revision: D40828746 Pulled By: cipolleschi fbshipit-source-id: 9c7cecf7268f16aaef29065c1983ad9a4dd18dbe --- .../__tests__/parsers-primitives-test.js | 27 +++++++++++++++++++ .../src/parsers/flow/modules/index.js | 5 ++-- .../src/parsers/parsers-primitives.js | 10 +++++++ .../src/parsers/typescript/modules/index.js | 5 ++-- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js index 4b7317dac29b7e..b64c48f776a3ee 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js @@ -14,6 +14,7 @@ const { emitBoolean, emitDouble, + emitFloat, emitNumber, emitInt32, emitObject, @@ -424,4 +425,30 @@ describe('emitObject', () => { expect(result).toEqual(expected); }); }); + + describe('emitFloat', () => { + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitFloat(true); + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'FloatTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitFloat(false); + const expected = { + type: 'FloatTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); + }); }); diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 041257f1aacf83..90bbfeda7e3de2 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -43,6 +43,7 @@ const { const { emitBoolean, emitDouble, + emitFloat, emitFunction, emitNumber, emitInt32, @@ -242,9 +243,7 @@ function translateTypeAnnotation( return emitDouble(nullable); } case 'Float': { - return wrapNullable(nullable, { - type: 'FloatTypeAnnotation', - }); + return emitFloat(nullable); } case 'UnsafeObject': case 'Object': { diff --git a/packages/react-native-codegen/src/parsers/parsers-primitives.js b/packages/react-native-codegen/src/parsers/parsers-primitives.js index 6af9551e24abdd..1b450d044ee9b7 100644 --- a/packages/react-native-codegen/src/parsers/parsers-primitives.js +++ b/packages/react-native-codegen/src/parsers/parsers-primitives.js @@ -26,6 +26,7 @@ import type { NativeModulePromiseTypeAnnotation, StringTypeAnnotation, VoidTypeAnnotation, + NativeModuleFloatTypeAnnotation, } from '../CodegenSchema'; import type {ParserType} from './errors'; import type {TypeAliasResolutionStatus} from './utils'; @@ -171,9 +172,18 @@ function emitObject( }); } +function emitFloat( + nullable: boolean, +): Nullable { + return wrapNullable(nullable, { + type: 'FloatTypeAnnotation', + }); +} + module.exports = { emitBoolean, emitDouble, + emitFloat, emitFunction, emitInt32, emitNumber, diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index c66a01ff46927d..5971cc84661026 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -46,6 +46,7 @@ const { const { emitBoolean, emitDouble, + emitFloat, emitFunction, emitNumber, emitInt32, @@ -255,9 +256,7 @@ function translateTypeAnnotation( return emitDouble(nullable); } case 'Float': { - return wrapNullable(nullable, { - type: 'FloatTypeAnnotation', - }); + return emitFloat(nullable); } case 'UnsafeObject': case 'Object': { From 87c356d56c73c3289da3d5911288909720b11994 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Sun, 30 Oct 2022 05:48:57 -0700 Subject: [PATCH 075/169] Add Map / indexed object support for TypeScript parser (#35098) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35098 Changelog: [General][Fixed] [react-native-codegen] react-native-codegen : Add Map / indexed object support for TypeScript parser In flow we can expose Maps via the following syntax in TM specs ` +getMap: (arg: {[key: string]: ?number}) => {[key: string]: ?number}; ` In TypeScript writing the same spec: ` readonly getMap: (arg: { [key: string]: number | null; }) => { [key: string]: number | null; }; ` leads to an exception the TypeScript code-gen parser ```UnsupportedObjectPropertyTypeAnnotationParserError: Module NativeTurboModuleCxx: 'ObjectTypeAnnotation' cannot contain 'TSIndexSignature'. at react-native-github/packages/react-native-codegen/src/parsers/typescript/modules/index.js:309:23``` ``` This change fixes the TypeScript parser Reviewed By: cipolleschi Differential Revision: D40753368 fbshipit-source-id: 0eef8ecb63d1ed049fde1e75cc6f2ec627f1f232 --- .../modules/__test_fixtures__/fixtures.js | 2 + .../module-parser-snapshot-test.js.snap | 74 +++++++++++++++++++ .../src/parsers/flow/modules/index.js | 25 +++++-- .../src/parsers/parsers-commons.js | 30 +++++++- .../modules/__test_fixtures__/fixtures.js | 2 + ...script-module-parser-snapshot-test.js.snap | 74 +++++++++++++++++++ .../src/parsers/typescript/modules/index.js | 19 ++++- 7 files changed, 215 insertions(+), 11 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js index 50e4e18aa4c2c6..e8668947ce28c1 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/__test_fixtures__/fixtures.js @@ -644,6 +644,8 @@ export interface Spec extends TurboModule { +getCallback: () => () => void; +getMixed: (arg: mixed) => mixed; +getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; + +getMap: (arg: {[a: string]: ?number}) => {[b: string]: ?number}; + +getAnotherMap: (arg: {[string]: string}) => {[string]: string}; +getUnion: (chooseInt: ChooseInt, chooseFloat: ChooseFloat, chooseObject: ChooseObject, chooseString: ChooseString) => ChooseObject; } diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap index e73868dc872a3c..8f308ace82dca7 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap +++ b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/__snapshots__/module-parser-snapshot-test.js.snap @@ -122,6 +122,80 @@ exports[`RN Codegen Flow Parser can generate fixture CXX_ONLY_NATIVE_MODULE 1`] ] } }, + { + 'name': 'getMap', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'b', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + }, + 'params': [ + { + 'name': 'arg', + 'optional': false, + 'typeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'a', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + } + } + ] + } + }, + { + 'name': 'getAnotherMap', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'key', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + }, + 'params': [ + { + 'name': 'arg', + 'optional': false, + 'typeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'key', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + } + } + ] + } + }, { 'name': 'getUnion', 'optional': false, diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 90bbfeda7e3de2..761931268a68d6 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -62,7 +62,6 @@ const { UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, UnsupportedEnumDeclarationParserError, - UnsupportedUnionTypeAnnotationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, IncorrectModuleRegistryCallArgumentTypeParserError, } = require('../../errors.js'); @@ -84,6 +83,7 @@ const { } = require('../../error-utils'); const {FlowParser} = require('../parser.js'); +const {getKeyName} = require('../../parsers-commons'); const language = 'Flow'; const parser = new FlowParser(); @@ -287,11 +287,17 @@ function translateTypeAnnotation( const objectTypeAnnotation = { type: 'ObjectTypeAnnotation', // $FlowFixMe[missing-type-arg] - properties: (typeAnnotation.properties: Array<$FlowFixMe>) + properties: ([ + ...typeAnnotation.properties, + ...typeAnnotation.indexers, + ]: Array<$FlowFixMe>) .map>>( property => { return tryParse(() => { - if (property.type !== 'ObjectTypeProperty') { + if ( + property.type !== 'ObjectTypeProperty' && + property.type !== 'ObjectTypeIndexer' + ) { throw new UnsupportedObjectPropertyTypeAnnotationParserError( hasteModuleName, property, @@ -300,8 +306,15 @@ function translateTypeAnnotation( ); } - const {optional, key} = property; - + const {optional = false} = property; + const name = getKeyName(property, hasteModuleName, language); + if (property.type === 'ObjectTypeIndexer') { + return { + name, + optional, + typeAnnotation: emitObject(nullable), + }; + } const [propertyTypeAnnotation, isPropertyNullable] = unwrapNullable( translateTypeAnnotation( @@ -328,7 +341,7 @@ function translateTypeAnnotation( ); } else { return { - name: key.name, + name, optional, typeAnnotation: wrapNullable( isPropertyNullable, diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js index eda3b3ef2990d3..1528399b066608 100644 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ b/packages/react-native-codegen/src/parsers/parsers-commons.js @@ -24,7 +24,9 @@ const { UnsupportedUnionTypeAnnotationParserError, } = require('./errors'); import type {ParserType} from './errors'; - +const { + UnsupportedObjectPropertyTypeAnnotationParserError, +} = require('./errors'); const invariant = require('invariant'); function wrapModuleSchema( @@ -155,6 +157,31 @@ function emitUnionTypeAnnotation( }); } +function getKeyName( + propertyOrIndex: $FlowFixMe, + hasteModuleName: string, + language: ParserType, +): string { + switch (propertyOrIndex.type) { + case 'ObjectTypeProperty': + case 'TSPropertySignature': + return propertyOrIndex.key.name; + case 'ObjectTypeIndexer': + // flow index name is optional + return propertyOrIndex.id?.name ?? 'key'; + case 'TSIndexSignature': + // TypeScript index name is mandatory + return propertyOrIndex.parameters[0].name; + default: + throw new UnsupportedObjectPropertyTypeAnnotationParserError( + hasteModuleName, + propertyOrIndex, + propertyOrIndex.type, + language, + ); + } +} + module.exports = { wrapModuleSchema, unwrapNullable, @@ -162,4 +189,5 @@ module.exports = { assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, emitUnionTypeAnnotation, + getKeyName, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js index 02a2ae68b98a14..83483075d5ba49 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__test_fixtures__/fixtures.js @@ -661,6 +661,8 @@ export interface Spec extends TurboModule { readonly getCallback: () => () => void; readonly getMixed: (arg: unknown) => unknown; readonly getEnums: (quality: Quality, resolution?: Resolution, floppy: Floppy, stringOptions: StringOptions) => string; + readonly getMap: (arg: {[a: string]: number | null;}) => {[b: string]: number | null;}; + readonly getAnotherMap: (arg: {[key: string]: string}) => {[key: string]: string}; readonly getUnion: (chooseInt: ChooseInt, chooseFloat: ChooseFloat, chooseObject: ChooseObject, chooseString: ChooseString) => ChooseObject; } diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap index 6b4ff88450528a..185a836a066752 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/__snapshots__/typescript-module-parser-snapshot-test.js.snap @@ -120,6 +120,80 @@ exports[`RN Codegen TypeScript Parser can generate fixture CXX_ONLY_NATIVE_MODUL ] } }, + { + 'name': 'getMap', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'b', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + }, + 'params': [ + { + 'name': 'arg', + 'optional': false, + 'typeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'a', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + } + } + ] + } + }, + { + 'name': 'getAnotherMap', + 'optional': false, + 'typeAnnotation': { + 'type': 'FunctionTypeAnnotation', + 'returnTypeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'key', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + }, + 'params': [ + { + 'name': 'arg', + 'optional': false, + 'typeAnnotation': { + 'type': 'ObjectTypeAnnotation', + 'properties': [ + { + 'name': 'key', + 'optional': false, + 'typeAnnotation': { + 'type': 'GenericObjectTypeAnnotation' + } + } + ] + } + } + ] + } + }, { 'name': 'getUnion', 'optional': false, diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 5971cc84661026..f080a5190a5d55 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -84,6 +84,7 @@ const { } = require('../../error-utils'); const {TypeScriptParser} = require('../parser'); +const {getKeyName} = require('../../parsers-commons'); const language = 'TypeScript'; const parser = new TypeScriptParser(); @@ -306,7 +307,10 @@ function translateTypeAnnotation( .map>>( property => { return tryParse(() => { - if (property.type !== 'TSPropertySignature') { + if ( + property.type !== 'TSPropertySignature' && + property.type !== 'TSIndexSignature' + ) { throw new UnsupportedObjectPropertyTypeAnnotationParserError( hasteModuleName, property, @@ -315,8 +319,15 @@ function translateTypeAnnotation( ); } - const {optional = false, key} = property; - + const {optional = false} = property; + const name = getKeyName(property, hasteModuleName, language); + if (property.type === 'TSIndexSignature') { + return { + name, + optional, + typeAnnotation: emitObject(nullable), + }; + } const [propertyTypeAnnotation, isPropertyNullable] = unwrapNullable( translateTypeAnnotation( @@ -343,7 +354,7 @@ function translateTypeAnnotation( ); } else { return { - name: key.name, + name, optional, typeAnnotation: wrapNullable( isPropertyNullable, From ad5e3f6b9ae870cbfcef2874511915c5dc309ce8 Mon Sep 17 00:00:00 2001 From: atp Date: Mon, 31 Oct 2022 02:32:58 -0700 Subject: [PATCH 076/169] Fix typo syncronization -> synchronization (#35132) Summary: Fix typo ## Changelog [General][Fixed] - Fixed typo syncronization -> synchronization [CATEGORY] [TYPE] - Message Pull Request resolved: https://github.com/facebook/react-native/pull/35132 Reviewed By: christophpurrer Differential Revision: D40832387 Pulled By: rshest fbshipit-source-id: 834ece525e4469c942e678e2a3d4ecf30be4f550 --- Libraries/Renderer/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Libraries/Renderer/README.md b/Libraries/Renderer/README.md index 0462f897e8d2ed..d7f278751a844a 100644 --- a/Libraries/Renderer/README.md +++ b/Libraries/Renderer/README.md @@ -1,7 +1,7 @@ # React & React Native Versions This page describes how React and React Native versions interact each other. -The version alignment between the two frameworks relies on two syncronization points: +The version alignment between the two frameworks relies on two synchronization points: 1. The versions in the `package.json` of the new app template. For example [for React Native 0.68.1](https://github.com/facebook/react-native/blob/0.68-stable/template/package.json#L12-L15) the versions are aligned as follows: From 84737e0069f820bdb4b210e979d5faa2ec85ed3e Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 31 Oct 2022 04:17:13 -0700 Subject: [PATCH 077/169] Remove unused #import import which breaks macOS (#35131) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35131 Changelog: [iOS][Fixed] - Remove unused #import import which breaks macOS Reviewed By: cortinico Differential Revision: D40797971 fbshipit-source-id: 29839913a642247576caba9fe34724129c2bd3ba --- React/Fabric/RCTSurfaceTouchHandler.mm | 1 - 1 file changed, 1 deletion(-) diff --git a/React/Fabric/RCTSurfaceTouchHandler.mm b/React/Fabric/RCTSurfaceTouchHandler.mm index 3f5a38ee0fa566..c6b7fd9dcaf8ff 100644 --- a/React/Fabric/RCTSurfaceTouchHandler.mm +++ b/React/Fabric/RCTSurfaceTouchHandler.mm @@ -10,7 +10,6 @@ #import #import #import -#import #import "RCTConversions.h" #import "RCTTouchableComponentViewProtocol.h" From f3d9f2ea233304870bd4ab67d9682af6eb0ae16f Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Mon, 31 Oct 2022 04:18:44 -0700 Subject: [PATCH 078/169] Map `accessibilityRole: grid` to `UIAccessibilityTraitNone` Summary: D38121921 (https://github.com/facebook/react-native/commit/5ddb9977e662a1b41dd7203605ca8480432fc06a) added a grid accessibilityRole to Flow typings and RNTester example shared with iOS. It it forwarded on Android, but doesn't have an equivalent UIAccessibilityTrait mapping.`RNTesterSnapshotTests/testScrollViewExample` reports an error: ``` Failure: RedBox errors: ( "Error setting property 'accessibilityRole' of RCTScrollView with tag #125: Invalid UIAccessibilityTraits 'grid'. should be one of: ( adjustable, ====================== 38 lines skipped ====================== ) (NSInternalInconsistencyException) Path: Line: 0 ``` This adds the grid mapping, which I think should fix this error. Changelog: [ios][Fixed] - Map `accessibilityRole: grid` to `UIAccessibilityTraitNone` Reviewed By: christophpurrer Differential Revision: D40848904 fbshipit-source-id: 80f72bcd4e4826cc0d535693117a6c1e5fbd1d7d --- React/Views/RCTViewManager.m | 1 + 1 file changed, 1 insertion(+) diff --git a/React/Views/RCTViewManager.m b/React/Views/RCTViewManager.m index a777d5f8271736..b034ff08ac244a 100644 --- a/React/Views/RCTViewManager.m +++ b/React/Views/RCTViewManager.m @@ -64,6 +64,7 @@ @implementation RCTConvert (UIAccessibilityTraits) @"timer" : @(UIAccessibilityTraitNone), @"toolbar" : @(UIAccessibilityTraitNone), @"list" : @(UIAccessibilityTraitNone), + @"grid" : @(UIAccessibilityTraitNone), }), UIAccessibilityTraitNone, unsignedLongLongValue) From e3e635ef84156a5283d378858f7c8deb44464fea Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Mon, 31 Oct 2022 04:47:35 -0700 Subject: [PATCH 079/169] feat: Add "option" to available role values (#35137) Summary: As pointed out by efoken on https://github.com/facebook/react-native/issues/34424#issuecomment-1283854395 we forgot we add the `option` value to the `role` prop, so this PR adds this missing value as requested on https://github.com/facebook/react-native/issues/34424. ## Changelog [General] [Added] - Add "option" to available role values Pull Request resolved: https://github.com/facebook/react-native/pull/35137 Test Plan: Ensure that CI is green as there isn't much to test in this case because we're just adding a value that maps to `undefined` Reviewed By: jacdebug Differential Revision: D40849497 Pulled By: NickGerleman fbshipit-source-id: 5e3e24c0ff05c361a7a8dc1ee1f20ba3fb6988ca --- Libraries/Components/View/ViewAccessibility.d.ts | 1 + Libraries/Components/View/ViewAccessibility.js | 1 + Libraries/Utilities/AcessibilityMapping.js | 2 ++ 3 files changed, 4 insertions(+) diff --git a/Libraries/Components/View/ViewAccessibility.d.ts b/Libraries/Components/View/ViewAccessibility.d.ts index 5fad1607d973cb..c68c758410c889 100644 --- a/Libraries/Components/View/ViewAccessibility.d.ts +++ b/Libraries/Components/View/ViewAccessibility.d.ts @@ -330,6 +330,7 @@ export type Role = | 'navigation' | 'none' | 'note' + | 'option' | 'presentation' | 'progressbar' | 'radio' diff --git a/Libraries/Components/View/ViewAccessibility.js b/Libraries/Components/View/ViewAccessibility.js index 729e5e0a32e5b8..c62be022b046e7 100644 --- a/Libraries/Components/View/ViewAccessibility.js +++ b/Libraries/Components/View/ViewAccessibility.js @@ -85,6 +85,7 @@ export type Role = | 'navigation' | 'none' | 'note' + | 'option' | 'presentation' | 'progressbar' | 'radio' diff --git a/Libraries/Utilities/AcessibilityMapping.js b/Libraries/Utilities/AcessibilityMapping.js index 8db68118821dd8..911f3381089fe9 100644 --- a/Libraries/Utilities/AcessibilityMapping.js +++ b/Libraries/Utilities/AcessibilityMapping.js @@ -92,6 +92,8 @@ export function getAccessibilityRoleFromRole(role: Role): ?AccessibilityRole { return 'none'; case 'note': return undefined; + case 'option': + return undefined; case 'presentation': return 'none'; case 'progressbar': From 76c7ccaa60c4e820757c5d8cd8ccc80a2cb5f4a0 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 31 Oct 2022 05:31:13 -0700 Subject: [PATCH 080/169] Enable ManagedObjectWrapper on react-native-macOS (#35146) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35146 This class is used by Fabric - but does not compile on macOS yet. Changelog: [iOS][Fixed] Make ManagedObjectWrapper compile on macOS Reviewed By: javache Differential Revision: D40839241 fbshipit-source-id: 73b93a9963db89af19529fbfd60a64f4e5aaf036 --- ReactCommon/react/utils/ManagedObjectWrapper.h | 2 +- ReactCommon/react/utils/ManagedObjectWrapper.mm | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ReactCommon/react/utils/ManagedObjectWrapper.h b/ReactCommon/react/utils/ManagedObjectWrapper.h index 727499abd6bd42..3af8b158eb663c 100644 --- a/ReactCommon/react/utils/ManagedObjectWrapper.h +++ b/ReactCommon/react/utils/ManagedObjectWrapper.h @@ -14,7 +14,7 @@ #endif #if defined(__OBJC__) && defined(__cplusplus) -#if TARGET_OS_MAC && TARGET_OS_IPHONE +#if TARGET_OS_MAC #include diff --git a/ReactCommon/react/utils/ManagedObjectWrapper.mm b/ReactCommon/react/utils/ManagedObjectWrapper.mm index 69bde90f422c5e..44e4241f48460c 100644 --- a/ReactCommon/react/utils/ManagedObjectWrapper.mm +++ b/ReactCommon/react/utils/ManagedObjectWrapper.mm @@ -7,8 +7,7 @@ #include "ManagedObjectWrapper.h" -#if defined(__OBJC__) && defined(__cplusplus) -#if TARGET_OS_MAC && TARGET_OS_IPHONE +#if TARGET_OS_MAC namespace facebook { namespace react { @@ -35,4 +34,3 @@ @implementation RCTInternalGenericWeakWrapper @end #endif -#endif From a2166b24f80b6e0634d8dbf0a9450809509084de Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 31 Oct 2022 12:31:00 -0700 Subject: [PATCH 081/169] bump codegen to v0.71.1 (#35154) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35154 This diff bumps the codegen to v0.71.1, preparing it for the branch cut. ## Changelog [General][Changed] - Bump codegen version Reviewed By: dmytrorykun Differential Revision: D40852498 fbshipit-source-id: ba1dc87f3726bc27cbd176f160c62a0bdc291433 --- packages/react-native-codegen/package.json | 2 +- repo-config/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 6a25c97458b303..db3efc860b3343 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -1,6 +1,6 @@ { "name": "react-native-codegen", - "version": "0.71.0", + "version": "0.71.1", "description": "⚛️ Code generation tools for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen", "repository": { diff --git a/repo-config/package.json b/repo-config/package.json index 4966d6516ef6a1..07dc70ae12cf11 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -46,7 +46,7 @@ "mkdirp": "^0.5.1", "prettier": "^2.4.1", "react": "18.2.0", - "react-native-codegen": "^0.71.0", + "react-native-codegen": "^0.71.1", "react-test-renderer": "18.2.0", "shelljs": "^0.8.5", "signedsource": "^1.0.0", From ab7b4d4cd89cf6a7cb76d2b6a60163919cc3c689 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 31 Oct 2022 12:31:00 -0700 Subject: [PATCH 082/169] Restore Filtering platform in codegen (#35028) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35028 **This Diff require a bump in the react-native-codegen (including this [commit](https://github.com/facebook/react-native/commit/7680bdeb4f96a8092393372a59c77a9d7b729cae)) to work** This diff sets up iOS and Android to pass their platform to the codegen so that we can have platform-specific specs. ## Changelog [General][Added] - Enable platform-specific Codegen Specs Reviewed By: cortinico Differential Revision: D40516395 fbshipit-source-id: 0624f0bfb93c90f78131a605a4847e780783bbaf --- .../com/facebook/react/tasks/GenerateCodegenSchemaTask.kt | 5 ++--- .../facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt | 6 +++--- scripts/codegen/generate-artifacts-executor.js | 3 +-- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt index b86b2e2b1299f7..d72bc0a379f214 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTask.kt @@ -63,7 +63,6 @@ abstract class GenerateCodegenSchemaTask : Exec() { } internal fun setupCommandLine() { - // TODO: restore the --platform android parameters as soon as we publish the codegen package. commandLine( windowsAwareCommandLine( *nodeExecutableAndArgs.get().toTypedArray(), @@ -72,8 +71,8 @@ abstract class GenerateCodegenSchemaTask : Exec() { .get() .asFile .absolutePath, - // "--platform", - // "android", + "--platform", + "android", generatedSchemaFile.get().asFile.absolutePath, jsRootDir.asFile.get().absolutePath, )) diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt index bf546613fabf9b..98e2b39795c1cb 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/tasks/GenerateCodegenSchemaTaskTest.kt @@ -144,13 +144,13 @@ class GenerateCodegenSchemaTaskTest { } task.setupCommandLine() - // TODO: restore the --platform android parameters as soon as we publish the codegen package. + assertEquals( listOf( "--verbose", File(codegenDir, "lib/cli/combine/combine-js-to-schema-cli.js").toString(), - // "--platform", - // "android", + "--platform", + "android", File(outputDir, "schema.json").toString(), jsRootDir.toString(), ), diff --git a/scripts/codegen/generate-artifacts-executor.js b/scripts/codegen/generate-artifacts-executor.js index d51bceb8c811fe..68a47b6fab5bf9 100644 --- a/scripts/codegen/generate-artifacts-executor.js +++ b/scripts/codegen/generate-artifacts-executor.js @@ -311,7 +311,6 @@ function generateSchema(tmpDir, library, node, codegenCliPath) { console.log(`\n\n[Codegen] >>>>> Processing ${library.config.name}`); // Generate one schema for the entire library... - // TODO: restore the `--platform ios` parameters as soon as we publish the codegen package. executeNodeScript( node, `${path.join( @@ -320,7 +319,7 @@ function generateSchema(tmpDir, library, node, codegenCliPath) { 'cli', 'combine', 'combine-js-to-schema-cli.js', - )} ${pathToSchema} ${pathToJavaScriptSources}`, + )} --platform ios ${pathToSchema} ${pathToJavaScriptSources}`, ); console.log(`[Codegen] Generated schema: ${pathToSchema}`); return pathToSchema; From ea55e3bf8d6c419023baf63a6b4feb117ae5c24a Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Mon, 31 Oct 2022 13:56:27 -0700 Subject: [PATCH 083/169] chore: Unify codegen Flow and TS default case from translateTypeAnnotation (#35086) Summary: This PR unifies the Flow and TS `default:` case from codegen `translateTypeAnnotation` function into a single function called `translateDefault` inside `parser-commons.js` as requested on https://github.com/facebook/react-native/issues/34872. ## Changelog [Internal] [Changed] - Unify codegen Flow and TS default case from translateTypeAnnotation Pull Request resolved: https://github.com/facebook/react-native/pull/35086 Test Plan: Run `yarn jest react-native-codegen` and ensure CI is green ![image](https://user-images.githubusercontent.com/11707729/197931439-a0f0f7cd-eee7-4908-a7f1-856b40954178.png) Reviewed By: cortinico Differential Revision: D40801612 Pulled By: cipolleschi fbshipit-source-id: 612768d6fabe091ac428e7d8416c6da059fe1332 --- .../src/parsers/flow/components/schema.js | 2 +- .../src/parsers/flow/modules/index.js | 32 ++----------- .../src/parsers/flow/parser.js | 15 ++++++ .../src/parsers/parser.js | 18 ++++++++ .../src/parsers/parsers-commons.js | 46 +++++++++++++++++++ .../parsers/typescript/components/schema.js | 2 +- .../src/parsers/typescript/modules/index.js | 33 ++----------- .../src/parsers/typescript/parser.js | 19 ++++++++ .../react-native-codegen/src/parsers/utils.js | 2 +- 9 files changed, 109 insertions(+), 60 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/flow/components/schema.js b/packages/react-native-codegen/src/parsers/flow/components/schema.js index ed6223c3347b50..ab165031cd25fb 100644 --- a/packages/react-native-codegen/src/parsers/flow/components/schema.js +++ b/packages/react-native-codegen/src/parsers/flow/components/schema.js @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. * * @format - * @flow strict-local + * @flow strict */ 'use strict'; diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index 761931268a68d6..eb4c21a2dd382f 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -39,6 +39,7 @@ const { assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, emitUnionTypeAnnotation, + translateDefault, } = require('../../parsers-commons'); const { emitBoolean, @@ -59,9 +60,7 @@ const { const { UnnamedFunctionParamParserError, UnsupportedArrayElementTypeAnnotationParserError, - UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, - UnsupportedEnumDeclarationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, IncorrectModuleRegistryCallArgumentTypeParserError, } = require('../../errors.js'); @@ -250,34 +249,11 @@ function translateTypeAnnotation( return emitObject(nullable); } default: { - const maybeEumDeclaration = types[typeAnnotation.id.name]; - if ( - maybeEumDeclaration && - maybeEumDeclaration.type === 'EnumDeclaration' - ) { - const memberType = maybeEumDeclaration.body.type - .replace('EnumNumberBody', 'NumberTypeAnnotation') - .replace('EnumStringBody', 'StringTypeAnnotation'); - if ( - memberType === 'NumberTypeAnnotation' || - memberType === 'StringTypeAnnotation' - ) { - return wrapNullable(nullable, { - type: 'EnumDeclaration', - memberType: memberType, - }); - } else { - throw new UnsupportedEnumDeclarationParserError( - hasteModuleName, - typeAnnotation, - memberType, - language, - ); - } - } - throw new UnsupportedGenericParserError( + return translateDefault( hasteModuleName, typeAnnotation, + types, + nullable, parser, ); } diff --git a/packages/react-native-codegen/src/parsers/flow/parser.js b/packages/react-native-codegen/src/parsers/flow/parser.js index 47481c90378365..5315411ecf49a5 100644 --- a/packages/react-native-codegen/src/parsers/flow/parser.js +++ b/packages/react-native-codegen/src/parsers/flow/parser.js @@ -10,9 +10,24 @@ 'use strict'; +import type {ParserType} from '../errors'; import type {Parser} from '../parser'; class FlowParser implements Parser { + getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string { + return maybeEnumDeclaration.body.type + .replace('EnumNumberBody', 'NumberTypeAnnotation') + .replace('EnumStringBody', 'StringTypeAnnotation'); + } + + isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean { + return maybeEnumDeclaration.type === 'EnumDeclaration'; + } + + language(): ParserType { + return 'Flow'; + } + nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { return typeAnnotation.id.name; } diff --git a/packages/react-native-codegen/src/parsers/parser.js b/packages/react-native-codegen/src/parsers/parser.js index e98b67872b2343..eec4faea60b700 100644 --- a/packages/react-native-codegen/src/parsers/parser.js +++ b/packages/react-native-codegen/src/parsers/parser.js @@ -10,11 +10,29 @@ 'use strict'; +import type {ParserType} from './errors'; + /** * This is the main interface for Parsers of various languages. * It exposes all the methods that contain language-specific logic. */ export interface Parser { + /** + * Given a type declaration, it possibly returns the name of the Enum type. + * @parameter maybeEnumDeclaration: an object possibly containing an Enum declaration. + * @returns: the name of the Enum type. + */ + getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string; + /** + * Given a type declaration, it returns a boolean specifying if is an Enum declaration. + * @parameter maybeEnumDeclaration: an object possibly containing an Enum declaration. + * @returns: a boolean specifying if is an Enum declaration. + */ + isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean; + /** + * @returns: the Parser language. + */ + language(): ParserType; /** * Given a type annotation for a generic type, it returns the type name. * @parameter typeAnnotation: the annotation for a type in the AST. diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js index 1528399b066608..3730d81ce59f9e 100644 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ b/packages/react-native-codegen/src/parsers/parsers-commons.js @@ -28,6 +28,13 @@ const { UnsupportedObjectPropertyTypeAnnotationParserError, } = require('./errors'); const invariant = require('invariant'); +import type {TypeDeclarationMap} from './utils'; +const { + UnsupportedEnumDeclarationParserError, + UnsupportedGenericParserError, +} = require('./errors'); +import type {Parser} from './parser'; +import type {NativeModuleEnumDeclaration} from '../CodegenSchema'; function wrapModuleSchema( nativeModuleSchema: NativeModuleSchema, @@ -157,6 +164,44 @@ function emitUnionTypeAnnotation( }); } +function translateDefault( + hasteModuleName: string, + typeAnnotation: $FlowFixMe, + types: TypeDeclarationMap, + nullable: boolean, + parser: Parser, +): Nullable { + const maybeEnumDeclaration = + types[parser.nameForGenericTypeAnnotation(typeAnnotation)]; + + if (maybeEnumDeclaration && parser.isEnumDeclaration(maybeEnumDeclaration)) { + const memberType = parser.getMaybeEnumMemberType(maybeEnumDeclaration); + + if ( + memberType === 'NumberTypeAnnotation' || + memberType === 'StringTypeAnnotation' + ) { + return wrapNullable(nullable, { + type: 'EnumDeclaration', + memberType: memberType, + }); + } else { + throw new UnsupportedEnumDeclarationParserError( + hasteModuleName, + typeAnnotation, + memberType, + parser.language(), + ); + } + } + + throw new UnsupportedGenericParserError( + hasteModuleName, + typeAnnotation, + parser, + ); +} + function getKeyName( propertyOrIndex: $FlowFixMe, hasteModuleName: string, @@ -190,4 +235,5 @@ module.exports = { emitMixedTypeAnnotation, emitUnionTypeAnnotation, getKeyName, + translateDefault, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/components/schema.js b/packages/react-native-codegen/src/parsers/typescript/components/schema.js index ed6223c3347b50..ab165031cd25fb 100644 --- a/packages/react-native-codegen/src/parsers/typescript/components/schema.js +++ b/packages/react-native-codegen/src/parsers/typescript/components/schema.js @@ -5,7 +5,7 @@ * LICENSE file in the root directory of this source tree. * * @format - * @flow strict-local + * @flow strict */ 'use strict'; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index f080a5190a5d55..39621f98a514c1 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -42,6 +42,7 @@ const { assertGenericTypeAnnotationHasExactlyOneTypeParameter, emitMixedTypeAnnotation, emitUnionTypeAnnotation, + translateDefault, } = require('../../parsers-commons'); const { emitBoolean, @@ -63,7 +64,6 @@ const { UnsupportedArrayElementTypeAnnotationParserError, UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, - UnsupportedEnumDeclarationParserError, UnsupportedObjectPropertyTypeAnnotationParserError, IncorrectModuleRegistryCallArgumentTypeParserError, } = require('../../errors.js'); @@ -264,36 +264,11 @@ function translateTypeAnnotation( return emitObject(nullable); } default: { - const maybeEumDeclaration = types[typeAnnotation.typeName.name]; - if ( - maybeEumDeclaration && - maybeEumDeclaration.type === 'TSEnumDeclaration' - ) { - const memberType = maybeEumDeclaration.members[0].initializer - ? maybeEumDeclaration.members[0].initializer.type - .replace('NumericLiteral', 'NumberTypeAnnotation') - .replace('StringLiteral', 'StringTypeAnnotation') - : 'StringTypeAnnotation'; - if ( - memberType === 'NumberTypeAnnotation' || - memberType === 'StringTypeAnnotation' - ) { - return wrapNullable(nullable, { - type: 'EnumDeclaration', - memberType: memberType, - }); - } else { - throw new UnsupportedEnumDeclarationParserError( - hasteModuleName, - typeAnnotation, - memberType, - language, - ); - } - } - throw new UnsupportedGenericParserError( + return translateDefault( hasteModuleName, typeAnnotation, + types, + nullable, parser, ); } diff --git a/packages/react-native-codegen/src/parsers/typescript/parser.js b/packages/react-native-codegen/src/parsers/typescript/parser.js index 1c9db6d8d175e2..3bcf2cdb6415e6 100644 --- a/packages/react-native-codegen/src/parsers/typescript/parser.js +++ b/packages/react-native-codegen/src/parsers/typescript/parser.js @@ -10,9 +10,28 @@ 'use strict'; +import type {ParserType} from '../errors'; import type {Parser} from '../parser'; class TypeScriptParser implements Parser { + getMaybeEnumMemberType(maybeEnumDeclaration: $FlowFixMe): string { + if (maybeEnumDeclaration.members[0].initializer) { + return maybeEnumDeclaration.members[0].initializer.type + .replace('NumericLiteral', 'NumberTypeAnnotation') + .replace('StringLiteral', 'StringTypeAnnotation'); + } + + return 'StringTypeAnnotation'; + } + + isEnumDeclaration(maybeEnumDeclaration: $FlowFixMe): boolean { + return maybeEnumDeclaration.type === 'TSEnumDeclaration'; + } + + language(): ParserType { + return 'TypeScript'; + } + nameForGenericTypeAnnotation(typeAnnotation: $FlowFixMe): string { return typeAnnotation.typeName.name; } diff --git a/packages/react-native-codegen/src/parsers/utils.js b/packages/react-native-codegen/src/parsers/utils.js index a6fad22822e208..5cfeb7b740b0ec 100644 --- a/packages/react-native-codegen/src/parsers/utils.js +++ b/packages/react-native-codegen/src/parsers/utils.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @flow strict-local + * @flow strict * @format */ From 56d7a87e8432503e458c253ab3c86996f7c4c853 Mon Sep 17 00:00:00 2001 From: Antoine Doubovetzky Date: Mon, 31 Oct 2022 13:56:27 -0700 Subject: [PATCH 084/169] Fix assertGenericTypeAnnotationHasExactlyOneTypeParameter throwing wrong error (#35134) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: 1. I noticed there was a mistake in the [IncorrectlyParameterizedGenericParserError](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/errors.js#L159): ``` if ( genericTypeAnnotation.typeParameters.type === 'TypeParameterInstantiation' && genericTypeAnnotation.typeParameters.params.length !== 1 ) { ``` Here we should replace ` 'TypeParameterInstantiation'` with ` 'TSTypeParameterInstantiation'` when the language is `TypeScript`. The result is that we get a ["Couldn't create IncorrectlyParameterizedGenericParserError"](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/errors.js#L172) error instead of ["Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/parsers-commons.js#L88). I added a [test case](https://github.com/facebook/react-native/commit/2f161166c033cc9de67e04cd683554b05c6173f8) to cover this case: Capture d’écran 2022-10-30 à 13 55 56 2. Looking closely at where IncorrectlyParameterizedGenericParserError is used, I noticed that the logic was duplicated in [assertGenericTypeAnnotationHasExactlyOneTypeParameter](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/parsers-commons.js#L65). I believe that the logic should reside in `assertGenericTypeAnnotationHasExactlyOneTypeParameter` so I split the `IncorrectlyParameterizedGenericParserError` in 2 different errors. ## Changelog [Internal] [Changed] - Fix assertGenericTypeAnnotationHasExactlyOneTypeParameter throwing wrong error Pull Request resolved: https://github.com/facebook/react-native/pull/35134 Test Plan: I tested using Jest and Flow commands. Reviewed By: rshest Differential Revision: D40853200 Pulled By: cipolleschi fbshipit-source-id: 7040e57e0a2f511ba23fd4c54beae2ccff2fa89d --- .../parsers/__tests__/parsers-commons-test.js | 48 +++++++++++++++- .../src/parsers/errors.js | 55 +++++++++---------- .../__tests__/module-parser-e2e-test.js | 10 ++-- .../src/parsers/parsers-commons.js | 7 ++- .../typescript-module-parser-e2e-test.js | 10 ++-- 5 files changed, 84 insertions(+), 46 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js index 0aab57937641d9..7e0237fa924df1 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js @@ -167,7 +167,8 @@ describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { ); }); - it("throws an IncorrectlyParameterizedGenericParserError if typeParameters don't have 1 exactly parameter", () => { + it("throws an IncorrectlyParameterizedGenericParserError if typeParameters don't have 1 exactly parameter for Flow", () => { + const language: ParserType = 'Flow'; const typeAnnotationWithTwoParams = { typeParameters: { params: [1, 2], @@ -181,7 +182,7 @@ describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { assertGenericTypeAnnotationHasExactlyOneTypeParameter( moduleName, typeAnnotationWithTwoParams, - 'Flow', + language, ), ).toThrowErrorMatchingInlineSnapshot( `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, @@ -200,7 +201,48 @@ describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { assertGenericTypeAnnotationHasExactlyOneTypeParameter( moduleName, typeAnnotationWithNoParams, - 'Flow', + language, + ), + ).toThrowErrorMatchingInlineSnapshot( + `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, + ); + }); + + it("throws an IncorrectlyParameterizedGenericParserError if typeParameters don't have 1 exactly parameter for TS", () => { + const language: ParserType = 'TypeScript'; + const typeAnnotationWithTwoParams = { + typeParameters: { + params: [1, 2], + type: 'TSTypeParameterInstantiation', + }, + typeName: { + name: 'typeAnnotationName', + }, + }; + expect(() => + assertGenericTypeAnnotationHasExactlyOneTypeParameter( + moduleName, + typeAnnotationWithTwoParams, + language, + ), + ).toThrowErrorMatchingInlineSnapshot( + `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, + ); + + const typeAnnotationWithNoParams = { + typeParameters: { + params: [], + type: 'TSTypeParameterInstantiation', + }, + typeName: { + name: 'typeAnnotationName', + }, + }; + expect(() => + assertGenericTypeAnnotationHasExactlyOneTypeParameter( + moduleName, + typeAnnotationWithNoParams, + language, ), ).toThrowErrorMatchingInlineSnapshot( `"Module testModuleName: Generic 'typeAnnotationName' must have exactly one type parameter."`, diff --git a/packages/react-native-codegen/src/parsers/errors.js b/packages/react-native-codegen/src/parsers/errors.js index 363f224764e029..b736a5979b1468 100644 --- a/packages/react-native-codegen/src/parsers/errors.js +++ b/packages/react-native-codegen/src/parsers/errors.js @@ -12,7 +12,6 @@ import type {UnionTypeAnnotationMemberType} from '../CodegenSchema'; -const invariant = require('invariant'); import type {Parser} from './parser'; export type ParserType = 'Flow' | 'TypeScript'; @@ -131,11 +130,7 @@ class UnsupportedGenericParserError extends ParserError { } } -class IncorrectlyParameterizedGenericParserError extends ParserError { - +genericName: string; - +numTypeParameters: number; - - // $FlowFixMe[missing-local-annot] +class MissingTypeParameterGenericParserError extends ParserError { constructor( nativeModuleName: string, genericTypeAnnotation: $FlowFixMe, @@ -145,31 +140,30 @@ class IncorrectlyParameterizedGenericParserError extends ParserError { language === 'TypeScript' ? genericTypeAnnotation.typeName.name : genericTypeAnnotation.id.name; - if (genericTypeAnnotation.typeParameters == null) { - super( - nativeModuleName, - genericTypeAnnotation, - `Generic '${genericName}' must have type parameters.`, - ); - return; - } - if ( - genericTypeAnnotation.typeParameters.type === - 'TypeParameterInstantiation' && - genericTypeAnnotation.typeParameters.params.length !== 1 - ) { - super( - nativeModuleName, - genericTypeAnnotation.typeParameters, - `Generic '${genericName}' must have exactly one type parameter.`, - ); - return; - } + super( + nativeModuleName, + genericTypeAnnotation, + `Generic '${genericName}' must have type parameters.`, + ); + } +} + +class MoreThanOneTypeParameterGenericParserError extends ParserError { + constructor( + nativeModuleName: string, + genericTypeAnnotation: $FlowFixMe, + language: ParserType, + ) { + const genericName = + language === 'TypeScript' + ? genericTypeAnnotation.typeName.name + : genericTypeAnnotation.id.name; - invariant( - false, - "Couldn't create IncorrectlyParameterizedGenericParserError", + super( + nativeModuleName, + genericTypeAnnotation, + `Generic '${genericName}' must have exactly one type parameter.`, ); } } @@ -422,7 +416,8 @@ class IncorrectModuleRegistryCallArgumentTypeParserError extends ParserError { module.exports = { ParserError, - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, + MoreThanOneTypeParameterGenericParserError, MisnamedModuleInterfaceParserError, ModuleInterfaceNotFoundParserError, MoreThanOneModuleInterfaceParserError, diff --git a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js index f4eb8f4a8528b5..c1f959b7a884fc 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js @@ -21,7 +21,7 @@ const { UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, UnnamedFunctionParamParserError, - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, } = require('../../../errors'); const invariant = require('invariant'); @@ -212,7 +212,7 @@ describe('Flow Module Parser', () => { describe('Array Types', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { expect(() => parseParamType('arg', 'Array')).toThrow( - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, ); }); @@ -510,7 +510,7 @@ describe('Flow Module Parser', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { expect(() => parseParamTypeObjectLiteralProp('prop', 'Array'), - ).toThrow(IncorrectlyParameterizedGenericParserError); + ).toThrow(MissingTypeParameterGenericParserError); }); function parseArrayElementType( @@ -782,7 +782,7 @@ describe('Flow Module Parser', () => { describe('Array Types', () => { it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { expect(() => parseReturnType('Array')).toThrow( - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, ); }); @@ -1050,7 +1050,7 @@ describe('Flow Module Parser', () => { it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { expect(() => parseObjectLiteralReturnTypeProp('prop', 'Array'), - ).toThrow(IncorrectlyParameterizedGenericParserError); + ).toThrow(MissingTypeParameterGenericParserError); }); function parseArrayElementType( diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js index 3730d81ce59f9e..28ac2725e2645c 100644 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ b/packages/react-native-codegen/src/parsers/parsers-commons.js @@ -20,7 +20,8 @@ import type { NativeModuleUnionTypeAnnotation, } from '../CodegenSchema.js'; const { - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, + MoreThanOneTypeParameterGenericParserError, UnsupportedUnionTypeAnnotationParserError, } = require('./errors'); import type {ParserType} from './errors'; @@ -80,7 +81,7 @@ function assertGenericTypeAnnotationHasExactlyOneTypeParameter( language: ParserType, ) { if (typeAnnotation.typeParameters == null) { - throw new IncorrectlyParameterizedGenericParserError( + throw new MissingTypeParameterGenericParserError( moduleName, typeAnnotation, language, @@ -98,7 +99,7 @@ function assertGenericTypeAnnotationHasExactlyOneTypeParameter( ); if (typeAnnotation.typeParameters.params.length !== 1) { - throw new IncorrectlyParameterizedGenericParserError( + throw new MoreThanOneTypeParameterGenericParserError( moduleName, typeAnnotation, language, diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js index 1128a1bc837983..92858546206bed 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/__tests__/typescript-module-parser-e2e-test.js @@ -21,7 +21,7 @@ const { UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, UnnamedFunctionParamParserError, - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, } = require('../../../errors'); const invariant = require('invariant'); @@ -212,7 +212,7 @@ describe('TypeScript Module Parser', () => { describe('Array Types', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array'`, () => { expect(() => parseParamType('arg', 'Array')).toThrow( - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, ); }); @@ -510,7 +510,7 @@ describe('TypeScript Module Parser', () => { it(`should not parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { expect(() => parseParamTypeObjectLiteralProp('prop', 'Array'), - ).toThrow(IncorrectlyParameterizedGenericParserError); + ).toThrow(MissingTypeParameterGenericParserError); }); function parseArrayElementType( @@ -780,7 +780,7 @@ describe('TypeScript Module Parser', () => { describe('Array Types', () => { it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array'`, () => { expect(() => parseReturnType('Array')).toThrow( - IncorrectlyParameterizedGenericParserError, + MissingTypeParameterGenericParserError, ); }); @@ -1049,7 +1049,7 @@ describe('TypeScript Module Parser', () => { it(`should not parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array`, () => { expect(() => parseObjectLiteralReturnTypeProp('prop', 'Array'), - ).toThrow(IncorrectlyParameterizedGenericParserError); + ).toThrow(MissingTypeParameterGenericParserError); }); function parseArrayElementType( From 83e2126b57265d7d0d9129151782f5419622b121 Mon Sep 17 00:00:00 2001 From: Antoine Doubovetzky Date: Mon, 31 Oct 2022 13:56:27 -0700 Subject: [PATCH 085/169] Extract isModuleRegistryCall function in parsers/utils (#35139) Summary: This PR is a task from https://github.com/facebook/react-native/issues/34872: > Extract the function isModuleRegistryCall ([Flow](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/flow/utils.js#L175-L211) [TypeScript](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/typescript/utils.js#L167-L203)) into a single function in the parsers/utils.js file and replace its invocation with this new function. ## Changelog [Internal] [Changed] - Extract the function isModuleRegistryCall in parsers/utils Pull Request resolved: https://github.com/facebook/react-native/pull/35139 Test Plan: I tested using Jest and Flow commands. Reviewed By: rshest Differential Revision: D40850471 Pulled By: cipolleschi fbshipit-source-id: 34ec8ea4d7175e205315d60f200df093f1204b7b --- .../src/parsers/__tests__/utils-test.js | 146 ++++++++++++++++++ .../src/parsers/flow/index.js | 7 +- .../src/parsers/flow/modules/index.js | 8 +- .../src/parsers/flow/utils.js | 40 ----- .../src/parsers/typescript/index.js | 8 +- .../src/parsers/typescript/modules/index.js | 8 +- .../src/parsers/typescript/utils.js | 40 ----- .../react-native-codegen/src/parsers/utils.js | 40 +++++ 8 files changed, 200 insertions(+), 97 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/utils-test.js b/packages/react-native-codegen/src/parsers/__tests__/utils-test.js index d639380d9b6b4e..caf08e01f6032b 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/utils-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/utils-test.js @@ -17,6 +17,7 @@ const { verifyPlatforms, visit, buildSchemaFromConfigType, + isModuleRegistryCall, } = require('../utils.js'); const {ParserError} = require('../errors'); @@ -435,4 +436,149 @@ describe('buildSchemaFromConfigType', () => { }); }); }); + + describe('isModuleRegistryCall', () => { + describe('when node is not of CallExpression type', () => { + it('returns false', () => { + const node = { + type: 'NotCallExpression', + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when node is of CallExpressionType', () => { + describe('when callee type is not of MemberExpression type', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'NotMemberExpression', + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when callee type is of MemberExpression type', () => { + describe('when memberExpression has an object of type different than "Identifier"', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'NotIdentifier', + name: 'TurboModuleRegistry', + }, + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when memberExpression has an object of name different than "TurboModuleRegistry"', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'Identifier', + name: 'NotTurboModuleRegistry', + }, + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when memberExpression has an object of type "Identifier" and name "TurboModuleRegistry', () => { + describe('when memberExpression has a property of type different than "Identifier"', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'Identifier', + name: 'TurboModuleRegistry', + }, + property: { + type: 'NotIdentifier', + name: 'get', + }, + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when memberExpression has a property of name different than "get" or "getEnforcing', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'Identifier', + name: 'TurboModuleRegistry', + }, + property: { + type: 'Identifier', + name: 'NotGet', + }, + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when memberExpression has a property of type "Identifier" and of name "get" or "getEnforcing', () => { + describe('when memberExpression is computed', () => { + it('returns false', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'Identifier', + name: 'TurboModuleRegistry', + }, + property: { + type: 'Identifier', + name: 'get', + }, + computed: true, + }, + }; + expect(isModuleRegistryCall(node)).toBe(false); + }); + }); + + describe('when memberExpression is not computed', () => { + it('returns true', () => { + const node = { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + object: { + type: 'Identifier', + name: 'TurboModuleRegistry', + }, + property: { + type: 'Identifier', + name: 'get', + }, + computed: false, + }, + }; + expect(isModuleRegistryCall(node)).toBe(true); + }); + }); + }); + }); + }); + }); + }); }); diff --git a/packages/react-native-codegen/src/parsers/flow/index.js b/packages/react-native-codegen/src/parsers/flow/index.js index af7309229a2da7..2dfd5ff37ccd49 100644 --- a/packages/react-native-codegen/src/parsers/flow/index.js +++ b/packages/react-native-codegen/src/parsers/flow/index.js @@ -15,11 +15,14 @@ import type {SchemaType} from '../../CodegenSchema.js'; // $FlowFixMe[untyped-import] there's no flowtype flow-parser const flowParser = require('flow-parser'); const fs = require('fs'); -const {buildSchemaFromConfigType, getConfigType} = require('../utils'); +const { + buildSchemaFromConfigType, + getConfigType, + isModuleRegistryCall, +} = require('../utils'); const {buildComponentSchema} = require('./components'); const {wrapComponentSchema} = require('./components/schema'); const {buildModuleSchema} = require('./modules'); -const {isModuleRegistryCall} = require('./utils'); function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { return { diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index eb4c21a2dd382f..cd6e2f3e4401cb 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -27,12 +27,8 @@ import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; const {nullGuard} = require('../../parsers-utils'); const {throwIfMoreThanOneModuleRegistryCalls} = require('../../error-utils'); -const {visit} = require('../../utils'); -const { - resolveTypeAnnotation, - getTypes, - isModuleRegistryCall, -} = require('../utils.js'); +const {visit, isModuleRegistryCall} = require('../../utils'); +const {resolveTypeAnnotation, getTypes} = require('../utils.js'); const { unwrapNullable, wrapNullable, diff --git a/packages/react-native-codegen/src/parsers/flow/utils.js b/packages/react-native-codegen/src/parsers/flow/utils.js index f3d52d5d8070a1..86c663db5bd23e 100644 --- a/packages/react-native-codegen/src/parsers/flow/utils.js +++ b/packages/react-native-codegen/src/parsers/flow/utils.js @@ -116,48 +116,8 @@ function getValueFromTypes(value: ASTNode, types: TypeDeclarationMap): ASTNode { return value; } -// TODO(T71778680): Flow-type ASTNodes. -function isModuleRegistryCall(node: $FlowFixMe): boolean { - if (node.type !== 'CallExpression') { - return false; - } - - const callExpression = node; - - if (callExpression.callee.type !== 'MemberExpression') { - return false; - } - - const memberExpression = callExpression.callee; - if ( - !( - memberExpression.object.type === 'Identifier' && - memberExpression.object.name === 'TurboModuleRegistry' - ) - ) { - return false; - } - - if ( - !( - memberExpression.property.type === 'Identifier' && - (memberExpression.property.name === 'get' || - memberExpression.property.name === 'getEnforcing') - ) - ) { - return false; - } - - if (memberExpression.computed) { - return false; - } - - return true; -} - module.exports = { getValueFromTypes, resolveTypeAnnotation, getTypes, - isModuleRegistryCall, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/index.js b/packages/react-native-codegen/src/parsers/typescript/index.js index 2c6c1d4625e58d..426e4c8eef950a 100644 --- a/packages/react-native-codegen/src/parsers/typescript/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/index.js @@ -14,13 +14,15 @@ import type {SchemaType} from '../../CodegenSchema.js'; const babelParser = require('@babel/parser'); const fs = require('fs'); -const {buildSchemaFromConfigType, getConfigType} = require('../utils'); +const { + buildSchemaFromConfigType, + getConfigType, + isModuleRegistryCall, +} = require('../utils'); const {buildComponentSchema} = require('./components'); const {wrapComponentSchema} = require('./components/schema'); const {buildModuleSchema} = require('./modules'); -const {isModuleRegistryCall} = require('./utils'); - function Visitor(infoMap: {isComponent: boolean, isModule: boolean}) { return { CallExpression(node: $FlowFixMe) { diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 39621f98a514c1..bc5aae5f65ecba 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -30,12 +30,8 @@ const { throwIfMoreThanOneModuleRegistryCalls, throwIfUnsupportedFunctionParamTypeAnnotationParserError, } = require('../../error-utils'); -const {visit} = require('../../utils'); -const { - resolveTypeAnnotation, - getTypes, - isModuleRegistryCall, -} = require('../utils.js'); +const {visit, isModuleRegistryCall} = require('../../utils'); +const {resolveTypeAnnotation, getTypes} = require('../utils.js'); const { unwrapNullable, wrapNullable, diff --git a/packages/react-native-codegen/src/parsers/typescript/utils.js b/packages/react-native-codegen/src/parsers/typescript/utils.js index 8e700a3ed2e64e..73728847e12b8b 100644 --- a/packages/react-native-codegen/src/parsers/typescript/utils.js +++ b/packages/react-native-codegen/src/parsers/typescript/utils.js @@ -109,47 +109,7 @@ function resolveTypeAnnotation( }; } -// TODO(T108222691): Use flow-types for @babel/parser -function isModuleRegistryCall(node: $FlowFixMe): boolean { - if (node.type !== 'CallExpression') { - return false; - } - - const callExpression = node; - - if (callExpression.callee.type !== 'MemberExpression') { - return false; - } - - const memberExpression = callExpression.callee; - if ( - !( - memberExpression.object.type === 'Identifier' && - memberExpression.object.name === 'TurboModuleRegistry' - ) - ) { - return false; - } - - if ( - !( - memberExpression.property.type === 'Identifier' && - (memberExpression.property.name === 'get' || - memberExpression.property.name === 'getEnforcing') - ) - ) { - return false; - } - - if (memberExpression.computed) { - return false; - } - - return true; -} - module.exports = { resolveTypeAnnotation, getTypes, - isModuleRegistryCall, }; diff --git a/packages/react-native-codegen/src/parsers/utils.js b/packages/react-native-codegen/src/parsers/utils.js index 5cfeb7b740b0ec..ede91c81c2d729 100644 --- a/packages/react-native-codegen/src/parsers/utils.js +++ b/packages/react-native-codegen/src/parsers/utils.js @@ -215,6 +215,45 @@ function getConfigType( } } +// TODO(T71778680): Flow-type ASTNodes. +function isModuleRegistryCall(node: $FlowFixMe): boolean { + if (node.type !== 'CallExpression') { + return false; + } + + const callExpression = node; + + if (callExpression.callee.type !== 'MemberExpression') { + return false; + } + + const memberExpression = callExpression.callee; + if ( + !( + memberExpression.object.type === 'Identifier' && + memberExpression.object.name === 'TurboModuleRegistry' + ) + ) { + return false; + } + + if ( + !( + memberExpression.property.type === 'Identifier' && + (memberExpression.property.name === 'get' || + memberExpression.property.name === 'getEnforcing') + ) + ) { + return false; + } + + if (memberExpression.computed) { + return false; + } + + return true; +} + module.exports = { getConfigType, extractNativeModuleName, @@ -223,4 +262,5 @@ module.exports = { parseFile, visit, buildSchemaFromConfigType, + isModuleRegistryCall, }; From 5738fe642601237e16417105d6727f777e73aae3 Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Mon, 31 Oct 2022 14:39:19 -0700 Subject: [PATCH 086/169] refactor(AsyncStorage): move android files from react-native-github Summary: ## Changelog: [Android] [Removed] - Removed AsyncStorage module Reviewed By: lunaleaps Differential Revision: D40175995 fbshipit-source-id: b583579b8c2fa6c502f265ffe464b81672bd7da5 --- .../storage/AsyncLocalStorageUtil.java | 125 ----- .../storage/AsyncStorageErrorUtil.java | 38 -- .../modules/storage/AsyncStorageModule.java | 433 ------------------ .../com/facebook/react/modules/storage/BUCK | 25 - .../storage/ReactDatabaseSupplier.java | 163 ------- .../main/java/com/facebook/react/shell/BUCK | 1 - .../react/shell/MainReactPackage.java | 5 - .../test/java/com/facebook/react/modules/BUCK | 1 - .../storage/AsyncStorageModuleTest.java | 345 -------------- 9 files changed, 1136 deletions(-) delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java delete mode 100644 ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java deleted file mode 100644 index d3e8fb9b359134..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncLocalStorageUtil.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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.modules.storage; - -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.KEY_COLUMN; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.TABLE_CATALYST; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.VALUE_COLUMN; - -import android.content.ContentValues; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.text.TextUtils; -import androidx.annotation.Nullable; -import com.facebook.react.bridge.ReadableArray; -import java.util.Arrays; -import java.util.Iterator; -import org.json.JSONException; -import org.json.JSONObject; - -/** Helper for database operations. */ -public class AsyncLocalStorageUtil { - - /** - * Build the String required for an SQL select statement: WHERE key IN (?, ?, ..., ?) without - * 'WHERE' and with selectionCount '?' - */ - /* package */ static String buildKeySelection(int selectionCount) { - String[] list = new String[selectionCount]; - Arrays.fill(list, "?"); - return KEY_COLUMN + " IN (" + TextUtils.join(", ", list) + ")"; - } - - /** - * Build the String[] arguments needed for an SQL selection, i.e.: {a, b, c} to be used in the SQL - * select statement: WHERE key in (?, ?, ?) - */ - /* package */ static String[] buildKeySelectionArgs(ReadableArray keys, int start, int count) { - String[] selectionArgs = new String[count]; - for (int keyIndex = 0; keyIndex < count; keyIndex++) { - selectionArgs[keyIndex] = keys.getString(start + keyIndex); - } - return selectionArgs; - } - - /** Returns the value of the given key, or null if not found. */ - public static @Nullable String getItemImpl(SQLiteDatabase db, String key) { - String[] columns = {VALUE_COLUMN}; - String[] selectionArgs = {key}; - - Cursor cursor = - db.query(TABLE_CATALYST, columns, KEY_COLUMN + "=?", selectionArgs, null, null, null); - - try { - if (!cursor.moveToFirst()) { - return null; - } else { - return cursor.getString(0); - } - } finally { - cursor.close(); - } - } - - /** Sets the value for the key given, returns true if successful, false otherwise. */ - /* package */ static boolean setItemImpl(SQLiteDatabase db, String key, String value) { - ContentValues contentValues = new ContentValues(); - contentValues.put(KEY_COLUMN, key); - contentValues.put(VALUE_COLUMN, value); - - long inserted = - db.insertWithOnConflict( - TABLE_CATALYST, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE); - - return (-1 != inserted); - } - - /** - * Does the actual merge of the (key, value) pair with the value stored in the database. NB: This - * assumes that a database lock is already in effect! - * - * @return the errorCode of the operation - */ - /* package */ static boolean mergeImpl(SQLiteDatabase db, String key, String value) - throws JSONException { - String oldValue = getItemImpl(db, key); - String newValue; - - if (oldValue == null) { - newValue = value; - } else { - JSONObject oldJSON = new JSONObject(oldValue); - JSONObject newJSON = new JSONObject(value); - deepMergeInto(oldJSON, newJSON); - newValue = oldJSON.toString(); - } - - return setItemImpl(db, key, newValue); - } - - /** - * Merges two {@link JSONObject}s. The newJSON object will be merged with the oldJSON object by - * either overriding its values, or merging them (if the values of the same key in both objects - * are of type {@link JSONObject}). oldJSON will contain the result of this merge. - */ - private static void deepMergeInto(JSONObject oldJSON, JSONObject newJSON) throws JSONException { - Iterator keys = newJSON.keys(); - while (keys.hasNext()) { - String key = (String) keys.next(); - - JSONObject newJSONObject = newJSON.optJSONObject(key); - JSONObject oldJSONObject = oldJSON.optJSONObject(key); - if (newJSONObject != null && oldJSONObject != null) { - deepMergeInto(oldJSONObject, newJSONObject); - oldJSON.put(key, oldJSONObject); - } else { - oldJSON.put(key, newJSON.get(key)); - } - } - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java deleted file mode 100644 index eaa59f4c2d05cb..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageErrorUtil.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.modules.storage; - -import androidx.annotation.Nullable; -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.WritableMap; - -/** Helper class for database errors. */ -public class AsyncStorageErrorUtil { - - /** Create Error object to be passed back to the JS callback. */ - /* package */ static WritableMap getError(@Nullable String key, String errorMessage) { - WritableMap errorMap = Arguments.createMap(); - errorMap.putString("message", errorMessage); - if (key != null) { - errorMap.putString("key", key); - } - return errorMap; - } - - /* package */ static WritableMap getInvalidKeyError(@Nullable String key) { - return getError(key, "Invalid key"); - } - - /* package */ static WritableMap getInvalidValueError(@Nullable String key) { - return getError(key, "Invalid Value"); - } - - /* package */ static WritableMap getDBError(@Nullable String key) { - return getError(key, "Database Error"); - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java deleted file mode 100644 index 1b33b4b83d7ddd..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/AsyncStorageModule.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * 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.modules.storage; - -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.KEY_COLUMN; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.TABLE_CATALYST; -import static com.facebook.react.modules.storage.ReactDatabaseSupplier.VALUE_COLUMN; - -import android.database.Cursor; -import android.database.sqlite.SQLiteStatement; -import android.os.AsyncTask; -import com.facebook.common.logging.FLog; -import com.facebook.fbreact.specs.NativeAsyncSQLiteDBStorageSpec; -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.GuardedAsyncTask; -import com.facebook.react.bridge.ReactApplicationContext; -import com.facebook.react.bridge.ReadableArray; -import com.facebook.react.bridge.WritableArray; -import com.facebook.react.bridge.WritableMap; -import com.facebook.react.common.ReactConstants; -import com.facebook.react.common.annotations.VisibleForTesting; -import com.facebook.react.module.annotations.ReactModule; -import com.facebook.react.modules.common.ModuleDataCleaner; -import java.util.ArrayDeque; -import java.util.HashSet; -import java.util.concurrent.Executor; - -@ReactModule(name = AsyncStorageModule.NAME) -public final class AsyncStorageModule extends NativeAsyncSQLiteDBStorageSpec - implements ModuleDataCleaner.Cleanable { - - public static final String NAME = "AsyncSQLiteDBStorage"; - - // SQL variable number limit, defined by SQLITE_LIMIT_VARIABLE_NUMBER: - // https://raw.githubusercontent.com/android/platform_external_sqlite/master/dist/sqlite3.c - private static final int MAX_SQL_KEYS = 999; - - private ReactDatabaseSupplier mReactDatabaseSupplier; - private boolean mShuttingDown = false; - - // Adapted from - // https://android.googlesource.com/platform/frameworks/base.git/+/1488a3a19d4681a41fb45570c15e14d99db1cb66/core/java/android/os/AsyncTask.java#237 - private class SerialExecutor implements Executor { - private final ArrayDeque mTasks = new ArrayDeque(); - private Runnable mActive; - private final Executor executor; - - SerialExecutor(Executor executor) { - this.executor = executor; - } - - public synchronized void execute(final Runnable r) { - mTasks.offer( - new Runnable() { - public void run() { - try { - r.run(); - } finally { - scheduleNext(); - } - } - }); - if (mActive == null) { - scheduleNext(); - } - } - - synchronized void scheduleNext() { - if ((mActive = mTasks.poll()) != null) { - executor.execute(mActive); - } - } - } - - private final SerialExecutor executor; - - public AsyncStorageModule(ReactApplicationContext reactContext) { - this(reactContext, AsyncTask.THREAD_POOL_EXECUTOR); - } - - @VisibleForTesting - AsyncStorageModule(ReactApplicationContext reactContext, Executor executor) { - super(reactContext); - this.executor = new SerialExecutor(executor); - mReactDatabaseSupplier = ReactDatabaseSupplier.getInstance(reactContext); - } - - @Override - public String getName() { - return NAME; - } - - @Override - public void initialize() { - super.initialize(); - mShuttingDown = false; - } - - @Override - public void invalidate() { - mShuttingDown = true; - } - - @Override - public void clearSensitiveData() { - // Clear local storage. If fails, crash, since the app is potentially in a bad state and could - // cause a privacy violation. We're still not recovering from this well, but at least the error - // will be reported to the server. - mReactDatabaseSupplier.clearAndCloseDatabase(); - } - - /** - * Given an array of keys, this returns a map of (key, value) pairs for the keys found, and (key, - * null) for the keys that haven't been found. - */ - @Override - public void multiGet(final ReadableArray keys, final Callback callback) { - if (keys == null) { - callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null), null); - return; - } - - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null), null); - return; - } - - String[] columns = {KEY_COLUMN, VALUE_COLUMN}; - HashSet keysRemaining = new HashSet<>(); - WritableArray data = Arguments.createArray(); - for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { - int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); - Cursor cursor = - mReactDatabaseSupplier - .get() - .query( - TABLE_CATALYST, - columns, - AsyncLocalStorageUtil.buildKeySelection(keyCount), - AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount), - null, - null, - null); - keysRemaining.clear(); - try { - if (cursor.getCount() != keys.size()) { - // some keys have not been found - insert them with null into the final array - for (int keyIndex = keyStart; keyIndex < keyStart + keyCount; keyIndex++) { - keysRemaining.add(keys.getString(keyIndex)); - } - } - - if (cursor.moveToFirst()) { - do { - WritableArray row = Arguments.createArray(); - row.pushString(cursor.getString(0)); - row.pushString(cursor.getString(1)); - data.pushArray(row); - keysRemaining.remove(cursor.getString(0)); - } while (cursor.moveToNext()); - } - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()), null); - return; - } finally { - cursor.close(); - } - - for (String key : keysRemaining) { - WritableArray row = Arguments.createArray(); - row.pushString(key); - row.pushNull(); - data.pushArray(row); - } - keysRemaining.clear(); - } - - callback.invoke(null, data); - } - }.executeOnExecutor(executor); - } - - /** - * Inserts multiple (key, value) pairs. If one or more of the pairs cannot be inserted, this will - * return AsyncLocalStorageFailure, but all other pairs will have been inserted. The insertion - * will replace conflicting (key, value) pairs. - */ - @Override - public void multiSet(final ReadableArray keyValueArray, final Callback callback) { - if (keyValueArray.size() == 0) { - callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null)); - return; - } - - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null)); - return; - } - - String sql = "INSERT OR REPLACE INTO " + TABLE_CATALYST + " VALUES (?, ?);"; - SQLiteStatement statement = mReactDatabaseSupplier.get().compileStatement(sql); - WritableMap error = null; - try { - mReactDatabaseSupplier.get().beginTransaction(); - for (int idx = 0; idx < keyValueArray.size(); idx++) { - if (keyValueArray.getArray(idx).size() != 2) { - error = AsyncStorageErrorUtil.getInvalidValueError(null); - return; - } - if (keyValueArray.getArray(idx).getString(0) == null) { - error = AsyncStorageErrorUtil.getInvalidKeyError(null); - return; - } - if (keyValueArray.getArray(idx).getString(1) == null) { - error = AsyncStorageErrorUtil.getInvalidValueError(null); - return; - } - - statement.clearBindings(); - statement.bindString(1, keyValueArray.getArray(idx).getString(0)); - statement.bindString(2, keyValueArray.getArray(idx).getString(1)); - statement.execute(); - } - mReactDatabaseSupplier.get().setTransactionSuccessful(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } finally { - try { - mReactDatabaseSupplier.get().endTransaction(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - if (error == null) { - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } - } - } - if (error != null) { - callback.invoke(error); - } else { - callback.invoke(); - } - } - }.executeOnExecutor(executor); - } - - /** Removes all rows of the keys given. */ - @Override - public void multiRemove(final ReadableArray keys, final Callback callback) { - if (keys.size() == 0) { - callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null)); - return; - } - - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null)); - return; - } - - WritableMap error = null; - try { - mReactDatabaseSupplier.get().beginTransaction(); - for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { - int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); - mReactDatabaseSupplier - .get() - .delete( - TABLE_CATALYST, - AsyncLocalStorageUtil.buildKeySelection(keyCount), - AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount)); - } - mReactDatabaseSupplier.get().setTransactionSuccessful(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } finally { - try { - mReactDatabaseSupplier.get().endTransaction(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - if (error == null) { - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } - } - } - if (error != null) { - callback.invoke(error); - } else { - callback.invoke(); - } - } - }.executeOnExecutor(executor); - } - - /** - * Given an array of (key, value) pairs, this will merge the given values with the stored values - * of the given keys, if they exist. - */ - @Override - public void multiMerge(final ReadableArray keyValueArray, final Callback callback) { - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null)); - return; - } - WritableMap error = null; - try { - mReactDatabaseSupplier.get().beginTransaction(); - for (int idx = 0; idx < keyValueArray.size(); idx++) { - if (keyValueArray.getArray(idx).size() != 2) { - error = AsyncStorageErrorUtil.getInvalidValueError(null); - return; - } - - if (keyValueArray.getArray(idx).getString(0) == null) { - error = AsyncStorageErrorUtil.getInvalidKeyError(null); - return; - } - - if (keyValueArray.getArray(idx).getString(1) == null) { - error = AsyncStorageErrorUtil.getInvalidValueError(null); - return; - } - - if (!AsyncLocalStorageUtil.mergeImpl( - mReactDatabaseSupplier.get(), - keyValueArray.getArray(idx).getString(0), - keyValueArray.getArray(idx).getString(1))) { - error = AsyncStorageErrorUtil.getDBError(null); - return; - } - } - mReactDatabaseSupplier.get().setTransactionSuccessful(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } finally { - try { - mReactDatabaseSupplier.get().endTransaction(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - if (error == null) { - error = AsyncStorageErrorUtil.getError(null, e.getMessage()); - } - } - } - if (error != null) { - callback.invoke(error); - } else { - callback.invoke(); - } - } - }.executeOnExecutor(executor); - } - - /** Clears the database. */ - @Override - public void clear(final Callback callback) { - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!mReactDatabaseSupplier.ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null)); - return; - } - try { - mReactDatabaseSupplier.clear(); - callback.invoke(); - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage())); - } - } - }.executeOnExecutor(executor); - } - - /** Returns an array with all keys from the database. */ - @Override - public void getAllKeys(final Callback callback) { - new GuardedAsyncTask(getReactApplicationContext()) { - @Override - protected void doInBackgroundGuarded(Void... params) { - if (!ensureDatabase()) { - callback.invoke(AsyncStorageErrorUtil.getDBError(null), null); - return; - } - WritableArray data = Arguments.createArray(); - String[] columns = {KEY_COLUMN}; - Cursor cursor = - mReactDatabaseSupplier - .get() - .query(TABLE_CATALYST, columns, null, null, null, null, null); - try { - if (cursor.moveToFirst()) { - do { - data.pushString(cursor.getString(0)); - } while (cursor.moveToNext()); - } - } catch (Exception e) { - FLog.w(ReactConstants.TAG, e.getMessage(), e); - callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()), null); - return; - } finally { - cursor.close(); - } - callback.invoke(null, data); - } - }.executeOnExecutor(executor); - } - - /** Verify the database is open for reads and writes. */ - private boolean ensureDatabase() { - return !mShuttingDown && mReactDatabaseSupplier.ensureDatabase(); - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK deleted file mode 100644 index 7df1b3640bf9ce..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/BUCK +++ /dev/null @@ -1,25 +0,0 @@ -load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") - -rn_android_library( - name = "storage", - srcs = glob(["**/*.java"]), - autoglob = False, - labels = [ - "pfh:ReactNative_CommonInfrastructurePlaceholder", - ], - language = "JAVA", - visibility = [ - "PUBLIC", - ], - deps = [ - react_native_dep("third-party/android/androidx:annotation"), - react_native_dep("libraries/fbcore/src/main/java/com/facebook/common/logging:logging"), - react_native_dep("third-party/java/infer-annotations:infer-annotations"), - react_native_dep("third-party/java/jsr-305:jsr-305"), - react_native_target("java/com/facebook/react/bridge:bridge"), - react_native_target("java/com/facebook/react/common:common"), - react_native_target("java/com/facebook/react/module/annotations:annotations"), - react_native_target("java/com/facebook/react/modules/common:common"), - ], - exported_deps = [react_native_root_target(":FBReactNativeSpec")], -) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java b/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java deleted file mode 100644 index ccf9fb9fe2aa1f..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/storage/ReactDatabaseSupplier.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * 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.modules.storage; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteException; -import android.database.sqlite.SQLiteOpenHelper; -import androidx.annotation.Nullable; -import com.facebook.common.logging.FLog; -import com.facebook.react.common.ReactConstants; - -/** - * Database supplier of the database used by react native. This creates, opens and deletes the - * database as necessary. - */ -public class ReactDatabaseSupplier extends SQLiteOpenHelper { - - // VisibleForTesting - public static final String DATABASE_NAME = "RKStorage"; - - private static final int DATABASE_VERSION = 1; - private static final int SLEEP_TIME_MS = 30; - - static final String TABLE_CATALYST = "catalystLocalStorage"; - static final String KEY_COLUMN = "key"; - static final String VALUE_COLUMN = "value"; - - static final String VERSION_TABLE_CREATE = - "CREATE TABLE " - + TABLE_CATALYST - + " (" - + KEY_COLUMN - + " TEXT PRIMARY KEY, " - + VALUE_COLUMN - + " TEXT NOT NULL" - + ")"; - - private static @Nullable ReactDatabaseSupplier sReactDatabaseSupplierInstance; - - private Context mContext; - private @Nullable SQLiteDatabase mDb; - private long mMaximumDatabaseSize = 6L * 1024L * 1024L; // 6 MB in bytes - - private ReactDatabaseSupplier(Context context) { - super(context, DATABASE_NAME, null, DATABASE_VERSION); - mContext = context; - } - - public static ReactDatabaseSupplier getInstance(Context context) { - if (sReactDatabaseSupplierInstance == null) { - sReactDatabaseSupplierInstance = new ReactDatabaseSupplier(context.getApplicationContext()); - } - return sReactDatabaseSupplierInstance; - } - - @Override - public void onCreate(SQLiteDatabase db) { - db.execSQL(VERSION_TABLE_CREATE); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - if (oldVersion != newVersion) { - deleteDatabase(); - onCreate(db); - } - } - - /** Verify the database exists and is open. */ - /* package */ synchronized boolean ensureDatabase() { - if (mDb != null && mDb.isOpen()) { - return true; - } - // Sometimes retrieving the database fails. We do 2 retries: first without database deletion - // and then with deletion. - SQLiteException lastSQLiteException = null; - for (int tries = 0; tries < 2; tries++) { - try { - if (tries > 0) { - deleteDatabase(); - } - mDb = getWritableDatabase(); - break; - } catch (SQLiteException e) { - lastSQLiteException = e; - } - // Wait before retrying. - try { - Thread.sleep(SLEEP_TIME_MS); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - } - } - if (mDb == null) { - throw lastSQLiteException; - } - // This is a sane limit to protect the user from the app storing too much data in the database. - // This also protects the database from filling up the disk cache and becoming malformed - // (endTransaction() calls will throw an exception, not rollback, and leave the db malformed). - mDb.setMaximumSize(mMaximumDatabaseSize); - return true; - } - - /** Create and/or open the database. */ - public synchronized SQLiteDatabase get() { - ensureDatabase(); - return mDb; - } - - public synchronized void clearAndCloseDatabase() throws RuntimeException { - try { - clear(); - closeDatabase(); - FLog.d(ReactConstants.TAG, "Cleaned " + DATABASE_NAME); - } catch (Exception e) { - // Clearing the database has failed, delete it instead. - if (deleteDatabase()) { - FLog.d(ReactConstants.TAG, "Deleted Local Database " + DATABASE_NAME); - return; - } - // Everything failed, throw - throw new RuntimeException("Clearing and deleting database " + DATABASE_NAME + " failed"); - } - } - - /* package */ synchronized void clear() { - get().delete(TABLE_CATALYST, null, null); - } - - /** - * Sets the maximum size the database will grow to. The maximum size cannot be set below the - * current size. - */ - public synchronized void setMaximumSize(long size) { - mMaximumDatabaseSize = size; - if (mDb != null) { - mDb.setMaximumSize(mMaximumDatabaseSize); - } - } - - private synchronized boolean deleteDatabase() { - closeDatabase(); - return mContext.deleteDatabase(DATABASE_NAME); - } - - private synchronized void closeDatabase() { - if (mDb != null && mDb.isOpen()) { - mDb.close(); - mDb = null; - } - } - - // For testing purposes only! - public static void deleteInstance() { - sReactDatabaseSupplierInstance = null; - } -} diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK index c79b69687e0654..f6d575f9aff635 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK @@ -46,7 +46,6 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/permissions:permissions"), react_native_target("java/com/facebook/react/modules/share:share"), react_native_target("java/com/facebook/react/modules/statusbar:statusbar"), - react_native_target("java/com/facebook/react/modules/storage:storage"), react_native_target("java/com/facebook/react/modules/sound:sound"), react_native_target("java/com/facebook/react/modules/toast:toast"), react_native_target("java/com/facebook/react/modules/vibration:vibration"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index 6fc4a536e2b1f7..f845a46118cfd8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -33,7 +33,6 @@ import com.facebook.react.modules.share.ShareModule; import com.facebook.react.modules.sound.SoundManagerModule; import com.facebook.react.modules.statusbar.StatusBarModule; -import com.facebook.react.modules.storage.AsyncStorageModule; import com.facebook.react.modules.toast.ToastModule; import com.facebook.react.modules.vibration.VibrationModule; import com.facebook.react.modules.websocket.WebSocketModule; @@ -69,7 +68,6 @@ AppStateModule.class, BlobModule.class, FileReaderModule.class, - AsyncStorageModule.class, ClipboardModule.class, DialogModule.class, FrescoModule.class, @@ -111,8 +109,6 @@ public MainReactPackage(MainPackageConfig config) { return new BlobModule(context); case FileReaderModule.NAME: return new FileReaderModule(context); - case AsyncStorageModule.NAME: - return new AsyncStorageModule(context); case ClipboardModule.NAME: return new ClipboardModule(context); case DialogModule.NAME: @@ -193,7 +189,6 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { AppStateModule.class, BlobModule.class, FileReaderModule.class, - AsyncStorageModule.class, ClipboardModule.class, DialogModule.class, FrescoModule.class, diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK index 7ab27c360a9714..235079472f328d 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK @@ -37,7 +37,6 @@ rn_robolectric_test( react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/network:network"), react_native_target("java/com/facebook/react/modules/share:share"), - react_native_target("java/com/facebook/react/modules/storage:storage"), react_native_target("java/com/facebook/react/modules/systeminfo:systeminfo"), react_native_target("java/com/facebook/react/touch:touch"), react_native_target("java/com/facebook/react/uimanager:uimanager"), diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java b/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java deleted file mode 100644 index d4b2ee2c4c4563..00000000000000 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/storage/AsyncStorageModuleTest.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * 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.modules.storage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.Callback; -import com.facebook.react.bridge.JavaOnlyArray; -import com.facebook.react.bridge.JavaOnlyMap; -import com.facebook.react.bridge.ReactTestHelper; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.mockito.verification.VerificationMode; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.robolectric.Robolectric; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.RuntimeEnvironment; -import org.robolectric.android.util.concurrent.RoboExecutorService; - -/** Tests for {@link com.facebook.react.modules.storage.AsyncStorageModule}. */ -@PrepareForTest({Arguments.class}) -@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*", "org.json.*"}) -@RunWith(RobolectricTestRunner.class) -public class AsyncStorageModuleTest { - - private AsyncStorageModule mStorage; - private JavaOnlyArray mEmptyArray; - - @Rule public PowerMockRule rule = new PowerMockRule(); - - @Before - public void prepareModules() { - PowerMockito.mockStatic(Arguments.class); - Mockito.when(Arguments.createArray()) - .thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyArray(); - } - }); - - Mockito.when(Arguments.createMap()) - .thenAnswer( - new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return new JavaOnlyMap(); - } - }); - - // don't use Robolectric before initializing mocks - mStorage = - new AsyncStorageModule( - ReactTestHelper.createCatalystContextForTest(), new RoboExecutorService()); - mEmptyArray = new JavaOnlyArray(); - } - - @After - public void cleanUp() { - RuntimeEnvironment.application.deleteDatabase(ReactDatabaseSupplier.DATABASE_NAME); - ReactDatabaseSupplier.deleteInstance(); - } - - @Test - public void testMultiSetMultiGet() { - final String key1 = "foo1"; - final String key2 = "foo2"; - final String fakeKey = "fakeKey"; - final String value1 = "bar1"; - final String value2 = "bar2"; - JavaOnlyArray keyValues = new JavaOnlyArray(); - keyValues.pushArray(getArray(key1, value1)); - keyValues.pushArray(getArray(key2, value2)); - - Callback setCallback = mock(Callback.class); - mStorage.multiSet(keyValues, setCallback); - verify(setCallback, Mockito.times(1)).invoke(); - - JavaOnlyArray keys = new JavaOnlyArray(); - keys.pushString(key1); - keys.pushString(key2); - - Callback getCallback = mock(Callback.class); - mStorage.multiGet(keys, getCallback); - verify(getCallback, Mockito.times(1)).invoke(null, keyValues); - - keys.pushString(fakeKey); - JavaOnlyArray row3 = new JavaOnlyArray(); - row3.pushString(fakeKey); - row3.pushString(null); - keyValues.pushArray(row3); - - Callback getCallback2 = mock(Callback.class); - mStorage.multiGet(keys, getCallback2); - verify(getCallback2, Mockito.times(1)).invoke(null, keyValues); - } - - @Test - public void testMultiRemove() { - final String key1 = "foo1"; - final String key2 = "foo2"; - final String value1 = "bar1"; - final String value2 = "bar2"; - - JavaOnlyArray keyValues = new JavaOnlyArray(); - keyValues.pushArray(getArray(key1, value1)); - keyValues.pushArray(getArray(key2, value2)); - mStorage.multiSet(keyValues, mock(Callback.class)); - - JavaOnlyArray keys = new JavaOnlyArray(); - keys.pushString(key1); - keys.pushString(key2); - - Callback getCallback = mock(Callback.class); - mStorage.multiRemove(keys, getCallback); - verify(getCallback, Mockito.times(1)).invoke(); - - Callback getAllCallback = mock(Callback.class); - mStorage.getAllKeys(getAllCallback); - verify(getAllCallback, Mockito.times(1)).invoke(null, mEmptyArray); - - mStorage.multiSet(keyValues, mock(Callback.class)); - - keys.pushString("fakeKey"); - Callback getCallback2 = mock(Callback.class); - mStorage.multiRemove(keys, getCallback2); - verify(getCallback2, Mockito.times(1)).invoke(); - - Callback getAllCallback2 = mock(Callback.class); - mStorage.getAllKeys(getAllCallback2); - verify(getAllCallback2, Mockito.times(1)).invoke(null, mEmptyArray); - } - - @Test - public void testMultiMerge() throws Exception { - final String mergeKey = "mergeTest"; - - JSONObject value = new JSONObject(); - value.put("foo1", "bar1"); - value.put("foo2", createJSONArray("val1", "val2", 3)); - value.put("foo3", 1001); - value.put("foo4", createJSONObject("key1", "randomValueThatWillNeverBeUsed")); - - mStorage.multiSet(JavaOnlyArray.of(getArray(mergeKey, value.toString())), mock(Callback.class)); - { - Callback callback = mock(Callback.class); - mStorage.multiGet(getArray(mergeKey), callback); - verify(callback, Mockito.times(1)) - .invoke(null, JavaOnlyArray.of(getArray(mergeKey, value.toString()))); - } - - value.put("foo1", 1001); - value.put("foo2", createJSONObject("key1", "val1")); - value.put("foo3", "bar1"); - value.put("foo4", createJSONArray("val1", "val2", 3)); - - JSONObject newValue = new JSONObject(); - newValue.put("foo2", createJSONObject("key2", "val2")); - - JSONObject newValue2 = new JSONObject(); - newValue2.put("foo2", createJSONObject("key1", "val3")); - - mStorage.multiMerge( - JavaOnlyArray.of( - JavaOnlyArray.of(mergeKey, value.toString()), - JavaOnlyArray.of(mergeKey, newValue.toString()), - JavaOnlyArray.of(mergeKey, newValue2.toString())), - mock(Callback.class)); - - value.put("foo2", createJSONObject("key1", "val3", "key2", "val2")); - Callback callback = mock(Callback.class); - mStorage.multiGet(getArray(mergeKey), callback); - verify(callback, Mockito.times(1)) - .invoke(null, JavaOnlyArray.of(getArray(mergeKey, value.toString()))); - } - - @Test - public void testGetAllKeys() { - final String[] keys = {"foo", "foo2"}; - final String[] values = {"bar", "bar2"}; - JavaOnlyArray keyValues = new JavaOnlyArray(); - keyValues.pushArray(getArray(keys[0], values[0])); - keyValues.pushArray(getArray(keys[1], values[1])); - mStorage.multiSet(keyValues, mock(Callback.class)); - - JavaOnlyArray storedKeys = new JavaOnlyArray(); - storedKeys.pushString(keys[0]); - storedKeys.pushString(keys[1]); - - Callback getAllCallback = mock(Callback.class); - mStorage.getAllKeys(getAllCallback); - verify(getAllCallback, Mockito.times(1)).invoke(null, storedKeys); - - Callback getAllCallback2 = mock(Callback.class); - mStorage.multiRemove(getArray(keys[0]), mock(Callback.class)); - - mStorage.getAllKeys(getAllCallback2); - verify(getAllCallback2, Mockito.times(1)).invoke(null, getArray(keys[1])); - - mStorage.multiRemove(getArray(keys[1]), mock(Callback.class)); - Callback getAllCallback3 = mock(Callback.class); - mStorage.getAllKeys(getAllCallback3); - verify(getAllCallback3, Mockito.times(1)).invoke(null, mEmptyArray); - } - - @Test - public void testClear() { - JavaOnlyArray keyValues = new JavaOnlyArray(); - keyValues.pushArray(getArray("foo", "foo2")); - keyValues.pushArray(getArray("bar", "bar2")); - mStorage.multiSet(keyValues, mock(Callback.class)); - - Callback clearCallback2 = mock(Callback.class); - mStorage.clear(clearCallback2); - verify(clearCallback2, Mockito.times(1)).invoke(); - - Callback getAllCallback2 = mock(Callback.class); - mStorage.getAllKeys(getAllCallback2); - verify(getAllCallback2, Mockito.times(1)).invoke(null, mEmptyArray); - } - - @Test - public void testHugeMultiGetMultiGet() { - // Test with many keys, so that it's above the 999 limit per batch imposed by SQLite. - final int keyCount = 1001; - // don't set keys that divide by this magical number, so that we can check that multiGet works, - // and returns null for missing keys - final int magicalNumber = 343; - - JavaOnlyArray keyValues = new JavaOnlyArray(); - for (int i = 0; i < keyCount; i++) { - if (i % magicalNumber > 0) { - keyValues.pushArray(getArray("key" + i, "value" + i)); - } - } - mStorage.multiSet(keyValues, mock(Callback.class)); - JavaOnlyArray keys = new JavaOnlyArray(); - for (int i = 0; i < keyCount; i++) { - keys.pushString("key" + i); - } - mStorage.multiGet( - keys, - new Callback() { - @Override - public void invoke(Object... args) { - assertThat(args.length).isEqualTo(2); - JavaOnlyArray resultArray = (JavaOnlyArray) args[1]; - - assertThat(resultArray.size()).isEqualTo(keyCount); - boolean keyReceived[] = new boolean[keyCount]; - for (int i = 0; i < keyCount; i++) { - String key = resultArray.getArray(i).getString(0).substring(3); - int idx = Integer.parseInt(key); - assertThat(keyReceived[idx]).isFalse(); - keyReceived[idx] = true; - - if (idx % magicalNumber > 0) { - String value = resultArray.getArray(i).getString(1).substring(5); - assertThat(key).isEqualTo(value); - } else { - assertThat(resultArray.getArray(i).isNull(1)); - } - } - } - }); - - // Test removal in same test, since it's costly to set up the test again. - // Remove only odd keys - JavaOnlyArray keyRemoves = new JavaOnlyArray(); - for (int i = 0; i < keyCount; i++) { - if (i % 2 > 0) { - keyRemoves.pushString("key" + i); - } - } - mStorage.multiRemove(keyRemoves, mock(Callback.class)); - mStorage.getAllKeys( - new Callback() { - @Override - public void invoke(Object... args) { - JavaOnlyArray resultArray = (JavaOnlyArray) args[1]; - assertThat(resultArray.size()).isEqualTo(499); - for (int i = 0; i < resultArray.size(); i++) { - String key = resultArray.getString(i).substring(3); - int idx = Integer.parseInt(key); - assertThat(idx % 2).isEqualTo(0); - } - } - }); - } - - private static JSONArray createJSONArray(Object... objects) { - return new JSONArray(Arrays.asList(objects)); - } - - private static JSONObject createJSONObject(Object... keysAndValues) { - if (keysAndValues.length % 2 != 0) { - throw new IllegalArgumentException("You must provide the same number of keys and values"); - } - Map map = new HashMap(); - for (int i = 0; i < keysAndValues.length; i += 2) { - map.put(keysAndValues[i], keysAndValues[i + 1]); - } - return new JSONObject(map); - } - - private JavaOnlyArray getArray(String... values) { - JavaOnlyArray array = new JavaOnlyArray(); - for (String value : values) { - array.pushString(value); - } - return array; - } - - private static void waitForAsync() { - Robolectric.flushForegroundThreadScheduler(); - Robolectric.flushBackgroundThreadScheduler(); - } - - private static T verify(T mock, VerificationMode mode) { - waitForAsync(); - return Mockito.verify(mock, mode); - } -} From 4de2aaba502b49f8360ee5622d6ee8a6d9a93a32 Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Mon, 31 Oct 2022 14:39:19 -0700 Subject: [PATCH 087/169] refactor(AsyncStorage): move iOS files from react-native-github Summary: ## Changelog: [iOS][Removed] - Removed AsyncStorage module Reviewed By: lunaleaps Differential Revision: D40283712 fbshipit-source-id: 5e74c71915c2fbba4363e3fc917555039069038e --- React/CoreModules/BUCK | 3 - React/CoreModules/CoreModulesPlugins.h | 1 - React/CoreModules/CoreModulesPlugins.mm | 1 - React/CoreModules/RCTAsyncLocalStorage.h | 41 -- React/CoreModules/RCTAsyncLocalStorage.mm | 470 ---------------------- packages/rn-tester/Podfile.lock | 14 +- 6 files changed, 7 insertions(+), 523 deletions(-) delete mode 100644 React/CoreModules/RCTAsyncLocalStorage.h delete mode 100644 React/CoreModules/RCTAsyncLocalStorage.mm diff --git a/React/CoreModules/BUCK b/React/CoreModules/BUCK index 5608bacdaea311..143a840eff4138 100644 --- a/React/CoreModules/BUCK +++ b/React/CoreModules/BUCK @@ -78,9 +78,6 @@ rn_apple_library( ) + react_module_plugin_providers( name = "AlertManager", native_class_func = "RCTAlertManagerCls", - ) + react_module_plugin_providers( - name = "AsyncLocalStorage", - native_class_func = "RCTAsyncLocalStorageCls", ) + react_module_plugin_providers( name = "Timing", native_class_func = "RCTTimingCls", diff --git a/React/CoreModules/CoreModulesPlugins.h b/React/CoreModules/CoreModulesPlugins.h index 632fd5aeab1ba2..e2a02a4e335bdf 100644 --- a/React/CoreModules/CoreModulesPlugins.h +++ b/React/CoreModules/CoreModulesPlugins.h @@ -39,7 +39,6 @@ Class RCTI18nManagerCls(void) __attribute__((used)); Class RCTSourceCodeCls(void) __attribute__((used)); Class RCTActionSheetManagerCls(void) __attribute__((used)); Class RCTAlertManagerCls(void) __attribute__((used)); -Class RCTAsyncLocalStorageCls(void) __attribute__((used)); Class RCTTimingCls(void) __attribute__((used)); Class RCTStatusBarManagerCls(void) __attribute__((used)); Class RCTKeyboardObserverCls(void) __attribute__((used)); diff --git a/React/CoreModules/CoreModulesPlugins.mm b/React/CoreModules/CoreModulesPlugins.mm index 8915f029c3fb21..85187305e90cc0 100644 --- a/React/CoreModules/CoreModulesPlugins.mm +++ b/React/CoreModules/CoreModulesPlugins.mm @@ -29,7 +29,6 @@ Class RCTCoreModulesClassProvider(const char *name) { {"SourceCode", RCTSourceCodeCls}, {"ActionSheetManager", RCTActionSheetManagerCls}, {"AlertManager", RCTAlertManagerCls}, - {"AsyncLocalStorage", RCTAsyncLocalStorageCls}, {"Timing", RCTTimingCls}, {"StatusBarManager", RCTStatusBarManagerCls}, {"KeyboardObserver", RCTKeyboardObserverCls}, diff --git a/React/CoreModules/RCTAsyncLocalStorage.h b/React/CoreModules/RCTAsyncLocalStorage.h deleted file mode 100644 index 66136c87110766..00000000000000 --- a/React/CoreModules/RCTAsyncLocalStorage.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#import -#import - -/** - * A simple, asynchronous, persistent, key-value storage system designed as a - * backend to the AsyncStorage JS module, which is modeled after LocalStorage. - * - * Current implementation stores small values in serialized dictionary and - * larger values in separate files. Since we use a serial file queue - * `RKFileQueue`, reading/writing from multiple threads should be perceived as - * being atomic, unless someone bypasses the `RCTAsyncLocalStorage` API. - * - * Keys and values must always be strings or an error is returned. - */ -@interface RCTAsyncLocalStorage : NSObject - -@property (nonatomic, assign) BOOL clearOnInvalidate; - -@property (nonatomic, readonly, getter=isValid) BOOL valid; - -// Clear the RCTAsyncLocalStorage data from native code -- (void)clearAllData; - -// For clearing data when the bridge may not exist, e.g. when logging out. -+ (void)clearAllData; - -// Grab data from the cache. ResponseBlock result array will have an error at position 0, and an array of arrays at -// position 1. -- (void)multiGet:(NSArray *)keys callback:(RCTResponseSenderBlock)callback; - -// Add multiple key value pairs to the cache. -- (void)multiSet:(NSArray *> *)kvPairs callback:(RCTResponseSenderBlock)callback; - -@end diff --git a/React/CoreModules/RCTAsyncLocalStorage.mm b/React/CoreModules/RCTAsyncLocalStorage.mm deleted file mode 100644 index 326ea78f8d69db..00000000000000 --- a/React/CoreModules/RCTAsyncLocalStorage.mm +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -#import "RCTAsyncLocalStorage.h" - -#import - -#import -#import -#import - -#import -#import -#import - -#import "CoreModulesPlugins.h" - -static NSString *const RCTStorageDirectory = @"RCTAsyncLocalStorage_V1"; -static NSString *const RCTManifestFileName = @"manifest.json"; -static const NSUInteger RCTInlineValueThreshold = 1024; - -#pragma mark - Static helper functions - -static NSDictionary *RCTErrorForKey(NSString *key) -{ - if (![key isKindOfClass:[NSString class]]) { - return RCTMakeAndLogError(@"Invalid key - must be a string. Key: ", key, @{@"key" : key}); - } else if (key.length < 1) { - return RCTMakeAndLogError(@"Invalid key - must be at least one character. Key: ", key, @{@"key" : key}); - } else { - return nil; - } -} - -static void RCTAppendError(NSDictionary *error, NSMutableArray **errors) -{ - if (error && errors) { - if (!*errors) { - *errors = [NSMutableArray new]; - } - [*errors addObject:error]; - } -} - -static NSString *RCTReadFile(NSString *filePath, NSString *key, NSDictionary **errorOut) -{ - if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { - NSError *error; - NSStringEncoding encoding; - NSString *entryString = [NSString stringWithContentsOfFile:filePath usedEncoding:&encoding error:&error]; - NSDictionary *extraData = @{@"key" : RCTNullIfNil(key)}; - - if (error) { - if (errorOut) - *errorOut = RCTMakeError(@"Failed to read storage file.", error, extraData); - return nil; - } - - if (encoding != NSUTF8StringEncoding) { - if (errorOut) - *errorOut = RCTMakeError(@"Incorrect encoding of storage file: ", @(encoding), extraData); - return nil; - } - return entryString; - } - - return nil; -} - -static NSString *RCTGetStorageDirectory() -{ - static NSString *storageDirectory = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - storageDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; - storageDirectory = [storageDirectory stringByAppendingPathComponent:RCTStorageDirectory]; - }); - return storageDirectory; -} - -static NSString *RCTGetManifestFilePath() -{ - static NSString *manifestFilePath = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - manifestFilePath = [RCTGetStorageDirectory() stringByAppendingPathComponent:RCTManifestFileName]; - }); - return manifestFilePath; -} - -// Only merges objects - all other types are just clobbered (including arrays) -static BOOL RCTMergeRecursive(NSMutableDictionary *destination, NSDictionary *source) -{ - BOOL modified = NO; - for (NSString *key in source) { - id sourceValue = source[key]; - id destinationValue = destination[key]; - if ([sourceValue isKindOfClass:[NSDictionary class]]) { - if ([destinationValue isKindOfClass:[NSDictionary class]]) { - if ([destinationValue classForCoder] != [NSMutableDictionary class]) { - destinationValue = [destinationValue mutableCopy]; - } - if (RCTMergeRecursive(destinationValue, sourceValue)) { - destination[key] = destinationValue; - modified = YES; - } - } else { - destination[key] = [sourceValue copy]; - modified = YES; - } - } else if (![source isEqual:destinationValue]) { - destination[key] = [sourceValue copy]; - modified = YES; - } - } - return modified; -} - -static dispatch_queue_t RCTGetMethodQueue() -{ - // We want all instances to share the same queue since they will be reading/writing the same files. - static dispatch_queue_t queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - queue = dispatch_queue_create("com.facebook.react.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL); - }); - return queue; -} - -static NSCache *RCTGetCache() -{ - // We want all instances to share the same cache since they will be reading/writing the same files. - static NSCache *cache; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - cache = [NSCache new]; - cache.totalCostLimit = 2 * 1024 * 1024; // 2MB - - // Clear cache in the event of a memory warning - [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification - object:nil - queue:nil - usingBlock:^(__unused NSNotification *note) { - [cache removeAllObjects]; - }]; - }); - return cache; -} - -static BOOL RCTHasCreatedStorageDirectory = NO; -static NSDictionary *RCTDeleteStorageDirectory() -{ - NSError *error; - [[NSFileManager defaultManager] removeItemAtPath:RCTGetStorageDirectory() error:&error]; - RCTHasCreatedStorageDirectory = NO; - return error ? RCTMakeError(@"Failed to delete storage directory.", error, nil) : nil; -} - -#pragma mark - RCTAsyncLocalStorage - -@interface RCTAsyncLocalStorage () -@end - -@implementation RCTAsyncLocalStorage { - BOOL _haveSetup; - // The manifest is a dictionary of all keys with small values inlined. Null values indicate values that are stored - // in separate files (as opposed to nil values which don't exist). The manifest is read off disk at startup, and - // written to disk after all mutations. - NSMutableDictionary *_manifest; -} - -RCT_EXPORT_MODULE() - -- (dispatch_queue_t)methodQueue -{ - return RCTGetMethodQueue(); -} - -- (void)clearAllData -{ - dispatch_async(RCTGetMethodQueue(), ^{ - [self->_manifest removeAllObjects]; - [RCTGetCache() removeAllObjects]; - RCTDeleteStorageDirectory(); - }); -} - -+ (void)clearAllData -{ - dispatch_async(RCTGetMethodQueue(), ^{ - [RCTGetCache() removeAllObjects]; - RCTDeleteStorageDirectory(); - }); -} - -- (void)invalidate -{ - if (_clearOnInvalidate) { - [RCTGetCache() removeAllObjects]; - RCTDeleteStorageDirectory(); - } - _clearOnInvalidate = NO; - [_manifest removeAllObjects]; - _haveSetup = NO; -} - -- (BOOL)isValid -{ - return _haveSetup; -} - -- (void)dealloc -{ - [self invalidate]; -} - -- (NSString *)_filePathForKey:(NSString *)key -{ - NSString *safeFileName = RCTMD5Hash(key); - return [RCTGetStorageDirectory() stringByAppendingPathComponent:safeFileName]; -} - -- (NSDictionary *)_ensureSetup -{ - RCTAssertThread(RCTGetMethodQueue(), @"Must be executed on storage thread"); - - NSError *error = nil; - if (!RCTHasCreatedStorageDirectory) { - [[NSFileManager defaultManager] createDirectoryAtPath:RCTGetStorageDirectory() - withIntermediateDirectories:YES - attributes:nil - error:&error]; - if (error) { - return RCTMakeError(@"Failed to create storage directory.", error, nil); - } - RCTHasCreatedStorageDirectory = YES; - } - if (!_haveSetup) { - NSDictionary *errorOut; - NSString *serialized = RCTReadFile(RCTGetManifestFilePath(), RCTManifestFileName, &errorOut); - _manifest = serialized ? RCTJSONParseMutable(serialized, &error) : [NSMutableDictionary new]; - if (error) { - RCTLogWarn(@"Failed to parse manifest - creating new one.\n\n%@", error); - _manifest = [NSMutableDictionary new]; - } - _haveSetup = YES; - } - return nil; -} - -- (NSDictionary *)_writeManifest:(NSMutableArray **)errors -{ - NSError *error; - NSString *serialized = RCTJSONStringify(_manifest, &error); - [serialized writeToFile:RCTGetManifestFilePath() atomically:YES encoding:NSUTF8StringEncoding error:&error]; - NSDictionary *errorOut; - if (error) { - errorOut = RCTMakeError(@"Failed to write manifest file.", error, nil); - RCTAppendError(errorOut, errors); - } - return errorOut; -} - -- (NSDictionary *)_appendItemForKey:(NSString *)key toArray:(NSMutableArray *> *)result -{ - NSDictionary *errorOut = RCTErrorForKey(key); - if (errorOut) { - return errorOut; - } - NSString *value = [self _getValueForKey:key errorOut:&errorOut]; - [result addObject:@[ key, RCTNullIfNil(value) ]]; // Insert null if missing or failure. - return errorOut; -} - -- (NSString *)_getValueForKey:(NSString *)key errorOut:(NSDictionary **)errorOut -{ - NSString *value = _manifest[key]; // nil means missing, null means there may be a data file, else: NSString - if (value == (id)kCFNull) { - value = [RCTGetCache() objectForKey:key]; - if (!value) { - NSString *filePath = [self _filePathForKey:key]; - value = RCTReadFile(filePath, key, errorOut); - if (value) { - [RCTGetCache() setObject:value forKey:key cost:value.length]; - } else { - // file does not exist after all, so remove from manifest (no need to save - // manifest immediately though, as cost of checking again next time is negligible) - [_manifest removeObjectForKey:key]; - } - } - } - return value; -} - -- (NSDictionary *)_writeEntry:(NSArray *)entry changedManifest:(BOOL *)changedManifest -{ - if (entry.count != 2) { - return RCTMakeAndLogError(@"Entries must be arrays of the form [key: string, value: string], got: ", entry, nil); - } - NSString *key = entry[0]; - NSDictionary *errorOut = RCTErrorForKey(key); - if (errorOut) { - return errorOut; - } - if (![entry[1] isKindOfClass:[NSString class]]) { - return RCTMakeAndLogError(@"Invalid value for entry - must be a string. Got entry: ", entry, nil); - } - NSString *value = entry[1]; - - NSString *filePath = [self _filePathForKey:key]; - NSError *error; - if (value.length <= RCTInlineValueThreshold) { - if (_manifest[key] == (id)kCFNull) { - // If the value already existed but wasn't inlined, remove the old file. - [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; - [RCTGetCache() removeObjectForKey:key]; - } - *changedManifest = YES; - _manifest[key] = value; - return nil; - } - [value writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; - [RCTGetCache() setObject:value forKey:key cost:value.length]; - if (error) { - errorOut = RCTMakeError(@"Failed to write value.", error, @{@"key" : key}); - } else if (_manifest[key] != (id)kCFNull) { - *changedManifest = YES; - _manifest[key] = (id)kCFNull; - } - return errorOut; -} - -#pragma mark - Exported JS Functions - -RCT_EXPORT_METHOD(multiGet : (NSArray *)keys callback : (RCTResponseSenderBlock)callback) -{ - NSDictionary *errorOut = [self _ensureSetup]; - if (errorOut) { - callback(@[ @[ errorOut ], (id)kCFNull ]); - return; - } - NSMutableArray *errors; - NSMutableArray *> *result = [[NSMutableArray alloc] initWithCapacity:keys.count]; - for (NSString *key in keys) { - id keyError; - id value = [self _getValueForKey:key errorOut:&keyError]; - [result addObject:@[ key, RCTNullIfNil(value) ]]; - RCTAppendError(keyError, &errors); - } - callback(@[ RCTNullIfNil(errors), result ]); -} - -RCT_EXPORT_METHOD(multiSet : (NSArray *> *)kvPairs callback : (RCTResponseSenderBlock)callback) -{ - NSDictionary *errorOut = [self _ensureSetup]; - if (errorOut) { - callback(@[ @[ errorOut ] ]); - return; - } - BOOL changedManifest = NO; - NSMutableArray *errors; - for (NSArray *entry in kvPairs) { - NSDictionary *keyError = [self _writeEntry:entry changedManifest:&changedManifest]; - RCTAppendError(keyError, &errors); - } - if (changedManifest) { - [self _writeManifest:&errors]; - } - callback(@[ RCTNullIfNil(errors) ]); -} - -RCT_EXPORT_METHOD(multiMerge : (NSArray *> *)kvPairs callback : (RCTResponseSenderBlock)callback) -{ - NSDictionary *errorOut = [self _ensureSetup]; - if (errorOut) { - callback(@[ @[ errorOut ] ]); - return; - } - BOOL changedManifest = NO; - NSMutableArray *errors; - for (__strong NSArray *entry in kvPairs) { - NSDictionary *keyError; - NSString *value = [self _getValueForKey:entry[0] errorOut:&keyError]; - if (!keyError) { - if (value) { - NSError *jsonError; - NSMutableDictionary *mergedVal = RCTJSONParseMutable(value, &jsonError); - if (RCTMergeRecursive(mergedVal, RCTJSONParse(entry[1], &jsonError))) { - entry = @[ entry[0], RCTNullIfNil(RCTJSONStringify(mergedVal, NULL)) ]; - } - if (jsonError) { - keyError = RCTJSErrorFromNSError(jsonError); - } - } - if (!keyError) { - keyError = [self _writeEntry:entry changedManifest:&changedManifest]; - } - } - RCTAppendError(keyError, &errors); - } - if (changedManifest) { - [self _writeManifest:&errors]; - } - callback(@[ RCTNullIfNil(errors) ]); -} - -RCT_EXPORT_METHOD(multiRemove : (NSArray *)keys callback : (RCTResponseSenderBlock)callback) -{ - NSDictionary *errorOut = [self _ensureSetup]; - if (errorOut) { - callback(@[ @[ errorOut ] ]); - return; - } - NSMutableArray *errors; - BOOL changedManifest = NO; - for (NSString *key in keys) { - NSDictionary *keyError = RCTErrorForKey(key); - if (!keyError) { - if (_manifest[key] == (id)kCFNull) { - NSString *filePath = [self _filePathForKey:key]; - [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; - [RCTGetCache() removeObjectForKey:key]; - } - if (_manifest[key]) { - changedManifest = YES; - [_manifest removeObjectForKey:key]; - } - } - RCTAppendError(keyError, &errors); - } - if (changedManifest) { - [self _writeManifest:&errors]; - } - callback(@[ RCTNullIfNil(errors) ]); -} - -RCT_EXPORT_METHOD(clear : (RCTResponseSenderBlock)callback) -{ - [_manifest removeAllObjects]; - [RCTGetCache() removeAllObjects]; - NSDictionary *error = RCTDeleteStorageDirectory(); - callback(@[ RCTNullIfNil(error) ]); -} - -RCT_EXPORT_METHOD(getAllKeys : (RCTResponseSenderBlock)callback) -{ - NSDictionary *errorOut = [self _ensureSetup]; - if (errorOut) { - callback(@[ errorOut, (id)kCFNull ]); - } else { - callback(@[ (id)kCFNull, _manifest.allKeys ]); - } -} - -- (std::shared_ptr)getTurboModule: - (const facebook::react::ObjCTurboModule::InitParams &)params -{ - return std::make_shared(params); -} - -@end - -Class RCTAsyncLocalStorageCls(void) -{ - return RCTAsyncLocalStorage.class; -} diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index fd7b6b9e62e3fa..4ed5001f3daf9f 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -929,7 +929,7 @@ EXTERNAL SOURCES: :path: "../../ReactCommon/yoga" SPEC CHECKSUMS: - boost: a7c83b31436843459a1961bfd74b96033dc77234 + boost: 57d2868c099736d80fcd648bf211b4431e51a558 CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 DoubleConversion: 5189b271737e1565bdce30deb4a08d647e3f5f54 FBLazyVector: 19e408e76fa9258dd32191a50d60c41444f52d29 @@ -948,7 +948,7 @@ SPEC CHECKSUMS: hermes-engine: cd15ebd246edff3a995ec666e898dd1cbdcaa10d libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c - RCT-Folly: 0080d0a6ebf2577475bda044aa59e2ca1f909cda + RCT-Folly: 424b8c9a7a0b9ab2886ffe9c3b041ef628fd4fb1 RCTRequired: 1c8808cf84569265784a6c33984bbb506ada8c6e RCTTypeSafety: b6dcb5036a808864ee8cad66ca15f263c24661cc React: 8d809d414723bb5763093ddec7658066a21ccabc @@ -957,15 +957,15 @@ SPEC CHECKSUMS: React-Codegen: d2434d5e4d238bceef25f40c4f58b199eb981ad0 React-Core: 3965263aa4b4e1ebf7b4fdb50d2f49ce7bf28f63 React-CoreModules: 675170bccf156da3a3348e04e2036ce401b2010d - React-cxxreact: 7276467c246302fedf598cc40d7003896ddb20ba + React-cxxreact: ebed982230716c3515ab2f435cb13aec8a56af02 React-Fabric: 141459e61c825acf02d26ece099acbd9cbd87b99 - React-graphics: 5ccc9cc0d91794fd42bc1c693e9aea207554bbef + React-graphics: 2dda97baebb0082bb85499c862c3f269a194f416 React-hermes: 0a5145bae4207edf0def8e28fbcb6a8fd6e806c2 React-jsi: c24dbcfdf7ea075138b73372387c7f17c0db56ef React-jsidynamic: 2b14ac1b6d3a1b7daa1e5a424b98de87da981698 React-jsiexecutor: 14e899380e3fe9ca74c4e19727540a03e7574721 React-jsinspector: 7733dd522d044aef87caa39f3eda77593358a7eb - React-logger: c7960346b021767ed90971aff592a44e3d69f8bb + React-logger: a2b4f0f204e45e25f493ca4ce245a336217c923e React-perflogger: c4fdd48988c2d3047186fc1bc1772d634cfca2ea React-RCTActionSheet: 166fd1df85ac10219466b45d12a5884d3eaceac1 React-RCTAnimation: d6127046c6bb44bd3e67b7503c4ad7f91131b58e @@ -977,13 +977,13 @@ SPEC CHECKSUMS: React-RCTNetwork: a865deadacbf6b3d863f0496e7d2c2e81c269317 React-RCTPushNotification: 7f678a88147254ede5d21a1e1e71e8a964dd0051 React-RCTSettings: 23ce1aa52ddf5db44c973bb5cc93713e871e09b6 - React-RCTTest: 06c388632dc7b30df17af01c8f9e89e641b4d31c + React-RCTTest: be92171ef0a1818f96324eac3be0356f4fa08844 React-RCTText: a861fbf2835299d3cc4189697cddd8bd8602afb9 React-RCTVibration: 0386f50996a153b3f39cecbe7d139763ac9a9fdf React-rncore: 665c70690f404bbfa3948148de72689672a906d2 React-runtimeexecutor: 97dca9247f4d3cfe0733384b189c6930fbd402b7 ReactCommon: b1f213aa09e3dfd0a89389b5023fdb1cd6528e96 - ScreenshotManager: 3fc534a218e7b8dde632158411d0f15b0ca8893c + ScreenshotManager: 06cb3d1794c8082d92b3e91813d1678d0977a4fb SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608 Yoga: 1b1a12ff3d86a10565ea7cbe057d42f5e5fb2a07 YogaKit: f782866e155069a2cca2517aafea43200b01fd5a From 20eeb1bfe30eacf26abd185b6fa062b708deaf8a Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Mon, 31 Oct 2022 14:39:19 -0700 Subject: [PATCH 088/169] refactor(react-native-github): remove AsyncStorage from JS Summary: ## Changelog [JS][Removed] - Removed AsyncStorage module from react-native Reviewed By: NickGerleman Differential Revision: D40302352 fbshipit-source-id: 9377ea12036e498dde0b4b0f56de5c4fb9bd2461 --- IntegrationTests/AsyncStorageTest.js | 261 ------------ IntegrationTests/IntegrationTestsApp.js | 1 - Libraries/Storage/AsyncStorage.d.ts | 120 ------ Libraries/Storage/AsyncStorage.js | 385 ------------------ Libraries/Storage/NativeAsyncLocalStorage.js | 45 -- .../Storage/NativeAsyncSQLiteDBStorage.js | 45 -- index.js | 26 +- types/__typetests__/index.tsx | 1 - types/index.d.ts | 1 - 9 files changed, 15 insertions(+), 870 deletions(-) delete mode 100644 IntegrationTests/AsyncStorageTest.js delete mode 100644 Libraries/Storage/AsyncStorage.d.ts delete mode 100644 Libraries/Storage/AsyncStorage.js delete mode 100644 Libraries/Storage/NativeAsyncLocalStorage.js delete mode 100644 Libraries/Storage/NativeAsyncSQLiteDBStorage.js diff --git a/IntegrationTests/AsyncStorageTest.js b/IntegrationTests/AsyncStorageTest.js deleted file mode 100644 index 42bdbd62965458..00000000000000 --- a/IntegrationTests/AsyncStorageTest.js +++ /dev/null @@ -1,261 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - * @flow - */ - -'use strict'; - -const React = require('react'); -const ReactNative = require('react-native'); -const {AsyncStorage, Text, View, StyleSheet} = ReactNative; -const {TestModule} = ReactNative.NativeModules; - -const deepDiffer = require('react-native/Libraries/Utilities/differ/deepDiffer'); -const nullthrows = require('nullthrows'); - -const DEBUG = false; - -const KEY_1 = 'key_1'; -const VAL_1 = 'val_1'; -const KEY_2 = 'key_2'; -const VAL_2 = 'val_2'; -const KEY_MERGE = 'key_merge'; -const VAL_MERGE_1 = {foo: 1, bar: {hoo: 1, boo: 1}, moo: {a: 3}}; -const VAL_MERGE_2 = {bar: {hoo: 2}, baz: 2, moo: {a: 3}}; -const VAL_MERGE_EXPECT = {foo: 1, bar: {hoo: 2, boo: 1}, baz: 2, moo: {a: 3}}; - -// setup in componentDidMount -let done = (result: ?boolean) => {}; -let updateMessage = (message: string) => {}; - -function runTestCase(description: string, fn: () => void) { - updateMessage(description); - fn(); -} - -function expectTrue(condition: boolean, message: string) { - if (!condition) { - throw new Error(message); - } -} - -// Type-safe wrapper around JSON.stringify -function stringify( - value: - | void - | null - | string - | number - | boolean - | {...} - | $ReadOnlyArray, -): string { - if (typeof value === 'undefined') { - return 'undefined'; - } - return JSON.stringify(value); -} - -function expectEqual( - lhs: ?(any | string | Array>), - rhs: - | null - | string - | { - bar: {boo: number, hoo: number}, - baz: number, - foo: number, - moo: {a: number}, - } - | Array>, - testname: string, -) { - expectTrue( - !deepDiffer(lhs, rhs), - 'Error in test ' + - testname + - ': expected\n' + - stringify(rhs) + - '\ngot\n' + - stringify(lhs), - ); -} - -function expectAsyncNoError( - place: string, - err: ?(Error | string | Array), -) { - if (err instanceof Error) { - err = err.message; - } - expectTrue( - err === null, - 'Unexpected error in ' + place + ': ' + stringify(err), - ); -} - -function testSetAndGet() { - AsyncStorage.setItem(KEY_1, VAL_1, err1 => { - expectAsyncNoError('testSetAndGet/setItem', err1); - AsyncStorage.getItem(KEY_1, (err2, result) => { - expectAsyncNoError('testSetAndGet/getItem', err2); - expectEqual(result, VAL_1, 'testSetAndGet setItem'); - updateMessage('get(key_1) correctly returned ' + String(result)); - runTestCase('should get null for missing key', testMissingGet); - }); - }); -} - -function testMissingGet() { - AsyncStorage.getItem(KEY_2, (err, result) => { - expectAsyncNoError('testMissingGet/setItem', err); - expectEqual(result, null, 'testMissingGet'); - updateMessage('missing get(key_2) correctly returned ' + String(result)); - runTestCase('check set twice results in a single key', testSetTwice); - }); -} - -function testSetTwice() { - AsyncStorage.setItem(KEY_1, VAL_1, () => { - AsyncStorage.setItem(KEY_1, VAL_1, () => { - AsyncStorage.getItem(KEY_1, (err, result) => { - expectAsyncNoError('testSetTwice/setItem', err); - expectEqual(result, VAL_1, 'testSetTwice'); - updateMessage('setTwice worked as expected'); - runTestCase('test removeItem', testRemoveItem); - }); - }); - }); -} - -function testRemoveItem() { - AsyncStorage.setItem(KEY_1, VAL_1, () => { - AsyncStorage.setItem(KEY_2, VAL_2, () => { - AsyncStorage.getAllKeys((err, result) => { - expectAsyncNoError('testRemoveItem/getAllKeys', err); - expectTrue( - nullthrows(result).indexOf(KEY_1) >= 0 && - nullthrows(result).indexOf(KEY_2) >= 0, - 'Missing KEY_1 or KEY_2 in ' + '(' + nullthrows(result).join() + ')', - ); - updateMessage('testRemoveItem - add two items'); - AsyncStorage.removeItem(KEY_1, err2 => { - expectAsyncNoError('testRemoveItem/removeItem', err2); - updateMessage('delete successful '); - AsyncStorage.getItem(KEY_1, (err3, result2) => { - expectAsyncNoError('testRemoveItem/getItem', err3); - expectEqual( - result2, - null, - 'testRemoveItem: key_1 present after delete', - ); - updateMessage('key properly removed '); - AsyncStorage.getAllKeys((err4, result3) => { - expectAsyncNoError('testRemoveItem/getAllKeys', err4); - expectTrue( - nullthrows(result3).indexOf(KEY_1) === -1, - 'Unexpected: KEY_1 present in ' + nullthrows(result3).join(), - ); - updateMessage('proper length returned.'); - runTestCase('should merge values', testMerge); - }); - }); - }); - }); - }); - }); -} - -function testMerge() { - AsyncStorage.setItem(KEY_MERGE, stringify(VAL_MERGE_1), err1 => { - expectAsyncNoError('testMerge/setItem', err1); - AsyncStorage.mergeItem(KEY_MERGE, stringify(VAL_MERGE_2), err2 => { - expectAsyncNoError('testMerge/mergeItem', err2); - AsyncStorage.getItem(KEY_MERGE, (err3, result) => { - expectAsyncNoError('testMerge/setItem', err3); - expectEqual( - JSON.parse(nullthrows(result)), - VAL_MERGE_EXPECT, - 'testMerge', - ); - updateMessage('objects deeply merged\nDone!'); - runTestCase('multi set and get', testOptimizedMultiGet); - }); - }); - }); -} - -function testOptimizedMultiGet() { - let batch = [ - [KEY_1, VAL_1], - [KEY_2, VAL_2], - ]; - let keys = batch.map(([key, value]) => key); - AsyncStorage.multiSet(batch, err1 => { - // yes, twice on purpose - [1, 2].forEach(i => { - expectAsyncNoError(`${i} testOptimizedMultiGet/multiSet`, err1); - AsyncStorage.multiGet(keys, (err2, result) => { - expectAsyncNoError(`${i} testOptimizedMultiGet/multiGet`, err2); - expectEqual(result, batch, `${i} testOptimizedMultiGet multiGet`); - updateMessage( - 'multiGet([key_1, key_2]) correctly returned ' + stringify(result), - ); - done(); - }); - }); - }); -} - -class AsyncStorageTest extends React.Component<{...}, $FlowFixMeState> { - state: any | {|done: boolean, messages: string|} = { - messages: 'Initializing...', - done: false, - }; - - componentDidMount() { - done = () => - this.setState({done: true}, () => { - TestModule.markTestCompleted(); - }); - updateMessage = (msg: string) => { - this.setState({messages: this.state.messages.concat('\n' + msg)}); - DEBUG && console.log(msg); - }; - AsyncStorage.clear(testSetAndGet); - } - - render(): React.Node { - return ( - - - { - /* $FlowFixMe[incompatible-type] (>=0.54.0 site=react_native_fb,react_ - * native_oss) This comment suppresses an error found when Flow v0.54 - * was deployed. To see the error delete this comment and run Flow. - */ - this.constructor.displayName + ': ' - } - {this.state.done ? 'Done' : 'Testing...'} - {'\n\n' + this.state.messages} - - - ); - } -} - -const styles = StyleSheet.create({ - container: { - backgroundColor: 'white', - padding: 40, - }, -}); - -AsyncStorageTest.displayName = 'AsyncStorageTest'; - -module.exports = AsyncStorageTest; diff --git a/IntegrationTests/IntegrationTestsApp.js b/IntegrationTests/IntegrationTestsApp.js index 6c3994e63b61b3..442e70327482e5 100644 --- a/IntegrationTests/IntegrationTestsApp.js +++ b/IntegrationTests/IntegrationTestsApp.js @@ -20,7 +20,6 @@ const {AppRegistry, ScrollView, StyleSheet, Text, TouchableOpacity, View} = const TESTS = [ require('./IntegrationTestHarnessTest'), require('./TimersTest'), - require('./AsyncStorageTest'), require('./LayoutEventsTest'), require('./AppEventsTest'), require('./SimpleSnapshotTest'), diff --git a/Libraries/Storage/AsyncStorage.d.ts b/Libraries/Storage/AsyncStorage.d.ts deleted file mode 100644 index 77c8780c40b5eb..00000000000000 --- a/Libraries/Storage/AsyncStorage.d.ts +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -/** - * AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage - * system that is global to the app. It should be used instead of LocalStorage. - * - * It is recommended that you use an abstraction on top of `AsyncStorage` - * instead of `AsyncStorage` directly for anything more than light usage since - * it operates globally. - * - * On iOS, `AsyncStorage` is backed by native code that stores small values in a - * serialized dictionary and larger values in separate files. On Android, - * `AsyncStorage` will use either [RocksDB](http://rocksdb.org/) or SQLite - * based on what is available. - * - * @see https://reactnative.dev/docs/asyncstorage#content - */ -export interface AsyncStorageStatic { - /** - * Fetches key and passes the result to callback, along with an Error if there is any. - */ - getItem( - key: string, - callback?: (error?: Error, result?: string) => void, - ): Promise; - - /** - * Sets value for key and calls callback on completion, along with an Error if there is any - */ - setItem( - key: string, - value: string, - callback?: (error?: Error) => void, - ): Promise; - - removeItem(key: string, callback?: (error?: Error) => void): Promise; - - /** - * Merges existing value with input value, assuming they are stringified json. Returns a Promise object. - * Not supported by all native implementation - */ - mergeItem( - key: string, - value: string, - callback?: (error?: Error) => void, - ): Promise; - - /** - * Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this. - * Use removeItem or multiRemove to clear only your own keys instead. - */ - clear(callback?: (error?: Error) => void): Promise; - - /** - * Gets all keys known to the app, for all callers, libraries, etc - */ - getAllKeys( - callback?: (error?: Error, keys?: string[]) => void, - ): Promise; - - /** - * multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet - */ - multiGet( - keys: string[], - callback?: (errors?: Error[], result?: [string, string][]) => void, - ): Promise<[string, string][]>; - - /** - * multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet, - * - * multiSet([['k1', 'val1'], ['k2', 'val2']], cb); - */ - multiSet( - keyValuePairs: string[][], - callback?: (errors?: Error[]) => void, - ): Promise; - - /** - * Delete all the keys in the keys array. - */ - multiRemove( - keys: string[], - callback?: (errors?: Error[]) => void, - ): Promise; - - /** - * Merges existing values with input values, assuming they are stringified json. - * Returns a Promise object. - * - * Not supported by all native implementations. - */ - multiMerge( - keyValuePairs: string[][], - callback?: (errors?: Error[]) => void, - ): Promise; -} - -/** - * AsyncStorage has been extracted from react-native core and will be removed in a future release. - * It can now be installed and imported from `@react-native-community/async-storage` instead of 'react-native'. - * @see https://github.com/react-native-community/async-storage - * @deprecated - */ -export const AsyncStorage: AsyncStorageStatic; - -/** - * AsyncStorage has been extracted from react-native core and will be removed in a future release. - * It can now be installed and imported from `@react-native-community/async-storage` instead of 'react-native'. - * @see https://github.com/react-native-community/async-storage - * @deprecated - */ -export type AsyncStorage = AsyncStorageStatic; diff --git a/Libraries/Storage/AsyncStorage.js b/Libraries/Storage/AsyncStorage.js deleted file mode 100644 index e9683ab0cf7a7e..00000000000000 --- a/Libraries/Storage/AsyncStorage.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - * @flow strict - * @jsdoc - */ - -import NativeAsyncLocalStorage from './NativeAsyncLocalStorage'; -import NativeAsyncSQLiteDBStorage from './NativeAsyncSQLiteDBStorage'; -import invariant from 'invariant'; - -// Use SQLite if available, otherwise file storage. -const RCTAsyncStorage = NativeAsyncSQLiteDBStorage || NativeAsyncLocalStorage; - -type GetRequest = { - keys: Array, - callback: ?(errors: ?Array, result: ?Array>) => void, - keyIndex: number, - resolve: ( - result?: - | void - | null - | Promise>> - | Array>, - ) => void, - reject: (error?: mixed) => void, -}; - -/** - * `AsyncStorage` is a simple, unencrypted, asynchronous, persistent, key-value - * storage system that is global to the app. It should be used instead of - * LocalStorage. - * - * See https://reactnative.dev/docs/asyncstorage - */ -const AsyncStorage = { - _getRequests: ([]: Array), - _getKeys: ([]: Array), - _immediate: (null: ?number), - - /** - * Fetches an item for a `key` and invokes a callback upon completion. - * - * See https://reactnative.dev/docs/asyncstorage#getitem - */ - getItem: function ( - key: string, - callback?: ?(error: ?Error, result: ?string) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiGet([key], function (errors, result) { - // Unpack result to get value from [[key,value]] - const value = result && result[0] && result[0][1] ? result[0][1] : null; - const errs = convertErrors(errors); - callback && callback(errs && errs[0], value); - if (errs) { - reject(errs[0]); - } else { - resolve(value); - } - }); - }); - }, - - /** - * Sets the value for a `key` and invokes a callback upon completion. - * - * See https://reactnative.dev/docs/asyncstorage#setitem - */ - setItem: function ( - key: string, - value: string, - callback?: ?(error: ?Error) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiSet([[key, value]], function (errors) { - const errs = convertErrors(errors); - callback && callback(errs && errs[0]); - if (errs) { - reject(errs[0]); - } else { - resolve(); - } - }); - }); - }, - - /** - * Removes an item for a `key` and invokes a callback upon completion. - * - * See https://reactnative.dev/docs/asyncstorage#removeitem - */ - removeItem: function ( - key: string, - callback?: ?(error: ?Error) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiRemove([key], function (errors) { - const errs = convertErrors(errors); - callback && callback(errs && errs[0]); - if (errs) { - reject(errs[0]); - } else { - resolve(); - } - }); - }); - }, - - /** - * Merges an existing `key` value with an input value, assuming both values - * are stringified JSON. - * - * **NOTE:** This is not supported by all native implementations. - * - * See https://reactnative.dev/docs/asyncstorage#mergeitem - */ - mergeItem: function ( - key: string, - value: string, - callback?: ?(error: ?Error) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiMerge([[key, value]], function (errors) { - const errs = convertErrors(errors); - callback && callback(errs && errs[0]); - if (errs) { - reject(errs[0]); - } else { - resolve(); - } - }); - }); - }, - - /** - * Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably - * don't want to call this; use `removeItem` or `multiRemove` to clear only - * your app's keys. - * - * See https://reactnative.dev/docs/asyncstorage#clear - */ - clear: function (callback?: ?(error: ?Error) => void): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.clear(function (error) { - callback && callback(convertError(error)); - if (error && convertError(error)) { - reject(convertError(error)); - } else { - resolve(); - } - }); - }); - }, - - /** - * Gets *all* keys known to your app; for all callers, libraries, etc. - * - * See https://reactnative.dev/docs/asyncstorage#getallkeys - */ - getAllKeys: function ( - callback?: ?(error: ?Error, keys: ?Array) => void, - ): Promise> { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.getAllKeys(function (error, keys) { - callback && callback(convertError(error), keys); - if (error) { - reject(convertError(error)); - } else { - resolve(keys); - } - }); - }); - }, - - /** - * The following batched functions are useful for executing a lot of - * operations at once, allowing for native optimizations and provide the - * convenience of a single callback after all operations are complete. - * - * These functions return arrays of errors, potentially one for every key. - * For key-specific errors, the Error object will have a key property to - * indicate which key caused the error. - */ - - /** - * Flushes any pending requests using a single batch call to get the data. - * - * See https://reactnative.dev/docs/asyncstorage#flushgetrequests - * */ - /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by - * Flow's LTI update could not be added via codemod */ - flushGetRequests: function (): void { - const getRequests = this._getRequests; - const getKeys = this._getKeys; - - this._getRequests = []; - this._getKeys = []; - - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - RCTAsyncStorage.multiGet(getKeys, function (errors, result) { - // Even though the runtime complexity of this is theoretically worse vs if we used a map, - // it's much, much faster in practice for the data sets we deal with (we avoid - // allocating result pair arrays). This was heavily benchmarked. - // - // Is there a way to avoid using the map but fix the bug in this breaking test? - // https://github.com/facebook/react-native/commit/8dd8ad76579d7feef34c014d387bf02065692264 - const map: {[string]: string} = {}; - result && - result.forEach(([key, value]) => { - map[key] = value; - return value; - }); - const reqLength = getRequests.length; - for (let i = 0; i < reqLength; i++) { - const request = getRequests[i]; - const requestKeys = request.keys; - const requestResult = requestKeys.map(key => [key, map[key]]); - request.callback && request.callback(null, requestResult); - request.resolve && request.resolve(requestResult); - } - }); - }, - - /** - * This allows you to batch the fetching of items given an array of `key` - * inputs. Your callback will be invoked with an array of corresponding - * key-value pairs found. - * - * See https://reactnative.dev/docs/asyncstorage#multiget - */ - /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by - * Flow's LTI update could not be added via codemod */ - multiGet: function ( - keys: Array, - callback?: ?(errors: ?Array, result: ?Array>) => void, - ): Promise>> { - if (!this._immediate) { - this._immediate = setImmediate(() => { - this._immediate = null; - this.flushGetRequests(); - }); - } - - return new Promise>>((resolve, reject) => { - this._getRequests.push({ - keys, - callback, - // do we need this? - keyIndex: this._getKeys.length, - resolve, - reject, - }); - // avoid fetching duplicates - keys.forEach(key => { - if (this._getKeys.indexOf(key) === -1) { - this._getKeys.push(key); - } - }); - }); - }, - - /** - * Use this as a batch operation for storing multiple key-value pairs. When - * the operation completes you'll get a single callback with any errors. - * - * See https://reactnative.dev/docs/asyncstorage#multiset - */ - multiSet: function ( - keyValuePairs: Array>, - callback?: ?(errors: ?Array) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiSet(keyValuePairs, function (errors) { - const error = convertErrors(errors); - callback && callback(error); - if (error) { - reject(error); - } else { - resolve(); - } - }); - }); - }, - - /** - * Call this to batch the deletion of all keys in the `keys` array. - * - * See https://reactnative.dev/docs/asyncstorage#multiremove - */ - multiRemove: function ( - keys: Array, - callback?: ?(errors: ?Array) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiRemove(keys, function (errors) { - const error = convertErrors(errors); - callback && callback(error); - if (error) { - reject(error); - } else { - resolve(); - } - }); - }); - }, - - /** - * Batch operation to merge in existing and new values for a given set of - * keys. This assumes that the values are stringified JSON. - * - * **NOTE**: This is not supported by all native implementations. - * - * See https://reactnative.dev/docs/asyncstorage#multimerge - */ - multiMerge: function ( - keyValuePairs: Array>, - callback?: ?(errors: ?Array) => void, - ): Promise { - invariant(RCTAsyncStorage, 'RCTAsyncStorage not available'); - return new Promise((resolve, reject) => { - RCTAsyncStorage.multiMerge(keyValuePairs, function (errors) { - const error = convertErrors(errors); - callback && callback(error); - if (error) { - reject(error); - } else { - resolve(); - } - }); - }); - }, -}; - -// Not all native implementations support merge. -// TODO: Check whether above comment is correct. multiMerge is guaranteed to -// exist in the module spec so we should be able to just remove this check. -if (RCTAsyncStorage && !RCTAsyncStorage.multiMerge) { - // $FlowFixMe[unclear-type] - delete (AsyncStorage: any).mergeItem; - // $FlowFixMe[unclear-type] - delete (AsyncStorage: any).multiMerge; -} - -function convertErrors( - // NOTE: The native module spec only has the Array case, but the Android - // implementation passes a single object. - errs: ?( - | {message: string, key?: string} - | Array<{message: string, key?: string}> - ), -) { - if (!errs) { - return null; - } - return (Array.isArray(errs) ? errs : [errs]).map(e => convertError(e)); -} - -declare function convertError(void | null): null; -declare function convertError({message: string, key?: string}): Error; -/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's - * LTI update could not be added via codemod */ -function convertError(error) { - if (!error) { - return null; - } - const out = new Error(error.message); - // $FlowFixMe[unclear-type] - (out: any).key = error.key; - return out; -} - -module.exports = AsyncStorage; diff --git a/Libraries/Storage/NativeAsyncLocalStorage.js b/Libraries/Storage/NativeAsyncLocalStorage.js deleted file mode 100644 index 9070559cb639d4..00000000000000 --- a/Libraries/Storage/NativeAsyncLocalStorage.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -import type {TurboModule} from '../TurboModule/RCTExport'; - -import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getConstants: () => {}; - +multiGet: ( - keys: Array, - callback: ( - errors: ?Array<{message: string, key?: string}>, - kvPairs: ?Array>, - ) => void, - ) => void; - +multiSet: ( - kvPairs: Array>, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +multiMerge: ( - kvPairs: Array>, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +multiRemove: ( - keys: Array, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +clear: (callback: (error: {message: string, key?: string}) => void) => void; - +getAllKeys: ( - callback: ( - error: ?{message: string, key?: string}, - allKeys: ?Array, - ) => void, - ) => void; -} - -export default (TurboModuleRegistry.get('AsyncLocalStorage'): ?Spec); diff --git a/Libraries/Storage/NativeAsyncSQLiteDBStorage.js b/Libraries/Storage/NativeAsyncSQLiteDBStorage.js deleted file mode 100644 index ac0481f338e76f..00000000000000 --- a/Libraries/Storage/NativeAsyncSQLiteDBStorage.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -import type {TurboModule} from '../TurboModule/RCTExport'; - -import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getConstants: () => {}; - +multiGet: ( - keys: Array, - callback: ( - errors: ?Array<{message: string, key?: string}>, - kvPairs: ?Array>, - ) => void, - ) => void; - +multiSet: ( - kvPairs: Array>, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +multiMerge: ( - kvPairs: Array>, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +multiRemove: ( - keys: Array, - callback: (errors: ?Array<{message: string, key?: string}>) => void, - ) => void; - +clear: (callback: (error: {message: string, key?: string}) => void) => void; - +getAllKeys: ( - callback: ( - error: ?{message: string, key?: string}, - allKeys: ?Array, - ) => void, - ) => void; -} - -export default (TurboModuleRegistry.get('AsyncSQLiteDBStorage'): ?Spec); diff --git a/index.js b/index.js index 255b3e6af1a43a..d33faf0bd9636d 100644 --- a/index.js +++ b/index.js @@ -51,7 +51,6 @@ import typeof * as AnimatedModule from './Libraries/Animated/Animated'; import typeof Appearance from './Libraries/Utilities/Appearance'; import typeof AppRegistry from './Libraries/ReactNative/AppRegistry'; import typeof AppState from './Libraries/AppState/AppState'; -import typeof AsyncStorage from './Libraries/Storage/AsyncStorage'; import typeof BackHandler from './Libraries/Utilities/BackHandler'; import typeof Clipboard from './Libraries/Components/Clipboard/Clipboard'; import typeof DeviceInfo from './Libraries/Utilities/DeviceInfo'; @@ -252,16 +251,6 @@ module.exports = { get AppState(): AppState { return require('./Libraries/AppState/AppState'); }, - // $FlowFixMe[value-as-type] - get AsyncStorage(): AsyncStorage { - warnOnce( - 'async-storage-moved', - 'AsyncStorage has been extracted from react-native core and will be removed in a future release. ' + - "It can now be installed and imported from '@react-native-async-storage/async-storage' instead of 'react-native'. " + - 'See https://github.com/react-native-async-storage/async-storage', - ); - return require('./Libraries/Storage/AsyncStorage'); - }, get BackHandler(): BackHandler { return require('./Libraries/Utilities/BackHandler'); }, @@ -761,4 +750,19 @@ if (__DEV__) { ); }, }); + /* $FlowFixMe[prop-missing] This is intentional: Flow will error when + * attempting to access AsyncStorage. */ + /* $FlowFixMe[invalid-export] This is intentional: Flow will error when + * attempting to access AsyncStorage. */ + Object.defineProperty(module.exports, 'AsyncStorage', { + configurable: true, + get() { + invariant( + false, + 'AsyncStorage has been removed from react-native core. ' + + "It can now be installed and imported from '@react-native-async-storage/async-storage' instead of 'react-native'. " + + 'See https://github.com/react-native-async-storage/async-storage', + ); + }, + }); } diff --git a/types/__typetests__/index.tsx b/types/__typetests__/index.tsx index 9e74cc4c675e95..f530b0702fcbf8 100644 --- a/types/__typetests__/index.tsx +++ b/types/__typetests__/index.tsx @@ -25,7 +25,6 @@ import * as React from 'react'; import { AccessibilityInfo, ActionSheetIOS, - AsyncStorage, Alert, AppState, AppStateStatus, diff --git a/types/index.d.ts b/types/index.d.ts index 4a392cd742f240..fe2e5b056b6145 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -135,7 +135,6 @@ export * from '../Libraries/Renderer/implementations/ReactNativeRenderer'; export * from '../Libraries/Renderer/shims/ReactNativeTypes'; export * from '../Libraries/Settings/Settings'; export * from '../Libraries/Share/Share'; -export * from '../Libraries/Storage/AsyncStorage'; export * from '../Libraries/StyleSheet/PlatformColorValueTypesIOS'; export * from '../Libraries/StyleSheet/PlatformColorValueTypes'; export * from '../Libraries/StyleSheet/StyleSheet'; From 8f124be40e83550f757ce95c605df7d80fb81923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Mon, 31 Oct 2022 15:30:02 -0700 Subject: [PATCH 089/169] Hermes scripts: rename tarball methods to distinguish between source code and prebuilt artifacts (#35156) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35156 There are two tarballs: the source code for Hermes that is downloaded from GitHub, and the hermes-runtime-darwin-{}-v{}.tar.gz tarball with prebuilt artifacts that is built in CI. Renamed some methods to make it clearer which tarball they work with. Changelog: [internal] Reviewed By: cipolleschi, dmytrorykun Differential Revision: D40812290 fbshipit-source-id: a2c865e1d1461829fe8d468f52deeb55f3565cb0 --- scripts/__tests__/hermes-utils-test.js | 40 +++++++++++----------- scripts/hermes/create-tarball.js | 4 +-- scripts/hermes/get-tarball-name.js | 7 ++-- scripts/hermes/hermes-utils.js | 26 ++++++++------ scripts/hermes/prepare-hermes-for-build.js | 8 ++--- 5 files changed, 46 insertions(+), 39 deletions(-) diff --git a/scripts/__tests__/hermes-utils-test.js b/scripts/__tests__/hermes-utils-test.js index 16d694399998c0..68ee3edabab179 100644 --- a/scripts/__tests__/hermes-utils-test.js +++ b/scripts/__tests__/hermes-utils-test.js @@ -13,9 +13,9 @@ const { configureMakeForPrebuiltHermesC, copyBuildScripts, copyPodSpec, - downloadHermesTarball, - expandHermesTarball, - getHermesTarballName, + downloadHermesSourceTarball, + expandHermesSourceTarball, + getHermesPrebuiltArtifactsTarballName, getHermesTagSHA, readHermesTag, setHermesTag, @@ -155,29 +155,29 @@ describe('hermes-utils', () => { expect(readHermesTag()).toEqual(hermesTag); }); }); - describe('getHermesTarballName', () => { + describe('getHermesPrebuiltArtifactsTarballName', () => { it('should return Hermes tarball name', () => { - expect(getHermesTarballName('Debug', '1000.0.0')).toEqual( - 'hermes-runtime-darwin-debug-v1000.0.0.tar.gz', - ); + expect( + getHermesPrebuiltArtifactsTarballName('Debug', '1000.0.0'), + ).toEqual('hermes-runtime-darwin-debug-v1000.0.0.tar.gz'); }); it('should throw if build type is undefined', () => { expect(() => { - getHermesTarballName(); + getHermesPrebuiltArtifactsTarballName(); }).toThrow('Did not specify build type.'); }); it('should throw if release version is undefined', () => { expect(() => { - getHermesTarballName('Release'); + getHermesPrebuiltArtifactsTarballName('Release'); }).toThrow('Did not specify release version.'); }); it('should return debug Hermes tarball name for RN 0.70.0', () => { - expect(getHermesTarballName('Debug', '0.70.0')).toEqual( + expect(getHermesPrebuiltArtifactsTarballName('Debug', '0.70.0')).toEqual( 'hermes-runtime-darwin-debug-v0.70.0.tar.gz', ); }); it('should return a wildcard Hermes tarball name for any RN version', () => { - expect(getHermesTarballName('Debug', '*')).toEqual( + expect(getHermesPrebuiltArtifactsTarballName('Debug', '*')).toEqual( 'hermes-runtime-darwin-debug-v*.tar.gz', ); }); @@ -188,10 +188,10 @@ describe('hermes-utils', () => { expect(execCalls.git).toBe(true); }); }); - describe('downloadHermesTarball', () => { - it('should download Hermes tarball to download dir', () => { + describe('downloadHermesSourceTarball', () => { + it('should download Hermes source tarball to download dir', () => { fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); - downloadHermesTarball(); + downloadHermesSourceTarball(); expect(execCalls.curl).toBe(true); expect( fs.readFileSync( @@ -210,25 +210,25 @@ describe('hermes-utils', () => { tarballContents, ); - downloadHermesTarball(); + downloadHermesSourceTarball(); expect(execCalls.curl).toBeUndefined(); }); }); - describe('expandHermesTarball', () => { - it('should expand Hermes tarball to Hermes source dir', () => { + describe('expandHermesSourceTarball', () => { + it('should expand Hermes source tarball to Hermes source dir', () => { fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); fs.writeFileSync( path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), tarballContents, ); expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBeFalsy(); - expandHermesTarball(); + expandHermesSourceTarball(); expect(execCalls.tar).toBe(true); expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBe(true); }); - it('should fail if Hermes tarball does not exist', () => { + it('should fail if Hermes source tarball does not exist', () => { expect(() => { - expandHermesTarball(); + expandHermesSourceTarball(); }).toThrow('[Hermes] Could not locate Hermes tarball.'); expect(execCalls.tar).toBeUndefined(); }); diff --git a/scripts/hermes/create-tarball.js b/scripts/hermes/create-tarball.js index 135a580b71db31..b41278ae1d6629 100644 --- a/scripts/hermes/create-tarball.js +++ b/scripts/hermes/create-tarball.js @@ -18,7 +18,7 @@ const path = require('path'); * Must be invoked after Hermes has been built. */ const yargs = require('yargs'); -const {createHermesTarball} = require('./hermes-utils'); +const {createHermesPrebuiltArtifactsTarball} = require('./hermes-utils'); let argv = yargs .option('i', { @@ -60,7 +60,7 @@ async function main() { } } - const tarballOutputPath = createHermesTarball( + const tarballOutputPath = createHermesPrebuiltArtifactsTarball( hermesDir, buildType, releaseVersion, diff --git a/scripts/hermes/get-tarball-name.js b/scripts/hermes/get-tarball-name.js index 274ca640e9b9e7..918b8c1004ea7e 100644 --- a/scripts/hermes/get-tarball-name.js +++ b/scripts/hermes/get-tarball-name.js @@ -14,7 +14,7 @@ * Hermes tarball for the given build type and release version. */ const yargs = require('yargs'); -const {getHermesTarballName} = require('./hermes-utils'); +const {getHermesPrebuiltArtifactsTarballName} = require('./hermes-utils'); let argv = yargs .option('b', { @@ -31,7 +31,10 @@ let argv = yargs }).argv; async function main() { - const tarballName = getHermesTarballName(argv.buildType, argv.releaseVersion); + const tarballName = getHermesPrebuiltArtifactsTarballName( + argv.buildType, + argv.releaseVersion, + ); console.log(tarballName); return tarballName; } diff --git a/scripts/hermes/hermes-utils.js b/scripts/hermes/hermes-utils.js index 79caaffff49103..f881784ad809e6 100644 --- a/scripts/hermes/hermes-utils.js +++ b/scripts/hermes/hermes-utils.js @@ -17,7 +17,8 @@ const {execSync} = require('child_process'); const SDKS_DIR = path.normalize(path.join(__dirname, '..', '..', 'sdks')); const HERMES_DIR = path.join(SDKS_DIR, 'hermes'); const HERMES_TAG_FILE_PATH = path.join(SDKS_DIR, '.hermesversion'); -const HERMES_TARBALL_BASE_URL = 'https://github.com/facebook/hermes/tarball/'; +const HERMES_SOURCE_TARBALL_BASE_URL = + 'https://github.com/facebook/hermes/tarball/'; const HERMES_TARBALL_DOWNLOAD_DIR = path.join(SDKS_DIR, 'download'); const MACOS_BIN_DIR = path.join(SDKS_DIR, 'hermesc', 'osx-bin'); const MACOS_HERMESC_PATH = path.join(MACOS_BIN_DIR, 'hermesc'); @@ -71,11 +72,11 @@ function getHermesTarballDownloadPath(hermesTag) { return path.join(HERMES_TARBALL_DOWNLOAD_DIR, `hermes-${hermesTagSHA}.tgz`); } -function downloadHermesTarball() { +function downloadHermesSourceTarball() { const hermesTag = readHermesTag(); const hermesTagSHA = getHermesTagSHA(hermesTag); const hermesTarballDownloadPath = getHermesTarballDownloadPath(hermesTag); - let hermesTarballUrl = HERMES_TARBALL_BASE_URL + hermesTag; + let hermesTarballUrl = HERMES_SOURCE_TARBALL_BASE_URL + hermesTag; if (fs.existsSync(hermesTarballDownloadPath)) { return; @@ -95,7 +96,7 @@ function downloadHermesTarball() { } } -function expandHermesTarball() { +function expandHermesSourceTarball() { const hermesTag = readHermesTag(); const hermesTagSHA = getHermesTagSHA(hermesTag); const hermesTarballDownloadPath = getHermesTarballDownloadPath(hermesTag); @@ -196,7 +197,7 @@ set_target_properties(native-hermesc PROPERTIES } } -function getHermesTarballName(buildType, releaseVersion) { +function getHermesPrebuiltArtifactsTarballName(buildType, releaseVersion) { if (!buildType) { throw Error('Did not specify build type.'); } @@ -206,7 +207,7 @@ function getHermesTarballName(buildType, releaseVersion) { return `hermes-runtime-darwin-${buildType.toLowerCase()}-v${releaseVersion}.tar.gz`; } -function createHermesTarball( +function createHermesPrebuiltArtifactsTarball( hermesDir, buildType, releaseVersion, @@ -245,7 +246,10 @@ function createHermesTarball( throw new Error(`Failed to copy destroot to tempdir: ${error}`); } - const tarballFilename = getHermesTarballName(buildType, releaseVersion); + const tarballFilename = getHermesPrebuiltArtifactsTarballName( + buildType, + releaseVersion, + ); const tarballOutputPath = path.join(tarballOutputDir, tarballFilename); try { @@ -267,11 +271,11 @@ module.exports = { configureMakeForPrebuiltHermesC, copyBuildScripts, copyPodSpec, - createHermesTarball, - downloadHermesTarball, - expandHermesTarball, + createHermesPrebuiltArtifactsTarball, + downloadHermesSourceTarball, + expandHermesSourceTarball, getHermesTagSHA, - getHermesTarballName, + getHermesPrebuiltArtifactsTarballName, readHermesTag, setHermesTag, shouldBuildHermesFromSource, diff --git a/scripts/hermes/prepare-hermes-for-build.js b/scripts/hermes/prepare-hermes-for-build.js index 140d9f3a4380d0..87792738e7c00a 100644 --- a/scripts/hermes/prepare-hermes-for-build.js +++ b/scripts/hermes/prepare-hermes-for-build.js @@ -17,8 +17,8 @@ const { configureMakeForPrebuiltHermesC, copyBuildScripts, copyPodSpec, - downloadHermesTarball, - expandHermesTarball, + downloadHermesSourceTarball, + expandHermesSourceTarball, shouldUsePrebuiltHermesC, shouldBuildHermesFromSource, } = require('./hermes-utils'); @@ -28,8 +28,8 @@ async function main(isInCI) { copyPodSpec(); return; } - downloadHermesTarball(); - expandHermesTarball(); + downloadHermesSourceTarball(); + expandHermesSourceTarball(); copyPodSpec(); copyBuildScripts(); From 07bd590843bf84c0196086f56f46ebd0d236b1ef Mon Sep 17 00:00:00 2001 From: George Zahariev Date: Mon, 31 Oct 2022 15:31:29 -0700 Subject: [PATCH 090/169] exact_empty_objects is on by default in 0.191, delete usage in fbsource Summary: `exact_empty_objects` is on by default in 0.191, delete usage Changelog: [Internal] Reviewed By: SamChou19815 Differential Revision: D40822684 fbshipit-source-id: 8e84f0542e6b66049cac34e429f0b724f85a9557 --- .flowconfig | 1 - .flowconfig.android | 1 - 2 files changed, 2 deletions(-) diff --git a/.flowconfig b/.flowconfig index 31885ce0546457..9862b98d35dbdb 100644 --- a/.flowconfig +++ b/.flowconfig @@ -32,7 +32,6 @@ flow/ emoji=true exact_by_default=true -exact_empty_objects=true format.bracket_spacing=false diff --git a/.flowconfig.android b/.flowconfig.android index fac572dc5e490a..ba1090d54053c5 100644 --- a/.flowconfig.android +++ b/.flowconfig.android @@ -32,7 +32,6 @@ flow/ emoji=true exact_by_default=true -exact_empty_objects=true format.bracket_spacing=false From 745e26288c656237b0f86f6cfc55643eeb0817ca Mon Sep 17 00:00:00 2001 From: Marco Fiorito Date: Mon, 31 Oct 2022 16:23:54 -0700 Subject: [PATCH 091/169] refactor(rn tester app): change dimensions example to hooks (#35084) Summary: This pull request migrates the dimensions example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate Dimensions to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/35084 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: yungsters Differential Revision: D40779014 Pulled By: NickGerleman fbshipit-source-id: e740684d3022a945da5abc33b2e8834c6cfabb97 --- .../examples/Dimensions/DimensionsExample.js | 36 ++++++------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js index 008ae41cc9ca9b..8e8d1a28da41a4 100644 --- a/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js +++ b/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js @@ -8,38 +8,24 @@ * @flow */ -import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; import {Dimensions, Text, useWindowDimensions} from 'react-native'; import * as React from 'react'; +import {useState, useEffect} from 'react'; -class DimensionsSubscription extends React.Component< - {dim: string, ...}, - {dims: Object, ...}, -> { - state: {dims: any, ...} = { - dims: Dimensions.get(this.props.dim), - }; +type Props = {dim: string}; - _dimensionsSubscription: ?EventSubscription; +function DimensionsSubscription(props: Props) { + const [dims, setDims] = useState(() => Dimensions.get(props.dim)); - componentDidMount() { - this._dimensionsSubscription = Dimensions.addEventListener( - 'change', - dimensions => { - this.setState({ - dims: dimensions[this.props.dim], - }); - }, - ); - } + useEffect(() => { + const subscription = Dimensions.addEventListener('change', dimensions => { + setDims(dimensions[props.dim]); + }); - componentWillUnmount() { - this._dimensionsSubscription?.remove(); - } + return () => subscription.remove(); + }, [props.dim]); - render(): React.Node { - return {JSON.stringify(this.state.dims, null, 2)}; - } + return {JSON.stringify(dims, null, 2)}; } const DimensionsViaHook = () => { From 1e6945e19e306bec6bfc77063e9760567b4b1a97 Mon Sep 17 00:00:00 2001 From: Oleksandr Melnykov Date: Mon, 31 Oct 2022 23:01:40 -0700 Subject: [PATCH 092/169] Back out "Add perftest dev support manager" Summary: Changelog: [Internal] Reviewed By: NickGerleman Differential Revision: D40879099 fbshipit-source-id: ff302819829aa21a1dd7c19c06ed8c29821ba815 --- .../DefaultDevSupportManagerFactory.java | 4 -- .../devsupport/PerftestDevSupportManager.java | 56 ------------------- 2 files changed, 60 deletions(-) delete mode 100644 ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java index 2a55a36c5b0675..97862539f424f2 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java @@ -10,7 +10,6 @@ import android.content.Context; import androidx.annotation.Nullable; import com.facebook.react.common.SurfaceDelegateFactory; -import com.facebook.react.common.build.ReactBuildConfig; import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener; import com.facebook.react.devsupport.interfaces.DevSupportManager; import com.facebook.react.devsupport.interfaces.RedBoxHandler; @@ -62,9 +61,6 @@ public DevSupportManager create( if (!enableOnCreate) { return new DisabledDevSupportManager(); } - if (!ReactBuildConfig.DEBUG) { - return new PerftestDevSupportManager(applicationContext); - } try { // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to // Class.forName() with a static string. So instead we generate a quasi-dynamic string to diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java deleted file mode 100644 index 2be621fc38ff6a..00000000000000 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.devsupport; - -import android.content.Context; - -/** - * Interface for accessing and interacting with development features related to performance testing. - * Communication is enabled via the Inspector, but everything else is disabled. - */ -public final class PerftestDevSupportManager extends DisabledDevSupportManager { - private final DevServerHelper mDevServerHelper; - private final DevInternalSettings mDevSettings; - private final InspectorPackagerConnection.BundleStatus mBundleStatus; - - public PerftestDevSupportManager(Context applicationContext) { - mDevSettings = - new DevInternalSettings( - applicationContext, - new DevInternalSettings.Listener() { - @Override - public void onInternalSettingsChanged() {} - }); - mBundleStatus = new InspectorPackagerConnection.BundleStatus(); - mDevServerHelper = - new DevServerHelper( - mDevSettings, - applicationContext.getPackageName(), - new InspectorPackagerConnection.BundleStatusProvider() { - @Override - public InspectorPackagerConnection.BundleStatus getBundleStatus() { - return mBundleStatus; - } - }); - } - - @Override - public DevInternalSettings getDevSettings() { - return mDevSettings; - } - - @Override - public void startInspector() { - mDevServerHelper.openInspectorConnection(); - } - - @Override - public void stopInspector() { - mDevServerHelper.closeInspectorConnection(); - } -} From 40ad31eacf29e83ba91031b714c4de1f4d22e469 Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Tue, 1 Nov 2022 07:47:23 -0700 Subject: [PATCH 093/169] Set C++ version for libs (#35160) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35160 With the simplified migration to the new arch, we are offering a function in cocoapods that takes care of configuring all the dependencies for libraries. That function was not setting the proper version of C++ for the library. This could lead to build problems. This Diff make sure that the libraries that are created with this function call have the proper C++ version. NOTE: we already have a post install hook that was setting the the proper C++ version, but that was only working for the project. Plus, we can't read that version from the React-Core podspec because at the podspec definition time, cocoapods has not read that yet. Therefore, I just hardcoded the C++ version on top of the file, so it will be easier to update if we decide to change it. ## Changelog [iOS][Fixed] - Make sure that libraries created with `install_modules_dependencies` has the right C++ version. Reviewed By: dmytrorykun Differential Revision: D40894561 fbshipit-source-id: a5187be2d85888a335d4c033f16fdacaf2c945f9 --- scripts/cocoapods/__tests__/new_architecture-test.rb | 2 ++ scripts/cocoapods/new_architecture.rb | 3 +++ 2 files changed, 5 insertions(+) diff --git a/scripts/cocoapods/__tests__/new_architecture-test.rb b/scripts/cocoapods/__tests__/new_architecture-test.rb index a3ee9fd3ff5d6e..2f1c3cad1aa5ba 100644 --- a/scripts/cocoapods/__tests__/new_architecture-test.rb +++ b/scripts/cocoapods/__tests__/new_architecture-test.rb @@ -124,6 +124,7 @@ def test_installModulesDependencies_whenNewArchEnabledAndNewArchAndNoSearchPaths # Assert assert_equal(spec.compiler_flags, NewArchitectureHelper.folly_compiler_flags) assert_equal(spec.pod_target_xcconfig["HEADER_SEARCH_PATHS"], "\"$(PODS_ROOT)/boost\"") + assert_equal(spec.pod_target_xcconfig["CLANG_CXX_LANGUAGE_STANDARD"], "c++17") assert_equal( spec.dependencies, [ @@ -152,6 +153,7 @@ def test_installModulesDependencies_whenNewArchDisabledAndSearchPathsAndCompiler # Assert assert_equal(spec.compiler_flags, "-Wno-nullability-completeness #{NewArchitectureHelper.folly_compiler_flags}") assert_equal(spec.pod_target_xcconfig["HEADER_SEARCH_PATHS"], "#{other_flags} \"$(PODS_ROOT)/boost\"") + assert_equal(spec.pod_target_xcconfig["CLANG_CXX_LANGUAGE_STANDARD"], "c++17") assert_equal( spec.dependencies, [ diff --git a/scripts/cocoapods/new_architecture.rb b/scripts/cocoapods/new_architecture.rb index 24a9f076e6c046..5382b8fb2e5b80 100644 --- a/scripts/cocoapods/new_architecture.rb +++ b/scripts/cocoapods/new_architecture.rb @@ -10,6 +10,8 @@ class NewArchitectureHelper @@new_arch_cpp_flags = "$(inherited) -DRCT_NEW_ARCH_ENABLED=1 #{@@shared_flags}" + @@cplusplus_version = "c++17" + def self.set_clang_cxx_language_standard_if_needed(installer) language_standard = nil @@ -73,6 +75,7 @@ def self.install_modules_dependencies(spec, new_arch_enabled, folly_version) spec.compiler_flags = compiler_flags.empty? ? @@folly_compiler_flags : "#{compiler_flags} #{@@folly_compiler_flags}" current_config["HEADER_SEARCH_PATHS"] = current_headers.empty? ? boost_search_path : "#{current_headers} #{boost_search_path}" + current_config["CLANG_CXX_LANGUAGE_STANDARD"] = @@cplusplus_version spec.pod_target_xcconfig = current_config spec.dependency "React-Core" From f49b2517d739ab129aae44d4ddab01748a96301c Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Tue, 1 Nov 2022 10:45:24 -0700 Subject: [PATCH 094/169] React Native sync for revisions 54f297a...ab075a2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: This sync includes the following changes: - **[ab075a232](https://github.com/facebook/react/commit/ab075a232 )**: Do not unmount layout effects on initial Offscreen mount ([#25592](https://github.com/facebook/react/pull/25592)) //// - **[765805bf8](https://github.com/facebook/react/commit/765805bf8 )**: Fix type check for null ([#25595](https://github.com/facebook/react/pull/25595)) //// - **[2ac77aab9](https://github.com/facebook/react/commit/2ac77aab9 )**: Clean up vestige of useOpaqueIdentifier ([#25587](https://github.com/facebook/react/pull/25587)) //// - **[bdd3d0807](https://github.com/facebook/react/commit/bdd3d0807 )**: Extract logic for detecting bad fallback to helper //// - **[952dfff3f](https://github.com/facebook/react/commit/952dfff3f )**: Split suspended work loop logic into separate functions //// - **[d2c0ab10d](https://github.com/facebook/react/commit/d2c0ab10d )**: In work loop, add enum of reasons for suspending //// - **[5450dd409](https://github.com/facebook/react/commit/5450dd409 )**: Strict Mode: Reuse memoized result from first pass ([#25583](https://github.com/facebook/react/pull/25583)) //// - **[d2a0176a1](https://github.com/facebook/react/commit/d2a0176a1 )**: Detect and warn if use(promise) is wrapped with try/catch block ([#25543](https://github.com/facebook/react/pull/25543)) //// - **[cf3932be5](https://github.com/facebook/react/commit/cf3932be5 )**: Remove old react-fetch, react-fs and react-pg libraries ([#25577](https://github.com/facebook/react/pull/25577)) //// - **[28a574ea8](https://github.com/facebook/react/commit/28a574ea8 )**: Try assigning fetch to globalThis if global assignment fails ([#25571](https://github.com/facebook/react/pull/25571)) //// - **[09def5990](https://github.com/facebook/react/commit/09def5990 )**: [Float] handle noscript context for Resources ([#25559](https://github.com/facebook/react/pull/25559)) //// - **[17204056d](https://github.com/facebook/react/commit/17204056d )**: [Float] fix coordination of resource identity and hydration ([#25569](https://github.com/facebook/react/pull/25569)) //// - **[d925a8d0b](https://github.com/facebook/react/commit/d925a8d0b )**: Flight client error stack ([#25560](https://github.com/facebook/react/pull/25560)) //// - **[996b00b78](https://github.com/facebook/react/commit/996b00b78 )**: [Tiny] Fixed incorrect import in `react-server-dom-webpack` ([#25554](https://github.com/facebook/react/pull/25554)) //// - **[e7c5af45c](https://github.com/facebook/react/commit/e7c5af45c )**: Update cache() and use() to the canary aka next channel ([#25502](https://github.com/facebook/react/pull/25502)) //// - **[fa77f52e7](https://github.com/facebook/react/commit/fa77f52e7 )**: Unify promise switch statements //// - **[7572e4931](https://github.com/facebook/react/commit/7572e4931 )**: Track thenable state in work loop //// - **[7fc3eefd8](https://github.com/facebook/react/commit/7fc3eefd8 )**: Revert yieldy behavior for non-use Suspense (in Flight, too) //// - **[61f9b5e97](https://github.com/facebook/react/commit/61f9b5e97 )**: [Float] support as Resource ([#25546](https://github.com/facebook/react/pull/25546)) //// - **[1d3fc9c9c](https://github.com/facebook/react/commit/1d3fc9c9c )**: Bug fix when resolving cache ([#25545](https://github.com/facebook/react/pull/25545)) //// - **[cce18e350](https://github.com/facebook/react/commit/cce18e350 )**: [Flight] Use AsyncLocalStorage to extend the scope of the cache to micro tasks ([#25542](https://github.com/facebook/react/pull/25542)) //// - **[caa84c8da](https://github.com/facebook/react/commit/caa84c8da )**: Revert fetch instrumentation to only RSC ([#25540](https://github.com/facebook/react/pull/25540)) //// - **[0c11baa6a](https://github.com/facebook/react/commit/0c11baa6a )**: add warnings for non-resources rendered outside body or head ([#25532](https://github.com/facebook/react/pull/25532)) //// - **[9236abdb5](https://github.com/facebook/react/commit/9236abdb5 )**: when float is enabled only push title and script as a single unit ([#25536](https://github.com/facebook/react/pull/25536)) //// - **[dd5c20825](https://github.com/facebook/react/commit/dd5c20825 )**: Revert yieldy behavior for non-use Suspense ([#25537](https://github.com/facebook/react/pull/25537)) //// - **[934177598](https://github.com/facebook/react/commit/934177598 )**: fix transposed escape functions ([#25534](https://github.com/facebook/react/pull/25534)) //// - **[d1ced9fd5](https://github.com/facebook/react/commit/d1ced9fd5 )**: [Float] support all links as Resources ([#25515](https://github.com/facebook/react/pull/25515)) //// - **[973b90bdf](https://github.com/facebook/react/commit/973b90bdf )**: [Float] support meta tags as Resources ([#25514](https://github.com/facebook/react/pull/25514)) //// - **[79c582981](https://github.com/facebook/react/commit/79c582981 )**: Let ReactDOM initialize in RSC ([#25503](https://github.com/facebook/react/pull/25503)) //// - **[1f7a2f577](https://github.com/facebook/react/commit/1f7a2f577 )**: [Float] support title tags as Resources ([#25508](https://github.com/facebook/react/pull/25508)) //// - **[c63580787](https://github.com/facebook/react/commit/c63580787 )**: Support `use` in `act` testing API ([#25523](https://github.com/facebook/react/pull/25523)) //// - **[65e32e58b](https://github.com/facebook/react/commit/65e32e58b )**: Add fetch Instrumentation to Dedupe Fetches ([#25516](https://github.com/facebook/react/pull/25516)) //// - **[9336e29d9](https://github.com/facebook/react/commit/9336e29d9 )**: [useEvent] Lint for presence of useEvent functions in dependency lists ([#25512](https://github.com/facebook/react/pull/25512)) //// - **[3cc792bfb](https://github.com/facebook/react/commit/3cc792bfb )**: [useEvent] Non-stable function identity ([#25473](https://github.com/facebook/react/pull/25473)) //// - **[987292815](https://github.com/facebook/react/commit/987292815 )**: Remove feature flag enableStrictEffects ([#25387](https://github.com/facebook/react/pull/25387)) //// - **[8e2bde6f2](https://github.com/facebook/react/commit/8e2bde6f2 )**: Add cache() API ([#25506](https://github.com/facebook/react/pull/25506)) //// - **[9cdf8a99e](https://github.com/facebook/react/commit/9cdf8a99e )**: [Codemod] Update copyright header to Meta ([#25315](https://github.com/facebook/react/pull/25315)) //// - **[e54015e26](https://github.com/facebook/react/commit/e54015e26 )**: Refactor: fill in the flow missing type ([#25496](https://github.com/facebook/react/pull/25496)) //// - **[3b1fd5767](https://github.com/facebook/react/commit/3b1fd5767 )**: refactor: Flow: typing of Scheduler ([#25485](https://github.com/facebook/react/pull/25485)) //// - **[14072ce64](https://github.com/facebook/react/commit/14072ce64 )**: Add detach to Offscreen component ([#25265](https://github.com/facebook/react/pull/25265)) //// - **[3bb71dfd4](https://github.com/facebook/react/commit/3bb71dfd4 )**: Rename react-server-dom-webpack entry points to /client and /server ([#25504](https://github.com/facebook/react/pull/25504)) //// - **[71f2c8cf1](https://github.com/facebook/react/commit/71f2c8cf1 )**: move resource acquisition to mutation phase ([#25500](https://github.com/facebook/react/pull/25500)) //// - **[500bea532](https://github.com/facebook/react/commit/500bea532 )**: Add option to load Fizz runtime from external file ([#25499](https://github.com/facebook/react/pull/25499)) //// - **[4494f2a86](https://github.com/facebook/react/commit/4494f2a86 )**: [Float] add support for scripts and other enhancements ([#25480](https://github.com/facebook/react/pull/25480)) //// - **[9ecf84ed7](https://github.com/facebook/react/commit/9ecf84ed7 )**: Bugfix: Suspending in shell during discrete update ([#25495](https://github.com/facebook/react/pull/25495)) //// Changelog: [General][Changed] - React Native sync for revisions 54f297a...ab075a2 jest_e2e[run_all_tests] Reviewed By: kassens Differential Revision: D40897093 fbshipit-source-id: 6a040315834dea5c0ab994ea94d91f5605b9d6b0 --- Libraries/Renderer/REVISION | 2 +- .../implementations/ReactNativeRenderer.d.ts | 149 ------------------ Libraries/Renderer/shims/ReactFabric.js | 4 +- Libraries/Renderer/shims/ReactFeatureFlags.js | 4 +- Libraries/Renderer/shims/ReactNative.js | 4 +- .../Renderer/shims/ReactNativeTypes.d.ts | 141 ----------------- Libraries/Renderer/shims/ReactNativeTypes.js | 4 +- .../shims/ReactNativeViewConfigRegistry.js | 4 +- .../shims/createReactNativeComponentClass.js | 4 +- 9 files changed, 13 insertions(+), 303 deletions(-) delete mode 100644 Libraries/Renderer/implementations/ReactNativeRenderer.d.ts delete mode 100644 Libraries/Renderer/shims/ReactNativeTypes.d.ts diff --git a/Libraries/Renderer/REVISION b/Libraries/Renderer/REVISION index 2bed83bcc1cc0c..21e513e87f3c70 100644 --- a/Libraries/Renderer/REVISION +++ b/Libraries/Renderer/REVISION @@ -1 +1 @@ -54f297a60ce13d6f9ea385614498650c1935c572 \ No newline at end of file +ab075a232409ea1f566526c6a5dca30f658280de \ No newline at end of file diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts b/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts deleted file mode 100644 index 2624d4a78ce01d..00000000000000 --- a/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import {GestureResponderEvent} from '../../Types/CoreEventTypes'; - -/** - * Gesture recognition on mobile devices is much more complicated than web. - * A touch can go through several phases as the app determines what the user's intention is. - * For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. - * This can even change during the duration of a touch. There can also be multiple simultaneous touches. - * - * The touch responder system is needed to allow components to negotiate these touch interactions - * without any additional knowledge about their parent or child components. - * This system is implemented in ResponderEventPlugin.js, which contains further details and documentation. - * - * Best Practices - * Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. - * Every action should have the following attributes: - * Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture - * Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away - * - * These features make users more comfortable while using an app, - * because it allows people to experiment and interact without fear of making mistakes. - * - * TouchableHighlight and Touchable* - * The responder system can be complicated to use. - * So we have provided an abstract Touchable implementation for things that should be "tappable". - * This uses the responder system and allows you to easily configure tap interactions declaratively. - * Use TouchableHighlight anywhere where you would use a button or link on web. - */ -export interface GestureResponderHandlers { - /** - * A view can become the touch responder by implementing the correct negotiation methods. - * There are two methods to ask the view if it wants to become responder: - */ - - /** - * Does this view want to become responder on the start of a touch? - */ - onStartShouldSetResponder?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? - */ - onMoveShouldSetResponder?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * If the View returns true and attempts to become the responder, one of the following will happen: - */ - - onResponderEnd?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * The View is now responding for touch events. - * This is the time to highlight and show the user what is happening - */ - onResponderGrant?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Something else is the responder right now and will not release it - */ - onResponderReject?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * If the view is responding, the following handlers can be called: - */ - - /** - * The user is moving their finger - */ - onResponderMove?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Fired at the end of the touch, ie "touchUp" - */ - onResponderRelease?: ((event: GestureResponderEvent) => void) | undefined; - - onResponderStart?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Something else wants to become responder. - * Should this view release the responder? Returning true allows release - */ - onResponderTerminationRequest?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * The responder has been taken from the View. - * Might be taken by other views after a call to onResponderTerminationRequest, - * or might be taken by the OS without asking (happens with control center/ notification center on iOS) - */ - onResponderTerminate?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, - * where the deepest node is called first. - * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. - * This is desirable in most cases, because it makes sure all controls and buttons are usable. - * - * However, sometimes a parent will want to make sure that it becomes responder. - * This can be handled by using the capture phase. - * Before the responder system bubbles up from the deepest component, - * it will do a capture phase, firing on*ShouldSetResponderCapture. - * So if a parent View wants to prevent the child from becoming responder on a touch start, - * it should have a onStartShouldSetResponderCapture handler which returns true. - */ - onStartShouldSetResponderCapture?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, - * where the deepest node is called first. - * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. - * This is desirable in most cases, because it makes sure all controls and buttons are usable. - * - * However, sometimes a parent will want to make sure that it becomes responder. - * This can be handled by using the capture phase. - * Before the responder system bubbles up from the deepest component, - * it will do a capture phase, firing on*ShouldSetResponderCapture. - * So if a parent View wants to prevent the child from becoming responder on a touch start, - * it should have a onStartShouldSetResponderCapture handler which returns true. - */ - onMoveShouldSetResponderCapture?: - | ((event: GestureResponderEvent) => boolean) - | undefined; -} - -/** - * React Native also implements unstable_batchedUpdates - */ -export function unstable_batchedUpdates( - callback: (a: A, b: B) => any, - a: A, - b: B, -): void; -export function unstable_batchedUpdates(callback: (a: A) => any, a: A): void; -export function unstable_batchedUpdates(callback: () => any): void; diff --git a/Libraries/Renderer/shims/ReactFabric.js b/Libraries/Renderer/shims/ReactFabric.js index e9897f032c32e2..6ce97d99526678 100644 --- a/Libraries/Renderer/shims/ReactFabric.js +++ b/Libraries/Renderer/shims/ReactFabric.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow - * @generated SignedSource<> + * @generated SignedSource<> * * This file was sync'd from the facebook/react repository. */ diff --git a/Libraries/Renderer/shims/ReactFeatureFlags.js b/Libraries/Renderer/shims/ReactFeatureFlags.js index d7101030a3e21f..19914b304c53ac 100644 --- a/Libraries/Renderer/shims/ReactFeatureFlags.js +++ b/Libraries/Renderer/shims/ReactFeatureFlags.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow strict-local - * @generated SignedSource<> + * @generated SignedSource<<47062f1b1abd7428381f0362986d9c0e>> * * This file was sync'd from the facebook/react repository. */ diff --git a/Libraries/Renderer/shims/ReactNative.js b/Libraries/Renderer/shims/ReactNative.js index eb3322c0cff28a..e2cff0253cc08d 100644 --- a/Libraries/Renderer/shims/ReactNative.js +++ b/Libraries/Renderer/shims/ReactNative.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow - * @generated SignedSource<<45ec3626ad048b08dac9b031b02bc0a8>> + * @generated SignedSource<<744176db456e2656dac661d36e55f42a>> * * This file was sync'd from the facebook/react repository. */ diff --git a/Libraries/Renderer/shims/ReactNativeTypes.d.ts b/Libraries/Renderer/shims/ReactNativeTypes.d.ts deleted file mode 100644 index 38e00e1cc933ca..00000000000000 --- a/Libraries/Renderer/shims/ReactNativeTypes.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import type * as React from 'react'; - -export type MeasureOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, - pageX: number, - pageY: number, -) => void; - -export type MeasureInWindowOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, -) => void; - -export type MeasureLayoutOnSuccessCallback = ( - left: number, - top: number, - width: number, - height: number, -) => void; - -/** - * NativeMethods provides methods to access the underlying native component directly. - * This can be useful in cases when you want to focus a view or measure its on-screen dimensions, - * for example. - * The methods described here are available on most of the default components provided by React Native. - * Note, however, that they are not available on composite components that aren't directly backed by a - * native view. This will generally include most components that you define in your own app. - * For more information, see [Direct Manipulation](https://reactnative.dev/docs/direct-manipulation). - * @see https://github.com/facebook/react-native/blob/master/Libraries/Renderer/shims/ReactNativeTypes.js#L87 - */ -export interface NativeMethods { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure(callback: MeasureOnSuccessCallback): void; - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow(callback: MeasureInWindowOnSuccessCallback): void; - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeComponentRef`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * _Can also be called with a relativeNativeNodeHandle but is deprecated._ - */ - measureLayout( - relativeToNativeComponentRef: HostComponent | number, - onSuccess: MeasureLayoutOnSuccessCallback, - onFail: () => void /* currently unused */, - ): void; - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](https://reactnative.dev/docs/direct-manipulation)). - */ - setNativeProps(nativeProps: object): void; - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus(): void; - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur(): void; - - refs: { - [key: string]: React.Component; - }; -} - -/** - * @deprecated Use NativeMethods instead. - */ -export type NativeMethodsMixin = NativeMethods; -/** - * @deprecated Use NativeMethods instead. - */ -export type NativeMethodsMixinType = NativeMethods; - -/** - * Represents a native component, such as those returned from `requireNativeComponent`. - * - * @see https://github.com/facebook/react-native/blob/v0.62.0-rc.5/Libraries/Renderer/shims/ReactNativeTypes.js - * - * @todo This should eventually be defined as an AbstractComponent, but that - * should first be introduced in the React typings. - */ -export interface HostComponent

- extends Pick< - React.ComponentClass

, - Exclude, 'new'> - > { - new (props: P, context?: any): React.Component

& Readonly; -} diff --git a/Libraries/Renderer/shims/ReactNativeTypes.js b/Libraries/Renderer/shims/ReactNativeTypes.js index e1e8dfaff3b060..39ecaf5257a8b1 100644 --- a/Libraries/Renderer/shims/ReactNativeTypes.js +++ b/Libraries/Renderer/shims/ReactNativeTypes.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow strict - * @generated SignedSource<<81b3507b34f3a91f9bf71beb0f487340>> + * @generated SignedSource<> * * This file was sync'd from the facebook/react repository. */ diff --git a/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js b/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js index 589303502e6b62..d46f2f70abc4e5 100644 --- a/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js +++ b/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow strict-local - * @generated SignedSource<<825c6cbf78ba133c9a0ffdeace7f6fc0>> + * @generated SignedSource<> * * This file was sync'd from the facebook/react repository. */ diff --git a/Libraries/Renderer/shims/createReactNativeComponentClass.js b/Libraries/Renderer/shims/createReactNativeComponentClass.js index 51bf22b7965bba..e1aee01e405d83 100644 --- a/Libraries/Renderer/shims/createReactNativeComponentClass.js +++ b/Libraries/Renderer/shims/createReactNativeComponentClass.js @@ -1,12 +1,12 @@ /** - * Copyright (c) Facebook, Inc. and its affiliates. + * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat * @flow strict-local - * @generated SignedSource<<4f1549884fbe8fc2aea495692e3f665d>> + * @generated SignedSource<<7d3d4090dadea2daa09d92e5e66f6e5d>> * * This file was sync'd from the facebook/react repository. */ From 6b8e13f53c5fc9c5e794bb7491648e4b25ad5811 Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Tue, 1 Nov 2022 11:55:41 -0700 Subject: [PATCH 095/169] Integrate Hermes with the Xcode build process Summary: ## Context If React Native is built from *main* of any non-stable commit, then Hermes is built from source. The build is performed by `build-ios-framework.sh` and `build-mac-framework.sh` scripts in `hermes-engine.podspec` `prepare_command` stage. Since those scripts have no access build target information, they build all possible architectures and platforms just in case. That takes ages. ## Solution The idea is to integrate build script into Xcode *run script* phase, and use build target information to build Hermes for active architecture only. ## Implementation - Existing behaviour remains unchanged for local tarball and remote prebuild cases. - `build-hermesc-xcode.sh` builds Hermesc as `hermes-engine.podspec` `prepare_command`. Default build location is `react-native/sdks/hermes-engine/build_host_hermesc`. - `build-hermes-xcode.sh` builds Hermes in 'Build Hermes' Xcode script phase. It uses `$PLATFORM_NAME`, `$CONFIGURATION`, `$ARCHS`, `$IPHONEOS_DEPLOYMENT_TARGET` and `$MACOSX_DEPLOYMENT_TARGET` environment variables to configure cmake project so it builds only active architecture. The script also gets RN version, *cmake* path and *hermesc* path from the podspec. - `copy-hermes-xcode.sh` copies Hermes.framework inside the app bundle. This script phase is added to the user app target in a `post_install` hook, after pods are integrated in a user project. - `OTHER_LDFLAGS -framework "hermes"` added to the user project to enable linking against Hermes.framework. - If `HERMES_OVERRIDE_HERMESC_PATH` is set, then Hermesc building is skipped, and `HERMES_OVERRIDE_HERMESC_PATH` is used for `build-hermes-xcode.sh`. - `HERMES_CLI_PATH` is injected into user project config to enable Hermes source maps in `react-native-xcode.sh`. ## Things that didn't work - *Running build-hermesc-xcode.sh in Xcode run script phase*. This doesn't work because Hermesc is supposed to be built for macos, and if build target is ios, then Xcode configures environment in such a way that Hermesc build fails. - *Installing Hermesc into CocoaPods download folder*. So it then ends up in `Pods/hermes-engine/build_host_hermesc`, and all the housekeeping is handled by CocoaPods. This doesn't work because cmake uses absolute paths in a configured project. If configured project is moved to a different location, nothing builds. - *Installing Hermesc directly into Pods/hermes-engine*. This doesn't work because CocoaPods runs prepare_command before Pods folder clean up, and everything gets wiped. ## Known issue - If `Pods/hermes-engine` is manually removed, then `sdks/hermes-engine/build_host_hermesc` must also be removed before running `pod install`. Otherwise cmake will complain about stale cache: ``` CMake Error: The source "/hermes-engine//CMakeLists.txt" does not match the source "/hermes-engine//CMakeLists.txt" used to generate cache. Re-run cmake with a different source directory. ``` ## Benchmark MacBook M1 2021 32 GB. ``` export REACT_NATIVE_PATH=~/fbsource/xplat/js/react-native-github cd $REACT_NATIVE_PATH/packages/rn-tester pod install rm -rf $REACT_NATIVE_PATH/sdks/hermes-engine/build_host_hermesc cd $REACT_NATIVE_PATH/packages/rn-tester/Pods/hermes-engine echo 't1=$(date +%s); $@; t2=$(date +%s); diff=$(echo "$t2 - $t1" | bc); echo Operation took $diff seconds.' > /tmp/benchmark.sh ``` ``` # Before export BUILD_TYPE=Debug export JSI_PATH=$REACT_NATIVE_PATH/ReactCommon/jsi export RELEASE_VERSION=1000.0 export IOS_DEPLOYMENT_TARGET=iphonesimulator export MAC_DEPLOYMENT_TARGET=12.6 cd $REACT_NATIVE_PATH/packages/rn-tester/Pods/hermes-engine . /tmp/benchmark.sh $REACT_NATIVE_PATH/sdks/hermes-engine/utils/build-ios-framework.sh # Operation took 252 seconds . /tmp/benchmark.sh $REACT_NATIVE_PATH/sdks/hermes-engine/utils/build-mac-framework.sh # Operation took 179 seconds ``` ``` # After . /tmp/benchmark.sh source $REACT_NATIVE_PATH/sdks/hermes-engine/utils/build-hermesc-xcode.sh $REACT_NATIVE_PATH/sdks/hermes-engine/build_host_hermesc # Operation took 59 seconds. . /tmp/benchmark.sh xcodebuild -workspace $REACT_NATIVE_PATH/packages/rn-tester/RNTesterPods.xcworkspace -scheme hermes-engine # Operation took 106 seconds. ``` |Before|||After||| |--| |iOS framework (s)|Mac framework (s)|Total (s)|Hermesc (s)|Target-specific framework (s)|Total (s)| |252|179|431|59|106|**165 (-266) (-61%)**| The performance win is fixed, and does not depend on the project size and structure. As an example, this is how these changes affect build time of RNTester. |Before||||After||| |--| ||Pod install (s)|Xcode build (s)|Total (s)|Pod install (s)|Xcode build (s)|Total (s)| |Clean build|1219|132|1352|734 (-485)|249(+117)|**983 (-369)**| |Incremental build|82|30|112|105 (+23)|**34 (+4)**|139 (+27)| The most important values here are the total clean build time and the incremental Xcode build time. The first one went down by 369 seconds, the second one went up by 4 seconds. I consider it a reasonable tradeoff. The extra 4 seconds in the incremental Xcode build time can potentially be mitigated by setting up output file lists for the new script phases. allow-large-files Changelog: [iOS][Changed] - Hermes is integrated into Xcode build. Reviewed By: hramos Differential Revision: D40063686 fbshipit-source-id: e6993d62225789377db769244bc07786cc978a27 --- .gitignore | 1 + ReactCommon/hermes/React-hermes.podspec | 2 +- packages/rn-tester/Podfile.lock | 14 ++- scripts/cocoapods/jsengine.rb | 20 ++++ scripts/react_native_pods.rb | 6 + sdks/hermes-engine/hermes-engine.podspec | 105 ++++++++++++------ .../hermes-engine/utils/build-hermes-xcode.sh | 56 ++++++++++ .../utils/build-hermesc-xcode.sh | 22 ++++ sdks/hermes-engine/utils/copy-hermes-xcode.sh | 14 +++ 9 files changed, 200 insertions(+), 40 deletions(-) create mode 100644 sdks/hermes-engine/utils/build-hermes-xcode.sh create mode 100644 sdks/hermes-engine/utils/build-hermesc-xcode.sh create mode 100644 sdks/hermes-engine/utils/copy-hermes-xcode.sh diff --git a/.gitignore b/.gitignore index 6250ebcc4a8737..fadf52a7f1c187 100644 --- a/.gitignore +++ b/.gitignore @@ -122,6 +122,7 @@ package-lock.json /sdks/download /sdks/hermes /sdks/hermesc +/sdks/hermes-engine/build_host_hermesc # Visual studio .vscode diff --git a/ReactCommon/hermes/React-hermes.podspec b/ReactCommon/hermes/React-hermes.podspec index 0b6432596c828b..1a33547c2c43e3 100644 --- a/ReactCommon/hermes/React-hermes.podspec +++ b/ReactCommon/hermes/React-hermes.podspec @@ -40,7 +40,7 @@ Pod::Spec.new do |s| s.public_header_files = "executor/HermesExecutorFactory.h" s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags s.pod_target_xcconfig = { - "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/..\" \"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/libevent/include\"" + "HEADER_SEARCH_PATHS" => "\"${PODS_ROOT}/hermes-engine/destroot/include\" \"$(PODS_TARGET_SRCROOT)/..\" \"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/libevent/include\"" }.merge!(build_type == :debug ? { "GCC_PREPROCESSOR_DEFINITIONS" => "HERMES_ENABLE_DEBUGGER=1" } : {}) s.header_dir = "reacthermes" s.dependency "React-cxxreact", version diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index 4ed5001f3daf9f..db2169f72cc96d 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -73,7 +73,13 @@ PODS: - FlipperKit/FlipperKitNetworkPlugin - fmt (6.2.1) - glog (0.3.5) - - hermes-engine (1000.0.0) + - hermes-engine (1000.0.0): + - hermes-engine/Hermes (= 1000.0.0) + - hermes-engine/JSI (= 1000.0.0) + - hermes-engine/Public (= 1000.0.0) + - hermes-engine/Hermes (1000.0.0) + - hermes-engine/JSI (1000.0.0) + - hermes-engine/Public (1000.0.0) - libevent (2.1.12) - OpenSSL-Universal (1.1.1100) - RCT-Folly (2021.07.22.00): @@ -933,7 +939,7 @@ SPEC CHECKSUMS: CocoaAsyncSocket: 065fd1e645c7abab64f7a6a2007a48038fdc6a99 DoubleConversion: 5189b271737e1565bdce30deb4a08d647e3f5f54 FBLazyVector: 19e408e76fa9258dd32191a50d60c41444f52d29 - FBReactNativeSpec: 27a89a8eea1b441a73a78f420dd18dad3ed13723 + FBReactNativeSpec: 9761d52cf2d3727e2557fbf4014c514909d76b6b Flipper: 26fc4b7382499f1281eb8cb921e5c3ad6de91fe0 Flipper-Boost-iOSX: fd1e2b8cbef7e662a122412d7ac5f5bea715403c Flipper-DoubleConversion: 2dc99b02f658daf147069aad9dbd29d8feb06d30 @@ -945,7 +951,7 @@ SPEC CHECKSUMS: FlipperKit: cbdee19bdd4e7f05472a66ce290f1b729ba3cb86 fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 glog: 04b94705f318337d7ead9e6d17c019bd9b1f6b1b - hermes-engine: cd15ebd246edff3a995ec666e898dd1cbdcaa10d + hermes-engine: 445a2267b04cb39ca4a0b2d6758b5a0e5a58ccad libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c RCT-Folly: 424b8c9a7a0b9ab2886ffe9c3b041ef628fd4fb1 @@ -960,7 +966,7 @@ SPEC CHECKSUMS: React-cxxreact: ebed982230716c3515ab2f435cb13aec8a56af02 React-Fabric: 141459e61c825acf02d26ece099acbd9cbd87b99 React-graphics: 2dda97baebb0082bb85499c862c3f269a194f416 - React-hermes: 0a5145bae4207edf0def8e28fbcb6a8fd6e806c2 + React-hermes: 4912383b4f062173cb623e570ead70ab380f7bef React-jsi: c24dbcfdf7ea075138b73372387c7f17c0db56ef React-jsidynamic: 2b14ac1b6d3a1b7daa1e5a424b98de87da981698 React-jsiexecutor: 14e899380e3fe9ca74c4e19727540a03e7574721 diff --git a/scripts/cocoapods/jsengine.rb b/scripts/cocoapods/jsengine.rb index 8ec69c59f0bafd..b5f549f753300a 100644 --- a/scripts/cocoapods/jsengine.rb +++ b/scripts/cocoapods/jsengine.rb @@ -34,3 +34,23 @@ def setup_hermes!(react_native_path: "../node_modules/react-native", fabric_enab pod 'React-hermes', :path => "#{react_native_path}/ReactCommon/hermes" pod 'libevent', '~> 2.1.12' end + +def add_copy_hermes_framework_script_phase(installer, react_native_path) + utils_dir = File.join(react_native_path, "sdks", "hermes-engine", "utils") + phase_name = "[RN]Copy Hermes framework" + project = installer.generated_aggregate_targets.first.user_project + target = project.targets.first + if target.shell_script_build_phases.none? { |phase| phase.name == phase_name } + phase = target.new_shell_script_build_phase(phase_name) + phase.shell_script = ". #{utils_dir}/copy-hermes-xcode.sh" + project.save() + end +end + +def remove_copy_hermes_framework_script_phase(installer, react_native_path) + utils_dir = File.join(react_native_path, "sdks", "hermes-engine", "utils") + phase_name = "[RN]Copy Hermes framework" + project = installer.generated_aggregate_targets.first.user_project + project.targets.first.shell_script_build_phases.delete_if { |phase| phase.name == phase_name } + project.save() +end diff --git a/scripts/react_native_pods.rb b/scripts/react_native_pods.rb index 73b44c12bab708..6d6df22fe35e6c 100644 --- a/scripts/react_native_pods.rb +++ b/scripts/react_native_pods.rb @@ -203,6 +203,12 @@ def react_native_post_install(installer, react_native_path = "../node_modules/re flipper_post_install(installer) end + if ReactNativePodsUtils.has_pod(installer, 'hermes-engine') && ENV['HERMES_BUILD_FROM_SOURCE'] == "1" + add_copy_hermes_framework_script_phase(installer, react_native_path) + else + remove_copy_hermes_framework_script_phase(installer, react_native_path) + end + ReactNativePodsUtils.exclude_i386_architecture_while_using_hermes(installer) ReactNativePodsUtils.fix_library_search_paths(installer) ReactNativePodsUtils.fix_react_bridging_header_search_paths(installer) diff --git a/sdks/hermes-engine/hermes-engine.podspec b/sdks/hermes-engine/hermes-engine.podspec index 810d8ab2a91267..6761738c6d7adf 100644 --- a/sdks/hermes-engine/hermes-engine.podspec +++ b/sdks/hermes-engine/hermes-engine.podspec @@ -19,9 +19,6 @@ version = package['version'] hermestag_file = File.join(react_native_path, "sdks", ".hermesversion") isInCI = ENV['CI'] == true -# sdks/hermesc/osx-bin/ImportHermesc.cmake -import_hermesc_file=File.join(react_native_path, "sdks", "hermesc", "osx-bin", "ImportHermesc.cmake") - source = {} git = "https://github.com/facebook/hermes.git" @@ -32,7 +29,7 @@ if ENV.has_key?('HERMES_ENGINE_TARBALL_PATH') Pod::UI.puts '[Hermes] Using pre-built Hermes binaries from local path.' if Object.const_defined?("Pod::UI") source[:http] = "file://#{ENV['HERMES_ENGINE_TARBALL_PATH']}" elsif isInMain - Pod::UI.puts '[Hermes] Installing hermes-engine may take a while, building Hermes from source...'.yellow if Object.const_defined?("Pod::UI") + Pod::UI.puts '[Hermes] Installing hermes-engine may take slightly longer, building Hermes compiler from source...'.yellow if Object.const_defined?("Pod::UI") source[:git] = git source[:commit] = `git ls-remote https://github.com/facebook/hermes main | cut -f 1`.strip elsif isNightly @@ -62,42 +59,80 @@ Pod::Spec.new do |spec| spec.source = source spec.platforms = { :osx => "10.13", :ios => "12.4" } - spec.preserve_paths = ["destroot/bin/*"].concat(build_type == :debug ? ["**/*.{h,c,cpp}"] : []) - spec.source_files = "destroot/include/**/*.h" - spec.exclude_files = [ - "destroot/include/jsi/jsi/JSIDynamic.{h,cpp}", - "destroot/include/jsi/jsi/jsilib-*.{h,cpp}", - ] - spec.header_mappings_dir = "destroot/include" - - spec.ios.vendored_frameworks = "destroot/Library/Frameworks/universal/hermes.xcframework" - spec.osx.vendored_frameworks = "destroot/Library/Frameworks/macosx/hermes.framework" + spec.preserve_paths = '**/*.*' + spec.source_files = '' spec.xcconfig = { "CLANG_CXX_LANGUAGE_STANDARD" => "c++17", "CLANG_CXX_LIBRARY" => "compiler-default" }.merge!(build_type == :debug ? { "GCC_PREPROCESSOR_DEFINITIONS" => "HERMES_ENABLE_DEBUGGER=1" } : {}) - if source[:git] then - ENV['REACT_NATIVE_PATH'] = react_native_path - hermes_utils_path = "/sdks/hermes-engine/utils" - - spec.prepare_command = <<-EOS - export BUILD_TYPE=#{build_type.to_s.capitalize} - export RELEASE_VERSION="#{version}" - export IOS_DEPLOYMENT_TARGET="#{spec.deployment_target('ios')}" - export MAC_DEPLOYMENT_TARGET="#{spec.deployment_target('osx')}" - export JSI_PATH="$REACT_NATIVE_PATH/ReactCommon/jsi" - - # Set HERMES_OVERRIDE_HERMESC_PATH if pre-built HermesC is available - #{File.exist?(import_hermesc_file) ? "export HERMES_OVERRIDE_HERMESC_PATH=#{import_hermesc_file}" : ""} - #{File.exist?(import_hermesc_file) ? "echo \"Overriding HermesC path...\"" : ""} - - # Build iOS framework - $REACT_NATIVE_PATH#{hermes_utils_path}/build-ios-framework.sh - - # Build Mac framework - $REACT_NATIVE_PATH#{hermes_utils_path}/build-mac-framework.sh - EOS + if source[:http] then + + spec.subspec 'Pre-built' do |ss| + ss.preserve_paths = ["destroot/bin/*"].concat(build_type == :debug ? ["**/*.{h,c,cpp}"] : []) + ss.source_files = "destroot/include/**/*.h" + ss.exclude_files = ["destroot/include/jsi/jsi/JSIDynamic.{h,cpp}", "destroot/include/jsi/jsi/jsilib-*.{h,cpp}"] + ss.header_mappings_dir = "destroot/include" + ss.ios.vendored_frameworks = "destroot/Library/Frameworks/universal/hermes.xcframework" + ss.osx.vendored_frameworks = "destroot/Library/Frameworks/macosx/hermes.framework" + end + + elsif source[:git] then + + ENV['HERMES_BUILD_FROM_SOURCE'] = "1" + + spec.subspec 'Hermes' do |ss| + ss.source_files = '' + ss.public_header_files = 'API/hermes/*.h' + ss.header_dir = 'hermes' + end + + spec.subspec 'JSI' do |ss| + ss.source_files = '' + ss.public_header_files = 'API/jsi/jsi/*.h' + ss.header_dir = 'jsi' + end + + spec.subspec 'Public' do |ss| + ss.source_files = '' + ss.public_header_files = 'public/hermes/Public/*.h' + ss.header_dir = 'hermes/Public' + end + + hermesc_path = "" + + if ENV.has_key?('HERMES_OVERRIDE_HERMESC_PATH') && File.exist?(ENV['HERMES_OVERRIDE_HERMESC_PATH']) then + hermesc_path = ENV['HERMES_OVERRIDE_HERMESC_PATH'] + else + # Keep hermesc_path synchronized with .gitignore entry. + ENV['REACT_NATIVE_PATH'] = react_native_path + hermesc_path = "${REACT_NATIVE_PATH}/sdks/hermes-engine/build_host_hermesc" + spec.prepare_command = ". #{react_native_path}/sdks/hermes-engine/utils/build-hermesc-xcode.sh #{hermesc_path}" + end + + spec.user_target_xcconfig = { + 'FRAMEWORK_SEARCH_PATHS' => '"$(PODS_ROOT)/hermes-engine/destroot/Library/Frameworks/iphoneos" ' + + '"$(PODS_ROOT)/hermes-engine/destroot/Library/Frameworks/iphonesimulator" ' + + '"$(PODS_ROOT)/hermes-engine/destroot/Library/Frameworks/macosx" ' + + '"$(PODS_ROOT)/hermes-engine/destroot/Library/Frameworks/catalyst"', + 'OTHER_LDFLAGS' => '-framework "hermes"', + 'HERMES_CLI_PATH' => "#{hermesc_path}/bin/hermesc" + } + + spec.script_phases = [ + { + :name => 'Build Hermes', + :script => <<-EOS + . ${PODS_ROOT}/../.xcode.env + export CMAKE_BINARY=${CMAKE_BINARY:-#{%x(command -v cmake | tr -d '\n')}} + . ${REACT_NATIVE_PATH}/sdks/hermes-engine/utils/build-hermes-xcode.sh #{version} #{hermesc_path}/ImportHermesc.cmake + EOS + }, + { + :name => 'Copy Hermes Framework', + :script => ". ${REACT_NATIVE_PATH}/sdks/hermes-engine/utils/copy-hermes-xcode.sh" + } + ] end end diff --git a/sdks/hermes-engine/utils/build-hermes-xcode.sh b/sdks/hermes-engine/utils/build-hermes-xcode.sh new file mode 100644 index 00000000000000..0ef2da262461f2 --- /dev/null +++ b/sdks/hermes-engine/utils/build-hermes-xcode.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# 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. + +set -x + +release_version="$1"; shift +hermesc_path="$1"; shift + +build_cli_tools="false" +if [[ "$PLATFORM_NAME" == macosx ]]; then + build_cli_tools="true" +fi + +enable_debugger="false" +if [[ "$CONFIGURATION" == "Debug" ]]; then + enable_debugger="true" +fi + +deployment_target=${IPHONEOS_DEPLOYMENT_TARGET} +if [ -z "$deployment_target" ]; then + deployment_target=${MACOSX_DEPLOYMENT_TARGET} +fi + +architectures=$( echo "$ARCHS" | tr " " ";" ) + +echo "Configure Apple framework" + +"$CMAKE_BINARY" \ + -S "${PODS_ROOT}/hermes-engine" \ + -B "${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}" \ + -DHERMES_APPLE_TARGET_PLATFORM:STRING="$PLATFORM_NAME" \ + -DCMAKE_OSX_ARCHITECTURES:STRING="$architectures" \ + -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING="$deployment_target" \ + -DHERMES_ENABLE_DEBUGGER:BOOLEAN="$enable_debugger" \ + -DHERMES_ENABLE_INTL:BOOLEAN=true \ + -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \ + -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \ + -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \ + -DHERMES_ENABLE_BITCODE:BOOLEAN=false \ + -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \ + -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \ + -DHERMES_ENABLE_TOOLS:BOOLEAN="$build_cli_tools" \ + -DIMPORT_HERMESC:PATH="${hermesc_path}" \ + -DHERMES_RELEASE_VERSION="for RN $release_version" \ + -DCMAKE_INSTALL_PREFIX:PATH="${PODS_ROOT}/hermes-engine/destroot" \ + -DCMAKE_BUILD_TYPE="$CONFIGURATION" + +echo "Build Apple framework" + +"$CMAKE_BINARY" \ + --build "${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}" \ + --target "install/strip" \ + -j "$(sysctl -n hw.ncpu)" diff --git a/sdks/hermes-engine/utils/build-hermesc-xcode.sh b/sdks/hermes-engine/utils/build-hermesc-xcode.sh new file mode 100644 index 00000000000000..59de6a74e9a3f6 --- /dev/null +++ b/sdks/hermes-engine/utils/build-hermesc-xcode.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# 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. + +set -x + +hermesc_dir_path="$1" + +CMAKE_BINARY=${CMAKE_BINARY:-cmake} + +if ! "$CMAKE_BINARY" -S . -B "$hermesc_dir_path" +then + echo "Failed to configure Hermesc cmake project." + exit 1 +fi +if ! "$CMAKE_BINARY" --build "$hermesc_dir_path" --target hermesc -j "$(sysctl -n hw.ncpu)" +then + echo "Failed to build Hermesc cmake project." + exit 1 +fi diff --git a/sdks/hermes-engine/utils/copy-hermes-xcode.sh b/sdks/hermes-engine/utils/copy-hermes-xcode.sh new file mode 100644 index 00000000000000..62cc99c064a72f --- /dev/null +++ b/sdks/hermes-engine/utils/copy-hermes-xcode.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# 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. + +set -x + +source="${PODS_ROOT}/hermes-engine/destroot/Library/Frameworks/${PLATFORM_NAME}/hermes.framework" + +if [[ ! -f "$source" ]]; then + cp -R "$source" "${PODS_XCFRAMEWORKS_BUILD_DIR}/hermes/hermes.framework" + cp -R "$source" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +fi From 58a1cd236731a8aabf75ae6193acdf1c5bc1e44c Mon Sep 17 00:00:00 2001 From: Xin Chen Date: Tue, 1 Nov 2022 12:11:10 -0700 Subject: [PATCH 096/169] Add unit test for ImageView to take null uri in source Summary: This is a follow up action item from S295231 and T136039462 where we want to make sure null uri in image source is handled properly. This diff adds an unit test to make sure we are using transparent image when uri is null. Changelog: [Android][Internal] - Add unit test to ImageView for null uri in source Reviewed By: javache Differential Revision: D40732791 fbshipit-source-id: fd468bfe7c33a4f3f8913ead3e84a1770d7c907f --- .../react/views/image/ReactImageView.java | 5 +++ .../test/java/com/facebook/react/views/BUCK | 2 ++ .../views/image/ReactImagePropertyTest.java | 36 +++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java index 08a2cd7fcf1e5e..30a6ed20bdf546 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java @@ -540,6 +540,11 @@ public void setControllerListener(ControllerListener controllerListener) { maybeUpdateView(); } + // VisibleForTesting + public @Nullable ImageSource getImageSource() { + return mImageSource; + } + @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/BUCK b/ReactAndroid/src/test/java/com/facebook/react/views/BUCK index d624727def624c..8a3f5f828798d6 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/BUCK +++ b/ReactAndroid/src/test/java/com/facebook/react/views/BUCK @@ -28,6 +28,8 @@ rn_robolectric_test( react_native_dep("third-party/java/okio:okio"), react_native_target("java/com/facebook/react:react"), react_native_target("java/com/facebook/react/bridge:bridge"), + react_native_target("java/com/facebook/react/util:util"), + react_native_target("java/com/facebook/react/views/imagehelper:imagehelper"), react_native_target("java/com/facebook/react/common:common"), react_native_target("java/com/facebook/react/touch:touch"), react_native_target("java/com/facebook/react/uimanager:uimanager"), diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java index 99788ecb6d7964..779b245d7a815e 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java @@ -14,22 +14,30 @@ import android.graphics.Color; import android.util.DisplayMetrics; import com.facebook.drawee.backends.pipeline.Fresco; +import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.JavaOnlyArray; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactTestHelper; +import com.facebook.react.bridge.WritableArray; +import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.ReactStylesDiffMap; import com.facebook.react.uimanager.ThemedReactContext; +import com.facebook.react.util.RNLog; +import com.facebook.react.views.imagehelper.ImageSource; import com.facebook.soloader.SoLoader; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.invocation.InvocationOnMock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; @@ -38,6 +46,7 @@ * Verify that {@link ScalingUtils} properties are being applied correctly by {@link * ReactImageManager}. */ +@PrepareForTest({Arguments.class, RNLog.class}) @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "androidx.*", "android.*"}) public class ReactImagePropertyTest { @@ -50,6 +59,17 @@ public class ReactImagePropertyTest { @Before public void setup() { + PowerMockito.mockStatic(Arguments.class); + PowerMockito.when(Arguments.createArray()) + .thenAnswer((InvocationOnMock invocation) -> new JavaOnlyArray()); + PowerMockito.when(Arguments.createMap()) + .thenAnswer((InvocationOnMock invocation) -> new JavaOnlyMap()); + + // RNLog is stubbed out and the whole class need to be mocked + PowerMockito.mockStatic(RNLog.class); + PowerMockito.doNothing().when(RNLog.class); + RNLog.w(null, ""); + SoLoader.setInTestMode(); mContext = new ReactApplicationContext(RuntimeEnvironment.application); mCatalystInstanceMock = ReactTestHelper.createMockCatalystInstance(); @@ -140,4 +160,20 @@ public void testTintColor() { viewManager.updateProperties(view, buildStyles("tintColor", null)); assertNull(view.getColorFilter()); } + + @Test + public void testNullSrcs() { + ReactImageManager viewManager = new ReactImageManager(); + ReactImageView view = viewManager.createViewInstance(mThemeContext); + WritableArray sources = Arguments.createArray(); + WritableMap srcObj = Arguments.createMap(); + srcObj.putNull("uri"); + srcObj.putNull("width"); + srcObj.putNull("height"); + sources.pushMap(srcObj); + viewManager.setSource(view, sources); + view.maybeUpdateView(); + assertEquals( + ImageSource.getTransparentBitmapImageSource(view.getContext()), view.getImageSource()); + } } From e3eeadb63afc74bc8ca4c8feb2abbd7a7d6f94ad Mon Sep 17 00:00:00 2001 From: Dmytro Voronkevych Date: Tue, 1 Nov 2022 12:25:00 -0700 Subject: [PATCH 097/169] Adding new markerAnnotateWithMap method Summary: ## Changelog: [Internal] [Added] - Adding new markerAnnotateWithMap to the QPL. This is part of bigger effort to unify JS QPL interfaces across platforms. Reviewed By: eddyerburgh Differential Revision: D40796537 fbshipit-source-id: a75b97c20ca411653552228f7dc2fcbedd8ddca9 --- .../Performance/QuickPerformanceLogger.js | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Libraries/Performance/QuickPerformanceLogger.js b/Libraries/Performance/QuickPerformanceLogger.js index 48fcc468b20e55..5b521eea289b23 100644 --- a/Libraries/Performance/QuickPerformanceLogger.js +++ b/Libraries/Performance/QuickPerformanceLogger.js @@ -13,7 +13,7 @@ const AUTO_SET_TIMESTAMP = -1; const DUMMY_INSTANCE_KEY = 0; -// Defines map of annotations for markEvent +// Defines map of annotations // Use as following: // {string: {key1: value1, key2: value2}} export type AnnotationsMap = $Shape<{ @@ -68,6 +68,30 @@ const QuickPerformanceLogger = { } }, + markerAnnotateWithMap( + markerId: number, + annotations: AnnotationsMap, + instanceKey: number = DUMMY_INSTANCE_KEY, + ): void { + if (global.nativeQPLMarkerAnnotateWithMap) { + global.nativeQPLMarkerAnnotateWithMap(markerId, annotations, instanceKey); + } else if (global.nativeQPLMarkerAnnotate) { + for (var type of ['string']) { + var keyValsOfType = annotations[type]; + if (keyValsOfType !== null && keyValsOfType !== undefined) { + for (var annotationKey of Object.keys(keyValsOfType)) { + global.nativeQPLMarkerAnnotate( + markerId, + instanceKey, + annotationKey, + keyValsOfType[annotationKey].toString(), + ); + } + } + } + } + }, + markerCancel( markerId: number, instanceKey?: number = DUMMY_INSTANCE_KEY, From c565a770eb3d1920d960a5962d5dde7c6f3249c8 Mon Sep 17 00:00:00 2001 From: Dmytro Voronkevych Date: Tue, 1 Nov 2022 12:25:00 -0700 Subject: [PATCH 098/169] Migrating all qpl.markerAnnotate call sites to the new signature Summary: As part of unifying JS QPL interface, I'm bringing markerAnnotate to the parity with Web version. At the moment it supports only string annotations, but I'm adding support for ints, arrays of ints, arrays of strings, etc. ## Changelog: [Internal] [Changed] - Refactored markerAnnotateWithMap -> markerAnnotate Reviewed By: eddyerburgh Differential Revision: D40796535 fbshipit-source-id: 9831e353036835b97bb7b2f60085016034c04269 --- .../Performance/QuickPerformanceLogger.js | 24 ++++--------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/Libraries/Performance/QuickPerformanceLogger.js b/Libraries/Performance/QuickPerformanceLogger.js index 5b521eea289b23..9e8a6cd657c3a4 100644 --- a/Libraries/Performance/QuickPerformanceLogger.js +++ b/Libraries/Performance/QuickPerformanceLogger.js @@ -53,22 +53,6 @@ const QuickPerformanceLogger = { }, markerAnnotate( - markerId: number, - annotationKey: string, - annotationValue: string, - instanceKey: number = DUMMY_INSTANCE_KEY, - ): void { - if (global.nativeQPLMarkerAnnotate) { - global.nativeQPLMarkerAnnotate( - markerId, - instanceKey, - annotationKey, - annotationValue, - ); - } - }, - - markerAnnotateWithMap( markerId: number, annotations: AnnotationsMap, instanceKey: number = DUMMY_INSTANCE_KEY, @@ -76,10 +60,10 @@ const QuickPerformanceLogger = { if (global.nativeQPLMarkerAnnotateWithMap) { global.nativeQPLMarkerAnnotateWithMap(markerId, annotations, instanceKey); } else if (global.nativeQPLMarkerAnnotate) { - for (var type of ['string']) { - var keyValsOfType = annotations[type]; - if (keyValsOfType !== null && keyValsOfType !== undefined) { - for (var annotationKey of Object.keys(keyValsOfType)) { + for (const type of ['string']) { + const keyValsOfType = annotations[type]; + if (keyValsOfType != null) { + for (const annotationKey of Object.keys(keyValsOfType)) { global.nativeQPLMarkerAnnotate( markerId, instanceKey, From 565a7439ac8af66ab9b15e28119388608fd287c5 Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Tue, 1 Nov 2022 12:50:05 -0700 Subject: [PATCH 099/169] Refactor EventDriverAnimations to customize event match Summary: Changelog: [Internal] - Refactor match logic on determining whether to run an EventAnimationDriver (drivers for natively animated events) for an Event dispatched. Previously, drivers were stored by key on the NativeAnimatedNodesManager (based on event handler and viewTag) and has been refactored to be stored in a list for easier matching. This diff changes it so the match logic for running an EventAnimationDriver happens on the Event instance. This change is motivated by PointerEvents needing custom match logic (done on a following change). Reviewed By: javache Differential Revision: D40691002 fbshipit-source-id: e4f6742a2af3b751214aefa1fc069f65e8e71d77 --- .../react/animated/EventAnimationDriver.java | 7 +- .../animated/NativeAnimatedNodesManager.java | 81 ++++++++++--------- .../react/uimanager/events/Event.java | 18 +++++ 3 files changed, 67 insertions(+), 39 deletions(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java index fce99e38ba415a..edc92c238c3bc3 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/EventAnimationDriver.java @@ -21,8 +21,13 @@ /* package */ class EventAnimationDriver implements RCTEventEmitter { private List mEventPath; /* package */ ValueAnimatedNode mValueNode; + /* package */ String mEventName; + /* package */ int mViewTag; - public EventAnimationDriver(List eventPath, ValueAnimatedNode valueNode) { + public EventAnimationDriver( + String eventName, int viewTag, List eventPath, ValueAnimatedNode valueNode) { + mEventName = eventName; + mViewTag = viewTag; mEventPath = eventPath; mValueNode = valueNode; } diff --git a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java index 9a6953529b4b14..bb626bed0b2dcc 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java +++ b/ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedNodesManager.java @@ -31,11 +31,9 @@ import com.facebook.react.uimanager.events.EventDispatcherListener; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; -import java.util.Map; import java.util.Queue; /** @@ -58,9 +56,9 @@ public class NativeAnimatedNodesManager implements EventDispatcherListener { private final SparseArray mAnimatedNodes = new SparseArray<>(); private final SparseArray mActiveAnimations = new SparseArray<>(); private final SparseArray mUpdatedNodes = new SparseArray<>(); - // Mapping of a view tag and an event name to a list of event animation drivers. 99% of the time - // there will be only one driver per mapping so all code code should be optimized around that. - private final Map> mEventDrivers = new HashMap<>(); + // List of event animation drivers for an event on view. + // There may be multiple drivers for the same event and view. + private final List mEventDrivers = new ArrayList<>(); private final ReactApplicationContext mReactApplicationContext; private int mAnimatedGraphBFSColor = 0; // Used to avoid allocating a new array on every frame in `runUpdates` and `onEventDispatch`. @@ -501,7 +499,8 @@ public void restoreDefaultValues(int animatedNodeTag) { } @UiThread - public void addAnimatedEventToView(int viewTag, String eventName, ReadableMap eventMapping) { + public void addAnimatedEventToView( + int viewTag, String eventHandlerName, ReadableMap eventMapping) { int nodeTag = eventMapping.getInt("animatedValueTag"); AnimatedNode node = mAnimatedNodes.get(nodeTag); if (node == null) { @@ -512,8 +511,8 @@ public void addAnimatedEventToView(int viewTag, String eventName, ReadableMap ev throw new JSApplicationIllegalArgumentException( "addAnimatedEventToView: Animated node on view [" + viewTag - + "] connected to event (" - + eventName + + "] connected to event handler (" + + eventHandlerName + ") should be of type " + ValueAnimatedNode.class.getName()); } @@ -524,32 +523,27 @@ public void addAnimatedEventToView(int viewTag, String eventName, ReadableMap ev pathList.add(path.getString(i)); } - EventAnimationDriver event = new EventAnimationDriver(pathList, (ValueAnimatedNode) node); - String key = viewTag + eventName; - if (mEventDrivers.containsKey(key)) { - mEventDrivers.get(key).add(event); - } else { - List drivers = new ArrayList<>(1); - drivers.add(event); - mEventDrivers.put(key, drivers); - } + String eventName = normalizeEventName(eventHandlerName); + + EventAnimationDriver eventDriver = + new EventAnimationDriver(eventName, viewTag, pathList, (ValueAnimatedNode) node); + mEventDrivers.add(eventDriver); } @UiThread - public void removeAnimatedEventFromView(int viewTag, String eventName, int animatedValueTag) { - String key = viewTag + eventName; - if (mEventDrivers.containsKey(key)) { - List driversForKey = mEventDrivers.get(key); - if (driversForKey.size() == 1) { - mEventDrivers.remove(viewTag + eventName); - } else { - ListIterator it = driversForKey.listIterator(); - while (it.hasNext()) { - if (it.next().mValueNode.mTag == animatedValueTag) { - it.remove(); - break; - } - } + public void removeAnimatedEventFromView( + int viewTag, String eventHandlerName, int animatedValueTag) { + + String eventName = normalizeEventName(eventHandlerName); + + ListIterator it = mEventDrivers.listIterator(); + while (it.hasNext()) { + EventAnimationDriver driver = it.next(); + if (eventName.equals(driver.mEventName) + && viewTag == driver.mViewTag + && animatedValueTag == driver.mValueNode.mTag) { + it.remove(); + break; } } } @@ -585,18 +579,19 @@ private void handleEvent(Event event) { if (uiManager == null) { return; } - String eventName = uiManager.resolveCustomDirectEventName(event.getEventName()); - if (eventName == null) { - eventName = ""; - } - List driversForKey = mEventDrivers.get(event.getViewTag() + eventName); - if (driversForKey != null) { - for (EventAnimationDriver driver : driversForKey) { + boolean foundAtLeastOneDriver = false; + Event.EventAnimationDriverMatchSpec matchSpec = event.getEventAnimationDriverMatchSpec(); + for (EventAnimationDriver driver : mEventDrivers) { + if (matchSpec.match(driver.mViewTag, driver.mEventName)) { + foundAtLeastOneDriver = true; stopAnimationsForNode(driver.mValueNode); event.dispatch(driver); mRunUpdateNodeList.add(driver.mValueNode); } + } + + if (foundAtLeastOneDriver) { updateNodes(mRunUpdateNodeList); mRunUpdateNodeList.clear(); } @@ -824,4 +819,14 @@ private void updateNodes(List nodes) { mWarnedAboutGraphTraversal = false; } } + + private String normalizeEventName(String eventHandlerName) { + // Fabric UIManager also makes this assumption + String eventName = eventHandlerName; + if (eventHandlerName.startsWith("on")) { + eventName = "top" + eventHandlerName.substring(2); + } + + return eventName; + } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java index 0b6a1140c8edab..01b355def8b8be 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/Event.java @@ -40,6 +40,7 @@ public abstract class Event { private int mViewTag; private long mTimestampMs; private int mUniqueID = sUniqueID++; + private @Nullable EventAnimationDriverMatchSpec mEventAnimationDriverMatchSpec; protected Event() {} @@ -165,6 +166,19 @@ public void onDispose() {} /** @return the name of this event as registered in JS */ public abstract String getEventName(); + public EventAnimationDriverMatchSpec getEventAnimationDriverMatchSpec() { + if (mEventAnimationDriverMatchSpec == null) { + mEventAnimationDriverMatchSpec = + new EventAnimationDriverMatchSpec() { + @Override + public boolean match(int viewTag, String eventName) { + return viewTag == getViewTag() && eventName.equals(getEventName()); + }; + }; + } + return mEventAnimationDriverMatchSpec; + } + /** * Dispatch this event to JS using the given event emitter. Compatible with old and new renderer. * Instead of using this or dispatchModern, it is recommended that you simply override @@ -225,4 +239,8 @@ public void dispatchModern(RCTModernEventEmitter rctEventEmitter) { } dispatch(rctEventEmitter); } + + public interface EventAnimationDriverMatchSpec { + boolean match(int viewTag, String eventName); + } } From cfe811ab18ec98776d2564de527544d45813508f Mon Sep 17 00:00:00 2001 From: Luna Wei Date: Tue, 1 Nov 2022 12:50:05 -0700 Subject: [PATCH 100/169] Fix natively driven animated.event for bubbling PointerEvents Summary: Changelog: [Internal] Override logic for determining whether a dispatched `Event` triggers a native `EventAnimationDriver`. Natively driven AnimatedEvents on bubbling events is not supported. `PointerEvents` requires this and this diff adds custom matching logic such that if a parent specifies an `AnimatedEvent` on `onPointerMove` and a child view dispatches it, the `AnimatedEvent` will still fire. Reviewed By: javache Differential Revision: D38722563 fbshipit-source-id: 7cde57eaff9584b33c6ab15f1fe85c0a9bac132e --- .../react/uimanager/events/PointerEvent.java | 30 +++++++++++++++++++ .../uimanager/events/PointerEventHelper.java | 14 +++++++++ 2 files changed, 44 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEvent.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEvent.java index e7e69919f913d0..ed7004a1fc9006 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEvent.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEvent.java @@ -66,6 +66,7 @@ public static PointerEvent obtain( private short mCoalescingKey = UNSET_COALESCING_KEY; private @Nullable List mPointersEventData; private PointerEventState mEventState; + private @Nullable Event.EventAnimationDriverMatchSpec mEventAnimationDriverMatchSpec; private void init( String eventName, @@ -114,6 +115,31 @@ public void dispatch(RCTEventEmitter rctEventEmitter) { return; } + @Override + public Event.EventAnimationDriverMatchSpec getEventAnimationDriverMatchSpec() { + if (mEventAnimationDriverMatchSpec == null) { + mEventAnimationDriverMatchSpec = + new EventAnimationDriverMatchSpec() { + @Override + public boolean match(int viewTag, String eventName) { + if (!PointerEventHelper.isBubblingEvent(eventName)) { + return false; + } + + List viewTargets = + mEventState.getHitPathForActivePointer(); + for (TouchTargetHelper.ViewTarget viewTarget : viewTargets) { + if (viewTarget.getViewId() == viewTag && eventName.equals(mEventName)) { + return true; + } + } + return false; + } + }; + } + return mEventAnimationDriverMatchSpec; + } + @Override public void onDispose() { mPointersEventData = null; @@ -329,5 +355,9 @@ public final Map> getHitPathByPointe public final Map getEventCoordinatesByPointerId() { return mEventCoordinatesByPointerId; } + + public final List getHitPathForActivePointer() { + return mHitPathByPointerId.get(mActivePointerId); + } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEventHelper.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEventHelper.java index 8e1873ed94c1af..da6b77cd1a2bd8 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEventHelper.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/events/PointerEventHelper.java @@ -212,4 +212,18 @@ public static double getPressure(int buttonState, String eventName) { boolean inActiveButtonState = buttonState != 0; return inActiveButtonState ? 0.5 : 0; } + + public static boolean isBubblingEvent(String eventName) { + switch (eventName) { + case POINTER_UP: + case POINTER_DOWN: + case POINTER_OVER: + case POINTER_OUT: + case POINTER_MOVE: + case POINTER_CANCEL: + return true; + default: + return false; + } + } } From dbb9252d288d614f08fa0d9364331835c427e080 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Tue, 1 Nov 2022 13:37:03 -0700 Subject: [PATCH 101/169] Annotate `Array.map` returns when the implicit return type is widened Summary: Changelog: [Internal] Differential Revision: D40840078 fbshipit-source-id: 0104444060d8d6a1a22066d63579ac06ff715226 --- Libraries/LogBox/Data/__tests__/LogBoxLog-test.js | 2 +- .../Data/__tests__/LogBoxSymbolication-test.js | 2 +- .../__tests__/LogBoxInspectorStackFrames-test.js | 4 +++- packages/rn-tester/js/utils/testerStateUtils.js | 14 ++++++++------ 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js b/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js index 0281ad416e2297..2327492caf97dd 100644 --- a/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js +++ b/Libraries/LogBox/Data/__tests__/LogBoxLog-test.js @@ -50,7 +50,7 @@ function getLogBoxSymbolication(): {| } const createStack = (methodNames: Array) => - methodNames.map(methodName => ({ + methodNames.map((methodName): StackFrame => ({ column: null, file: 'file://path/to/file.js', lineNumber: 1, diff --git a/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js b/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js index 09ba968f465cc7..3d272839c59a55 100644 --- a/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js +++ b/Libraries/LogBox/Data/__tests__/LogBoxSymbolication-test.js @@ -24,7 +24,7 @@ const symbolicateStackTrace: JestMockFn< > = (require('../../../Core/Devtools/symbolicateStackTrace'): any); const createStack = (methodNames: Array) => - methodNames.map(methodName => ({ + methodNames.map((methodName): StackFrame => ({ column: null, file: 'file://path/to/file.js', lineNumber: 1, diff --git a/Libraries/LogBox/UI/__tests__/LogBoxInspectorStackFrames-test.js b/Libraries/LogBox/UI/__tests__/LogBoxInspectorStackFrames-test.js index 83ce6b449e90cb..c1b6b50d97f9ae 100644 --- a/Libraries/LogBox/UI/__tests__/LogBoxInspectorStackFrames-test.js +++ b/Libraries/LogBox/UI/__tests__/LogBoxInspectorStackFrames-test.js @@ -9,6 +9,8 @@ * @oncall react_native */ +import type {StackFrame} from '../../../Core/NativeExceptionsManager'; + import LogBoxInspectorStackFrames, { getCollapseMessage, } from '../LogBoxInspectorStackFrames'; @@ -33,7 +35,7 @@ const createLogWithFrames = (collapsedOptions: Array) => { }; const createCollapsedFrames = (collapsedOptions: Array) => { - return collapsedOptions.map(option => ({ + return collapsedOptions.map((option): StackFrame => ({ column: 1, file: 'dependency.js', lineNumber: 1, diff --git a/packages/rn-tester/js/utils/testerStateUtils.js b/packages/rn-tester/js/utils/testerStateUtils.js index 78ed62190399c6..a7ec6ae7c4d08c 100644 --- a/packages/rn-tester/js/utils/testerStateUtils.js +++ b/packages/rn-tester/js/utils/testerStateUtils.js @@ -62,11 +62,13 @@ export const getExamplesListWithBookmarksAndRecentlyUsed = ({ return null; } - const components = RNTesterList.Components.map(componentExample => ({ - ...componentExample, - isBookmarked: bookmarks.components.includes(componentExample.key), - exampleType: Screens.COMPONENTS, - })); + const components = RNTesterList.Components.map( + (componentExample): RNTesterModuleInfo => ({ + ...componentExample, + isBookmarked: bookmarks.components.includes(componentExample.key), + exampleType: Screens.COMPONENTS, + }), + ); const recentlyUsedComponents = recentlyUsed.components .map(recentComponentKey => @@ -78,7 +80,7 @@ export const getExamplesListWithBookmarksAndRecentlyUsed = ({ component => component.isBookmarked, ); - const apis = RNTesterList.APIs.map(apiExample => ({ + const apis = RNTesterList.APIs.map((apiExample): RNTesterModuleInfo => ({ ...apiExample, isBookmarked: bookmarks.apis.includes(apiExample.key), exampleType: Screens.APIS, From d71d0db51dec825ed9151ea02533279411381bb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Tue, 1 Nov 2022 16:02:21 -0700 Subject: [PATCH 102/169] hermes-utils: Strip debug symbols during tarball creation (#35162) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35162 The dSYMs for Apple will not be distributed as part of the prebuilts tarball. They can still be included in the tarball by passing a `-d` flag to the create-tarball script. Changelog: [internal] Reviewed By: cipolleschi Differential Revision: D40813679 fbshipit-source-id: 26dee8251684c5ecad649ccd27ce688cfe88ec8f --- scripts/hermes/create-tarball.js | 7 +++++ scripts/hermes/hermes-utils.js | 48 +++++++++++++++++++++----------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/scripts/hermes/create-tarball.js b/scripts/hermes/create-tarball.js index b41278ae1d6629..2d1cd8d3a6f890 100644 --- a/scripts/hermes/create-tarball.js +++ b/scripts/hermes/create-tarball.js @@ -40,12 +40,18 @@ let argv = yargs .option('o', { alias: 'outputDir', describe: 'Location where the tarball will be saved to.', + }) + .option('exclude-debug-symbols', { + describe: 'Whether dSYMs should be excluded from the tarball.', + type: 'boolean', + default: true, }).argv; async function main() { const hermesDir = argv.inputDir; const buildType = argv.buildType; const releaseVersion = argv.releaseVersion; + const excludeDebugSymbols = argv.excludeDebugSymbols; let tarballOutputDir = argv.outputDir; if (!tarballOutputDir) { @@ -65,6 +71,7 @@ async function main() { buildType, releaseVersion, tarballOutputDir, + excludeDebugSymbols, ); console.log(tarballOutputPath); return tarballOutputPath; diff --git a/scripts/hermes/hermes-utils.js b/scripts/hermes/hermes-utils.js index f881784ad809e6..2ddbfe522417e9 100644 --- a/scripts/hermes/hermes-utils.js +++ b/scripts/hermes/hermes-utils.js @@ -212,33 +212,28 @@ function createHermesPrebuiltArtifactsTarball( buildType, releaseVersion, tarballOutputDir, + excludeDebugSymbols, ) { - if (!hermesDir) { - hermesDir = HERMES_DIR; - } - if (!fs.existsSync(hermesDir)) { - throw new Error(`Path to Hermes does not exist at ${hermesDir}`); - } - if (!fs.existsSync(path.join(hermesDir, 'destroot'))) { - throw new Error( - `destroot not found at ${path.join( - hermesDir, - 'destroot', - )}. Are you sure Hermes has been built?`, - ); - } + validateHermesFrameworksExist(path.join(hermesDir, 'destroot')); + if (!fs.existsSync(tarballOutputDir)) { fs.mkdirSync(tarballOutputDir, {recursive: true}); } let tarballTempDir; - try { tarballTempDir = fs.mkdtempSync( path.join(os.tmpdir(), 'hermes-engine-destroot-'), ); - execSync(`cp -R ./destroot ${tarballTempDir}`, {cwd: hermesDir}); + let args = ['-a']; + if (excludeDebugSymbols) { + args.push('--exclude=dSYMs/'); + args.push('--exclude=*.dSYM/'); + } + execSync(`rsync ${args.join(' ')} ./destroot ${tarballTempDir}`, { + cwd: hermesDir, + }); if (fs.existsSync(path.join(hermesDir, 'LICENSE'))) { execSync(`cp LICENSE ${tarballTempDir}`, {cwd: hermesDir}); } @@ -267,6 +262,27 @@ function createHermesPrebuiltArtifactsTarball( return tarballOutputPath; } +function validateHermesFrameworksExist(destrootDir) { + if ( + !fs.existsSync( + path.join(destrootDir, 'Library/Frameworks/macosx/hermes.framework'), + ) + ) { + throw new Error( + 'Error: Hermes macOS Framework not found. Are you sure Hermes has been built?', + ); + } + if ( + !fs.existsSync( + path.join(destrootDir, 'Library/Frameworks/universal/hermes.xcframework'), + ) + ) { + throw new Error( + 'Error: Hermes iOS XCFramework not found. Are you sure Hermes has been built?', + ); + } +} + module.exports = { configureMakeForPrebuiltHermesC, copyBuildScripts, From 91d58cf5b5bccd380a44b0f7056fac0da0a9c9a2 Mon Sep 17 00:00:00 2001 From: Mike Vitousek Date: Tue, 1 Nov 2022 17:13:27 -0700 Subject: [PATCH 103/169] Codemod cycle annotations for xplat/js Summary: Add annotations using flow codemod annotate-cycles --write Changelog: [internal] Reviewed By: SamChou19815 Differential Revision: D40896688 fbshipit-source-id: 0c32932d17542be070360db29b7797f8e6e5978b --- IntegrationTests/TimersTest.js | 6 +++--- Libraries/Animated/AnimatedImplementation.js | 2 +- Libraries/BatchedBridge/MessageQueue.js | 2 +- Libraries/BugReporting/getReactData.js | 2 +- Libraries/Core/Timers/JSTimers.js | 19 +++++++++++-------- Libraries/Lists/ViewabilityHelper.js | 2 +- Libraries/LogBox/Data/LogBoxData.js | 2 +- .../emitter/__tests__/EventEmitter-test.js | 9 +++++++-- .../GenerateModuleObjCpp/serializeMethod.js | 2 +- .../src/parsers/flow/components/events.js | 6 +++++- .../ActivityIndicatorExample.js | 2 +- .../AnimatedGratuitousApp/AnExTilt.js | 2 +- 12 files changed, 34 insertions(+), 22 deletions(-) diff --git a/IntegrationTests/TimersTest.js b/IntegrationTests/TimersTest.js index 04496e0a943081..3a74f97edf3131 100644 --- a/IntegrationTests/TimersTest.js +++ b/IntegrationTests/TimersTest.js @@ -39,7 +39,7 @@ class TimersTest extends React.Component { }; setTimeout(fn: () => void, time: number): TimeoutID { - const id = setTimeout(() => { + const id: TimeoutID = setTimeout(() => { this._timeoutIDs.delete(id); fn(); }, time); @@ -70,7 +70,7 @@ class TimersTest extends React.Component { } setImmediate(fn: () => void): ImmediateID { - const id = setImmediate(() => { + const id: any = setImmediate(() => { this._immediateIDs.delete(id); fn(); }); @@ -81,7 +81,7 @@ class TimersTest extends React.Component { } requestAnimationFrame(fn: () => void): AnimationFrameID { - const id = requestAnimationFrame(() => { + const id: AnimationFrameID = requestAnimationFrame(() => { this._animationFrameIDs.delete(id); fn(); }); diff --git a/Libraries/Animated/AnimatedImplementation.js b/Libraries/Animated/AnimatedImplementation.js index 21f6c7069e17b1..7e25c65f2a461e 100644 --- a/Libraries/Animated/AnimatedImplementation.js +++ b/Libraries/Animated/AnimatedImplementation.js @@ -415,7 +415,7 @@ const parallel = function ( }); }, - _startNativeLoop: function () { + _startNativeLoop: function (): empty { throw new Error( 'Loops run using the native driver cannot contain Animated.parallel animations', ); diff --git a/Libraries/BatchedBridge/MessageQueue.js b/Libraries/BatchedBridge/MessageQueue.js index 65c7102ca72a8d..a9810bc6f94204 100644 --- a/Libraries/BatchedBridge/MessageQueue.js +++ b/Libraries/BatchedBridge/MessageQueue.js @@ -252,7 +252,7 @@ class MessageQueue { // folly-convertible. As a special case, if a prop value is a // function it is permitted here, and special-cased in the // conversion. - const isValidArgument = (val: mixed) => { + const isValidArgument = (val: mixed): boolean => { switch (typeof val) { case 'undefined': case 'boolean': diff --git a/Libraries/BugReporting/getReactData.js b/Libraries/BugReporting/getReactData.js index 4440cc4e0d0e60..cc988ced109854 100644 --- a/Libraries/BugReporting/getReactData.js +++ b/Libraries/BugReporting/getReactData.js @@ -165,7 +165,7 @@ function copyWithSetImpl( path: Array, idx: number, value: any, -) { +): any { if (idx >= path.length) { return value; } diff --git a/Libraries/Core/Timers/JSTimers.js b/Libraries/Core/Timers/JSTimers.js index 8147ebb8e90f31..33f8a68d76b67f 100644 --- a/Libraries/Core/Timers/JSTimers.js +++ b/Libraries/Core/Timers/JSTimers.js @@ -242,7 +242,7 @@ const JSTimers = { * @param {function} func Callback to be invoked before the end of the * current JavaScript execution loop. */ - queueReactNativeMicrotask: function (func: Function, ...args: any) { + queueReactNativeMicrotask: function (func: Function, ...args: any): number { const id = _allocateCallback( () => func.apply(undefined, args), 'queueReactNativeMicrotask', @@ -254,7 +254,7 @@ const JSTimers = { /** * @param {function} func Callback to be invoked every frame. */ - requestAnimationFrame: function (func: Function) { + requestAnimationFrame: function (func: Function): any | number { const id = _allocateCallback(func, 'requestAnimationFrame'); createTimer(id, 1, Date.now(), /* recurring */ false); return id; @@ -265,16 +265,19 @@ const JSTimers = { * with time remaining in frame. * @param {?object} options */ - requestIdleCallback: function (func: Function, options: ?Object) { + requestIdleCallback: function ( + func: Function, + options: ?Object, + ): any | number { if (requestIdleCallbacks.length === 0) { setSendIdleEvents(true); } const timeout = options && options.timeout; - const id = _allocateCallback( + const id: number = _allocateCallback( timeout != null ? (deadline: any) => { - const timeoutId = requestIdleCallbackTimeouts[id]; + const timeoutId: number = requestIdleCallbackTimeouts[id]; if (timeoutId) { JSTimers.clearTimeout(timeoutId); delete requestIdleCallbackTimeouts[id]; @@ -287,8 +290,8 @@ const JSTimers = { requestIdleCallbacks.push(id); if (timeout != null) { - const timeoutId = JSTimers.setTimeout(() => { - const index = requestIdleCallbacks.indexOf(id); + const timeoutId: number = JSTimers.setTimeout(() => { + const index: number = requestIdleCallbacks.indexOf(id); if (index > -1) { requestIdleCallbacks.splice(index, 1); _callTimer(id, global.performance.now(), true); @@ -345,7 +348,7 @@ const JSTimers = { * This is called from the native side. We are passed an array of timerIDs, * and */ - callTimers: function (timersToCall: Array) { + callTimers: function (timersToCall: Array): any | void { invariant( timersToCall.length !== 0, 'Cannot call `callTimers` with an empty list of IDs.', diff --git a/Libraries/Lists/ViewabilityHelper.js b/Libraries/Lists/ViewabilityHelper.js index 104f3931c0af6e..33a9811825affd 100644 --- a/Libraries/Lists/ViewabilityHelper.js +++ b/Libraries/Lists/ViewabilityHelper.js @@ -234,7 +234,7 @@ class ViewabilityHelper { } this._viewableIndices = viewableIndices; if (this._config.minimumViewTime) { - const handle = setTimeout(() => { + const handle: TimeoutID = setTimeout(() => { /* $FlowFixMe[incompatible-call] (>=0.63.0 site=react_native_fb) This * comment suppresses an error found when Flow v0.63 was deployed. To * see the error delete this comment and run Flow. */ diff --git a/Libraries/LogBox/Data/LogBoxData.js b/Libraries/LogBox/Data/LogBoxData.js index d868d89e8e9534..6c5e160dfe0f46 100644 --- a/Libraries/LogBox/Data/LogBoxData.js +++ b/Libraries/LogBox/Data/LogBoxData.js @@ -68,7 +68,7 @@ const observers: Set<{observer: Observer, ...}> = new Set(); const ignorePatterns: Set = new Set(); let appInfo: ?() => AppInfo = null; let logs: LogBoxLogs = new Set(); -let updateTimeout = null; +let updateTimeout: $FlowFixMe | null = null; let _isDisabled = false; let _selectedIndex = -1; diff --git a/Libraries/vendor/emitter/__tests__/EventEmitter-test.js b/Libraries/vendor/emitter/__tests__/EventEmitter-test.js index 7ae26000cc6d8d..99288ac3e2e88e 100644 --- a/Libraries/vendor/emitter/__tests__/EventEmitter-test.js +++ b/Libraries/vendor/emitter/__tests__/EventEmitter-test.js @@ -9,6 +9,8 @@ * @oncall react_native */ +import type {EventSubscription} from '../EventEmitter'; + import EventEmitter from '../EventEmitter'; describe('listeners', () => { @@ -309,7 +311,7 @@ describe('event emission', () => { const listenerA = jest.fn(() => { results.push('A'); }); - const listenerB = jest.fn(() => { + const listenerB: JestMockFn, void> = jest.fn(() => { results.push('B'); subscriptionB.remove(); }); @@ -317,7 +319,10 @@ describe('event emission', () => { results.push('C'); }); emitter.addListener('A', listenerA); - const subscriptionB = emitter.addListener('A', listenerB); + const subscriptionB: EventSubscription = emitter.addListener( + 'A', + listenerB, + ); emitter.addListener('A', listenerC); emitter.emit('A'); diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js index ea84c731b2c653..d0864ca5ea8ee2 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js @@ -295,7 +295,7 @@ function getParamObjCType( function getReturnObjCType( methodName: string, nullableTypeAnnotation: Nullable, -) { +): string { const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); function wrapIntoNullableIfNeeded(generatedType: string) { diff --git a/packages/react-native-codegen/src/parsers/flow/components/events.js b/packages/react-native-codegen/src/parsers/flow/components/events.js index a6a788a467d86e..8384edd789b8a5 100644 --- a/packages/react-native-codegen/src/parsers/flow/components/events.js +++ b/packages/react-native-codegen/src/parsers/flow/components/events.js @@ -104,7 +104,11 @@ function findEventArgumentsAndType( types: TypeMap, bubblingType: void | 'direct' | 'bubble', paperName: ?$FlowFixMe, -) { +): { + argumentProps: $FlowFixMe, + bubblingType: ?('direct' | 'bubble'), + paperTopLevelNameDeprecated: ?$FlowFixMe, +} { if (!typeAnnotation.id) { throw new Error("typeAnnotation of event doesn't have a name"); } diff --git a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js index 7be8bc4a5dd5f3..2713fce143facf 100644 --- a/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js +++ b/packages/rn-tester/js/examples/ActivityIndicator/ActivityIndicatorExample.js @@ -17,7 +17,7 @@ function ToggleAnimatingActivityIndicator() { const [animating, setAnimating] = useState(true); - const setToggleTimeout = useCallback(() => { + const setToggleTimeout: () => void = useCallback(() => { timer.current = setTimeout(() => { setAnimating(currentState => !currentState); setToggleTimeout(); diff --git a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExTilt.js b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExTilt.js index 3f9552ca88d9e3..3e9b54a338d7c8 100644 --- a/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExTilt.js +++ b/packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExTilt.js @@ -60,7 +60,7 @@ class AnExTilt extends React.Component { useNativeDriver: false, }).start(); this.state.panX.removeAllListeners(); - const id = this.state.panX.addListener(({value}) => { + const id: any = this.state.panX.addListener(({value}) => { // listen until offscreen if (Math.abs(value) > 400) { this.state.panX.removeListener(id); // offscreen, so stop listening From 7964d484bc800e1108e8462fc7aeb1fbaae842b9 Mon Sep 17 00:00:00 2001 From: Ramanpreet Nara Date: Tue, 1 Nov 2022 17:14:11 -0700 Subject: [PATCH 104/169] Introduce soft exceptions in the bridgeless core Summary: Changelog: [Internal] Reviewed By: fkgozali Differential Revision: D40824468 fbshipit-source-id: c840610e923c35cc5c36b37e5c580d0296c1e46b --- .../java/com/facebook/react/config/ReactFeatureFlags.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java index 02bdfb07c84de1..f837171c99490b 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java +++ b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java @@ -37,6 +37,11 @@ public class ReactFeatureFlags { */ public static boolean enableBridgelessArchitecture = false; + /** + * Does the bridgeless architecture log soft exceptions. Could be useful for tracking down issues. + */ + public static volatile boolean enableBridgelessArchitectureSoftExceptions = false; + /** * After TurboModules and Fabric are enabled, we need to ensure that the legacy NativeModule isn't * isn't used. So, turn this flag on to trigger warnings whenever the legacy NativeModule system From b5bb227be88fc89538279cfd84fbec810e2b8aa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Tue, 1 Nov 2022 18:27:39 -0700 Subject: [PATCH 105/169] Hermes: Include iOS debug symbols in Hermes XCFramework Summary: Include dSYMs when building the universal XCFramework for Hermes iOS. CocoaPods should pick up dSYMs automatically when using `vendored_framework` if: - `hermes.framework` has a `hermes.framework.dSYM` in the same base directory - `hermes.xcframework` has a `dSYMs` folder with a `hermes.framework.dSYM` in it, for each slice The dSYMs for the macOS hermes.framework are already being created. Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D40790250 fbshipit-source-id: 50fcb3492434637b00458c1aa443ac6ec5472fac --- .../utils/build-apple-framework.sh | 91 ++++++++++++------- 1 file changed, 57 insertions(+), 34 deletions(-) diff --git a/sdks/hermes-engine/utils/build-apple-framework.sh b/sdks/hermes-engine/utils/build-apple-framework.sh index a48b565c3cb415..9f391a53fa4287 100755 --- a/sdks/hermes-engine/utils/build-apple-framework.sh +++ b/sdks/hermes-engine/utils/build-apple-framework.sh @@ -4,9 +4,19 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. -NUM_CORES=$(sysctl -n hw.ncpu) +# Defines functions for building various Hermes frameworks. +# See build-ios-framework.sh and build-mac-framework.sh for usage examples. + +CURR_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" + IMPORT_HERMESC_PATH=${HERMES_OVERRIDE_HERMESC_PATH:-$PWD/build_host_hermesc/ImportHermesc.cmake} -REACT_NATIVE_PATH=${REACT_NATIVE_PATH:-$PWD/../..} +BUILD_TYPE=${BUILD_TYPE:-Debug} + +HERMES_PATH="$CURR_SCRIPT_DIR/.." +REACT_NATIVE_PATH=${REACT_NATIVE_PATH:-$CURR_SCRIPT_DIR/../../..} + +NUM_CORES=$(sysctl -n hw.ncpu) + if [[ -z "$JSI_PATH" ]]; then JSI_PATH="$REACT_NATIVE_PATH/ReactCommon/jsi" fi @@ -34,8 +44,10 @@ function get_mac_deployment_target { # Build host hermes compiler for internal bytecode function build_host_hermesc { echo "Building hermesc" - cmake -S . -B build_host_hermesc - cmake --build ./build_host_hermesc --target hermesc -j ${NUM_CORES} + pushd "$HERMES_PATH" > /dev/null || exit 1 + cmake -S . -B build_host_hermesc -DJSI_DIR="$JSI_PATH" + cmake --build ./build_host_hermesc --target hermesc -j "${NUM_CORES}" + popd > /dev/null || exit 1 } # Utility function to configure an Apple framework @@ -58,30 +70,30 @@ function configure_apple_framework { enable_debugger="false" fi - cmake -S . -B "build_$1" \ - -DHERMES_APPLE_TARGET_PLATFORM:STRING="$1" \ - -DCMAKE_OSX_ARCHITECTURES:STRING="$2" \ - -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING="$3" \ - -DHERMES_ENABLE_DEBUGGER:BOOLEAN="$enable_debugger" \ - -DHERMES_ENABLE_INTL:BOOLEAN=true \ - -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \ - -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \ - -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \ - -DHERMES_ENABLE_BITCODE:BOOLEAN="$enable_bitcode" \ - -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \ - -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \ - -DHERMES_ENABLE_TOOLS:BOOLEAN="$build_cli_tools" \ - -DIMPORT_HERMESC:PATH="$IMPORT_HERMESC_PATH" \ - -DJSI_DIR="$JSI_PATH" \ - -DHERMES_RELEASE_VERSION="for RN $(get_release_version)" \ - -DCMAKE_INSTALL_PREFIX:PATH=../destroot \ - -DCMAKE_BUILD_TYPE="$BUILD_TYPE" + pushd "$HERMES_PATH" > /dev/null || exit 1 + cmake -S . -B "build_$1" \ + -DHERMES_APPLE_TARGET_PLATFORM:STRING="$1" \ + -DCMAKE_OSX_ARCHITECTURES:STRING="$2" \ + -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING="$3" \ + -DHERMES_ENABLE_DEBUGGER:BOOLEAN="$enable_debugger" \ + -DHERMES_ENABLE_INTL:BOOLEAN=true \ + -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \ + -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \ + -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \ + -DHERMES_ENABLE_BITCODE:BOOLEAN="$enable_bitcode" \ + -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \ + -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \ + -DHERMES_ENABLE_TOOLS:BOOLEAN="$build_cli_tools" \ + -DIMPORT_HERMESC:PATH="$IMPORT_HERMESC_PATH" \ + -DJSI_DIR="$JSI_PATH" \ + -DHERMES_RELEASE_VERSION="for RN $(get_release_version)" \ + -DCMAKE_INSTALL_PREFIX:PATH=../destroot \ + -DCMAKE_BUILD_TYPE="$BUILD_TYPE" + popd > /dev/null || exit 1 } # Utility function to build an Apple framework function build_apple_framework { - echo "Building $BUILD_TYPE framework for $1 with architectures: $2" - # Only build host HermesC if no file found at $IMPORT_HERMESC_PATH [ ! -f "$IMPORT_HERMESC_PATH" ] && build_host_hermesc @@ -90,15 +102,19 @@ function build_apple_framework { [ ! -f "$IMPORT_HERMESC_PATH" ] && echo "Host hermesc is required to build apple frameworks!" + echo "Building $BUILD_TYPE framework for $1 with architectures: $2" configure_apple_framework "$1" "$2" "$3" - cmake --build "./build_$1" --target install/strip -j ${NUM_CORES} + + pushd "$HERMES_PATH" > /dev/null || exit 1 + cmake --build "./build_$1" --target install/strip -j "${NUM_CORES}" + popd > /dev/null || exit 1 } # Accepts an array of frameworks and will place all of # the architectures into an universal folder and then remove # the merged frameworks from destroot function create_universal_framework { - cd ./destroot/Library/Frameworks || exit 1 + pushd "$HERMES_PATH/destroot/Library/Frameworks" > /dev/null || exit 1 local platforms=("$@") local args="" @@ -106,16 +122,23 @@ function create_universal_framework { echo "Creating universal framework for platforms: ${platforms[*]}" for i in "${!platforms[@]}"; do - args+="-framework ${platforms[$i]}/hermes.framework " + local hermes_framework_path="${platforms[$i]}/hermes.framework" + args+="-framework $hermes_framework_path " + + # Path to dSYM must be absolute + args+="-debug-symbols $HERMES_PATH/destroot/Library/Frameworks/$hermes_framework_path.dSYM " done - mkdir universal + mkdir -p universal # shellcheck disable=SC2086 - xcodebuild -create-xcframework $args -output "universal/hermes.xcframework" - - for platform in "$@"; do - rm -r "$platform" - done + if xcodebuild -create-xcframework $args -output "universal/hermes.xcframework" + then + # # Remove the thin iOS hermes.frameworks that are now part of the universal + # XCFramework + for platform in "${platforms[@]}"; do + rm -r "$platform" + done + fi - cd - || exit 1 + popd > /dev/null || exit 1 } From 358b7a4458859f768921a31dd3dfe85947d9abeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Tue, 1 Nov 2022 18:27:39 -0700 Subject: [PATCH 106/169] hermes-utils.js: Add test coverage Summary: Improving test coverage in anticipation of some changes being made to `hermes-utils.js`. Moved test scripts to `hermes/__tests__` and grouped related tests. We have been delegating some of the work to local binaries via `execSync`, which can be hard to mock or test. We now use a proxy `delegateSync` method that uses `spawnSync` internally to break down the invocation into `command`, `arguments`, `options`. Instead of simply mocking based on the command being executed, we can now conditionally mock based on the arguments being passed. Added a `createTarballFromDirectory` method. This can be used later when creating different tarballs. Added `populateMockFilesystemWithHermesBuildArtifacts()` to mock the filesystem state after Hermes has been built. Changelog: [internal] Reviewed By: cipolleschi Differential Revision: D40871802 fbshipit-source-id: 4348d3c38926ec7eb13d794040a9040010879f58 --- scripts/__tests__/hermes-utils-test.js | 336 ------------- scripts/hermes/__tests__/hermes-utils-test.js | 466 ++++++++++++++++++ scripts/hermes/hermes-utils.js | 56 ++- 3 files changed, 507 insertions(+), 351 deletions(-) delete mode 100644 scripts/__tests__/hermes-utils-test.js create mode 100644 scripts/hermes/__tests__/hermes-utils-test.js diff --git a/scripts/__tests__/hermes-utils-test.js b/scripts/__tests__/hermes-utils-test.js deleted file mode 100644 index 68ee3edabab179..00000000000000 --- a/scripts/__tests__/hermes-utils-test.js +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import * as path from 'path'; - -const { - configureMakeForPrebuiltHermesC, - copyBuildScripts, - copyPodSpec, - downloadHermesSourceTarball, - expandHermesSourceTarball, - getHermesPrebuiltArtifactsTarballName, - getHermesTagSHA, - readHermesTag, - setHermesTag, - shouldUsePrebuiltHermesC, -} = require('../hermes/hermes-utils'); - -const hermesTag = - 'hermes-2022-04-28-RNv0.69.0-15d07c2edd29a4ea0b8f15ab0588a0c1adb1200f'; -const tarballContents = 'dummy string'; -const hermescContents = 'dummy string'; -const hermesTagSha = '5244f819b2f3949ca94a3a1bf75d54a8ed59d94a'; - -const ROOT_DIR = path.normalize(path.join(__dirname, '..', '..')); -const SDKS_DIR = path.join(ROOT_DIR, 'sdks'); - -const MemoryFs = require('metro-memory-fs'); - -let execCalls; -let fs; - -jest.mock('child_process', () => ({ - execSync: jest.fn(command => { - if (command.startsWith('curl')) { - fs.writeFileSync( - path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), - tarballContents, - ); - execCalls.curl = true; - return {code: 0}; - } - - if (command.startsWith('git')) { - execCalls.git = true; - return hermesTagSha + '\n'; - } - - if (command.startsWith('tar')) { - fs.mkdirSync(path.join(SDKS_DIR, 'hermes', 'utils'), { - recursive: true, - }); - fs.writeFileSync(path.join(SDKS_DIR, 'hermes', `package.json`), '{}'); - execCalls.tar = true; - return {code: 0}; - } - }), -})); - -function populateMockFilesystem() { - fs.mkdirSync(path.join(SDKS_DIR, 'hermes-engine', 'utils'), { - recursive: true, - }); - fs.writeFileSync( - path.join( - ROOT_DIR, - 'sdks', - 'hermes-engine', - 'utils', - 'build-apple-framework.sh', - ), - 'Dummy file', - ); - fs.writeFileSync( - path.join( - ROOT_DIR, - 'sdks', - 'hermes-engine', - 'utils', - 'build-ios-framework.sh', - ), - 'Dummy file', - ); - fs.writeFileSync( - path.join( - ROOT_DIR, - 'sdks', - 'hermes-engine', - 'utils', - 'build-mac-framework.sh', - ), - 'Dummy file', - ); - fs.writeFileSync( - path.join(SDKS_DIR, 'hermes-engine', 'hermes-engine.podspec'), - 'Dummy file', - ); - fs.writeFileSync( - path.join(SDKS_DIR, 'hermes-engine', 'hermes-utils.rb'), - 'Dummy file', - ); -} - -describe('hermes-utils', () => { - beforeEach(() => { - jest.resetModules(); - - jest.mock( - 'fs', - () => - new MemoryFs({ - platform: process.platform === 'win32' ? 'win32' : 'posix', - }), - ); - fs = require('fs'); - fs.reset(); - - populateMockFilesystem(); - - execCalls = Object.create(null); - }); - describe('readHermesTag', () => { - it('should return main if .hermesversion does not exist', () => { - expect(readHermesTag()).toEqual('main'); - }); - it('should fail if hermes tag is empty', () => { - fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), ''); - expect(() => { - readHermesTag(); - }).toThrow('[Hermes] .hermesversion file is empty.'); - }); - it('should return tag from .hermesversion if file exists', () => { - fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); - expect(readHermesTag()).toEqual(hermesTag); - }); - }); - describe('setHermesTag', () => { - it('should write tag to .hermesversion file', () => { - setHermesTag(hermesTag); - expect( - fs.readFileSync(path.join(SDKS_DIR, '.hermesversion'), { - encoding: 'utf8', - flag: 'r', - }), - ).toEqual(hermesTag); - }); - it('should set Hermes tag and read it back', () => { - setHermesTag(hermesTag); - expect(readHermesTag()).toEqual(hermesTag); - }); - }); - describe('getHermesPrebuiltArtifactsTarballName', () => { - it('should return Hermes tarball name', () => { - expect( - getHermesPrebuiltArtifactsTarballName('Debug', '1000.0.0'), - ).toEqual('hermes-runtime-darwin-debug-v1000.0.0.tar.gz'); - }); - it('should throw if build type is undefined', () => { - expect(() => { - getHermesPrebuiltArtifactsTarballName(); - }).toThrow('Did not specify build type.'); - }); - it('should throw if release version is undefined', () => { - expect(() => { - getHermesPrebuiltArtifactsTarballName('Release'); - }).toThrow('Did not specify release version.'); - }); - it('should return debug Hermes tarball name for RN 0.70.0', () => { - expect(getHermesPrebuiltArtifactsTarballName('Debug', '0.70.0')).toEqual( - 'hermes-runtime-darwin-debug-v0.70.0.tar.gz', - ); - }); - it('should return a wildcard Hermes tarball name for any RN version', () => { - expect(getHermesPrebuiltArtifactsTarballName('Debug', '*')).toEqual( - 'hermes-runtime-darwin-debug-v*.tar.gz', - ); - }); - }); - describe('getHermesTagSHA', () => { - it('should return trimmed commit SHA for Hermes tag', () => { - expect(getHermesTagSHA(hermesTag)).toEqual(hermesTagSha); - expect(execCalls.git).toBe(true); - }); - }); - describe('downloadHermesSourceTarball', () => { - it('should download Hermes source tarball to download dir', () => { - fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); - downloadHermesSourceTarball(); - expect(execCalls.curl).toBe(true); - expect( - fs.readFileSync( - path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ).toEqual(tarballContents); - }); - it('should not re-download Hermes tarball if tarball exists', () => { - fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); - fs.writeFileSync( - path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), - tarballContents, - ); - - downloadHermesSourceTarball(); - expect(execCalls.curl).toBeUndefined(); - }); - }); - describe('expandHermesSourceTarball', () => { - it('should expand Hermes source tarball to Hermes source dir', () => { - fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); - fs.writeFileSync( - path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), - tarballContents, - ); - expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBeFalsy(); - expandHermesSourceTarball(); - expect(execCalls.tar).toBe(true); - expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBe(true); - }); - it('should fail if Hermes source tarball does not exist', () => { - expect(() => { - expandHermesSourceTarball(); - }).toThrow('[Hermes] Could not locate Hermes tarball.'); - expect(execCalls.tar).toBeUndefined(); - }); - }); - describe('copyBuildScripts', () => { - it('should copy React Native Hermes build scripts to Hermes source directory', () => { - copyBuildScripts(); - - [ - 'build-apple-framework.sh', - 'build-ios-framework.sh', - 'build-mac-framework.sh', - ].forEach(buildScript => { - expect( - fs.readFileSync( - path.join(ROOT_DIR, 'sdks', 'hermes', 'utils', buildScript), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ).toEqual( - fs.readFileSync( - path.join(ROOT_DIR, 'sdks', 'hermes-engine', 'utils', buildScript), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ); - }); - }); - }); - describe('copyPodSpec', () => { - it('should copy React Native Hermes Podspec to Hermes source directory', () => { - copyPodSpec(); - expect( - fs.readFileSync( - path.join(SDKS_DIR, 'hermes', 'hermes-engine.podspec'), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ).toEqual( - fs.readFileSync( - path.join(SDKS_DIR, 'hermes-engine', 'hermes-engine.podspec'), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ); - }); - it('should copy hermes-utils.rb to Hermes source directory', () => { - copyPodSpec(); - expect( - fs.readFileSync(path.join(SDKS_DIR, 'hermes', 'hermes-utils.rb'), { - encoding: 'utf8', - flag: 'r', - }), - ).toEqual( - fs.readFileSync( - path.join(SDKS_DIR, 'hermes-engine', 'hermes-utils.rb'), - { - encoding: 'utf8', - flag: 'r', - }, - ), - ); - }); - }); - describe('shouldUsePrebuiltHermesC', () => { - it('returns false if path to osx hermesc does not exist', () => { - expect(shouldUsePrebuiltHermesC('macos')).toBeFalsy(); - }); - it('returns false for non-macOS', () => { - expect(shouldUsePrebuiltHermesC('windows')).toBeFalsy(); - }); - it('return true only if path to hermesc exists', () => { - fs.mkdirSync(path.join(SDKS_DIR, 'hermesc', 'osx-bin'), { - recursive: true, - }); - fs.writeFileSync( - path.join(SDKS_DIR, 'hermesc', 'osx-bin', 'hermesc'), - hermescContents, - ); - expect(shouldUsePrebuiltHermesC('macos')).toBe(true); - }); - }); - - describe('configureMakeForPrebuiltHermesC', () => { - it('creates ImportHermesC file', () => { - fs.mkdirSync(path.join(SDKS_DIR, 'hermesc', 'osx-bin'), { - recursive: true, - }); - configureMakeForPrebuiltHermesC(); - expect( - fs.existsSync( - path.join(SDKS_DIR, 'hermesc', 'osx-bin', 'ImportHermesc.cmake'), - ), - ).toBe(true); - }); - }); -}); diff --git a/scripts/hermes/__tests__/hermes-utils-test.js b/scripts/hermes/__tests__/hermes-utils-test.js new file mode 100644 index 00000000000000..f9c446b9a818fe --- /dev/null +++ b/scripts/hermes/__tests__/hermes-utils-test.js @@ -0,0 +1,466 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import * as path from 'path'; + +const os = require('os'); + +const { + configureMakeForPrebuiltHermesC, + copyBuildScripts, + copyPodSpec, + createHermesPrebuiltArtifactsTarball, + createTarballFromDirectory, + downloadHermesSourceTarball, + expandHermesSourceTarball, + getHermesTarballDownloadPath, + getHermesPrebuiltArtifactsTarballName, + getHermesTagSHA, + readHermesTag, + setHermesTag, + shouldUsePrebuiltHermesC, +} = require('../hermes-utils'); + +const hermesTag = + 'hermes-2022-04-28-RNv0.69.0-15d07c2edd29a4ea0b8f15ab0588a0c1adb1200f'; +const tarballContents = 'dummy string'; +const hermescContents = 'dummy string'; +const hermesTagSha = '5244f819b2f3949ca94a3a1bf75d54a8ed59d94a'; + +const ROOT_DIR = path.normalize(path.join(__dirname, '../../..')); +const SDKS_DIR = path.join(ROOT_DIR, 'sdks'); + +const MemoryFs = require('metro-memory-fs'); + +let execCalls, spawnCalls; +let fs; + +jest.mock('child_process', () => ({ + execSync: jest.fn((command, options) => { + // git is used in getHermesTagSHA to obtain the commit sha for the latest commit to Hermes main + if (command.startsWith('git')) { + execCalls.git = true; + return hermesTagSha + '\n'; + } + }), + spawnSync: jest.fn((command, args, options) => { + // curl is used in downloadHermesSourceTarball to fetch the source code from github.com/facebook/hermes for a specific Hermes commit sha + if (command === 'curl') { + const downloadPath = args[2]; + fs.writeFileSync(downloadPath, tarballContents); + spawnCalls.curl = true; + return {code: 0}; + } + + // tar is used in createTarballFromDirectory + if (command === 'tar') { + spawnCalls.tar = true; + + if (args[0] === '-zxf') { + // We are expanding the tarball + fs.mkdirSync(path.join(SDKS_DIR, 'hermes/utils'), { + recursive: true, + }); + fs.writeFileSync(path.join(SDKS_DIR, 'hermes/package.json'), '{}'); + return {code: 0}; + } else if (args[2] === '-czvf') { + // We are creating the tarball + const filename = args[3]; + fs.writeFileSync(filename, tarballContents); + return {code: 0}; + } + } + + // rsync is used in createHermesPrebuiltArtifactsTarball + if (command === 'rsync') { + spawnCalls.rsync = true; + spawnCalls.rsyncArgs = args; + const destination = args[args.length - 1]; + + // Create destination directory + fs.mkdirSync(path.join(options.cwd, destination), { + recursive: true, + }); + } + }), +})); + +function populateMockFilesystemWithHermesBuildScripts() { + fs.mkdirSync(path.join(SDKS_DIR, 'hermes-engine/utils'), { + recursive: true, + }); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermes-engine/utils/build-apple-framework.sh'), + 'Dummy file', + ); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermes-engine/utils/build-ios-framework.sh'), + 'Dummy file', + ); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermes-engine/utils/build-mac-framework.sh'), + 'Dummy file', + ); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermes-engine/hermes-engine.podspec'), + 'Dummy file', + ); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermes-engine/hermes-utils.rb'), + 'Dummy file', + ); +} + +function populateMockFilesystemWithHermesBuildArtifacts() { + fs.mkdirSync(os.tmpdir(), {recursive: true}); + const frameworksDir = path.join( + SDKS_DIR, + 'hermes/destroot/Library/Frameworks', + ); + fs.mkdirSync(path.join(frameworksDir, 'macosx/hermes.framework'), { + recursive: true, + }); + fs.mkdirSync(path.join(frameworksDir, 'universal/hermes.xcframework'), { + recursive: true, + }); + + const dsymsDirs = [ + 'macosx', + 'universal/hermes.xcframework/ios-arm64/dSYMs', + 'universal/hermes.xcframework/ios-arm64_x86_64-simulator/dSYMs', + 'universal/hermes.xcframework/ios-arm64_x86_64-maccatalyst/dSYMs', + ]; + + for (const dsymsDir of dsymsDirs) { + fs.mkdirSync(path.join(frameworksDir, dsymsDir, 'hermes.framework.dSYM'), { + recursive: true, + }); + } +} + +describe('hermes-utils', () => { + beforeEach(() => { + jest.resetModules(); + + jest.mock( + 'fs', + () => + new MemoryFs({ + platform: process.platform === 'win32' ? 'win32' : 'posix', + }), + ); + fs = require('fs'); + fs.reset(); + + populateMockFilesystemWithHermesBuildScripts(); + + execCalls = Object.create(null); + spawnCalls = Object.create(null); + }); + + describe('Versioning Hermes', () => { + describe('readHermesTag', () => { + it('should return main if .hermesversion does not exist', () => { + expect(readHermesTag()).toEqual('main'); + }); + it('should fail if hermes tag is empty', () => { + fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), ''); + expect(() => { + readHermesTag(); + }).toThrow('[Hermes] .hermesversion file is empty.'); + }); + it('should return tag from .hermesversion if file exists', () => { + fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); + expect(readHermesTag()).toEqual(hermesTag); + }); + }); + + describe('setHermesTag', () => { + it('should write tag to .hermesversion file', () => { + setHermesTag(hermesTag); + expect( + fs.readFileSync(path.join(SDKS_DIR, '.hermesversion'), { + encoding: 'utf8', + flag: 'r', + }), + ).toEqual(hermesTag); + }); + it('should set Hermes tag and read it back', () => { + setHermesTag(hermesTag); + expect(readHermesTag()).toEqual(hermesTag); + }); + }); + + describe('getHermesTagSHA', () => { + it('should return trimmed commit SHA for Hermes tag', () => { + expect(getHermesTagSHA(hermesTag)).toEqual(hermesTagSha); + expect(execCalls.git).toBe(true); + }); + }); + }); + + describe('Downloading Hermes', () => { + describe('getHermesTarballDownloadPath', () => { + it('returns download path with Hermes tag sha', () => { + const hermesTarballDownloadPath = + getHermesTarballDownloadPath(hermesTag); + expect(hermesTarballDownloadPath).toEqual( + path.join( + SDKS_DIR, + 'download', + `hermes-${getHermesTagSHA(hermesTag)}.tgz`, + ), + ); + }); + }); + describe('downloadHermesSourceTarball', () => { + it('should download Hermes source tarball to download dir', () => { + fs.writeFileSync(path.join(SDKS_DIR, '.hermesversion'), hermesTag); + const hermesTarballDownloadPath = + getHermesTarballDownloadPath(hermesTag); + downloadHermesSourceTarball(); + expect(spawnCalls.curl).toBe(true); + expect( + fs.readFileSync(hermesTarballDownloadPath, { + encoding: 'utf8', + flag: 'r', + }), + ).toEqual(tarballContents); + }); + it('should not re-download Hermes source tarball if tarball exists', () => { + fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); + fs.writeFileSync( + path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), + tarballContents, + ); + + downloadHermesSourceTarball(); + expect(spawnCalls.curl).toBeUndefined(); + }); + }); + + describe('expandHermesSourceTarball', () => { + it('should expand Hermes source tarball to Hermes source dir', () => { + fs.mkdirSync(path.join(SDKS_DIR, 'download'), {recursive: true}); + fs.writeFileSync( + path.join(SDKS_DIR, 'download', `hermes-${hermesTagSha}.tgz`), + tarballContents, + ); + expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBeFalsy(); + expandHermesSourceTarball(); + expect(fs.existsSync(path.join(SDKS_DIR, 'hermes'))).toBe(true); + }); + it('should fail if Hermes source tarball does not exist', () => { + expect(() => { + expandHermesSourceTarball(); + }).toThrow('[Hermes] Could not locate Hermes tarball.'); + }); + }); + }); + + describe('Configuring Hermes Build', () => { + describe('copyBuildScripts', () => { + it('should copy React Native Hermes build scripts to Hermes source directory', () => { + copyBuildScripts(); + + [ + 'build-apple-framework.sh', + 'build-ios-framework.sh', + 'build-mac-framework.sh', + ].forEach(buildScript => { + expect( + fs.readFileSync( + path.join(ROOT_DIR, 'sdks/hermes/utils', buildScript), + { + encoding: 'utf8', + flag: 'r', + }, + ), + ).toEqual( + fs.readFileSync( + path.join(ROOT_DIR, 'sdks/hermes-engine/utils', buildScript), + { + encoding: 'utf8', + flag: 'r', + }, + ), + ); + }); + }); + }); + describe('copyPodSpec', () => { + it('should copy React Native Hermes Podspec to Hermes source directory', () => { + copyPodSpec(); + expect( + fs.readFileSync(path.join(SDKS_DIR, 'hermes/hermes-engine.podspec'), { + encoding: 'utf8', + flag: 'r', + }), + ).toEqual( + fs.readFileSync( + path.join(SDKS_DIR, 'hermes-engine/hermes-engine.podspec'), + { + encoding: 'utf8', + flag: 'r', + }, + ), + ); + }); + it('should copy hermes-utils.rb to Hermes source directory', () => { + copyPodSpec(); + expect( + fs.readFileSync(path.join(SDKS_DIR, 'hermes/hermes-utils.rb'), { + encoding: 'utf8', + flag: 'r', + }), + ).toEqual( + fs.readFileSync( + path.join(SDKS_DIR, 'hermes-engine/hermes-utils.rb'), + { + encoding: 'utf8', + flag: 'r', + }, + ), + ); + }); + }); + describe('shouldUsePrebuiltHermesC', () => { + it('returns false if path to osx hermesc does not exist', () => { + expect(shouldUsePrebuiltHermesC('macos')).toBeFalsy(); + }); + it('returns false for non-macOS', () => { + expect(shouldUsePrebuiltHermesC('windows')).toBeFalsy(); + }); + it('return true only if path to hermesc exists', () => { + fs.mkdirSync(path.join(SDKS_DIR, 'hermesc/osx-bin'), { + recursive: true, + }); + fs.writeFileSync( + path.join(SDKS_DIR, 'hermesc/osx-bin/hermesc'), + hermescContents, + ); + expect(shouldUsePrebuiltHermesC('macos')).toBe(true); + }); + }); + + describe('configureMakeForPrebuiltHermesC', () => { + it('creates ImportHermesC file', () => { + fs.mkdirSync(path.join(SDKS_DIR, 'hermesc/osx-bin'), { + recursive: true, + }); + configureMakeForPrebuiltHermesC(); + expect( + fs.existsSync( + path.join(SDKS_DIR, 'hermesc/osx-bin/ImportHermesc.cmake'), + ), + ).toBe(true); + }); + }); + }); + + describe('Packaging Hermes', () => { + beforeEach(() => { + populateMockFilesystemWithHermesBuildArtifacts(); + }); + + describe('createTarballFromDirectory', () => { + it('should create the tarball', () => { + fs.mkdirSync(path.join(SDKS_DIR, 'downloads'), {recursive: true}); + const tarballFilename = path.join( + SDKS_DIR, + 'downloads/hermes-runtime-darwin.tar.gz', + ); + createTarballFromDirectory( + path.join(SDKS_DIR, 'hermes/destroot'), + tarballFilename, + ); + expect(spawnCalls.tar).toBe(true); + expect(fs.existsSync(tarballFilename)).toBe(true); + }); + }); + + describe('getHermesPrebuiltArtifactsTarballName', () => { + it('should return Hermes prebuilts tarball name', () => { + expect( + getHermesPrebuiltArtifactsTarballName('Debug', '1000.0.0'), + ).toEqual('hermes-runtime-darwin-debug-v1000.0.0.tar.gz'); + }); + it('should throw if build type is undefined', () => { + expect(() => { + getHermesPrebuiltArtifactsTarballName(); + }).toThrow('Did not specify build type.'); + }); + it('should throw if release version is undefined', () => { + expect(() => { + getHermesPrebuiltArtifactsTarballName('Release'); + }).toThrow('Did not specify release version.'); + }); + it('should return debug Hermes prebuilts tarball name for RN 0.70.0', () => { + expect( + getHermesPrebuiltArtifactsTarballName('Debug', '0.70.0'), + ).toEqual('hermes-runtime-darwin-debug-v0.70.0.tar.gz'); + }); + it('should return a wildcard Hermes prebuilts tarball name for any RN version', () => { + expect(getHermesPrebuiltArtifactsTarballName('Debug', '*')).toEqual( + 'hermes-runtime-darwin-debug-v*.tar.gz', + ); + }); + }); + + describe('createHermesPrebuiltArtifactsTarball', () => { + it('creates tarball', () => { + const tarballOutputDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'hermes-prebuilts-'), + ); + fs.mkdirSync(tarballOutputDir, { + recursive: true, + }); + + const excludeDebugSymbols = false; + const tarballOutputPath = createHermesPrebuiltArtifactsTarball( + path.join(SDKS_DIR, 'hermes'), + 'Debug', + '1000.0.0', + tarballOutputDir, + excludeDebugSymbols, + ); + expect(fs.existsSync(tarballOutputPath)).toBe(true); + expect(spawnCalls.rsync).toBe(true); + // rsync -a src dest + expect(spawnCalls.rsyncArgs.length).toEqual(3); + }); + + it('creates tarball with debug symbols excluded', () => { + const tarballOutputDir = fs.mkdtempSync( + path.join(os.tmpdir(), 'hermes-prebuilts-'), + ); + fs.mkdirSync(tarballOutputDir, { + recursive: true, + }); + + const excludeDebugSymbols = true; + const tarballOutputPath = createHermesPrebuiltArtifactsTarball( + path.join(SDKS_DIR, 'hermes'), + 'Debug', + '1000.0.0', + tarballOutputDir, + excludeDebugSymbols, + ); + expect(fs.existsSync(tarballOutputPath)).toBe(true); + expect(spawnCalls.rsync).toBe(true); + + // When the debug symbols are excluded, we pass an additional two parameters to rsync: + // rsync -a --exclude=dSYMs/ --exclude=*.dSYM/ src dest + expect(spawnCalls.rsyncArgs.length).toEqual(5); + expect(spawnCalls.rsyncArgs[1]).toEqual('--exclude=dSYMs/'); + expect(spawnCalls.rsyncArgs[2]).toEqual('--exclude=*.dSYM/'); + }); + }); + }); +}); diff --git a/scripts/hermes/hermes-utils.js b/scripts/hermes/hermes-utils.js index 2ddbfe522417e9..918e3014f26acf 100644 --- a/scripts/hermes/hermes-utils.js +++ b/scripts/hermes/hermes-utils.js @@ -12,7 +12,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); -const {execSync} = require('child_process'); +const {execSync, spawnSync} = require('child_process'); const SDKS_DIR = path.normalize(path.join(__dirname, '..', '..', 'sdks')); const HERMES_DIR = path.join(SDKS_DIR, 'hermes'); @@ -27,6 +27,17 @@ const MACOS_IMPORT_HERMESC_PATH = path.join( 'ImportHermesc.cmake', ); +/** + * Delegate execution to the supplied command. + * + * @param command Path to the command. + * @param args Array of arguments pass to the command. + * @param options child process options. + */ +function delegateSync(command, args, options) { + return spawnSync(command, args, {stdio: 'inherit', ...options}); +} + function readHermesTag() { if (fs.existsSync(HERMES_TAG_FILE_PATH)) { const data = fs @@ -90,7 +101,7 @@ function downloadHermesSourceTarball() { `[Hermes] Downloading Hermes source code for commit ${hermesTagSHA}`, ); try { - execSync(`curl ${hermesTarballUrl} -Lo ${hermesTarballDownloadPath}`); + delegateSync('curl', [hermesTarballUrl, '-Lo', hermesTarballDownloadPath]); } catch (error) { throw new Error(`[Hermes] Failed to download Hermes tarball. ${error}`); } @@ -110,9 +121,13 @@ function expandHermesSourceTarball() { } console.info(`[Hermes] Expanding Hermes tarball for commit ${hermesTagSHA}`); try { - execSync( - `tar -zxf ${hermesTarballDownloadPath} --strip-components=1 --directory ${HERMES_DIR}`, - ); + delegateSync('tar', [ + '-zxf', + hermesTarballDownloadPath, + '--strip-components=1', + '--directory', + HERMES_DIR, + ]); } catch (error) { throw new Error('[Hermes] Failed to expand Hermes tarball.'); } @@ -207,6 +222,14 @@ function getHermesPrebuiltArtifactsTarballName(buildType, releaseVersion) { return `hermes-runtime-darwin-${buildType.toLowerCase()}-v${releaseVersion}.tar.gz`; } +/** + * Creates a tarball with the contents of the supplied directory. + */ +function createTarballFromDirectory(directory, filename) { + const args = ['-C', directory, '-czvf', filename, '.']; + delegateSync('tar', args); +} + function createHermesPrebuiltArtifactsTarball( hermesDir, buildType, @@ -231,35 +254,36 @@ function createHermesPrebuiltArtifactsTarball( args.push('--exclude=dSYMs/'); args.push('--exclude=*.dSYM/'); } - execSync(`rsync ${args.join(' ')} ./destroot ${tarballTempDir}`, { + args.push('./destroot'); + args.push(tarballTempDir); + delegateSync('rsync', args, { cwd: hermesDir, }); if (fs.existsSync(path.join(hermesDir, 'LICENSE'))) { - execSync(`cp LICENSE ${tarballTempDir}`, {cwd: hermesDir}); + delegateSync('cp', ['LICENSE', tarballTempDir], {cwd: hermesDir}); } } catch (error) { throw new Error(`Failed to copy destroot to tempdir: ${error}`); } - const tarballFilename = getHermesPrebuiltArtifactsTarballName( - buildType, - releaseVersion, + const tarballFilename = path.join( + tarballOutputDir, + getHermesPrebuiltArtifactsTarballName(buildType, releaseVersion), ); - const tarballOutputPath = path.join(tarballOutputDir, tarballFilename); try { - execSync(`tar -C ${tarballTempDir} -czvf ${tarballOutputPath} .`); + createTarballFromDirectory(tarballTempDir, tarballFilename); } catch (error) { throw new Error(`[Hermes] Failed to create tarball: ${error}`); } - if (!fs.existsSync(tarballOutputPath)) { + if (!fs.existsSync(tarballFilename)) { throw new Error( - `Tarball creation failed, could not locate tarball at ${tarballOutputPath}`, + `Tarball creation failed, could not locate tarball at ${tarballFilename}`, ); } - return tarballOutputPath; + return tarballFilename; } function validateHermesFrameworksExist(destrootDir) { @@ -288,9 +312,11 @@ module.exports = { copyBuildScripts, copyPodSpec, createHermesPrebuiltArtifactsTarball, + createTarballFromDirectory, downloadHermesSourceTarball, expandHermesSourceTarball, getHermesTagSHA, + getHermesTarballDownloadPath, getHermesPrebuiltArtifactsTarballName, readHermesTag, setHermesTag, From 74cb441e97a16c133d9540a00962e420e42edb47 Mon Sep 17 00:00:00 2001 From: William Sawyer Date: Wed, 2 Nov 2022 05:37:43 -0700 Subject: [PATCH 107/169] Corrected documentation to be more gramatically correct (#35141) Summary: The documentation for `useColorScheme()` suggested that the user's preferred color scheme will be 'Dark Mode'. Instead suggesting 'Dark Mode' as an example of what the user's preferred color scheme could be is more correct. ## Changelog [INTERNAL] [FIXED] - Edited documentation for `useColorScheme()` hook Edited ```javascript /** * A new useColorScheme hook is provided as the preferred way of accessing * the user's preferred color scheme (aka Dark Mode). */ export function useColorScheme(): ColorSchemeName; ``` to ```javascript /** * A new useColorScheme hook is provided as the preferred way of accessing * the user's preferred color scheme (e.g. Dark Mode). */ export function useColorScheme(): ColorSchemeName; ``` Pull Request resolved: https://github.com/facebook/react-native/pull/35141 Test Plan: Documentation only - no testing required. Reviewed By: cipolleschi Differential Revision: D40934781 Pulled By: rshest fbshipit-source-id: acac8947c3f99016839be27f505066e8992a20fa --- Libraries/Utilities/Appearance.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Libraries/Utilities/Appearance.d.ts b/Libraries/Utilities/Appearance.d.ts index 4cef70aa073ab9..7d2faf69d8cec4 100644 --- a/Libraries/Utilities/Appearance.d.ts +++ b/Libraries/Utilities/Appearance.d.ts @@ -38,6 +38,6 @@ export namespace Appearance { /** * A new useColorScheme hook is provided as the preferred way of accessing - * the user's preferred color scheme (aka Dark Mode). + * the user's preferred color scheme (e.g. Dark Mode). */ export function useColorScheme(): ColorSchemeName; From 64c3906280bbb643f758fa86f92a6d179007e36b Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Wed, 2 Nov 2022 06:06:52 -0700 Subject: [PATCH 108/169] Remove redundant import from TextInputSharedExamples Summary: changelog: [internal] Fix lint error Reviewed By: cipolleschi Differential Revision: D40936194 fbshipit-source-id: 24987f86f1f95d42f978baaa560bfd57381ca5a4 --- .../rn-tester/js/examples/TextInput/TextInputSharedExamples.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js b/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js index 76ce20be27bf90..e5b1c4f580bfcb 100644 --- a/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js +++ b/packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js @@ -10,8 +10,6 @@ 'use strict'; -import type {HostComponent} from 'react-native'; - const React = require('react'); const { From e89d223c31e9360a5e5f55f97ba3bfc0405fb2af Mon Sep 17 00:00:00 2001 From: Ruslan Shestopalyuk Date: Wed, 2 Nov 2022 07:44:34 -0700 Subject: [PATCH 109/169] Remove misleading comment about RootTag type not being opaque Summary: Changelog: [Internal] Reviewed By: lunaleaps Differential Revision: D40902247 fbshipit-source-id: 5ed8f69bb46e35d5250bd04898765ead500d7db6 --- Libraries/ReactNative/RootTag.js | 1 - 1 file changed, 1 deletion(-) diff --git a/Libraries/ReactNative/RootTag.js b/Libraries/ReactNative/RootTag.js index e2cb96cfa58056..693fa31cbb7989 100644 --- a/Libraries/ReactNative/RootTag.js +++ b/Libraries/ReactNative/RootTag.js @@ -10,7 +10,6 @@ import * as React from 'react'; -// TODO: Make this into an opaque type. export opaque type RootTag = number; export const RootTagContext: React$Context = From 0fd282f2cd7d383a1ac7549e644a8865c4894d34 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 2 Nov 2022 08:22:05 -0700 Subject: [PATCH 110/169] Link against the app codegen if available (#35176) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35176 This commit extends the ReactNative-application.cmake logic so that if the app is using codegen at the app level, the generate library is properly built and linked. It helps us simplify the RN Tester setup and makes it easier for app users to use the codegen at the app level. Changelog: [Internal] [Changed] - [Android] Link against the app codegen if available Reviewed By: cipolleschi Differential Revision: D40936941 fbshipit-source-id: 26fa4d764fb369c987e94e0c3bce61841b982b27 --- .../cmake-utils/ReactNative-application.cmake | 12 ++++++++++-- .../android/app/src/main/jni/CMakeLists.txt | 4 +--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/ReactAndroid/cmake-utils/ReactNative-application.cmake b/ReactAndroid/cmake-utils/ReactNative-application.cmake index 78cf9dfd0f16b9..2b2a79d8694a4a 100644 --- a/ReactAndroid/cmake-utils/ReactNative-application.cmake +++ b/ReactAndroid/cmake-utils/ReactNative-application.cmake @@ -95,7 +95,7 @@ target_link_libraries(${CMAKE_PROJECT_NAME} turbomodulejsijni # prefab ready yoga) # prefab ready -# We use an interface targe to propagate flags to all the generated targets +# We use an interface target to propagate flags to all the generated targets # such as the folly flags or others. add_library(common_flags INTERFACE) target_compile_options(common_flags INTERFACE ${folly_FLAGS}) @@ -106,6 +106,14 @@ if(EXISTS ${PROJECT_BUILD_DIR}/generated/rncli/src/main/jni/Android-rncli.cmake) include(${PROJECT_BUILD_DIR}/generated/rncli/src/main/jni/Android-rncli.cmake) target_link_libraries(${CMAKE_PROJECT_NAME} ${AUTOLINKED_LIBRARIES}) foreach(autolinked_library ${AUTOLINKED_LIBRARIES}) - target_link_libraries(autolinked_library INTERFACE common_flags) + target_link_libraries(autolinked_library common_flags) endforeach() endif() + +# If project is running codegen at the app level, we want to link and build the generated library. +if(EXISTS ${PROJECT_BUILD_DIR}/generated/source/codegen/jni/CMakeLists.txt) + add_subdirectory(${PROJECT_BUILD_DIR}/generated/source/codegen/jni/ codegen_app_build) + get_property(APP_CODEGEN_TARGET DIRECTORY ${PROJECT_BUILD_DIR}/generated/source/codegen/jni/ PROPERTY BUILDSYSTEM_TARGETS) + target_link_libraries(${CMAKE_PROJECT_NAME} ${APP_CODEGEN_TARGET}) + target_link_libraries(${APP_CODEGEN_TARGET} common_flags) +endif() diff --git a/packages/rn-tester/android/app/src/main/jni/CMakeLists.txt b/packages/rn-tester/android/app/src/main/jni/CMakeLists.txt index e263a03350c428..d1af2d92e230ca 100644 --- a/packages/rn-tester/android/app/src/main/jni/CMakeLists.txt +++ b/packages/rn-tester/android/app/src/main/jni/CMakeLists.txt @@ -10,10 +10,8 @@ project(appmodules) include(${REACT_ANDROID_DIR}/cmake-utils/ReactNative-application.cmake) -add_subdirectory(${PROJECT_BUILD_DIR}/generated/source/codegen/jni/ codegen_build) add_subdirectory(${REACT_COMMON_DIR}/react/nativemodule/samples/platform/android/ sampleturbomodule_build) -# RN Tester needs to link against the local codegen-ned library and a sample turbomobule +# RN Tester needs to link against the sample turbomobule target_link_libraries(${CMAKE_PROJECT_NAME} - react_codegen_AppSpecs sampleturbomodule) From c540ff7bd156a3b1636161a42128dfc2b575e031 Mon Sep 17 00:00:00 2001 From: Lorenzo Sciandra Date: Wed, 2 Nov 2022 08:23:50 -0700 Subject: [PATCH 111/169] fix(local-e2e-script): add logic to handle maven local for iOS and Android accordingly (#35104) Summary: This PR is a follow up of https://github.com/facebook/react-native/pull/35075 and https://github.com/facebook/react-native/commit/1546666a6d713ef756b2f11de9581e3b2bbe08dc to ensure that even in the local e2e testing scenario the new maven approach is followed - without this, RNTestProject on Android won't work, like so: Screenshot 2022-10-27 at 12 15 38 And iOS will always build everything from source every time. This PR addresses both by generating the artifacts locally, and passing them to RNTestProject as if they were coming from a url (mimicking as closely as possible the behaviour for the final user) In doing so, there's been some refactoring to prep the ground for follow up work. * refactor CI to rely less on scripts directly in the CircleCI config, but invoke .js ones * we should be able to trigger more the "manual" artifacts generation so that it will only happen once between RNTester and RNTestProject, and we can pass existing artifacts to the other flows. * once all of this in place, a very good improvement would be to be able to download the maven artifacts kind of like nightlies and stables do. This will only be viable by checking that there's no local changes, after which there needs to be logic to pull down from CircleCI the artifacts based on git commit <-> circleCI job references. --- While at it, I've also fixed the hermes-engine podspec logic for detecting if it's on CI: basically the local e2e script needs to align with the changes done here: https://github.com/facebook/react-native/commit/4b512077354eb4702ce144e9958d7513c1607275 but as you can see there, the condition was actually inconsistent across the various files, so realigned to `CI === 'true'`. We probably didn't catch that so far 'cause the other condition in the hermes podspect (existence of `hermestag_file`) is only true on release branches and this new logic has not been in any release branches yet. ## Changelog [Internal] [Fixed] - add logic to local e2e script to handle maven local for iOS and Android accordingly Pull Request resolved: https://github.com/facebook/react-native/pull/35104 Test Plan: Run ` yarn test-e2e-local -t RNTestProject -p Android` successfully. Run ` yarn test-e2e-local -t RNTestProject -p iOS` successfully. On the pod install stage, you will see `[Hermes] Using pre-built Hermes binaries from local path.` Reviewed By: dmytrorykun Differential Revision: D40893239 Pulled By: cipolleschi fbshipit-source-id: a31217ec4f177383c62292d00fabc4cbe4391cfd --- scripts/release-utils.js | 41 ++++++- scripts/test-e2e-local-clean.js | 1 + scripts/test-e2e-local.js | 108 ++++++++++++------ sdks/hermes-engine/hermes-engine.podspec | 4 +- .../hermes-engine/utils/build-hermes-xcode.sh | 0 .../utils/build-hermesc-xcode.sh | 0 sdks/hermes-engine/utils/copy-hermes-xcode.sh | 0 7 files changed, 119 insertions(+), 35 deletions(-) mode change 100644 => 100755 sdks/hermes-engine/utils/build-hermes-xcode.sh mode change 100644 => 100755 sdks/hermes-engine/utils/build-hermesc-xcode.sh mode change 100644 => 100755 sdks/hermes-engine/utils/copy-hermes-xcode.sh diff --git a/scripts/release-utils.js b/scripts/release-utils.js index 0ade67ac98b3b3..5b018bdb03b06c 100644 --- a/scripts/release-utils.js +++ b/scripts/release-utils.js @@ -9,9 +9,11 @@ 'use strict'; -const {exec, echo, exit, test, env} = require('shelljs'); +const {exec, echo, exit, test, env, pushd, popd} = require('shelljs'); const {saveFiles} = require('./scm-utils'); +const {createHermesPrebuiltArtifactsTarball} = require('./hermes/hermes-utils'); +// TODO: we should probably remove this because of this? https://github.com/facebook/react-native/pull/34846 function saveFilesToRestore(tmpPublishingFolder) { const filesToSaveAndRestore = [ 'template/Gemfile', @@ -94,8 +96,45 @@ function publishAndroidArtifactsToMaven(releaseVersion, isNightly) { echo('Published artifacts to Maven Central'); } +function generateiOSArtifacts( + jsiFolder, + hermesCoreSourceFolder, + buildType, + releaseVersion, + targetFolder, +) { + pushd(`${hermesCoreSourceFolder}`); + + //Need to generate hermesc + exec( + `${hermesCoreSourceFolder}/utils/build-hermesc-xcode.sh ${hermesCoreSourceFolder}/build_host_hermesc`, + ); + + //Generating iOS Artifacts + exec( + `JSI_PATH=${jsiFolder} BUILD_TYPE=${buildType} ${hermesCoreSourceFolder}/utils/build-mac-framework.sh`, + ); + + exec( + `JSI_PATH=${jsiFolder} BUILD_TYPE=${buildType} ${hermesCoreSourceFolder}/utils/build-ios-framework.sh`, + ); + + popd(); + + const tarballOutputPath = createHermesPrebuiltArtifactsTarball( + hermesCoreSourceFolder, + buildType, + releaseVersion, + targetFolder, + true, // this is excludeDebugSymbols, we keep it as the default + ); + + return tarballOutputPath; +} + module.exports = { generateAndroidArtifacts, + generateiOSArtifacts, publishAndroidArtifactsToMaven, saveFilesToRestore, }; diff --git a/scripts/test-e2e-local-clean.js b/scripts/test-e2e-local-clean.js index 6dd5f9080db770..59f6333d793ffa 100644 --- a/scripts/test-e2e-local-clean.js +++ b/scripts/test-e2e-local-clean.js @@ -43,6 +43,7 @@ if (isPackagerRunning() === 'running') { // Android console.info('\n** Cleaning Gradle build artifacts **\n'); exec('./gradlew cleanAll'); +exec('rm -rf /tmp/maven-local'); // iOS console.info('\n** Nuking the derived data folder **\n'); diff --git a/scripts/test-e2e-local.js b/scripts/test-e2e-local.js index de157bde11253b..b4c2175d4afea0 100644 --- a/scripts/test-e2e-local.js +++ b/scripts/test-e2e-local.js @@ -16,7 +16,7 @@ * and to make it more accessible for other devs to play around with. */ -const {exec, exit, pushd, popd, pwd, cd} = require('shelljs'); +const {exec, exit, pushd, popd, pwd, cd, cp} = require('shelljs'); const yargs = require('yargs'); const fs = require('fs'); const path = require('path'); @@ -31,8 +31,14 @@ const { const { generateAndroidArtifacts, saveFilesToRestore, + generateiOSArtifacts, } = require('./release-utils'); +const { + downloadHermesSourceTarball, + expandHermesSourceTarball, +} = require('./hermes/hermes-utils'); + const argv = yargs .option('t', { alias: 'target', @@ -65,6 +71,12 @@ if (isPackagerRunning() === 'running') { exec("lsof -i :8081 | grep LISTEN | /usr/bin/awk '{print $2}' | xargs kill"); } +const onReleaseBranch = exec('git rev-parse --abbrev-ref HEAD', { + silent: true, +}) + .stdout.trim() + .endsWith('-stable'); + if (argv.target === 'RNTester') { // FIXME: make sure that the commands retains colors // (--ansi) doesn't always work @@ -76,10 +88,15 @@ if (argv.target === 'RNTester') { argv.hermes ? 'Hermes' : 'JSC' } version of RNTester iOS with the new Architecture enabled`, ); + + // remember that for this to be successful + // you should have run bundle install once + // in your local setup - also: if I'm on release branch, I pick the + // hermes ref from the hermes ref file (see hermes-engine.podspec) exec( `cd packages/rn-tester && USE_HERMES=${ argv.hermes ? 1 : 0 - } RCT_NEW_ARCH_ENABLED=1 bundle exec pod install --ansi`, + } CI=${onReleaseBranch} RCT_NEW_ARCH_ENABLED=1 bundle exec pod install --ansi`, ); // if everything succeeded so far, we can launch Metro and the app @@ -113,12 +130,14 @@ if (argv.target === 'RNTester') { // if everything succeeded so far, we can launch Metro and the app // start the Metro server in a separate window launchPackagerInSeparateWindow(); - // just to make sure that the Android up won't have troubles finding the Metro server - exec('adb reverse tcp:8081 tcp:8081'); + // launch the app exec( 'adb shell am start -n com.facebook.react.uiapp/com.facebook.react.uiapp.RNTesterActivity', ); + + // just to make sure that the Android up won't have troubles finding the Metro server + exec('adb reverse tcp:8081 tcp:8081'); } } else { console.info("We're going to test a fresh new RN project"); @@ -147,19 +166,51 @@ if (argv.target === 'RNTester') { // this is needed to generate the Android artifacts correctly exec(`node scripts/set-rn-version.js --to-version ${releaseVersion}`).code; - // Generate native files (Android only for now) + // Generate native files for Android generateAndroidArtifacts(releaseVersion, tmpPublishingFolder); + // Setting up generating native iOS (will be done later) + const repoRoot = pwd(); + const jsiFolder = `${repoRoot}/ReactCommon/jsi`; + const hermesCoreSourceFolder = `${repoRoot}/sdks/hermes`; + + if (!fs.existsSync(hermesCoreSourceFolder)) { + console.info('The Hermes source folder is missing. Downloading...'); + downloadHermesSourceTarball(); + expandHermesSourceTarball(); + } + + // need to move the scripts inside the local hermes cloned folder + // cp sdks/hermes-engine/utils/*.sh /utils/. + cp( + `${repoRoot}/sdks/hermes-engine/utils/*.sh`, + `${repoRoot}/sdks/hermes/utils/.`, + ); + + // for this scenario, we only need to create the debug build + // (env variable PRODUCTION defines that podspec side) + const buildType = 'Debug'; + + // the android ones get set into /private/tmp/maven-local + const localMavenPath = '/private/tmp/maven-local'; + + // Generate native files for iOS + const tarballOutputPath = generateiOSArtifacts( + jsiFolder, + hermesCoreSourceFolder, + buildType, + releaseVersion, + localMavenPath, + ); + // create locally the node module exec('npm pack'); - const localNodeTGZPath = `${pwd()}/react-native-${releaseVersion}.tgz`; + const localNodeTGZPath = `${repoRoot}/react-native-${releaseVersion}.tgz`; exec(`node scripts/set-rn-template-version.js "file:${localNodeTGZPath}"`); - const repoRoot = pwd(); - pushd('/tmp/'); - // need to avoid the pod install step because it will fail! (see above) + // need to avoid the pod install step - we'll do it later exec( `node ${repoRoot}/cli.js init RNTestProject --template ${repoRoot} --skip-install`, ); @@ -167,30 +218,23 @@ if (argv.target === 'RNTester') { cd('RNTestProject'); exec('yarn install'); + // need to do this here so that Android will be properly setup either way + exec( + 'echo "REACT_NATIVE_MAVEN_LOCAL_REPO=/private/tmp/maven-local" >> android/gradle.properties', + ); + + // doing the pod install here so that it's easier to play around RNTestProject + cd('ios'); + exec('bundle install'); + exec( + `HERMES_ENGINE_TARBALL_PATH=${tarballOutputPath} USE_HERMES=${ + argv.hermes ? 1 : 0 + } bundle exec pod install --ansi`, + ); + + cd('..'); + if (argv.platform === 'iOS') { - // if we want iOS, we need to do pod install - but with a trick - cd('ios'); - exec('bundle install'); - - // TODO: we should be able to also use HERMES_ENGINE_TARBALL_PATH - // if we can make RNTester step generate it already so that it gets reused - - // need to discern if it's main branch or release branch - if (baseVersion === '1000.0.0') { - // main branch - exec(`USE_HERMES=${argv.hermes ? 1 : 0} bundle exec pod install --ansi`); - } else { - // TODO: to test this, I need to apply changes on top of a release branch - // a release branch - // copy over the .hermesversion file from react-native core into the RNTestProject - exec(`cp -f ${repoRoot}/sdks/.hermesversion .`); - exec( - `CI=true USE_HERMES=${ - argv.hermes ? 1 : 0 - } bundle exec pod install --ansi`, - ); - } - cd('..'); exec('yarn ios'); } else { // android diff --git a/sdks/hermes-engine/hermes-engine.podspec b/sdks/hermes-engine/hermes-engine.podspec index 6761738c6d7adf..8ce5017049f906 100644 --- a/sdks/hermes-engine/hermes-engine.podspec +++ b/sdks/hermes-engine/hermes-engine.podspec @@ -17,7 +17,7 @@ version = package['version'] # sdks/.hermesversion hermestag_file = File.join(react_native_path, "sdks", ".hermesversion") -isInCI = ENV['CI'] == true +isInCI = ENV['CI'] === 'true' source = {} git = "https://github.com/facebook/hermes.git" @@ -38,7 +38,7 @@ elsif isNightly # set tarball as hermes engine source[:http] = "file://#{destination_path}" elsif File.exists?(hermestag_file) && isInCI - Pod::UI.puts '[Hermes] Detected that you are on a React Native release branch, building Hermes from source...'.yellow if Object.const_defined?("Pod::UI") + Pod::UI.puts '[Hermes] Detected that you are on a React Native release branch, building Hermes from source but fetched from tag...'.yellow if Object.const_defined?("Pod::UI") hermestag = File.read(hermestag_file).strip source[:git] = git source[:tag] = hermestag diff --git a/sdks/hermes-engine/utils/build-hermes-xcode.sh b/sdks/hermes-engine/utils/build-hermes-xcode.sh old mode 100644 new mode 100755 diff --git a/sdks/hermes-engine/utils/build-hermesc-xcode.sh b/sdks/hermes-engine/utils/build-hermesc-xcode.sh old mode 100644 new mode 100755 diff --git a/sdks/hermes-engine/utils/copy-hermes-xcode.sh b/sdks/hermes-engine/utils/copy-hermes-xcode.sh old mode 100644 new mode 100755 From 6a23b131e5d17f35657bc65e0e72d3caacb5630f Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Wed, 2 Nov 2022 08:43:22 -0700 Subject: [PATCH 112/169] Add file ReactNativeTypes.d.ts to fix CircleCI (#35173) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35173 changelog: [internal] D40897093 (https://github.com/facebook/react-native/commit/f49b2517d739ab129aae44d4ddab01748a96301c) deleted TypeScript definitions. Reviewed By: cipolleschi Differential Revision: D40935747 fbshipit-source-id: 020cba21b8b40c8b0c92bb5ab2dc4f6ba5da610a --- .../implementations/ReactNativeRenderer.d.ts | 149 ++++++++++++++++++ .../Renderer/shims/ReactNativeTypes.d.ts | 141 +++++++++++++++++ 2 files changed, 290 insertions(+) create mode 100644 Libraries/Renderer/implementations/ReactNativeRenderer.d.ts create mode 100644 Libraries/Renderer/shims/ReactNativeTypes.d.ts diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts b/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts new file mode 100644 index 00000000000000..2624d4a78ce01d --- /dev/null +++ b/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts @@ -0,0 +1,149 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import {GestureResponderEvent} from '../../Types/CoreEventTypes'; + +/** + * Gesture recognition on mobile devices is much more complicated than web. + * A touch can go through several phases as the app determines what the user's intention is. + * For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. + * This can even change during the duration of a touch. There can also be multiple simultaneous touches. + * + * The touch responder system is needed to allow components to negotiate these touch interactions + * without any additional knowledge about their parent or child components. + * This system is implemented in ResponderEventPlugin.js, which contains further details and documentation. + * + * Best Practices + * Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. + * Every action should have the following attributes: + * Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture + * Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away + * + * These features make users more comfortable while using an app, + * because it allows people to experiment and interact without fear of making mistakes. + * + * TouchableHighlight and Touchable* + * The responder system can be complicated to use. + * So we have provided an abstract Touchable implementation for things that should be "tappable". + * This uses the responder system and allows you to easily configure tap interactions declaratively. + * Use TouchableHighlight anywhere where you would use a button or link on web. + */ +export interface GestureResponderHandlers { + /** + * A view can become the touch responder by implementing the correct negotiation methods. + * There are two methods to ask the view if it wants to become responder: + */ + + /** + * Does this view want to become responder on the start of a touch? + */ + onStartShouldSetResponder?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? + */ + onMoveShouldSetResponder?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * If the View returns true and attempts to become the responder, one of the following will happen: + */ + + onResponderEnd?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * The View is now responding for touch events. + * This is the time to highlight and show the user what is happening + */ + onResponderGrant?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Something else is the responder right now and will not release it + */ + onResponderReject?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * If the view is responding, the following handlers can be called: + */ + + /** + * The user is moving their finger + */ + onResponderMove?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Fired at the end of the touch, ie "touchUp" + */ + onResponderRelease?: ((event: GestureResponderEvent) => void) | undefined; + + onResponderStart?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Something else wants to become responder. + * Should this view release the responder? Returning true allows release + */ + onResponderTerminationRequest?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * The responder has been taken from the View. + * Might be taken by other views after a call to onResponderTerminationRequest, + * or might be taken by the OS without asking (happens with control center/ notification center on iOS) + */ + onResponderTerminate?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, + * where the deepest node is called first. + * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. + * This is desirable in most cases, because it makes sure all controls and buttons are usable. + * + * However, sometimes a parent will want to make sure that it becomes responder. + * This can be handled by using the capture phase. + * Before the responder system bubbles up from the deepest component, + * it will do a capture phase, firing on*ShouldSetResponderCapture. + * So if a parent View wants to prevent the child from becoming responder on a touch start, + * it should have a onStartShouldSetResponderCapture handler which returns true. + */ + onStartShouldSetResponderCapture?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, + * where the deepest node is called first. + * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. + * This is desirable in most cases, because it makes sure all controls and buttons are usable. + * + * However, sometimes a parent will want to make sure that it becomes responder. + * This can be handled by using the capture phase. + * Before the responder system bubbles up from the deepest component, + * it will do a capture phase, firing on*ShouldSetResponderCapture. + * So if a parent View wants to prevent the child from becoming responder on a touch start, + * it should have a onStartShouldSetResponderCapture handler which returns true. + */ + onMoveShouldSetResponderCapture?: + | ((event: GestureResponderEvent) => boolean) + | undefined; +} + +/** + * React Native also implements unstable_batchedUpdates + */ +export function unstable_batchedUpdates( + callback: (a: A, b: B) => any, + a: A, + b: B, +): void; +export function unstable_batchedUpdates(callback: (a: A) => any, a: A): void; +export function unstable_batchedUpdates(callback: () => any): void; diff --git a/Libraries/Renderer/shims/ReactNativeTypes.d.ts b/Libraries/Renderer/shims/ReactNativeTypes.d.ts new file mode 100644 index 00000000000000..38e00e1cc933ca --- /dev/null +++ b/Libraries/Renderer/shims/ReactNativeTypes.d.ts @@ -0,0 +1,141 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import type * as React from 'react'; + +export type MeasureOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, + pageX: number, + pageY: number, +) => void; + +export type MeasureInWindowOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, +) => void; + +export type MeasureLayoutOnSuccessCallback = ( + left: number, + top: number, + width: number, + height: number, +) => void; + +/** + * NativeMethods provides methods to access the underlying native component directly. + * This can be useful in cases when you want to focus a view or measure its on-screen dimensions, + * for example. + * The methods described here are available on most of the default components provided by React Native. + * Note, however, that they are not available on composite components that aren't directly backed by a + * native view. This will generally include most components that you define in your own app. + * For more information, see [Direct Manipulation](https://reactnative.dev/docs/direct-manipulation). + * @see https://github.com/facebook/react-native/blob/master/Libraries/Renderer/shims/ReactNativeTypes.js#L87 + */ +export interface NativeMethods { + /** + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. + */ + measure(callback: MeasureOnSuccessCallback): void; + + /** + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: + * + * - x + * - y + * - width + * - height + * + * Note that these measurements are not available until after the rendering + * has been completed in native. + */ + measureInWindow(callback: MeasureInWindowOnSuccessCallback): void; + + /** + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeComponentRef`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. + * _Can also be called with a relativeNativeNodeHandle but is deprecated._ + */ + measureLayout( + relativeToNativeComponentRef: HostComponent | number, + onSuccess: MeasureLayoutOnSuccessCallback, + onFail: () => void /* currently unused */, + ): void; + + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](https://reactnative.dev/docs/direct-manipulation)). + */ + setNativeProps(nativeProps: object): void; + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus(): void; + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur(): void; + + refs: { + [key: string]: React.Component; + }; +} + +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixin = NativeMethods; +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixinType = NativeMethods; + +/** + * Represents a native component, such as those returned from `requireNativeComponent`. + * + * @see https://github.com/facebook/react-native/blob/v0.62.0-rc.5/Libraries/Renderer/shims/ReactNativeTypes.js + * + * @todo This should eventually be defined as an AbstractComponent, but that + * should first be introduced in the React typings. + */ +export interface HostComponent

+ extends Pick< + React.ComponentClass

, + Exclude, 'new'> + > { + new (props: P, context?: any): React.Component

& Readonly; +} From b5ea5a2c4d053cc0962305a7b4f834c28f6d8ddf Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Wed, 2 Nov 2022 10:24:56 -0700 Subject: [PATCH 113/169] Fix WebSocketModule not closing connections on reload Summary: Saw in the logs an ever increasing number of warnings coming from WebSocketModule about requesting an instance that has already gone away. On module invalidation we should close all outstanding websockets, as they will no longer be able to send events to JS. Changelog: [Android][Fixed] On instance destroy, websockets are correctly closed Reviewed By: mdvacca Differential Revision: D40897255 fbshipit-source-id: 1578de8baa342479d14ee1070c3314d45c7fbd8d --- .../react/modules/websocket/WebSocketModule.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java index 92e5b9143b3f9e..50e6f9d84c3c3a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/websocket/WebSocketModule.java @@ -58,10 +58,18 @@ public WebSocketModule(ReactApplicationContext context) { mCookieHandler = new ForwardingCookieHandler(context); } - private void sendEvent(String eventName, WritableMap params) { - ReactApplicationContext reactApplicationContext = getReactApplicationContextIfActiveOrWarn(); + @Override + public void invalidate() { + for (WebSocket socket : mWebSocketConnections.values()) { + socket.close(1001 /* endpoint is going away */, null); + } + mWebSocketConnections.clear(); + mContentHandlers.clear(); + } - if (reactApplicationContext != null) { + private void sendEvent(String eventName, WritableMap params) { + ReactApplicationContext reactApplicationContext = getReactApplicationContext(); + if (reactApplicationContext.hasActiveReactInstance()) { reactApplicationContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); From b5405b2954e143d9931eb14dd28bae269c0be70d Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 2 Nov 2022 10:55:23 -0700 Subject: [PATCH 114/169] Make sure nightly versions are using the -SNAPSHOT artifacts (#35178) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35178 I forgot to add the logic to fetch the -SNAPSHOT version when on nightlies. This code takes care of it. Changelog: [Internal] [Changed] - Make sure nightly versions are using the -SNAPSHOT artifacts Reviewed By: cipolleschi Differential Revision: D40939367 fbshipit-source-id: 29d60cf281d30b3dbd05d7ea1c766541a8fab90a --- .../com/facebook/react/utils/DependencyUtils.kt | 8 +++++++- .../facebook/react/utils/DependencyUtilsTest.kt | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt index 1fb2d39ca5b6a7..c96213eb2aa98e 100644 --- a/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt +++ b/packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/DependencyUtils.kt @@ -45,7 +45,13 @@ internal object DependencyUtils { fun readVersionString(propertiesFile: File): String { val reactAndroidProperties = Properties() propertiesFile.inputStream().use { reactAndroidProperties.load(it) } - return reactAndroidProperties["VERSION_NAME"] as? String ?: "" + val versionString = 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 + } } fun Project.mavenRepoFromUrl(url: String): MavenArtifactRepository = diff --git a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt index 4936df735f2e50..e73eeb7937fa51 100644 --- a/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt +++ b/packages/react-native-gradle-plugin/src/test/kotlin/com/facebook/react/utils/DependencyUtilsTest.kt @@ -198,6 +198,23 @@ class DependencyUtilsTest { assertEquals("1000.0.0", versionString) } + @Test + fun readVersionString_withNightlyVersionString_returnsSnapshotVersion() { + val propertiesFile = + tempFolder.newFile("gradle.properties").apply { + writeText( + """ + VERSION_NAME=0.0.0-20221101-2019-cfe811ab1 + ANOTHER_PROPERTY=true + """ + .trimIndent()) + } + + val versionString = readVersionString(propertiesFile) + + assertEquals("0.0.0-20221101-2019-cfe811ab1-SNAPSHOT", versionString) + } + @Test fun readVersionString_withMissingVersionString_returnsEmpty() { val propertiesFile = From 5d26ceaa236684c7bd6d0d9001ff2c8908d88c29 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 2 Nov 2022 14:58:37 -0700 Subject: [PATCH 115/169] Fixup TS Organization (#35169) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35169 This reorganizes typing structure a bit. `Utilities.d.ts` was originally added for utilitiy types but I ended up leaving it a grab bag of types that didn't belong to any individual bit of code. Out of what is in it right now, `Insets` was actually public, and seems to have been imported. We also run into files around the renderer which are [currently overwritten](https://github.com/facebook/react-native/commits/e286da25fc83324363486eb668806aca179f74b3/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts) by the React sync script. Finally, all of the top-level imports of `Utilities` were auto-generated by VS Code, but fail in real apps. I think this is because our tsconfig sets a `baseUrl` to allow resolution from the types folder, so the tooling in the RN repo will use that, but it breaks in real apps that don't have that mapping. This splits all these up into a couple separate directories that are hopefully easier to reason about, and removes `Omit` which has been a builtin type for quite some time (we were actually already using built-in `Omit`). Changelog: [General][Fixed] - Fixup TS Organization Reviewed By: cipolleschi Differential Revision: D40932319 fbshipit-source-id: 0b6e3e3eda603885b4dc01dcb9f5233aa546d128 --- .../AccessibilityInfo/AccessibilityInfo.d.ts | 2 +- .../ActivityIndicator/ActivityIndicator.d.ts | 4 +- .../Components/DatePicker/DatePickerIOS.d.ts | 4 +- .../DrawerAndroid/DrawerLayoutAndroid.d.ts | 4 +- .../Keyboard/KeyboardAvoidingView.d.ts | 3 +- Libraries/Components/Pressable/Pressable.d.ts | 2 +- .../ProgressBarAndroid.d.ts | 4 +- .../ProgressViewIOS/ProgressViewIOS.d.ts | 4 +- .../RefreshControl/RefreshControl.d.ts | 4 +- .../Components/SafeAreaView/SafeAreaView.d.ts | 4 +- .../Components/ScrollView/ScrollView.d.ts | 3 +- Libraries/Components/Slider/Slider.d.ts | 4 +- Libraries/Components/Switch/Switch.d.ts | 4 +- Libraries/Components/TextInput/TextInput.d.ts | 5 +- Libraries/Components/Touchable/Touchable.d.ts | 2 +- .../Touchable/TouchableHighlight.d.ts | 5 +- .../Touchable/TouchableNativeFeedback.d.ts | 2 +- .../Touchable/TouchableOpacity.d.ts | 5 +- .../Touchable/TouchableWithoutFeedback.d.ts | 4 +- Libraries/Components/View/View.d.ts | 4 +- Libraries/Components/View/ViewPropTypes.d.ts | 4 +- Libraries/Image/Image.d.ts | 5 +- Libraries/Interaction/PanResponder.d.ts | 2 +- Libraries/ReactNative/UIManager.d.ts | 2 +- .../ReactNative/requireNativeComponent.d.ts | 2 +- Libraries/Text/Text.d.ts | 4 +- Libraries/Types/CoreEventTypes.d.ts | 2 +- types/index.d.ts | 18 +- types/legacy-properties.d.ts | 208 ------------------ types/{ => modules}/BatchedBridge.d.ts | 0 types/{ => modules}/Codegen.d.ts | 0 types/{ => modules}/Devtools.d.ts | 0 types/{ => modules}/LaunchScreen.d.ts | 0 types/{ => modules}/globals.d.ts | 0 .../TimerMixin.d.ts} | 10 - types/private/Utilities.d.ts | 10 + types/public/DeprecatedPropertiesAlias.d.ts | 205 +++++++++++++++++ types/public/Insets.d.ts | 15 ++ types/public/ReactNativeRenderer.d.ts | 149 +++++++++++++ types/public/ReactNativeTypes.d.ts | 141 ++++++++++++ types/tsconfig.json | 4 - 41 files changed, 581 insertions(+), 273 deletions(-) delete mode 100644 types/legacy-properties.d.ts rename types/{ => modules}/BatchedBridge.d.ts (100%) rename types/{ => modules}/Codegen.d.ts (100%) rename types/{ => modules}/Devtools.d.ts (100%) rename types/{ => modules}/LaunchScreen.d.ts (100%) rename types/{ => modules}/globals.d.ts (100%) rename types/{Utilities.d.ts => private/TimerMixin.d.ts} (67%) create mode 100644 types/private/Utilities.d.ts create mode 100644 types/public/DeprecatedPropertiesAlias.d.ts create mode 100644 types/public/Insets.d.ts create mode 100644 types/public/ReactNativeRenderer.d.ts create mode 100644 types/public/ReactNativeTypes.d.ts diff --git a/Libraries/Components/AccessibilityInfo/AccessibilityInfo.d.ts b/Libraries/Components/AccessibilityInfo/AccessibilityInfo.d.ts index 36512268553aae..749d44e36717d0 100644 --- a/Libraries/Components/AccessibilityInfo/AccessibilityInfo.d.ts +++ b/Libraries/Components/AccessibilityInfo/AccessibilityInfo.d.ts @@ -8,7 +8,7 @@ */ import type * as React from 'react'; -import {HostComponent} from '../../Renderer/shims/ReactNativeTypes'; +import {HostComponent} from '../../../types/public/ReactNativeTypes'; import {EmitterSubscription} from '../../vendor/emitter/EventEmitter'; type AccessibilityChangeEventName = diff --git a/Libraries/Components/ActivityIndicator/ActivityIndicator.d.ts b/Libraries/Components/ActivityIndicator/ActivityIndicator.d.ts index 3ba3d00e44c0ad..f1a4b246dd44fe 100644 --- a/Libraries/Components/ActivityIndicator/ActivityIndicator.d.ts +++ b/Libraries/Components/ActivityIndicator/ActivityIndicator.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {LayoutChangeEvent} from '../../Types/CoreEventTypes'; diff --git a/Libraries/Components/DatePicker/DatePickerIOS.d.ts b/Libraries/Components/DatePicker/DatePickerIOS.d.ts index 3db5f3feb3b884..17c60b75161406 100644 --- a/Libraries/Components/DatePicker/DatePickerIOS.d.ts +++ b/Libraries/Components/DatePicker/DatePickerIOS.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ViewProps} from '../View/ViewPropTypes'; export interface DatePickerIOSProps extends ViewProps { diff --git a/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.d.ts b/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.d.ts index baaf38151e1f02..9f90951c884425 100644 --- a/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.d.ts +++ b/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue} from '../../StyleSheet/StyleSheet'; import { NativeSyntheticEvent, diff --git a/Libraries/Components/Keyboard/KeyboardAvoidingView.d.ts b/Libraries/Components/Keyboard/KeyboardAvoidingView.d.ts index 0fa8783c0333cb..42bff4a5191230 100644 --- a/Libraries/Components/Keyboard/KeyboardAvoidingView.d.ts +++ b/Libraries/Components/Keyboard/KeyboardAvoidingView.d.ts @@ -8,7 +8,8 @@ */ import type * as React from 'react'; -import {Constructor, TimerMixin} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; +import {TimerMixin} from '../../../types/private/TimerMixin'; import {StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/Pressable/Pressable.d.ts b/Libraries/Components/Pressable/Pressable.d.ts index 4fe0a82e34b470..640e41261110f9 100644 --- a/Libraries/Components/Pressable/Pressable.d.ts +++ b/Libraries/Components/Pressable/Pressable.d.ts @@ -8,7 +8,7 @@ */ import type * as React from 'react'; -import {Insets} from 'Utilities'; +import {Insets} from '../../../types/public/Insets'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import { diff --git a/Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.d.ts b/Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.d.ts index d1d5a930a108fb..a368adfb075689 100644 --- a/Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.d.ts +++ b/Libraries/Components/ProgressBarAndroid/ProgressBarAndroid.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue} from '../../StyleSheet/StyleSheet'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/ProgressViewIOS/ProgressViewIOS.d.ts b/Libraries/Components/ProgressViewIOS/ProgressViewIOS.d.ts index 51946629414f1a..1f38df718c1faa 100644 --- a/Libraries/Components/ProgressViewIOS/ProgressViewIOS.d.ts +++ b/Libraries/Components/ProgressViewIOS/ProgressViewIOS.d.ts @@ -8,9 +8,9 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; import {ImageURISource} from '../../Image/ImageSource'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue} from '../../StyleSheet/StyleSheet'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/RefreshControl/RefreshControl.d.ts b/Libraries/Components/RefreshControl/RefreshControl.d.ts index 2af44a819e25d6..81eba749c98885 100644 --- a/Libraries/Components/RefreshControl/RefreshControl.d.ts +++ b/Libraries/Components/RefreshControl/RefreshControl.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue} from '../../StyleSheet/StyleSheet'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/SafeAreaView/SafeAreaView.d.ts b/Libraries/Components/SafeAreaView/SafeAreaView.d.ts index 1386556277d297..f96a1a50753ea5 100644 --- a/Libraries/Components/SafeAreaView/SafeAreaView.d.ts +++ b/Libraries/Components/SafeAreaView/SafeAreaView.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ViewProps} from '../View/ViewPropTypes'; /** diff --git a/Libraries/Components/ScrollView/ScrollView.d.ts b/Libraries/Components/ScrollView/ScrollView.d.ts index 1e0d6f02b509e7..0803499a44e24d 100644 --- a/Libraries/Components/ScrollView/ScrollView.d.ts +++ b/Libraries/Components/ScrollView/ScrollView.d.ts @@ -8,7 +8,8 @@ */ import type * as React from 'react'; -import {Constructor, Insets} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; +import {Insets} from '../../../types/public/Insets'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import { diff --git a/Libraries/Components/Slider/Slider.d.ts b/Libraries/Components/Slider/Slider.d.ts index befb08daa33f88..33f26d06941057 100644 --- a/Libraries/Components/Slider/Slider.d.ts +++ b/Libraries/Components/Slider/Slider.d.ts @@ -8,9 +8,9 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; import {ImageURISource} from '../../Image/ImageSource'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/Switch/Switch.d.ts b/Libraries/Components/Switch/Switch.d.ts index ea52709c54d5e1..64a735d6648ec6 100644 --- a/Libraries/Components/Switch/Switch.d.ts +++ b/Libraries/Components/Switch/Switch.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {ViewProps} from '../View/ViewPropTypes'; diff --git a/Libraries/Components/TextInput/TextInput.d.ts b/Libraries/Components/TextInput/TextInput.d.ts index 3ad310bd8ced7f..12cfec2987cb2a 100644 --- a/Libraries/Components/TextInput/TextInput.d.ts +++ b/Libraries/Components/TextInput/TextInput.d.ts @@ -8,11 +8,12 @@ */ import type * as React from 'react'; -import {Constructor, TimerMixin} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; +import {TimerMixin} from '../../../types/private/TimerMixin'; import { HostComponent, NativeMethods, -} from '../../Renderer/shims/ReactNativeTypes'; +} from '../../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {TextStyle} from '../../StyleSheet/StyleSheetTypes'; import { diff --git a/Libraries/Components/Touchable/Touchable.d.ts b/Libraries/Components/Touchable/Touchable.d.ts index 34bce2c464e5b6..6915dd27927d62 100644 --- a/Libraries/Components/Touchable/Touchable.d.ts +++ b/Libraries/Components/Touchable/Touchable.d.ts @@ -8,7 +8,7 @@ */ import type * as React from 'react'; -import {Insets} from 'Utilities'; +import {Insets} from '../../../types/public/Insets'; import {GestureResponderEvent} from '../../Types/CoreEventTypes'; /** diff --git a/Libraries/Components/Touchable/TouchableHighlight.d.ts b/Libraries/Components/Touchable/TouchableHighlight.d.ts index 39a487e06657f7..b9faa3a8798fee 100644 --- a/Libraries/Components/Touchable/TouchableHighlight.d.ts +++ b/Libraries/Components/Touchable/TouchableHighlight.d.ts @@ -8,8 +8,9 @@ */ import type * as React from 'react'; -import {Constructor, TimerMixin} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {TimerMixin} from '../../../types/private/TimerMixin'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {TouchableMixin} from './Touchable'; diff --git a/Libraries/Components/Touchable/TouchableNativeFeedback.d.ts b/Libraries/Components/Touchable/TouchableNativeFeedback.d.ts index ebf7d66d2acfbd..9de3953b3150cb 100644 --- a/Libraries/Components/Touchable/TouchableNativeFeedback.d.ts +++ b/Libraries/Components/Touchable/TouchableNativeFeedback.d.ts @@ -8,7 +8,7 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; import {ColorValue} from '../../StyleSheet/StyleSheet'; import {TouchableMixin} from './Touchable'; diff --git a/Libraries/Components/Touchable/TouchableOpacity.d.ts b/Libraries/Components/Touchable/TouchableOpacity.d.ts index fccbd393302028..37c4ce6df43e4c 100644 --- a/Libraries/Components/Touchable/TouchableOpacity.d.ts +++ b/Libraries/Components/Touchable/TouchableOpacity.d.ts @@ -8,8 +8,9 @@ */ import type * as React from 'react'; -import {Constructor, TimerMixin} from 'Utilities'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {Constructor} from '../../../types/private/Utilities'; +import {TimerMixin} from '../../../types/private/TimerMixin'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; import {TVParallaxProperties} from '../View/ViewPropTypes'; import {TouchableMixin} from './Touchable'; import {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback'; diff --git a/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts b/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts index 23c08df60d97b3..a6f3316d36be14 100644 --- a/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts +++ b/Libraries/Components/Touchable/TouchableWithoutFeedback.d.ts @@ -8,7 +8,9 @@ */ import type * as React from 'react'; -import {Constructor, Insets, TimerMixin} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; +import {TimerMixin} from '../../../types/private/TimerMixin'; +import {Insets} from '../../../types/public/Insets'; import {StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import { diff --git a/Libraries/Components/View/View.d.ts b/Libraries/Components/View/View.d.ts index 4c3528e270c317..5fbb52928e5a23 100644 --- a/Libraries/Components/View/View.d.ts +++ b/Libraries/Components/View/View.d.ts @@ -8,9 +8,9 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; +import {Constructor} from '../../../types/private/Utilities'; import {ViewProps} from './ViewPropTypes'; -import {NativeMethods} from '../../Renderer/shims/ReactNativeTypes'; +import {NativeMethods} from '../../../types/public/ReactNativeTypes'; /** * The most fundamental component for building UI, View is a container that supports layout with flexbox, style, some touch handling, diff --git a/Libraries/Components/View/ViewPropTypes.d.ts b/Libraries/Components/View/ViewPropTypes.d.ts index 5a7b24e21c10f1..b7da46fe4bc5f2 100644 --- a/Libraries/Components/View/ViewPropTypes.d.ts +++ b/Libraries/Components/View/ViewPropTypes.d.ts @@ -8,8 +8,8 @@ */ import type * as React from 'react'; -import {Insets} from '../../../types/Utilities'; -import {GestureResponderHandlers} from '../../Renderer/implementations/ReactNativeRenderer'; +import {Insets} from '../../../types/public/Insets'; +import {GestureResponderHandlers} from '../../../types/public/ReactNativeRenderer'; import {StyleProp} from '../../StyleSheet/StyleSheet'; import {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; import {LayoutChangeEvent, PointerEvents} from '../../Types/CoreEventTypes'; diff --git a/Libraries/Image/Image.d.ts b/Libraries/Image/Image.d.ts index 21c873844a56e9..dd2c089e75a4be 100644 --- a/Libraries/Image/Image.d.ts +++ b/Libraries/Image/Image.d.ts @@ -8,9 +8,10 @@ */ import * as React from 'react'; -import {Constructor, Insets} from 'Utilities'; +import {Constructor} from '../../types/private/Utilities'; import {AccessibilityProps} from '../Components/View/ViewAccessibility'; -import {NativeMethods} from '../Renderer/shims/ReactNativeTypes'; +import {Insets} from '../../types/public/Insets'; +import {NativeMethods} from '../../types/public/ReactNativeTypes'; import {StyleProp} from '../StyleSheet/StyleSheet'; import {ImageStyle, ViewStyle} from '../StyleSheet/StyleSheetTypes'; import {LayoutChangeEvent, NativeSyntheticEvent} from '../Types/CoreEventTypes'; diff --git a/Libraries/Interaction/PanResponder.d.ts b/Libraries/Interaction/PanResponder.d.ts index 0cbb93cd10468f..8a2d4f2a0ef1bc 100644 --- a/Libraries/Interaction/PanResponder.d.ts +++ b/Libraries/Interaction/PanResponder.d.ts @@ -7,7 +7,7 @@ * @format */ -import {GestureResponderHandlers} from '../Renderer/implementations/ReactNativeRenderer'; +import {GestureResponderHandlers} from '../../types/public/ReactNativeRenderer'; import {GestureResponderEvent} from '../Types/CoreEventTypes'; export interface PanResponderGestureState { diff --git a/Libraries/ReactNative/UIManager.d.ts b/Libraries/ReactNative/UIManager.d.ts index b975a79fade83b..1f0b346802d739 100644 --- a/Libraries/ReactNative/UIManager.d.ts +++ b/Libraries/ReactNative/UIManager.d.ts @@ -12,7 +12,7 @@ import { MeasureInWindowOnSuccessCallback, MeasureLayoutOnSuccessCallback, MeasureOnSuccessCallback, -} from '../Renderer/shims/ReactNativeTypes'; +} from '../../types/public/ReactNativeTypes'; export interface UIManagerStatic { /** diff --git a/Libraries/ReactNative/requireNativeComponent.d.ts b/Libraries/ReactNative/requireNativeComponent.d.ts index b3f1169687753e..935762a3e259cc 100644 --- a/Libraries/ReactNative/requireNativeComponent.d.ts +++ b/Libraries/ReactNative/requireNativeComponent.d.ts @@ -7,7 +7,7 @@ * @format */ -import {HostComponent} from '../Renderer/shims/ReactNativeTypes'; +import {HostComponent} from '../../types/public//ReactNativeTypes'; /** * Creates values that can be used like React components which represent native diff --git a/Libraries/Text/Text.d.ts b/Libraries/Text/Text.d.ts index 715123576a12c1..e752148a5d5257 100644 --- a/Libraries/Text/Text.d.ts +++ b/Libraries/Text/Text.d.ts @@ -8,9 +8,9 @@ */ import type * as React from 'react'; -import {Constructor} from 'Utilities'; +import {Constructor} from '../../types/private/Utilities'; import {AccessibilityProps} from '../Components/View/ViewAccessibility'; -import {NativeMethods} from '../Renderer/shims/ReactNativeTypes'; +import {NativeMethods} from '../../types/public/ReactNativeTypes'; import {ColorValue, StyleProp} from '../StyleSheet/StyleSheet'; import {TextStyle} from '../StyleSheet/StyleSheetTypes'; import { diff --git a/Libraries/Types/CoreEventTypes.d.ts b/Libraries/Types/CoreEventTypes.d.ts index 778a8998f3cee2..7aff083b07a2bf 100644 --- a/Libraries/Types/CoreEventTypes.d.ts +++ b/Libraries/Types/CoreEventTypes.d.ts @@ -9,7 +9,7 @@ import type * as React from 'react'; import {NodeHandle} from '../ReactNative/RendererProxy'; -import {HostComponent} from '../Renderer/shims/ReactNativeTypes'; +import {HostComponent} from '../../types/public/ReactNativeTypes'; export interface LayoutRectangle { x: number; diff --git a/types/index.d.ts b/types/index.d.ts index fe2e5b056b6145..542f22e59199a8 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -65,12 +65,11 @@ // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// export * from '../Libraries/ActionSheetIOS/ActionSheetIOS'; export * from '../Libraries/Alert/Alert'; @@ -131,8 +130,6 @@ export * from '../Libraries/ReactNative/I18nManager'; export * from '../Libraries/ReactNative/RendererProxy'; export * from '../Libraries/ReactNative/UIManager'; export * from '../Libraries/ReactNative/requireNativeComponent'; -export * from '../Libraries/Renderer/implementations/ReactNativeRenderer'; -export * from '../Libraries/Renderer/shims/ReactNativeTypes'; export * from '../Libraries/Settings/Settings'; export * from '../Libraries/Share/Share'; export * from '../Libraries/StyleSheet/PlatformColorValueTypesIOS'; @@ -155,6 +152,11 @@ export * from '../Libraries/YellowBox/YellowBoxDeprecated'; export * from '../Libraries/vendor/core/ErrorUtils'; export * from '../Libraries/vendor/emitter/EventEmitter'; +export * from './public/DeprecatedPropertiesAlias'; +export * from './public/Insets'; +export * from './public/ReactNativeRenderer'; +export * from './public/ReactNativeTypes'; + import type {ErrorUtils} from '../Libraries/vendor/core/ErrorUtils'; declare global { diff --git a/types/legacy-properties.d.ts b/types/legacy-properties.d.ts deleted file mode 100644 index 6e7a00966bf559..00000000000000 --- a/types/legacy-properties.d.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import { - TextProps, - TextPropsIOS, - TextPropsAndroid, - AccessibilityProps, - AccessibilityPropsIOS, - AccessibilityPropsAndroid, - TextInputProps, - TextInputIOSProps, - TextInputAndroidProps, - ViewProps, - ViewPropsIOS, - ViewPropsAndroid, - ScrollViewProps, - ScrollViewPropsIOS, - ScrollViewPropsAndroid, - InputAccessoryViewProps, - ActivityIndicatorProps, - ActivityIndicatorIOSProps, - DatePickerIOSProps, - DrawerLayoutAndroidProps, - ProgressBarAndroidProps, - ProgressViewIOSProps, - RefreshControlProps, - RefreshControlPropsIOS, - RefreshControlPropsAndroid, - SliderProps, - SliderPropsIOS, - SliderPropsAndroid, - ImageSourcePropType, - ImageProps, - ImagePropsIOS, - ImagePropsAndroid, - ImageBackgroundProps, - FlatListProps, - VirtualizedListProps, - SectionListProps, - ModalProps, - TouchableWithoutFeedbackProps, - TouchableHighlightProps, - TouchableOpacityProps, - TouchableNativeFeedbackProps, - ButtonProps, - StatusBarProps, - StatusBarPropsIOS, - StatusBarPropsAndroid, - SwitchProps, - SwitchPropsIOS, -} from 'react-native'; - -declare module 'react-native' { - /* - * Previously, props interfaces where named *Properties - * They have been renamed to *Props to match React Native documentation - * The following lines ensure compatibility with *Properties and should be removed in the future - */ - - /** @deprecated Use TextProps */ - export type TextProperties = TextProps; - - /** @deprecated Use TextPropsIOS */ - export type TextPropertiesIOS = TextPropsIOS; - - /** @deprecated Use TextPropsAndroid */ - export type TextPropertiesAndroid = TextPropsAndroid; - - /** @deprecated Use AccessibilityProps */ - export type AccessibilityProperties = AccessibilityProps; - - /** @deprecated Use AccessibilityPropsIOS */ - export type AccessibilityPropertiesIOS = AccessibilityPropsIOS; - - /** @deprecated Use AccessibilityPropsAndroid */ - export type AccessibilityPropertiesAndroid = AccessibilityPropsAndroid; - - /** @deprecated Use TextInputProps */ - export type TextInputProperties = TextInputProps; - - /** @deprecated Use TextInputIOSProps */ - export type TextInputIOSProperties = TextInputIOSProps; - - /** @deprecated Use TextInputAndroidProps */ - export type TextInputAndroidProperties = TextInputAndroidProps; - - /** @deprecated Use ViewProps */ - export type ViewProperties = ViewProps; - - /** @deprecated Use ViewPropsIOS */ - export type ViewPropertiesIOS = ViewPropsIOS; - - /** @deprecated Use ViewPropsAndroid */ - export type ViewPropertiesAndroid = ViewPropsAndroid; - - /** @deprecated Use ScrollViewProps */ - export type ScrollViewProperties = ScrollViewProps; - - /** @deprecated Use ScrollViewPropsIOS */ - export type ScrollViewPropertiesIOS = ScrollViewPropsIOS; - - /** @deprecated Use ScrollViewPropsAndroid */ - export type ScrollViewPropertiesAndroid = ScrollViewPropsAndroid; - - /** @deprecated Use InputAccessoryViewProps */ - export type InputAccessoryViewProperties = InputAccessoryViewProps; - - /** @deprecated Use ActivityIndicatorProps */ - export type ActivityIndicatorProperties = ActivityIndicatorProps; - - /** @deprecated Use ActivityIndicatorIOSProps */ - export type ActivityIndicatorIOSProperties = ActivityIndicatorIOSProps; - - /** @deprecated Use DatePickerIOSProps */ - export type DatePickerIOSProperties = DatePickerIOSProps; - - /** @deprecated Use DrawerLayoutAndroidProps */ - export type DrawerLayoutAndroidProperties = DrawerLayoutAndroidProps; - - /** @deprecated Use ProgressBarAndroidProps */ - export type ProgressBarAndroidProperties = ProgressBarAndroidProps; - - /** @deprecated Use ProgressViewIOSProps */ - export type ProgressViewIOSProperties = ProgressViewIOSProps; - - /** @deprecated Use RefreshControlProps */ - export type RefreshControlProperties = RefreshControlProps; - - /** @deprecated Use RefreshControlPropsIOS */ - export type RefreshControlPropertiesIOS = RefreshControlPropsIOS; - - /** @deprecated Use RefreshControlPropsAndroid */ - export type RefreshControlPropertiesAndroid = RefreshControlPropsAndroid; - - /** @deprecated Use SliderProps */ - export type SliderProperties = SliderProps; - - /** @deprecated Use SliderPropsIOS */ - export type SliderPropertiesIOS = SliderPropsIOS; - - /** @deprecated Use SliderPropsAndroid */ - export type SliderPropertiesAndroid = SliderPropsAndroid; - - /** @deprecated Use ImageSourcePropType */ - export type ImagePropertiesSourceOptions = ImageSourcePropType; - - /** @deprecated Use ImageProps */ - export type ImageProperties = ImageProps; - - /** @deprecated Use ImagePropsIOS */ - export type ImagePropertiesIOS = ImagePropsIOS; - - /** @deprecated Use ImagePropsAndroid */ - export type ImagePropertiesAndroid = ImagePropsAndroid; - - /** @deprecated Use ImageBackgroundProps */ - export type ImageBackgroundProperties = ImageBackgroundProps; - - /** @deprecated Use FlatListProps */ - export type FlatListProperties = FlatListProps; - - /** @deprecated Use VirtualizedListProps */ - export type VirtualizedListProperties = VirtualizedListProps; - - /** @deprecated Use SectionListProps */ - export type SectionListProperties = SectionListProps; - - /** @deprecated Use ModalProps */ - export type ModalProperties = ModalProps; - - /** @deprecated Use TouchableWithoutFeedbackProps */ - export type TouchableWithoutFeedbackProperties = - TouchableWithoutFeedbackProps; - - /** @deprecated Use TouchableHighlightProps */ - export type TouchableHighlightProperties = TouchableHighlightProps; - - /** @deprecated Use TouchableOpacityProps */ - export type TouchableOpacityProperties = TouchableOpacityProps; - - /** @deprecated Use TouchableNativeFeedbackProps */ - export type TouchableNativeFeedbackProperties = TouchableNativeFeedbackProps; - - /** @deprecated Use ButtonProps */ - export type ButtonProperties = ButtonProps; - - /** @deprecated Use StatusBarProps */ - export type StatusBarProperties = StatusBarProps; - - /** @deprecated Use StatusBarPropsIOS */ - export type StatusBarPropertiesIOS = StatusBarPropsIOS; - - /** @deprecated Use StatusBarPropsAndroid */ - export type StatusBarPropertiesAndroid = StatusBarPropsAndroid; - - /** @deprecated Use SwitchProps */ - export type SwitchProperties = SwitchProps; - - /** @deprecated Use SwitchPropsIOS */ - export type SwitchPropertiesIOS = SwitchPropsIOS; -} diff --git a/types/BatchedBridge.d.ts b/types/modules/BatchedBridge.d.ts similarity index 100% rename from types/BatchedBridge.d.ts rename to types/modules/BatchedBridge.d.ts diff --git a/types/Codegen.d.ts b/types/modules/Codegen.d.ts similarity index 100% rename from types/Codegen.d.ts rename to types/modules/Codegen.d.ts diff --git a/types/Devtools.d.ts b/types/modules/Devtools.d.ts similarity index 100% rename from types/Devtools.d.ts rename to types/modules/Devtools.d.ts diff --git a/types/LaunchScreen.d.ts b/types/modules/LaunchScreen.d.ts similarity index 100% rename from types/LaunchScreen.d.ts rename to types/modules/LaunchScreen.d.ts diff --git a/types/globals.d.ts b/types/modules/globals.d.ts similarity index 100% rename from types/globals.d.ts rename to types/modules/globals.d.ts diff --git a/types/Utilities.d.ts b/types/private/TimerMixin.d.ts similarity index 67% rename from types/Utilities.d.ts rename to types/private/TimerMixin.d.ts index 34b52345773d55..616183c79c4bf6 100644 --- a/types/Utilities.d.ts +++ b/types/private/TimerMixin.d.ts @@ -7,9 +7,6 @@ * @format */ -export type Omit = Pick>; -export type Constructor = new (...args: any[]) => T; - export interface TimerMixin { setTimeout: typeof setTimeout; clearTimeout: typeof clearTimeout; @@ -20,10 +17,3 @@ export interface TimerMixin { requestAnimationFrame: typeof requestAnimationFrame; cancelAnimationFrame: typeof cancelAnimationFrame; } - -export interface Insets { - top?: number | undefined; - left?: number | undefined; - bottom?: number | undefined; - right?: number | undefined; -} diff --git a/types/private/Utilities.d.ts b/types/private/Utilities.d.ts new file mode 100644 index 00000000000000..563cac81a02306 --- /dev/null +++ b/types/private/Utilities.d.ts @@ -0,0 +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. + * + * @format + */ + +export type Constructor = new (...args: any[]) => T; diff --git a/types/public/DeprecatedPropertiesAlias.d.ts b/types/public/DeprecatedPropertiesAlias.d.ts new file mode 100644 index 00000000000000..b7b1aa68254b8d --- /dev/null +++ b/types/public/DeprecatedPropertiesAlias.d.ts @@ -0,0 +1,205 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import { + TextProps, + TextPropsIOS, + TextPropsAndroid, + AccessibilityProps, + AccessibilityPropsIOS, + AccessibilityPropsAndroid, + TextInputProps, + TextInputIOSProps, + TextInputAndroidProps, + ViewProps, + ViewPropsIOS, + ViewPropsAndroid, + ScrollViewProps, + ScrollViewPropsIOS, + ScrollViewPropsAndroid, + InputAccessoryViewProps, + ActivityIndicatorProps, + ActivityIndicatorIOSProps, + DatePickerIOSProps, + DrawerLayoutAndroidProps, + ProgressBarAndroidProps, + ProgressViewIOSProps, + RefreshControlProps, + RefreshControlPropsIOS, + RefreshControlPropsAndroid, + SliderProps, + SliderPropsIOS, + SliderPropsAndroid, + ImageSourcePropType, + ImageProps, + ImagePropsIOS, + ImagePropsAndroid, + ImageBackgroundProps, + FlatListProps, + VirtualizedListProps, + SectionListProps, + ModalProps, + TouchableWithoutFeedbackProps, + TouchableHighlightProps, + TouchableOpacityProps, + TouchableNativeFeedbackProps, + ButtonProps, + StatusBarProps, + StatusBarPropsIOS, + StatusBarPropsAndroid, + SwitchProps, + SwitchPropsIOS, +} from 'react-native'; + +/* + * Previously, props interfaces where named *Properties + * They have been renamed to *Props to match React Native documentation + * The following lines ensure compatibility with *Properties and should be removed in the future + */ + +/** @deprecated Use TextProps */ +export type TextProperties = TextProps; + +/** @deprecated Use TextPropsIOS */ +export type TextPropertiesIOS = TextPropsIOS; + +/** @deprecated Use TextPropsAndroid */ +export type TextPropertiesAndroid = TextPropsAndroid; + +/** @deprecated Use AccessibilityProps */ +export type AccessibilityProperties = AccessibilityProps; + +/** @deprecated Use AccessibilityPropsIOS */ +export type AccessibilityPropertiesIOS = AccessibilityPropsIOS; + +/** @deprecated Use AccessibilityPropsAndroid */ +export type AccessibilityPropertiesAndroid = AccessibilityPropsAndroid; + +/** @deprecated Use TextInputProps */ +export type TextInputProperties = TextInputProps; + +/** @deprecated Use TextInputIOSProps */ +export type TextInputIOSProperties = TextInputIOSProps; + +/** @deprecated Use TextInputAndroidProps */ +export type TextInputAndroidProperties = TextInputAndroidProps; + +/** @deprecated Use ViewProps */ +export type ViewProperties = ViewProps; + +/** @deprecated Use ViewPropsIOS */ +export type ViewPropertiesIOS = ViewPropsIOS; + +/** @deprecated Use ViewPropsAndroid */ +export type ViewPropertiesAndroid = ViewPropsAndroid; + +/** @deprecated Use ScrollViewProps */ +export type ScrollViewProperties = ScrollViewProps; + +/** @deprecated Use ScrollViewPropsIOS */ +export type ScrollViewPropertiesIOS = ScrollViewPropsIOS; + +/** @deprecated Use ScrollViewPropsAndroid */ +export type ScrollViewPropertiesAndroid = ScrollViewPropsAndroid; + +/** @deprecated Use InputAccessoryViewProps */ +export type InputAccessoryViewProperties = InputAccessoryViewProps; + +/** @deprecated Use ActivityIndicatorProps */ +export type ActivityIndicatorProperties = ActivityIndicatorProps; + +/** @deprecated Use ActivityIndicatorIOSProps */ +export type ActivityIndicatorIOSProperties = ActivityIndicatorIOSProps; + +/** @deprecated Use DatePickerIOSProps */ +export type DatePickerIOSProperties = DatePickerIOSProps; + +/** @deprecated Use DrawerLayoutAndroidProps */ +export type DrawerLayoutAndroidProperties = DrawerLayoutAndroidProps; + +/** @deprecated Use ProgressBarAndroidProps */ +export type ProgressBarAndroidProperties = ProgressBarAndroidProps; + +/** @deprecated Use ProgressViewIOSProps */ +export type ProgressViewIOSProperties = ProgressViewIOSProps; + +/** @deprecated Use RefreshControlProps */ +export type RefreshControlProperties = RefreshControlProps; + +/** @deprecated Use RefreshControlPropsIOS */ +export type RefreshControlPropertiesIOS = RefreshControlPropsIOS; + +/** @deprecated Use RefreshControlPropsAndroid */ +export type RefreshControlPropertiesAndroid = RefreshControlPropsAndroid; + +/** @deprecated Use SliderProps */ +export type SliderProperties = SliderProps; + +/** @deprecated Use SliderPropsIOS */ +export type SliderPropertiesIOS = SliderPropsIOS; + +/** @deprecated Use SliderPropsAndroid */ +export type SliderPropertiesAndroid = SliderPropsAndroid; + +/** @deprecated Use ImageSourcePropType */ +export type ImagePropertiesSourceOptions = ImageSourcePropType; + +/** @deprecated Use ImageProps */ +export type ImageProperties = ImageProps; + +/** @deprecated Use ImagePropsIOS */ +export type ImagePropertiesIOS = ImagePropsIOS; + +/** @deprecated Use ImagePropsAndroid */ +export type ImagePropertiesAndroid = ImagePropsAndroid; + +/** @deprecated Use ImageBackgroundProps */ +export type ImageBackgroundProperties = ImageBackgroundProps; + +/** @deprecated Use FlatListProps */ +export type FlatListProperties = FlatListProps; + +/** @deprecated Use VirtualizedListProps */ +export type VirtualizedListProperties = VirtualizedListProps; + +/** @deprecated Use SectionListProps */ +export type SectionListProperties = SectionListProps; + +/** @deprecated Use ModalProps */ +export type ModalProperties = ModalProps; + +/** @deprecated Use TouchableWithoutFeedbackProps */ +export type TouchableWithoutFeedbackProperties = TouchableWithoutFeedbackProps; + +/** @deprecated Use TouchableHighlightProps */ +export type TouchableHighlightProperties = TouchableHighlightProps; + +/** @deprecated Use TouchableOpacityProps */ +export type TouchableOpacityProperties = TouchableOpacityProps; + +/** @deprecated Use TouchableNativeFeedbackProps */ +export type TouchableNativeFeedbackProperties = TouchableNativeFeedbackProps; + +/** @deprecated Use ButtonProps */ +export type ButtonProperties = ButtonProps; + +/** @deprecated Use StatusBarProps */ +export type StatusBarProperties = StatusBarProps; + +/** @deprecated Use StatusBarPropsIOS */ +export type StatusBarPropertiesIOS = StatusBarPropsIOS; + +/** @deprecated Use StatusBarPropsAndroid */ +export type StatusBarPropertiesAndroid = StatusBarPropsAndroid; + +/** @deprecated Use SwitchProps */ +export type SwitchProperties = SwitchProps; + +/** @deprecated Use SwitchPropsIOS */ +export type SwitchPropertiesIOS = SwitchPropsIOS; diff --git a/types/public/Insets.d.ts b/types/public/Insets.d.ts new file mode 100644 index 00000000000000..9f77753ecc1604 --- /dev/null +++ b/types/public/Insets.d.ts @@ -0,0 +1,15 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +export interface Insets { + top?: number | undefined; + left?: number | undefined; + bottom?: number | undefined; + right?: number | undefined; +} diff --git a/types/public/ReactNativeRenderer.d.ts b/types/public/ReactNativeRenderer.d.ts new file mode 100644 index 00000000000000..542788c77b5b73 --- /dev/null +++ b/types/public/ReactNativeRenderer.d.ts @@ -0,0 +1,149 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import {GestureResponderEvent} from '../../Libraries/Types/CoreEventTypes'; + +/** + * Gesture recognition on mobile devices is much more complicated than web. + * A touch can go through several phases as the app determines what the user's intention is. + * For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. + * This can even change during the duration of a touch. There can also be multiple simultaneous touches. + * + * The touch responder system is needed to allow components to negotiate these touch interactions + * without any additional knowledge about their parent or child components. + * This system is implemented in ResponderEventPlugin.js, which contains further details and documentation. + * + * Best Practices + * Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. + * Every action should have the following attributes: + * Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture + * Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away + * + * These features make users more comfortable while using an app, + * because it allows people to experiment and interact without fear of making mistakes. + * + * TouchableHighlight and Touchable* + * The responder system can be complicated to use. + * So we have provided an abstract Touchable implementation for things that should be "tappable". + * This uses the responder system and allows you to easily configure tap interactions declaratively. + * Use TouchableHighlight anywhere where you would use a button or link on web. + */ +export interface GestureResponderHandlers { + /** + * A view can become the touch responder by implementing the correct negotiation methods. + * There are two methods to ask the view if it wants to become responder: + */ + + /** + * Does this view want to become responder on the start of a touch? + */ + onStartShouldSetResponder?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? + */ + onMoveShouldSetResponder?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * If the View returns true and attempts to become the responder, one of the following will happen: + */ + + onResponderEnd?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * The View is now responding for touch events. + * This is the time to highlight and show the user what is happening + */ + onResponderGrant?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Something else is the responder right now and will not release it + */ + onResponderReject?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * If the view is responding, the following handlers can be called: + */ + + /** + * The user is moving their finger + */ + onResponderMove?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Fired at the end of the touch, ie "touchUp" + */ + onResponderRelease?: ((event: GestureResponderEvent) => void) | undefined; + + onResponderStart?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * Something else wants to become responder. + * Should this view release the responder? Returning true allows release + */ + onResponderTerminationRequest?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * The responder has been taken from the View. + * Might be taken by other views after a call to onResponderTerminationRequest, + * or might be taken by the OS without asking (happens with control center/ notification center on iOS) + */ + onResponderTerminate?: ((event: GestureResponderEvent) => void) | undefined; + + /** + * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, + * where the deepest node is called first. + * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. + * This is desirable in most cases, because it makes sure all controls and buttons are usable. + * + * However, sometimes a parent will want to make sure that it becomes responder. + * This can be handled by using the capture phase. + * Before the responder system bubbles up from the deepest component, + * it will do a capture phase, firing on*ShouldSetResponderCapture. + * So if a parent View wants to prevent the child from becoming responder on a touch start, + * it should have a onStartShouldSetResponderCapture handler which returns true. + */ + onStartShouldSetResponderCapture?: + | ((event: GestureResponderEvent) => boolean) + | undefined; + + /** + * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, + * where the deepest node is called first. + * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. + * This is desirable in most cases, because it makes sure all controls and buttons are usable. + * + * However, sometimes a parent will want to make sure that it becomes responder. + * This can be handled by using the capture phase. + * Before the responder system bubbles up from the deepest component, + * it will do a capture phase, firing on*ShouldSetResponderCapture. + * So if a parent View wants to prevent the child from becoming responder on a touch start, + * it should have a onStartShouldSetResponderCapture handler which returns true. + */ + onMoveShouldSetResponderCapture?: + | ((event: GestureResponderEvent) => boolean) + | undefined; +} + +/** + * React Native also implements unstable_batchedUpdates + */ +export function unstable_batchedUpdates( + callback: (a: A, b: B) => any, + a: A, + b: B, +): void; +export function unstable_batchedUpdates(callback: (a: A) => any, a: A): void; +export function unstable_batchedUpdates(callback: () => any): void; diff --git a/types/public/ReactNativeTypes.d.ts b/types/public/ReactNativeTypes.d.ts new file mode 100644 index 00000000000000..38e00e1cc933ca --- /dev/null +++ b/types/public/ReactNativeTypes.d.ts @@ -0,0 +1,141 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import type * as React from 'react'; + +export type MeasureOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, + pageX: number, + pageY: number, +) => void; + +export type MeasureInWindowOnSuccessCallback = ( + x: number, + y: number, + width: number, + height: number, +) => void; + +export type MeasureLayoutOnSuccessCallback = ( + left: number, + top: number, + width: number, + height: number, +) => void; + +/** + * NativeMethods provides methods to access the underlying native component directly. + * This can be useful in cases when you want to focus a view or measure its on-screen dimensions, + * for example. + * The methods described here are available on most of the default components provided by React Native. + * Note, however, that they are not available on composite components that aren't directly backed by a + * native view. This will generally include most components that you define in your own app. + * For more information, see [Direct Manipulation](https://reactnative.dev/docs/direct-manipulation). + * @see https://github.com/facebook/react-native/blob/master/Libraries/Renderer/shims/ReactNativeTypes.js#L87 + */ +export interface NativeMethods { + /** + * Determines the location on screen, width, and height of the given view and + * returns the values via an async callback. If successful, the callback will + * be called with the following arguments: + * + * - x + * - y + * - width + * - height + * - pageX + * - pageY + * + * Note that these measurements are not available until after the rendering + * has been completed in native. If you need the measurements as soon as + * possible, consider using the [`onLayout` + * prop](docs/view.html#onlayout) instead. + */ + measure(callback: MeasureOnSuccessCallback): void; + + /** + * Determines the location of the given view in the window and returns the + * values via an async callback. If the React root view is embedded in + * another native view, this will give you the absolute coordinates. If + * successful, the callback will be called with the following + * arguments: + * + * - x + * - y + * - width + * - height + * + * Note that these measurements are not available until after the rendering + * has been completed in native. + */ + measureInWindow(callback: MeasureInWindowOnSuccessCallback): void; + + /** + * Like [`measure()`](#measure), but measures the view relative an ancestor, + * specified as `relativeToNativeComponentRef`. This means that the returned x, y + * are relative to the origin x, y of the ancestor view. + * _Can also be called with a relativeNativeNodeHandle but is deprecated._ + */ + measureLayout( + relativeToNativeComponentRef: HostComponent | number, + onSuccess: MeasureLayoutOnSuccessCallback, + onFail: () => void /* currently unused */, + ): void; + + /** + * This function sends props straight to native. They will not participate in + * future diff process - this means that if you do not include them in the + * next render, they will remain active (see [Direct + * Manipulation](https://reactnative.dev/docs/direct-manipulation)). + */ + setNativeProps(nativeProps: object): void; + + /** + * Requests focus for the given input or view. The exact behavior triggered + * will depend on the platform and type of view. + */ + focus(): void; + + /** + * Removes focus from an input or view. This is the opposite of `focus()`. + */ + blur(): void; + + refs: { + [key: string]: React.Component; + }; +} + +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixin = NativeMethods; +/** + * @deprecated Use NativeMethods instead. + */ +export type NativeMethodsMixinType = NativeMethods; + +/** + * Represents a native component, such as those returned from `requireNativeComponent`. + * + * @see https://github.com/facebook/react-native/blob/v0.62.0-rc.5/Libraries/Renderer/shims/ReactNativeTypes.js + * + * @todo This should eventually be defined as an AbstractComponent, but that + * should first be introduced in the React typings. + */ +export interface HostComponent

+ extends Pick< + React.ComponentClass

, + Exclude, 'new'> + > { + new (props: P, context?: any): React.Component

& Readonly; +} diff --git a/types/tsconfig.json b/types/tsconfig.json index 83a180a27f46d8..7cabbef31792d9 100644 --- a/types/tsconfig.json +++ b/types/tsconfig.json @@ -10,10 +10,6 @@ "jsx": "react", "noEmit": true, "forceConsistentCasingInFileNames": true, - - // If the library is an external module (uses `export`), this allows your test file to import "mylib" instead of "./index". - // If the library is global (cannot be imported via `import` or `require`), leave this out. - "baseUrl": ".", "paths": {"react-native": ["."]} } } From 46de03a46a25567db62c316e6ea5af5cfdbfe4d9 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 2 Nov 2022 16:02:53 -0700 Subject: [PATCH 116/169] Fix test_buck by not using lambdas inside ReactImagePropertyTest (#35181) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35181 As the title says, this unblocks `test_buck` by removign the lambdas used inside test. Changelog: [Internal] [Changed] - Fix test_buck by not using lambdas inside ReactImagePropertyTest Reviewed By: cipolleschi Differential Revision: D40958412 fbshipit-source-id: 60b8609a25985230dfd6c4dcdf983dc2a8cfaf64 --- .../views/image/ReactImagePropertyTest.java | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java index 779b245d7a815e..a2e255f1e4db5c 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java +++ b/ReactAndroid/src/test/java/com/facebook/react/views/image/ReactImagePropertyTest.java @@ -35,6 +35,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -61,9 +62,21 @@ public class ReactImagePropertyTest { public void setup() { PowerMockito.mockStatic(Arguments.class); PowerMockito.when(Arguments.createArray()) - .thenAnswer((InvocationOnMock invocation) -> new JavaOnlyArray()); + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return new JavaOnlyArray(); + } + }); PowerMockito.when(Arguments.createMap()) - .thenAnswer((InvocationOnMock invocation) -> new JavaOnlyMap()); + .thenAnswer( + new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return new JavaOnlyMap(); + } + }); // RNLog is stubbed out and the whole class need to be mocked PowerMockito.mockStatic(RNLog.class); From e8d3fb87f19a8b41a95c461f73d6f60c3fa1803a Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Wed, 2 Nov 2022 18:57:10 -0700 Subject: [PATCH 117/169] Bump RNGP to 0.71.8 Summary: Just bumping RNGP to make the new sources avialable to the template. Changelog: [Internal] [Changed] - Bump RNGP to 0.71.8 Reviewed By: robhogan Differential Revision: D40948246 fbshipit-source-id: c6a193fcdc0675be9ef7f1320d63e884b8b65daa --- package.json | 2 +- packages/react-native-gradle-plugin/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 406d52d52ef9ef..4261b905d07838 100644 --- a/package.json +++ b/package.json @@ -132,7 +132,7 @@ "pretty-format": "^26.5.2", "promise": "^8.3.0", "react-devtools-core": "^4.26.1", - "react-native-gradle-plugin": "^0.71.7", + "react-native-gradle-plugin": "^0.71.8", "react-refresh": "^0.4.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 0a5919742154a0..6338d040198037 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "react-native-gradle-plugin", - "version": "0.71.7", + "version": "0.71.8", "description": "⚛️ Gradle Plugin for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", "repository": { From 714b22bb431a7384a6e06141d5b3f367de2f75cd Mon Sep 17 00:00:00 2001 From: Shawn Dempsey Date: Wed, 2 Nov 2022 19:00:07 -0700 Subject: [PATCH 118/169] Local filenames with colon should be parsed correctly (#35123) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35123 **Context** On RN Desktop, images can be copy/pasted into text inputs. When copy/pasting local files w/ semi-colons in the filename (`/downloads/devices:pre-call-IMG_346C38284B2B-1.jpeg`), RN would throw this error. {F785684529} The error was due to no having the correct asset loader due to the local file path being parsed incorrectly. To parse the url, we convert the string URI to a `NSURL` using a custom convertor fn. The conversion was matching any `:` and assuming it was a network url scheme: https://www.internalfb.com/code/archon_react_native_macos/[fde4113acd89fb13ee11636c48b59eac49c21bae]/React/Base/RCTConvert.m?lines=97-111 When an image path with `:` in the name was passed to this, it was assuming it was a valid network url and not file path. Because this is a local filepath, the image path needs to be a filesystem url. Since this was parsed as network url, it did not have the `file://` prefix and would not pass this check, causing the loader to throw.l https://www.internalfb.com/code/fbsource/%5B60d9d5e67383%5D/xplat/js/react-native-github/Libraries/Image/RCTImageLoader.mm?lines=220-230 ## Changelog [iOS] [Added] - Add support for parsing files w/ `:` in filename Reviewed By: christophpurrer, philIip Differential Revision: D40729963 fbshipit-source-id: 2f3adcabc8f0f1f22cbfca69c3484e72b1d93d25 --- React/Base/RCTConvert.m | 2 +- packages/rn-tester/RNTesterUnitTests/RCTConvert_NSURLTests.m | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/React/Base/RCTConvert.m b/React/Base/RCTConvert.m index 33e2a094a0484a..5e4820585b0131 100644 --- a/React/Base/RCTConvert.m +++ b/React/Base/RCTConvert.m @@ -91,7 +91,7 @@ + (NSURL *)NSURL:(id)json } // Check if it has a scheme - if ([path rangeOfString:@":"].location != NSNotFound) { + if ([path rangeOfString:@"://"].location != NSNotFound) { NSMutableCharacterSet *urlAllowedCharacterSet = [NSMutableCharacterSet new]; [urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLUserAllowedCharacterSet]]; [urlAllowedCharacterSet formUnionWithCharacterSet:[NSCharacterSet URLPasswordAllowedCharacterSet]]; diff --git a/packages/rn-tester/RNTesterUnitTests/RCTConvert_NSURLTests.m b/packages/rn-tester/RNTesterUnitTests/RCTConvert_NSURLTests.m index 2eb72a7a170078..7d3dadde38fbc8 100644 --- a/packages/rn-tester/RNTesterUnitTests/RCTConvert_NSURLTests.m +++ b/packages/rn-tester/RNTesterUnitTests/RCTConvert_NSURLTests.m @@ -45,6 +45,9 @@ -(void)test_##name \ TEST_BUNDLE_PATH(imageAt2XPath, @"images/foo@2x.jpg", @"images/foo@2x.jpg") TEST_BUNDLE_PATH(imageFile, @"foo.jpg", @"foo.jpg") +TEST_BUNDLE_PATH(imageFileWithSemicolon, @"folder/foo:bar-baz.jpg", @"folder/foo:bar-baz.jpg") +TEST_URL(filePathWithSemicolon, @"/folder/foo:bar-baz.jpg", @"file:///folder/foo:bar-baz.jpg") + // User documents TEST_PATH( documentsFolder, From a671d61b6de5f106e9fd803a73fddb4b6fa6656b Mon Sep 17 00:00:00 2001 From: Ruslan Shestopalyuk Date: Wed, 2 Nov 2022 19:44:29 -0700 Subject: [PATCH 119/169] Add JS stub for PerformanceObserver specs Summary: This stubs all the type definitions for the [PerformanceObserver web perf APIs](https://www.w3.org/TR/performance-timeline/#the-performanceobserver-interface). Changelog: [Internal] Reviewed By: javache Differential Revision: D40892974 fbshipit-source-id: 31fe972fc069eb62e51bca82e9cd42ca65811753 --- Libraries/Performance/PerformanceObserver.js | 124 +++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 Libraries/Performance/PerformanceObserver.js diff --git a/Libraries/Performance/PerformanceObserver.js b/Libraries/Performance/PerformanceObserver.js new file mode 100644 index 00000000000000..8974b1da6c8189 --- /dev/null +++ b/Libraries/Performance/PerformanceObserver.js @@ -0,0 +1,124 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @flow strict + */ + +'use strict'; + +export type Timestamp = number; +export type PerformanceEntryType = 'event'; + +export class PerformanceEntry { + name: string; + entryType: PerformanceEntryType; + startTime: Timestamp; + duration: number; + + // For "event" entries only: + processingStart: ?Timestamp; + processingEnd: ?Timestamp; + interactionId: ?number; + + // $FlowIgnore: Flow(unclear-type) + toJSON(): Object { + return { + name: this.name, + entryType: this.entryType, + startTime: this.startTime, + duration: this.duration, + }; + } +} + +export type PerformanceEntryList = $ReadOnlyArray; + +export class PerformanceObserverEntryList { + _entries: PerformanceEntryList; + + constructor(entries: PerformanceEntryList) { + this._entries = entries; + } + + getEntries(): PerformanceEntryList { + return this._entries; + } + + getEntriesByType(type: PerformanceEntryType): PerformanceEntryList { + return this._entries.filter(entry => entry.entryType === type); + } + + getEntriesByName( + name: string, + type?: PerformanceEntryType, + ): PerformanceEntryList { + if (type === undefined) { + return this._entries.filter(entry => entry.name === name); + } else { + return this._entries.filter( + entry => entry.name === name && entry.entryType === type, + ); + } + } +} + +export type PerformanceObserverCallback = ( + list: PerformanceObserverEntryList, + observer: PerformanceObserver, +) => void; + +export type PerformanceObserverInit = + | { + entryTypes: PerformanceEntryType[], + buffered?: boolean, + } + | { + type: PerformanceEntryType, + buffered?: boolean, + }; + +/** + * Implementation of the PerformanceObserver interface for RN, + * corresponding to the standard in https://www.w3.org/TR/performance-timeline/ + * + * @example + * const observer = new PerformanceObserver((list, _observer) => { + * const entries = list.getEntries(); + * entries.forEach(entry => { + * reportEvent({ + * eventName: entry.name, + * startTime: entry.startTime, + * endTime: entry.startTime + entry.duration, + * processingStart: entry.processingStart, + * processingEnd: entry.processingEnd, + * interactionId: entry.interactionId, + * }); + * }); + * }); + * observer.observe({ type: "event" }); + */ +export default class PerformanceObserver { + _callback: PerformanceObserverCallback; + + constructor(callback: PerformanceObserverCallback) { + this._callback = callback; + } + + observe(options: PerformanceObserverInit) { + console.log('PerformanceObserver: started observing'); + } + + disconnect(): void { + console.log('PerformanceObserver: stopped observing'); + } + + takeRecords(): PerformanceEntryList { + return []; + } + + static supportedEntryTypes: PerformanceEntryType[] = ['event']; +} From 4f3ca8facfc41f27169c49ad8b3a28d3022d5f0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Wed, 2 Nov 2022 20:59:03 -0700 Subject: [PATCH 120/169] cleanup publish-npm.js: --include-hermes is not used anywhere (#35166) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35166 The Hermes source code is not included in the RN npm package. This piece of code is a remnant from an early experimentation into integrating Hermes more tightly with React Native. We ended up using a combination of the scripts in `scripts/hermes` to fetch the source code from GitHub and relying on prebuilts for stable releases. Added `strict()` flag to ensure the script fails immediately if an unrecognized flag is passed. Avoid logging temp publishing folder value to console when `--help` is used. Changelog: [internal] Reviewed By: cortinico Differential Revision: D40918939 fbshipit-source-id: 2e62ab16467c4c67f03efdf5211a156cb70e0b11 --- scripts/publish-npm.js | 67 ++++-------------------------------------- 1 file changed, 5 insertions(+), 62 deletions(-) diff --git a/scripts/publish-npm.js b/scripts/publish-npm.js index 25900e6bea89db..4b9821b37c8570 100755 --- a/scripts/publish-npm.js +++ b/scripts/publish-npm.js @@ -53,7 +53,6 @@ const otp = process.env.NPM_CONFIG_OTP; const tmpPublishingFolder = fs.mkdtempSync( path.join(os.tmpdir(), 'rn-publish-'), ); -echo(`The temp publishing folder is ${tmpPublishingFolder}`); const argv = yargs .option('n', { @@ -66,73 +65,17 @@ const argv = yargs type: 'boolean', default: false, }) - .option('h', { - alias: 'include-hermes', - type: 'boolean', - default: false, - }).argv; + .strict().argv; const nightlyBuild = argv.nightly; const dryRunBuild = argv.dryRun; -const includeHermes = argv.includeHermes; const isCommitly = nightlyBuild || dryRunBuild; -saveFilesToRestore(tmpPublishingFolder); - -if (includeHermes) { - const HERMES_INSTALL_LOCATION = 'sdks'; - const HERMES_SOURCE_DEST_PATH = `${HERMES_INSTALL_LOCATION}/hermes`; - - let hermesReleaseTag; - let hermesReleaseURI; - if (isCommitly) { - // use latest commit / tarball - hermesReleaseURI = 'https://github.com/facebook/hermes/tarball/main'; - } else { - // use one configured in disk - fs.readFile( - `${HERMES_INSTALL_LOCATION}/.hermesversion`, - { - encoding: 'utf8', - flag: 'r', - }, - function (err, data) { - if (err) { - echo('Failed to read current Hermes release tag.'); - // TODO: We'll need to make sure every release going forward has one of these. - exit(1); - } else { - hermesReleaseTag = data.trim(); - hermesReleaseURI = `https://github.com/facebook/hermes/archive/refs/tags/${hermesReleaseTag}.tar.gz`; - } - }, - ); - } - - const tmpDownloadDir = fs.mkdtempSync( - path.join(os.tmpdir(), 'hermes-tarball'), - ); - const tmpExtractDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes')); - - const hermesInstallScript = ` - mkdir -p ${HERMES_SOURCE_DEST_PATH} && \ - wget ${hermesReleaseURI} -O ${tmpDownloadDir}/hermes.tar.gz && \ - tar -xzf ${tmpDownloadDir}/hermes.tar.gz -C ${tmpExtractDir} && \ - HERMES_SOURCE_EXTRACT_PATH=$(ls -d ${tmpExtractDir}/*) && \ - mv $HERMES_SOURCE_EXTRACT_PATH ${HERMES_SOURCE_DEST_PATH} - `; - - if (fs.existsSync(`${HERMES_SOURCE_DEST_PATH}`)) { - if (exec(`rm -rf ./${HERMES_SOURCE_DEST_PATH}`).code) { - echo('Failed to clean up previous Hermes installation.'); - exit(1); - } - } - if (exec(hermesInstallScript).code) { - echo('Failed to include Hermes in release.'); - exit(1); - } +if (!argv.help) { + echo(`The temp publishing folder is ${tmpPublishingFolder}`); } +saveFilesToRestore(tmpPublishingFolder); + // 34c034298dc9cad5a4553964a5a324450fda0385 const currentCommit = getCurrentCommit(); const shortCommit = currentCommit.slice(0, 9); From f207cfddf37c01b5ff2c2f53b4d44a4cc7ad2484 Mon Sep 17 00:00:00 2001 From: Lulu Wu Date: Wed, 2 Nov 2022 21:01:53 -0700 Subject: [PATCH 121/169] Add atomic registerSegment method to test Summary: In the top js errors there are 2 mids related to segment fetching: - requireForFacebook.js:unknownModuleError (https://www.internalfb.com/logview/details/facebook_android_javascripterrors/ba11461526aff8a6842401b35b02f5a4), 11.64 K vs. 524 - asyncRequire.js:verifySegment (https://www.internalfb.com/logview/details/facebook_android_javascripterrors/5452ba893b8d9ba8e97e070cf6976b65) 5.39 K vs. 180 Both errors will result in surface not loading. A lot of traces have logs similar with the following: ```11-01 19:57:51.166 27735 7626 W fb4a.BridgelessReact: registerSegment(segmentId = "1090", path = "/data/data/com.facebook.katana/app_overtheair/resources/412137089/414433453/hbc-seg-1090__DELIM__main.jsbundle") 11-01 19:57:51.167 27735 7445 I ReactNativeJS: Module 39122 in segment 0 doesn not exist moduleDefiner 11-01 19:57:51.171 27735 7445 E ReactNativeJS: Error: Requiring unknown module "39122"., js build: 414433453 11-01 19:57:51.175 27735 7445 E ReactNativeJS: Error: Segment meta module is not setup properly. Details: segmentId = 1090, metaModule === undefined 11-01 19:57:51.175 27735 7445 E ReactNativeJS: 11-01 19:57:51.175 27735 7445 E ReactNativeJS: This error is located at: ``` RegisterSegment lives through 3 threads while in bridge there are only 2 threads involved (native & JS): - Native thread, log printed (fb4a.BridgelessReact: registerSegment...) - Background thread: no log, added in this diff (Finish registerSegment...) - JS thread: logs not printed, should print logs here: https://www.internalfb.com/code/fbsource/[60521987354ed1ef9a0d10bafc60db3c25302ab4]/xplat/ReactNative/venice/ReactInstance.cpp?lines=308-330 Since the JS thread logs aren't printed and there are segment errors right after calling registerSegemnt, I think registerSegment is not done. It could be caused by: - ReactInstance being null, I added logs in background thread to verify (Finish registerSegment...) since dispatching to background thread relies on non-nullable ReactInstance. - Work on JS thread hasn't been executed when trying to use/verify the segment. I added atomic method ```registerSegmentAtomic``` to make sure JS thread is blocked until segment is fully registered. ```registerSegmentAtomic``` will be tested behind gating added in D40917444. Changelog: [Android][Changed] - Add feature flag enableAtomicRegisterSegment Reviewed By: RSNara Differential Revision: D40921759 fbshipit-source-id: 84221aa81f0c549f931a4847b154187299639ef4 --- .../main/java/com/facebook/react/config/ReactFeatureFlags.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java index f837171c99490b..a4cf989ca750bf 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java +++ b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java @@ -120,4 +120,7 @@ public class ReactFeatureFlags { /** Temporary flag to allow execution of mount items up to 15ms earlier than normal. */ public static boolean enableEarlyScheduledMountItemExecution = false; + + // TODO (T136375139): Remove this once finish testing + public static boolean enableAtomicRegisterSegment = false; } From aaf1990287088a6b38269174e402143c90683881 Mon Sep 17 00:00:00 2001 From: Nick Gerleman Date: Wed, 2 Nov 2022 21:40:58 -0700 Subject: [PATCH 122/169] Use TypeScript by default for new applications (#35165) Summary: This change moves the default new application template in OSS from Flow to TypeScript. This better aligns with the communities usage, and aligns to the great work that has been happening for TS codegen and built-in types. This used [`react-native-community/react-native-template-typescript`](https://github.com/react-native-community/react-native-template-typescript) as a main reference, maintained by radko93. A few things are different: 1. Updated `types/*` devDependencies to match bumped libraries (e.g. Jest 26 to 20). 2. Removed `types/react-native` 3. Removed explicit `moduleFileExtensions` to Jest config in package.json (TS and TSX and added by default in current versions) 4. Removed overrides to eslint config to disable `no-shadow` and `no-undef`, since this was fixed in the underlying eslint config with https://github.com/facebook/react-native/pull/32644 and https://github.com/facebook/react-native/pull/32655 5. Re-translated `App.js` to be a direct translation (e.g. still a raw function instead of React.FC which is sometimes discouraged) 6. Aligns completely to `tsconfig/react-native` maintained configuration (We no longer have the opinionated override of `skipLibCheck`). The important settings are that `strict` is enabled for, but `allowJS` is also enabled to let users import JS modules without anything unexpected. `esModuleInterop` is enabled, which is needed for consistency with Babel import transformations used by Metro. Consistent with our [current documentation](https://reactnative.dev/docs/typescript) built against the community template, `tsc` will typecheck your code without emitting(building) anything. [Documentation](https://reactnative.dev/docs/typescript) will need to be updated as a followup. Changelog: [General][Changed] - Use TypeScript by default for new applications Pull Request resolved: https://github.com/facebook/react-native/pull/35165 Test Plan: Added usage of `tsc` and `jest` when validating a newly built app. Passes in CircleCI `test_js` job. This also meant removing some cases of copying packages into the users app to pull in the root Metro config (we seem to be able to use the template Metro config consistent with what real apps would get). Reviewed By: cortinico Differential Revision: D40911951 Pulled By: NickGerleman fbshipit-source-id: 15994534235695e91cf994ad06ba2183dfc89a50 --- scripts/run-ci-e2e-tests.js | 32 +++++----- template/{App.js => App.tsx} | 14 ++--- .../__tests__/{App-test.js => App-test.tsx} | 0 template/_buckconfig | 6 -- template/_eslintrc.js | 2 + template/_flowconfig | 63 ------------------- template/package.json | 13 +++- template/tsconfig.json | 3 + 8 files changed, 35 insertions(+), 98 deletions(-) rename template/{App.js => App.tsx} (92%) rename template/__tests__/{App-test.js => App-test.tsx} (100%) delete mode 100644 template/_buckconfig delete mode 100644 template/_flowconfig create mode 100644 template/tsconfig.json diff --git a/scripts/run-ci-e2e-tests.js b/scripts/run-ci-e2e-tests.js index 1c013ba073537c..cdff750f3192b9 100644 --- a/scripts/run-ci-e2e-tests.js +++ b/scripts/run-ci-e2e-tests.js @@ -89,19 +89,9 @@ try { exec(`rsync -a ${ROOT}/template ${REACT_NATIVE_TEMP_DIR}`); cd(REACT_NATIVE_APP_DIR); - const METRO_CONFIG = path.join(ROOT, 'metro.config.js'); - const RN_GET_POLYFILLS = path.join(ROOT, 'rn-get-polyfills.js'); - const RN_POLYFILLS_PATH = 'packages/polyfills/'; - exec(`mkdir -p ${RN_POLYFILLS_PATH}`); - - cp(METRO_CONFIG, '.'); - cp(RN_GET_POLYFILLS, '.'); - exec( - `rsync -a ${ROOT}/${RN_POLYFILLS_PATH} ${REACT_NATIVE_APP_DIR}/${RN_POLYFILLS_PATH}`, - ); - mv('_flowconfig', '.flowconfig'); - mv('_watchmanconfig', '.watchmanconfig'); mv('_bundle', '.bundle'); + mv('_eslintrc.js', '.eslintrc.js'); + mv('_watchmanconfig', '.watchmanconfig'); describe('Install React Native package'); exec(`npm install ${REACT_NATIVE_PACKAGE}`); @@ -267,6 +257,7 @@ try { exitCode = 1; throw Error(exitCode); } + describe('Test: Verify packager can generate an iOS bundle'); if ( exec( @@ -277,12 +268,17 @@ try { exitCode = 1; throw Error(exitCode); } - describe('Test: Flow check'); - // The resolve package included a test for a malformed package.json (see https://github.com/browserify/resolve/issues/89) - // that is failing the flow check. We're removing it. - rm('-rf', './node_modules/resolve/test/resolver/malformed_package_json'); - if (exec(`${ROOT}/node_modules/.bin/flow check`).code) { - echo('Flow check failed.'); + + describe('Test: TypeScript typechecking'); + if (exec('yarn tsc').code) { + echo('Typechecking errors were found'); + exitCode = 1; + throw Error(exitCode); + } + + describe('Test: Jest tests'); + if (exec('yarn test').code) { + echo('Jest tests failed'); exitCode = 1; throw Error(exitCode); } diff --git a/template/App.js b/template/App.tsx similarity index 92% rename from template/App.js rename to template/App.tsx index ba7b59897f496e..71991406fe1fe9 100644 --- a/template/App.js +++ b/template/App.tsx @@ -3,11 +3,10 @@ * https://github.com/facebook/react-native * * @format - * @flow strict-local */ import React from 'react'; -import type {Node} from 'react'; +import type {PropsWithChildren} from 'react'; import { SafeAreaView, ScrollView, @@ -26,12 +25,11 @@ import { ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; -type SectionProps = { - title: string, - children: Node, -}; +type SectionProps = PropsWithChildren<{ + title: string; +}>; -function Section({children, title}: SectionProps): Node { +function Section({children, title}: SectionProps): JSX.Element { const isDarkMode = useColorScheme() === 'dark'; return ( @@ -57,7 +55,7 @@ function Section({children, title}: SectionProps): Node { ); } -function App(): Node { +function App(): JSX.Element { const isDarkMode = useColorScheme() === 'dark'; const backgroundStyle = { diff --git a/template/__tests__/App-test.js b/template/__tests__/App-test.tsx similarity index 100% rename from template/__tests__/App-test.js rename to template/__tests__/App-test.tsx diff --git a/template/_buckconfig b/template/_buckconfig deleted file mode 100644 index 934256cb29d4a3..00000000000000 --- a/template/_buckconfig +++ /dev/null @@ -1,6 +0,0 @@ - -[android] - target = Google Inc.:Google APIs:23 - -[maven_repositories] - central = https://repo1.maven.org/maven2 diff --git a/template/_eslintrc.js b/template/_eslintrc.js index 40c6dcd05f3100..189699723fd268 100644 --- a/template/_eslintrc.js +++ b/template/_eslintrc.js @@ -1,4 +1,6 @@ module.exports = { root: true, extends: '@react-native-community', + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint'], }; diff --git a/template/_flowconfig b/template/_flowconfig deleted file mode 100644 index b929e039dc850d..00000000000000 --- a/template/_flowconfig +++ /dev/null @@ -1,63 +0,0 @@ -[ignore] -; We fork some components by platform -.*/*[.]android.js - -; Ignore polyfills -node_modules/react-native/Libraries/polyfills/.* - -; Flow doesn't support platforms -.*/Libraries/Utilities/LoadingView.js - -.*/node_modules/resolve/test/resolver/malformed_package_json/package\.json$ - -[untyped] -.*/node_modules/@react-native-community/cli/.*/.* - -[include] - -[libs] -node_modules/react-native/interface.js -node_modules/react-native/flow/ - -[options] -emoji=true - -exact_by_default=true - -format.bracket_spacing=false - -module.file_ext=.js -module.file_ext=.json -module.file_ext=.ios.js - -munge_underscores=true - -module.name_mapper='^react-native/\(.*\)$' -> '/node_modules/react-native/\1' -module.name_mapper='^@?[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> '/node_modules/react-native/Libraries/Image/RelativeImageStub' - -suppress_type=$FlowIssue -suppress_type=$FlowFixMe -suppress_type=$FlowFixMeProps -suppress_type=$FlowFixMeState - -[lints] -sketchy-null-number=warn -sketchy-null-mixed=warn -sketchy-number=warn -untyped-type-import=warn -nonstrict-import=warn -deprecated-type=warn -unsafe-getters-setters=warn -unnecessary-invariant=warn - -[strict] -deprecated-type -nonstrict-import -sketchy-null -unclear-type -unsafe-getters-setters -untyped-import -untyped-type-import - -[version] -^0.191.0 diff --git a/template/package.json b/template/package.json index af4a7228d099ca..b70769d0759293 100644 --- a/template/package.json +++ b/template/package.json @@ -5,9 +5,9 @@ "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", + "lint": "eslint .", "start": "react-native start", - "test": "jest", - "lint": "eslint ." + "test": "jest" }, "dependencies": { "react": "18.2.0", @@ -17,11 +17,18 @@ "@babel/core": "^7.12.9", "@babel/runtime": "^7.12.5", "@react-native-community/eslint-config": "^3.0.0", + "@tsconfig/react-native": "^2.0.2", + "@types/jest": "^29.2.1", + "@types/react": "^18.0.24", + "@types/react-test-renderer": "^18.0.0", + "@typescript-eslint/eslint-plugin": "^5.37.0", + "@typescript-eslint/parser": "^5.37.0", "babel-jest": "^29.2.1", "eslint": "^8.19.0", "jest": "^29.2.1", "metro-react-native-babel-preset": "0.73.3", - "react-test-renderer": "18.2.0" + "react-test-renderer": "18.2.0", + "typescript": "^4.8.3" }, "jest": { "preset": "react-native" diff --git a/template/tsconfig.json b/template/tsconfig.json new file mode 100644 index 00000000000000..45a6c707223871 --- /dev/null +++ b/template/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "@tsconfig/react-native/tsconfig.json" +} From 890805db9cc639846c93edc0e13eddbf67dbc7af Mon Sep 17 00:00:00 2001 From: Sergei Karpukhin Date: Thu, 3 Nov 2022 02:44:08 -0700 Subject: [PATCH 123/169] Add various annotation types to markEvent ReactNative API Summary: Support various annotations types in QuickPerformanceLogger markEvent for Android. Changelog: [Internal][Changed] - Added support for various markEvent annotation types Reviewed By: dmitry-voronkevich Differential Revision: D40852658 fbshipit-source-id: fc4053555f65958653be30a58742c83040a19df1 --- .../Performance/QuickPerformanceLogger.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Libraries/Performance/QuickPerformanceLogger.js b/Libraries/Performance/QuickPerformanceLogger.js index 9e8a6cd657c3a4..4a0da73e47825d 100644 --- a/Libraries/Performance/QuickPerformanceLogger.js +++ b/Libraries/Performance/QuickPerformanceLogger.js @@ -18,6 +18,13 @@ const DUMMY_INSTANCE_KEY = 0; // {string: {key1: value1, key2: value2}} export type AnnotationsMap = $Shape<{ string: ?{[string]: string, ...}, + int: ?{[string]: number, ...}, + double: ?{[string]: number, ...}, + bool: ?{[string]: boolean, ...}, + string_array: ?{[string]: $ReadOnlyArray, ...}, + int_array: ?{[string]: $ReadOnlyArray, ...}, + double_array: ?{[string]: $ReadOnlyArray, ...}, + bool_array: ?{[string]: $ReadOnlyArray, ...}, }>; const QuickPerformanceLogger = { @@ -60,7 +67,16 @@ const QuickPerformanceLogger = { if (global.nativeQPLMarkerAnnotateWithMap) { global.nativeQPLMarkerAnnotateWithMap(markerId, annotations, instanceKey); } else if (global.nativeQPLMarkerAnnotate) { - for (const type of ['string']) { + for (const type of [ + 'string', + 'int', + 'double', + 'bool', + 'string_array', + 'int_array', + 'double_array', + 'bool_array', + ]) { const keyValsOfType = annotations[type]; if (keyValsOfType != null) { for (const annotationKey of Object.keys(keyValsOfType)) { From d9ab5e81cf6a030438b36e0c27d45f20317c316e Mon Sep 17 00:00:00 2001 From: Yoonseok Ko Date: Thu, 3 Nov 2022 05:19:36 -0700 Subject: [PATCH 124/169] A bug fix - the undefined behavior of `idleCallbacks`'s `timeRemaining`. Summary: ## Changelog: [Android] [Fixed] - Fix a bug that returns a random number from callback argument `timeRemaining` of `idleCallbacks` registered by `requestIdleCallbacks`. `global.performance.now()` returns a time from an unknown origin, while `frameTime` is epoch time. Thus, `global.performance.now() - frameTime` is just a random number rather than an elapsed time from the frame start time. As a simple solution, I would suggest to use `Date.now()`. Its resolution is lower than `frameTime` due to the security issue in JavaScript VM. So, it loses some precision, but, at least, it is not wrong. Reviewed By: javache Differential Revision: D40941461 fbshipit-source-id: b0094e181b97a844d133a9268fe48cd8c8fadfda --- Libraries/Core/Timers/JSTimers.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Libraries/Core/Timers/JSTimers.js b/Libraries/Core/Timers/JSTimers.js index 33f8a68d76b67f..f996f9c26d47da 100644 --- a/Libraries/Core/Timers/JSTimers.js +++ b/Libraries/Core/Timers/JSTimers.js @@ -379,7 +379,7 @@ const JSTimers = { callIdleCallbacks: function (frameTime: number) { if ( - FRAME_DURATION - (global.performance.now() - frameTime) < + FRAME_DURATION - (Date.now() - frameTime) < IDLE_CALLBACK_FRAME_DEADLINE ) { return; From 5e863fc42c8a2b27f4a785766eb643de9a243b2d Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Thu, 3 Nov 2022 06:55:39 -0700 Subject: [PATCH 125/169] Ship modern animated Summary: changelog: [general][Added] - Concurrent rendering safe implementation of Animated Reviewed By: yungsters Differential Revision: D40681265 fbshipit-source-id: b3979c69342ebd7f232f7a00f279ef0b082d4182 --- Libraries/Animated/NativeAnimatedHelper.js | 10 +- Libraries/Animated/__tests__/Animated-test.js | 14 +- .../createAnimatedComponentInjection-test.js | 68 ----- Libraries/Animated/createAnimatedComponent.js | 265 ++---------------- .../createAnimatedComponentInjection.js | 48 ---- .../createAnimatedComponent_EXPERIMENTAL.js | 48 ---- ...ogBoxInspectorSourceMapStatus-test.js.snap | 4 +- 7 files changed, 42 insertions(+), 415 deletions(-) delete mode 100644 Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js delete mode 100644 Libraries/Animated/createAnimatedComponentInjection.js delete mode 100644 Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js diff --git a/Libraries/Animated/NativeAnimatedHelper.js b/Libraries/Animated/NativeAnimatedHelper.js index e0c91788c4b830..1e0d9e57611556 100644 --- a/Libraries/Animated/NativeAnimatedHelper.js +++ b/Libraries/Animated/NativeAnimatedHelper.js @@ -142,7 +142,8 @@ const API = { } }, flushQueue: function (): void { - invariant(NativeAnimatedModule, 'Native animated module is not available'); + // TODO: (T136971132) + // invariant(NativeAnimatedModule, 'Native animated module is not available'); flushQueueTimeout = null; // Early returns before calling any APIs @@ -165,16 +166,17 @@ const API = { // use RCTDeviceEventEmitter. This reduces overhead of sending lots of // JSI functions across to native code; but also, TM infrastructure currently // does not support packing a function into native arrays. - NativeAnimatedModule.queueAndExecuteBatchedOperations?.(singleOpQueue); + NativeAnimatedModule?.queueAndExecuteBatchedOperations?.(singleOpQueue); singleOpQueue.length = 0; } else { - Platform.OS === 'android' && NativeAnimatedModule.startOperationBatch?.(); + Platform.OS === 'android' && + NativeAnimatedModule?.startOperationBatch?.(); for (let q = 0, l = queue.length; q < l; q++) { queue[q](); } queue.length = 0; Platform.OS === 'android' && - NativeAnimatedModule.finishOperationBatch?.(); + NativeAnimatedModule?.finishOperationBatch?.(); } }, queueOperation: , Fn: (...Args) => void>( diff --git a/Libraries/Animated/__tests__/Animated-test.js b/Libraries/Animated/__tests__/Animated-test.js index 698dee83e9994a..d02ffa8aad1f8d 100644 --- a/Libraries/Animated/__tests__/Animated-test.js +++ b/Libraries/Animated/__tests__/Animated-test.js @@ -9,10 +9,10 @@ */ import * as React from 'react'; -import TestRenderer from 'react-test-renderer'; let Animated = require('../Animated').default; let AnimatedProps = require('../nodes/AnimatedProps').default; +let TestRenderer = require('react-test-renderer'); jest.mock('../../BatchedBridge/NativeModules', () => ({ NativeAnimatedModule: {}, @@ -175,11 +175,13 @@ describe('Animated tests', () => { expect(testRenderer.toJSON().props.style.opacity).toEqual(0); - Animated.timing(opacity, { - toValue: 1, - duration: 0, - useNativeDriver: false, - }).start(); + TestRenderer.act(() => { + Animated.timing(opacity, { + toValue: 1, + duration: 0, + useNativeDriver: false, + }).start(); + }); expect(testRenderer.toJSON().props.style.opacity).toEqual(1); }); diff --git a/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js b/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js deleted file mode 100644 index 15936f7b675a3b..00000000000000 --- a/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - * @oncall react_native - */ - -'use strict'; - -import * as React from 'react'; - -const createAnimatedComponent = require('../createAnimatedComponent').default; -const createAnimatedComponentInjection = require('../createAnimatedComponentInjection'); - -function injected( - Component: React.AbstractComponent, -): React.AbstractComponent { - return createAnimatedComponent(Component); -} - -beforeEach(() => { - jest.resetModules(); - jest.resetAllMocks(); -}); - -test('does nothing without injection', () => { - expect(typeof createAnimatedComponent).toBe('function'); - expect(createAnimatedComponent).not.toBe(injected); -}); - -test('injection overrides `createAnimatedComponent`', () => { - createAnimatedComponentInjection.inject(injected); - - expect(createAnimatedComponent).toBe(injected); -}); - -test('injection errors if called too late', () => { - jest.spyOn(console, 'error').mockReturnValue(undefined); - - // Causes `createAnimatedComponent` to be initialized. - createAnimatedComponent; - - createAnimatedComponentInjection.inject(injected); - - expect(createAnimatedComponent).not.toBe(injected); - expect(console.error).toBeCalledWith( - 'createAnimatedComponentInjection: Must be called before `createAnimatedComponent`.', - ); -}); - -test('injection errors if called more than once', () => { - jest.spyOn(console, 'error').mockReturnValue(undefined); - - createAnimatedComponentInjection.inject(injected); - - expect(createAnimatedComponent).toBe(injected); - expect(console.error).not.toBeCalled(); - - createAnimatedComponentInjection.inject(injected); - - expect(console.error).toBeCalledWith( - 'createAnimatedComponentInjection: Cannot be called more than once.', - ); -}); diff --git a/Libraries/Animated/createAnimatedComponent.js b/Libraries/Animated/createAnimatedComponent.js index fb64ba05ffd375..09d749c8ca85e0 100644 --- a/Libraries/Animated/createAnimatedComponent.js +++ b/Libraries/Animated/createAnimatedComponent.js @@ -8,19 +8,11 @@ * @format */ -'use strict'; - import View from '../Components/View/View'; -import setAndForwardRef from '../Utilities/setAndForwardRef'; -import {AnimatedEvent} from './AnimatedEvent'; -import * as createAnimatedComponentInjection from './createAnimatedComponentInjection'; -import NativeAnimatedHelper from './NativeAnimatedHelper'; -import AnimatedProps from './nodes/AnimatedProps'; -import invariant from 'invariant'; +import useMergeRefs from '../Utilities/useMergeRefs'; +import useAnimatedProps from './useAnimatedProps'; import * as React from 'react'; -let animatedComponentNextId = 1; - export type AnimatedComponentType< -Props: {+[string]: mixed, ...}, +Instance = mixed, @@ -37,238 +29,33 @@ export type AnimatedComponentType< Instance, >; -function createAnimatedComponent( - Component: React.AbstractComponent, -): AnimatedComponentType { - invariant( - typeof Component !== 'function' || - (Component.prototype && Component.prototype.isReactComponent), - '`createAnimatedComponent` does not support stateless functional components; ' + - 'use a class component instead.', - ); - - class AnimatedComponent extends React.Component { - _component: any; // TODO T53738161: flow type this, and the whole file - _invokeAnimatedPropsCallbackOnMount: boolean = false; - _prevComponent: any; - _propsAnimated: AnimatedProps; - _eventDetachers: Array = []; - - // Only to be used in this file, and only in Fabric. - _animatedComponentId: string = `${animatedComponentNextId++}:animatedComponent`; - - _attachNativeEvents() { - // Make sure to get the scrollable node for components that implement - // `ScrollResponder.Mixin`. - const scrollableNode = this._component?.getScrollableNode - ? this._component.getScrollableNode() - : this._component; - - for (const key in this.props) { - const prop = this.props[key]; - if (prop instanceof AnimatedEvent && prop.__isNative) { - prop.__attach(scrollableNode, key); - this._eventDetachers.push(() => prop.__detach(scrollableNode, key)); - } - } - } - - _detachNativeEvents() { - this._eventDetachers.forEach(remove => remove()); - this._eventDetachers = []; - } - - _isFabric = (): boolean => { - // When called during the first render, `_component` is always null. - // Therefore, even if a component is rendered in Fabric, we can't detect - // that until ref is set, which happens sometime after the first render. - // In cases where this value switching between "false" and "true" on Fabric - // causes issues, add an additional check for _component nullity. - if (this._component == null) { - return false; - } - return ( - // eslint-disable-next-line dot-notation - this._component['_internalInstanceHandle']?.stateNode?.canonical != - null || - // Some components have a setNativeProps function but aren't a host component - // such as lists like FlatList and SectionList. These should also use - // forceUpdate in Fabric since setNativeProps doesn't exist on the underlying - // host component. This crazy hack is essentially special casing those lists and - // ScrollView itself to use forceUpdate in Fabric. - // If these components end up using forwardRef then these hacks can go away - // as this._component would actually be the underlying host component and the above check - // would be sufficient. - (this._component.getNativeScrollRef != null && - this._component.getNativeScrollRef() != null && - // eslint-disable-next-line dot-notation - this._component.getNativeScrollRef()['_internalInstanceHandle'] - ?.stateNode?.canonical != null) || - (this._component.getScrollResponder != null && - this._component.getScrollResponder() != null && - this._component.getScrollResponder().getNativeScrollRef != null && - this._component.getScrollResponder().getNativeScrollRef() != null && - this._component.getScrollResponder().getNativeScrollRef()[ - // eslint-disable-next-line dot-notation - '_internalInstanceHandle' - ]?.stateNode?.canonical != null) - ); - }; - - _waitForUpdate = (): void => { - if (this._isFabric()) { - NativeAnimatedHelper.API.setWaitingForIdentifier( - this._animatedComponentId, - ); - } - }; - - _markUpdateComplete = (): void => { - if (this._isFabric()) { - NativeAnimatedHelper.API.unsetWaitingForIdentifier( - this._animatedComponentId, - ); - } - }; - - // The system is best designed when setNativeProps is implemented. It is - // able to avoid re-rendering and directly set the attributes that changed. - // However, setNativeProps can only be implemented on leaf native - // components. If you want to animate a composite component, you need to - // re-render it. In this case, we have a fallback that uses forceUpdate. - // This fallback is also called in Fabric. - _animatedPropsCallback = (): void => { - if (this._component == null) { - // AnimatedProps is created in will-mount because it's used in render. - // But this callback may be invoked before mount in async mode, - // In which case we should defer the setNativeProps() call. - // React may throw away uncommitted work in async mode, - // So a deferred call won't always be invoked. - this._invokeAnimatedPropsCallbackOnMount = true; - } else if ( - process.env.NODE_ENV === 'test' || - // For animating properties of non-leaf/non-native components - typeof this._component.setNativeProps !== 'function' || - // In Fabric, force animations to go through forceUpdate and skip setNativeProps - this._isFabric() - ) { - this.forceUpdate(); - } else if (!this._propsAnimated.__isNative) { - this._component.setNativeProps( - this._propsAnimated.__getAnimatedValue(), - ); - } else { - throw new Error( - 'Attempting to run JS driven animation on animated ' + - 'node that has been moved to "native" earlier by starting an ' + - 'animation with `useNativeDriver: true`', - ); - } - }; - - _attachProps(nextProps: any) { - const oldPropsAnimated = this._propsAnimated; - - this._propsAnimated = new AnimatedProps( - nextProps, - this._animatedPropsCallback, - ); - this._propsAnimated.__attach(); - - // When you call detach, it removes the element from the parent list - // of children. If it goes to 0, then the parent also detaches itself - // and so on. - // An optimization is to attach the new elements and THEN detach the old - // ones instead of detaching and THEN attaching. - // This way the intermediate state isn't to go to 0 and trigger - // this expensive recursive detaching to then re-attach everything on - // the very next operation. - if (oldPropsAnimated) { - oldPropsAnimated.__restoreDefaultValues(); - oldPropsAnimated.__detach(); - } - } - - _setComponentRef: (ref: React.ElementRef) => void = setAndForwardRef({ - getForwardedRef: () => this.props.forwardedRef, - setLocalRef: ref => { - this._prevComponent = this._component; - this._component = ref; - }, - }); - - render(): React.Node { - const animatedProps = this._propsAnimated.__getValue() || {}; - - const {style = {}, ...props} = animatedProps; - const {style: passthruStyle = {}, ...passthruProps} = - this.props.passthroughAnimatedPropExplicitValues || {}; - const mergedStyle = {...style, ...passthruStyle}; - - // Force `collapsable` to be false so that native view is not flattened. - // Flattened views cannot be accurately referenced by a native driver. - return ( - - ); - } - - UNSAFE_componentWillMount() { - this._waitForUpdate(); - this._attachProps(this.props); - } - - componentDidMount() { - if (this._invokeAnimatedPropsCallbackOnMount) { - this._invokeAnimatedPropsCallbackOnMount = false; - this._animatedPropsCallback(); - } - - this._propsAnimated.setNativeView(this._component); - this._attachNativeEvents(); - this._markUpdateComplete(); - } - - UNSAFE_componentWillReceiveProps(newProps: any) { - this._waitForUpdate(); - this._attachProps(newProps); - } - - componentDidUpdate(prevProps: any) { - if (this._component !== this._prevComponent) { - this._propsAnimated.setNativeView(this._component); - } - if (this._component !== this._prevComponent || prevProps !== this.props) { - this._detachNativeEvents(); - this._attachNativeEvents(); - } - this._markUpdateComplete(); - } - - componentWillUnmount() { - this._propsAnimated && this._propsAnimated.__detach(); - this._detachNativeEvents(); - this._markUpdateComplete(); - this._component = null; - this._prevComponent = null; - } - } +export default function createAnimatedComponent( + Component: React.AbstractComponent, +): AnimatedComponentType { + return React.forwardRef((props, forwardedRef) => { + const [reducedProps, callbackRef] = useAnimatedProps( + // $FlowFixMe[incompatible-call] + props, + ); + const ref = useMergeRefs(callbackRef, forwardedRef); + + // Some components require explicit passthrough values for animation + // to work properly. For example, if an animated component is + // transformed and Pressable, onPress will not work after transform + // without these passthrough values. + // $FlowFixMe[prop-missing] + const {passthroughAnimatedPropExplicitValues, style} = reducedProps; + const {style: passthroughStyle, ...passthroughProps} = + passthroughAnimatedPropExplicitValues ?? {}; + const mergedStyle = {...style, ...passthroughStyle}; - return React.forwardRef(function AnimatedComponentWrapper(props, ref) { return ( - ); }); } - -// $FlowIgnore[incompatible-cast] - Will be compatible after refactors. -export default (createAnimatedComponentInjection.recordAndRetrieve() ?? - createAnimatedComponent: typeof createAnimatedComponent); diff --git a/Libraries/Animated/createAnimatedComponentInjection.js b/Libraries/Animated/createAnimatedComponentInjection.js deleted file mode 100644 index ab172bf12ca21d..00000000000000 --- a/Libraries/Animated/createAnimatedComponentInjection.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import * as React from 'react'; - -type createAnimatedComponent = ( - Component: React.AbstractComponent, -) => React.AbstractComponent; - -// This can be undefined, null, or the experimental implementation. If this is -// null, that means `createAnimatedComponent` has already been initialized and -// it is too late to call `inject`. -let injected: ?createAnimatedComponent; - -/** - * Call during bundle initialization to opt-in to new `createAnimatedComponent`. - */ -export function inject(newInjected: createAnimatedComponent): void { - if (injected !== undefined) { - if (__DEV__) { - console.error( - 'createAnimatedComponentInjection: ' + - (injected == null - ? 'Must be called before `createAnimatedComponent`.' - : 'Cannot be called more than once.'), - ); - } - return; - } - injected = newInjected; -} - -/** - * Only called by `createAnimatedComponent.js`. - */ -export function recordAndRetrieve(): createAnimatedComponent | null { - if (injected === undefined) { - injected = null; - } - return injected; -} diff --git a/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js b/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js deleted file mode 100644 index eb7c78cecc815c..00000000000000 --- a/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict-local - * @format - */ - -import StyleSheet from '../StyleSheet/StyleSheet'; -import useMergeRefs from '../Utilities/useMergeRefs'; -import useAnimatedProps from './useAnimatedProps'; -import * as React from 'react'; - -/** - * Experimental implementation of `createAnimatedComponent` that is intended to - * be compatible with concurrent rendering. - */ -export default function createAnimatedComponent( - Component: React.AbstractComponent, -): React.AbstractComponent { - return React.forwardRef((props, forwardedRef) => { - const [reducedProps, callbackRef] = useAnimatedProps( - props, - ); - const ref = useMergeRefs(callbackRef, forwardedRef); - - // Some components require explicit passthrough values for animation - // to work properly. For example, if an animated component is - // transformed and Pressable, onPress will not work after transform - // without these passthrough values. - // $FlowFixMe[prop-missing] - const {passthroughAnimatedPropExplicitValues, style} = reducedProps; - const {style: passthroughStyle, ...passthroughProps} = - passthroughAnimatedPropExplicitValues ?? {}; - const mergedStyle = StyleSheet.compose(style, passthroughStyle); - - return ( - - ); - }); -} diff --git a/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap b/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap index a2c2cd03b6a442..d814a90fe50c96 100644 --- a/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap +++ b/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap @@ -27,7 +27,7 @@ exports[`LogBoxInspectorSourceMapStatus should render for failed 1`] = ` } } > - - Date: Thu, 3 Nov 2022 07:14:41 -0700 Subject: [PATCH 126/169] Exclude PerformanceObserver from flow/haste Summary: [Changelog][Internal] This is to prevent an accidental use of PerformanceObserver while it's still a work in progress. PerformanceObserver is also moved into a dedicated folder, `Libraries/WebPerformance`. Reviewed By: rubennorte Differential Revision: D40978749 fbshipit-source-id: 09645a95bed72902870ebc00c1b4a3d81ab4c829 --- Libraries/{Performance => WebPerformance}/PerformanceObserver.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Libraries/{Performance => WebPerformance}/PerformanceObserver.js (100%) diff --git a/Libraries/Performance/PerformanceObserver.js b/Libraries/WebPerformance/PerformanceObserver.js similarity index 100% rename from Libraries/Performance/PerformanceObserver.js rename to Libraries/WebPerformance/PerformanceObserver.js From c63133202b015adc6cd94e77069586a619aca4a8 Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 3 Nov 2022 07:32:16 -0700 Subject: [PATCH 127/169] Correctly set -DCMAKE_BUILD_TYPE for Hermes on iOS Summary: We accidentally added `-DCMAKE_BUILD_TYPE=Debug` for Hermes which is causing a really slow engine execution. This fixes it and keep the -DCMAKE_BUILD_TYPE aligned with the one used on Android. Changelog: [iOS] [Fixed] - Correctly set -DCMAKE_BUILD_TYPE for Hermes on iOS Reviewed By: hramos, cipolleschi Differential Revision: D40980934 fbshipit-source-id: 30f0455990a911b51eb109bebca8272507302650 --- sdks/hermes-engine/utils/build-apple-framework.sh | 11 +++++++++-- sdks/hermes-engine/utils/build-hermes-xcode.sh | 11 ++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/sdks/hermes-engine/utils/build-apple-framework.sh b/sdks/hermes-engine/utils/build-apple-framework.sh index 9f391a53fa4287..87faae6cb69942 100755 --- a/sdks/hermes-engine/utils/build-apple-framework.sh +++ b/sdks/hermes-engine/utils/build-apple-framework.sh @@ -52,7 +52,7 @@ function build_host_hermesc { # Utility function to configure an Apple framework function configure_apple_framework { - local build_cli_tools enable_bitcode enable_debugger + local build_cli_tools enable_bitcode enable_debugger cmake_build_type if [[ $1 == iphoneos || $1 == catalyst ]]; then enable_bitcode="true" @@ -69,6 +69,13 @@ function configure_apple_framework { else enable_debugger="false" fi + if [[ $BUILD_TYPE == "Debug" ]]; then + # JS developers aren't VM developers. + # Therefore we're passing as build type Release, to provide a faster build. + cmake_build_type="Release" + else + cmake_build_type="MinSizeRel" + fi pushd "$HERMES_PATH" > /dev/null || exit 1 cmake -S . -B "build_$1" \ @@ -88,7 +95,7 @@ function configure_apple_framework { -DJSI_DIR="$JSI_PATH" \ -DHERMES_RELEASE_VERSION="for RN $(get_release_version)" \ -DCMAKE_INSTALL_PREFIX:PATH=../destroot \ - -DCMAKE_BUILD_TYPE="$BUILD_TYPE" + -DCMAKE_BUILD_TYPE="$cmake_build_type" popd > /dev/null || exit 1 } diff --git a/sdks/hermes-engine/utils/build-hermes-xcode.sh b/sdks/hermes-engine/utils/build-hermes-xcode.sh index 0ef2da262461f2..37faee32506029 100755 --- a/sdks/hermes-engine/utils/build-hermes-xcode.sh +++ b/sdks/hermes-engine/utils/build-hermes-xcode.sh @@ -19,6 +19,15 @@ if [[ "$CONFIGURATION" == "Debug" ]]; then enable_debugger="true" fi +cmake_build_type="" +if [[ $CONFIGURATION == "Debug" ]]; then + # JS developers aren't VM developers. + # Therefore we're passing as build type Release, to provide a faster build. + cmake_build_type="Release" +else + cmake_build_type="MinSizeRel" +fi + deployment_target=${IPHONEOS_DEPLOYMENT_TARGET} if [ -z "$deployment_target" ]; then deployment_target=${MACOSX_DEPLOYMENT_TARGET} @@ -46,7 +55,7 @@ echo "Configure Apple framework" -DIMPORT_HERMESC:PATH="${hermesc_path}" \ -DHERMES_RELEASE_VERSION="for RN $release_version" \ -DCMAKE_INSTALL_PREFIX:PATH="${PODS_ROOT}/hermes-engine/destroot" \ - -DCMAKE_BUILD_TYPE="$CONFIGURATION" + -DCMAKE_BUILD_TYPE="$cmake_build_type" echo "Build Apple framework" From bbd432e9994eb3b3114d429913bb8ce1a4f6e877 Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Thu, 3 Nov 2022 08:52:34 -0700 Subject: [PATCH 128/169] feat: make RCTBlobManager TurboModule-compatible (#35188) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35188 This diff reverts D40716048 (https://github.com/facebook/react-native/commit/279cfec55fdf404fdb9198edbb37d3adfdfb3bf1) (https://github.com/facebook/react-native/pull/35047) which breaks RCTImageLoader. https://pxl.cl/2jKrM Those files are auto-generated and are not supposed to be edited manually. Changelog: [iOS] [Fixed] - https://github.com/facebook/react-native/pull/35047 reverted. Reviewed By: cipolleschi Differential Revision: D40979350 fbshipit-source-id: ef92cf05636cba818151d4184e0275a3aab56cff --- React/CoreModules/CoreModulesPlugins.h | 1 - React/CoreModules/CoreModulesPlugins.mm | 1 - 2 files changed, 2 deletions(-) diff --git a/React/CoreModules/CoreModulesPlugins.h b/React/CoreModules/CoreModulesPlugins.h index e2a02a4e335bdf..564988958a046e 100644 --- a/React/CoreModules/CoreModulesPlugins.h +++ b/React/CoreModules/CoreModulesPlugins.h @@ -53,7 +53,6 @@ Class RCTWebSocketModuleCls(void) __attribute__((used)); Class RCTDevLoadingViewCls(void) __attribute__((used)); Class RCTDevSplitBundleLoaderCls(void) __attribute__((used)); Class RCTEventDispatcherCls(void) __attribute__((used)); -Class RCTBlobManagerCls(void) __attribute__((used)); #ifdef __cplusplus } diff --git a/React/CoreModules/CoreModulesPlugins.mm b/React/CoreModules/CoreModulesPlugins.mm index 85187305e90cc0..7e54e5a0909325 100644 --- a/React/CoreModules/CoreModulesPlugins.mm +++ b/React/CoreModules/CoreModulesPlugins.mm @@ -36,7 +36,6 @@ Class RCTCoreModulesClassProvider(const char *name) { {"PerfMonitor", RCTPerfMonitorCls}, {"DevMenu", RCTDevMenuCls}, {"DevSettings", RCTDevSettingsCls}, - {"BlobModule", RCTBlobManagerCls}, {"RedBox", RCTRedBoxCls}, {"LogBox", RCTLogBoxCls}, {"WebSocketExecutor", RCTWebSocketExecutorCls}, From f32a3a53726cdc3dc243d597283b4a6997b84bf6 Mon Sep 17 00:00:00 2001 From: Ruslan Shestopalyuk Date: Thu, 3 Nov 2022 09:07:14 -0700 Subject: [PATCH 129/169] Refactor PerformanceObserver public API Summary: Changelog: [Internal] This is a follow-up to D40892974 (https://github.com/facebook/react-native/commit/a671d61b6de5f106e9fd803a73fddb4b6fa6656b), addressing the post-land comments and discussions. Reviewed By: rubennorte Differential Revision: D40979654 fbshipit-source-id: 2e7e1d24be8211cc3363a07678745039e5606d8d --- .../WebPerformance/PerformanceObserver.js | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/Libraries/WebPerformance/PerformanceObserver.js b/Libraries/WebPerformance/PerformanceObserver.js index 8974b1da6c8189..80857cac24097a 100644 --- a/Libraries/WebPerformance/PerformanceObserver.js +++ b/Libraries/WebPerformance/PerformanceObserver.js @@ -8,22 +8,16 @@ * @flow strict */ -'use strict'; - -export type Timestamp = number; -export type PerformanceEntryType = 'event'; +export type HighResTimeStamp = number; +// TODO: Extend once new types (such as event) are supported +export type PerformanceEntryType = empty; export class PerformanceEntry { name: string; entryType: PerformanceEntryType; - startTime: Timestamp; + startTime: HighResTimeStamp; duration: number; - // For "event" entries only: - processingStart: ?Timestamp; - processingEnd: ?Timestamp; - interactionId: ?number; - // $FlowIgnore: Flow(unclear-type) toJSON(): Object { return { @@ -73,12 +67,10 @@ export type PerformanceObserverCallback = ( export type PerformanceObserverInit = | { - entryTypes: PerformanceEntryType[], - buffered?: boolean, + entryTypes: Array, } | { type: PerformanceEntryType, - buffered?: boolean, }; /** @@ -120,5 +112,7 @@ export default class PerformanceObserver { return []; } - static supportedEntryTypes: PerformanceEntryType[] = ['event']; + static supportedEntryTypes: $ReadOnlyArray = + // TODO: add types once they are fully supported + Object.freeze([]); } From e81c98c842380d8b72c1dc8d4a6e64f760e2a58c Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Thu, 3 Nov 2022 11:20:16 -0700 Subject: [PATCH 130/169] Fix Cpp codegen handling of optional arguments Summary: Changelog: [General][Fixed] - Codegen for C++ TurboModules of optional method arguments was incorrect Reviewed By: christophpurrer Differential Revision: D40979066 fbshipit-source-id: 5bb48dbafc14dcea21b7e0b15e3f4bb527bc8476 --- .../generators/modules/GenerateModuleCpp.js | 16 ++++++++++------ .../src/generators/modules/GenerateModuleH.js | 6 +++++- .../modules/__test_fixtures__/fixtures.js | 19 +++++++++++++++++++ .../GenerateModuleCpp-test.js.snap | 6 +++++- .../GenerateModuleH-test.js.snap | 13 +++++++++++-- .../GenerateModuleHObjCpp-test.js.snap | 3 +++ .../GenerateModuleJavaSpec-test.js.snap | 4 ++++ .../GenerateModuleJniCpp-test.js.snap | 6 ++++++ .../GenerateModuleMm-test.js.snap | 7 +++++++ 9 files changed, 70 insertions(+), 10 deletions(-) diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js index 1846ebc682677a..159c05f1300689 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js @@ -118,9 +118,10 @@ function serializeArg( index: number, resolveAlias: AliasResolver, ): string { - const {typeAnnotation: nullableTypeAnnotation} = arg; + const {typeAnnotation: nullableTypeAnnotation, optional} = arg; const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation); + const isRequired = !optional && !nullable; let realTypeAnnotation = typeAnnotation; if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { @@ -130,12 +131,15 @@ function serializeArg( function wrap(callback: (val: string) => string) { const val = `args[${index}]`; const expression = callback(val); - - if (nullable) { - return `${val}.isNull() || ${val}.isUndefined() ? std::nullopt : std::make_optional(${expression})`; + if (isRequired) { + return expression; + } else { + let condition = `${val}.isNull() || ${val}.isUndefined()`; + if (optional) { + condition = `count < ${index} || ${condition}`; + } + return `${condition} ? std::nullopt : std::make_optional(${expression})`; } - - return expression; } switch (realTypeAnnotation.type) { diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js index dad386c4c9e7a9..865f60b63f30c9 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleH.js @@ -107,12 +107,14 @@ ${modules.join('\n\n')} function translatePrimitiveJSTypeToCpp( nullableTypeAnnotation: Nullable, + optional: boolean, createErrorMessage: (typeName: string) => string, resolveAlias: AliasResolver, ) { const [typeAnnotation, nullable] = unwrapNullable( nullableTypeAnnotation, ); + const isRequired = !optional && !nullable; let realTypeAnnotation = typeAnnotation; if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { @@ -120,7 +122,7 @@ function translatePrimitiveJSTypeToCpp( } function wrap(type: string) { - return nullable ? `std::optional<${type}>` : type; + return isRequired ? type : `std::optional<${type}>`; } switch (realTypeAnnotation.type) { @@ -199,6 +201,7 @@ function translatePropertyToCpp( const paramTypes = propTypeAnnotation.params.map(param => { const translatedParam = translatePrimitiveJSTypeToCpp( param.typeAnnotation, + param.optional, typeName => `Unsupported type for param "${param.name}" in ${prop.name}. Found: ${typeName}`, resolveAlias, @@ -208,6 +211,7 @@ function translatePropertyToCpp( const returnType = translatePrimitiveJSTypeToCpp( propTypeAnnotation.returnTypeAnnotation, + false, typeName => `Unsupported return type for ${prop.name}. Found: ${typeName}`, resolveAlias, ); diff --git a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js index 991d76f2dd7456..f3b88e526ba1df 100644 --- a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js @@ -275,6 +275,25 @@ const SIMPLE_NATIVE_MODULES: SchemaType = { ], }, }, + { + name: 'getValueWithOptionalArg', + optional: false, + typeAnnotation: { + type: 'FunctionTypeAnnotation', + returnTypeAnnotation: { + type: 'PromiseTypeAnnotation', + }, + params: [ + { + optional: true, + name: 'parameter', + typeAnnotation: { + type: 'GenericObjectTypeAnnotation', + }, + }, + ], + }, + }, { name: 'getEnums', optional: false, diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap index 7446e0559ce36e..01d83b6869d405 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap @@ -54,7 +54,7 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionals(jsi return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_optionalMethod(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->optionalMethod(rt, args[0].asObject(rt), args[1].asObject(rt).asFunction(rt), args[2].asObject(rt).asArray(rt)); + static_cast(&turboModule)->optionalMethod(rt, args[0].asObject(rt), args[1].asObject(rt).asFunction(rt), count < 2 || args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asObject(rt).asArray(rt))); return jsi::Value::undefined(); } static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getArrays(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { @@ -337,6 +337,9 @@ static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithC static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getValueWithPromise(rt, args[0].asBool()); } +static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithOptionalArg(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { + return static_cast(&turboModule)->getValueWithOptionalArg(rt, count < 0 || args[0].isNull() || args[0].isUndefined() ? std::nullopt : std::make_optional(args[0].asObject(rt))); +} static jsi::Value __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { return static_cast(&turboModule)->getEnums(rt, args[0].asNumber(), args[1].asNumber(), args[2].asString(rt)); } @@ -354,6 +357,7 @@ NativeSampleTurboModuleCxxSpecJSI::NativeSampleTurboModuleCxxSpecJSI(std::shared methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValue}; methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithCallback}; methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithPromise}; + methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getValueWithOptionalArg}; methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleCxxSpecJSI_getEnums}; } diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap index 63d09d5948b265..f8349c6811bf25 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap @@ -87,7 +87,7 @@ protected: public: virtual jsi::Object difficult(jsi::Runtime &rt, jsi::Object A) = 0; virtual void optionals(jsi::Runtime &rt, jsi::Object A) = 0; - virtual void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, jsi::Array extras) = 0; + virtual void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, std::optional extras) = 0; virtual void getArrays(jsi::Runtime &rt, jsi::Object options) = 0; virtual std::optional getNullableObject(jsi::Runtime &rt) = 0; virtual std::optional getNullableGenericObject(jsi::Runtime &rt) = 0; @@ -129,7 +129,7 @@ private: return bridging::callFromJs( rt, &T::optionals, jsInvoker_, instance_, std::move(A)); } - void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, jsi::Array extras) override { + void optionalMethod(jsi::Runtime &rt, jsi::Object options, jsi::Function callback, std::optional extras) override { static_assert( bridging::getParameterCount(&T::optionalMethod) == 4, \\"Expected optionalMethod(...) to have 4 parameters\\"); @@ -668,6 +668,7 @@ public: virtual jsi::Object getValue(jsi::Runtime &rt, double x, jsi::String y, jsi::Object z) = 0; virtual void getValueWithCallback(jsi::Runtime &rt, jsi::Function callback) = 0; virtual jsi::Value getValueWithPromise(jsi::Runtime &rt, bool error) = 0; + virtual jsi::Value getValueWithOptionalArg(jsi::Runtime &rt, std::optional parameter) = 0; virtual jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) = 0; }; @@ -778,6 +779,14 @@ private: return bridging::callFromJs( rt, &T::getValueWithPromise, jsInvoker_, instance_, std::move(error)); } + jsi::Value getValueWithOptionalArg(jsi::Runtime &rt, std::optional parameter) override { + static_assert( + bridging::getParameterCount(&T::getValueWithOptionalArg) == 2, + \\"Expected getValueWithOptionalArg(...) to have 2 parameters\\"); + + return bridging::callFromJs( + rt, &T::getValueWithOptionalArg, jsInvoker_, instance_, std::move(parameter)); + } jsi::String getEnums(jsi::Runtime &rt, double enumInt, double enumFloat, jsi::String enumString) override { static_assert( bridging::getParameterCount(&T::getEnums) == 4, diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap index 119fb989e7a102..6c6afb74db32ca 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap @@ -933,6 +933,9 @@ namespace JS { - (void)getValueWithPromise:(BOOL)error resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject; +- (void)getValueWithOptionalArg:(NSDictionary *)parameter + resolve:(RCTPromiseResolveBlock)resolve + reject:(RCTPromiseRejectBlock)reject; - (NSString *)getEnums:(double)enumInt enumFloat:(double)enumFloat enumString:(NSString *)enumString; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap index 4d41e02ccd04f8..473878ebefa929 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap @@ -377,6 +377,10 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo @DoNotStrip public abstract void getValueWithPromise(boolean error, Promise promise); + @ReactMethod + @DoNotStrip + public abstract void getValueWithOptionalArg(ReadableMap parameter, Promise promise); + @ReactMethod(isBlockingSynchronousMethod = true) @DoNotStrip public abstract String getEnums(double enumInt, double enumFloat, String enumString); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap index 3fdf54878310b0..bb1428ed7ae0cd 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJniCpp-test.js.snap @@ -384,6 +384,11 @@ static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getVal return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getValueWithPromise\\", \\"(ZLcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); } +static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + static jmethodID cachedMethodId = nullptr; + return static_cast(turboModule).invokeJavaMethod(rt, PromiseKind, \\"getValueWithOptionalArg\\", \\"(Lcom/facebook/react/bridge/ReadableMap;Lcom/facebook/react/bridge/Promise;)V\\", args, count, cachedMethodId); +} + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { static jmethodID cachedMethodId = nullptr; return static_cast(turboModule).invokeJavaMethod(rt, StringKind, \\"getEnums\\", \\"(DDLjava/lang/String;)Ljava/lang/String;\\", args, count, cachedMethodId); @@ -402,6 +407,7 @@ NativeSampleTurboModuleSpecJSI::NativeSampleTurboModuleSpecJSI(const JavaTurboMo methodMap_[\\"getValue\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getValue}; methodMap_[\\"getValueWithCallback\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithCallback}; methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; + methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg}; methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; } diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap index d4b708e3d9023d..7630f24132a3d3 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap @@ -453,6 +453,10 @@ namespace facebook { return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithPromise\\", @selector(getValueWithPromise:resolve:reject:), args, count); } + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { + return static_cast(turboModule).invokeObjCMethod(rt, PromiseKind, \\"getValueWithOptionalArg\\", @selector(getValueWithOptionalArg:resolve:reject:), args, count); + } + static facebook::jsi::Value __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { return static_cast(turboModule).invokeObjCMethod(rt, StringKind, \\"getEnums\\", @selector(getEnums:enumFloat:enumString:), args, count); } @@ -494,6 +498,9 @@ namespace facebook { methodMap_[\\"getValueWithPromise\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithPromise}; + methodMap_[\\"getValueWithOptionalArg\\"] = MethodMetadata {1, __hostFunction_NativeSampleTurboModuleSpecJSI_getValueWithOptionalArg}; + + methodMap_[\\"getEnums\\"] = MethodMetadata {3, __hostFunction_NativeSampleTurboModuleSpecJSI_getEnums}; From e73b615f14cade70c4693aa6e0a85e84cd544293 Mon Sep 17 00:00:00 2001 From: Pranav Yadav Date: Thu, 3 Nov 2022 16:23:45 -0700 Subject: [PATCH 131/169] fix lint warn -> rm unused import `rm` (#35186) Summary: - Fixed lint warning -> rm unused import `rm` in `scripts/run-ci-e2e-tests.js` file - Hence, removed unused import `rm` in `scripts/run-ci-e2e-tests.js` file ## Changelog [GENERAL] [FIXED] - Fixed lint warning -> rm unused import `rm` in `scripts/run-ci-e2e-tests.js` file Pull Request resolved: https://github.com/facebook/react-native/pull/35186 Test Plan: `yarn test-ci` ![image](https://user-images.githubusercontent.com/55224033/199700838-c8a6d2d6-0634-4e0a-b50d-5ca89957cf38.png) Reviewed By: sshic Differential Revision: D40978104 Pulled By: NickGerleman fbshipit-source-id: 5a99cd33d25015325133aee1442980b218104e86 --- scripts/run-ci-e2e-tests.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/run-ci-e2e-tests.js b/scripts/run-ci-e2e-tests.js index cdff750f3192b9..71cdff980a3020 100644 --- a/scripts/run-ci-e2e-tests.js +++ b/scripts/run-ci-e2e-tests.js @@ -19,7 +19,7 @@ * --retries [num] - how many times to retry possible flaky commands: yarn add and running tests, default 1 */ -const {cd, cp, echo, exec, exit, mv, rm} = require('shelljs'); +const {cd, cp, echo, exec, exit, mv} = require('shelljs'); const spawn = require('child_process').spawn; const argv = require('yargs').argv; const path = require('path'); From 8183aac0b1f55db8fd5d45d4fc6a8e596e3db32b Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Thu, 3 Nov 2022 17:28:26 -0700 Subject: [PATCH 132/169] Bump dependency versions before the branch cut 0.71.0 Summary: Changelog: [General][Changed] - Bump dependency versions. Reviewed By: cipolleschi Differential Revision: D40991336 fbshipit-source-id: 71c8edbeb274d095403b2f17e60f217d16fe01c0 --- package.json | 2 +- packages/babel-plugin-codegen/package.json | 2 +- packages/eslint-config-react-native-community/package.json | 2 +- packages/eslint-plugin-react-native-community/package.json | 2 +- packages/eslint-plugin-specs/package.json | 2 +- packages/hermes-inspector-msggen/package.json | 2 +- packages/normalize-color/package.json | 2 +- packages/react-native-codegen/package.json | 2 +- repo-config/package.json | 4 ++-- 9 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 4261b905d07838..f9f12e5974df4a 100644 --- a/package.json +++ b/package.json @@ -113,7 +113,7 @@ "@react-native-community/cli-platform-android": "10.0.0-alpha.2", "@react-native-community/cli-platform-ios": "10.0.0-alpha.1", "@react-native/assets": "1.0.0", - "@react-native/normalize-color": "2.0.0", + "@react-native/normalize-color": "2.1.0", "@react-native/polyfills": "2.0.0", "abort-controller": "^3.0.0", "anser": "^1.4.9", diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json index 24a348986519b7..9a06f6cfa73a25 100644 --- a/packages/babel-plugin-codegen/package.json +++ b/packages/babel-plugin-codegen/package.json @@ -1,5 +1,5 @@ { - "version": "0.71.0", + "version": "0.71.1", "name": "@react-native/babel-plugin-codegen", "description": "Babel plugin to generate native module and view manager code for React Native.", "repository": { diff --git a/packages/eslint-config-react-native-community/package.json b/packages/eslint-config-react-native-community/package.json index cee4162fce3fbe..c9d777b7bd3ff0 100644 --- a/packages/eslint-config-react-native-community/package.json +++ b/packages/eslint-config-react-native-community/package.json @@ -1,6 +1,6 @@ { "name": "@react-native-community/eslint-config", - "version": "3.1.0", + "version": "3.2.0", "description": "ESLint config for React Native", "main": "index.js", "license": "MIT", diff --git a/packages/eslint-plugin-react-native-community/package.json b/packages/eslint-plugin-react-native-community/package.json index 29c7ddaa610262..f50afbdad52de6 100644 --- a/packages/eslint-plugin-react-native-community/package.json +++ b/packages/eslint-plugin-react-native-community/package.json @@ -1,6 +1,6 @@ { "name": "@react-native-community/eslint-plugin", - "version": "1.2.0", + "version": "1.3.0", "description": "ESLint rules for @react-native-community/eslint-config", "main": "index.js", "repository": { diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json index ced1c1d18ad767..2956a52d482ac7 100644 --- a/packages/eslint-plugin-specs/package.json +++ b/packages/eslint-plugin-specs/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/eslint-plugin-specs", - "version": "0.71.0", + "version": "0.71.1", "description": "ESLint rules to validate NativeModule and Component Specs", "main": "index.js", "repository": { diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index 68b2d0f949ce02..add61d46ca79eb 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -1,7 +1,7 @@ { "name": "@react-native/hermes-inspector-msggen", "private": true, - "version": "0.71.0", + "version": "0.71.1", "license": "MIT", "bin": { "msggen": "./bin/index.js" diff --git a/packages/normalize-color/package.json b/packages/normalize-color/package.json index 7ecb89c6b89cbe..27fe68afd5cbfe 100644 --- a/packages/normalize-color/package.json +++ b/packages/normalize-color/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/normalize-color", - "version": "2.0.0", + "version": "2.1.0", "description": "Color normalization for React Native.", "repository": { "type": "git", diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index db3efc860b3343..7e268a7bcc959e 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -1,6 +1,6 @@ { "name": "react-native-codegen", - "version": "0.71.1", + "version": "0.71.2", "description": "⚛️ Code generation tools for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen", "repository": { diff --git a/repo-config/package.json b/repo-config/package.json index 07dc70ae12cf11..00eef94f108ff5 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -15,7 +15,7 @@ "@babel/plugin-transform-regenerator": "^7.0.0", "@definitelytyped/dtslint": "^0.0.127", "@react-native-community/eslint-plugin": "*", - "@react-native/eslint-plugin-specs": "^0.71.0", + "@react-native/eslint-plugin-specs": "^0.71.1", "@reactions/component": "^2.0.2", "@types/react": "^18.0.18", "@typescript-eslint/parser": "^5.30.5", @@ -46,7 +46,7 @@ "mkdirp": "^0.5.1", "prettier": "^2.4.1", "react": "18.2.0", - "react-native-codegen": "^0.71.1", + "react-native-codegen": "^0.71.2", "react-test-renderer": "18.2.0", "shelljs": "^0.8.5", "signedsource": "^1.0.0", From ef75de97b5fc24719d9ccb4e3244cf55191cf79b Mon Sep 17 00:00:00 2001 From: Nicola Corti Date: Thu, 3 Nov 2022 20:22:23 -0700 Subject: [PATCH 133/169] Remove project.android block from rn-tester's CLI config (#35197) Summary: The project.android block is unnecessary and contains a wrong path. Let's use the default path which is `./android`. ## Changelog [Internal] - Remove project.android block from rn-tester's CLI config Pull Request resolved: https://github.com/facebook/react-native/pull/35197 Test Plan: Tested locally + will wait for a CI run Reviewed By: robhogan Differential Revision: D41013193 Pulled By: cortinico fbshipit-source-id: 5c76c9b571b23ad71a23a8f3f05a9acb4d6e20b9 --- packages/rn-tester/react-native.config.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/rn-tester/react-native.config.js b/packages/rn-tester/react-native.config.js index df48de8b0958b2..9e9896b9a35bb2 100644 --- a/packages/rn-tester/react-native.config.js +++ b/packages/rn-tester/react-native.config.js @@ -29,8 +29,5 @@ module.exports = { ios: { sourceDir: '.', }, - android: { - sourceDir: '.', - }, }, }; From 7211366c48f50cd3c47fb55aa2cf7ecac5a86d11 Mon Sep 17 00:00:00 2001 From: Mike Vitousek Date: Thu, 3 Nov 2022 21:40:00 -0700 Subject: [PATCH 134/169] Pre-suppress errors in xplat ahead of the v0.192 release Summary: Adds needed suppressions ahead of the release of Flow 0.192 drop-conflicts Changelog: [internal] Reviewed By: SamChou19815 Differential Revision: D41011869 fbshipit-source-id: 3922eb4463006da5b0bec803051136e8351f68fa --- Libraries/BatchedBridge/MessageQueue.js | 1 + Libraries/Inspector/ElementBox.js | 2 ++ Libraries/Lists/VirtualizedSectionList.js | 1 + packages/rn-tester/js/utils/RNTesterList.ios.js | 1 + 4 files changed, 5 insertions(+) diff --git a/Libraries/BatchedBridge/MessageQueue.js b/Libraries/BatchedBridge/MessageQueue.js index a9810bc6f94204..24e00b0a029fe1 100644 --- a/Libraries/BatchedBridge/MessageQueue.js +++ b/Libraries/BatchedBridge/MessageQueue.js @@ -381,6 +381,7 @@ class MessageQueue { return ( // $FlowFixMe[cannot-resolve-name] typeof DebuggerInternal !== 'undefined' && + // $FlowFixMe[cannot-resolve-name] DebuggerInternal.shouldPauseOnThrow === true ); } diff --git a/Libraries/Inspector/ElementBox.js b/Libraries/Inspector/ElementBox.js index f5064cb40aead9..e615d33807c1fb 100644 --- a/Libraries/Inspector/ElementBox.js +++ b/Libraries/Inspector/ElementBox.js @@ -123,12 +123,14 @@ function resolveSizeInPlace( ) { if (style[direction] !== null && typeof style[direction] === 'string') { if (style[direction].indexOf('%') !== -1) { + // $FlowFixMe[prop-missing] style[direction] = (parseFloat(style[direction]) / 100.0) * Dimensions.get('window')[dimension]; } if (style[direction] === 'auto') { // Ignore auto sizing in frame drawing due to complexity of correctly rendering this + // $FlowFixMe[prop-missing] style[direction] = 0; } } diff --git a/Libraries/Lists/VirtualizedSectionList.js b/Libraries/Lists/VirtualizedSectionList.js index 6d9aecdc432d90..b1b3f8f447077e 100644 --- a/Libraries/Lists/VirtualizedSectionList.js +++ b/Libraries/Lists/VirtualizedSectionList.js @@ -416,6 +416,7 @@ class VirtualizedSectionList< if (updateHighlightFn != null) { this._updateHighlightMap[cellKey] = updateHighlightFn; } else { + // $FlowFixMe[prop-missing] delete this._updateHighlightFor[cellKey]; } }; diff --git a/packages/rn-tester/js/utils/RNTesterList.ios.js b/packages/rn-tester/js/utils/RNTesterList.ios.js index cb0e34893de90b..61db89b0b4bedd 100644 --- a/packages/rn-tester/js/utils/RNTesterList.ios.js +++ b/packages/rn-tester/js/utils/RNTesterList.ios.js @@ -339,6 +339,7 @@ if (ReactNativeFeatureFlags.shouldEmitW3CPointerEvents()) { const Modules: {...} = {}; APIs.concat(Components).forEach(Example => { + // $FlowFixMe[prop-missing] Modules[Example.key] = Example.module; }); From ad43deca232b208956f44d46151571ba8064dd68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Thu, 3 Nov 2022 23:37:45 -0700 Subject: [PATCH 135/169] Remove unused saveFilesToRestore function Summary: The method that would restore these files was removed in https://github.com/facebook/react-native/pull/34846. The action performed by `saveFilesToRestore` is no longer necessary (thanks kelset for pointing this out). Changelog: [internal] Reviewed By: cortinico Differential Revision: D41003911 fbshipit-source-id: bbc057ac450e7f134c4664173291ca56c18f1b17 --- scripts/publish-npm.js | 3 --- scripts/release-utils.js | 22 ---------------------- 2 files changed, 25 deletions(-) diff --git a/scripts/publish-npm.js b/scripts/publish-npm.js index 4b9821b37c8570..fea68bf374d3e5 100755 --- a/scripts/publish-npm.js +++ b/scripts/publish-npm.js @@ -41,7 +41,6 @@ const { const { generateAndroidArtifacts, publishAndroidArtifactsToMaven, - saveFilesToRestore, } = require('./release-utils'); const fs = require('fs'); const os = require('os'); @@ -74,8 +73,6 @@ if (!argv.help) { echo(`The temp publishing folder is ${tmpPublishingFolder}`); } -saveFilesToRestore(tmpPublishingFolder); - // 34c034298dc9cad5a4553964a5a324450fda0385 const currentCommit = getCurrentCommit(); const shortCommit = currentCommit.slice(0, 9); diff --git a/scripts/release-utils.js b/scripts/release-utils.js index 5b018bdb03b06c..f2e8cbb6032cd4 100644 --- a/scripts/release-utils.js +++ b/scripts/release-utils.js @@ -10,29 +10,8 @@ 'use strict'; const {exec, echo, exit, test, env, pushd, popd} = require('shelljs'); -const {saveFiles} = require('./scm-utils'); const {createHermesPrebuiltArtifactsTarball} = require('./hermes/hermes-utils'); -// TODO: we should probably remove this because of this? https://github.com/facebook/react-native/pull/34846 -function saveFilesToRestore(tmpPublishingFolder) { - const filesToSaveAndRestore = [ - 'template/Gemfile', - 'template/_ruby-version', - 'template/package.json', - '.ruby-version', - 'Gemfile.lock', - 'Gemfile', - 'package.json', - 'ReactAndroid/gradle.properties', - 'Libraries/Core/ReactNativeVersion.js', - 'React/Base/RCTVersion.m', - 'ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java', - 'ReactCommon/cxxreact/ReactNativeVersion.h', - ]; - - saveFiles(filesToSaveAndRestore, tmpPublishingFolder); -} - function generateAndroidArtifacts(releaseVersion, tmpPublishingFolder) { // -------- Generating Android Artifacts echo('Generating Android artifacts inside /tmp/maven-local'); @@ -136,5 +115,4 @@ module.exports = { generateAndroidArtifacts, generateiOSArtifacts, publishAndroidArtifactsToMaven, - saveFilesToRestore, }; From 5cfb88685f2b5f168edf356fb2cd9de799d36ac2 Mon Sep 17 00:00:00 2001 From: Lorenzo Sciandra Date: Fri, 4 Nov 2022 03:31:21 -0700 Subject: [PATCH 136/169] fix (deps): add explicitly eslint config to dependencies (#35192) Summary: Basically since this change https://github.com/facebook/react-native/pull/34423 everything worked ok because in the main branch where the monorepo has the workspace section and everything, `react-native-community/eslint-config` was getting pulled in as a node_module anyway - but when moving to a stable branch and wanting to do a release, as we are now with 0.71, because of what the final package.json looks like for react-native and [the modifications that it goes through](https://github.com/facebook/react-native/commit/f0054e1e303e238d40970d23a3b3ae47502c32ea#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519) (ex. the `workspace` section disappears), the fact that it's not directly listed as dependency makes [the CI fails](https://app.circleci.com/pipelines/github/facebook/react-native/17124/workflows/54a4162d-f466-4eab-94ba-ec9fe77e2ecf/jobs/339643) with `Error: Failed to load config "react-native-community" to extend from.` ## Changelog [General] [Fixed] - add explicitly eslint config to dependencies Pull Request resolved: https://github.com/facebook/react-native/pull/35192 Test Plan: In 0.71, add the deps to see the error disappear (it gets replaced by a different one though, looking into that) Reviewed By: jacdebug, cortinico Differential Revision: D40988407 Pulled By: cipolleschi fbshipit-source-id: 38f433a0b4b47a7cb61b59e887459d11182a5b4b --- .../eslint-config-react-native-community/BUCK | 23 +++++++++++++++++++ repo-config/package.json | 1 + 2 files changed, 24 insertions(+) create mode 100644 packages/eslint-config-react-native-community/BUCK diff --git a/packages/eslint-config-react-native-community/BUCK b/packages/eslint-config-react-native-community/BUCK new file mode 100644 index 00000000000000..8fd38289431bdb --- /dev/null +++ b/packages/eslint-config-react-native-community/BUCK @@ -0,0 +1,23 @@ +load("@fbsource//tools/build_defs/third_party:yarn_defs.bzl", "yarn_workspace") + +yarn_workspace( + name = "yarn-workspace", + srcs = glob( + ["**/*.js"], + exclude = [ + "**/__fixtures__/**", + "**/__flowtests__/**", + "**/__mocks__/**", + "**/__server_snapshot_tests__/**", + "**/__tests__/**", + "**/node_modules/**", + "**/node_modules/.bin/**", + "**/.*", + "**/.*/**", + "**/.*/.*", + "**/*.xcodeproj/**", + "**/*.xcworkspace/**", + ], + ), + visibility = ["PUBLIC"], +) diff --git a/repo-config/package.json b/repo-config/package.json index 00eef94f108ff5..d0a2a719c3b7b1 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -14,6 +14,7 @@ "@babel/generator": "^7.14.0", "@babel/plugin-transform-regenerator": "^7.0.0", "@definitelytyped/dtslint": "^0.0.127", + "@react-native-community/eslint-config": "*", "@react-native-community/eslint-plugin": "*", "@react-native/eslint-plugin-specs": "^0.71.1", "@reactions/component": "^2.0.2", From 35ebb57afa6d1a26a168806f70199c045b1df4c5 Mon Sep 17 00:00:00 2001 From: Abraham Romero Date: Fri, 4 Nov 2022 03:32:42 -0700 Subject: [PATCH 137/169] Back out "Ship modern animated" Summary: Changelog: [General][Removed] - Reverting concurrency-safe `Animated` to investigate some newly identified issues Reviewed By: sammy-SC Differential Revision: D41006680 fbshipit-source-id: 37b89911dfa72f5a94f9bb796d49f2b138b3f45b --- Libraries/Animated/NativeAnimatedHelper.js | 10 +- Libraries/Animated/__tests__/Animated-test.js | 14 +- .../createAnimatedComponentInjection-test.js | 68 +++++ Libraries/Animated/createAnimatedComponent.js | 265 ++++++++++++++++-- .../createAnimatedComponentInjection.js | 48 ++++ .../createAnimatedComponent_EXPERIMENTAL.js | 48 ++++ ...ogBoxInspectorSourceMapStatus-test.js.snap | 4 +- 7 files changed, 415 insertions(+), 42 deletions(-) create mode 100644 Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js create mode 100644 Libraries/Animated/createAnimatedComponentInjection.js create mode 100644 Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js diff --git a/Libraries/Animated/NativeAnimatedHelper.js b/Libraries/Animated/NativeAnimatedHelper.js index 1e0d9e57611556..e0c91788c4b830 100644 --- a/Libraries/Animated/NativeAnimatedHelper.js +++ b/Libraries/Animated/NativeAnimatedHelper.js @@ -142,8 +142,7 @@ const API = { } }, flushQueue: function (): void { - // TODO: (T136971132) - // invariant(NativeAnimatedModule, 'Native animated module is not available'); + invariant(NativeAnimatedModule, 'Native animated module is not available'); flushQueueTimeout = null; // Early returns before calling any APIs @@ -166,17 +165,16 @@ const API = { // use RCTDeviceEventEmitter. This reduces overhead of sending lots of // JSI functions across to native code; but also, TM infrastructure currently // does not support packing a function into native arrays. - NativeAnimatedModule?.queueAndExecuteBatchedOperations?.(singleOpQueue); + NativeAnimatedModule.queueAndExecuteBatchedOperations?.(singleOpQueue); singleOpQueue.length = 0; } else { - Platform.OS === 'android' && - NativeAnimatedModule?.startOperationBatch?.(); + Platform.OS === 'android' && NativeAnimatedModule.startOperationBatch?.(); for (let q = 0, l = queue.length; q < l; q++) { queue[q](); } queue.length = 0; Platform.OS === 'android' && - NativeAnimatedModule?.finishOperationBatch?.(); + NativeAnimatedModule.finishOperationBatch?.(); } }, queueOperation: , Fn: (...Args) => void>( diff --git a/Libraries/Animated/__tests__/Animated-test.js b/Libraries/Animated/__tests__/Animated-test.js index d02ffa8aad1f8d..698dee83e9994a 100644 --- a/Libraries/Animated/__tests__/Animated-test.js +++ b/Libraries/Animated/__tests__/Animated-test.js @@ -9,10 +9,10 @@ */ import * as React from 'react'; +import TestRenderer from 'react-test-renderer'; let Animated = require('../Animated').default; let AnimatedProps = require('../nodes/AnimatedProps').default; -let TestRenderer = require('react-test-renderer'); jest.mock('../../BatchedBridge/NativeModules', () => ({ NativeAnimatedModule: {}, @@ -175,13 +175,11 @@ describe('Animated tests', () => { expect(testRenderer.toJSON().props.style.opacity).toEqual(0); - TestRenderer.act(() => { - Animated.timing(opacity, { - toValue: 1, - duration: 0, - useNativeDriver: false, - }).start(); - }); + Animated.timing(opacity, { + toValue: 1, + duration: 0, + useNativeDriver: false, + }).start(); expect(testRenderer.toJSON().props.style.opacity).toEqual(1); }); diff --git a/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js b/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js new file mode 100644 index 00000000000000..15936f7b675a3b --- /dev/null +++ b/Libraries/Animated/__tests__/createAnimatedComponentInjection-test.js @@ -0,0 +1,68 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + * @oncall react_native + */ + +'use strict'; + +import * as React from 'react'; + +const createAnimatedComponent = require('../createAnimatedComponent').default; +const createAnimatedComponentInjection = require('../createAnimatedComponentInjection'); + +function injected( + Component: React.AbstractComponent, +): React.AbstractComponent { + return createAnimatedComponent(Component); +} + +beforeEach(() => { + jest.resetModules(); + jest.resetAllMocks(); +}); + +test('does nothing without injection', () => { + expect(typeof createAnimatedComponent).toBe('function'); + expect(createAnimatedComponent).not.toBe(injected); +}); + +test('injection overrides `createAnimatedComponent`', () => { + createAnimatedComponentInjection.inject(injected); + + expect(createAnimatedComponent).toBe(injected); +}); + +test('injection errors if called too late', () => { + jest.spyOn(console, 'error').mockReturnValue(undefined); + + // Causes `createAnimatedComponent` to be initialized. + createAnimatedComponent; + + createAnimatedComponentInjection.inject(injected); + + expect(createAnimatedComponent).not.toBe(injected); + expect(console.error).toBeCalledWith( + 'createAnimatedComponentInjection: Must be called before `createAnimatedComponent`.', + ); +}); + +test('injection errors if called more than once', () => { + jest.spyOn(console, 'error').mockReturnValue(undefined); + + createAnimatedComponentInjection.inject(injected); + + expect(createAnimatedComponent).toBe(injected); + expect(console.error).not.toBeCalled(); + + createAnimatedComponentInjection.inject(injected); + + expect(console.error).toBeCalledWith( + 'createAnimatedComponentInjection: Cannot be called more than once.', + ); +}); diff --git a/Libraries/Animated/createAnimatedComponent.js b/Libraries/Animated/createAnimatedComponent.js index 09d749c8ca85e0..fb64ba05ffd375 100644 --- a/Libraries/Animated/createAnimatedComponent.js +++ b/Libraries/Animated/createAnimatedComponent.js @@ -8,11 +8,19 @@ * @format */ +'use strict'; + import View from '../Components/View/View'; -import useMergeRefs from '../Utilities/useMergeRefs'; -import useAnimatedProps from './useAnimatedProps'; +import setAndForwardRef from '../Utilities/setAndForwardRef'; +import {AnimatedEvent} from './AnimatedEvent'; +import * as createAnimatedComponentInjection from './createAnimatedComponentInjection'; +import NativeAnimatedHelper from './NativeAnimatedHelper'; +import AnimatedProps from './nodes/AnimatedProps'; +import invariant from 'invariant'; import * as React from 'react'; +let animatedComponentNextId = 1; + export type AnimatedComponentType< -Props: {+[string]: mixed, ...}, +Instance = mixed, @@ -29,33 +37,238 @@ export type AnimatedComponentType< Instance, >; -export default function createAnimatedComponent( - Component: React.AbstractComponent, -): AnimatedComponentType { - return React.forwardRef((props, forwardedRef) => { - const [reducedProps, callbackRef] = useAnimatedProps( - // $FlowFixMe[incompatible-call] - props, - ); - const ref = useMergeRefs(callbackRef, forwardedRef); - - // Some components require explicit passthrough values for animation - // to work properly. For example, if an animated component is - // transformed and Pressable, onPress will not work after transform - // without these passthrough values. - // $FlowFixMe[prop-missing] - const {passthroughAnimatedPropExplicitValues, style} = reducedProps; - const {style: passthroughStyle, ...passthroughProps} = - passthroughAnimatedPropExplicitValues ?? {}; - const mergedStyle = {...style, ...passthroughStyle}; +function createAnimatedComponent( + Component: React.AbstractComponent, +): AnimatedComponentType { + invariant( + typeof Component !== 'function' || + (Component.prototype && Component.prototype.isReactComponent), + '`createAnimatedComponent` does not support stateless functional components; ' + + 'use a class component instead.', + ); + + class AnimatedComponent extends React.Component { + _component: any; // TODO T53738161: flow type this, and the whole file + _invokeAnimatedPropsCallbackOnMount: boolean = false; + _prevComponent: any; + _propsAnimated: AnimatedProps; + _eventDetachers: Array = []; + + // Only to be used in this file, and only in Fabric. + _animatedComponentId: string = `${animatedComponentNextId++}:animatedComponent`; + + _attachNativeEvents() { + // Make sure to get the scrollable node for components that implement + // `ScrollResponder.Mixin`. + const scrollableNode = this._component?.getScrollableNode + ? this._component.getScrollableNode() + : this._component; + + for (const key in this.props) { + const prop = this.props[key]; + if (prop instanceof AnimatedEvent && prop.__isNative) { + prop.__attach(scrollableNode, key); + this._eventDetachers.push(() => prop.__detach(scrollableNode, key)); + } + } + } + + _detachNativeEvents() { + this._eventDetachers.forEach(remove => remove()); + this._eventDetachers = []; + } + + _isFabric = (): boolean => { + // When called during the first render, `_component` is always null. + // Therefore, even if a component is rendered in Fabric, we can't detect + // that until ref is set, which happens sometime after the first render. + // In cases where this value switching between "false" and "true" on Fabric + // causes issues, add an additional check for _component nullity. + if (this._component == null) { + return false; + } + return ( + // eslint-disable-next-line dot-notation + this._component['_internalInstanceHandle']?.stateNode?.canonical != + null || + // Some components have a setNativeProps function but aren't a host component + // such as lists like FlatList and SectionList. These should also use + // forceUpdate in Fabric since setNativeProps doesn't exist on the underlying + // host component. This crazy hack is essentially special casing those lists and + // ScrollView itself to use forceUpdate in Fabric. + // If these components end up using forwardRef then these hacks can go away + // as this._component would actually be the underlying host component and the above check + // would be sufficient. + (this._component.getNativeScrollRef != null && + this._component.getNativeScrollRef() != null && + // eslint-disable-next-line dot-notation + this._component.getNativeScrollRef()['_internalInstanceHandle'] + ?.stateNode?.canonical != null) || + (this._component.getScrollResponder != null && + this._component.getScrollResponder() != null && + this._component.getScrollResponder().getNativeScrollRef != null && + this._component.getScrollResponder().getNativeScrollRef() != null && + this._component.getScrollResponder().getNativeScrollRef()[ + // eslint-disable-next-line dot-notation + '_internalInstanceHandle' + ]?.stateNode?.canonical != null) + ); + }; + + _waitForUpdate = (): void => { + if (this._isFabric()) { + NativeAnimatedHelper.API.setWaitingForIdentifier( + this._animatedComponentId, + ); + } + }; + + _markUpdateComplete = (): void => { + if (this._isFabric()) { + NativeAnimatedHelper.API.unsetWaitingForIdentifier( + this._animatedComponentId, + ); + } + }; + + // The system is best designed when setNativeProps is implemented. It is + // able to avoid re-rendering and directly set the attributes that changed. + // However, setNativeProps can only be implemented on leaf native + // components. If you want to animate a composite component, you need to + // re-render it. In this case, we have a fallback that uses forceUpdate. + // This fallback is also called in Fabric. + _animatedPropsCallback = (): void => { + if (this._component == null) { + // AnimatedProps is created in will-mount because it's used in render. + // But this callback may be invoked before mount in async mode, + // In which case we should defer the setNativeProps() call. + // React may throw away uncommitted work in async mode, + // So a deferred call won't always be invoked. + this._invokeAnimatedPropsCallbackOnMount = true; + } else if ( + process.env.NODE_ENV === 'test' || + // For animating properties of non-leaf/non-native components + typeof this._component.setNativeProps !== 'function' || + // In Fabric, force animations to go through forceUpdate and skip setNativeProps + this._isFabric() + ) { + this.forceUpdate(); + } else if (!this._propsAnimated.__isNative) { + this._component.setNativeProps( + this._propsAnimated.__getAnimatedValue(), + ); + } else { + throw new Error( + 'Attempting to run JS driven animation on animated ' + + 'node that has been moved to "native" earlier by starting an ' + + 'animation with `useNativeDriver: true`', + ); + } + }; + + _attachProps(nextProps: any) { + const oldPropsAnimated = this._propsAnimated; + this._propsAnimated = new AnimatedProps( + nextProps, + this._animatedPropsCallback, + ); + this._propsAnimated.__attach(); + + // When you call detach, it removes the element from the parent list + // of children. If it goes to 0, then the parent also detaches itself + // and so on. + // An optimization is to attach the new elements and THEN detach the old + // ones instead of detaching and THEN attaching. + // This way the intermediate state isn't to go to 0 and trigger + // this expensive recursive detaching to then re-attach everything on + // the very next operation. + if (oldPropsAnimated) { + oldPropsAnimated.__restoreDefaultValues(); + oldPropsAnimated.__detach(); + } + } + + _setComponentRef: (ref: React.ElementRef) => void = setAndForwardRef({ + getForwardedRef: () => this.props.forwardedRef, + setLocalRef: ref => { + this._prevComponent = this._component; + this._component = ref; + }, + }); + + render(): React.Node { + const animatedProps = this._propsAnimated.__getValue() || {}; + + const {style = {}, ...props} = animatedProps; + const {style: passthruStyle = {}, ...passthruProps} = + this.props.passthroughAnimatedPropExplicitValues || {}; + const mergedStyle = {...style, ...passthruStyle}; + + // Force `collapsable` to be false so that native view is not flattened. + // Flattened views cannot be accurately referenced by a native driver. + return ( + + ); + } + + UNSAFE_componentWillMount() { + this._waitForUpdate(); + this._attachProps(this.props); + } + + componentDidMount() { + if (this._invokeAnimatedPropsCallbackOnMount) { + this._invokeAnimatedPropsCallbackOnMount = false; + this._animatedPropsCallback(); + } + + this._propsAnimated.setNativeView(this._component); + this._attachNativeEvents(); + this._markUpdateComplete(); + } + + UNSAFE_componentWillReceiveProps(newProps: any) { + this._waitForUpdate(); + this._attachProps(newProps); + } + + componentDidUpdate(prevProps: any) { + if (this._component !== this._prevComponent) { + this._propsAnimated.setNativeView(this._component); + } + if (this._component !== this._prevComponent || prevProps !== this.props) { + this._detachNativeEvents(); + this._attachNativeEvents(); + } + this._markUpdateComplete(); + } + + componentWillUnmount() { + this._propsAnimated && this._propsAnimated.__detach(); + this._detachNativeEvents(); + this._markUpdateComplete(); + this._component = null; + this._prevComponent = null; + } + } + + return React.forwardRef(function AnimatedComponentWrapper(props, ref) { return ( - ); }); } + +// $FlowIgnore[incompatible-cast] - Will be compatible after refactors. +export default (createAnimatedComponentInjection.recordAndRetrieve() ?? + createAnimatedComponent: typeof createAnimatedComponent); diff --git a/Libraries/Animated/createAnimatedComponentInjection.js b/Libraries/Animated/createAnimatedComponentInjection.js new file mode 100644 index 00000000000000..ab172bf12ca21d --- /dev/null +++ b/Libraries/Animated/createAnimatedComponentInjection.js @@ -0,0 +1,48 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import * as React from 'react'; + +type createAnimatedComponent = ( + Component: React.AbstractComponent, +) => React.AbstractComponent; + +// This can be undefined, null, or the experimental implementation. If this is +// null, that means `createAnimatedComponent` has already been initialized and +// it is too late to call `inject`. +let injected: ?createAnimatedComponent; + +/** + * Call during bundle initialization to opt-in to new `createAnimatedComponent`. + */ +export function inject(newInjected: createAnimatedComponent): void { + if (injected !== undefined) { + if (__DEV__) { + console.error( + 'createAnimatedComponentInjection: ' + + (injected == null + ? 'Must be called before `createAnimatedComponent`.' + : 'Cannot be called more than once.'), + ); + } + return; + } + injected = newInjected; +} + +/** + * Only called by `createAnimatedComponent.js`. + */ +export function recordAndRetrieve(): createAnimatedComponent | null { + if (injected === undefined) { + injected = null; + } + return injected; +} diff --git a/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js b/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js new file mode 100644 index 00000000000000..eb7c78cecc815c --- /dev/null +++ b/Libraries/Animated/createAnimatedComponent_EXPERIMENTAL.js @@ -0,0 +1,48 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import StyleSheet from '../StyleSheet/StyleSheet'; +import useMergeRefs from '../Utilities/useMergeRefs'; +import useAnimatedProps from './useAnimatedProps'; +import * as React from 'react'; + +/** + * Experimental implementation of `createAnimatedComponent` that is intended to + * be compatible with concurrent rendering. + */ +export default function createAnimatedComponent( + Component: React.AbstractComponent, +): React.AbstractComponent { + return React.forwardRef((props, forwardedRef) => { + const [reducedProps, callbackRef] = useAnimatedProps( + props, + ); + const ref = useMergeRefs(callbackRef, forwardedRef); + + // Some components require explicit passthrough values for animation + // to work properly. For example, if an animated component is + // transformed and Pressable, onPress will not work after transform + // without these passthrough values. + // $FlowFixMe[prop-missing] + const {passthroughAnimatedPropExplicitValues, style} = reducedProps; + const {style: passthroughStyle, ...passthroughProps} = + passthroughAnimatedPropExplicitValues ?? {}; + const mergedStyle = StyleSheet.compose(style, passthroughStyle); + + return ( + + ); + }); +} diff --git a/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap b/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap index d814a90fe50c96..a2c2cd03b6a442 100644 --- a/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap +++ b/Libraries/LogBox/UI/__tests__/__snapshots__/LogBoxInspectorSourceMapStatus-test.js.snap @@ -27,7 +27,7 @@ exports[`LogBoxInspectorSourceMapStatus should render for failed 1`] = ` } } > - - Date: Fri, 4 Nov 2022 05:11:39 -0700 Subject: [PATCH 138/169] mv `emitMixedTypeAnnotation` fn > `parsers-primitives.js` (#35185) Summary: This PR is a task of https://github.com/facebook/react-native/issues/34872 - Moved the [emitMixedTypeAnnotation](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/parsers-commons.js#L102) function to the [`parser-primitives.js` file](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/parsers/parsers-primitives.js). - Moved tests for the same respectively - Fixed/Updated imports and exports for the same respectively ## Changelog [INTERNAL] [Changed] - Moved the `emitMixedTypeAnnotation` function to the `parser-primitives.js` file. Pull Request resolved: https://github.com/facebook/react-native/pull/35185 Test Plan: `yarn test-ci` ![image](https://user-images.githubusercontent.com/55224033/199693475-60c034bf-cd5c-4cb8-bfe8-e7c7ccbc4300.png) Reviewed By: cipolleschi Differential Revision: D40993027 Pulled By: rshest fbshipit-source-id: 5e025804f4ef6723396accf2f859483f76cb6cd6 --- .../parsers/__tests__/parsers-commons-test.js | 27 ------------------- .../__tests__/parsers-primitives-test.js | 27 +++++++++++++++++++ .../src/parsers/flow/modules/index.js | 2 +- .../src/parsers/parsers-commons.js | 10 ------- .../src/parsers/parsers-primitives.js | 11 ++++++++ .../src/parsers/typescript/modules/index.js | 2 +- 6 files changed, 40 insertions(+), 39 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js index 7e0237fa924df1..232a75c4fdc13e 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/parsers-commons-test.js @@ -16,7 +16,6 @@ import type {ParserType} from '../errors'; const { wrapNullable, unwrapNullable, - emitMixedTypeAnnotation, emitUnionTypeAnnotation, } = require('../parsers-commons.js'); const {UnsupportedUnionTypeAnnotationParserError} = require('../errors'); @@ -250,32 +249,6 @@ describe('assertGenericTypeAnnotationHasExactlyOneTypeParameter', () => { }); }); -describe('emitMixedTypeAnnotation', () => { - describe('when nullable is true', () => { - it('returns nullable type annotation', () => { - const result = emitMixedTypeAnnotation(true); - const expected = { - type: 'NullableTypeAnnotation', - typeAnnotation: { - type: 'MixedTypeAnnotation', - }, - }; - - expect(result).toEqual(expected); - }); - }); - describe('when nullable is false', () => { - it('returns non nullable type annotation', () => { - const result = emitMixedTypeAnnotation(false); - const expected = { - type: 'MixedTypeAnnotation', - }; - - expect(result).toEqual(expected); - }); - }); -}); - describe('emitUnionTypeAnnotation', () => { const hasteModuleName = 'SampleTurboModule'; diff --git a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js b/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js index b64c48f776a3ee..ecd36400bc6448 100644 --- a/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js +++ b/packages/react-native-codegen/src/parsers/__tests__/parsers-primitives-test.js @@ -23,6 +23,7 @@ const { emitVoid, emitString, emitStringish, + emitMixedTypeAnnotation, typeAliasResolution, } = require('../parsers-primitives.js'); @@ -452,3 +453,29 @@ describe('emitObject', () => { }); }); }); + +describe('emitMixedTypeAnnotation', () => { + describe('when nullable is true', () => { + it('returns nullable type annotation', () => { + const result = emitMixedTypeAnnotation(true); + const expected = { + type: 'NullableTypeAnnotation', + typeAnnotation: { + type: 'MixedTypeAnnotation', + }, + }; + + expect(result).toEqual(expected); + }); + }); + describe('when nullable is false', () => { + it('returns non nullable type annotation', () => { + const result = emitMixedTypeAnnotation(false); + const expected = { + type: 'MixedTypeAnnotation', + }; + + expect(result).toEqual(expected); + }); + }); +}); diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index cd6e2f3e4401cb..ee7842bdb51430 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -33,7 +33,6 @@ const { unwrapNullable, wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, emitUnionTypeAnnotation, translateDefault, } = require('../../parsers-commons'); @@ -50,6 +49,7 @@ const { emitVoid, emitString, emitStringish, + emitMixedTypeAnnotation, typeAliasResolution, } = require('../../parsers-primitives'); diff --git a/packages/react-native-codegen/src/parsers/parsers-commons.js b/packages/react-native-codegen/src/parsers/parsers-commons.js index 28ac2725e2645c..cdeb0c7bf5c147 100644 --- a/packages/react-native-codegen/src/parsers/parsers-commons.js +++ b/packages/react-native-codegen/src/parsers/parsers-commons.js @@ -15,7 +15,6 @@ import type { NativeModuleSchema, NativeModuleTypeAnnotation, Nullable, - NativeModuleMixedTypeAnnotation, UnionTypeAnnotationMemberType, NativeModuleUnionTypeAnnotation, } from '../CodegenSchema.js'; @@ -107,14 +106,6 @@ function assertGenericTypeAnnotationHasExactlyOneTypeParameter( } } -function emitMixedTypeAnnotation( - nullable: boolean, -): Nullable { - return wrapNullable(nullable, { - type: 'MixedTypeAnnotation', - }); -} - function remapUnionTypeAnnotationMemberNames( types: $FlowFixMe, language: ParserType, @@ -233,7 +224,6 @@ module.exports = { unwrapNullable, wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, emitUnionTypeAnnotation, getKeyName, translateDefault, diff --git a/packages/react-native-codegen/src/parsers/parsers-primitives.js b/packages/react-native-codegen/src/parsers/parsers-primitives.js index 1b450d044ee9b7..7ccfebc293a2f8 100644 --- a/packages/react-native-codegen/src/parsers/parsers-primitives.js +++ b/packages/react-native-codegen/src/parsers/parsers-primitives.js @@ -17,6 +17,7 @@ import type { NativeModuleFunctionTypeAnnotation, NativeModuleTypeAliasTypeAnnotation, NativeModuleNumberTypeAnnotation, + NativeModuleMixedTypeAnnotation, BooleanTypeAnnotation, DoubleTypeAnnotation, Int32TypeAnnotation, @@ -80,6 +81,7 @@ function emitStringish(nullable: boolean): Nullable { type: 'StringTypeAnnotation', }); } + function emitFunction( nullable: boolean, translateFunctionTypeAnnotationValue: NativeModuleFunctionTypeAnnotation, @@ -87,6 +89,14 @@ function emitFunction( return wrapNullable(nullable, translateFunctionTypeAnnotationValue); } +function emitMixedTypeAnnotation( + nullable: boolean, +): Nullable { + return wrapNullable(nullable, { + type: 'MixedTypeAnnotation', + }); +} + function emitString(nullable: boolean): Nullable { return wrapNullable(nullable, { type: 'StringTypeAnnotation', @@ -193,5 +203,6 @@ module.exports = { emitVoid, emitString, emitStringish, + emitMixedTypeAnnotation, typeAliasResolution, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index bc5aae5f65ecba..045b4d6df07263 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -36,7 +36,6 @@ const { unwrapNullable, wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, - emitMixedTypeAnnotation, emitUnionTypeAnnotation, translateDefault, } = require('../../parsers-commons'); @@ -53,6 +52,7 @@ const { emitVoid, emitString, emitStringish, + emitMixedTypeAnnotation, typeAliasResolution, } = require('../../parsers-primitives'); const { From fc9954ac14e287b4e945e9f8f6fe4057ccd91ed5 Mon Sep 17 00:00:00 2001 From: Sam Zhou Date: Fri, 4 Nov 2022 08:03:05 -0700 Subject: [PATCH 139/169] Deploy Flow 0.192.0 Summary: Changelog: [Internal] Reviewed By: bradzacher Differential Revision: D41018709 fbshipit-source-id: 9e0e18d55815bd449b20b3a9a3e556cda74731ba --- .flowconfig | 2 +- .flowconfig.android | 2 +- package.json | 2 +- repo-config/package.json | 2 +- yarn.lock | 8 ++++---- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.flowconfig b/.flowconfig index 9862b98d35dbdb..31876f8dbb3c4f 100644 --- a/.flowconfig +++ b/.flowconfig @@ -73,4 +73,4 @@ untyped-import untyped-type-import [version] -^0.191.0 +^0.192.0 diff --git a/.flowconfig.android b/.flowconfig.android index ba1090d54053c5..cdfe915be1ac8e 100644 --- a/.flowconfig.android +++ b/.flowconfig.android @@ -73,4 +73,4 @@ untyped-import untyped-type-import [version] -^0.191.0 +^0.192.0 diff --git a/package.json b/package.json index f9f12e5974df4a..3bb9836aff8be1 100644 --- a/package.json +++ b/package.json @@ -143,7 +143,7 @@ "ws": "^6.2.2" }, "devDependencies": { - "flow-bin": "^0.191.0", + "flow-bin": "^0.192.0", "hermes-eslint": "0.8.0", "react": "18.2.0", "react-test-renderer": "^18.2.0" diff --git a/repo-config/package.json b/repo-config/package.json index d0a2a719c3b7b1..94a78ed7440614 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -37,7 +37,7 @@ "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-native": "^4.0.0", "eslint-plugin-relay": "^1.8.3", - "flow-bin": "^0.191.0", + "flow-bin": "^0.192.0", "inquirer": "^7.1.0", "jest": "^29.2.1", "jest-junit": "^10.0.0", diff --git a/yarn.lock b/yarn.lock index d7224029f83700..072f8ecf2e6abe 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4523,10 +4523,10 @@ flatted@^3.1.0: resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.2.tgz#64bfed5cb68fe3ca78b3eb214ad97b63bedce561" integrity sha512-JaTY/wtrcSyvXJl4IMFHPKyFur1sE9AUqc0QnhOaJ0CxHtAoIV8pYDzeEfAaNEtGkOfq4gr3LBFmdXW5mOQFnA== -flow-bin@^0.191.0: - version "0.191.0" - resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.191.0.tgz#9324c9498584b60575fd8d77a2897ee4f384443b" - integrity sha512-IhaDGoOtRDdGUJLjm7KQlHK8BAzOVJmpx+CIR6bCju4pF7zon2v7WNrds5706WZqDE3rD2c8cM4GdhDnIFYXtg== +flow-bin@^0.192.0: + version "0.192.0" + resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.192.0.tgz#a1d75fb955b3980b23cff43577044c52f5d95d33" + integrity sha512-RlHhXn9m1IRTB5yKhnLGgLWq9z4qJ76slum/DXvmTlrAUPaVcmU/IsTHiY4JpjqK7nFz4oyrnU/YES8xDVBoZg== flow-parser@0.*, flow-parser@^0.185.0: version "0.185.0" From d03a29ce5f7a40b4b0d172b7f2eb957143684818 Mon Sep 17 00:00:00 2001 From: Ruslan Lesiutin Date: Fri, 4 Nov 2022 08:08:54 -0700 Subject: [PATCH 140/169] refactor(react-native-github): move ImagePickerIOS to internal (#35199) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35199 **Changelog:** [iOS][Removed] - Removed ImagePickerIOS module native sources [JS][Removed] - Removed ImagePickerIOS module from react-native Reviewed By: cortinico Differential Revision: D40859520 fbshipit-source-id: a6a114a05574d46ea62600999bff95025ba7cdc8 --- Libraries/Image/ImagePickerIOS.d.ts | 48 -------- Libraries/Image/ImagePickerIOS.js | 103 ------------------ Libraries/Image/NativeImagePickerIOS.js | 39 ------- index.js | 27 +++-- .../modules/__test_fixtures__/fixtures.js | 67 ------------ .../GenerateModuleCpp-test.js.snap | 9 -- .../GenerateModuleH-test.js.snap | 43 -------- .../GenerateModuleHObjCpp-test.js.snap | 44 -------- .../GenerateModuleMm-test.js.snap | 21 ---- types/index.d.ts | 1 - 10 files changed, 16 insertions(+), 386 deletions(-) delete mode 100644 Libraries/Image/ImagePickerIOS.d.ts delete mode 100644 Libraries/Image/ImagePickerIOS.js delete mode 100644 Libraries/Image/NativeImagePickerIOS.js diff --git a/Libraries/Image/ImagePickerIOS.d.ts b/Libraries/Image/ImagePickerIOS.d.ts deleted file mode 100644 index 7dbd447581bb0b..00000000000000 --- a/Libraries/Image/ImagePickerIOS.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -export interface OpenCameraDialogOptions { - /** Defaults to false */ - videoMode?: boolean | undefined; -} - -export interface OpenSelectDialogOptions { - /** Defaults to true */ - showImages?: boolean | undefined; - /** Defaults to false */ - showVideos?: boolean | undefined; -} - -/** [imageURL|tempImageTag, height, width] */ -export type ImagePickerResult = [string, number, number]; - -export interface ImagePickerIOSStatic { - canRecordVideos(callback: (value: boolean) => void): void; - canUseCamera(callback: (value: boolean) => void): void; - openCameraDialog( - config: OpenCameraDialogOptions, - successCallback: (args: ImagePickerResult) => void, - cancelCallback: (args: any[]) => void, - ): void; - openSelectDialog( - config: OpenSelectDialogOptions, - successCallback: (args: ImagePickerResult) => void, - cancelCallback: (args: any[]) => void, - ): void; -} - -/** - * ImagePickerIOS has been extracted from react-native core and will be removed in a future release. - * Please upgrade to use either `@react-native-community/react-native-image-picker` or 'expo-image-picker'. - * If you cannot upgrade to a different library, please install the deprecated `@react-native-community/image-picker-ios` package. - * @see https://github.com/react-native-community/react-native-image-picker-ios - * @deprecated - */ -export const ImagePickerIOS: ImagePickerIOSStatic; -export type ImagePickerIOS = ImagePickerIOSStatic; diff --git a/Libraries/Image/ImagePickerIOS.js b/Libraries/Image/ImagePickerIOS.js deleted file mode 100644 index e94cd646e9a1f0..00000000000000 --- a/Libraries/Image/ImagePickerIOS.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - * @flow strict-local - */ - -import NativeImagePickerIOS from './NativeImagePickerIOS'; -import invariant from 'invariant'; - -const ImagePickerIOS = { - canRecordVideos: function (callback: (result: boolean) => void): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - return NativeImagePickerIOS.canRecordVideos(callback); - }, - canUseCamera: function (callback: (result: boolean) => void): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - return NativeImagePickerIOS.canUseCamera(callback); - }, - openCameraDialog: function ( - config: $ReadOnly<{| - unmirrorFrontFacingCamera?: boolean, - videoMode?: boolean, - |}>, - successCallback: (imageURL: string, height: number, width: number) => void, - cancelCallback: () => void, - ): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - - var newConfig = { - videoMode: true, - unmirrorFrontFacingCamera: false, - }; - - if (config.videoMode != null) { - newConfig.videoMode = config.videoMode; - } - - if (config.unmirrorFrontFacingCamera != null) { - newConfig.unmirrorFrontFacingCamera = config.unmirrorFrontFacingCamera; - } - - return NativeImagePickerIOS.openCameraDialog( - newConfig, - successCallback, - cancelCallback, - ); - }, - openSelectDialog: function ( - config: $ReadOnly<{| - showImages?: boolean, - showVideos?: boolean, - |}>, - successCallback: (imageURL: string, height: number, width: number) => void, - cancelCallback: () => void, - ): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - - var newConfig = { - showImages: true, - showVideos: false, - }; - - if (config.showImages != null) { - newConfig.showImages = config.showImages; - } - - if (config.showVideos != null) { - newConfig.showVideos = config.showVideos; - } - - return NativeImagePickerIOS.openSelectDialog( - newConfig, - successCallback, - cancelCallback, - ); - }, - /** - * In iOS 13, the video URLs returned by the Image Picker are invalidated when - * the picker is dismissed, unless reference to it is held. This API allows - * the application to signal when it's finished with the video so that the - * reference can be cleaned up. - * It is safe to call this method for urlsthat aren't video URLs; - * it will be a no-op. - */ - removePendingVideo: function (url: string): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - NativeImagePickerIOS.removePendingVideo(url); - }, - /** - * WARNING: In most cases, removePendingVideo should be used instead because - * clearAllPendingVideos could clear out pending videos made by other callers. - */ - clearAllPendingVideos: function (): void { - invariant(NativeImagePickerIOS, 'ImagePickerIOS is not available'); - NativeImagePickerIOS.clearAllPendingVideos(); - }, -}; - -module.exports = ImagePickerIOS; diff --git a/Libraries/Image/NativeImagePickerIOS.js b/Libraries/Image/NativeImagePickerIOS.js deleted file mode 100644 index 47f06fa1d36066..00000000000000 --- a/Libraries/Image/NativeImagePickerIOS.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @flow strict - * @format - */ - -import type {TurboModule} from '../TurboModule/RCTExport'; - -import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; - -export interface Spec extends TurboModule { - +getConstants: () => {||}; - +canRecordVideos: (callback: (result: boolean) => void) => void; - +canUseCamera: (callback: (result: boolean) => void) => void; - +openCameraDialog: ( - config: {| - unmirrorFrontFacingCamera: boolean, - videoMode: boolean, - |}, - successCallback: (imageURL: string, height: number, width: number) => void, - cancelCallback: () => void, - ) => void; - +openSelectDialog: ( - config: {| - showImages: boolean, - showVideos: boolean, - |}, - successCallback: (imageURL: string, height: number, width: number) => void, - cancelCallback: () => void, - ) => void; - +clearAllPendingVideos: () => void; - +removePendingVideo: (url: string) => void; -} - -export default (TurboModuleRegistry.get('ImagePickerIOS'): ?Spec); diff --git a/index.js b/index.js index d33faf0bd9636d..f556fa31fa1d42 100644 --- a/index.js +++ b/index.js @@ -59,7 +59,6 @@ import typeof Dimensions from './Libraries/Utilities/Dimensions'; import typeof Easing from './Libraries/Animated/Easing'; import typeof ReactNative from './Libraries/Renderer/shims/ReactNative'; import typeof I18nManager from './Libraries/ReactNative/I18nManager'; -import typeof ImagePickerIOS from './Libraries/Image/ImagePickerIOS'; import typeof InteractionManager from './Libraries/Interaction/InteractionManager'; import typeof Keyboard from './Libraries/Components/Keyboard/Keyboard'; import typeof LayoutAnimation from './Libraries/LayoutAnimation/LayoutAnimation'; @@ -281,16 +280,6 @@ module.exports = { get I18nManager(): I18nManager { return require('./Libraries/ReactNative/I18nManager'); }, - get ImagePickerIOS(): ImagePickerIOS { - warnOnce( - 'imagePickerIOS-moved', - 'ImagePickerIOS has been extracted from react-native core and will be removed in a future release. ' + - "Please upgrade to use either '@react-native-community/react-native-image-picker' or 'expo-image-picker'. " + - "If you cannot upgrade to a different library, please install the deprecated '@react-native-community/image-picker-ios' package. " + - 'See https://github.com/rnc-archive/react-native-image-picker-ios', - ); - return require('./Libraries/Image/ImagePickerIOS'); - }, get InteractionManager(): InteractionManager { return require('./Libraries/Interaction/InteractionManager'); }, @@ -765,4 +754,20 @@ if (__DEV__) { ); }, }); + /* $FlowFixMe[prop-missing] This is intentional: Flow will error when + * attempting to access ImagePickerIOS. */ + /* $FlowFixMe[invalid-export] This is intentional: Flow will error when + * attempting to access ImagePickerIOS. */ + Object.defineProperty(module.exports, 'ImagePickerIOS', { + configurable: true, + get() { + invariant( + false, + 'ImagePickerIOS has been removed from React Native. ' + + "Please upgrade to use either '@react-native-community/react-native-image-picker' or 'expo-image-picker'. " + + "If you cannot upgrade to a different library, please install the deprecated '@react-native-community/image-picker-ios' package. " + + 'See https://github.com/rnc-archive/react-native-image-picker-ios', + ); + }, + }); } diff --git a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js index f3b88e526ba1df..b2b7e0cdfa9ae5 100644 --- a/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js +++ b/packages/react-native-codegen/src/generators/modules/__test_fixtures__/fixtures.js @@ -1224,73 +1224,6 @@ const REAL_MODULE_EXAMPLE: SchemaType = { }, moduleNames: ['CameraRollManager'], }, - NativeImagePickerIOS: { - type: 'NativeModule', - aliases: {}, - spec: { - properties: [ - { - name: 'openCameraDialog', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - params: [ - { - optional: false, - name: 'config', - typeAnnotation: { - type: 'ObjectTypeAnnotation', - properties: [ - { - optional: false, - name: 'unmirrorFrontFacingCamera', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - { - optional: false, - name: 'videoMode', - typeAnnotation: { - type: 'BooleanTypeAnnotation', - }, - }, - ], - }, - }, - { - name: 'successCallback', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - { - name: 'cancelCallback', - optional: false, - typeAnnotation: { - type: 'FunctionTypeAnnotation', - params: [], - returnTypeAnnotation: { - type: 'VoidTypeAnnotation', - }, - }, - }, - ], - }, - }, - ], - }, - moduleNames: ['ImagePickerIOS'], - excludedPlatforms: ['android'], - }, NativeExceptionsManager: { type: 'NativeModule', aliases: { diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap index 01d83b6869d405..4a22ab252d743b 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleCpp-test.js.snap @@ -240,15 +240,6 @@ NativeCameraRollManagerCxxSpecJSI::NativeCameraRollManagerCxxSpecJSI(std::shared methodMap_[\\"saveToCameraRoll\\"] = MethodMetadata {2, __hostFunction_NativeCameraRollManagerCxxSpecJSI_saveToCameraRoll}; methodMap_[\\"deletePhotos\\"] = MethodMetadata {1, __hostFunction_NativeCameraRollManagerCxxSpecJSI_deletePhotos}; } -static jsi::Value __hostFunction_NativeImagePickerIOSCxxSpecJSI_openCameraDialog(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { - static_cast(&turboModule)->openCameraDialog(rt, args[0].asObject(rt), args[1].asObject(rt).asFunction(rt), args[2].asObject(rt).asFunction(rt)); - return jsi::Value::undefined(); -} - -NativeImagePickerIOSCxxSpecJSI::NativeImagePickerIOSCxxSpecJSI(std::shared_ptr jsInvoker) - : TurboModule(\\"ImagePickerIOS\\", jsInvoker) { - methodMap_[\\"openCameraDialog\\"] = MethodMetadata {3, __hostFunction_NativeImagePickerIOSCxxSpecJSI_openCameraDialog}; -} static jsi::Value __hostFunction_NativeExceptionsManagerCxxSpecJSI_reportFatalException(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) { static_cast(&turboModule)->reportFatalException(rt, args[0].asString(rt), args[1].asObject(rt).asArray(rt), args[2].asNumber()); return jsi::Value::undefined(); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap index f8349c6811bf25..2e7955758b4d4e 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleH-test.js.snap @@ -505,49 +505,6 @@ private: Delegate delegate_; }; -class JSI_EXPORT NativeImagePickerIOSCxxSpecJSI : public TurboModule { -protected: - NativeImagePickerIOSCxxSpecJSI(std::shared_ptr jsInvoker); - -public: - virtual void openCameraDialog(jsi::Runtime &rt, jsi::Object config, jsi::Function successCallback, jsi::Function cancelCallback) = 0; - -}; - -template -class JSI_EXPORT NativeImagePickerIOSCxxSpec : public TurboModule { -public: - jsi::Value get(jsi::Runtime &rt, const jsi::PropNameID &propName) override { - return delegate_.get(rt, propName); - } - -protected: - NativeImagePickerIOSCxxSpec(std::shared_ptr jsInvoker) - : TurboModule(\\"ImagePickerIOS\\", jsInvoker), - delegate_(static_cast(this), jsInvoker) {} - -private: - class Delegate : public NativeImagePickerIOSCxxSpecJSI { - public: - Delegate(T *instance, std::shared_ptr jsInvoker) : - NativeImagePickerIOSCxxSpecJSI(std::move(jsInvoker)), instance_(instance) {} - - void openCameraDialog(jsi::Runtime &rt, jsi::Object config, jsi::Function successCallback, jsi::Function cancelCallback) override { - static_assert( - bridging::getParameterCount(&T::openCameraDialog) == 4, - \\"Expected openCameraDialog(...) to have 4 parameters\\"); - - return bridging::callFromJs( - rt, &T::openCameraDialog, jsInvoker_, instance_, std::move(config), std::move(successCallback), std::move(cancelCallback)); - } - - private: - T *instance_; - }; - - Delegate delegate_; -}; - class JSI_EXPORT NativeExceptionsManagerCxxSpecJSI : public TurboModule { protected: NativeExceptionsManagerCxxSpecJSI(std::shared_ptr jsInvoker); diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap index 6c6afb74db32ca..4e923454c77659 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap @@ -711,40 +711,6 @@ namespace facebook { }; } // namespace react } // namespace facebook -namespace JS { - namespace NativeImagePickerIOS { - struct SpecOpenCameraDialogConfig { - bool unmirrorFrontFacingCamera() const; - bool videoMode() const; - - SpecOpenCameraDialogConfig(NSDictionary *const v) : _v(v) {} - private: - NSDictionary *_v; - }; - } -} - -@interface RCTCxxConvert (NativeImagePickerIOS_SpecOpenCameraDialogConfig) -+ (RCTManagedPointer *)JS_NativeImagePickerIOS_SpecOpenCameraDialogConfig:(id)json; -@end -@protocol NativeImagePickerIOSSpec - -- (void)openCameraDialog:(JS::NativeImagePickerIOS::SpecOpenCameraDialogConfig &)config - successCallback:(RCTResponseSenderBlock)successCallback - cancelCallback:(RCTResponseSenderBlock)cancelCallback; - -@end -namespace facebook { - namespace react { - /** - * ObjC++ class for module 'NativeImagePickerIOS' - */ - class JSI_EXPORT NativeImagePickerIOSSpecJSI : public ObjCTurboModule { - public: - NativeImagePickerIOSSpecJSI(const ObjCTurboModule::InitParams ¶ms); - }; - } // namespace react -} // namespace facebook inline double JS::NativeCameraRollManager::GetPhotosParams::first() const { id const p = _v[@\\"first\\"]; @@ -845,16 +811,6 @@ inline id _Nullable JS::NativeExceptionsManager::ExceptionData::extraD id const p = _v[@\\"extraData\\"]; return p; } -inline bool JS::NativeImagePickerIOS::SpecOpenCameraDialogConfig::unmirrorFrontFacingCamera() const -{ - id const p = _v[@\\"unmirrorFrontFacingCamera\\"]; - return RCTBridgingToBool(p); -} -inline bool JS::NativeImagePickerIOS::SpecOpenCameraDialogConfig::videoMode() const -{ - id const p = _v[@\\"videoMode\\"]; - return RCTBridgingToBool(p); -} ", } `; diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap index 7630f24132a3d3..867858ae3252a7 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleMm-test.js.snap @@ -367,27 +367,6 @@ namespace facebook { } } // namespace react } // namespace facebook -@implementation RCTCxxConvert (NativeImagePickerIOS_SpecOpenCameraDialogConfig) -+ (RCTManagedPointer *)JS_NativeImagePickerIOS_SpecOpenCameraDialogConfig:(id)json -{ - return facebook::react::managedPointer(json); -} -@end -namespace facebook { - namespace react { - - static facebook::jsi::Value __hostFunction_NativeImagePickerIOSSpecJSI_openCameraDialog(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) { - return static_cast(turboModule).invokeObjCMethod(rt, VoidKind, \\"openCameraDialog\\", @selector(openCameraDialog:successCallback:cancelCallback:), args, count); - } - - NativeImagePickerIOSSpecJSI::NativeImagePickerIOSSpecJSI(const ObjCTurboModule::InitParams ¶ms) - : ObjCTurboModule(params) { - - methodMap_[\\"openCameraDialog\\"] = MethodMetadata {3, __hostFunction_NativeImagePickerIOSSpecJSI_openCameraDialog}; - setMethodArgConversionSelector(@\\"openCameraDialog\\", 0, @\\"JS_NativeImagePickerIOS_SpecOpenCameraDialogConfig:\\"); - } - } // namespace react -} // namespace facebook ", } `; diff --git a/types/index.d.ts b/types/index.d.ts index 542f22e59199a8..c29ececdc92b12 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -110,7 +110,6 @@ export * from '../Libraries/EventEmitter/NativeEventEmitter'; export * from '../Libraries/EventEmitter/RCTDeviceEventEmitter'; export * from '../Libraries/EventEmitter/RCTNativeAppEventEmitter'; export * from '../Libraries/Image/Image'; -export * from '../Libraries/Image/ImagePickerIOS'; export * from '../Libraries/Image/ImageResizeMode'; export * from '../Libraries/Image/ImageSource'; export * from '../Libraries/Interaction/InteractionManager'; From cf55e4a14e4ced4a62ab5f0252adcab9ec56f7a6 Mon Sep 17 00:00:00 2001 From: Ruslan Shestopalyuk Date: Fri, 4 Nov 2022 08:41:01 -0700 Subject: [PATCH 141/169] JS side implementation of PerformanceObserver API Summary: [Changelog][Internal] This adds module specs for the native part of PerformanceObserver, as well as the interaction logic vs the NativePerformanceObserver API. See https://fb.quip.com/MdqgAk1Eb2dV for more detail. Reviewed By: rubennorte Differential Revision: D40897006 fbshipit-source-id: 77475f21dad9ee9dbe15df5a989eb08d314e6db2 --- .../specs/NativePerformanceObserverCxx.js | 44 +++++++ .../WebPerformance/PerformanceObserver.js | 123 ++++++++++++++++-- 2 files changed, 159 insertions(+), 8 deletions(-) create mode 100644 Libraries/NativeModules/specs/NativePerformanceObserverCxx.js diff --git a/Libraries/NativeModules/specs/NativePerformanceObserverCxx.js b/Libraries/NativeModules/specs/NativePerformanceObserverCxx.js new file mode 100644 index 00000000000000..420b495e091d70 --- /dev/null +++ b/Libraries/NativeModules/specs/NativePerformanceObserverCxx.js @@ -0,0 +1,44 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import type {TurboModule} from '../../TurboModule/RCTExport'; + +import * as TurboModuleRegistry from '../../TurboModule/TurboModuleRegistry'; + +export type RawTimeStamp = number; + +export const RawPerformanceEntryTypeValues = { + UNDEFINED: 0, +}; + +export type RawPerformanceEntryType = number; + +export type RawPerformanceEntry = $ReadOnly<{ + name: string, + entryType: RawPerformanceEntryType, + startTime: RawTimeStamp, + duration: number, + + // For "event" entries only: + processingStart?: RawTimeStamp, + processingEnd?: RawTimeStamp, + interactionId?: RawTimeStamp, +}>; + +export type RawPerformanceEntryList = $ReadOnlyArray; + +export interface Spec extends TurboModule { + +startReporting: (entryType: string) => void; + +stopReporting: (entryType: string) => void; + +getPendingEntries: () => RawPerformanceEntryList; + +setOnPerformanceEntryCallback: (callback?: () => void) => void; +} + +export default (TurboModuleRegistry.get('PerformanceObserver'): ?Spec); diff --git a/Libraries/WebPerformance/PerformanceObserver.js b/Libraries/WebPerformance/PerformanceObserver.js index 80857cac24097a..aa750b2166e4c5 100644 --- a/Libraries/WebPerformance/PerformanceObserver.js +++ b/Libraries/WebPerformance/PerformanceObserver.js @@ -8,9 +8,19 @@ * @flow strict */ +import type { + RawPerformanceEntry, + RawPerformanceEntryList, + RawPerformanceEntryType, +} from '../NativeModules/specs/NativePerformanceObserverCxx'; + +import NativePerformanceObserver from '../NativeModules/specs/NativePerformanceObserverCxx'; +import warnOnce from '../Utilities/warnOnce'; + export type HighResTimeStamp = number; -// TODO: Extend once new types (such as event) are supported -export type PerformanceEntryType = empty; +// TODO: Extend once new types (such as event) are supported. +// TODO: Get rid of the "undefined" once there is at least one type supported. +export type PerformanceEntryType = 'undefined'; export class PerformanceEntry { name: string; @@ -18,6 +28,18 @@ export class PerformanceEntry { startTime: HighResTimeStamp; duration: number; + constructor(init: { + name: string, + entryType: PerformanceEntryType, + startTime: HighResTimeStamp, + duration: number, + }) { + this.name = init.name; + this.entryType = init.entryType; + this.startTime = init.startTime; + this.duration = init.duration; + } + // $FlowIgnore: Flow(unclear-type) toJSON(): Object { return { @@ -29,6 +51,21 @@ export class PerformanceEntry { } } +function rawToPerformanceEntryType( + type: RawPerformanceEntryType, +): PerformanceEntryType { + return 'undefined'; +} + +function rawToPerformanceEntry(entry: RawPerformanceEntry): PerformanceEntry { + return new PerformanceEntry({ + name: entry.name, + entryType: rawToPerformanceEntryType(entry.entryType), + startTime: entry.startTime, + duration: entry.duration, + }); +} + export type PerformanceEntryList = $ReadOnlyArray; export class PerformanceObserverEntryList { @@ -73,6 +110,19 @@ export type PerformanceObserverInit = type: PerformanceEntryType, }; +let _observedEntryTypeRefCount: Map = new Map(); + +let _observers: Set = new Set(); + +let _onPerformanceEntryCallbackIsSet: boolean = false; + +function warnNoNativePerformanceObserver() { + warnOnce( + 'missing-native-performance-observer', + 'Missing native implementation of PerformanceObserver', + ); +} + /** * Implementation of the PerformanceObserver interface for RN, * corresponding to the standard in https://www.w3.org/TR/performance-timeline/ @@ -95,24 +145,81 @@ export type PerformanceObserverInit = */ export default class PerformanceObserver { _callback: PerformanceObserverCallback; + _entryTypes: $ReadOnlySet; constructor(callback: PerformanceObserverCallback) { this._callback = callback; } observe(options: PerformanceObserverInit) { - console.log('PerformanceObserver: started observing'); + if (!NativePerformanceObserver) { + warnNoNativePerformanceObserver(); + return; + } + if (!_onPerformanceEntryCallbackIsSet) { + NativePerformanceObserver.setOnPerformanceEntryCallback( + onPerformanceEntry, + ); + _onPerformanceEntryCallbackIsSet = true; + } + if (options.entryTypes) { + this._entryTypes = new Set(options.entryTypes); + } else { + this._entryTypes = new Set([options.type]); + } + this._entryTypes.forEach(type => { + if (!_observedEntryTypeRefCount.has(type)) { + NativePerformanceObserver.startReporting(type); + } + _observedEntryTypeRefCount.set( + type, + (_observedEntryTypeRefCount.get(type) ?? 0) + 1, + ); + }); + _observers.add(this); } disconnect(): void { - console.log('PerformanceObserver: stopped observing'); - } - - takeRecords(): PerformanceEntryList { - return []; + if (!NativePerformanceObserver) { + warnNoNativePerformanceObserver(); + return; + } + this._entryTypes.forEach(type => { + const entryTypeRefCount = _observedEntryTypeRefCount.get(type) ?? 0; + if (entryTypeRefCount === 1) { + _observedEntryTypeRefCount.delete(type); + NativePerformanceObserver.stopReporting(type); + } else if (entryTypeRefCount !== 0) { + _observedEntryTypeRefCount.set(type, entryTypeRefCount - 1); + } + }); + _observers.delete(this); + if (_observers.size === 0) { + NativePerformanceObserver.setOnPerformanceEntryCallback(); + _onPerformanceEntryCallbackIsSet = false; + } } static supportedEntryTypes: $ReadOnlyArray = // TODO: add types once they are fully supported Object.freeze([]); } + +// This is a callback that gets scheduled and periodically called from the native side +function onPerformanceEntry() { + if (!NativePerformanceObserver) { + return; + } + const rawEntries: RawPerformanceEntryList = + NativePerformanceObserver.getPendingEntries(); + const entries = rawEntries.map(rawToPerformanceEntry); + _observers.forEach(observer => { + const entriesForObserver: PerformanceEntryList = entries.filter(entry => + observer._entryTypes.has(entry.entryType), + ); + observer._callback( + new PerformanceObserverEntryList(entriesForObserver), + observer, + ); + }); +} From 44f3234d1f4d21f779f2dfb3b9dbe16249e7c9d2 Mon Sep 17 00:00:00 2001 From: Mitch Powell Date: Fri, 4 Nov 2022 09:44:51 -0700 Subject: [PATCH 142/169] Clean up xplat/folly/container redirects Summary: Cleans up redirects for xplat/folly/container targets including: ``` //xplat/folly/container:bit_iterator //xplat/folly/container:f14_hash //xplat/folly/container:evicting_cache_map //xplat/folly/container:enumerate //xplat/folly/container:foreach ``` Reviewed By: Gownta Differential Revision: D40954195 fbshipit-source-id: c14bfa572a9316cb0262a98f183adb457d0797f2 --- ReactCommon/butter/BUCK | 2 +- ReactCommon/react/utils/BUCK | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ReactCommon/butter/BUCK b/ReactCommon/butter/BUCK index 58c92e8f7a26fe..0d7a73af1b7c4c 100644 --- a/ReactCommon/butter/BUCK +++ b/ReactCommon/butter/BUCK @@ -47,9 +47,9 @@ rn_xplat_cxx_library( deps = [ "//third-party/glog:glog", "//xplat/fbsystrace:fbsystrace", - "//xplat/folly:container_f14_hash", "//xplat/folly:memory", "//xplat/folly:shared_mutex", "//xplat/folly:small_vector", + "//xplat/folly/container:f14_hash", ], ) diff --git a/ReactCommon/react/utils/BUCK b/ReactCommon/react/utils/BUCK index e29248a92859f4..726caece924f62 100644 --- a/ReactCommon/react/utils/BUCK +++ b/ReactCommon/react/utils/BUCK @@ -55,7 +55,7 @@ rn_xplat_cxx_library( tests = [], visibility = ["PUBLIC"], deps = [ - "//xplat/folly:container_evicting_cache_map", + "//xplat/folly/container:evicting_cache_map", "//xplat/jsi:jsi", react_native_xplat_target("butter:butter"), react_native_xplat_target("react/debug:debug"), From f0b7cbe22e2d67c102149d6d118b563b71a7fbb5 Mon Sep 17 00:00:00 2001 From: Michael Anthony Leon Date: Fri, 4 Nov 2022 14:47:19 -0700 Subject: [PATCH 143/169] Add perftest dev support manager Summary: This is the 2nd iteration of D39468561 (https://github.com/facebook/react-native/commit/4d1a56813c7975c848631de331e424587054fd57). We first check if the `BridgeDevSupportManager` can be used before we return the `PerfTestDevSupportManager`. This is to avoid a breakage of Quantum that happened on the previous diff. Add a `DevSupportManager` that can be used for performance testing. This `DevSupportManager` allows the inspector connection to be established, but leaves everything else disabled. Previously, if Developer Support was enabled on a release build, the application would present an error as it unsuccessfully attempted to use the bridge dev support manager. This is now conceptually the new flow for deciding what DevSupportManager to choose. ``` if (developerSupportEnabled) { if (full support available) { use full support (i.e. bridge) } else { use profiling-only support (i.e. perftest) } } else { disable dev support } ``` The first attempt at this diff erroneously used this logic: ``` if (developerSupportEnabled) { if (debug build) { use full support (i.e. bridge) } else { use profiling-only support (i.e. perftest) } } else { disable dev support } ``` So now we are always checking to see if the `BridgeDevSupportManager` is available, and if it is, we use it. (`enableOnCrease` indicates the development mode setting: https://www.internalfb.com/code/fbsource/[6b8a941fdf2a0fd58d9db36f5a59fa5fb53ad2df]/xplat/js/react-native-github/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java?lines=259) Changelog: [internal] Reviewed By: makovkastar Differential Revision: D40948243 fbshipit-source-id: 50c6b6b905f5b9c5b5ecc090b36edbd6090ea774 --- .../DefaultDevSupportManagerFactory.java | 9 +-- .../devsupport/PerftestDevSupportManager.java | 56 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java index 97862539f424f2..d25dc60eec268a 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java @@ -61,6 +61,10 @@ public DevSupportManager create( if (!enableOnCreate) { return new DisabledDevSupportManager(); } + // Developer support is enabled, we now must choose whether to return a DevSupportManager, + // or a more lean profiling-only PerftestDevSupportManager. We make the choice by first + // trying to return the full support DevSupportManager and if it fails, then just + // return PerftestDevSupportManager. try { // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to // Class.forName() with a static string. So instead we generate a quasi-dynamic string to @@ -94,10 +98,7 @@ public DevSupportManager create( customPackagerCommandHandlers, surfaceDelegateFactory); } catch (Exception e) { - throw new RuntimeException( - "Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found" - + " or could not be created", - e); + return new PerftestDevSupportManager(applicationContext); } } } diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java new file mode 100644 index 00000000000000..2be621fc38ff6a --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/PerftestDevSupportManager.java @@ -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.devsupport; + +import android.content.Context; + +/** + * Interface for accessing and interacting with development features related to performance testing. + * Communication is enabled via the Inspector, but everything else is disabled. + */ +public final class PerftestDevSupportManager extends DisabledDevSupportManager { + private final DevServerHelper mDevServerHelper; + private final DevInternalSettings mDevSettings; + private final InspectorPackagerConnection.BundleStatus mBundleStatus; + + public PerftestDevSupportManager(Context applicationContext) { + mDevSettings = + new DevInternalSettings( + applicationContext, + new DevInternalSettings.Listener() { + @Override + public void onInternalSettingsChanged() {} + }); + mBundleStatus = new InspectorPackagerConnection.BundleStatus(); + mDevServerHelper = + new DevServerHelper( + mDevSettings, + applicationContext.getPackageName(), + new InspectorPackagerConnection.BundleStatusProvider() { + @Override + public InspectorPackagerConnection.BundleStatus getBundleStatus() { + return mBundleStatus; + } + }); + } + + @Override + public DevInternalSettings getDevSettings() { + return mDevSettings; + } + + @Override + public void startInspector() { + mDevServerHelper.openInspectorConnection(); + } + + @Override + public void stopInspector() { + mDevServerHelper.closeInspectorConnection(); + } +} From 7f60bcceac736aee99e4a8deaadcad30e94f43bc Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Mon, 7 Nov 2022 01:06:38 -0800 Subject: [PATCH 144/169] Fix removing Copy Hermes Framework script phase Summary: Changelog: [iOS][Fixed] - Remove `Copy Hermes Framework` script phase for non-Hermes build. Reviewed By: hramos Differential Revision: D41051076 fbshipit-source-id: b4b92330934e950ec3156f39f3807b90f803c1ba --- scripts/cocoapods/jsengine.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/scripts/cocoapods/jsengine.rb b/scripts/cocoapods/jsengine.rb index b5f549f753300a..9a565c250795e0 100644 --- a/scripts/cocoapods/jsengine.rb +++ b/scripts/cocoapods/jsengine.rb @@ -37,7 +37,7 @@ def setup_hermes!(react_native_path: "../node_modules/react-native", fabric_enab def add_copy_hermes_framework_script_phase(installer, react_native_path) utils_dir = File.join(react_native_path, "sdks", "hermes-engine", "utils") - phase_name = "[RN]Copy Hermes framework" + phase_name = "[RN] Copy Hermes Framework" project = installer.generated_aggregate_targets.first.user_project target = project.targets.first if target.shell_script_build_phases.none? { |phase| phase.name == phase_name } @@ -49,8 +49,13 @@ def add_copy_hermes_framework_script_phase(installer, react_native_path) def remove_copy_hermes_framework_script_phase(installer, react_native_path) utils_dir = File.join(react_native_path, "sdks", "hermes-engine", "utils") - phase_name = "[RN]Copy Hermes framework" + phase_name = "[RN] Copy Hermes Framework" project = installer.generated_aggregate_targets.first.user_project - project.targets.first.shell_script_build_phases.delete_if { |phase| phase.name == phase_name } + target = project.native_targets.first + target.shell_script_build_phases.each do |phase| + if phase.name == phase_name + target.build_phases.delete(phase) + end + end project.save() end From c05e6c47df95f36f0afa94a7aa6725a34bee4095 Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Mon, 7 Nov 2022 01:06:38 -0800 Subject: [PATCH 145/169] Remove hermesc build dir for non-Hermes build Summary: Changelog: [iOS][Fixed] - Remove hermesc build dir for non-Hermes build. Reviewed By: christophpurrer Differential Revision: D41052884 fbshipit-source-id: c9e85ca06cef79fa35e81972181558d44ca93d90 --- scripts/cocoapods/jsengine.rb | 4 ++++ scripts/react_native_pods.rb | 1 + 2 files changed, 5 insertions(+) diff --git a/scripts/cocoapods/jsengine.rb b/scripts/cocoapods/jsengine.rb index 9a565c250795e0..345972449d8802 100644 --- a/scripts/cocoapods/jsengine.rb +++ b/scripts/cocoapods/jsengine.rb @@ -59,3 +59,7 @@ def remove_copy_hermes_framework_script_phase(installer, react_native_path) end project.save() end + +def remove_hermesc_build_dir(react_native_path) + %x(rm -rf #{react_native_path}/sdks/hermes-engine/build_host_hermesc) +end diff --git a/scripts/react_native_pods.rb b/scripts/react_native_pods.rb index 6d6df22fe35e6c..0a64c7b221e3e6 100644 --- a/scripts/react_native_pods.rb +++ b/scripts/react_native_pods.rb @@ -207,6 +207,7 @@ def react_native_post_install(installer, react_native_path = "../node_modules/re add_copy_hermes_framework_script_phase(installer, react_native_path) else remove_copy_hermes_framework_script_phase(installer, react_native_path) + remove_hermesc_build_dir(react_native_path) end ReactNativePodsUtils.exclude_i386_architecture_while_using_hermes(installer) From abe76fbb5695e497926a4a38cdf9ce4c18812566 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Nov 2022 03:07:05 -0800 Subject: [PATCH 146/169] Remove tvOS support rememants (#35214) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35214 Changelog: [Internal] Reviewed By: philIip Differential Revision: D41058649 fbshipit-source-id: 16b1ec537d09e9ee50fe609417f62a146bc0f075 --- .../RNTesterSnapshotTests.m | 4 -- .../js/components/RNTesterModuleList.js | 3 +- packages/rn-tester/js/types/RNTesterTypes.js | 1 - .../js/utils/RNTesterList.android.js | 1 - .../rn-tester/js/utils/RNTesterList.ios.js | 56 ------------------- 5 files changed, 1 insertion(+), 64 deletions(-) diff --git a/packages/rn-tester/RNTesterIntegrationTests/RNTesterSnapshotTests.m b/packages/rn-tester/RNTesterIntegrationTests/RNTesterSnapshotTests.m index cf97294c73faab..d0d4f1d95d176c 100644 --- a/packages/rn-tester/RNTesterIntegrationTests/RNTesterSnapshotTests.m +++ b/packages/rn-tester/RNTesterIntegrationTests/RNTesterSnapshotTests.m @@ -40,10 +40,6 @@ -(void)test##name \ RCT_TEST(LayoutExample) RCT_TEST(ScrollViewExample) RCT_TEST(TextExample) -#if !TARGET_OS_TV -// No switch available on tvOS -RCT_TEST(SwitchExample) -#endif - (void)testZZZNotInRecordMode { diff --git a/packages/rn-tester/js/components/RNTesterModuleList.js b/packages/rn-tester/js/components/RNTesterModuleList.js index 8dbcb28b3b9777..04421e3cf229fe 100644 --- a/packages/rn-tester/js/components/RNTesterModuleList.js +++ b/packages/rn-tester/js/components/RNTesterModuleList.js @@ -122,8 +122,7 @@ const RNTesterModuleList: React$AbstractComponent = React.memo( ({sections, toggleBookmark, handleModuleCardPress}) => { const filter = ({example, filterRegex, category}: any) => filterRegex.test(example.module.title) && - (!category || example.category === category) && - (!Platform.isTV || example.supportsTVOS); + (!category || example.category === category); /* $FlowFixMe[missing-local-annot] The type annotation(s) required by * Flow's LTI update could not be added via codemod */ diff --git a/packages/rn-tester/js/types/RNTesterTypes.js b/packages/rn-tester/js/types/RNTesterTypes.js index 76416a5cf400f4..83c030e2b6a06e 100644 --- a/packages/rn-tester/js/types/RNTesterTypes.js +++ b/packages/rn-tester/js/types/RNTesterTypes.js @@ -37,7 +37,6 @@ export type RNTesterModuleInfo = $ReadOnly<{| key: string, module: RNTesterModule, category?: string, - supportsTVOS?: boolean, documentationURL?: string, isBookmarked?: boolean, exampleType?: 'components' | 'apis', diff --git a/packages/rn-tester/js/utils/RNTesterList.android.js b/packages/rn-tester/js/utils/RNTesterList.android.js index 5156c746ceef50..f92ff40c207528 100644 --- a/packages/rn-tester/js/utils/RNTesterList.android.js +++ b/packages/rn-tester/js/utils/RNTesterList.android.js @@ -29,7 +29,6 @@ const Components: Array = [ key: 'FlatListExampleIndex', module: require('../examples/FlatList/FlatListExampleIndex').default, category: 'ListView', - supportsTVOS: true, }, { key: 'ImageExample', diff --git a/packages/rn-tester/js/utils/RNTesterList.ios.js b/packages/rn-tester/js/utils/RNTesterList.ios.js index 61db89b0b4bedd..af266e7ea0efdb 100644 --- a/packages/rn-tester/js/utils/RNTesterList.ios.js +++ b/packages/rn-tester/js/utils/RNTesterList.ios.js @@ -19,25 +19,21 @@ const Components: Array = [ key: 'ActivityIndicatorExample', category: 'UI', module: require('../examples/ActivityIndicator/ActivityIndicatorExample'), - supportsTVOS: true, }, { key: 'ButtonExample', module: require('../examples/Button/ButtonExample'), category: 'UI', - supportsTVOS: true, }, { key: 'FlatListExampleIndex', module: require('../examples/FlatList/FlatListExampleIndex').default, category: 'ListView', - supportsTVOS: true, }, { key: 'ImageExample', module: require('../examples/Image/ImageExample'), category: 'Basic', - supportsTVOS: true, }, { key: 'JSResponderHandlerExample', @@ -46,59 +42,48 @@ const Components: Array = [ { key: 'InputAccessoryViewExample', module: require('../examples/InputAccessoryView/InputAccessoryViewExample'), - supportsTVOS: true, }, { key: 'KeyboardAvoidingViewExample', module: require('../examples/KeyboardAvoidingView/KeyboardAvoidingViewExample'), - supportsTVOS: false, }, { key: 'LayoutEventsExample', module: require('../examples/Layout/LayoutEventsExample'), - supportsTVOS: true, }, { key: 'ModalExample', module: require('../examples/Modal/ModalExample'), - supportsTVOS: true, }, { key: 'NewAppScreenExample', module: require('../examples/NewAppScreen/NewAppScreenExample'), - supportsTVOS: false, }, { key: 'PressableExample', module: require('../examples/Pressable/PressableExample'), - supportsTVOS: true, }, { key: 'RefreshControlExample', module: require('../examples/RefreshControl/RefreshControlExample'), - supportsTVOS: false, }, { key: 'ScrollViewSimpleExample', module: require('../examples/ScrollView/ScrollViewSimpleExample'), category: 'Basic', - supportsTVOS: true, }, { key: 'SafeAreaViewExample', module: require('../examples/SafeAreaView/SafeAreaViewExample'), - supportsTVOS: true, }, { key: 'ScrollViewExample', module: require('../examples/ScrollView/ScrollViewExample'), category: 'Basic', - supportsTVOS: true, }, { key: 'ScrollViewAnimatedExample', module: require('../examples/ScrollView/ScrollViewAnimatedExample'), - supportsTVOS: true, }, { key: 'ScrollViewIndicatorInsetsExample', @@ -108,58 +93,48 @@ const Components: Array = [ key: 'SectionListIndex', module: require('../examples/SectionList/SectionListIndex'), category: 'ListView', - supportsTVOS: true, }, { key: 'StatusBarExample', module: require('../examples/StatusBar/StatusBarExample'), - supportsTVOS: false, }, { key: 'SwipeableCardExample', module: require('../examples/SwipeableCardExample/SwipeableCardExample'), category: 'UI', - supportsTVOS: false, }, { key: 'SwitchExample', module: require('../examples/Switch/SwitchExample'), category: 'UI', - supportsTVOS: false, }, { key: 'TextExample', module: require('../examples/Text/TextExample.ios'), category: 'Basic', - supportsTVOS: true, }, { key: 'TextInputExample', module: require('../examples/TextInput/TextInputExample'), category: 'Basic', - supportsTVOS: true, }, { key: 'TouchableExample', module: require('../examples/Touchable/TouchableExample'), - supportsTVOS: true, }, { key: 'TransparentHitTestExample', module: require('../examples/TransparentHitTest/TransparentHitTestExample'), - supportsTVOS: false, }, { key: 'ViewExample', module: require('../examples/View/ViewExample'), category: 'Basic', - supportsTVOS: true, }, { key: 'NewArchitectureExample', category: 'UI', module: require('../examples/NewArchitecture/NewArchitectureExample'), - supportsTVOS: false, }, ]; @@ -167,60 +142,49 @@ const APIs: Array = [ { key: 'AccessibilityExample', module: require('../examples/Accessibility/AccessibilityExample'), - supportsTVOS: false, }, { key: 'AccessibilityIOSExample', module: require('../examples/Accessibility/AccessibilityIOSExample'), category: 'iOS', - supportsTVOS: false, }, { key: 'ActionSheetIOSExample', module: require('../examples/ActionSheetIOS/ActionSheetIOSExample'), category: 'iOS', - supportsTVOS: true, }, { key: 'AlertIOSExample', module: require('../examples/Alert/AlertIOSExample'), category: 'iOS', - supportsTVOS: true, }, { key: 'AnimatedIndex', module: require('../examples/Animated/AnimatedIndex').default, - supportsTVOS: true, }, { key: 'AnExApp', module: require('../examples/AnimatedGratuitousApp/AnExApp'), - supportsTVOS: true, }, { key: 'AppearanceExample', module: require('../examples/Appearance/AppearanceExample'), - supportsTVOS: false, }, { key: 'AppStateExample', module: require('../examples/AppState/AppStateExample'), - supportsTVOS: true, }, { key: 'BorderExample', module: require('../examples/Border/BorderExample'), - supportsTVOS: true, }, { key: 'BoxShadowExample', module: require('../examples/BoxShadow/BoxShadowExample'), - supportsTVOS: true, }, { key: 'CrashExample', module: require('../examples/Crash/CrashExample'), - supportsTVOS: false, }, { key: 'DevSettings', @@ -229,102 +193,82 @@ const APIs: Array = [ { key: 'Dimensions', module: require('../examples/Dimensions/DimensionsExample'), - supportsTVOS: true, }, { key: 'Keyboard', module: require('../examples/Keyboard/KeyboardExample').default, - supportsTVOS: true, }, { key: 'LayoutAnimationExample', module: require('../examples/Layout/LayoutAnimationExample'), - supportsTVOS: true, }, { key: 'LayoutExample', module: require('../examples/Layout/LayoutExample'), - supportsTVOS: true, }, { key: 'LinkingExample', module: require('../examples/Linking/LinkingExample'), - supportsTVOS: true, }, { key: 'NativeAnimationsExample', module: require('../examples/NativeAnimation/NativeAnimationsExample'), - supportsTVOS: true, }, { key: 'OrientationChangeExample', module: require('../examples/OrientationChange/OrientationChangeExample'), - supportsTVOS: false, }, { key: 'PanResponderExample', module: require('../examples/PanResponder/PanResponderExample'), - supportsTVOS: false, }, { key: 'PlatformColorExample', module: require('../examples/PlatformColor/PlatformColorExample'), - supportsTVOS: true, }, { key: 'PointerEventsExample', module: require('../examples/PointerEvents/PointerEventsExample'), - supportsTVOS: false, }, { key: 'RCTRootViewIOSExample', module: require('../examples/RCTRootView/RCTRootViewIOSExample'), - supportsTVOS: true, }, { key: 'RTLExample', module: require('../examples/RTL/RTLExample'), - supportsTVOS: true, }, { key: 'ShareExample', module: require('../examples/Share/ShareExample'), - supportsTVOS: true, }, { key: 'SnapshotExample', module: require('../examples/Snapshot/SnapshotExample'), - supportsTVOS: true, }, { key: 'TimerExample', module: require('../examples/Timer/TimerExample'), - supportsTVOS: true, }, { key: 'TransformExample', module: require('../examples/Transform/TransformExample'), - supportsTVOS: true, }, { key: 'TurboModuleExample', module: require('../examples/TurboModule/TurboModuleExample'), - supportsTVOS: false, }, { key: 'VibrationExample', module: require('../examples/Vibration/VibrationExample'), - supportsTVOS: false, }, { key: 'WebSocketExample', module: require('../examples/WebSocket/WebSocketExample'), - supportsTVOS: true, }, { key: 'XHRExample', module: require('../examples/XHR/XHRExample'), - supportsTVOS: true, }, ]; From 35b2150adb04b54bd1e9126857e225428025d0d5 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Nov 2022 04:22:35 -0800 Subject: [PATCH 147/169] react-native-codegen: Enable C++ TurboModule generation in OpenSource builds (#35211) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35211 This enables the generation of C++ TurboModule specs in addition to existing Java/ObjC ones. An example is shown in https://github.com/facebook/react-native/pull/35138 Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D41057630 fbshipit-source-id: 303881a63eb82f0fe8dfe10e533043a6eedb3d11 --- .../codegen/__tests__/generate-specs-cli-executor-test.js | 2 +- scripts/codegen/generate-specs-cli-executor.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/codegen/__tests__/generate-specs-cli-executor-test.js b/scripts/codegen/__tests__/generate-specs-cli-executor-test.js index b12e7833da039b..463ed28dbf6ba0 100644 --- a/scripts/codegen/__tests__/generate-specs-cli-executor-test.js +++ b/scripts/codegen/__tests__/generate-specs-cli-executor-test.js @@ -26,7 +26,7 @@ describe('generateSpec', () => { const outputDirectory = normalize('app/ios/build/generated/ios'); const libraryName = 'library'; const packageName = 'com.library'; - const generators = ['componentsIOS', 'modulesIOS']; + const generators = ['componentsIOS', 'modulesIOS', 'modulesCxx']; jest.mock('fs', () => ({ readFileSync: (path, encoding) => { diff --git a/scripts/codegen/generate-specs-cli-executor.js b/scripts/codegen/generate-specs-cli-executor.js index fe37b07fd9db88..8eda8012c8beea 100644 --- a/scripts/codegen/generate-specs-cli-executor.js +++ b/scripts/codegen/generate-specs-cli-executor.js @@ -17,16 +17,16 @@ const RNCodegen = utils.getCodegen(); const GENERATORS = { all: { - android: ['componentsAndroid', 'modulesAndroid'], - ios: ['componentsIOS', 'modulesIOS'], + android: ['componentsAndroid', 'modulesAndroid', 'modulesCxx'], + ios: ['componentsIOS', 'modulesIOS', 'modulesCxx'], }, components: { android: ['componentsAndroid'], ios: ['componentsIOS'], }, modules: { - android: ['modulesAndroid'], - ios: ['modulesIOS'], + android: ['modulesAndroid', 'modulesCxx'], + ios: ['modulesIOS', 'modulesCxx'], }, }; From 3823703a4154c7e7854af7bb334e52347e3e78cc Mon Sep 17 00:00:00 2001 From: Riccardo Cipolleschi Date: Mon, 7 Nov 2022 04:42:36 -0800 Subject: [PATCH 148/169] chore: update changelog with exceptional releases (#35238) Summary: This PR updates the Changelog with the recent patch releases. ## Changelog [Internal] - Update the changelog Pull Request resolved: https://github.com/facebook/react-native/pull/35238 Test Plan: Not needed Reviewed By: dmytrorykun Differential Revision: D41079159 Pulled By: cipolleschi fbshipit-source-id: 3be8f1dafb5d46a67b65ff8ec58dae98ebee9ad0 --- CHANGELOG.md | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b190ae10648c2..06d5eba31bc221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## v0.70.5 + +### Fixed + +- Force dependencies resolution to minor series for 0.70 ([59407a4d34](https://github.com/facebook/react-native/commit/59407a4d3442dddb7f4c29049bf56bbc345f950f) by [@cortinico](https://github.com/cortinico)) + +## v0.70.4 + +### Changed + +- Bump CLI to 9.2.1 ([a24c8946e0](https://github.com/facebook/react-native/commit/a24c8946e065ca89048e574abd7c2dc0434a350b) by [@kelset](https://github.com/kelset)) +- Bump react-native-codegen to 0.70.6 ([866021b58c](https://github.com/facebook/react-native/commit/866021b58c28a1f1c394294ddc4ed69d4ecef10a) by [@dmytrorykun](https://github.com/dmytrorykun)) + +### Fixed + +- Load react-native.config.js from correct path during codegen ([74fda10702](https://github.com/facebook/react-native/commit/74fda1070266df13e1b58680a670dde3acf9d205) by [@krystofwoldrich](https://github.com/krystofwoldrich)) + +#### iOS specific + +- Fix error in the Codegen template for ThirdPartyFabricComponentsProvider ([2f6b2127d9](https://github.com/facebook/react-native/commit/2f6b2127d933094f864523749d13cfbb140b5b63) by [@gispada](https://github.com/gispada)) +- Center text if line height isn't 0 ([70cc27c901](https://github.com/facebook/react-native/commit/70cc27c901aeb447910e30ac3ceac85990d3c16d) by [@sammy-SC](https://github.com/sammy-SC)) + ## v0.70.3 ### Fixed @@ -251,6 +273,12 @@ - Add GitHub token permissions for workflows ([3da3d82320](https://github.com/facebook/react-native/commit/3da3d82320bd035c6bd361a82ea12a70dba4e851) by [@varunsh-coder](https://github.com/varunsh-coder)) - Bump RCT-Folly to 2021-07-22 ([68f3a42fc7](https://github.com/facebook/react-native/commit/68f3a42fc7380051714253f43b42175de361f8bd) by [@luissantana](https://github.com/luissantana)) +## v0.69.7 + +### Fixed + +- Force dependencies resolution to minor series for 0.69 ([c4da74c463](https://github.com/facebook/react-native/commit/c4da74c4636cbbd6bbf681d39a8a8cca49f11f56) by [@Titozzz](https://github.com/Titozzz)) + ## v0.69.6 ### Changed @@ -545,6 +573,12 @@ - Encode URL params in URLSearchParams.toString() ([1042a8012f](https://github.com/facebook/react-native/commit/1042a8012fb472bd5c882b469fe507dd6279d562) by [@sshic](https://github.com/sshic)) +## v0.68.5 + +### Fixed + +- Force dependencies resolution to minor series for 0.68 ([edcb3ca996](https://github.com/facebook/react-native/commit/edcb3ca996fb3296762af300a36c1d46356f1b24) by [@Titozzz](https://github.com/Titozzz)) + ## v0.68.4 ### Changed @@ -807,6 +841,13 @@ - Remove RCTUIManagerObserver from RCTNativeAnimatedTurboModule ([e9ed115bab](https://github.com/facebook/react-native/commit/e9ed115babbc82968380dae22fa928d4ce3cd6da) by [@p-sun](https://github.com/p-sun)) +## v0.67.5 + +🚨 **IMPORTANT:** This is an exceptional release on an unsupported version. We recommend you upgrade to one of [the supported versions, listed here](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported). + +### Fixed + +- Force dependencies resolution to minor series for 0.67 ([9f2acda1b8](https://github.com/facebook/react-native/commit/9f2acda1b807e790b3e7562ce3436b93bcc2ad09) by [@cortinico](https://github.com/cortinico)) ## v0.67.4 @@ -949,6 +990,14 @@ - Avoiding logging root view params outside of dev / debug mode builds ([e612d3a116](https://github.com/facebook/react-native/commit/e612d3a116f39ab354169643bab0d4bb9cfc1a85) by [@sterlingwes](https://github.com/sterlingwes)) +## v0.66.5 + +🚨 **IMPORTANT:** This is an exceptional release on an unsupported version. We recommend you upgrade to one of [the supported versions, listed here](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported). + +### Fixed + +- Force dependencies resolution to minor series for 0.66 ([201824c89e](https://github.com/facebook/react-native/commit/201824c89ecebd749ba7e603415edbe6a5b9b73d) by [@cortinico](https://github.com/cortinico)) + ## v0.66.4 ### Fixed @@ -1119,6 +1168,14 @@ - content is reset when emoji is entered at the max length ([f3b8d4976f](https://github.com/facebook/react-native/commit/f3b8d4976f8608c2cda1f071923f14b6d4538967)) - Use `actionName` in accessibility event callback ([fed6ad5bad](https://github.com/facebook/react-native/commit/fed6ad5badb4196a1895370fc81c522572cb34b4) by [@ShikaSD](https://github.com/ShikaSD)) +## v0.65.3 + +🚨 **IMPORTANT:** This is an exceptional release on an unsupported version. We recommend you upgrade to one of [the supported versions, listed here](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported). + +### Fixed + +- Force dependencies resolution to minor series for 0.65 ([9548eaea74](https://github.com/facebook/react-native/commit/9548eaea74c6ad242c015d1984503c4b7eb19b6f) by [@kelset](https://github.com/kelset)) + ## v0.65.2 ### Fixed @@ -1358,6 +1415,15 @@ - Fix builds on Xcode 12.5 ([36b58a824e](https://github.com/facebook/react-native/commit/36b58a824ea20daa22fe7c528a3bf0ff4e6a4cb5) by [@PeteTheHeat](https://github.com/PeteTheHeat)) - Fix running React Native project with Xcode 12 in Release on iPhone Simulator ([fdcacd7f76](https://github.com/facebook/react-native/commit/fdcacd7f76ea8ca6dafda32ac431c8adc7bdad00) by [@grabbou](https://github.com/grabbou)) +## v0.64.4 + +🚨 **IMPORTANT:** This is an exceptional release on an unsupported version. We recommend you upgrade to one of [the supported versions, listed here](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported). + +### Fixed + +- Add an afterEvaluate to solve AGP 4.1.x configuration resolution ([667f1bd21a](https://github.com/facebook/react-native/commit/667f1bd21abfdda19e56f8bbf0520fddba3102ed) by [@cortinico](https://github.com/cortinico)) +- Force dependencies resolution to minor series for 0.64 ([a6a183ad81](https://github.com/facebook/react-native/commit/a6a183ad8106d67e3befce842138e82fb1e136fd) by [@kelset](https://github.com/kelset)) + ## v0.64.3 ### Fixed @@ -1621,6 +1687,15 @@ - Fix crash inside RCTRedBox when trying to present same UIViewController twice ([46c77dc296](https://github.com/facebook/react-native/commit/46c77dc296dfab754356cd9346a01dae8d4869f4) by [@sammy-SC](https://github.com/sammy-SC)) - Fix outdated CocoaPods version requirement in a React.podspec ([8a6ac1fef3](https://github.com/facebook/react-native/commit/8a6ac1fef369071405a3bf14a89924c66f28d192) by [@sunnylqm](https://github.com/sunnylqm)) +## v0.63.5 + +🚨 **IMPORTANT:** This is an exceptional release on an unsupported version. We recommend you upgrade to one of [the supported versions, listed here](https://github.com/reactwg/react-native-releases#which-versions-are-currently-supported). + +### Fixed + +- Add an afterEvaluate to solve AGP 3.x configuration resolution ([473a36099c](https://github.com/facebook/react-native/commit/473a36099c80de08591e3cb51687f7d531145ee3) by [@cortinico](https://github.com/cortinico)) +- Force dependencies resolution to minor series for 0.63 ([28cc286cc4](https://github.com/facebook/react-native/commit/28cc286cc4d43b9fe5153d779ea3eecf4d72c51e) by [@cortinico](https://github.com/cortinico)) + ## v0.63.4 ### Changed From 3e44d207a577876f3698a4a4f4d11f1af26840a2 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Mon, 7 Nov 2022 05:04:04 -0800 Subject: [PATCH 149/169] Shared Fabric color implementation across platforms Summary: Changelog: [Internal] Align C++ implementations of SharedColor Reviewed By: mdvacca Differential Revision: D40632527 fbshipit-source-id: 8ebca5157e5898de4311015c92b5a72dca7197d3 --- ReactCommon/react/renderer/.clang-tidy | 7 ++ ReactCommon/react/renderer/graphics/BUCK | 4 - .../react/renderer/graphics/CMakeLists.txt | 11 +-- .../react/renderer/graphics => }/Color.cpp | 2 +- .../graphics/{platform/ios => }/Color.h | 28 +++---- .../react/renderer/graphics/conversions.h | 10 +-- .../android/react/renderer/graphics/Float.h | 22 +++++ .../renderer/graphics/PlatformColorParser.h | 1 - .../cxx/react/renderer/graphics/Color.h | 80 ------------------- .../renderer/graphics/platform/ios/Color.cpp | 63 --------------- .../platform/ios/RCTPlatformColorUtils.mm | 3 +- packages/rn-tester/Podfile.lock | 4 +- 12 files changed, 49 insertions(+), 186 deletions(-) rename ReactCommon/react/renderer/graphics/{platform/cxx/react/renderer/graphics => }/Color.cpp (94%) rename ReactCommon/react/renderer/graphics/{platform/ios => }/Color.h (70%) create mode 100644 ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/Float.h delete mode 100644 ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.h delete mode 100644 ReactCommon/react/renderer/graphics/platform/ios/Color.cpp diff --git a/ReactCommon/react/renderer/.clang-tidy b/ReactCommon/react/renderer/.clang-tidy index d709ad7385399a..6ddb7b64c1b8c6 100644 --- a/ReactCommon/react/renderer/.clang-tidy +++ b/ReactCommon/react/renderer/.clang-tidy @@ -185,4 +185,11 @@ clang-analyzer-valist.Uninitialized, clang-analyzer-valist.Unterminated, google-build-using-namespace, ' + +CheckOptions: +- key: performance-unnecessary-value-param.AllowedTypes + value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$;' +- key: performance-unnecessary-copy-initialization.AllowedTypes + value: '[Pp]ointer$;[Pp]tr$;[Rr]ef(erence)?$' + ... diff --git a/ReactCommon/react/renderer/graphics/BUCK b/ReactCommon/react/renderer/graphics/BUCK index 275235d888c8c5..84cae226046c70 100644 --- a/ReactCommon/react/renderer/graphics/BUCK +++ b/ReactCommon/react/renderer/graphics/BUCK @@ -56,17 +56,13 @@ rn_xplat_cxx_library( fbandroid_exported_headers = subdir_glob( [ ("platform/android/react/renderer/graphics", "**/*.h"), - ("platform/cxx/react/renderer/graphics", "**/*.h"), ], - exclude = ["platform/cxx/react/renderer/graphics/PlatformColorParser.h"], prefix = "react/renderer/graphics", ), fbandroid_srcs = glob( [ - "platform/cxx/react/renderer/graphics/**/*.cpp", "platform/android/react/renderer/graphics/**/*.cpp", ], - exclude = ["platform/cxx/react/renderer/graphics/PlatformColorParser.h"], ), fbobjc_compiler_flags = APPLE_COMPILER_FLAGS, fbobjc_preprocessor_flags = get_preprocessor_flags_for_build_mode() + get_apple_inspector_flags(), diff --git a/ReactCommon/react/renderer/graphics/CMakeLists.txt b/ReactCommon/react/renderer/graphics/CMakeLists.txt index a977c4080733e0..3e257d5968624b 100644 --- a/ReactCommon/react/renderer/graphics/CMakeLists.txt +++ b/ReactCommon/react/renderer/graphics/CMakeLists.txt @@ -15,18 +15,13 @@ add_compile_options( -Wno-gnu-zero-variadic-macro-arguments -DLOG_TAG=\"Fabric\") -file(GLOB react_render_graphics_SRC CONFIGURE_DEPENDS - *.cpp - platform/cxx/react/renderer/graphics/*.cpp) - -add_library(react_render_graphics - SHARED - ${react_render_graphics_SRC}) +file(GLOB react_render_graphics_SRC CONFIGURE_DEPENDS *.cpp) +add_library(react_render_graphics SHARED ${react_render_graphics_SRC}) target_include_directories(react_render_graphics PUBLIC ${REACT_COMMON_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/platform/cxx/ + ${CMAKE_CURRENT_SOURCE_DIR}/platform/android/ ) target_link_libraries(react_render_graphics glog fb fbjni folly_runtime react_debug) diff --git a/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.cpp b/ReactCommon/react/renderer/graphics/Color.cpp similarity index 94% rename from ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.cpp rename to ReactCommon/react/renderer/graphics/Color.cpp index a56c5460d9eb85..83de8a0271dd85 100644 --- a/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.cpp +++ b/ReactCommon/react/renderer/graphics/Color.cpp @@ -26,7 +26,7 @@ SharedColor colorFromComponents(ColorComponents components) { ((int)round(components.blue * ratio) & 0xff)}; } -ColorComponents colorComponentsFromColor(SharedColor const &sharedColor) { +ColorComponents colorComponentsFromColor(SharedColor sharedColor) { float ratio = 255; Color color = *sharedColor; return ColorComponents{ diff --git a/ReactCommon/react/renderer/graphics/platform/ios/Color.h b/ReactCommon/react/renderer/graphics/Color.h similarity index 70% rename from ReactCommon/react/renderer/graphics/platform/ios/Color.h rename to ReactCommon/react/renderer/graphics/Color.h index 0a50fa455ad54f..4bb331bde42d58 100644 --- a/ReactCommon/react/renderer/graphics/platform/ios/Color.h +++ b/ReactCommon/react/renderer/graphics/Color.h @@ -8,32 +8,29 @@ #pragma once #include -#include +#include +#include -#include #include -#include -namespace facebook { -namespace react { +namespace facebook::react { using Color = int32_t; +/* + * On Android, a color can be represented as 32 bits integer, so there is no + * need to instantiate complex color objects and then pass them as shared + * pointers. Hense instead of using shared_ptr, we use a simple wrapper class + * which provides a pointer-like interface. + */ class SharedColor { public: static const Color UndefinedColor = std::numeric_limits::max(); SharedColor() : color_(UndefinedColor) {} - SharedColor(const SharedColor &sharedColor) : color_(sharedColor.color_) {} - SharedColor(Color color) : color_(color) {} - SharedColor &operator=(const SharedColor &sharedColor) { - color_ = sharedColor.color_; - return *this; - } - Color operator*() const { return color_; } @@ -62,12 +59,11 @@ SharedColor clearColor(); SharedColor blackColor(); SharedColor whiteColor(); -} // namespace react -} // namespace facebook +} // namespace facebook::react template <> struct std::hash { - std::size_t operator()(facebook::react::SharedColor const &color) const { - return hash()(*color); + size_t operator()(facebook::react::SharedColor color) const { + return std::hash{}(*color); } }; diff --git a/ReactCommon/react/renderer/graphics/conversions.h b/ReactCommon/react/renderer/graphics/conversions.h index 8e28bdcb4d6372..cb7aa05ee6dbef 100644 --- a/ReactCommon/react/renderer/graphics/conversions.h +++ b/ReactCommon/react/renderer/graphics/conversions.h @@ -50,17 +50,9 @@ inline void fromRawValue( } #ifdef ANDROID - inline int toAndroidRepr(const SharedColor &color) { - ColorComponents components = colorComponentsFromColor(color); - auto ratio = 255.f; - return ( - ((int)round(components.alpha * ratio) & 0xff) << 24 | - ((int)round(components.red * ratio) & 0xff) << 16 | - ((int)round(components.green * ratio) & 0xff) << 8 | - ((int)round(components.blue * ratio) & 0xff)); + return *color; } - #endif inline std::string toString(const SharedColor &value) { diff --git a/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/Float.h b/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/Float.h new file mode 100644 index 00000000000000..ef2c55c93ff24f --- /dev/null +++ b/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/Float.h @@ -0,0 +1,22 @@ +/* + * 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. + */ + +#pragma once + +#include + +namespace facebook { +namespace react { + +/* + * Exact type of float numbers which ideally should match a type behing + * platform- and chip-architecture-specific float type. + */ +using Float = float; + +} // namespace react +} // namespace facebook diff --git a/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h b/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h index be78b82b5826cd..d2b485ec8431f9 100644 --- a/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h +++ b/ReactCommon/react/renderer/graphics/platform/android/react/renderer/graphics/PlatformColorParser.h @@ -8,7 +8,6 @@ #pragma once #include -#include #include #include #include diff --git a/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.h b/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.h deleted file mode 100644 index 7de09df3adc5db..00000000000000 --- a/ReactCommon/react/renderer/graphics/platform/cxx/react/renderer/graphics/Color.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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. - */ - -#pragma once - -#include -#include -#include - -#include - -namespace facebook { -namespace react { - -using Color = int; - -/* - * On Android, a color can be represented as 32 bits integer, so there is no - * need to instantiate complex color objects and then pass them as shared - * pointers. Hense instead of using shared_ptr, we use a simple wrapper class - * which provides a pointer-like interface. - */ -class SharedColor { - public: - static const Color UndefinedColor = std::numeric_limits::max(); - - SharedColor() : color_(UndefinedColor) {} - - SharedColor(const SharedColor &sharedColor) : color_(sharedColor.color_) {} - - SharedColor(Color color) : color_(color) {} - - SharedColor &operator=(const SharedColor &sharedColor) { - color_ = sharedColor.color_; - return *this; - } - - Color operator*() const { - return color_; - } - - bool operator==(const SharedColor &otherColor) const { - return color_ == otherColor.color_; - } - - bool operator!=(const SharedColor &otherColor) const { - return color_ != otherColor.color_; - } - - operator bool() const { - return color_ != UndefinedColor; - } - - private: - Color color_; -}; - -bool isColorMeaningful(SharedColor const &color) noexcept; -SharedColor colorFromComponents(ColorComponents components); -ColorComponents colorComponentsFromColor(SharedColor const &color); - -SharedColor clearColor(); -SharedColor blackColor(); -SharedColor whiteColor(); - -} // namespace react -} // namespace facebook - -namespace std { -template <> -struct hash { - size_t operator()(const facebook::react::SharedColor &sharedColor) const { - return hash{}(*sharedColor); - } -}; -} // namespace std diff --git a/ReactCommon/react/renderer/graphics/platform/ios/Color.cpp b/ReactCommon/react/renderer/graphics/platform/ios/Color.cpp deleted file mode 100644 index 61da5e26797f1c..00000000000000 --- a/ReactCommon/react/renderer/graphics/platform/ios/Color.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - */ - -#include "Color.h" -#include - -namespace facebook { -namespace react { - -bool isColorMeaningful(SharedColor const &color) noexcept { - if (!color) { - return false; - } - - return colorComponentsFromColor(color).alpha > 0; -} - -SharedColor colorFromComponents(ColorComponents components) { - float ratio = 255; - return SharedColor( - ((int)round(components.alpha * ratio) & 0xff) << 24 | - ((int)round(components.red * ratio) & 0xff) << 16 | - ((int)round(components.green * ratio) & 0xff) << 8 | - ((int)round(components.blue * ratio) & 0xff)); -} - -ColorComponents colorComponentsFromColor(SharedColor sharedColor) { - if (!sharedColor) { - // Empty color object can be considered as `clear` (black, fully - // transparent) color. - return ColorComponents{0, 0, 0, 0}; - } - - float ratio = 255; - Color color = *sharedColor; - return ColorComponents{ - (float)((color >> 16) & 0xff) / ratio, - (float)((color >> 8) & 0xff) / ratio, - (float)((color >> 0) & 0xff) / ratio, - (float)((color >> 24) & 0xff) / ratio}; -} - -SharedColor clearColor() { - static SharedColor color = colorFromComponents(ColorComponents{0, 0, 0, 0}); - return color; -} - -SharedColor blackColor() { - static SharedColor color = colorFromComponents(ColorComponents{0, 0, 0, 1}); - return color; -} - -SharedColor whiteColor() { - static SharedColor color = colorFromComponents(ColorComponents{1, 1, 1, 1}); - return color; -} - -} // namespace react -} // namespace facebook diff --git a/ReactCommon/react/renderer/graphics/platform/ios/RCTPlatformColorUtils.mm b/ReactCommon/react/renderer/graphics/platform/ios/RCTPlatformColorUtils.mm index f11b2af9e40e8e..1d566ac8d6c440 100644 --- a/ReactCommon/react/renderer/graphics/platform/ios/RCTPlatformColorUtils.mm +++ b/ReactCommon/react/renderer/graphics/platform/ios/RCTPlatformColorUtils.mm @@ -8,7 +8,6 @@ #import "RCTPlatformColorUtils.h" #import -#import #import #include @@ -180,7 +179,7 @@ static inline facebook::react::ColorComponents _ColorComponentsFromUIColor(UIColor *color) { CGFloat rgba[4]; - RCTGetRGBAColorComponents(color.CGColor, rgba); + [color getRed:&rgba[0] green:&rgba[1] blue:&rgba[2] alpha:&rgba[3]]; return {(float)rgba[0], (float)rgba[1], (float)rgba[2], (float)rgba[3]}; } diff --git a/packages/rn-tester/Podfile.lock b/packages/rn-tester/Podfile.lock index db2169f72cc96d..1207d1bfa8a33a 100644 --- a/packages/rn-tester/Podfile.lock +++ b/packages/rn-tester/Podfile.lock @@ -951,7 +951,7 @@ SPEC CHECKSUMS: FlipperKit: cbdee19bdd4e7f05472a66ce290f1b729ba3cb86 fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9 glog: 04b94705f318337d7ead9e6d17c019bd9b1f6b1b - hermes-engine: 445a2267b04cb39ca4a0b2d6758b5a0e5a58ccad + hermes-engine: 05b2399259b25f6c105858adc778c04342c1f424 libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913 OpenSSL-Universal: ebc357f1e6bc71fa463ccb2fe676756aff50e88c RCT-Folly: 424b8c9a7a0b9ab2886ffe9c3b041ef628fd4fb1 @@ -989,7 +989,7 @@ SPEC CHECKSUMS: React-rncore: 665c70690f404bbfa3948148de72689672a906d2 React-runtimeexecutor: 97dca9247f4d3cfe0733384b189c6930fbd402b7 ReactCommon: b1f213aa09e3dfd0a89389b5023fdb1cd6528e96 - ScreenshotManager: 06cb3d1794c8082d92b3e91813d1678d0977a4fb + ScreenshotManager: cf552c19152e3357f08875fc2f85adb2dee6a66b SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608 Yoga: 1b1a12ff3d86a10565ea7cbe057d42f5e5fb2a07 YogaKit: f782866e155069a2cca2517aafea43200b01fd5a From 6db39951755cef82f06e23a5464cf1caf53c7966 Mon Sep 17 00:00:00 2001 From: Pieter De Baets Date: Mon, 7 Nov 2022 05:13:30 -0800 Subject: [PATCH 150/169] Improve @Nullable annotions in Java TurboModule codegen Summary: Noticed these types could be improved based on the tests added in D40979066 (https://github.com/facebook/react-native/commit/e81c98c842380d8b72c1dc8d4a6e64f760e2a58c). Changelog: [Android][Fixed] Corrected Nullable annotations for parameters and return values in TurboModules codegen Reviewed By: mdvacca, cipolleschi Differential Revision: D40979940 fbshipit-source-id: cfc352a9e7eb9f59e2cce3d7da110a9a8d32db4b --- .../modules/GenerateModuleJavaSpec.js | 68 +++++++++---------- .../GenerateModuleJavaSpec-test.js.snap | 4 +- 2 files changed, 35 insertions(+), 37 deletions(-) diff --git a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js index 0b807bbbfa966e..8ef4278dbc9954 100644 --- a/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js +++ b/packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js @@ -104,14 +104,15 @@ function translateFunctionParamToJavaType( unwrapNullable(nullableTypeAnnotation); const isRequired = !optional && !nullable; - function wrapIntoNullableIfNeeded(generatedType: string) { + function wrapNullable(javaType: string, nullableType?: string) { if (!isRequired) { imports.add('javax.annotation.Nullable'); - return `@Nullable ${generatedType}`; + return `@Nullable ${nullableType ?? javaType}`; } - return generatedType; + return javaType; } + // FIXME: support class alias for args let realTypeAnnotation = typeAnnotation; if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { realTypeAnnotation = resolveAlias(realTypeAnnotation.name); @@ -121,49 +122,45 @@ function translateFunctionParamToJavaType( case 'ReservedTypeAnnotation': switch (realTypeAnnotation.name) { case 'RootTag': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); default: (realTypeAnnotation.name: empty); throw new Error(createErrorMessage(realTypeAnnotation.name)); } case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); + return wrapNullable('String'); case 'NumberTypeAnnotation': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'FloatTypeAnnotation': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'DoubleTypeAnnotation': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'Int32TypeAnnotation': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'BooleanTypeAnnotation': - return !isRequired ? 'Boolean' : 'boolean'; + return wrapNullable('boolean', 'Boolean'); case 'EnumDeclaration': switch (realTypeAnnotation.memberType) { case 'NumberTypeAnnotation': - return !isRequired ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); + return wrapNullable('String'); default: throw new Error(createErrorMessage(realTypeAnnotation.type)); } case 'ObjectTypeAnnotation': imports.add('com.facebook.react.bridge.ReadableMap'); - if (typeAnnotation.type === 'TypeAliasTypeAnnotation') { - // No class alias for args, so it still falls under ReadableMap. - return 'ReadableMap'; - } - return 'ReadableMap'; + return wrapNullable('ReadableMap'); case 'GenericObjectTypeAnnotation': // Treat this the same as ObjectTypeAnnotation for now. imports.add('com.facebook.react.bridge.ReadableMap'); - return 'ReadableMap'; + return wrapNullable('ReadableMap'); case 'ArrayTypeAnnotation': imports.add('com.facebook.react.bridge.ReadableArray'); - return 'ReadableArray'; + return wrapNullable('ReadableArray'); case 'FunctionTypeAnnotation': imports.add('com.facebook.react.bridge.Callback'); - return 'Callback'; + return wrapNullable('Callback'); default: (realTypeAnnotation.type: | 'EnumDeclaration' @@ -184,14 +181,15 @@ function translateFunctionReturnTypeToJavaType( nullableReturnTypeAnnotation, ); - function wrapIntoNullableIfNeeded(generatedType: string) { + function wrapNullable(javaType: string, nullableType?: string) { if (nullable) { imports.add('javax.annotation.Nullable'); - return `@Nullable ${generatedType}`; + return `@Nullable ${nullableType ?? javaType}`; } - return generatedType; + return javaType; } + // FIXME: support class alias for args let realTypeAnnotation = returnTypeAnnotation; if (realTypeAnnotation.type === 'TypeAliasTypeAnnotation') { realTypeAnnotation = resolveAlias(realTypeAnnotation.name); @@ -201,7 +199,7 @@ function translateFunctionReturnTypeToJavaType( case 'ReservedTypeAnnotation': switch (realTypeAnnotation.name) { case 'RootTag': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); default: (realTypeAnnotation.name: empty); throw new Error(createErrorMessage(realTypeAnnotation.name)); @@ -211,35 +209,35 @@ function translateFunctionReturnTypeToJavaType( case 'PromiseTypeAnnotation': return 'void'; case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); + return wrapNullable('String'); case 'NumberTypeAnnotation': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'FloatTypeAnnotation': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'DoubleTypeAnnotation': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'Int32TypeAnnotation': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'BooleanTypeAnnotation': - return nullable ? 'Boolean' : 'boolean'; + return wrapNullable('boolean', 'Boolean'); case 'EnumDeclaration': switch (realTypeAnnotation.memberType) { case 'NumberTypeAnnotation': - return nullable ? 'Double' : 'double'; + return wrapNullable('double', 'Double'); case 'StringTypeAnnotation': - return wrapIntoNullableIfNeeded('String'); + return wrapNullable('String'); default: throw new Error(createErrorMessage(realTypeAnnotation.type)); } case 'ObjectTypeAnnotation': imports.add('com.facebook.react.bridge.WritableMap'); - return wrapIntoNullableIfNeeded('WritableMap'); + return wrapNullable('WritableMap'); case 'GenericObjectTypeAnnotation': imports.add('com.facebook.react.bridge.WritableMap'); - return wrapIntoNullableIfNeeded('WritableMap'); + return wrapNullable('WritableMap'); case 'ArrayTypeAnnotation': imports.add('com.facebook.react.bridge.WritableArray'); - return wrapIntoNullableIfNeeded('WritableArray'); + return wrapNullable('WritableArray'); default: (realTypeAnnotation.type: | 'EnumDeclaration' diff --git a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap index 473878ebefa929..159c207e5d0814 100644 --- a/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap +++ b/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleJavaSpec-test.js.snap @@ -78,7 +78,7 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo @ReactMethod @DoNotStrip - public void optionalMethod(ReadableMap options, Callback callback, ReadableArray extras) {} + public void optionalMethod(ReadableMap options, Callback callback, @Nullable ReadableArray extras) {} @ReactMethod @DoNotStrip @@ -379,7 +379,7 @@ public abstract class NativeSampleTurboModuleSpec extends ReactContextBaseJavaMo @ReactMethod @DoNotStrip - public abstract void getValueWithOptionalArg(ReadableMap parameter, Promise promise); + public abstract void getValueWithOptionalArg(@Nullable ReadableMap parameter, Promise promise); @ReactMethod(isBlockingSynchronousMethod = true) @DoNotStrip From 62244d4a1ef26113f5dc94828c731d27dbbd889d Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Mon, 7 Nov 2022 06:14:38 -0800 Subject: [PATCH 151/169] chore: Extract codegen translateFunctionTypeAnnotation into a common function (#35182) Summary: This PR extracts the codegen `translateFunctionTypeAnnotation` Flow and TypeScript functions into a single common function in the `parsers-primitives.js` file that can be used by both parsers as requested on https://github.com/facebook/react-native/issues/34872. ## Changelog [Internal] [Changed] - Extract codegen `translateFunctionTypeAnnotation` into a common function in the` parsers-primitives.js` file Pull Request resolved: https://github.com/facebook/react-native/pull/35182 Test Plan: Run `yarn jest react-native-codegen` and ensure CI is green ![image](https://user-images.githubusercontent.com/11707729/199625849-e89b647f-63fb-40f8-b643-a59dedb4c59a.png) Reviewed By: cortinico Differential Revision: D41030544 Pulled By: rshest fbshipit-source-id: bc93c21e31ed4e8c3293cafe3d808d9f36cf8ecc --- .../src/parsers/flow/modules/index.js | 97 +----------- .../src/parsers/parsers-primitives.js | 148 +++++++++++++++++- .../src/parsers/typescript/modules/index.js | 105 +------------ 3 files changed, 158 insertions(+), 192 deletions(-) diff --git a/packages/react-native-codegen/src/parsers/flow/modules/index.js b/packages/react-native-codegen/src/parsers/flow/modules/index.js index ee7842bdb51430..5c2538adf7c341 100644 --- a/packages/react-native-codegen/src/parsers/flow/modules/index.js +++ b/packages/react-native-codegen/src/parsers/flow/modules/index.js @@ -51,6 +51,7 @@ const { emitStringish, emitMixedTypeAnnotation, typeAliasResolution, + translateFunctionTypeAnnotation, } = require('../../parsers-primitives'); const { @@ -355,6 +356,8 @@ function translateTypeAnnotation( aliasMap, tryParse, cxxOnly, + translateTypeAnnotation, + language, ); return emitFunction(nullable, translateFunctionTypeAnnotationValue); } @@ -385,98 +388,6 @@ function translateTypeAnnotation( } } -function translateFunctionTypeAnnotation( - hasteModuleName: string, - // TODO(T71778680): This is a FunctionTypeAnnotation. Type this. - flowFunctionTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModuleFunctionTypeAnnotation { - type Param = NamedShape>; - const params: Array = []; - - for (const flowParam of (flowFunctionTypeAnnotation.params: $ReadOnlyArray<$FlowFixMe>)) { - const parsedParam = tryParse(() => { - if (flowParam.name == null) { - throw new UnnamedFunctionParamParserError( - flowParam, - hasteModuleName, - language, - ); - } - - const paramName = flowParam.name.name; - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - flowParam.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - paramTypeAnnotation.type === 'VoidTypeAnnotation' || - paramTypeAnnotation.type === 'PromiseTypeAnnotation' - ) { - return throwIfUnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - flowParam.typeAnnotation, - paramName, - paramTypeAnnotation.type, - ); - } - - return { - name: flowParam.name.name, - optional: flowParam.optional, - typeAnnotation: wrapNullable( - isParamTypeAnnotationNullable, - paramTypeAnnotation, - ), - }; - }); - - if (parsedParam != null) { - params.push(parsedParam); - } - } - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - flowFunctionTypeAnnotation.returnType, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - hasteModuleName, - flowFunctionTypeAnnotation, - 'FunctionTypeAnnotation', - language, - cxxOnly, - returnTypeAnnotation.type, - ); - - return { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: wrapNullable( - isReturnTypeAnnotationNullable, - returnTypeAnnotation, - ), - params, - }; -} - function buildPropertySchema( hasteModuleName: string, // TODO(T71778680): This is an ObjectTypeProperty containing either: @@ -516,6 +427,8 @@ function buildPropertySchema( aliasMap, tryParse, cxxOnly, + translateTypeAnnotation, + language, ), ), }; diff --git a/packages/react-native-codegen/src/parsers/parsers-primitives.js b/packages/react-native-codegen/src/parsers/parsers-primitives.js index 7ccfebc293a2f8..0d845ddbb7cea8 100644 --- a/packages/react-native-codegen/src/parsers/parsers-primitives.js +++ b/packages/react-native-codegen/src/parsers/parsers-primitives.js @@ -28,11 +28,25 @@ import type { StringTypeAnnotation, VoidTypeAnnotation, NativeModuleFloatTypeAnnotation, + NativeModuleParamTypeAnnotation, + NamedShape, } from '../CodegenSchema'; import type {ParserType} from './errors'; -import type {TypeAliasResolutionStatus} from './utils'; +import type { + ParserErrorCapturer, + TypeAliasResolutionStatus, + TypeDeclarationMap, +} from './utils'; + +const {UnnamedFunctionParamParserError} = require('./errors'); const { + throwIfUnsupportedFunctionParamTypeAnnotationParserError, + throwIfUnsupportedFunctionReturnTypeAnnotationParserError, +} = require('./error-utils'); + +const { + unwrapNullable, wrapNullable, assertGenericTypeAnnotationHasExactlyOneTypeParameter, } = require('./parsers-commons'); @@ -190,6 +204,137 @@ function emitFloat( }); } +function getTypeAnnotationParameters( + typeAnnotation: $FlowFixMe, + language: ParserType, +): $ReadOnlyArray<$FlowFixMe> { + return language === 'Flow' + ? typeAnnotation.params + : typeAnnotation.parameters; +} + +function getFunctionNameFromParameter( + param: NamedShape>, + language: ParserType, +) { + return language === 'Flow' ? param.name : param.typeAnnotation; +} + +function getParameterName(param: $FlowFixMe, language: ParserType): string { + return language === 'Flow' ? param.name.name : param.name; +} + +function getParameterTypeAnnotation(param: $FlowFixMe, language: ParserType) { + return language === 'Flow' + ? param.typeAnnotation + : param.typeAnnotation.typeAnnotation; +} + +function getTypeAnnotationReturnType( + typeAnnotation: $FlowFixMe, + language: ParserType, +) { + return language === 'Flow' + ? typeAnnotation.returnType + : typeAnnotation.typeAnnotation.typeAnnotation; +} + +function translateFunctionTypeAnnotation( + hasteModuleName: string, + // TODO(T108222691): Use flow-types for @babel/parser + // TODO(T71778680): This is a FunctionTypeAnnotation. Type this. + typeAnnotation: $FlowFixMe, + types: TypeDeclarationMap, + aliasMap: {...NativeModuleAliasMap}, + tryParse: ParserErrorCapturer, + cxxOnly: boolean, + translateTypeAnnotation: $FlowFixMe, + language: ParserType, +): NativeModuleFunctionTypeAnnotation { + type Param = NamedShape>; + const params: Array = []; + + for (const param of getTypeAnnotationParameters(typeAnnotation, language)) { + const parsedParam = tryParse(() => { + if (getFunctionNameFromParameter(param, language) == null) { + throw new UnnamedFunctionParamParserError( + param, + hasteModuleName, + language, + ); + } + + const paramName = getParameterName(param, language); + + const [paramTypeAnnotation, isParamTypeAnnotationNullable] = + unwrapNullable( + translateTypeAnnotation( + hasteModuleName, + getParameterTypeAnnotation(param, language), + types, + aliasMap, + tryParse, + cxxOnly, + ), + ); + + if ( + paramTypeAnnotation.type === 'VoidTypeAnnotation' || + paramTypeAnnotation.type === 'PromiseTypeAnnotation' + ) { + return throwIfUnsupportedFunctionParamTypeAnnotationParserError( + hasteModuleName, + param.typeAnnotation, + paramName, + paramTypeAnnotation.type, + ); + } + + return { + name: paramName, + optional: Boolean(param.optional), + typeAnnotation: wrapNullable( + isParamTypeAnnotationNullable, + paramTypeAnnotation, + ), + }; + }); + + if (parsedParam != null) { + params.push(parsedParam); + } + } + + const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = unwrapNullable( + translateTypeAnnotation( + hasteModuleName, + getTypeAnnotationReturnType(typeAnnotation, language), + types, + aliasMap, + tryParse, + cxxOnly, + ), + ); + + throwIfUnsupportedFunctionReturnTypeAnnotationParserError( + hasteModuleName, + typeAnnotation, + 'FunctionTypeAnnotation', + language, + cxxOnly, + returnTypeAnnotation.type, + ); + + return { + type: 'FunctionTypeAnnotation', + returnTypeAnnotation: wrapNullable( + isReturnTypeAnnotationNullable, + returnTypeAnnotation, + ), + params, + }; +} + module.exports = { emitBoolean, emitDouble, @@ -205,4 +350,5 @@ module.exports = { emitStringish, emitMixedTypeAnnotation, typeAliasResolution, + translateFunctionTypeAnnotation, }; diff --git a/packages/react-native-codegen/src/parsers/typescript/modules/index.js b/packages/react-native-codegen/src/parsers/typescript/modules/index.js index 045b4d6df07263..e58366297b16f9 100644 --- a/packages/react-native-codegen/src/parsers/typescript/modules/index.js +++ b/packages/react-native-codegen/src/parsers/typescript/modules/index.js @@ -16,7 +16,6 @@ import type { NativeModuleArrayTypeAnnotation, NativeModuleBaseTypeAnnotation, NativeModuleFunctionTypeAnnotation, - NativeModuleParamTypeAnnotation, NativeModulePropertyShape, NativeModuleSchema, Nullable, @@ -26,10 +25,7 @@ import type {ParserErrorCapturer, TypeDeclarationMap} from '../../utils'; import type {NativeModuleTypeAnnotation} from '../../../CodegenSchema.js'; const {nullGuard} = require('../../parsers-utils'); -const { - throwIfMoreThanOneModuleRegistryCalls, - throwIfUnsupportedFunctionParamTypeAnnotationParserError, -} = require('../../error-utils'); +const {throwIfMoreThanOneModuleRegistryCalls} = require('../../error-utils'); const {visit, isModuleRegistryCall} = require('../../utils'); const {resolveTypeAnnotation, getTypes} = require('../utils.js'); const { @@ -54,9 +50,9 @@ const { emitStringish, emitMixedTypeAnnotation, typeAliasResolution, + translateFunctionTypeAnnotation, } = require('../../parsers-primitives'); const { - UnnamedFunctionParamParserError, UnsupportedArrayElementTypeAnnotationParserError, UnsupportedGenericParserError, UnsupportedTypeAnnotationParserError, @@ -76,7 +72,6 @@ const { throwIfWrongNumberOfCallExpressionArgs, throwIfMoreThanOneModuleInterfaceParserError, throwIfIncorrectModuleRegistryCallTypeParameterParserError, - throwIfUnsupportedFunctionReturnTypeAnnotationParserError, } = require('../../error-utils'); const {TypeScriptParser} = require('../parser'); @@ -367,6 +362,8 @@ function translateTypeAnnotation( aliasMap, tryParse, cxxOnly, + translateTypeAnnotation, + language, ); return emitFunction(nullable, translateFunctionTypeAnnotationValue); @@ -398,98 +395,6 @@ function translateTypeAnnotation( } } -function translateFunctionTypeAnnotation( - hasteModuleName: string, - // TODO(T108222691): Use flow-types for @babel/parser - typescriptFunctionTypeAnnotation: $FlowFixMe, - types: TypeDeclarationMap, - aliasMap: {...NativeModuleAliasMap}, - tryParse: ParserErrorCapturer, - cxxOnly: boolean, -): NativeModuleFunctionTypeAnnotation { - type Param = NamedShape>; - const params: Array = []; - - for (const typeScriptParam of (typescriptFunctionTypeAnnotation.parameters: $ReadOnlyArray<$FlowFixMe>)) { - const parsedParam = tryParse(() => { - if (typeScriptParam.typeAnnotation == null) { - throw new UnnamedFunctionParamParserError( - typeScriptParam, - hasteModuleName, - language, - ); - } - - const paramName = typeScriptParam.name; - const [paramTypeAnnotation, isParamTypeAnnotationNullable] = - unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - typeScriptParam.typeAnnotation.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - if ( - paramTypeAnnotation.type === 'VoidTypeAnnotation' || - paramTypeAnnotation.type === 'PromiseTypeAnnotation' - ) { - return throwIfUnsupportedFunctionParamTypeAnnotationParserError( - hasteModuleName, - typeScriptParam.typeAnnotation, - paramName, - paramTypeAnnotation.type, - ); - } - - return { - name: typeScriptParam.name, - optional: Boolean(typeScriptParam.optional), - typeAnnotation: wrapNullable( - isParamTypeAnnotationNullable, - paramTypeAnnotation, - ), - }; - }); - - if (parsedParam != null) { - params.push(parsedParam); - } - } - - const [returnTypeAnnotation, isReturnTypeAnnotationNullable] = unwrapNullable( - translateTypeAnnotation( - hasteModuleName, - typescriptFunctionTypeAnnotation.typeAnnotation.typeAnnotation, - types, - aliasMap, - tryParse, - cxxOnly, - ), - ); - - throwIfUnsupportedFunctionReturnTypeAnnotationParserError( - hasteModuleName, - typescriptFunctionTypeAnnotation, - 'FunctionTypeAnnotation', - language, - cxxOnly, - returnTypeAnnotation.type, - ); - - return { - type: 'FunctionTypeAnnotation', - returnTypeAnnotation: wrapNullable( - isReturnTypeAnnotationNullable, - returnTypeAnnotation, - ), - params, - }; -} - function buildPropertySchema( hasteModuleName: string, // TODO(T108222691): Use flow-types for @babel/parser @@ -527,6 +432,8 @@ function buildPropertySchema( aliasMap, tryParse, cxxOnly, + translateTypeAnnotation, + language, ), ), }; From 38e35df47c59e425fdac34d1f91540b8b8ca2908 Mon Sep 17 00:00:00 2001 From: Thibault Malbranche Date: Mon, 7 Nov 2022 06:30:33 -0800 Subject: [PATCH 152/169] chore: fix typo in build.gradle (#35209) Summary: ## Changelog [Android] [Fixed] - fixed typo in template build.gradle Pull Request resolved: https://github.com/facebook/react-native/pull/35209 Reviewed By: cipolleschi Differential Revision: D41080347 Pulled By: cortinico fbshipit-source-id: d2e36f232f798a636f98843edbc5651730125fc4 --- template/android/app/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/template/android/app/build.gradle b/template/android/app/build.gradle index 23a5e50e3abf4d..db242847621b2c 100644 --- a/template/android/app/build.gradle +++ b/template/android/app/build.gradle @@ -12,9 +12,9 @@ react { // The root of your project, i.e. where "package.json" lives. Default is '..' // root = file("../") // The folder where the react-native NPM package is. Default is ../node_modules/react-native - // reactNativeDir = file("../node-modules/react-native") + // reactNativeDir = file("../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen - // codegenDir = file("../node-modules/react-native-codegen") + // codegenDir = file("../node_modules/react-native-codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js // cliFile = file("../node_modules/react-native/cli.js") From 78844458dce01d598baf9dcbc4a0554ac4eae306 Mon Sep 17 00:00:00 2001 From: Samuel Susla Date: Mon, 7 Nov 2022 06:52:28 -0800 Subject: [PATCH 153/169] React Native sync for revisions ab075a2...4bd245e MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: This sync includes the following changes: - **[4bd245e9e](https://github.com/facebook/react/commit/4bd245e9e )**: Do not unmount layout effects if ancestor Offscreen is hidden ([#25628](https://github.com/facebook/react/pull/25628)) //// - **[df61e708c](https://github.com/facebook/react/commit/df61e708c )**: Remove check in renderDidSuspendDelayIfPossible ([#25630](https://github.com/facebook/react/pull/25630)) //// - **[1a08f1478](https://github.com/facebook/react/commit/1a08f1478 )**: [ServerRenderer] Move fizz external runtime implementation to react-dom-bindings ([#25617](https://github.com/facebook/react/pull/25617)) //// - **[1a902623a](https://github.com/facebook/react/commit/1a902623a )**: Unwrap sync resolved thenables without suspending ([#25615](https://github.com/facebook/react/pull/25615)) //// - **[4ea063b56](https://github.com/facebook/react/commit/4ea063b56 )**: refactor isHostResourceType to not receive the context from reconciler and not leak types ([#25610](https://github.com/facebook/react/pull/25610)) //// - **[8e69bc45a](https://github.com/facebook/react/commit/8e69bc45a )**: Make host context use null as empty and only error in dev ([#25609](https://github.com/facebook/react/pull/25609)) //// - **[5f7ef8c4c](https://github.com/facebook/react/commit/5f7ef8c4c )**: [Float] handle resource Resource creation inside svg context ([#25599](https://github.com/facebook/react/pull/25599)) //// - **[36426e6cb](https://github.com/facebook/react/commit/36426e6cb )**: Allow uncached IO to stablize ([#25561](https://github.com/facebook/react/pull/25561)) //// - **[6883d7944](https://github.com/facebook/react/commit/6883d7944 )**: [ServerRenderer] Setup for adding data attributes streaming format ([#25567](https://github.com/facebook/react/pull/25567)) //// Changelog: [General][Changed] - React Native sync for revisions ab075a2...4bd245e jest_e2e[run_all_tests] Reviewed By: GijsWeterings Differential Revision: D41028209 fbshipit-source-id: a67fdcd441ddd50784f7c1ce402eaecdb5e3126d --- Libraries/Renderer/REVISION | 2 +- .../implementations/ReactNativeRenderer.d.ts | 149 ------------------ .../Renderer/shims/ReactNativeTypes.d.ts | 141 ----------------- 3 files changed, 1 insertion(+), 291 deletions(-) delete mode 100644 Libraries/Renderer/implementations/ReactNativeRenderer.d.ts delete mode 100644 Libraries/Renderer/shims/ReactNativeTypes.d.ts diff --git a/Libraries/Renderer/REVISION b/Libraries/Renderer/REVISION index 21e513e87f3c70..c6b54e2eb29883 100644 --- a/Libraries/Renderer/REVISION +++ b/Libraries/Renderer/REVISION @@ -1 +1 @@ -ab075a232409ea1f566526c6a5dca30f658280de \ No newline at end of file +4bd245e9ee22458bcd5b68524c47eaaab2cf2058 \ No newline at end of file diff --git a/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts b/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts deleted file mode 100644 index 2624d4a78ce01d..00000000000000 --- a/Libraries/Renderer/implementations/ReactNativeRenderer.d.ts +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import {GestureResponderEvent} from '../../Types/CoreEventTypes'; - -/** - * Gesture recognition on mobile devices is much more complicated than web. - * A touch can go through several phases as the app determines what the user's intention is. - * For example, the app needs to determine if the touch is scrolling, sliding on a widget, or tapping. - * This can even change during the duration of a touch. There can also be multiple simultaneous touches. - * - * The touch responder system is needed to allow components to negotiate these touch interactions - * without any additional knowledge about their parent or child components. - * This system is implemented in ResponderEventPlugin.js, which contains further details and documentation. - * - * Best Practices - * Users can feel huge differences in the usability of web apps vs. native, and this is one of the big causes. - * Every action should have the following attributes: - * Feedback/highlighting- show the user what is handling their touch, and what will happen when they release the gesture - * Cancel-ability- when making an action, the user should be able to abort it mid-touch by dragging their finger away - * - * These features make users more comfortable while using an app, - * because it allows people to experiment and interact without fear of making mistakes. - * - * TouchableHighlight and Touchable* - * The responder system can be complicated to use. - * So we have provided an abstract Touchable implementation for things that should be "tappable". - * This uses the responder system and allows you to easily configure tap interactions declaratively. - * Use TouchableHighlight anywhere where you would use a button or link on web. - */ -export interface GestureResponderHandlers { - /** - * A view can become the touch responder by implementing the correct negotiation methods. - * There are two methods to ask the view if it wants to become responder: - */ - - /** - * Does this view want to become responder on the start of a touch? - */ - onStartShouldSetResponder?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * Called for every touch move on the View when it is not the responder: does this view want to "claim" touch responsiveness? - */ - onMoveShouldSetResponder?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * If the View returns true and attempts to become the responder, one of the following will happen: - */ - - onResponderEnd?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * The View is now responding for touch events. - * This is the time to highlight and show the user what is happening - */ - onResponderGrant?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Something else is the responder right now and will not release it - */ - onResponderReject?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * If the view is responding, the following handlers can be called: - */ - - /** - * The user is moving their finger - */ - onResponderMove?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Fired at the end of the touch, ie "touchUp" - */ - onResponderRelease?: ((event: GestureResponderEvent) => void) | undefined; - - onResponderStart?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * Something else wants to become responder. - * Should this view release the responder? Returning true allows release - */ - onResponderTerminationRequest?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * The responder has been taken from the View. - * Might be taken by other views after a call to onResponderTerminationRequest, - * or might be taken by the OS without asking (happens with control center/ notification center on iOS) - */ - onResponderTerminate?: ((event: GestureResponderEvent) => void) | undefined; - - /** - * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, - * where the deepest node is called first. - * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. - * This is desirable in most cases, because it makes sure all controls and buttons are usable. - * - * However, sometimes a parent will want to make sure that it becomes responder. - * This can be handled by using the capture phase. - * Before the responder system bubbles up from the deepest component, - * it will do a capture phase, firing on*ShouldSetResponderCapture. - * So if a parent View wants to prevent the child from becoming responder on a touch start, - * it should have a onStartShouldSetResponderCapture handler which returns true. - */ - onStartShouldSetResponderCapture?: - | ((event: GestureResponderEvent) => boolean) - | undefined; - - /** - * onStartShouldSetResponder and onMoveShouldSetResponder are called with a bubbling pattern, - * where the deepest node is called first. - * That means that the deepest component will become responder when multiple Views return true for *ShouldSetResponder handlers. - * This is desirable in most cases, because it makes sure all controls and buttons are usable. - * - * However, sometimes a parent will want to make sure that it becomes responder. - * This can be handled by using the capture phase. - * Before the responder system bubbles up from the deepest component, - * it will do a capture phase, firing on*ShouldSetResponderCapture. - * So if a parent View wants to prevent the child from becoming responder on a touch start, - * it should have a onStartShouldSetResponderCapture handler which returns true. - */ - onMoveShouldSetResponderCapture?: - | ((event: GestureResponderEvent) => boolean) - | undefined; -} - -/** - * React Native also implements unstable_batchedUpdates - */ -export function unstable_batchedUpdates( - callback: (a: A, b: B) => any, - a: A, - b: B, -): void; -export function unstable_batchedUpdates(callback: (a: A) => any, a: A): void; -export function unstable_batchedUpdates(callback: () => any): void; diff --git a/Libraries/Renderer/shims/ReactNativeTypes.d.ts b/Libraries/Renderer/shims/ReactNativeTypes.d.ts deleted file mode 100644 index 38e00e1cc933ca..00000000000000 --- a/Libraries/Renderer/shims/ReactNativeTypes.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - * - * @format - */ - -import type * as React from 'react'; - -export type MeasureOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, - pageX: number, - pageY: number, -) => void; - -export type MeasureInWindowOnSuccessCallback = ( - x: number, - y: number, - width: number, - height: number, -) => void; - -export type MeasureLayoutOnSuccessCallback = ( - left: number, - top: number, - width: number, - height: number, -) => void; - -/** - * NativeMethods provides methods to access the underlying native component directly. - * This can be useful in cases when you want to focus a view or measure its on-screen dimensions, - * for example. - * The methods described here are available on most of the default components provided by React Native. - * Note, however, that they are not available on composite components that aren't directly backed by a - * native view. This will generally include most components that you define in your own app. - * For more information, see [Direct Manipulation](https://reactnative.dev/docs/direct-manipulation). - * @see https://github.com/facebook/react-native/blob/master/Libraries/Renderer/shims/ReactNativeTypes.js#L87 - */ -export interface NativeMethods { - /** - * Determines the location on screen, width, and height of the given view and - * returns the values via an async callback. If successful, the callback will - * be called with the following arguments: - * - * - x - * - y - * - width - * - height - * - pageX - * - pageY - * - * Note that these measurements are not available until after the rendering - * has been completed in native. If you need the measurements as soon as - * possible, consider using the [`onLayout` - * prop](docs/view.html#onlayout) instead. - */ - measure(callback: MeasureOnSuccessCallback): void; - - /** - * Determines the location of the given view in the window and returns the - * values via an async callback. If the React root view is embedded in - * another native view, this will give you the absolute coordinates. If - * successful, the callback will be called with the following - * arguments: - * - * - x - * - y - * - width - * - height - * - * Note that these measurements are not available until after the rendering - * has been completed in native. - */ - measureInWindow(callback: MeasureInWindowOnSuccessCallback): void; - - /** - * Like [`measure()`](#measure), but measures the view relative an ancestor, - * specified as `relativeToNativeComponentRef`. This means that the returned x, y - * are relative to the origin x, y of the ancestor view. - * _Can also be called with a relativeNativeNodeHandle but is deprecated._ - */ - measureLayout( - relativeToNativeComponentRef: HostComponent | number, - onSuccess: MeasureLayoutOnSuccessCallback, - onFail: () => void /* currently unused */, - ): void; - - /** - * This function sends props straight to native. They will not participate in - * future diff process - this means that if you do not include them in the - * next render, they will remain active (see [Direct - * Manipulation](https://reactnative.dev/docs/direct-manipulation)). - */ - setNativeProps(nativeProps: object): void; - - /** - * Requests focus for the given input or view. The exact behavior triggered - * will depend on the platform and type of view. - */ - focus(): void; - - /** - * Removes focus from an input or view. This is the opposite of `focus()`. - */ - blur(): void; - - refs: { - [key: string]: React.Component; - }; -} - -/** - * @deprecated Use NativeMethods instead. - */ -export type NativeMethodsMixin = NativeMethods; -/** - * @deprecated Use NativeMethods instead. - */ -export type NativeMethodsMixinType = NativeMethods; - -/** - * Represents a native component, such as those returned from `requireNativeComponent`. - * - * @see https://github.com/facebook/react-native/blob/v0.62.0-rc.5/Libraries/Renderer/shims/ReactNativeTypes.js - * - * @todo This should eventually be defined as an AbstractComponent, but that - * should first be introduced in the React typings. - */ -export interface HostComponent

- extends Pick< - React.ComponentClass

, - Exclude, 'new'> - > { - new (props: P, context?: any): React.Component

& Readonly; -} From d62b0b463b12d40a236edfa214537b29f4236eae Mon Sep 17 00:00:00 2001 From: Dmitry Rykun Date: Mon, 7 Nov 2022 06:57:35 -0800 Subject: [PATCH 154/169] Bump dependency versions to 0.72.0 after the branch cut Summary: Changelog [General][Changed] - Bump dependency versions to 0.72.0 after the branch cut. Reviewed By: cipolleschi Differential Revision: D41079762 fbshipit-source-id: 83e912c4eaf969c1673ccc5fa854646efa99fa4a --- package.json | 2 +- packages/babel-plugin-codegen/package.json | 2 +- packages/eslint-plugin-specs/package.json | 2 +- packages/hermes-inspector-msggen/package.json | 2 +- packages/react-native-codegen/package.json | 2 +- packages/react-native-gradle-plugin/package.json | 2 +- repo-config/package.json | 4 ++-- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 3bb9836aff8be1..618104ad75e7c3 100644 --- a/package.json +++ b/package.json @@ -132,7 +132,7 @@ "pretty-format": "^26.5.2", "promise": "^8.3.0", "react-devtools-core": "^4.26.1", - "react-native-gradle-plugin": "^0.71.8", + "react-native-gradle-plugin": "^0.72.0", "react-refresh": "^0.4.0", "react-shallow-renderer": "^16.15.0", "regenerator-runtime": "^0.13.2", diff --git a/packages/babel-plugin-codegen/package.json b/packages/babel-plugin-codegen/package.json index 9a06f6cfa73a25..2706e70e2fc327 100644 --- a/packages/babel-plugin-codegen/package.json +++ b/packages/babel-plugin-codegen/package.json @@ -1,5 +1,5 @@ { - "version": "0.71.1", + "version": "0.72.0", "name": "@react-native/babel-plugin-codegen", "description": "Babel plugin to generate native module and view manager code for React Native.", "repository": { diff --git a/packages/eslint-plugin-specs/package.json b/packages/eslint-plugin-specs/package.json index 2956a52d482ac7..b27d8d7bf2f78d 100644 --- a/packages/eslint-plugin-specs/package.json +++ b/packages/eslint-plugin-specs/package.json @@ -1,6 +1,6 @@ { "name": "@react-native/eslint-plugin-specs", - "version": "0.71.1", + "version": "0.72.0", "description": "ESLint rules to validate NativeModule and Component Specs", "main": "index.js", "repository": { diff --git a/packages/hermes-inspector-msggen/package.json b/packages/hermes-inspector-msggen/package.json index add61d46ca79eb..445905497edf46 100644 --- a/packages/hermes-inspector-msggen/package.json +++ b/packages/hermes-inspector-msggen/package.json @@ -1,7 +1,7 @@ { "name": "@react-native/hermes-inspector-msggen", "private": true, - "version": "0.71.1", + "version": "0.72.0", "license": "MIT", "bin": { "msggen": "./bin/index.js" diff --git a/packages/react-native-codegen/package.json b/packages/react-native-codegen/package.json index 7e268a7bcc959e..3dfa85fe9a7cf6 100644 --- a/packages/react-native-codegen/package.json +++ b/packages/react-native-codegen/package.json @@ -1,6 +1,6 @@ { "name": "react-native-codegen", - "version": "0.71.2", + "version": "0.72.0", "description": "⚛️ Code generation tools for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen", "repository": { diff --git a/packages/react-native-gradle-plugin/package.json b/packages/react-native-gradle-plugin/package.json index 6338d040198037..aeff3bfcc02822 100644 --- a/packages/react-native-gradle-plugin/package.json +++ b/packages/react-native-gradle-plugin/package.json @@ -1,6 +1,6 @@ { "name": "react-native-gradle-plugin", - "version": "0.71.8", + "version": "0.72.0", "description": "⚛️ Gradle Plugin for React Native", "homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-gradle-plugin", "repository": { diff --git a/repo-config/package.json b/repo-config/package.json index 94a78ed7440614..603ea922439d49 100644 --- a/repo-config/package.json +++ b/repo-config/package.json @@ -16,7 +16,7 @@ "@definitelytyped/dtslint": "^0.0.127", "@react-native-community/eslint-config": "*", "@react-native-community/eslint-plugin": "*", - "@react-native/eslint-plugin-specs": "^0.71.1", + "@react-native/eslint-plugin-specs": "^0.72.0", "@reactions/component": "^2.0.2", "@types/react": "^18.0.18", "@typescript-eslint/parser": "^5.30.5", @@ -47,7 +47,7 @@ "mkdirp": "^0.5.1", "prettier": "^2.4.1", "react": "18.2.0", - "react-native-codegen": "^0.71.2", + "react-native-codegen": "^0.72.0", "react-test-renderer": "18.2.0", "shelljs": "^0.8.5", "signedsource": "^1.0.0", From 7203187c808531b279ba9a9e2e73748c4254cbb6 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Nov 2022 07:24:11 -0800 Subject: [PATCH 155/169] TurboModules: Simplify React-bridging usage (#35212) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35212 A previous change - https://github.com/facebook/react-native/pull/34011 - already fixed basic usage of Any other header besides from header via the React-Codegen CocoaPod. Hence adding bridging now as a sub-spec to the ReactCommon CocoaPod Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D41057878 fbshipit-source-id: 83c117bc5252d84dd419cdb72f145f65547d23b2 --- ReactCommon/React-bridging.podspec | 43 --------------- ReactCommon/ReactCommon.podspec | 11 +++- .../cocoapods/__tests__/codegen_utils-test.rb | 1 + .../__tests__/new_architecture-test.rb | 1 + scripts/cocoapods/__tests__/utils-test.rb | 54 ------------------- scripts/cocoapods/codegen_utils.rb | 5 +- scripts/cocoapods/new_architecture.rb | 1 + scripts/cocoapods/utils.rb | 12 ----- scripts/react_native_pods.rb | 2 - 9 files changed, 15 insertions(+), 115 deletions(-) delete mode 100644 ReactCommon/React-bridging.podspec diff --git a/ReactCommon/React-bridging.podspec b/ReactCommon/React-bridging.podspec deleted file mode 100644 index 660d0efdd9deb5..00000000000000 --- a/ReactCommon/React-bridging.podspec +++ /dev/null @@ -1,43 +0,0 @@ -# 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. - -require "json" - -package = JSON.parse(File.read(File.join(__dir__, "..", "package.json"))) -version = package['version'] - -source = { :git => 'https://github.com/facebook/react-native.git' } -if version == '1000.0.0' - # This is an unpublished version, use the latest commit hash of the react-native repo, which we’re presumably in. - source[:commit] = `git rev-parse HEAD`.strip if system("git rev-parse --git-dir > /dev/null 2>&1") -else - source[:tag] = "v#{version}" -end - -folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32 -Wno-gnu-zero-variadic-macro-arguments' -folly_version = '2021.07.22.00' - -Pod::Spec.new do |s| - s.name = "React-bridging" - s.version = version - s.summary = "-" # TODO - s.homepage = "https://reactnative.dev/" - s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" - s.platforms = { :ios => "12.4" } - s.source = source - s.source_files = "react/bridging/**/*.{cpp,h}" - s.exclude_files = "react/bridging/tests" - s.header_dir = "react/bridging" - s.header_mappings_dir = "." - s.compiler_flags = folly_compiler_flags - s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/RCT-Folly\"", - "USE_HEADERMAP" => "YES", - "CLANG_CXX_LANGUAGE_STANDARD" => "c++17", - "GCC_WARN_PEDANTIC" => "YES" } - - s.dependency "RCT-Folly", folly_version - s.dependency "React-jsi", version -end diff --git a/ReactCommon/ReactCommon.podspec b/ReactCommon/ReactCommon.podspec index 4cd4f04e59c31a..46af7c0411ba15 100644 --- a/ReactCommon/ReactCommon.podspec +++ b/ReactCommon/ReactCommon.podspec @@ -32,7 +32,7 @@ Pod::Spec.new do |s| s.source = source s.header_dir = "ReactCommon" # Use global header_dir for all subspecs for use_frameworks! compatibility s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags - s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/Headers/Private/React-Core\" \"$(PODS_ROOT)/Headers/Private/React-bridging/react/bridging\" \"$(PODS_CONFIGURATION_BUILD_DIR)/React-bridging/react_bridging.framework/Headers\"", + s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/DoubleConversion\" \"$(PODS_ROOT)/Headers/Private/React-Core\"", "USE_HEADERMAP" => "YES", "CLANG_CXX_LANGUAGE_STANDARD" => "c++17", "GCC_WARN_PEDANTIC" => "YES" } @@ -40,7 +40,6 @@ Pod::Spec.new do |s| # TODO (T48588859): Restructure this target to align with dir structure: "react/nativemodule/..." # Note: Update this only when ready to minimize breaking changes. s.subspec "turbomodule" do |ss| - ss.dependency "React-bridging", version ss.dependency "React-callinvoker", version ss.dependency "React-perflogger", version ss.dependency "React-Core", version @@ -51,6 +50,14 @@ Pod::Spec.new do |s| ss.dependency "DoubleConversion" ss.dependency "glog" + ss.subspec "bridging" do |sss| + sss.dependency "React-jsi", version + sss.source_files = "react/bridging/**/*.{cpp,h}" + sss.exclude_files = "react/bridging/tests" + sss.header_dir = "react/bridging" + sss.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_TARGET_SRCROOT)/ReactCommon\" \"$(PODS_ROOT)/RCT-Folly\"" } + end + ss.subspec "core" do |sss| sss.source_files = "react/nativemodule/core/ReactCommon/**/*.{cpp,h}", "react/nativemodule/core/platform/ios/**/*.{mm,cpp,h}" diff --git a/scripts/cocoapods/__tests__/codegen_utils-test.rb b/scripts/cocoapods/__tests__/codegen_utils-test.rb index 69a5f8c2dc0b35..989b7e87857788 100644 --- a/scripts/cocoapods/__tests__/codegen_utils-test.rb +++ b/scripts/cocoapods/__tests__/codegen_utils-test.rb @@ -466,6 +466,7 @@ def get_podspec_no_fabric_no_script "React-Core": ["99.98.97"], "React-jsi": ["99.98.97"], "hermes-engine": ["99.98.97"], + "ReactCommon/turbomodule/bridging": ["99.98.97"], "ReactCommon/turbomodule/core": ["99.98.97"] } } diff --git a/scripts/cocoapods/__tests__/new_architecture-test.rb b/scripts/cocoapods/__tests__/new_architecture-test.rb index 2f1c3cad1aa5ba..98ceecdc37a3a1 100644 --- a/scripts/cocoapods/__tests__/new_architecture-test.rb +++ b/scripts/cocoapods/__tests__/new_architecture-test.rb @@ -134,6 +134,7 @@ def test_installModulesDependencies_whenNewArchEnabledAndNewArchAndNoSearchPaths { :dependency_name => "React-Codegen" }, { :dependency_name => "RCTRequired" }, { :dependency_name => "RCTTypeSafety" }, + { :dependency_name => "ReactCommon/turbomodule/bridging" }, { :dependency_name => "ReactCommon/turbomodule/core" } ]) end diff --git a/scripts/cocoapods/__tests__/utils-test.rb b/scripts/cocoapods/__tests__/utils-test.rb index 76d316505ebe0e..429055cf4ca28b 100644 --- a/scripts/cocoapods/__tests__/utils-test.rb +++ b/scripts/cocoapods/__tests__/utils-test.rb @@ -328,60 +328,6 @@ def test_fixLibrarySearchPaths_correctlySetsTheSearchPathsForAllProjects assert_equal(pods_projects_mock.save_invocation_count, 1) end - # ============================================= # - # Test - Fix React-bridging Header Search Paths # - # ============================================= # - - def test_fixReactBridgingHeaderSearchPaths_correctlySetsTheHeaderSearchPathsForAllTargets - # Arrange - first_target = prepare_target("FirstTarget") - second_target = prepare_target("SecondTarget") - third_target = TargetMock.new("ThirdTarget", [ - BuildConfigurationMock.new("Debug", { - "HEADER_SEARCH_PATHS" => '$(inherited) "${PODS_ROOT}/Headers/Public" ' - }), - BuildConfigurationMock.new("Release", { - "HEADER_SEARCH_PATHS" => '$(inherited) "${PODS_ROOT}/Headers/Public" ' - }), - ], nil) - - user_project_mock = UserProjectMock.new("a/path", [ - prepare_config("Debug"), - prepare_config("Release"), - ], - :native_targets => [ - first_target, - second_target - ] - ) - pods_projects_mock = PodsProjectMock.new([], {"hermes-engine" => {}}, :native_targets => [ - third_target - ]) - installer = InstallerMock.new(pods_projects_mock, [ - AggregatedProjectMock.new(user_project_mock) - ]) - - # Act - ReactNativePodsUtils.fix_react_bridging_header_search_paths(installer) - - # Assert - first_target.build_configurations.each do |config| - assert_equal(config.build_settings["HEADER_SEARCH_PATHS"].strip, - '$(inherited) "$(PODS_ROOT)/Headers/Private/React-bridging/react/bridging" "$(PODS_CONFIGURATION_BUILD_DIR)/React-bridging/react_bridging.framework/Headers"' - ) - end - second_target.build_configurations.each do |config| - assert_equal(config.build_settings["HEADER_SEARCH_PATHS"].strip, - '$(inherited) "$(PODS_ROOT)/Headers/Private/React-bridging/react/bridging" "$(PODS_CONFIGURATION_BUILD_DIR)/React-bridging/react_bridging.framework/Headers"' - ) - end - third_target.build_configurations.each do |config| - assert_equal(config.build_settings["HEADER_SEARCH_PATHS"].strip, - '$(inherited) "${PODS_ROOT}/Headers/Public" "$(PODS_ROOT)/Headers/Private/React-bridging/react/bridging" "$(PODS_CONFIGURATION_BUILD_DIR)/React-bridging/react_bridging.framework/Headers"' - ) - end - end - # ===================================== # # Test - Apply Xcode14 React-Core patch # # ===================================== # diff --git a/scripts/cocoapods/codegen_utils.rb b/scripts/cocoapods/codegen_utils.rb index 608d9f210cfd4d..bd1c4648049eb9 100644 --- a/scripts/cocoapods/codegen_utils.rb +++ b/scripts/cocoapods/codegen_utils.rb @@ -98,13 +98,14 @@ def get_react_codegen_spec(package_json_file, folly_version: '2021.07.22.00', fa ].join(' ') }, 'dependencies': { - "FBReactNativeSpec": [version], - "React-jsiexecutor": [version], + "FBReactNativeSpec": [version], + "React-jsiexecutor": [version], "RCT-Folly": [folly_version], "RCTRequired": [version], "RCTTypeSafety": [version], "React-Core": [version], "React-jsi": [version], + "ReactCommon/turbomodule/bridging": [version], "ReactCommon/turbomodule/core": [version] } } diff --git a/scripts/cocoapods/new_architecture.rb b/scripts/cocoapods/new_architecture.rb index 5382b8fb2e5b80..0ce4b91f8b8f1f 100644 --- a/scripts/cocoapods/new_architecture.rb +++ b/scripts/cocoapods/new_architecture.rb @@ -87,6 +87,7 @@ def self.install_modules_dependencies(spec, new_arch_enabled, folly_version) spec.dependency "RCTRequired" spec.dependency "RCTTypeSafety" + spec.dependency "ReactCommon/turbomodule/bridging" spec.dependency "ReactCommon/turbomodule/core" end end diff --git a/scripts/cocoapods/utils.rb b/scripts/cocoapods/utils.rb index ffec05d27a79c1..dcf8642206498d 100644 --- a/scripts/cocoapods/utils.rb +++ b/scripts/cocoapods/utils.rb @@ -107,18 +107,6 @@ def self.fix_library_search_paths(installer) end end - def self.fix_react_bridging_header_search_paths(installer) - 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| - # For third party modules who have React-bridging dependency to search correct headers - config.build_settings['HEADER_SEARCH_PATHS'] ||= '$(inherited) ' - config.build_settings['HEADER_SEARCH_PATHS'] << '"$(PODS_ROOT)/Headers/Private/React-bridging/react/bridging" ' - config.build_settings['HEADER_SEARCH_PATHS'] << '"$(PODS_CONFIGURATION_BUILD_DIR)/React-bridging/react_bridging.framework/Headers" ' - end - end - end - def self.apply_mac_catalyst_patches(installer) # Fix bundle signing issues installer.pods_project.targets.each do |target| diff --git a/scripts/react_native_pods.rb b/scripts/react_native_pods.rb index 0a64c7b221e3e6..074965bfbd63a6 100644 --- a/scripts/react_native_pods.rb +++ b/scripts/react_native_pods.rb @@ -93,7 +93,6 @@ def use_react_native! ( pod 'React-RCTVibration', :path => "#{prefix}/Libraries/Vibration" pod 'React-Core/RCTWebSocket', :path => "#{prefix}/" - pod 'React-bridging', :path => "#{prefix}/ReactCommon" pod 'React-cxxreact', :path => "#{prefix}/ReactCommon/cxxreact" if hermes_enabled @@ -212,7 +211,6 @@ def react_native_post_install(installer, react_native_path = "../node_modules/re ReactNativePodsUtils.exclude_i386_architecture_while_using_hermes(installer) ReactNativePodsUtils.fix_library_search_paths(installer) - ReactNativePodsUtils.fix_react_bridging_header_search_paths(installer) ReactNativePodsUtils.set_node_modules_user_settings(installer, react_native_path) NewArchitectureHelper.set_clang_cxx_language_standard_if_needed(installer) From 6152763398efe60521fc86fcf992b6a84361df12 Mon Sep 17 00:00:00 2001 From: Robert Balicki Date: Mon, 7 Nov 2022 07:40:21 -0800 Subject: [PATCH 156/169] Buck, etc. changes that enable persisted, sync settings for DevTools (#35163) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35163 # What This diff contains all the changes from D40333083 (https://github.com/facebook/react-native/commit/0fac9817df403e31d8256befe52409c948614706) (aka https://github.com/facebook/react-native/pull/34964), **except** the change to `setUpReactDevTools.js`, which actually uses the new files. # Why * We want to ship the Buck, C++, etc. changes before the JavaScript changes that depend on those files. * Otherwise, apps can fail at startup with the message: ``` `TurboModuleRegistry.getEnforcing(...): '${name}' could not be found. ` + 'Verify that a module by this name is registered in the native binary.', ``` * Note that this only occurs if you are using a previously-built version of the C++, Obj C, etc. files in RN, but a more recent version of the JavaScript files. If you are building from matching sources, this does not occur. * After a few days, we can land the JS files. ## Changelog Changelog [General][Added] Add, but don't use, DevTools Settings Manager. Reviewed By: NickGerleman Differential Revision: D40873390 fbshipit-source-id: c7bac6ae65f85666b8616443db278ebb175b691b --- .../DevToolsSettingsManager.android.js | 13 +++++ .../DevToolsSettingsManager.ios.js | 33 +++++++++++++ .../NativeDevToolsSettingsManager.js | 22 +++++++++ React/CoreModules/BUCK | 1 + .../src/main/java/com/facebook/react/BUCK | 1 + .../react/modules/devtoolssettings/BUCK | 28 +++++++++++ .../DevToolsSettingsManagerModule.java | 49 +++++++++++++++++++ .../main/java/com/facebook/react/shell/BUCK | 1 + .../react/shell/MainReactPackage.java | 7 ++- .../test/java/com/facebook/react/modules/BUCK | 1 + 10 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.android.js create mode 100644 Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js create mode 100644 Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js create mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK create mode 100644 ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js new file mode 100644 index 00000000000000..262aafbcb0d69b --- /dev/null +++ b/Libraries/DevToolsSettings/DevToolsSettingsManager.android.js @@ -0,0 +1,13 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import NativeDevToolsSettingsManager from './NativeDevToolsSettingsManager'; + +module.exports = NativeDevToolsSettingsManager; diff --git a/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js b/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js new file mode 100644 index 00000000000000..fdc61730166bf4 --- /dev/null +++ b/Libraries/DevToolsSettings/DevToolsSettingsManager.ios.js @@ -0,0 +1,33 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {Spec} from './NativeDevToolsSettingsManager'; + +import Settings from '../Settings/Settings'; + +const CONSOLE_PATCH_SETTINGS_KEY = 'ReactDevTools::ConsolePatchSettings'; + +const DevToolsSettingsManager = { + setConsolePatchSettings: (newConsolePatchSettings: string) => { + Settings.set({ + [CONSOLE_PATCH_SETTINGS_KEY]: newConsolePatchSettings, + }); + }, + getConsolePatchSettings: () => { + const value = Settings.get(CONSOLE_PATCH_SETTINGS_KEY); + if (typeof value === 'string') { + // $FlowFixMe[unclear-type] + return ((value: any): string); + } + return null; + }, +}; + +module.exports = (DevToolsSettingsManager: Spec); diff --git a/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js b/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js new file mode 100644 index 00000000000000..904e8d6701c756 --- /dev/null +++ b/Libraries/DevToolsSettings/NativeDevToolsSettingsManager.js @@ -0,0 +1,22 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + * @format + */ + +import type {TurboModule} from '../TurboModule/RCTExport'; + +import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; + +export interface Spec extends TurboModule { + +setConsolePatchSettings: (newConsolePatchSettings: string) => void; + +getConsolePatchSettings: () => ?string; +} + +export default (TurboModuleRegistry.get( + 'DevToolsSettingsManager', +): ?Spec); diff --git a/React/CoreModules/BUCK b/React/CoreModules/BUCK index 143a840eff4138..9820c22ed4b943 100644 --- a/React/CoreModules/BUCK +++ b/React/CoreModules/BUCK @@ -134,6 +134,7 @@ rn_apple_library( "//xplat/js/react-native-github:FBReactNativeSpecApple", "//xplat/js/react-native-github:RCTLinkingApple", "//xplat/js/react-native-github:RCTPushNotificationApple", + "//xplat/js/react-native-github:RCTSettingsApple", "//xplat/js/react-native-github:ReactInternalApple", ], ) diff --git a/ReactAndroid/src/main/java/com/facebook/react/BUCK b/ReactAndroid/src/main/java/com/facebook/react/BUCK index dd21088699dab5..08f8c1176bc528 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/BUCK @@ -41,6 +41,7 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/appearance:appearance"), react_native_target("java/com/facebook/react/modules/bundleloader:bundleloader"), react_native_target("java/com/facebook/react/modules/debug:debug"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/fabric:fabric"), react_native_target("java/com/facebook/react/modules/debug:interfaces"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK new file mode 100644 index 00000000000000..50f0d888a9cdf4 --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/BUCK @@ -0,0 +1,28 @@ +load("//tools/build_defs/oss:rn_defs.bzl", "react_native_dep", "react_native_root_target", "react_native_target", "rn_android_library") + +rn_android_library( + name = "devtoolssettings", + srcs = glob(["**/*.java"]), + autoglob = False, + labels = [ + "pfh:ReactNative_CommonInfrastructurePlaceholder", + "supermodule:xplat/default/public.react_native.infra", + ], + language = "JAVA", + provided_deps = [ + react_native_dep("third-party/android/androidx:annotation"), + ], + visibility = [ + "PUBLIC", + ], + deps = [ + react_native_dep("libraries/fbcore/src/main/java/com/facebook/common/logging:logging"), + react_native_dep("third-party/java/infer-annotations:infer-annotations"), + react_native_dep("third-party/java/jsr-305:jsr-305"), + react_native_target("java/com/facebook/react/bridge:bridge"), + react_native_target("java/com/facebook/react/common:common"), + react_native_target("java/com/facebook/react/module/annotations:annotations"), + react_native_target("java/com/facebook/react/modules/core:core"), + ], + exported_deps = [react_native_root_target(":FBReactNativeSpec")], +) diff --git a/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java new file mode 100644 index 00000000000000..0164de2788292f --- /dev/null +++ b/ReactAndroid/src/main/java/com/facebook/react/modules/devtoolssettings/DevToolsSettingsManagerModule.java @@ -0,0 +1,49 @@ +/* + * 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.modules.devtoolssettings; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import androidx.annotation.Nullable; +import com.facebook.fbreact.specs.NativeDevToolsSettingsManagerSpec; +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.module.annotations.ReactModule; + +@ReactModule(name = DevToolsSettingsManagerModule.NAME) +public class DevToolsSettingsManagerModule extends NativeDevToolsSettingsManagerSpec { + public static final String NAME = "DevToolsSettingsManager"; + + private static final String SHARED_PREFERENCES_PREFIX = "ReactNative__DevToolsSettings"; + private static final String KEY_CONSOLE_PATCH_SETTINGS = "ConsolePatchSettings"; + + private final SharedPreferences mSharedPreferences; + + public DevToolsSettingsManagerModule(ReactApplicationContext reactContext) { + super(reactContext); + mSharedPreferences = + reactContext.getSharedPreferences(SHARED_PREFERENCES_PREFIX, Context.MODE_PRIVATE); + } + + @Override + public String getName() { + return NAME; + } + + @Override + public @Nullable String getConsolePatchSettings() { + return mSharedPreferences.getString(KEY_CONSOLE_PATCH_SETTINGS, null); + } + + @Override + public void setConsolePatchSettings(String newSettings) { + Editor editor = mSharedPreferences.edit(); + editor.putString(KEY_CONSOLE_PATCH_SETTINGS, newSettings); + editor.apply(); + } +} diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK index f6d575f9aff635..5ea6716012c739 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/BUCK @@ -37,6 +37,7 @@ rn_android_library( react_native_target("java/com/facebook/react/modules/clipboard:clipboard"), react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/fresco:fresco"), react_native_target("java/com/facebook/react/modules/i18nmanager:i18nmanager"), diff --git a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java index f845a46118cfd8..df4a46adacf91e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java +++ b/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java @@ -23,6 +23,7 @@ import com.facebook.react.modules.blob.FileReaderModule; import com.facebook.react.modules.camera.ImageStoreManager; import com.facebook.react.modules.clipboard.ClipboardModule; +import com.facebook.react.modules.devtoolssettings.DevToolsSettingsManagerModule; import com.facebook.react.modules.dialog.DialogModule; import com.facebook.react.modules.fresco.FrescoModule; import com.facebook.react.modules.i18nmanager.I18nManagerModule; @@ -141,6 +142,8 @@ public MainReactPackage(MainPackageConfig config) { return new VibrationModule(context); case WebSocketModule.NAME: return new WebSocketModule(context); + case DevToolsSettingsManagerModule.NAME: + return new DevToolsSettingsManagerModule(context); default: return null; } @@ -181,7 +184,8 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { Class.forName("com.facebook.react.shell.MainReactPackage$$ReactModuleInfoProvider"); return (ReactModuleInfoProvider) reactModuleInfoProviderClass.newInstance(); } catch (ClassNotFoundException e) { - // In OSS case, the annotation processor does not run. We fall back on creating this byhand + // In the OSS case, the annotation processor does not run. We fall back to creating this by + // hand Class[] moduleList = new Class[] { AccessibilityInfoModule.class, @@ -199,6 +203,7 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() { NativeAnimatedModule.class, NetworkingModule.class, PermissionsModule.class, + DevToolsSettingsManagerModule.class, ShareModule.class, StatusBarModule.class, SoundManagerModule.class, diff --git a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK index 235079472f328d..555b08c3863fff 100644 --- a/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK +++ b/ReactAndroid/src/test/java/com/facebook/react/modules/BUCK @@ -34,6 +34,7 @@ rn_robolectric_test( react_native_target("java/com/facebook/react/modules/core:core"), react_native_target("java/com/facebook/react/modules/debug:debug"), react_native_target("java/com/facebook/react/modules/deviceinfo:deviceinfo"), + react_native_target("java/com/facebook/react/modules/devtoolssettings:devtoolssettings"), react_native_target("java/com/facebook/react/modules/dialog:dialog"), react_native_target("java/com/facebook/react/modules/network:network"), react_native_target("java/com/facebook/react/modules/share:share"), From 19d65a2baff2b2ab10d423e33baf373712ceda93 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Nov 2022 09:52:52 -0800 Subject: [PATCH 157/169] Update .podspec license information (#35245) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35245 Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D41084913 fbshipit-source-id: a4ba31a19ffe515aa4e7c5a6e273a8cc4b6bc42d --- Libraries/ActionSheetIOS/React-RCTActionSheet.podspec | 2 +- Libraries/AppDelegate/React-RCTAppDelegate.podspec | 2 +- Libraries/Blob/React-RCTBlob.podspec | 2 +- Libraries/FBLazyVector/FBLazyVector.podspec | 2 +- Libraries/Image/React-RCTImage.podspec | 2 +- Libraries/LinkingIOS/React-RCTLinking.podspec | 2 +- Libraries/NativeAnimation/React-RCTAnimation.podspec | 2 +- Libraries/Network/React-RCTNetwork.podspec | 2 +- Libraries/PushNotificationIOS/React-RCTPushNotification.podspec | 2 +- Libraries/RCTRequired/RCTRequired.podspec | 2 +- Libraries/Settings/React-RCTSettings.podspec | 2 +- Libraries/Text/React-RCTText.podspec | 2 +- Libraries/TypeSafety/RCTTypeSafety.podspec | 2 +- Libraries/Vibration/React-RCTVibration.podspec | 2 +- React-Core.podspec | 2 +- React.podspec | 2 +- React/CoreModules/React-CoreModules.podspec | 2 +- React/FBReactNativeSpec/FBReactNativeSpec.podspec | 2 +- React/React-RCTFabric.podspec | 2 +- ReactCommon/React-Fabric.podspec | 2 +- ReactCommon/React-rncore.podspec | 2 +- ReactCommon/ReactCommon.podspec | 2 +- ReactCommon/callinvoker/React-callinvoker.podspec | 2 +- ReactCommon/cxxreact/React-cxxreact.podspec | 2 +- ReactCommon/hermes/React-hermes.podspec | 2 +- ReactCommon/jsi/React-jsc.podspec | 2 +- ReactCommon/jsi/React-jsi.podspec | 2 +- ReactCommon/jsi/React-jsidynamic.podspec | 2 +- ReactCommon/jsiexecutor/React-jsiexecutor.podspec | 2 +- ReactCommon/jsinspector/React-jsinspector.podspec | 2 +- ReactCommon/logger/React-logger.podspec | 2 +- ReactCommon/react/renderer/graphics/React-graphics.podspec | 2 +- ReactCommon/reactperflogger/React-perflogger.podspec | 2 +- ReactCommon/runtimeexecutor/React-runtimeexecutor.podspec | 2 +- packages/rn-tester/NativeComponentExample/MyNativeView.podspec | 2 +- .../rn-tester/NativeModuleExample/ScreenshotManager.podspec | 2 +- packages/rn-tester/RCTTest/React-RCTTest.podspec | 2 +- 37 files changed, 37 insertions(+), 37 deletions(-) diff --git a/Libraries/ActionSheetIOS/React-RCTActionSheet.podspec b/Libraries/ActionSheetIOS/React-RCTActionSheet.podspec index a9bd4ca8235d0d..5cad0ca81915b3 100644 --- a/Libraries/ActionSheetIOS/React-RCTActionSheet.podspec +++ b/Libraries/ActionSheetIOS/React-RCTActionSheet.podspec @@ -23,7 +23,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/actionsheetios" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{m}" diff --git a/Libraries/AppDelegate/React-RCTAppDelegate.podspec b/Libraries/AppDelegate/React-RCTAppDelegate.podspec index fff87118479cc6..bf6c9b578717c1 100644 --- a/Libraries/AppDelegate/React-RCTAppDelegate.podspec +++ b/Libraries/AppDelegate/React-RCTAppDelegate.podspec @@ -46,7 +46,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/actionsheetios" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{c,h,m,mm,S,cpp}" diff --git a/Libraries/Blob/React-RCTBlob.podspec b/Libraries/Blob/React-RCTBlob.podspec index 30cf7e14171060..3d69eeced3ac9b 100644 --- a/Libraries/Blob/React-RCTBlob.podspec +++ b/Libraries/Blob/React-RCTBlob.podspec @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.summary = "An API for displaying iOS action sheets and share sheets." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/FBLazyVector/FBLazyVector.podspec b/Libraries/FBLazyVector/FBLazyVector.podspec index 41a0f756f0fdb0..b8473d5bae5a9a 100644 --- a/Libraries/FBLazyVector/FBLazyVector.podspec +++ b/Libraries/FBLazyVector/FBLazyVector.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{c,h,m,mm,cpp}" diff --git a/Libraries/Image/React-RCTImage.podspec b/Libraries/Image/React-RCTImage.podspec index 614245a225300d..5eb0fdbcf74b0e 100644 --- a/Libraries/Image/React-RCTImage.podspec +++ b/Libraries/Image/React-RCTImage.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/image" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/LinkingIOS/React-RCTLinking.podspec b/Libraries/LinkingIOS/React-RCTLinking.podspec index 1def01915d53d2..c975d321ee2f1b 100644 --- a/Libraries/LinkingIOS/React-RCTLinking.podspec +++ b/Libraries/LinkingIOS/React-RCTLinking.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/linking" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/NativeAnimation/React-RCTAnimation.podspec b/Libraries/NativeAnimation/React-RCTAnimation.podspec index 2a15aed44359b7..a1e4126d4cba22 100644 --- a/Libraries/NativeAnimation/React-RCTAnimation.podspec +++ b/Libraries/NativeAnimation/React-RCTAnimation.podspec @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.summary = "A native driver for the Animated API." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/Network/React-RCTNetwork.podspec b/Libraries/Network/React-RCTNetwork.podspec index c0bd78a8cfb8e3..6b57d3c3d0ab0c 100644 --- a/Libraries/Network/React-RCTNetwork.podspec +++ b/Libraries/Network/React-RCTNetwork.podspec @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.summary = "The networking library of React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec b/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec index 4d410d7fdc5176..ce1f9da25f0bb9 100644 --- a/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec +++ b/Libraries/PushNotificationIOS/React-RCTPushNotification.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/pushnotificationios" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/RCTRequired/RCTRequired.podspec b/Libraries/RCTRequired/RCTRequired.podspec index a0f1a646aeca0d..dc38d2a4c477ff 100644 --- a/Libraries/RCTRequired/RCTRequired.podspec +++ b/Libraries/RCTRequired/RCTRequired.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{c,h,m,mm,cpp}" diff --git a/Libraries/Settings/React-RCTSettings.podspec b/Libraries/Settings/React-RCTSettings.podspec index 11770ad527e999..c721a573670552 100644 --- a/Libraries/Settings/React-RCTSettings.podspec +++ b/Libraries/Settings/React-RCTSettings.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/settings" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/Libraries/Text/React-RCTText.podspec b/Libraries/Text/React-RCTText.podspec index 793a8dbf346149..091ccea4c99bf2 100644 --- a/Libraries/Text/React-RCTText.podspec +++ b/Libraries/Text/React-RCTText.podspec @@ -23,7 +23,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/text" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{h,m}" diff --git a/Libraries/TypeSafety/RCTTypeSafety.podspec b/Libraries/TypeSafety/RCTTypeSafety.podspec index d2744689a01c4d..79c04d09fe4c47 100644 --- a/Libraries/TypeSafety/RCTTypeSafety.podspec +++ b/Libraries/TypeSafety/RCTTypeSafety.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{c,h,m,mm,cpp}" diff --git a/Libraries/Vibration/React-RCTVibration.podspec b/Libraries/Vibration/React-RCTVibration.podspec index 28dcce4487b89a..90ec1a6f0f70e4 100644 --- a/Libraries/Vibration/React-RCTVibration.podspec +++ b/Libraries/Vibration/React-RCTVibration.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.homepage = "https://reactnative.dev/" s.documentation_url = "https://reactnative.dev/docs/vibration" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/React-Core.podspec b/React-Core.podspec index 7be727f36705bc..b0bc4959222338 100644 --- a/React-Core.podspec +++ b/React-Core.podspec @@ -55,7 +55,7 @@ Pod::Spec.new do |s| s.summary = "The core of React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.resource_bundle = { "AccessibilityResources" => ["React/AccessibilityResources/*.lproj"]} diff --git a/React.podspec b/React.podspec index a0de5a6359ef13..0ea4f42f39454d 100644 --- a/React.podspec +++ b/React.podspec @@ -35,7 +35,7 @@ Pod::Spec.new do |s| DESC s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.preserve_paths = "package.json", "LICENSE", "LICENSE-docs" diff --git a/React/CoreModules/React-CoreModules.podspec b/React/CoreModules/React-CoreModules.podspec index a4a605aaf01257..90c8adf1bc27f7 100644 --- a/React/CoreModules/React-CoreModules.podspec +++ b/React/CoreModules/React-CoreModules.podspec @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/React/FBReactNativeSpec/FBReactNativeSpec.podspec b/React/FBReactNativeSpec/FBReactNativeSpec.podspec index 37f2a17d8dffb5..2d9b0b25cb111b 100644 --- a/React/FBReactNativeSpec/FBReactNativeSpec.podspec +++ b/React/FBReactNativeSpec/FBReactNativeSpec.podspec @@ -28,7 +28,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source diff --git a/React/React-RCTFabric.podspec b/React/React-RCTFabric.podspec index a494a6b75789b9..8855651666aa5f 100644 --- a/React/React-RCTFabric.podspec +++ b/React/React-RCTFabric.podspec @@ -27,7 +27,7 @@ Pod::Spec.new do |s| s.summary = "RCTFabric for React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "Fabric/**/*.{c,h,m,mm,S,cpp}" diff --git a/ReactCommon/React-Fabric.podspec b/ReactCommon/React-Fabric.podspec index c28eee60d06fbe..03db45f21fad41 100644 --- a/ReactCommon/React-Fabric.podspec +++ b/ReactCommon/React-Fabric.podspec @@ -28,7 +28,7 @@ Pod::Spec.new do |s| s.summary = "Fabric for React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "dummyFile.cpp" diff --git a/ReactCommon/React-rncore.podspec b/ReactCommon/React-rncore.podspec index 635c80e7d241d5..e2708f721fbe3e 100644 --- a/ReactCommon/React-rncore.podspec +++ b/ReactCommon/React-rncore.podspec @@ -24,7 +24,7 @@ Pod::Spec.new do |s| s.summary = "Fabric for React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "dummyFile.cpp" diff --git a/ReactCommon/ReactCommon.podspec b/ReactCommon/ReactCommon.podspec index 46af7c0411ba15..786cf0300fd08c 100644 --- a/ReactCommon/ReactCommon.podspec +++ b/ReactCommon/ReactCommon.podspec @@ -27,7 +27,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.header_dir = "ReactCommon" # Use global header_dir for all subspecs for use_frameworks! compatibility diff --git a/ReactCommon/callinvoker/React-callinvoker.podspec b/ReactCommon/callinvoker/React-callinvoker.podspec index 7ade869b280185..dbff635a1c3e95 100644 --- a/ReactCommon/callinvoker/React-callinvoker.podspec +++ b/ReactCommon/callinvoker/React-callinvoker.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{cpp,h}" diff --git a/ReactCommon/cxxreact/React-cxxreact.podspec b/ReactCommon/cxxreact/React-cxxreact.podspec index 8888f85473345c..b672f5489764b2 100644 --- a/ReactCommon/cxxreact/React-cxxreact.podspec +++ b/ReactCommon/cxxreact/React-cxxreact.podspec @@ -27,7 +27,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{cpp,h}" diff --git a/ReactCommon/hermes/React-hermes.podspec b/ReactCommon/hermes/React-hermes.podspec index 1a33547c2c43e3..02a072c313df67 100644 --- a/ReactCommon/hermes/React-hermes.podspec +++ b/ReactCommon/hermes/React-hermes.podspec @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.summary = "Hermes engine for React Native" s.homepage = "https://reactnative.dev/" s.license = package['license'] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :osx => "10.14", :ios => "12.4" } s.source = source s.source_files = "executor/*.{cpp,h}", diff --git a/ReactCommon/jsi/React-jsc.podspec b/ReactCommon/jsi/React-jsc.podspec index ce59f0e69e6ac9..a3e3c2cdf2ae98 100644 --- a/ReactCommon/jsi/React-jsc.podspec +++ b/ReactCommon/jsi/React-jsc.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.summary = "JavaScriptCore engine for React Native" s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "JSCRuntime.{cpp,h}" diff --git a/ReactCommon/jsi/React-jsi.podspec b/ReactCommon/jsi/React-jsi.podspec index ac21bada4f44b2..f73127ffc96ac7 100644 --- a/ReactCommon/jsi/React-jsi.podspec +++ b/ReactCommon/jsi/React-jsi.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "JavaScript Interface layer for React Native" s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source diff --git a/ReactCommon/jsi/React-jsidynamic.podspec b/ReactCommon/jsi/React-jsidynamic.podspec index 831c6b010fc461..b528de568c28ad 100644 --- a/ReactCommon/jsi/React-jsidynamic.podspec +++ b/ReactCommon/jsi/React-jsidynamic.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "Provides support for converting between folly::dynamic and jsi::value" s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "jsi/JSIDynamic.{cpp,h}" diff --git a/ReactCommon/jsiexecutor/React-jsiexecutor.podspec b/ReactCommon/jsiexecutor/React-jsiexecutor.podspec index c0846011f90c01..cbfaf3879a3270 100644 --- a/ReactCommon/jsiexecutor/React-jsiexecutor.podspec +++ b/ReactCommon/jsiexecutor/React-jsiexecutor.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "jsireact/*.{cpp,h}" diff --git a/ReactCommon/jsinspector/React-jsinspector.podspec b/ReactCommon/jsinspector/React-jsinspector.podspec index a1d6f7f2c3c60a..cf77de1da3044b 100644 --- a/ReactCommon/jsinspector/React-jsinspector.podspec +++ b/ReactCommon/jsinspector/React-jsinspector.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{cpp,h}" diff --git a/ReactCommon/logger/React-logger.podspec b/ReactCommon/logger/React-logger.podspec index 193f42e231576d..17c2856a92e5f2 100644 --- a/ReactCommon/logger/React-logger.podspec +++ b/ReactCommon/logger/React-logger.podspec @@ -27,7 +27,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "*.{cpp,h}" diff --git a/ReactCommon/react/renderer/graphics/React-graphics.podspec b/ReactCommon/react/renderer/graphics/React-graphics.podspec index 8c297d76b43ecd..8b2d2bf463d995 100644 --- a/ReactCommon/react/renderer/graphics/React-graphics.podspec +++ b/ReactCommon/react/renderer/graphics/React-graphics.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "Fabric for React Native." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.compiler_flags = folly_compiler_flags + ' ' + boost_compiler_flags diff --git a/ReactCommon/reactperflogger/React-perflogger.podspec b/ReactCommon/reactperflogger/React-perflogger.podspec index 24229c0eeead52..37a372c07b19fd 100644 --- a/ReactCommon/reactperflogger/React-perflogger.podspec +++ b/ReactCommon/reactperflogger/React-perflogger.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{cpp,h}" diff --git a/ReactCommon/runtimeexecutor/React-runtimeexecutor.podspec b/ReactCommon/runtimeexecutor/React-runtimeexecutor.podspec index 5cbadf30d531fe..2a36877299a842 100644 --- a/ReactCommon/runtimeexecutor/React-runtimeexecutor.podspec +++ b/ReactCommon/runtimeexecutor/React-runtimeexecutor.podspec @@ -26,7 +26,7 @@ Pod::Spec.new do |s| s.summary = "-" # TODO s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.source = source s.source_files = "**/*.{cpp,h}" diff --git a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec index 3368c3e47c0cc3..d81e98d10d5688 100644 --- a/packages/rn-tester/NativeComponentExample/MyNativeView.podspec +++ b/packages/rn-tester/NativeComponentExample/MyNativeView.podspec @@ -19,7 +19,7 @@ Pod::Spec.new do |s| s.license = "MIT" s.platforms = { :ios => "12.4" } s.compiler_flags = boost_compiler_flags + ' -Wno-nullability-completeness' - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/my-native-view.git", :tag => "#{s.version}" } s.pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/RCT-Folly\" \"$(PODS_ROOT)/boost\" \"${PODS_CONFIGURATION_BUILD_DIR}/React-Codegen/React_Codegen.framework/Headers\"", diff --git a/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec b/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec index 339f68e1d41249..4738a515998ad2 100644 --- a/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec +++ b/packages/rn-tester/NativeModuleExample/ScreenshotManager.podspec @@ -16,7 +16,7 @@ Pod::Spec.new do |s| s.license = "MIT" s.platforms = { :ios => "12.4" } s.compiler_flags = '-Wno-nullability-completeness' - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.source = { :git => "https://github.com/facebook/react-native.git", :tag => "#{s.version}" } s.source_files = "**/*.{h,m,mm,swift}" diff --git a/packages/rn-tester/RCTTest/React-RCTTest.podspec b/packages/rn-tester/RCTTest/React-RCTTest.podspec index 5f6d58f908ecef..8d32267c8128e9 100644 --- a/packages/rn-tester/RCTTest/React-RCTTest.podspec +++ b/packages/rn-tester/RCTTest/React-RCTTest.podspec @@ -25,7 +25,7 @@ Pod::Spec.new do |s| s.summary = "Tools for integration and snapshot testing." s.homepage = "https://reactnative.dev/" s.license = package["license"] - s.author = "Facebook, Inc. and its affiliates" + s.author = "Meta Platforms, Inc. and its affiliates" s.platforms = { :ios => "12.4" } s.compiler_flags = folly_compiler_flags + ' -Wno-nullability-completeness' s.source = source From 3d9a15da870a75ed76d60d0c9b0d38c351a15003 Mon Sep 17 00:00:00 2001 From: Christoph Purrer Date: Mon, 7 Nov 2022 10:30:10 -0800 Subject: [PATCH 158/169] Update ReactCommon.podspec | Debug section (#35236) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/35236 Changelog: [Internal] Reviewed By: cipolleschi Differential Revision: D41078409 fbshipit-source-id: fbd3daf61da29d0b595902e2541563343ba50de1 --- ReactCommon/ReactCommon.podspec | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ReactCommon/ReactCommon.podspec b/ReactCommon/ReactCommon.podspec index 786cf0300fd08c..79a77e1f7849a7 100644 --- a/ReactCommon/ReactCommon.podspec +++ b/ReactCommon/ReactCommon.podspec @@ -64,14 +64,14 @@ Pod::Spec.new do |s| sss.dependency "React-jsidynamic", version end - s.subspec "react_debug_core" do |sss| - sss.source_files = "react/debug/*.{cpp,h}" - end - ss.subspec "samples" do |sss| sss.source_files = "react/nativemodule/samples/ReactCommon/**/*.{cpp,h}", - "react/nativemodule/samples/platform/ios/**/*.{mm,cpp,h}" + "react/nativemodule/samples/platform/ios/**/*.{mm,cpp,h}" sss.dependency "ReactCommon/turbomodule/core", version end end + + s.subspec "react_debug_core" do |sss| + sss.source_files = "react/debug/*.{cpp,h}" + end end From 7a327d967357ecf04ddd64b6f6661dd1e7f0ea22 Mon Sep 17 00:00:00 2001 From: Arushi Kesarwani Date: Mon, 7 Nov 2022 11:31:55 -0800 Subject: [PATCH 159/169] Refactor accessory show methods for DevLoading Summary: Changelog: [Internal][Changed] - In order to make Dev Loading View cross platform, refactoring the accessary show methods. Reviewed By: cortinico Differential Revision: D41029102 fbshipit-source-id: 475949548fe98217e61d6cf64accbbdc0fb0f1c5 --- .../devsupport/DevLoadingViewController.java | 30 ------------------- .../devsupport/DevSupportManagerBase.java | 25 ++++++++++++++-- 2 files changed, 23 insertions(+), 32 deletions(-) diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java index fa1554bda002f4..9697c4da7e8132 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevLoadingViewController.java @@ -22,8 +22,6 @@ import com.facebook.react.R; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.common.ReactConstants; -import java.net.MalformedURLException; -import java.net.URL; import java.util.Locale; /** Controller to display loading messages on top of the screen. All methods are thread safe. */ @@ -55,34 +53,6 @@ public void run() { }); } - public void showForUrl(String url) { - Context context = getContext(); - if (context == null) { - return; - } - - URL parsedURL; - try { - parsedURL = new URL(url); - } catch (MalformedURLException e) { - FLog.e(ReactConstants.TAG, "Bundle url format is invalid. \n\n" + e.toString()); - return; - } - - int port = parsedURL.getPort() != -1 ? parsedURL.getPort() : parsedURL.getDefaultPort(); - showMessage( - context.getString(R.string.catalyst_loading_from_url, parsedURL.getHost() + ":" + port)); - } - - public void showForRemoteJSEnabled() { - Context context = getContext(); - if (context == null) { - return; - } - - showMessage(context.getString(R.string.catalyst_debug_connecting)); - } - public void updateProgress( final @Nullable String status, final @Nullable Integer done, final @Nullable Integer total) { if (!sEnabled) { diff --git a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.java b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.java index 0141e70c3eb69b..2bf304a6b1ea4c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.java +++ b/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerBase.java @@ -752,13 +752,34 @@ protected ReactInstanceDevHelper getReactInstanceDevHelper() { @UiThread private void showDevLoadingViewForUrl(String bundleUrl) { - mDevLoadingViewController.showForUrl(bundleUrl); + if (mApplicationContext == null) { + return; + } + + URL parsedURL; + + try { + parsedURL = new URL(bundleUrl); + } catch (MalformedURLException e) { + FLog.e(ReactConstants.TAG, "Bundle url format is invalid. \n\n" + e.toString()); + return; + } + + int port = parsedURL.getPort() != -1 ? parsedURL.getPort() : parsedURL.getDefaultPort(); + mDevLoadingViewController.showMessage( + mApplicationContext.getString( + R.string.catalyst_loading_from_url, parsedURL.getHost() + ":" + port)); mDevLoadingViewVisible = true; } @UiThread protected void showDevLoadingViewForRemoteJSEnabled() { - mDevLoadingViewController.showForRemoteJSEnabled(); + if (mApplicationContext == null) { + return; + } + + mDevLoadingViewController.showMessage( + mApplicationContext.getString(R.string.catalyst_debug_connecting)); mDevLoadingViewVisible = true; } From b6869be1ac0bedcb846722160f29fb4591ae5013 Mon Sep 17 00:00:00 2001 From: Gabriel Donadel Dall'Agnol Date: Mon, 7 Nov 2022 17:43:10 -0800 Subject: [PATCH 160/169] feat: Update TextInput inputMode to map "none" to showSoftInputOnFocus (#35228) Summary: This PR updates `inputMode` prop from the `TextInput` component to map the `none` option to `showSoftInputOnFocus={false}` as suggested by necolas here -> https://github.com/facebook/react-native/pull/34460#issuecomment-1304837271. This change makes the inputMode API behaves a bit more similarly across platforms. Related to https://github.com/necolas/react-native-web/issues/2421 ## Changelog [General] [Changed] - Update TextInput inputMode to map "none" to showSoftInputOnFocus ## Test Plan 1. Open the RNTester app and navigate to the TextInput page 2. Test the `TextInput` component through the `Input modes` section https://user-images.githubusercontent.com/11707729/200218435-6a33b319-e989-4086-aac3-506546982b38.mov Pull Request resolved: https://github.com/facebook/react-native/pull/35228 Reviewed By: lunaleaps, necolas Differential Revision: D41081876 Pulled By: jacdebug fbshipit-source-id: cc634c3723647d8950bf2cfe67be70d0fbd488a6 --- Libraries/Components/TextInput/TextInput.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Libraries/Components/TextInput/TextInput.js b/Libraries/Components/TextInput/TextInput.js index 386e6b87c8822e..ada8c7bcdc9af6 100644 --- a/Libraries/Components/TextInput/TextInput.js +++ b/Libraries/Components/TextInput/TextInput.js @@ -1602,6 +1602,7 @@ const ExportedForwardRef: React.AbstractComponent< enterKeyHint, returnKeyType, inputMode, + showSoftInputOnFocus, keyboardType, ...restProps }, @@ -1628,6 +1629,9 @@ const ExportedForwardRef: React.AbstractComponent< keyboardType={ inputMode ? inputModeToKeyboardTypeMap[inputMode] : keyboardType } + showSoftInputOnFocus={ + inputMode == null ? showSoftInputOnFocus : inputMode !== 'none' + } autoComplete={ Platform.OS === 'android' ? // $FlowFixMe From 78aabd29ca935ef5a10c30c202c0305af4181922 Mon Sep 17 00:00:00 2001 From: Ramanpreet Nara Date: Mon, 7 Nov 2022 17:57:44 -0800 Subject: [PATCH 161/169] Align Bridgeless mode's create/reload/destroy with bridge's Summary: Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D40778326 fbshipit-source-id: b5dadfdc06f08ef0db0f97af2ec75e079bb77be6 --- .../main/java/com/facebook/react/config/ReactFeatureFlags.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java index a4cf989ca750bf..42492c19ff6a7c 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java +++ b/ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java @@ -42,6 +42,9 @@ public class ReactFeatureFlags { */ public static volatile boolean enableBridgelessArchitectureSoftExceptions = false; + /** Does the bridgeless architecture use the new create/reload/destroy routines */ + public static volatile boolean enableBridgelessArchitectureNewCreateReloadDestroy = false; + /** * After TurboModules and Fabric are enabled, we need to ensure that the legacy NativeModule isn't * isn't used. So, turn this flag on to trigger warnings whenever the legacy NativeModule system From 55c0df43b9859853e41b6e2ef271b78b783538f0 Mon Sep 17 00:00:00 2001 From: fabriziobertoglio1987 Date: Mon, 7 Nov 2022 23:25:33 -0800 Subject: [PATCH 162/169] Adding pager, scrollview, viewgroup, webview, drawer roles (#34477) Summary: - adds missing roles - adds custom roles that don't exist in TalkBack (see the [compositor.json][10] and [string.xml][11] files). - fixes [issues with Drawer][12] - fixes issues with ScrollView missing roles - seek control already exist as adjustable https://github.com/facebook/react-native/pull/34477/commits/d460d097ac0f5df8002e072711023517905f9ca9 Relevant https://github.com/facebook/react-native/issues/30839#issuecomment-1222293556 fixes https://github.com/facebook/react-native/issues/30839 ## Changelog [Android] [Fixed] - Adding pager, scrollview, viewgroup, webview, drawer roles Pull Request resolved: https://github.com/facebook/react-native/pull/34477 Test Plan: Android - Drawer Layout and ScrollView (02/09/22) https://github.com/facebook/react-native/pull/34477#issuecomment-1235293165 - sliding drawer, drawer layout, icon menu https://github.com/facebook/react-native/pull/34477#issuecomment-1224112650 - Horizontal and Vertical ScrollView https://github.com/facebook/react-native/pull/34477#issuecomment-1225478289 - Toast https://github.com/facebook/react-native/pull/34477#issuecomment-1225369629 - CheckedTextView https://github.com/facebook/react-native/pull/34477#discussion_r959329833 - Spinner (dropdownlist) https://github.com/facebook/react-native/pull/34477#discussion_r959374894 - EditText https://github.com/facebook/react-native/pull/34477#discussion_r959412185 - WebView https://github.com/facebook/react-native/pull/34477#discussion_r959417518 - Testing chime_up and chime_down sound feedback in Scrollable https://github.com/facebook/react-native/pull/34477#issuecomment-1238882030 iOS https://github.com/facebook/react-native/pull/34477#issuecomment-1232418595 [10]: https://github.com/google/talkback/blob/771de7cdbf55b6adb4ca4c64c27a52584f2337cc/compositor/src/main/res/raw/compositor.json#L1082-L1108 [11]: https://github.com/google/talkback/blob/771de7cdbf55b6adb4ca4c64c27a52584f2337cc/compositor/src/main/res/values/strings.xml#L223 [12]: https://github.com/facebook/react-native/pull/34477#issuecomment-1224112650 Reviewed By: NickGerleman Differential Revision: D39894307 Pulled By: blavalla fbshipit-source-id: 4a8da78bae485ead0523689631d88d1031a07b74 --- .../DrawerLayoutAndroid.android.js | 3 + .../Components/View/ViewAccessibility.js | 11 +- React/Views/RCTViewManager.m | 10 + .../uimanager/ReactAccessibilityDelegate.java | 29 +- .../java/com/facebook/react/views/drawer/BUCK | 1 + .../react/views/drawer/ReactDrawerLayout.java | 30 ++ .../Accessibility/AccessibilityExample.js | 274 +++++++++++------- .../DrawerLayoutAndroidExample.js | 100 +++++++ .../js/utils/RNTesterList.android.js | 5 + 9 files changed, 357 insertions(+), 106 deletions(-) create mode 100644 packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js diff --git a/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js b/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js index 10e265c553cccb..4435044e57a102 100644 --- a/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js +++ b/Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js @@ -21,6 +21,7 @@ import dismissKeyboard from '../../Utilities/dismissKeyboard'; import Platform from '../../Utilities/Platform'; import StatusBar from '../StatusBar/StatusBar'; import View from '../View/View'; +import type {AccessibilityRole} from '../../Components/View/ViewAccessibility'; import AndroidDrawerLayoutNativeComponent, { Commands, } from './AndroidDrawerLayoutNativeComponent'; @@ -36,6 +37,8 @@ type DrawerSlideEvent = $ReadOnly<{| |}>; type Props = $ReadOnly<{| + accessibilityRole?: ?AccessibilityRole, + /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default), drags do not dismiss the keyboard. diff --git a/Libraries/Components/View/ViewAccessibility.js b/Libraries/Components/View/ViewAccessibility.js index c62be022b046e7..18da75effcb1d7 100644 --- a/Libraries/Components/View/ViewAccessibility.js +++ b/Libraries/Components/View/ViewAccessibility.js @@ -16,6 +16,7 @@ import type {SyntheticEvent} from '../../Types/CoreEventTypes'; export type AccessibilityRole = | 'none' | 'button' + | 'dropdownlist' | 'togglebutton' | 'link' | 'search' @@ -44,7 +45,15 @@ export type AccessibilityRole = | 'timer' | 'list' | 'toolbar' - | 'grid'; + | 'grid' + | 'pager' + | 'scrollview' + | 'horizontalscrollview' + | 'viewgroup' + | 'webview' + | 'drawerlayout' + | 'slidingdrawer' + | 'iconmenu'; // Role types for web export type Role = diff --git a/React/Views/RCTViewManager.m b/React/Views/RCTViewManager.m index b034ff08ac244a..309f9a2fb8fc5c 100644 --- a/React/Views/RCTViewManager.m +++ b/React/Views/RCTViewManager.m @@ -28,6 +28,7 @@ @implementation RCTConvert (UIAccessibilityTraits) (@{ @"none" : @(UIAccessibilityTraitNone), @"button" : @(UIAccessibilityTraitButton), + @"dropdownlist" : @(UIAccessibilityTraitNone), @"togglebutton" : @(UIAccessibilityTraitButton), @"link" : @(UIAccessibilityTraitLink), @"header" : @(UIAccessibilityTraitHeader), @@ -63,6 +64,15 @@ @implementation RCTConvert (UIAccessibilityTraits) @"tablist" : @(UIAccessibilityTraitNone), @"timer" : @(UIAccessibilityTraitNone), @"toolbar" : @(UIAccessibilityTraitNone), + @"grid" : @(UIAccessibilityTraitNone), + @"pager" : @(UIAccessibilityTraitNone), + @"scrollview" : @(UIAccessibilityTraitNone), + @"horizontalscrollview" : @(UIAccessibilityTraitNone), + @"viewgroup" : @(UIAccessibilityTraitNone), + @"webview" : @(UIAccessibilityTraitNone), + @"drawerlayout" : @(UIAccessibilityTraitNone), + @"slidingdrawer" : @(UIAccessibilityTraitNone), + @"iconmenu" : @(UIAccessibilityTraitNone), @"list" : @(UIAccessibilityTraitNone), @"grid" : @(UIAccessibilityTraitNone), }), diff --git a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java index 0f5f1671c8ffd6..1ec4a23f73fb0e 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java +++ b/ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactAccessibilityDelegate.java @@ -96,6 +96,7 @@ private void scheduleAccessibilityEventSender(View host) { public enum AccessibilityRole { NONE, BUTTON, + DROPDOWNLIST, TOGGLEBUTTON, LINK, SEARCH, @@ -123,12 +124,22 @@ public enum AccessibilityRole { TIMER, LIST, GRID, + PAGER, + SCROLLVIEW, + HORIZONTALSCROLLVIEW, + VIEWGROUP, + WEBVIEW, + DRAWERLAYOUT, + SLIDINGDRAWER, + ICONMENU, TOOLBAR; public static String getValue(AccessibilityRole role) { switch (role) { case BUTTON: return "android.widget.Button"; + case DROPDOWNLIST: + return "android.widget.Spinner"; case TOGGLEBUTTON: return "android.widget.ToggleButton"; case SEARCH: @@ -136,7 +147,7 @@ public static String getValue(AccessibilityRole role) { case IMAGE: return "android.widget.ImageView"; case IMAGEBUTTON: - return "android.widget.ImageButon"; + return "android.widget.ImageButton"; case KEYBOARDKEY: return "android.inputmethodservice.Keyboard$Key"; case TEXT: @@ -155,6 +166,22 @@ public static String getValue(AccessibilityRole role) { return "android.widget.AbsListView"; case GRID: return "android.widget.GridView"; + case SCROLLVIEW: + return "android.widget.ScrollView"; + case HORIZONTALSCROLLVIEW: + return "android.widget.HorizontalScrollView"; + case PAGER: + return "androidx.viewpager.widget.ViewPager"; + case DRAWERLAYOUT: + return "androidx.drawerlayout.widget.DrawerLayout"; + case SLIDINGDRAWER: + return "android.widget.SlidingDrawer"; + case ICONMENU: + return "com.android.internal.view.menu.IconMenuView"; + case VIEWGROUP: + return "android.view.ViewGroup"; + case WEBVIEW: + return "android.webkit.WebView"; case NONE: case LINK: case SUMMARY: diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK index 9677362369c1ca..0b70da4c4df2db 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/BUCK @@ -29,5 +29,6 @@ rn_android_library( react_native_target("java/com/facebook/react/uimanager/annotations:annotations"), react_native_target("java/com/facebook/react/views/scroll:scroll"), react_native_root_target(":generated_components_java-FBReactNativeComponentSpec"), + react_native_target("res:uimanager"), ], ) diff --git a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java index ab9bb7d30d3ea2..40392887a1c781 100644 --- a/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java +++ b/ReactAndroid/src/main/java/com/facebook/react/views/drawer/ReactDrawerLayout.java @@ -10,10 +10,16 @@ import android.view.Gravity; import android.view.MotionEvent; import android.view.View; +import android.view.accessibility.AccessibilityEvent; +import androidx.core.view.AccessibilityDelegateCompat; +import androidx.core.view.ViewCompat; +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat; import androidx.drawerlayout.widget.DrawerLayout; import com.facebook.common.logging.FLog; +import com.facebook.react.R; import com.facebook.react.bridge.ReactContext; import com.facebook.react.common.ReactConstants; +import com.facebook.react.uimanager.ReactAccessibilityDelegate.AccessibilityRole; import com.facebook.react.uimanager.events.NativeGestureUtil; /** @@ -29,6 +35,30 @@ public ReactDrawerLayout(ReactContext reactContext) { super(reactContext); + ViewCompat.setAccessibilityDelegate( + this, + new AccessibilityDelegateCompat() { + @Override + public void onInitializeAccessibilityNodeInfo( + View host, AccessibilityNodeInfoCompat info) { + super.onInitializeAccessibilityNodeInfo(host, info); + final AccessibilityRole accessibilityRole = + (AccessibilityRole) host.getTag(R.id.accessibility_role); + if (accessibilityRole != null) { + info.setClassName(AccessibilityRole.getValue(accessibilityRole)); + } + } + + @Override + public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { + super.onInitializeAccessibilityEvent(host, event); + final AccessibilityRole accessibilityRole = + (AccessibilityRole) host.getTag(R.id.accessibility_role); + if (accessibilityRole != null) { + event.setClassName(AccessibilityRole.getValue(accessibilityRole)); + } + } + }); } @Override diff --git a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js index c552f75699656a..d5caca95b71530 100644 --- a/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js +++ b/packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js @@ -28,6 +28,7 @@ const { Slider, Platform, Switch, + ScrollView, } = require('react-native'); import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; @@ -84,6 +85,9 @@ const styles = StyleSheet.create({ textAlign: 'center', backgroundColor: '#000000c0', }, + scrollView: { + height: 50, + }, }); class AccessibilityExample extends React.Component<{}> { @@ -571,106 +575,168 @@ class NestedCheckBox extends React.Component< class AccessibilityRoleAndStateExample extends React.Component<{}> { render(): React.Node { + const content = [ + This is some text, + This is some text, + This is some text, + This is some text, + This is some text, + This is some text, + This is some text, + ]; + return ( - - - Alert example - - - - Combobox example - - - Menu example - - - Menu bar example - - - Menu item example - - - Progress bar example - - - Radio button example - - - Radio group example - - - Scrollbar example - - - Spin button example - - - - Tab example - - - Tab list example - - - Timer example - - - Toolbar example - - - State busy example - - - - - + <> + + + {content} + - + + + {content} + + + + + {content} + + + + + + Alert example + + + + Combobox example + + + Menu example + + + Menu bar example + + + Menu item example + + + Progress bar example + + + Radio button example + + + Radio group example + + + Scrollbar example + + + Spin button example + + + + Tab example + + + Tab list example + + + Timer example + + + Toolbar example + + + State busy example + + + Drop Down List example + + + Pager example + + + Toggle Button example + + + Viewgroup example + + + Webview example + + + + + + + + + ); } } @@ -1369,18 +1435,18 @@ exports.title = 'Accessibility'; exports.documentationURL = 'https://reactnative.dev/docs/accessibilityinfo'; exports.description = 'Examples of using Accessibility APIs.'; exports.examples = [ - { - title: 'Accessibility elements', - render(): React.Element { - return ; - }, - }, { title: 'New accessibility roles and states', render(): React.Element { return ; }, }, + { + title: 'Accessibility elements', + render(): React.Element { + return ; + }, + }, { title: 'Accessibility action examples', render(): React.Element { diff --git a/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js b/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js new file mode 100644 index 00000000000000..2906099c49d27d --- /dev/null +++ b/packages/rn-tester/js/examples/DrawerLayoutAndroid/DrawerLayoutAndroidExample.js @@ -0,0 +1,100 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * @flow + */ + +'use strict'; + +import React, {useRef, useState} from 'react'; +import type {Node} from 'react'; +import { + Button, + DrawerLayoutAndroid, + Text, + StyleSheet, + View, +} from 'react-native'; + +const Drawer = () => { + const drawer = useRef(null); + const [drawerPosition, setDrawerPosition] = useState('left'); + const changeDrawerPosition = () => { + if (drawerPosition === 'left') { + setDrawerPosition('right'); + } else { + setDrawerPosition('left'); + } + }; + + const navigationView = () => ( + + I'm in the Drawer! +