diff --git a/.github/workflows/test-all.yml b/.github/workflows/test-all.yml index f1ee1caab331..fa1c87fd937f 100644 --- a/.github/workflows/test-all.yml +++ b/.github/workflows/test-all.yml @@ -41,8 +41,8 @@ jobs: if: github.repository == 'react/react-native' outputs: any_code_change: ${{ steps.filter_exclusions.outputs.any_code_change == 'true' || github.event_name != 'pull_request' }} - should_test_android: ${{ steps.filter_exclusions.outputs.should_test_android == 'true' || github.event_name != 'pull_request' }} - should_test_ios: ${{ steps.filter_exclusions.outputs.should_test_ios == 'true' || github.event_name != 'pull_request' }} + should_test_android: ${{ steps.filter_exclusions.outputs.should_test_android == 'true' || steps.filter_inclusions.outputs.react_shared == 'true' || github.event_name != 'pull_request' }} + should_test_ios: ${{ steps.filter_exclusions.outputs.should_test_ios == 'true' || steps.filter_inclusions.outputs.react_shared == 'true' || github.event_name != 'pull_request' }} debugger_shell: ${{ steps.filter_inclusions.outputs.debugger_shell }} steps: - name: Checkout @@ -85,6 +85,9 @@ jobs: id: filter_inclusions with: filters: | + # Shared Kotlin and its build configuration affect both platforms. + react_shared: + - 'packages/react-native/ReactShared/**' debugger_shell: - 'packages/debugger-shell/**' - 'scripts/debugger-shell/**' diff --git a/.github/workflows/test-kmp.yml b/.github/workflows/test-kmp.yml new file mode 100644 index 000000000000..b29eb07c2dd5 --- /dev/null +++ b/.github/workflows/test-kmp.yml @@ -0,0 +1,404 @@ +name: Test Kotlin Multiplatform pilot + +on: + workflow_dispatch: + pull_request: + paths: + - '.github/workflows/test-kmp.yml' + - '.github/actions/setup-gradle/**' + - '.github/actions/setup-xcode/**' + - '.github/actions/setup-node/**' + - '.github/actions/yarn-install/**' + - 'Gemfile' + - 'Gemfile.lock' + - 'build.gradle.kts' + - 'gradle.properties' + - 'gradle/wrapper/**' + - 'settings.gradle.kts' + - 'yarn.lock' + - 'packages/rn-tester/Podfile' + - 'packages/rn-tester/RCTTest/**' + - 'packages/rn-tester/RNTesterPods.xcodeproj/**' + - 'packages/rn-tester/RNTester/RNTester.xctestplan' + - 'packages/react-native/ReactShared/**' + - 'packages/react-native/ReactAndroid/build.gradle.kts' + - 'packages/react-native/ReactAndroid/gradle.properties' + - 'packages/react-native/gradle/libs.versions.toml' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt' + - 'packages/react-native/React/Fabric/Utils/RCTGradientUtils.*' + - 'packages/react-native/React/Fabric/RCTConversions.h' + - 'packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.*' + - 'packages/react-native/ReactCommon/react/renderer/graphics/**' + - 'packages/react-native/ReactCommon/react/utils/FloatComparison.h' + - 'packages/react-native/ReactCommon/react/utils/ManagedObjectWrapper.*' + - 'packages/react-native/React/React-RCTFabric.podspec' + - 'packages/react-native/React-Core.podspec' + - 'packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/**' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/**' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/scroll/**' + - 'packages/react-native/React/Base/RCTMultipartStreamReader.*' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt' + - 'packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m' + - 'packages/react-native/scripts/react_native_pods.rb' + - 'packages/react-native/scripts/cocoapods/kmp.rb' + - 'packages/react-native/Package.swift' + - 'packages/react-native/package.json' + - 'packages/react-native/settings.gradle.kts' + push: + branches: + - main + - '*-stable' + paths: + - '.github/workflows/test-kmp.yml' + - '.github/actions/setup-gradle/**' + - '.github/actions/setup-xcode/**' + - '.github/actions/setup-node/**' + - '.github/actions/yarn-install/**' + - 'Gemfile' + - 'Gemfile.lock' + - 'build.gradle.kts' + - 'gradle.properties' + - 'gradle/wrapper/**' + - 'settings.gradle.kts' + - 'yarn.lock' + - 'packages/rn-tester/Podfile' + - 'packages/rn-tester/RCTTest/**' + - 'packages/rn-tester/RNTesterPods.xcodeproj/**' + - 'packages/rn-tester/RNTester/RNTester.xctestplan' + - 'packages/react-native/ReactShared/**' + - 'packages/react-native/ReactAndroid/build.gradle.kts' + - 'packages/react-native/ReactAndroid/gradle.properties' + - 'packages/react-native/gradle/libs.versions.toml' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt' + - 'packages/react-native/React/Fabric/Utils/RCTGradientUtils.*' + - 'packages/react-native/React/Fabric/RCTConversions.h' + - 'packages/react-native/Libraries/NativeAnimation/RCTAnimationUtils.*' + - 'packages/react-native/ReactCommon/react/renderer/graphics/**' + - 'packages/react-native/ReactCommon/react/utils/FloatComparison.h' + - 'packages/react-native/ReactCommon/react/utils/ManagedObjectWrapper.*' + - 'packages/react-native/React/React-RCTFabric.podspec' + - 'packages/react-native/React-Core.podspec' + - 'packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/**' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/**' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/scroll/**' + - 'packages/react-native/React/Base/RCTMultipartStreamReader.*' + - 'packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt' + - 'packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt' + - 'packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m' + - 'packages/react-native/scripts/react_native_pods.rb' + - 'packages/react-native/scripts/cocoapods/kmp.rb' + - 'packages/react-native/Package.swift' + - 'packages/react-native/package.json' + - 'packages/react-native/settings.gradle.kts' + +permissions: + contents: read + +concurrency: + group: kmp-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test-shared: + runs-on: macos-26 + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v6 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + java-version: '17' + distribution: 'zulu' + - name: Set up Xcode for Kotlin Native + uses: ./.github/actions/setup-xcode + with: + xcode-version: '26.4.1' + - name: Set up Gradle + uses: ./.github/actions/setup-gradle + - name: Set up Ruby and CocoaPods + uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.2.0' + bundler-cache: true + - name: Check CocoaPods linking configurations + run: bundle exec ruby packages/react-native/ReactShared/scripts/test-cocoapods-linking.rb + - name: Cache Kotlin Native toolchain + uses: actions/cache@v5 + with: + path: ~/.konan + key: kmp-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('packages/react-native/ReactShared/*.gradle.kts', 'packages/react-native/ReactShared/gradle.properties', 'packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties') }} + - name: Test shared code on JVM and iOS + id: shared + working-directory: packages/react-native/ReactShared + run: >- + ./gradlew + jvmTest iosSimulatorArm64Test + linkDebugFrameworkIosArm64 linkReleaseFrameworkIosArm64 + linkDebugFrameworkIosSimulatorArm64 linkReleaseFrameworkIosSimulatorArm64 + linkDebugFrameworkIosX64 linkReleaseFrameworkIosX64 + --stacktrace --console=plain + - name: Compare the Apple adapter with native gradients + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: ./scripts/test-apple-gradient.sh + - name: Compare optimized Apple gradients + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + env: + RCT_KMP_BUILD_TYPE: Release + run: ./scripts/test-apple-gradient.sh + - name: Compare native and shared multipart adapters + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: | + ./scripts/test-apple-multipart.sh + python3 scripts/test-android-multipart.py --max-workers 2 + - name: Compare native and shared scroll snap adapters + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: python3 scripts/test-apple-scroll-snap.py --output "$RUNNER_TEMP/apple-scroll-snap" --benchmark-repeats 0 + - name: Test packaged XCFramework consumption + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: ./scripts/test-apple-distribution.sh + - name: Test independent Kotlin runtime coexistence + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: python3 scripts/test-kotlin-coexistence.py + - name: Measure native gradient costs + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: python3 scripts/benchmark-apple-gradient.py + - name: Measure clean and incremental shared builds + if: ${{ !cancelled() && steps.shared.outcome == 'success' }} + working-directory: packages/react-native/ReactShared + run: python3 scripts/benchmark-kmp-build.py + - name: Upload test reports + if: always() + uses: actions/upload-artifact@v6 + with: + name: kotlin-multiplatform-test-results + path: | + packages/react-native/ReactShared/build/reports/tests + packages/react-native/ReactShared/build/test-results + ${{ runner.temp }}/apple-scroll-snap/**/*.json + ${{ runner.temp }}/apple-scroll-snap/**/*.log + packages/react-native/ReactShared/build/apple-multipart-test/**/*.log + packages/react-native/ReactShared/build/android-multipart-test/build/test-results + packages/react-native/ReactShared/build/apple-distribution/**/*.json + packages/react-native/ReactShared/build/apple-distribution/**/*.log + packages/react-native/ReactShared/build/apple-distribution/**/consumer.xcresult + packages/react-native/ReactShared/build/kotlin-coexistence/**/*.json + packages/react-native/ReactShared/build/kotlin-coexistence/**/*.log + packages/react-native/ReactShared/build/apple-gradient-benchmark/**/*.json + packages/react-native/ReactShared/build/apple-gradient-benchmark/**/*.log + packages/react-native/ReactShared/build/kmp-build-benchmark/**/*.json + packages/react-native/ReactShared/build/kmp-build-benchmark/**/*.log + if-no-files-found: warn + + test-android-consumers: + name: Android Maven and npm source consumers + runs-on: 8-core-ubuntu + timeout-minutes: 90 + steps: + - name: Checkout + uses: actions/checkout@v6 + - name: Set up Node + uses: ./.github/actions/setup-node + - name: Install JavaScript dependencies + uses: ./.github/actions/yarn-install + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + java-version: '17' + distribution: 'zulu' + - name: Set up Gradle + uses: ./.github/actions/setup-gradle + - name: Install Android build SDK + id: android-sdk + run: | + python3 - <<'PY' + import os, pathlib, re, shutil, subprocess, tomllib + versions = tomllib.loads(pathlib.Path('packages/react-native/gradle/libs.versions.toml').read_text())['versions'] + sdkmanager = shutil.which('sdkmanager') or str(pathlib.Path(os.environ['ANDROID_HOME']) / 'cmdline-tools/latest/bin/sdkmanager') + packages = subprocess.check_output([sdkmanager, '--list'], text=True) + base = 'platforms;android-' + versions['compileSdk'] + # Recent SDKs use a minor version in their package ID (for example android-37.0). + platform = next((name for name in [base + '.0', base] if re.search(r'^\s*' + re.escape(name) + r'\s*\|', packages, re.M)), None) + if platform is None: + raise SystemExit('No Android SDK package matches compileSdk ' + versions['compileSdk']) + subprocess.run([sdkmanager, platform, 'build-tools;' + versions['buildTools']], check=True) + with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + output.write('ndk=' + versions['ndkVersion'] + '\n') + PY + - name: Enable emulator hardware acceleration + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Build and run packaged Android consumers + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 35 + target: google_apis + arch: x86_64 + ndk: ${{ steps.android-sdk.outputs.ndk }} + cmake: 3.30.5 + cores: 4 + disable-animations: true + script: python3 packages/react-native/ReactShared/scripts/test-android-consumers.py --output-dir "$RUNNER_TEMP/kmp-android-consumers" --abi x86_64 --device emulator-5554 + - name: Upload consumer reports + if: always() + uses: actions/upload-artifact@v6 + with: + name: kmp-android-consumers + path: | + ${{ runner.temp }}/kmp-android-consumers/*.log + ${{ runner.temp }}/kmp-android-consumers/*.json + if-no-files-found: warn + + test-apple-app: + name: RNTester KMP ${{ matrix.platform }} (${{ matrix.linkage }}) + runs-on: macos-26 + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: + - platform: simulator + linkage: libraries + - platform: simulator + linkage: static + - platform: simulator + linkage: dynamic + - platform: device + linkage: libraries + - platform: catalyst + linkage: libraries + env: + RCT_KMP_APP_OUTPUT_DIR: ${{ github.workspace }}/packages/react-native/ReactShared/build/apple-app-results + steps: + - name: Checkout + uses: actions/checkout@v6 + - name: Set up Node + uses: ./.github/actions/setup-node + - name: Install JavaScript dependencies + uses: ./.github/actions/yarn-install + - name: Select the Hermes compiler package + run: node scripts/releases/use-hermes-prebuilt.js + - name: Install the selected Hermes compiler + uses: ./.github/actions/yarn-install + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + java-version: '17' + distribution: 'zulu' + - name: Set up Xcode for Kotlin Native + uses: ./.github/actions/setup-xcode + with: + xcode-version: '26.4.1' + - name: Set up Gradle + uses: ./.github/actions/setup-gradle + - name: Set up Ruby and CocoaPods + uses: ruby/setup-ruby@v1 + with: + ruby-version: '3.2.0' + bundler-cache: true + - name: Cache Kotlin Native toolchain + uses: actions/cache@v5 + with: + path: ~/.konan + key: kmp-native-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('packages/react-native/ReactShared/*.gradle.kts', 'packages/react-native/ReactShared/gradle.properties', 'packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties') }} + - name: Build and validate the KMP source application + run: | + if [[ '${{ matrix.linkage }}' != libraries ]]; then + export USE_FRAMEWORKS='${{ matrix.linkage }}' + fi + ./packages/react-native/ReactShared/scripts/test-apple-app.sh '${{ matrix.platform }}' + - name: Upload application test reports + if: always() + uses: actions/upload-artifact@v6 + with: + name: kmp-app-${{ matrix.platform }}-${{ matrix.linkage }} + path: | + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/*.log + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/*.json + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/*.txt + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/*.xcresult + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/Podfile* + ${{ env.RCT_KMP_APP_OUTPUT_DIR }}/project.pbxproj + if-no-files-found: warn + + smoke: + runs-on: macos-26 + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v6 + - name: Set up JDK 17 + uses: actions/setup-java@v5 + with: + java-version: '17' + distribution: 'zulu' + - name: Set up Xcode + uses: ./.github/actions/setup-xcode + with: + xcode-version: '26.4.1' + - name: Set up Gradle + uses: ./.github/actions/setup-gradle + - name: Cache Kotlin Native toolchain + uses: actions/cache@v5 + with: + path: ~/.konan + key: kmp-foundation-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('packages/react-native/ReactShared/*.gradle.kts', 'packages/react-native/ReactShared/gradle.properties', 'packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties') }} + - name: Test common code and build Apple frameworks + working-directory: packages/react-native/ReactShared + run: >- + ./gradlew -PreactNativeSharedSmoke=true + jvmTest iosSimulatorArm64Test + linkDebugFrameworkIosArm64 linkReleaseFrameworkIosArm64 + linkDebugFrameworkIosSimulatorArm64 linkReleaseFrameworkIosSimulatorArm64 + linkDebugFrameworkIosX64 linkReleaseFrameworkIosX64 + --max-workers=2 --stacktrace --console=plain + - name: Test Objective-C consumption + working-directory: packages/react-native/ReactShared + run: ./scripts/test-apple-smoke.sh + - name: Verify nonempty tests and fixture isolation + working-directory: packages/react-native/ReactShared + run: | + ./gradlew jvmJar --max-workers=2 --console=plain + python3 - <<'PY' + from pathlib import Path + import xml.etree.ElementTree as ET + import zipfile + for target in ('jvmTest', 'iosSimulatorArm64Test'): + suites = [ET.parse(p).getroot() for p in Path('build/smoke/test-results', target).glob('TEST-*.xml')] + assert suites and sum(int(s.get('tests', 0)) for s in suites) > 0, target + assert all(not int(s.get(k, 0)) for s in suites for k in ('failures', 'errors', 'skipped')), target + jars = list(Path('build/libs').glob('*.jar')) + assert len(jars) == 1, jars + with zipfile.ZipFile(jars[0]) as jar: + assert not any('/smoke/' in name for name in jar.namelist()), 'Test fixture leaked into default output' + PY + - name: Upload smoke reports + if: always() + uses: actions/upload-artifact@v6 + with: + name: kotlin-multiplatform-smoke-results + path: | + packages/react-native/ReactShared/build/smoke/reports/tests + packages/react-native/ReactShared/build/smoke/test-results + packages/react-native/ReactShared/build/smoke/apple-interop/*.log + if-no-files-found: warn diff --git a/build.gradle.kts b/build.gradle.kts index 19fcc1df1a66..c56aa5238203 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -72,6 +72,7 @@ nexusPublishing { tasks.register("clean", Delete::class.java) { description = "Remove all the build files and intermediate build outputs" dependsOn(gradle.includedBuild("gradle-plugin").task(":clean")) + dependsOn(gradle.includedBuild("react-native-shared").task(":clean")) subprojects.forEach { if ( it.project.plugins.hasPlugin("com.android.library") || @@ -103,6 +104,7 @@ tasks.register("clean", Delete::class.java) { tasks.register("build") { description = "Build and test all the React Native relevant projects." dependsOn(gradle.includedBuild("gradle-plugin").task(":build")) + dependsOn(gradle.includedBuild("react-native-shared").task(":jvmTest")) } tasks.register("publishAllToMavenTempLocal") { diff --git a/packages/react-native/Package.swift b/packages/react-native/Package.swift index 386ca6958b7f..5e35ce276fdb 100644 --- a/packages/react-native/Package.swift +++ b/packages/react-native/Package.swift @@ -9,6 +9,10 @@ import Foundation import PackageDescription +if ProcessInfo.processInfo.environment["RCT_USE_KMP"] == "1" { + fatalError("RCT_USE_KMP=1 currently supports CocoaPods source builds only. Run RCT_USE_KMP=1 pod install in the iOS app; the SwiftPM prebuild does not include ReactNativeShared.") +} + let BUILD_FROM_SOURCE = false // Removing the legacy TurboModule and component interop layers is opt-in while those diff --git a/packages/react-native/React-Core.podspec b/packages/react-native/React-Core.podspec index 4e5802e7035d..1e209d256306 100644 --- a/packages/react-native/React-Core.podspec +++ b/packages/react-native/React-Core.podspec @@ -7,6 +7,10 @@ require "json" package = JSON.parse(File.read(File.join(__dir__, "package.json"))) version = package['version'] +kmp_enabled = ENV['RCT_USE_KMP'] == '1' +if kmp_enabled && ENV['RCT_USE_PREBUILT_RNCORE'] != '0' + raise 'RCT_USE_KMP=1 requires React Native core source builds. Use use_react_native! or set RCT_USE_PREBUILT_RNCORE=0.' +end source = { :git => 'https://github.com/facebook/react-native.git' } if version == '1000.0.0' @@ -54,13 +58,25 @@ Pod::Spec.new do |s| s.compiler_flags = js_engine_flags() s.header_dir = "React" s.weak_framework = "JavaScriptCore" - s.pod_target_xcconfig = { + pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => header_search_paths, "DEFINES_MODULE" => "YES", "GCC_PREPROCESSOR_DEFINITIONS" => "RCT_METRO_PORT=${RCT_METRO_PORT}", "CLANG_CXX_LANGUAGE_STANDARD" => rct_cxx_language_standard(), "FRAMEWORK_SEARCH_PATHS" => frameworks_search_paths.join(" ") } + if kmp_enabled + s.dependency 'React-KMP' + # React-Core is the common dependency of all Apple consumers. With dynamic + # pods it owns the Kotlin runtime once, even before Core calls a shared API. + # Static builds link the archive in the application via the post-install helper. + %w[iphoneos iphonesimulator].each do |sdk| + pod_target_xcconfig["GCC_PREPROCESSOR_DEFINITIONS[sdk=#{sdk}*]"] = '$(inherited) RCT_USE_KMP=1' + pod_target_xcconfig["FRAMEWORK_SEARCH_PATHS[sdk=#{sdk}*]"] = '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeSharedKMP"' + pod_target_xcconfig["OTHER_LDFLAGS[sdk=#{sdk}*]"] = '$(inherited) -ObjC -framework ReactNativeShared' + end + end + s.pod_target_xcconfig = pod_target_xcconfig s.user_target_xcconfig = { "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/Headers/Private/React-Core\""} s.default_subspec = "Default" diff --git a/packages/react-native/React/Base/RCTMultipartStreamReader.m b/packages/react-native/React/Base/RCTMultipartStreamReader.m index a57b9ea944bf..0ab5a7b23a77 100644 --- a/packages/react-native/React/Base/RCTMultipartStreamReader.m +++ b/packages/react-native/React/Base/RCTMultipartStreamReader.m @@ -7,6 +7,14 @@ #import "RCTMultipartStreamReader.h" #import +#import + +#if RCT_USE_KMP && TARGET_OS_IOS && !TARGET_OS_MACCATALYST +#define RCT_MULTIPART_USE_KMP 1 +#import +#else +#define RCT_MULTIPART_USE_KMP 0 +#endif #define CRLF @"\r\n" @@ -30,6 +38,12 @@ - (NSDictionary *)parseHeaders:(NSData *)data { NSMutableDictionary *headers = [NSMutableDictionary new]; NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; +#if RCT_MULTIPART_USE_KMP + for (RNSMultipartHeader *header in [RNSMultipartHeaders.shared parseText:text ?: @""]) { + NSString *value = [header.value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + [headers setValue:value forKey:header.name]; + } +#else NSArray *lines = [text componentsSeparatedByString:CRLF]; for (NSString *line in lines) { NSUInteger location = [line rangeOfString:@":"].location; @@ -41,6 +55,7 @@ - (NSDictionary *)parseHeaders:(NSData *)data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [headers setValue:value forKey:key]; } +#endif return headers; } @@ -84,13 +99,17 @@ - (void)emitProgress:(NSDictionary *)headers - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback progressCallback:(RCTMultipartProgressCallback)progressCallback { - NSInteger chunkStart = 0; - NSInteger bytesSeen = 0; - NSData *delimiter = [[NSString stringWithFormat:@"%@--%@%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; NSData *closeDelimiter = [[NSString stringWithFormat:@"%@--%@--%@", CRLF, _boundary, CRLF] dataUsingEncoding:NSUTF8StringEncoding]; +#if RCT_MULTIPART_USE_KMP + RNSMultipartFraming *framing = [[RNSMultipartFraming alloc] initWithDelimiterLength:(int32_t)delimiter.length + closeDelimiterLength:(int32_t)closeDelimiter.length]; +#else + NSInteger chunkStart = 0; + NSInteger bytesSeen = 0; +#endif NSMutableData *content = [[NSMutableData alloc] initWithCapacity:1]; NSDictionary *currentHeaders = nil; NSUInteger currentHeadersLength = 0; @@ -101,9 +120,13 @@ - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback [_stream open]; while (true) { BOOL isCloseDelimiter = NO; - // Search only a subset of chunk that we haven't seen before + few bytes - // to allow for the edge case when the delimiter is cut by read call +#if RCT_MULTIPART_USE_KMP + NSInteger searchStart = [framing searchStartBufferOffset:0]; + NSInteger chunkStart = [framing partStartBufferOffset:0]; +#else + // Preserve overlap when a delimiter is split between reads. NSInteger searchStart = MAX(bytesSeen - (NSInteger)closeDelimiter.length, chunkStart); +#endif NSRange remainingBufferRange = NSMakeRange(searchStart, content.length - searchStart); // Check for delimiters. @@ -113,6 +136,14 @@ - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback range = [content rangeOfData:closeDelimiter options:0 range:remainingBufferRange]; } +#if RCT_MULTIPART_USE_KMP + NSInteger index = range.location == NSNotFound ? -1 : (NSInteger)range.location; + RNSMultipartChunk *chunk = [framing nextChunkBufferLength:content.length + bufferOffset:0 + delimiterIndex:isCloseDelimiter ? -1 : index + closeDelimiterIndex:isCloseDelimiter ? index : -1]; +#endif + if (range.location == NSNotFound) { if (currentHeaders == nil) { // Check for the headers delimiter. @@ -131,7 +162,9 @@ - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback callback:progressCallback]; } +#if !RCT_MULTIPART_USE_KMP bytesSeen = content.length; +#endif NSInteger bytesRead = [_stream read:buffer maxLength:bufferLen]; if (bytesRead <= 0 || _stream.streamError) { return NO; @@ -140,12 +173,19 @@ - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback continue; } +#if RCT_MULTIPART_USE_KMP + NSInteger chunkEnd = chunk.end; + BOOL isPart = chunk.isPart; + isCloseDelimiter = chunk.isLast; +#else NSInteger chunkEnd = range.location; - NSInteger length = chunkEnd - chunkStart; + BOOL isPart = chunkStart > 0; bytesSeen = chunkEnd; +#endif + NSInteger length = chunkEnd - chunkStart; // Ignore preamble - if (chunkStart > 0) { + if (isPart) { NSData *chunk = [content subdataWithRange:NSMakeRange(chunkStart, length)]; [self emitProgress:currentHeaders contentLength:chunk.length - currentHeadersLength @@ -160,7 +200,9 @@ - (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback return YES; } +#if !RCT_MULTIPART_USE_KMP chunkStart = chunkEnd + delimiter.length; +#endif } } diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTEnhancedScrollView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTEnhancedScrollView.mm index b3481c1b98b4..3440d3799ca3 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTEnhancedScrollView.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/ScrollView/RCTEnhancedScrollView.mm @@ -7,15 +7,44 @@ #import "RCTEnhancedScrollView.h" #import +#import #import +#if RCT_USE_KMP && TARGET_OS_IOS && !TARGET_OS_MACCATALYST +#define RCT_SCROLL_SNAP_USE_KMP 1 +#import +#else +#define RCT_SCROLL_SNAP_USE_KMP 0 +#endif + @interface RCTEnhancedScrollView () @end @implementation RCTEnhancedScrollView { __weak id _publicDelegate; BOOL _isSetContentOffsetDisabled; +#if RCT_SCROLL_SNAP_USE_KMP + RNSScrollSnapOffsets *_sharedSnapOffsets; +#endif +} + +#if RCT_SCROLL_SNAP_USE_KMP +@synthesize snapToOffsets = _snapToOffsets; + +- (void)setSnapToOffsets:(NSArray *)snapToOffsets +{ + _snapToOffsets = [snapToOffsets copy]; + _sharedSnapOffsets = nil; + if (_snapToOffsets.count > 0) { + // Convert once per property update, retaining the existing floatValue precision. + RNSKotlinDoubleArray *offsets = [RNSKotlinDoubleArray arrayWithSize:(int32_t)_snapToOffsets.count]; + for (NSUInteger i = 0; i < _snapToOffsets.count; i++) { + [offsets setIndex:(int32_t)i value:_snapToOffsets[i].floatValue]; + } + _sharedSnapOffsets = [[RNSScrollSnapOffsets alloc] initWithOffsets:offsets]; + } } +#endif + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { @@ -199,6 +228,15 @@ - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView // Calculate the snap offsets adjacent to the initial offset target CGFloat targetOffset = isHorizontal ? targetContentOffset->x : targetContentOffset->y; +#if RCT_SCROLL_SNAP_USE_KMP + targetOffset = [_sharedSnapOffsets resolveCurrentOffset:offsetAlongAxis + targetOffset:targetOffset + maximumOffset:maximumOffset + velocity:velocityAlongAxis + snapToStart:self.snapToStart + snapToEnd:self.snapToEnd] + .targetOffset; +#else CGFloat smallerOffset = 0.0; CGFloat largerOffset = maximumOffset; @@ -250,6 +288,7 @@ - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView // Make sure the new offset isn't out of bounds targetOffset = MIN(MAX(0, targetOffset), maximumOffset); +#endif // Set new targetContentOffset if (isHorizontal) { diff --git a/packages/react-native/React/Fabric/Utils/RCTGradientUtils.mm b/packages/react-native/React/Fabric/Utils/RCTGradientUtils.mm index ee0f5ff8e0c9..8efb481a1d6f 100644 --- a/packages/react-native/React/Fabric/Utils/RCTGradientUtils.mm +++ b/packages/react-native/React/Fabric/Utils/RCTGradientUtils.mm @@ -8,10 +8,18 @@ #import "RCTGradientUtils.h" #import #import +#import #import #include #import +#if RCT_USE_KMP && TARGET_OS_IOS && !TARGET_OS_MACCATALYST +#define RCT_GRADIENT_USE_KMP 1 +#import +#else +#define RCT_GRADIENT_USE_KMP 0 +#endif + using namespace facebook::react; namespace { @@ -156,6 +164,45 @@ CGSize calculateMultipliers(CGSize bounds) return std::nullopt; } +#if RCT_GRADIENT_USE_KMP +static std::vector resolveSharedColorStops( + const std::vector &colorStops, + CGFloat gradientLineLength) +{ + NSMutableArray *inputs = [NSMutableArray arrayWithCapacity:colorStops.size()]; + for (const auto &stop : colorStops) { + auto position = resolveColorStopPosition(stop.position, gradientLineLength); + RNSDouble *boxedPosition = position.has_value() ? [RNSDouble numberWithDouble:position.value()] : nil; + auto input = [[RNSGradientStopInput alloc] initWithPosition:boxedPosition hasColor:static_cast(stop.color)]; + [inputs addObject:input]; + } + + auto resolved = [RNSGradientStops.shared resolveStops:inputs epsilon:kDefaultEpsilon useDoublePrecision:YES]; + std::vector result; + result.reserve(resolved.count); + NSArray *inputRange = @[ @0.0, @1.0 ]; + for (RNSResolvedGradientStop *stop in resolved) { + const auto &leftColor = colorStops[stop.leftColorIndex].color; + SharedColor color; + if (stop.leftColorIndex == stop.rightColorIndex) { + // Preserve the original native color, including dynamic UIColor behavior. + color = leftColor; + } else if (std::isfinite(stop.weight)) { + const auto &rightColor = colorStops[stop.rightColorIndex].color; + NSArray *outputRange = + @[ RCTUIColorFromSharedColor(leftColor), RCTUIColorFromSharedColor(rightColor) ]; + auto interpolatedColor = RCTInterpolateColorInRange(stop.weight, inputRange, outputRange); + auto alpha = (interpolatedColor >> 24) & 0xFF; + auto red = (interpolatedColor >> 16) & 0xFF; + auto green = (interpolatedColor >> 8) & 0xFF; + auto blue = interpolatedColor & 0xFF; + color = colorFromRGBA(red, green, blue, alpha); + } + result.push_back({.color = color, .position = stop.position}); + } + return result; +} +#else // Spec: https://drafts.csswg.org/css-images-4/#coloring-gradient-line (Refer transition hint section) // Browsers add 9 intermediate color stops when a transition hint is present // Algorithm is referred from Blink engine @@ -261,12 +308,16 @@ CGSize calculateMultipliers(CGSize bounds) return colorStops; } +#endif @implementation RCTGradientUtils // https://drafts.csswg.org/css-images-4/#color-stop-fixup + (std::vector)getFixedColorStops:(const std::vector &)colorStops gradientLineLength:(CGFloat)gradientLineLength { +#if RCT_GRADIENT_USE_KMP + return resolveSharedColorStops(colorStops, gradientLineLength); +#else if (colorStops.empty()) { return {}; } @@ -334,6 +385,7 @@ @implementation RCTGradientUtils } } return processColorTransitionHints(fixedColorStops); +#endif } // CAGradientLayer linear gradient squishes the non-square gradient to square gradient. diff --git a/packages/react-native/React/React-RCTFabric.podspec b/packages/react-native/React/React-RCTFabric.podspec index 121669d1fa0e..92b4de666d5b 100644 --- a/packages/react-native/React/React-RCTFabric.podspec +++ b/packages/react-native/React/React-RCTFabric.podspec @@ -17,6 +17,10 @@ else end new_arch_flags = ENV['RCT_NEW_ARCH_ENABLED'] == '1' ? ' -DRCT_NEW_ARCH_ENABLED=1' : '' +kmp_enabled = ENV['RCT_USE_KMP'] == '1' +if kmp_enabled && ENV['RCT_USE_PREBUILT_RNCORE'] != '0' + raise 'RCT_USE_KMP=1 requires React Native core source builds. Use use_react_native! or set RCT_USE_PREBUILT_RNCORE=0.' +end header_search_paths = [ "\"$(PODS_TARGET_SRCROOT)/ReactCommon\"", @@ -50,13 +54,24 @@ Pod::Spec.new do |s| s.module_name = module_name s.weak_framework = "JavaScriptCore" s.framework = "MobileCoreServices" - s.pod_target_xcconfig = { + pod_target_xcconfig = { "HEADER_SEARCH_PATHS" => header_search_paths, "OTHER_CFLAGS" => "$(inherited) " + new_arch_flags, "CLANG_CXX_LANGUAGE_STANDARD" => rct_cxx_language_standard() }.merge!(ENV['USE_FRAMEWORKS'] != nil ? { "PUBLIC_HEADERS_FOLDER_PATH" => "#{module_name}.framework/Headers/#{header_dir}" }: {}) + if kmp_enabled + # Catalyst has no Kotlin/Native target. Its build keeps the existing implementation. + s.dependency 'React-KMP' + pod_target_xcconfig.merge!({ + 'GCC_PREPROCESSOR_DEFINITIONS[sdk=iphoneos*]' => '$(inherited) RCT_USE_KMP=1', + 'GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*]' => '$(inherited) RCT_USE_KMP=1', + 'FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]' => '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeSharedKMP"', + 'FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]' => '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeSharedKMP"', + }) + end + s.pod_target_xcconfig = pod_target_xcconfig s.dependency "React-Core" s.dependency "React-RCTImage" diff --git a/packages/react-native/ReactAndroid/build.gradle.kts b/packages/react-native/ReactAndroid/build.gradle.kts index f792d51a8567..f548f678cf58 100644 --- a/packages/react-native/ReactAndroid/build.gradle.kts +++ b/packages/react-native/ReactAndroid/build.gradle.kts @@ -717,6 +717,12 @@ tasks.withType().configureEach { } dependencies { + // Embed the common Kotlin implementation in react-android's AAR. This keeps published + // consumers on the existing artifact instead of requiring a separate KMP publication. + implementation( + files("$reactNativeRootDir/ReactShared/build/android/react-native-shared.jar") + .builtBy(gradle.includedBuild("react-native-shared").task(":exportAndroidJar")) + ) api(libs.androidx.appcompat) api(libs.androidx.appcompat.resources) api(libs.androidx.autofill) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt index f7d4d12d4b93..8e7eb1173ff8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt @@ -9,6 +9,8 @@ package com.facebook.react.devsupport +import com.facebook.react.shared.MultipartFraming +import com.facebook.react.shared.MultipartHeaders import java.io.IOException import java.util.TreeMap import kotlin.math.max @@ -52,30 +54,22 @@ internal class MultipartStreamReader( // throughput and fewer syscalls. For a 2MB bundle: ~128 reads instead of ~512. // Memory impact is negligible (12KB increase) while I/O overhead is significantly reduced. val bufferLen = 16 * 1024 - var chunkStart: Long = 0 - var bytesSeen: Long = 0 + val framing = MultipartFraming(delimiter.size(), closeDelimiter.size()) + var bufferOffset = 0L val content = Buffer() var currentHeaders: Map? = null var currentBodyStartIndexInContent: Long = -1 while (true) { - var isCloseDelimiter = false - - // Search only a subset of chunk that we haven't seen before + few bytes - // to allow for the edge case when the delimiter is cut by read call. - val searchStart = - max((bytesSeen - closeDelimiter.size()).toDouble(), chunkStart.toDouble()).toLong() - - var indexOfDelimiter = content.indexOf(delimiter, searchStart) - if (indexOfDelimiter == -1L) { - isCloseDelimiter = true - indexOfDelimiter = content.indexOf(closeDelimiter, searchStart) - } - - if (indexOfDelimiter == -1L) { - bytesSeen = content.size() - + val searchStart = framing.searchStart(bufferOffset) + val indexOfDelimiter = content.indexOf(delimiter, searchStart) + val indexOfCloseDelimiter = + if (indexOfDelimiter < 0) content.indexOf(closeDelimiter, searchStart) else -1L + val chunk = + framing.nextChunk(content.size(), bufferOffset, indexOfDelimiter, indexOfCloseDelimiter) + + if (chunk == null) { if (currentHeaders == null) { val indexOfHeadersDelimiter = content.indexOf(headersDelimiter, searchStart) if (indexOfHeadersDelimiter >= 0) { @@ -97,29 +91,27 @@ internal class MultipartStreamReader( continue } - val chunkEnd = indexOfDelimiter - val length = chunkEnd - chunkStart + val chunkEnd = chunk.end + val length = chunkEnd - chunk.start // Ignore preamble - if (chunkStart > 0) { + if (chunk.isPart) { if (currentHeaders != null && currentBodyStartIndexInContent >= 0) { val loadedFinal = max(0L, chunkEnd - currentBodyStartIndexInContent) emitProgress(currentHeaders, loadedFinal, true, listener) } - content.skip(chunkStart) - emitChunk(content, length, isCloseDelimiter, listener) + content.skip(chunk.start) + emitChunk(content, length, chunk.isLast, listener) currentHeaders = null currentBodyStartIndexInContent = -1 } else { content.skip(chunkEnd) } - if (isCloseDelimiter) { + if (chunk.isLast) { return true } - - chunkStart = delimiter.size().toLong() - bytesSeen = chunkStart + bufferOffset += chunkEnd } } @@ -127,14 +119,9 @@ internal class MultipartStreamReader( // Header names are case-insensitive val headers: MutableMap = TreeMap(String.CASE_INSENSITIVE_ORDER) val text = data.readUtf8() - val lines = text.split(CRLF.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() - for (line in lines) { - val indexOfSeparator = line.indexOf(":") - if (indexOfSeparator == -1) { - continue - } - val key = line.substring(0, indexOfSeparator).trim { it <= ' ' } - val value = line.substring(indexOfSeparator + 1).trim { it <= ' ' } + for (header in MultipartHeaders.parse(text)) { + val key = header.name.trim { it <= ' ' } + val value = header.value.trim { it <= ' ' } headers[key] = value } return headers @@ -156,7 +143,7 @@ internal class MultipartStreamReader( val marker: ByteString = ByteString.encodeUtf8(CRLF + CRLF) val indexOfMarker = content.indexOf(marker, 0) - if (indexOfMarker == -1L || indexOfMarker >= chunkLength) { + if (indexOfMarker == -1L || indexOfMarker > chunkLength - marker.size()) { // No headers marker found inside the chunk. Treat the entire chunk as body. val bodyLength = chunkLength val body = Okio.buffer(FixedLengthSource(content, bodyLength)) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt index 32e101bcbcf1..c2a0eab93a38 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/style/ColorStop.kt @@ -8,11 +8,11 @@ package com.facebook.react.uimanager.style import androidx.core.graphics.ColorUtils -import com.facebook.react.uimanager.FloatUtil +import com.facebook.react.shared.GradientStopInput +import com.facebook.react.shared.GradientStops import com.facebook.react.uimanager.LengthPercentage import com.facebook.react.uimanager.LengthPercentageType import com.facebook.react.uimanager.PixelUtil -import kotlin.math.ln /** * Represents a color stop in a gradient as specified by the user. @@ -68,170 +68,25 @@ internal object ColorStopUtils { colorStops: List, gradientLineLength: Float, ): List { - val fixedColorStops = Array(colorStops.size) { ProcessedColorStop() } - var hasNullPositions = false - var maxPositionSoFar = - resolveColorStopPosition(colorStops[0].position, gradientLineLength) ?: 0f - - for (i in colorStops.indices) { - val colorStop = colorStops[i] - var newPosition = resolveColorStopPosition(colorStop.position, gradientLineLength) - - // Step 1: - // If the first color stop does not have a position, - // set its position to 0%. If the last color stop does not have a position, - // set its position to 100%. - newPosition = - newPosition - ?: when (i) { - 0 -> 0f - colorStops.size - 1 -> 1f - else -> null - } - - // Step 2: - // If a color stop or transition hint has a position - // that is less than the specified position of any color stop or transition hint - // before it in the list, set its position to be equal to the - // largest specified position of any color stop or transition hint before it. - if (newPosition != null) { - newPosition = maxOf(newPosition, maxPositionSoFar) - fixedColorStops[i] = ProcessedColorStop(colorStop.color, newPosition) - maxPositionSoFar = newPosition - } else { - hasNullPositions = true - } - } - - // Step 3: - // If any color stop still does not have a position, - // then, for each run of adjacent color stops without positions, - // set their positions so that they are evenly spaced between the preceding and - // following color stops with positions. - if (hasNullPositions) { - var lastDefinedIndex = 0 - for (i in 1 until fixedColorStops.size) { - val endPosition = fixedColorStops[i].position - val startPosition = fixedColorStops[lastDefinedIndex].position - val unpositionedStops = i - lastDefinedIndex - 1 - if (endPosition != null && startPosition != null && unpositionedStops > 0) { - val increment = (endPosition - startPosition) / (unpositionedStops + 1) - for (j in 1..unpositionedStops) { - fixedColorStops[lastDefinedIndex + j] = - ProcessedColorStop( - colorStops[lastDefinedIndex + j].color, - startPosition + increment * j, - ) - } - lastDefinedIndex = i - } else if (endPosition != null) { - // Current stop has a defined position but there are no unpositioned - // stops between lastDefinedIndex and i. Still need to advance - // lastDefinedIndex so that subsequent interpolation uses the - // correct start point instead of stale data. - lastDefinedIndex = i + val inputs = + colorStops.map { stop -> + GradientStopInput( + resolveColorStopPosition(stop.position, gradientLineLength)?.toDouble(), + stop.color != null, + ) } - } - } - - return processColorTransitionHints(fixedColorStops) - } - - // Spec: https://drafts.csswg.org/css-images-4/#coloring-gradient-line (Refer transition hint - // section) - // Browsers add 9 intermediate color stops when a transition hint is present - // Algorithm is referred from Blink engine - // [source](https://github.com/chromium/chromium/blob/a296b1bad6dc1ed9d751b7528f7ca2134227b828/third_party/blink/renderer/core/css/css_gradient_value.cc#L240). - private fun processColorTransitionHints( - originalStops: Array, - ): List { - val colorStops = originalStops.toMutableList() - var indexOffset = 0 - - for (i in 1 until originalStops.size - 1) { - // Skip if not a color hint - if (originalStops[i].color != null) { - continue - } - - val x = i + indexOffset - if (x < 1) { - continue - } - - val offsetLeft = colorStops[x - 1].position - val offsetRight = colorStops[x + 1].position - val offset = colorStops[x].position - if (offsetLeft == null || offsetRight == null || offset == null) { - continue - } - val leftDist = offset - offsetLeft - val rightDist = offsetRight - offset - val totalDist = offsetRight - offsetLeft - val leftColor = colorStops[x - 1].color - val rightColor = colorStops[x + 1].color - - if (FloatUtil.floatsEqual(leftDist, rightDist)) { - colorStops.removeAt(x) - --indexOffset - continue - } - - if (FloatUtil.floatsEqual(leftDist, 0f)) { - colorStops[x].color = rightColor - continue - } - - if (FloatUtil.floatsEqual(rightDist, 0f)) { - colorStops[x].color = leftColor - continue - } - - val newStops = ArrayList(9) - - // Position the new color stops - if (leftDist > rightDist) { - for (y in 0..6) { - newStops.add(ProcessedColorStop(null, offsetLeft + leftDist * ((7f + y) / 13f))) - } - newStops.add(ProcessedColorStop(null, offset + rightDist * (1f / 3f))) - newStops.add(ProcessedColorStop(null, offset + rightDist * (2f / 3f))) - } else { - newStops.add(ProcessedColorStop(null, offsetLeft + leftDist * (1f / 3f))) - newStops.add(ProcessedColorStop(null, offsetLeft + leftDist * (2f / 3f))) - for (y in 0..6) { - newStops.add(ProcessedColorStop(null, offset + rightDist * (y / 13f))) - } - } - - // Calculate colors for the new stops - val hintRelativeOffset = leftDist / totalDist - val logRatio = ln(0.5) / ln(hintRelativeOffset) - - for (newStop in newStops) { - if (newStop.position == null) { - continue - } - val pointRelativeOffset = (newStop.position - offsetLeft) / totalDist - val weighting = Math.pow(pointRelativeOffset.toDouble(), logRatio).toFloat() - - if (!weighting.isFinite() || weighting.isNaN()) { - continue - } - - // Interpolate color using the calculated weighting - leftColor?.let { left -> - rightColor?.let { right -> newStop.color = ColorUtils.blendARGB(left, right, weighting) } - } - } - - // Replace the color hint with new color stops - colorStops.removeAt(x) - colorStops.addAll(x, newStops) - indexOffset += 8 + return GradientStops.resolve(inputs, epsilon = .00001f.toDouble()).map { stop -> + val leftColor = colorStops[stop.leftColorIndex].color + val rightColor = colorStops[stop.rightColorIndex].color + val weighting = stop.weight.toFloat() + val color = + when { + stop.leftColorIndex == stop.rightColorIndex -> leftColor + leftColor == null || rightColor == null || !weighting.isFinite() -> null + else -> ColorUtils.blendARGB(leftColor, rightColor, weighting) + } + ProcessedColorStop(color, stop.position.toFloat()) } - - return colorStops } private fun resolveColorStopPosition( diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.kt index 1bfb84f45368..1000cad9cf66 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.kt @@ -35,6 +35,8 @@ import com.facebook.react.R import com.facebook.react.common.ReactConstants import com.facebook.react.common.build.ReactBuildConfig import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.shared.ScrollSnapDirection +import com.facebook.react.shared.ScrollSnapOffsets import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.HasChildPressedStateDelay import com.facebook.react.uimanager.LengthPercentage @@ -169,6 +171,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : private var disableIntervalMomentum = false private var snapInterval = 0 private var snapOffsets: List? = null + private var sharedSnapOffsets: ScrollSnapOffsets? = null private var snapToStart = true private var snapToEnd = true private var snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -277,6 +280,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : disableIntervalMomentum = false snapInterval = 0 snapOffsets = null + sharedSnapOffsets = null snapToStart = true snapToEnd = true snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -388,6 +392,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : public open fun setSnapOffsets(snapOffsets: List?) { this.snapOffsets = snapOffsets + sharedSnapOffsets = snapOffsets?.let { ScrollSnapOffsets.fromIntegerOffsets(it) } } public open fun setSnapToStart(snapToStart: Boolean) { @@ -1223,8 +1228,8 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : var smallerOffset = 0 var largerOffset = maximumOffset - var firstOffset = 0 - var lastOffset = maximumOffset + val firstOffset = 0 + val lastOffset = maximumOffset val viewportWidth = width - paddingStart - paddingEnd // offsets are from the right edge in RTL layouts @@ -1233,26 +1238,21 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : velocityX = -velocityX } - // get the nearest snap points to the target offset - val offsets = snapOffsets - if (!offsets.isNullOrEmpty()) { - firstOffset = offsets[0] - lastOffset = offsets[offsets.size - 1] - - for (i in offsets.indices) { - val offset = offsets[i] - if (offset <= targetOffset) { - if (targetOffset - offset < targetOffset - smallerOffset) { - smallerOffset = offset - } - } - if (offset >= targetOffset) { - if (offset - targetOffset < largerOffset - targetOffset) { - largerOffset = offset - } - } - } - } else if (snapToAlignment != SNAP_ALIGNMENT_DISABLED) { + val snapResult = + sharedSnapOffsets + ?.takeIf { !snapOffsets.isNullOrEmpty() } + ?.resolve( + currentOffset = + (if (layoutDirection == LAYOUT_DIRECTION_RTL) maximumOffset - scrollX + else scrollX) + .toDouble(), + targetOffset = targetOffset.toDouble(), + maximumOffset = maximumOffset.toDouble(), + velocity = velocityX.toDouble(), + snapToStart = snapToStart, + snapToEnd = snapToEnd, + ) + if (snapResult == null && snapToAlignment != SNAP_ALIGNMENT_DISABLED) { if (snapInterval > 0) { val ratio = targetOffset.toDouble() / snapInterval smallerOffset = @@ -1303,7 +1303,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : smallerOffset = max(smallerOffset, smallerChildOffset) largerOffset = kotlin.math.min(largerOffset, largerChildOffset) } - } else { + } else if (snapResult == null) { val interval = getSnapInterval().toDouble() val ratio = targetOffset.toDouble() / interval smallerOffset = (floor(ratio) * interval).toInt() @@ -1321,7 +1321,18 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : if (layoutDirection == LAYOUT_DIRECTION_RTL) { currentOffset = maximumOffset - currentOffset } - if (!snapToEnd && targetOffset >= lastOffset) { + if (snapResult != null) { + if (!hasCustomizedFlingAnimator) { + when (snapResult.direction) { + ScrollSnapDirection.FORWARD -> + velocityX += ((snapResult.selectedOffset.toInt() - targetOffset) * 10.0).toInt() + ScrollSnapDirection.BACKWARD -> + velocityX -= ((targetOffset - snapResult.selectedOffset.toInt()) * 10.0).toInt() + ScrollSnapDirection.NONE -> {} + } + } + targetOffset = snapResult.targetOffset.toInt() + } else if (!snapToEnd && targetOffset >= lastOffset) { if (currentOffset >= lastOffset) { // free scrolling } else { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactNestedScrollView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactNestedScrollView.kt index 45fee3cd19d1..b77233a0af61 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactNestedScrollView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactNestedScrollView.kt @@ -37,6 +37,8 @@ import com.facebook.react.R import com.facebook.react.bridge.ReadableMap import com.facebook.react.common.ReactConstants import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.shared.ScrollSnapDirection +import com.facebook.react.shared.ScrollSnapOffsets import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.HasChildPressedStateDelay import com.facebook.react.uimanager.LengthPercentage @@ -203,6 +205,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : private var disableIntervalMomentum = false private var snapInterval = 0 private var snapOffsets: List? = null + private var sharedSnapOffsets: ScrollSnapOffsets? = null private var snapToStart = true private var snapToEnd = true private var snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -252,6 +255,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : disableIntervalMomentum = false snapInterval = 0 snapOffsets = null + sharedSnapOffsets = null snapToStart = true snapToEnd = true snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -359,6 +363,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : open fun setSnapOffsets(snapOffsets: List?) { this.snapOffsets = snapOffsets + sharedSnapOffsets = snapOffsets?.let { ScrollSnapOffsets.fromIntegerOffsets(it) } } open fun setSnapToStart(snapToStart: Boolean) { @@ -923,29 +928,20 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : var smallerOffset = 0 var largerOffset = maximumOffset - var firstOffset = 0 - var lastOffset = maximumOffset + val firstOffset = 0 + val lastOffset = maximumOffset val viewportHeight = height - paddingBottom - paddingTop - val currentSnapOffsets = snapOffsets - if (currentSnapOffsets != null) { - firstOffset = currentSnapOffsets[0] - lastOffset = currentSnapOffsets[currentSnapOffsets.size - 1] - - for (i in currentSnapOffsets.indices) { - val offset = currentSnapOffsets[i] - if (offset <= targetOffset) { - if (targetOffset - offset < targetOffset - smallerOffset) { - smallerOffset = offset - } - } - if (offset >= targetOffset) { - if (offset - targetOffset < largerOffset - targetOffset) { - largerOffset = offset - } - } - } - } else if (snapToAlignment != SNAP_ALIGNMENT_DISABLED) { + val snapResult = + sharedSnapOffsets?.resolve( + currentOffset = scrollY.toDouble(), + targetOffset = targetOffset.toDouble(), + maximumOffset = maximumOffset.toDouble(), + velocity = velocityY.toDouble(), + snapToStart = snapToStart, + snapToEnd = snapToEnd, + ) + if (snapResult == null && snapToAlignment != SNAP_ALIGNMENT_DISABLED) { if (snapInterval > 0) { val ratio = targetOffset.toDouble() / snapInterval smallerOffset = @@ -998,7 +994,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : smallerOffset = max(smallerOffset, smallerChildOffset) largerOffset = min(largerOffset, largerChildOffset) } - } else { + } else if (snapResult == null) { val interval = getSnapInterval().toDouble() val ratio = targetOffset.toDouble() / interval smallerOffset = (floor(ratio) * interval).toInt() @@ -1009,7 +1005,18 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : if (abs(targetOffset - smallerOffset) < abs(largerOffset - targetOffset)) smallerOffset else largerOffset - if (!snapToEnd && targetOffset >= lastOffset) { + if (snapResult != null) { + if (!hasCustomizedFlingAnimator) { + when (snapResult.direction) { + ScrollSnapDirection.FORWARD -> + velocityY += ((snapResult.selectedOffset.toInt() - targetOffset) * 10.0).toInt() + ScrollSnapDirection.BACKWARD -> + velocityY -= ((targetOffset - snapResult.selectedOffset.toInt()) * 10.0).toInt() + ScrollSnapDirection.NONE -> {} + } + } + targetOffset = snapResult.targetOffset.toInt() + } else if (!snapToEnd && targetOffset >= lastOffset) { if (scrollY >= lastOffset) { // free scrolling } else { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.kt index b553f6af997d..1454fd3a7b99 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.kt @@ -29,6 +29,8 @@ import com.facebook.react.R import com.facebook.react.bridge.ReadableMap import com.facebook.react.common.ReactConstants import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.shared.ScrollSnapDirection +import com.facebook.react.shared.ScrollSnapOffsets import com.facebook.react.uimanager.BackgroundStyleApplicator import com.facebook.react.uimanager.HasChildPressedStateDelay import com.facebook.react.uimanager.LengthPercentage @@ -195,6 +197,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : private var disableIntervalMomentum = false private var snapInterval = 0 private var snapOffsets: List? = null + private var sharedSnapOffsets: ScrollSnapOffsets? = null private var snapToStart = true private var snapToEnd = true private var snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -244,6 +247,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : disableIntervalMomentum = false snapInterval = 0 snapOffsets = null + sharedSnapOffsets = null snapToStart = true snapToEnd = true snapToAlignment = SNAP_ALIGNMENT_DISABLED @@ -351,6 +355,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : public open fun setSnapOffsets(snapOffsets: List?) { this.snapOffsets = snapOffsets + sharedSnapOffsets = snapOffsets?.let { ScrollSnapOffsets.fromIntegerOffsets(it) } } public open fun setSnapToStart(snapToStart: Boolean) { @@ -915,29 +920,20 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : var smallerOffset = 0 var largerOffset = maximumOffset - var firstOffset = 0 - var lastOffset = maximumOffset + val firstOffset = 0 + val lastOffset = maximumOffset val viewportHeight = height - paddingBottom - paddingTop - val currentSnapOffsets = snapOffsets - if (currentSnapOffsets != null) { - firstOffset = currentSnapOffsets[0] - lastOffset = currentSnapOffsets[currentSnapOffsets.size - 1] - - for (i in currentSnapOffsets.indices) { - val offset = currentSnapOffsets[i] - if (offset <= targetOffset) { - if (targetOffset - offset < targetOffset - smallerOffset) { - smallerOffset = offset - } - } - if (offset >= targetOffset) { - if (offset - targetOffset < largerOffset - targetOffset) { - largerOffset = offset - } - } - } - } else if (snapToAlignment != SNAP_ALIGNMENT_DISABLED) { + val snapResult = + sharedSnapOffsets?.resolve( + currentOffset = scrollY.toDouble(), + targetOffset = targetOffset.toDouble(), + maximumOffset = maximumOffset.toDouble(), + velocity = velocityY.toDouble(), + snapToStart = snapToStart, + snapToEnd = snapToEnd, + ) + if (snapResult == null && snapToAlignment != SNAP_ALIGNMENT_DISABLED) { if (snapInterval > 0) { val ratio = targetOffset.toDouble() / snapInterval smallerOffset = @@ -990,7 +986,7 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : smallerOffset = max(smallerOffset, smallerChildOffset) largerOffset = min(largerOffset, largerChildOffset) } - } else { + } else if (snapResult == null) { val interval = getSnapInterval().toDouble() val ratio = targetOffset.toDouble() / interval smallerOffset = (floor(ratio) * interval).toInt() @@ -1001,7 +997,18 @@ constructor(context: Context, private val fpsListener: FpsListener? = null) : if (abs(targetOffset - smallerOffset) < abs(largerOffset - targetOffset)) smallerOffset else largerOffset - if (!snapToEnd && targetOffset >= lastOffset) { + if (snapResult != null) { + if (!hasCustomizedFlingAnimator) { + when (snapResult.direction) { + ScrollSnapDirection.FORWARD -> + velocityY += ((snapResult.selectedOffset.toInt() - targetOffset) * 10.0).toInt() + ScrollSnapDirection.BACKWARD -> + velocityY -= ((targetOffset - snapResult.selectedOffset.toInt()) * 10.0).toInt() + ScrollSnapDirection.NONE -> {} + } + } + targetOffset = snapResult.targetOffset.toInt() + } else if (!snapToEnd && targetOffset >= lastOffset) { if (scrollY >= lastOffset) { // free scrolling } else { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt index 1ef4499184aa..84d227da0fa3 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt @@ -10,6 +10,8 @@ package com.facebook.react.devsupport import okio.Buffer import okio.BufferedSource import okio.ByteString +import okio.ForwardingSource +import okio.Okio import org.assertj.core.api.Assertions.assertThat import org.junit.Test @@ -212,6 +214,93 @@ class MultipartStreamReaderTest { assertThat(callback.callCount).isEqualTo(1) } + @Test + @Suppress("DEPRECATION_ERROR") // Match the reader's compatibility with legacy Okio. + fun testDelimitersAcrossEveryReadBoundary() { + // The trailing CRLF must not become a header separator spanning the next boundary. + val body = "binary\u0000\r\n--samplX\r\n--sample-\r\n" + val response = "preamble\r\n--sample\r\n${body}\r\n--sample\r\nsecond\r\n--sample--\r\nepilogue" + for (readSize in 1..response.length) { + val upstream = Buffer().writeUtf8(response) + val source = + Okio.buffer( + object : ForwardingSource(upstream) { + override fun read(sink: Buffer, byteCount: Long): Long = + super.read(sink, minOf(byteCount, readSize.toLong())) + } + ) + val parts = mutableListOf() + val last = mutableListOf() + val success = + MultipartStreamReader(source, "sample") + .readAllParts( + object : CallCountTrackingChunkCallback() { + override fun onChunkComplete( + headers: Map, + body: BufferedSource, + isLastChunk: Boolean, + ) { + parts.add(body.readUtf8()) + last.add(isLastChunk) + } + } + ) + assertThat(success).describedAs("read size %s", readSize).isTrue() + assertThat(parts).containsExactly(body, "second") + assertThat(last).containsExactly(false, true) + } + } + + @Test + fun testHeaderWhitespaceDuplicatesAndColonValues() { + val source = + Buffer() + .writeUtf8( + "\r\n--sample\r\n X-Name : first\r\nx-name: second:extra \r\ninvalid\r\n\r\nbody\r\n--sample--\r\n" + ) + var calls = 0 + assertThat( + MultipartStreamReader(source, "sample") + .readAllParts( + object : CallCountTrackingChunkCallback() { + override fun onChunkComplete( + headers: Map, + body: BufferedSource, + isLastChunk: Boolean, + ) { + calls++ + assertThat(headers).hasSize(1) + assertThat(headers["X-Name"]).isEqualTo("second:extra") + assertThat(body.readUtf8()).isEqualTo("body") + assertThat(isLastChunk).isTrue() + } + } + ) + ) + .isTrue() + assertThat(calls).isEqualTo(1) + } + + @Test + fun testFinalProgressForFragmentedBody() { + val body = "x".repeat(64 * 1024) + val source = + Buffer() + .writeUtf8( + "\r\n--sample\r\nContent-Length: ${body.length}\r\n\r\n$body\r\n--sample--\r\n" + ) + val progress = mutableListOf>() + val callback = + object : CallCountTrackingChunkCallback() { + override fun onChunkProgress(headers: Map, loaded: Long, total: Long) { + progress.add(loaded to total) + } + } + assertThat(MultipartStreamReader(source, "sample").readAllParts(callback)).isTrue() + assertThat(callback.callCount).isEqualTo(1) + assertThat(progress.last()).isEqualTo(body.length.toLong() to body.length.toLong()) + } + internal open class CallCountTrackingChunkCallback : MultipartStreamReader.ChunkListener { var callCount = 0 private set diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt index 005b0bf6d4c6..fa89503d22fc 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/uimanager/style/ColorStopTest.kt @@ -176,4 +176,90 @@ class ColorStopTest { assertThat(processed[4].color).isEqualTo(Color.MAGENTA) assertThat(processed[4].position).isEqualTo(1f) } + + @Test + fun testPointPositionsUseAndroidDisplayDensityBeforeSharedFixup() { + val metrics = DisplayMetrics() + metrics.density = 2f + DisplayMetricsHolder.setScreenDisplayMetrics(metrics) + val colorStops = + listOf( + ColorStop(Color.RED, LengthPercentage(25f, LengthPercentageType.POINT)), + ColorStop(Color.BLUE, LengthPercentage(100f, LengthPercentageType.PERCENT)), + ) + + val processed = ColorStopUtils.getFixedColorStops(colorStops, 200f) + + assertThat(processed[0].position).isEqualTo(.25f) + assertThat(processed[1].position).isEqualTo(1f) + } + + @Test + fun testTransitionHintKeepsAndroidColorAndAlphaRounding() { + val colorStops = + listOf( + ColorStop(Color.argb(128, 255, 0, 0)), + ColorStop(null, LengthPercentage(25f, LengthPercentageType.PERCENT)), + ColorStop(Color.BLUE), + ) + + val processed = ColorStopUtils.getFixedColorStops(colorStops, 100f) + + assertThat(processed).hasSize(11) + assertThat(processed[3].position).isEqualTo(.25f) + assertThat(processed[3].color).isEqualTo(Color.argb(191, 127, 0, 127)) + assertThat(processed.first().color).isEqualTo(Color.argb(128, 255, 0, 0)) + assertThat(processed.last().color).isEqualTo(Color.BLUE) + } + + @Test + fun testEndpointHintsReuseTheOppositeColorWithoutBlending() { + for ((hintPosition, expectedColor) in listOf(0f to Color.BLUE, 100f to Color.RED)) { + val colorStops = + listOf( + ColorStop(Color.RED), + ColorStop(null, LengthPercentage(hintPosition, LengthPercentageType.PERCENT)), + ColorStop(Color.BLUE), + ) + + val processed = ColorStopUtils.getFixedColorStops(colorStops, 100f) + + assertThat(processed).hasSize(3) + assertThat(processed[1].color).isEqualTo(expectedColor) + assertThat(processed[1].position).isEqualTo(hintPosition / 100f) + } + } + + @Test + fun testCenteredHintDoesNotChangeTheColors() { + val colorStops = + listOf( + ColorStop(Color.RED), + ColorStop(null, LengthPercentage(50f, LengthPercentageType.PERCENT)), + ColorStop(Color.BLUE), + ) + + val processed = ColorStopUtils.getFixedColorStops(colorStops, 100f) + + assertThat(processed).hasSize(2) + assertThat(processed[0].color).isEqualTo(Color.RED) + assertThat(processed[1].color).isEqualTo(Color.BLUE) + } + + @Test + fun testZeroLengthGradientKeepsNonFiniteSamplesUncolored() { + val colorStops = + listOf( + ColorStop(Color.RED), + ColorStop(null, LengthPercentage(10f, LengthPercentageType.POINT)), + ColorStop(Color.BLUE, LengthPercentage(20f, LengthPercentageType.POINT)), + ) + + val processed = ColorStopUtils.getFixedColorStops(colorStops, 0f) + + assertThat(processed).hasSize(11) + assertThat(processed.first().color).isEqualTo(Color.RED) + assertThat(processed.last().color).isEqualTo(Color.BLUE) + assertThat(processed.subList(1, 10).all { it.color == null }).isTrue() + } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/scroll/ReactScrollSnapOffsetsTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/scroll/ReactScrollSnapOffsetsTest.kt new file mode 100644 index 000000000000..a837024b9b0e --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/scroll/ReactScrollSnapOffsetsTest.kt @@ -0,0 +1,295 @@ +/* + * 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.views.scroll + +import android.animation.ValueAnimator +import android.graphics.Point +import android.view.View +import android.view.ViewGroup +import android.widget.OverScroller +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockedStatic +import org.mockito.Mockito +import org.mockito.stubbing.Answer +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** Exercises the real flingAndSnap methods while recording their native physics calls. */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class ReactScrollSnapOffsetsTest { + private val drivers = mutableListOf() + private lateinit var helper: MockedStatic + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + helper = + Mockito.mockStatic( + ReactScrollViewHelper::class.java, + Answer { invocation -> + if (invocation.method.name == "predictFinalScrollPosition") { + val driver = drivers.single { it.view === invocation.arguments[0] } + if (driver.horizontal) Point(driver.predicted, 0) else Point(0, driver.predicted) + } else { + invocation.callRealMethod() + } + }, + ) + } + + @After + fun tearDown() { + helper.close() + } + + private fun eachView(block: (ScrollSnapTestDriver) -> Unit) { + for (name in listOf("ReactScrollView", "ReactNestedScrollView", "ReactHorizontalScrollView")) { + val driver = ScrollSnapTestDriver(name) + drivers.add(driver) + block(driver) + } + } + + @Test + fun explicitOffsetsPreserveNativeVelocityBoost() = eachView { driver -> + driver.setOffsets(listOf(20, 60, 100)) + driver.predicted = 40 + assertEquals(ScrollSnapObservation(60, 210, 0), driver.fling(10)) + assertEquals(ScrollSnapObservation(20, -210, 0), driver.fling(-10)) + assertEquals(ScrollSnapObservation(60, 60, 0), driver.fling(0)) + } + + @Test + fun customizedAnimatorReceivesOnlyTheSelectedTarget() = eachView { driver -> + driver.customAnimator = true + driver.setOffsets(listOf(20, 60, 100)) + driver.predicted = 40 + assertEquals(ScrollSnapObservation(60, null, null), driver.fling(10)) + assertEquals(ScrollSnapObservation(20, null, null), driver.fling(-10)) + } + + @Test + fun disabledBoundariesPreserveFreeScrollingAndCrossing() = eachView { driver -> + driver.setOffsets(listOf(20, 60, 100)) + driver.set("setSnapToStart", false) + driver.set("setSnapToEnd", false) + driver.current = 110 + driver.predicted = 120 + assertEquals(ScrollSnapObservation(120, 10, 0), driver.fling(10)) + driver.current = 90 + assertEquals(ScrollSnapObservation(100, 10, 0), driver.fling(10)) + driver.current = 10 + driver.predicted = 0 + assertEquals(ScrollSnapObservation(0, -10, 100), driver.fling(-10)) + driver.current = 30 + assertEquals(ScrollSnapObservation(20, -10, 0), driver.fling(-10)) + } + + @Test + fun disablingMomentumUsesCurrentOffsetBeforeSelecting() = eachView { driver -> + driver.setOffsets(listOf(20, 60, 100)) + driver.set("setDisableIntervalMomentum", true) + driver.current = 25 + driver.predicted = 90 + assertEquals(ScrollSnapObservation(60, 360, 0), driver.fling(10)) + } + + @Test + fun propertyChangesAndNativeMutationsRemainVisible() = eachView { driver -> + driver.customAnimator = true + val offsets = mutableListOf(20, 60, 100) + driver.setOffsets(offsets) + driver.predicted = 40 + offsets[1] = 90 + assertEquals(90, driver.fling(10).target) + offsets.add(50) + assertEquals(50, driver.fling(10).target) + driver.setOffsets(listOf(20, 80, 100)) + assertEquals(80, driver.fling(10).target) + driver.setOffsets(null) + driver.set("setSnapInterval", 50) + assertEquals(50, driver.fling(10).target) + } + + @Test + fun clearingRetainedListsPreservesPlatformEmptyListBehavior() = eachView { driver -> + val offsets = mutableListOf(20, 60, 100) + driver.setOffsets(offsets) + driver.set("setSnapInterval", 50) + driver.predicted = 40 + offsets.clear() + if (driver.horizontal) { + assertEquals(50, driver.fling(10).target) + } else { + val failure = + assertThrows(java.lang.reflect.InvocationTargetException::class.java) { driver.fling(10) } + assertTrue(failure.cause is IndexOutOfBoundsException) + } + } + + @Test + fun recyclingClearsTheSelectorBeforeNativeIntervalSnapping() = eachView { driver -> + driver.setOffsets(listOf(20, 60, 100)) + driver.recycle() + driver.set("setSnapInterval", 50) + driver.predicted = 40 + assertEquals(50, driver.fling(10).target) + } + + @Test + fun extremeOffsetsPreserveAndroidIntegerArithmetic() = eachView { driver -> + driver.setOffsets(listOf(Int.MIN_VALUE, 20, 100)) + driver.predicted = 150 + assertEquals(ScrollSnapObservation(300, 300, 100), driver.fling(0)) + } + + @Test + fun horizontalRtlKeepsCoordinatesAndVelocityInNativeSpace() { + val driver = ScrollSnapTestDriver("ReactHorizontalScrollView") + drivers.add(driver) + driver.rtl = true + driver.current = 280 + driver.predicted = 260 + driver.setOffsets(listOf(20, 60, 100)) + assertEquals(ScrollSnapObservation(240, -210, 0), driver.fling(-10)) + assertEquals(ScrollSnapObservation(280, 210, 0), driver.fling(10)) + } +} + +internal data class ScrollSnapObservation(val target: Int, val velocity: Int?, val overscroll: Int?) + +/** + * Native prediction/rendering are controlled; selection and velocity adjustment execute unchanged. + */ +internal class ScrollSnapTestDriver(name: String) { + val horizontal = name.contains("Horizontal") + var current = 0 + var predicted = 0 + var maximum = 300 + var rtl = false + var customAnimator = false + private var observation: ScrollSnapObservation? = null + private val type = + Class.forName("com.facebook.react.views.scroll.$name").asSubclass(ViewGroup::class.java) + private val defaultAnimator = Mockito.mock(ValueAnimator::class.java) + private val otherAnimator = Mockito.mock(ValueAnimator::class.java) + private val state = ReactScrollViewHelper.ReactScrollViewScrollState().apply { isFinished = true } + private val child = + Mockito.mock( + View::class.java, + Answer { invocation -> + when (invocation.method.name) { + "getHeight", + "getWidth", + "getBottom", + "getRight" -> maximum + 200 + else -> Mockito.RETURNS_DEFAULTS.answer(invocation) + } + }, + ) + private val scroller = + Mockito.mock( + OverScroller::class.java, + Answer { invocation -> + if (invocation.method.name == "fling") { + val args = invocation.arguments + observation = + ScrollSnapObservation( + args[if (horizontal) 4 else 6] as Int, + args[if (horizontal) 2 else 3] as Int, + args[if (horizontal) 8 else 9] as Int, + ) + null + } else { + Mockito.RETURNS_DEFAULTS.answer(invocation) + } + }, + ) + val view: ViewGroup = + Mockito.mock( + type, + Answer { invocation -> + when (invocation.method.name) { + "getFlingAnimator" -> if (customAnimator) otherAnimator else defaultAnimator + "getFlingExtrapolatedDistance" -> predicted - current + "getReactScrollViewScrollState" -> state + "getScrollX" -> if (horizontal) current else 0 + "getScrollY" -> if (horizontal) 0 else current + "getWidth", + "getHeight" -> 200 + "computeHorizontalScrollRange" -> maximum + 200 + "getPaddingStart", + "getPaddingEnd", + "getPaddingTop", + "getPaddingBottom" -> 0 + "getChildCount" -> 1 + "getChildAt" -> child + "getLayoutDirection" -> + if (rtl) View.LAYOUT_DIRECTION_RTL else View.LAYOUT_DIRECTION_LTR + "postInvalidateOnAnimation", "invalidate" -> null + "reactSmoothScrollTo" -> { + observation = + ScrollSnapObservation( + invocation.arguments[if (horizontal) 0 else 1] as Int, + null, + null, + ) + null + } + else -> invocation.callRealMethod() + } + }, + ) + + init { + for ((name, value) in + listOf( + "defaultFlingAnimator" to defaultAnimator, + "scroller" to scroller, + "contentView" to child, + )) { + type.declaredFields.find { it.name == name }?.apply { isAccessible = true }?.set(view, value) + } + set("setSnapToStart", true) + set("setSnapToEnd", true) + } + + fun set(name: String, value: Any) { + type.methods.single { it.name == name && it.parameterCount == 1 }.invoke(view, value) + } + + fun setOffsets(offsets: List?) { + type.getMethod("setSnapOffsets", List::class.java).invoke(view, offsets) + } + + fun recycle() { + type.declaredMethods + .single { it.name.startsWith("recycleView") } + .apply { isAccessible = true } + .invoke(view) + // Reattach the fixture's measured content after the real recycle reset. + type.getMethod("onChildViewAdded", View::class.java, View::class.java).invoke(view, view, child) + } + + fun fling(velocity: Int): ScrollSnapObservation { + observation = null + type + .getDeclaredMethod("flingAndSnap", Int::class.javaPrimitiveType) + .apply { isAccessible = true } + .invoke(view, velocity) + return checkNotNull(observation) + } +} diff --git a/packages/react-native/ReactShared/.gitignore b/packages/react-native/ReactShared/.gitignore new file mode 100644 index 000000000000..5d8581f71fc8 --- /dev/null +++ b/packages/react-native/ReactShared/.gitignore @@ -0,0 +1,3 @@ +/build/ +/.gradle/ +/.kotlin/ diff --git a/packages/react-native/ReactShared/README.md b/packages/react-native/ReactShared/README.md new file mode 100644 index 000000000000..12051499206b --- /dev/null +++ b/packages/react-native/ReactShared/README.md @@ -0,0 +1,229 @@ +# React Native shared Kotlin experiments + +These use cases build on the standalone KMP foundation. The +foundation's unpublished compiler/interop fixture remains available with +`-PreactNativeSharedSmoke=true`; its classes and reports stay under +`build/smoke` and are excluded from normal shared outputs. Run +`./scripts/test-apple-smoke.sh` to check that fixture through Objective-C. +Each use case has a separate behavior and performance review. + +This module shares CSS gradient stop position and transition-hint calculations +between Android and iOS using Kotlin Multiplatform. It has no Compose dependency. +Native views, gradient geometry, color interpolation, and drawing remain in their +existing platform implementations. + +`commonMain` accepts positions and color-presence flags and returns positions, +source color indices, and interpolation weights. Platform adapters retain their +existing tolerance, logarithm precision, and color-space behavior. The module does +not depend on ReactAndroid, React-Core, UIKit, JNI, or the C++ renderer. + +## Multipart framing + +`MultipartFraming` shares delimiter overlap, preamble and completed-part state +between Android's sliding Okio buffer and Apple's retained NSData buffer. +`MultipartHeaders` splits raw header fields; each platform keeps its existing +whitespace and key-comparison rules. Native code retains buffer searches, stream +and body ownership, callbacks and progress timing. Body bytes never cross the +Kotlin/Objective-C boundary. + +Run `./scripts/test-apple-multipart.sh` and +`python3 scripts/test-android-multipart.py` for the actual adapters' tests from a +repository checkout; their Android and RNTester test sources are not distributed +in the npm package. The Android runner requires Python 3.11 or later and uses the +repository's Okio, AssertJ, JUnit and Kotlin standard-library versions. Its newer +standalone compiler retains ReactAndroid's Kotlin language and API level. +The Apple runner also compares exact callbacks/body bytes against the native +fallback and checks Catalyst. Set `RCT_KMP_BENCHMARK=1` for its optional 2–20 MiB +parser benchmark. The Android runner supports `--baseline-ref` with an explicit +native parser revision and `--benchmark`; see `--help`. Its timings and allocation +counters describe a host JVM, not Android ART or network download throughput. +Both probes exclude constructing their known input payloads. + +This use case can amortize interop over buffer reads. A C++ implementation could +also share decisions and directly search native buffers, but would add an Android +JNI interface to this currently Kotlin/Objective-C utility. Neither approach +removes platform I/O or Catalyst fallback. Measure application memory and real +bundle-download behavior before broadening adoption. + +## Explicit scroll offsets + +`ScrollSnapOffsets` selects a target from explicit offsets for three Android views +and Apple's enhanced scroll view. Target prediction, axis/RTL handling, density, +velocity adjustment, interval snapping and native physics remain in the views. +Android retains its caller-owned integer list and pixel arithmetic. Apple caches +a primitive offset array when the property changes, then calls the selector once +per fling. It does not call Kotlin on every animation frame. + +`python3 scripts/test-apple-scroll-snap.py --benchmark-repeats 0` compiles the +actual Apple view with native and KMP paths, checks their target outputs, and +checks Catalyst fallback. The runner also compiles a test-only cached native +control to separate storage/caching benefits from Kotlin's contribution. +Omit that option to collect timing samples; the framework includes all use cases +present in the checkout. The Android core test suite includes +`ReactScrollSnapOffsetsTest`, which exercises all three views' actual fling code. + +This is a Kotlin-first consumer with a small target/direction result on Apple. A shared +C++ selector or caching the native Apple offsets are both alternatives; faster +results against the original NSNumber loop alone would not establish a KMP +advantage. Evaluate first-use cost, offset updates and repeated calls separately. + +## Build and test + +The standalone build uses its own Gradle wrapper and Kotlin plugin so that it +does not change the Kotlin plugin used by the main Android build. It requires +JDK 17. Apple builds also require macOS and Xcode; the pilot CI selects Xcode +26.4.1 without changing the existing React Native CI toolchain. + +From this directory: + +```sh +./gradlew jvmTest +./gradlew iosSimulatorArm64Test +./gradlew linkDebugFrameworkIosArm64 linkReleaseFrameworkIosArm64 \ + linkDebugFrameworkIosSimulatorArm64 linkReleaseFrameworkIosSimulatorArm64 \ + linkDebugFrameworkIosX64 linkReleaseFrameworkIosX64 +./scripts/test-apple-gradient.sh +RCT_KMP_BUILD_TYPE=Release ./scripts/test-apple-gradient.sh +``` + +The same common tests run on JVM and the Apple Silicon iOS simulator. The build +also defines an `iosX64` target for Intel simulators. Device and simulator +frameworks are static and named `ReactNativeShared.framework`. The Apple parity +script requires an installed iOS simulator runtime and compares the actual +Objective-C++ adapter with the existing native gradient implementation. + +With CocoaPods installed, `bundle exec ruby scripts/test-cocoapods-linking.rb` +checks generated host and test configurations for static, dynamic, and mixed +per-target linkage. Local fixture pods cover inherited and full-pod sibling hosted +tests, with and without `TestTargetID`, including renamed and SDK-specific app products. Negative +controls cover standalone tests and non-KMP hosts with unrelated KMP app dependencies. +No native code is compiled; the check verifies framework search paths and expected +Kotlin archive links, then prints the generated configuration directory. +Host paths with unresolved architecture or SDK-version conditions are not treated +as proof that the app provides the Kotlin runtime; those configurations need explicit +validation before relying on hosted-test suppression. + +## Android integration + +The repository and npm source-build settings include this directory as a +separate Gradle build. ReactAndroid consumes its JVM output through +`exportAndroidJar`, which writes `build/android/react-native-shared.jar`. +ReactAndroid embeds that JAR in its existing AAR; consumers continue to use the +existing `com.facebook.react:react-android` dependency. + +The JVM target uses Java 17 bytecode and Kotlin 2.2 language/API compatibility. +Android-specific build variants, resources, CMake, JNI, and publication remain +owned by ReactAndroid. + +`python3 scripts/test-android-consumers.py` publishes to a temporary local Maven +repository, packs the npm sources, and builds a fresh Android application for +each dependency route. It checks dependency resolution, shared-class uniqueness, +Debug packaging and Release shrinking. See `--help` for emulator execution and +fixture preparation options. These small consumers exercise the real Android +gradient and multipart adapters; they do not replace RNTester coverage. + +## Apple opt-in + +The Apple adapter is a source-build pilot. Set the flag when installing Pods in +the application directory that contains its Podfile: + +```sh +RCT_USE_KMP=1 bundle exec pod install +``` + +This enables the `React-KMP` support pod and selects React Native core source +builds. During the Xcode build, the support pod builds the shared static framework +for the current SDK, architecture, and configuration. The application still uses +its existing Objective-C++ and UIKit rendering code. + +All Apple consumers use one shared Kotlin runtime. With dynamic CocoaPods +frameworks, `React-Core` owns the static Kotlin archive and exports its Objective-C +classes to dependent pods such as Fabric. The archive is explicitly loaded so the +owner does not depend on which shared algorithm it happens to call. With static +libraries or static frameworks, the application owns the archive instead. Hosted +tests inherit their host's runtime. Adding an algorithm must not add another +framework link to its consuming pod. + +For a custom Xcode configuration name that does not contain `Debug` or `Release`, +set the `RCT_KMP_BUILD_TYPE` build setting to `Debug` or `Release`. + +Mac Catalyst retains the existing gradient implementation because Kotlin/Native +does not provide a Catalyst target. SwiftPM does not support this pilot: setting +`RCT_USE_KMP=1` for that integration fails with a message directing developers to +the CocoaPods source-build route. Published React Native Apple prebuilts do not +contain the pilot framework. + +`./scripts/test-apple-distribution.sh` tests a separate binary-distribution +fixture: a device ARM64 plus universal simulator XCFramework, the matching Kotlin +license bundle, and a SwiftPM consumer. It builds iOS and Catalyst and executes +the consumer's test on the host simulator. `--build-only` omits execution; +`--package-only` packages previously built frameworks and records that reuse in +`distribution.json`. This probe does not enable React Native core's SwiftPM or +prebuilt integration. Those routes still need complete React core build and app +validation before their guard can be removed. + +To return to the default Apple implementation, remove the flag and run Pod +installation again. No change to the JavaScript gradient API is needed. + +## Application, runtime and cost checks + +From a repository checkout with RNTester dependencies installed: + +```sh +./scripts/test-apple-app.sh simulator +USE_FRAMEWORKS=static ./scripts/test-apple-app.sh simulator +USE_FRAMEWORKS=dynamic ./scripts/test-apple-app.sh simulator +./scripts/test-apple-app.sh device +./scripts/test-apple-app.sh catalyst +python3 scripts/test-kotlin-coexistence.py +python3 scripts/benchmark-apple-gradient.py +python3 scripts/benchmark-kmp-build.py +``` + +The app script copies RNTester into an isolated sibling directory, enables KMP, +and verifies the actual compiled gradient, multipart and scroll adapters. Simulator runs +execute the RNTester test plan and launch the app; device and Catalyst runs are unsigned +build checks. Catalyst is enabled in the copied Podfile and application project. +Each run requires fresh build outputs. It preserves RNTester's existing hosted-test topology and removes +the temporary app and any test-owned servers and simulator when it finishes. + +The coexistence fixture checks independently compiled Kotlin frameworks using +the same compiler as ReactShared, including all four combinations of static and dynamic runtime ownership, +object lifetimes, and concurrent calls. Values cross that boundary as native +primitives. It does not establish compatibility with arbitrary Kotlin compiler +versions or allow one framework's exported Kotlin objects to be cast to another's. + +The Apple benchmark compares the actual native and KMP adapters in separate +optimized executables. It records first-call and repeated-call timings, process +memory snapshots and binary size. Memory snapshots are not allocation counts, +and simulator measurements are not application startup or physical-device +performance. The build benchmark measures clean outputs, unchanged builds and a +common-source edit in a copied module with warm dependency/compiler caches and +Gradle's build-output cache disabled. Reports have no timing pass/fail thresholds. +Measure full application size, startup, allocations and build costs on representative +devices before expanding adoption. + +This is an experimental code-sharing pilot. Local optimized simulator probes +show additional latency, executable size and process memory cost from the shared +adapter and Kotlin runtime. Passing correctness and integration tests does not +establish an acceptable performance budget for broader adoption. + +## Scope and validation + +Common tests cover stop positioning and transition hints. They do not replace +platform rendering tests: color precision, gradient geometry, and framework +linking still need validation in the Android and Apple adapters. Adoption beyond +this pilot should also measure application size and startup cost and preserve +the existing Catalyst path. + +The dedicated `test-kmp.yml` workflow runs common tests, builds Debug and Release +frameworks for all three Apple targets, and checks Apple adapter parity in both +configurations with static and dynamic linkage. It also checks CocoaPods linking +for application and test targets with static, dynamic, and mixed framework settings. +Additional jobs cover KMP-enabled RNTester builds/tests and Android package consumers; +the shared job runs the distribution, coexistence and cost probes. Intel iOS +simulator frameworks are built, but executing Intel or physical-device tests +requires suitable hardware and runtimes outside these hosted jobs. +Shared Kotlin changes also trigger the existing Android and iOS test paths. This source directory and its +wrapper are included in the npm package; generated build outputs and local Gradle +caches are not. diff --git a/packages/react-native/ReactShared/React-KMP.podspec b/packages/react-native/ReactShared/React-KMP.podspec new file mode 100644 index 000000000000..9a36d38ba47f --- /dev/null +++ b/packages/react-native/ReactShared/React-KMP.podspec @@ -0,0 +1,36 @@ +# 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'))) + +Pod::Spec.new do |s| + s.name = 'React-KMP' + s.version = package['version'] + s.summary = 'Opt-in shared Kotlin algorithms for React Native.' + s.homepage = 'https://reactnative.dev/' + s.license = package['license'] + s.author = 'Meta Platforms, Inc. and its affiliates' + s.source = { :git => 'https://github.com/facebook/react-native.git', :tag => "v#{package['version']}" } + s.platforms = min_supported_versions + # The small support target establishes build ordering without trying to link an + # iOS-only vendored XCFramework when the application is built for Catalyst. + s.source_files = 'cocoapods/ReactNativeShared.m' + s.preserve_paths = 'src/**/*', 'gradle/**/*', 'gradlew', '*.kts', '*.properties', 'scripts/**/*' + s.pod_target_xcconfig = { 'ENABLE_USER_SCRIPT_SANDBOXING' => 'NO' } + s.user_target_xcconfig = { + 'FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]' => '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeSharedKMP"', + 'FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]' => '$(inherited) "$(PODS_CONFIGURATION_BUILD_DIR)/ReactNativeSharedKMP"', + } + # Link flags are added to direct consumers in react_native_post_install. + # user_target_xcconfig also reaches tests that inherit only search paths. + s.script_phase = { + :name => 'Build shared Kotlin framework', + :execution_position => :before_compile, + :always_out_of_date => '1', + :script => '"${PODS_TARGET_SRCROOT}/scripts/build-apple-framework.sh"', + } +end diff --git a/packages/react-native/ReactShared/build.gradle.kts b/packages/react-native/ReactShared/build.gradle.kts new file mode 100644 index 000000000000..a383ea7ec72a --- /dev/null +++ b/packages/react-native/ReactShared/build.gradle.kts @@ -0,0 +1,73 @@ +/* + * 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 java.util.Properties +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget + +plugins { kotlin("multiplatform") version "2.4.20" } + +group = "com.facebook.react" + +val reactAndroidProperties = Properties() + +file("../ReactAndroid/gradle.properties").inputStream().use(reactAndroidProperties::load) + +version = reactAndroidProperties.getProperty("VERSION_NAME") + +val smokeEnabled = + providers.gradleProperty("reactNativeSharedSmoke").map { it.toBooleanStrict() }.getOrElse(false) + +if (smokeEnabled) { + // Keep test-only exports separate from any future production artifacts. + layout.buildDirectory.set(layout.projectDirectory.dir("build/smoke")) +} + +kotlin { + explicitApi() + jvmToolchain(17) + compilerOptions { + // ReactAndroid consumers still compile with the older Kotlin language level. + languageVersion.set(KotlinVersion.KOTLIN_2_2) + apiVersion.set(KotlinVersion.KOTLIN_2_2) + } + jvm { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } } + iosArm64() + iosSimulatorArm64() + iosX64() + + targets.withType().configureEach { + binaries.framework { + baseName = "ReactNativeShared" + isStatic = true + binaryOption("bundleId", "com.facebook.react.shared") + } + } + + sourceSets { + commonMain.dependencies { + // Keep the JVM runtime dependency compatible with the existing Android library. + implementation(kotlin("stdlib", "2.2.0")) + } + commonTest.dependencies { implementation(kotlin("test")) } + if (smokeEnabled) { + commonMain { kotlin.srcDir("tests/smoke/kotlin") } + commonTest { kotlin.srcDir("tests/smoke/kotlinTest") } + } + } +} + +// ReactAndroid embeds this JAR in its AAR, preserving the existing Maven coordinates. +// A stable output path also works when this build is included by a source-build consumer. +val jvmJar = tasks.named("jvmJar") + +tasks.register("exportAndroidJar") { + from(jvmJar.flatMap { it.archiveFile }) + into(layout.buildDirectory.dir("android")) + rename { "react-native-shared.jar" } +} diff --git a/packages/react-native/ReactShared/cocoapods/ReactNativeShared.m b/packages/react-native/ReactShared/cocoapods/ReactNativeShared.m new file mode 100644 index 000000000000..5dc776e831f0 --- /dev/null +++ b/packages/react-native/ReactShared/cocoapods/ReactNativeShared.m @@ -0,0 +1,9 @@ +/* + * 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. + */ + +// The support pod orders the Kotlin framework build before React-RCTFabric. +// All shared implementations are supplied by ReactNativeShared.framework. diff --git a/packages/react-native/ReactShared/gradle.properties b/packages/react-native/ReactShared/gradle.properties new file mode 100644 index 000000000000..e8b989142732 --- /dev/null +++ b/packages/react-native/ReactShared/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=768m -Dfile.encoding=UTF-8 +org.gradle.caching=true +kotlin.stdlib.default.dependency=false diff --git a/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.jar b/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..d997cfc60f4c Binary files /dev/null and b/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.jar differ diff --git a/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties b/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..80d82296e83e --- /dev/null +++ b/packages/react-native/ReactShared/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +distributionSha256Sum=2ab2958f2a1e51120c326cad6f385153bb11ee93b3c216c5fccebfdfbb7ec6cb +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/packages/react-native/ReactShared/gradlew b/packages/react-native/ReactShared/gradlew new file mode 100755 index 000000000000..739907dfd159 --- /dev/null +++ b/packages/react-native/ReactShared/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/packages/react-native/ReactShared/gradlew.bat b/packages/react-native/ReactShared/gradlew.bat new file mode 100644 index 000000000000..c4bdd3ab8e3c --- /dev/null +++ b/packages/react-native/ReactShared/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/packages/react-native/ReactShared/scripts/benchmark-apple-gradient.py b/packages/react-native/ReactShared/scripts/benchmark-apple-gradient.py new file mode 100644 index 000000000000..8566c4557c47 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/benchmark-apple-gradient.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# 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. + +"""Measure the real native and KMP adapters in separate Release executables. + +Requires the same toolchain and simulator runtime as test-apple-gradient.sh. +Results are simulator microbenchmarks, not device or application benchmarks. +""" + +import argparse +import hashlib +import json +import os +import pathlib +import platform +import statistics +import subprocess +import time + + +def run(command, **kwargs): + started = time.perf_counter() + result = subprocess.run(command, capture_output=True, text=True, **kwargs) + if result.returncode: + raise RuntimeError( + f"Command failed ({result.returncode}): {command}\n" + + (result.stdout + result.stderr)[-12000:] + ) + return result, time.perf_counter() - started + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-only", action="store_true", help="Compile without accessing the simulator.") + parser.add_argument("--iterations", type=int, default=2000) + parser.add_argument("--samples", type=int, default=7) + parser.add_argument("--repeats", type=int, default=3, help="Fresh processes per case and variant.") + parser.add_argument("--output", type=pathlib.Path) + parser.add_argument("--prepared-release-dir", type=pathlib.Path, + help="Reuse artifacts previously built by test-apple-gradient.sh with RCT_KMP_BUILD_TYPE=Release.") + args = parser.parse_args() + if not 1 <= args.iterations <= 1000000 or not 1 <= args.samples <= 100 or not 1 <= args.repeats <= 100: + parser.error("iterations must be 1..1000000; samples and repeats must be 1..100") + shared = pathlib.Path(__file__).resolve().parent.parent + react = shared.parent + output = (args.output or shared / "build/apple-gradient-benchmark").resolve() + output.mkdir(parents=True, exist_ok=True) + prepared = args.prepared_release_dir.resolve() if args.prepared_release_dir else output / "prepared" + preparation_seconds = None + if not args.prepared_release_dir: + env = dict(os.environ, RCT_KMP_BUILD_TYPE="Release", RCT_KMP_BUILD_ONLY="1", RCT_KMP_TEST_OUTPUT_DIR=str(prepared)) + preparation, preparation_seconds = run([str(shared / "scripts/test-apple-gradient.sh")], env=env) + (output / "prepare.log").write_text(preparation.stdout + preparation.stderr) + sdk = run(["xcrun", "--sdk", "iphonesimulator", "--show-sdk-path"])[0].stdout.strip() + architecture = platform.machine() + graphics = react / "ReactCommon/react/renderer/graphics" + flags = [ + "-std=c++20", "-O2", "-fobjc-arc", "-DREACT_NATIVE_PRODUCTION", "-DRCTLOG_ENABLED=0", + "-include", "memory", "-include", "vector", "-target", f"{architecture}-apple-ios15.1-simulator", + "-isysroot", sdk, "-I", str(prepared / "include"), "-I", str(react / "ReactCommon"), + "-I", str(graphics / "platform/ios"), "-F", str(prepared / "ReactNativeSharedKMP"), + ] + native_objects = [str(prepared / name) for name in [ + "RCTAnimationUtils.mm.o", "Color.cpp.o", "ColorComponents.cpp.o", "HostPlatformColor.mm.o", + "RCTPlatformColorUtils.mm.o", "ManagedObjectWrapper.mm.o", + ]] + frameworks = ["-framework", "Foundation", "-framework", "UIKit", "-framework", "QuartzCore", "-framework", "CoreGraphics"] + builds = {} + executables = {} + for variant in ("native", "kmp"): + adapter = output / f"{variant}-adapter.o" + defines = ["-DRCT_USE_KMP=1"] if variant == "kmp" else ["-DRCT_USE_KMP=0", "-DRCTGradientUtils=RCTGradientUtilsBaseline"] + _, compile_seconds = run(["xcrun", "clang++", *flags, *defines, "-c", str(react / "React/Fabric/Utils/RCTGradientUtils.mm"), "-o", str(adapter)]) + executable = output / f"AppleGradientBenchmark-{variant}" + link = ["xcrun", "clang++", *flags, f"-DRCT_BENCHMARK_KMP={int(variant == 'kmp')}", + str(shared / "tests/AppleGradientBenchmark.mm"), str(adapter), *native_objects, + *frameworks, "-Wl,-dead_strip", "-o", str(executable)] + if variant == "kmp": + link.extend(["-framework", "ReactNativeShared"]) + _, link_seconds = run(link) + executables[variant] = executable + builds[variant] = {"adapterCompileSeconds": compile_seconds, "harnessCompileAndLinkSeconds": link_seconds, + "executableBytes": executable.stat().st_size} + size = run(["xcrun", "size", "-m", str(executable)])[0].stdout + (output / f"{variant}-segments.txt").write_text(size) + framework = prepared / "ReactNativeSharedKMP/ReactNativeShared.framework/ReactNativeShared" + report = { + "configuration": "Release; clang -O2; dead stripping; separate native-only and KMP executables", + "platform": "iOS simulator", "hostArchitecture": architecture, "sdk": sdk, + "xcode": run(["xcodebuild", "-version"])[0].stdout.strip(), + "preparationSeconds": preparation_seconds, "builds": builds, + "reusedReleaseArtifacts": bool(args.prepared_release_dir), + "artifactSha256": {str(path): hashlib.sha256(path.read_bytes()).hexdigest() + for path in [framework, *(pathlib.Path(item) for item in native_objects)]}, + "staticFrameworkBytes": framework.stat().st_size, + "incrementalExecutableBytes": builds["kmp"]["executableBytes"] - builds["native"]["executableBytes"], + "runtimeExecuted": False, "measurements": [], "firstCallProcesses": [], + "limitations": [ + "Simulator results are not physical-device performance or RN application startup.", + "First-call latency starts after inputs exist; process elapsed time includes simctl/OS launch overhead.", + "Memory values are process footprint snapshots, not total allocated bytes; Kotlin GC is not forced.", + "Binary size is this isolated executable, not an installed, signed, or compressed application delta.", + "Compilation timings are one warm-cache observation; preparation includes framework and parity harness builds.", + ], + } + if not args.build_only: + simulator = os.environ.get("RCT_KMP_SIMULATOR_UDID") + if not simulator: + devices = json.loads(run(["xcrun", "simctl", "list", "devices", "available", "-j"])[0].stdout)["devices"] + simulator = next((items[0]["udid"] for runtime, items in devices.items() if ".iOS-" in runtime and items), None) + if not simulator: + raise RuntimeError("Install a compatible iOS simulator runtime or set RCT_KMP_SIMULATOR_UDID.") + for repetition in range(args.repeats): + for variant in (("native", "kmp") if repetition % 2 == 0 else ("kmp", "native")): + result, elapsed = run(["xcrun", "simctl", "spawn", "--standalone", simulator, + str(executables[variant]), "two_stops", "1", "1", "--first-call-only"]) + measurement = json.loads(result.stdout) + measurement.update(repetition=repetition, processElapsedSeconds=elapsed) + report["firstCallProcesses"].append(measurement) + (output / f"first-call-{variant}-{repetition}.stderr.log").write_text(result.stderr) + cases = ("two_stops", "implicit_16", "explicit_64", "asymmetric_hint", "multiple_hints") + for repetition in range(args.repeats): + for case in cases: + # Alternate order across independent processes to reduce ordering bias. + for variant in (("native", "kmp") if repetition % 2 == 0 else ("kmp", "native")): + result, elapsed = run(["xcrun", "simctl", "spawn", "--standalone", simulator, + str(executables[variant]), case, str(args.iterations), str(args.samples)]) + measurement = json.loads(result.stdout) + measurement.update(repetition=repetition, processElapsedSeconds=elapsed) + measurement["medianNanosecondsPerCall"] = statistics.median(measurement["nanosecondsPerCall"]) + report["measurements"].append(measurement) + (output / f"{case}-{variant}-{repetition}.stderr.log").write_text(result.stderr) + pair = report["measurements"][-2:] + if pair[0]["checksum"] != pair[1]["checksum"]: + raise RuntimeError(f"Observed output checksum differs for {case}; inspect parity before comparing timings.") + report["runtimeExecuted"] = True + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"{'Compiled' if args.build_only else 'Measured'} native and KMP gradient executables: {output / 'results.json'}") + + +if __name__ == "__main__": + main() diff --git a/packages/react-native/ReactShared/scripts/benchmark-kmp-build.py b/packages/react-native/ReactShared/scripts/benchmark-kmp-build.py new file mode 100644 index 000000000000..f748e0bfded3 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/benchmark-kmp-build.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# 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. + +"""Measure clean, unchanged, and edited shared-module builds in an isolated copy. + +Dependency/compiler caches stay warm. Gradle's build-output cache is disabled so +the clean build measures compilation instead of restoring another build's outputs. +This measures the added shared module, not the entire Android or iOS application. +""" + +import argparse +import json +import pathlib +import platform +import shutil +import subprocess +import time + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--plan-only", action="store_true", help="Print the measurement plan without building.") + parser.add_argument("--output", type=pathlib.Path) + args = parser.parse_args() + shared = pathlib.Path(__file__).resolve().parent.parent + output = (args.output or shared / "build/kmp-build-benchmark").resolve() + output.mkdir(parents=True, exist_ok=True) + target = "IosSimulatorArm64" if platform.machine() == "arm64" else "IosX64" + tasks = ["jvmTest", f"linkReleaseFramework{target}"] + phases = [ + {"name": "clean_outputs", "tasks": ["clean", *tasks]}, + {"name": "unchanged_incremental", "tasks": tasks}, + {"name": "edited_common_source", "tasks": tasks}, + ] + report = { + "dependencyAndCompilerCaches": "warm; existing user caches", + "gradleBuildOutputCache": "disabled", "measurementsExecuted": False, + "scope": "isolated shared module; not total application build time", + "sourceEdit": "append a comment to the copied common source; original source remains unchanged", + "phases": phases, + } + if not args.plan_only: + if platform.system() != "Darwin": + parser.error("The paired JVM/iOS measurement requires macOS and Xcode.") + fixture = output / "fixture" + if fixture.exists(): + parser.error(f"Choose a fresh --output directory; fixture already exists: {fixture}") + copied_shared = fixture / "ReactShared" + copied_shared.mkdir(parents=True) + for name in ("build.gradle.kts", "settings.gradle.kts", "gradle.properties", "gradlew", "gradlew.bat", "gradle", "src"): + source = shared / name + if source.is_dir(): + shutil.copytree(source, copied_shared / name) + else: + shutil.copy2(source, copied_shared / name) + (fixture / "ReactAndroid").mkdir() + shutil.copy2(shared.parent / "ReactAndroid/gradle.properties", fixture / "ReactAndroid/gradle.properties") + for phase in phases: + if phase["name"] == "edited_common_source": + source = copied_shared / "src/commonMain/kotlin/com/facebook/react/shared/GradientStops.kt" + with source.open("a") as stream: + stream.write("\n// Non-semantic edit in the isolated build-cost fixture.\n") + command = [str(copied_shared / "gradlew"), *phase["tasks"], "--no-build-cache", "--max-workers=2", "--console=plain"] + started = time.perf_counter() + completed = subprocess.run(command, cwd=copied_shared, capture_output=True, text=True) + phase.update(elapsedSeconds=time.perf_counter() - started, exitCode=completed.returncode) + (output / f"{phase['name']}.log").write_text(completed.stdout + completed.stderr) + if completed.returncode != 0: + report["failurePhase"] = phase["name"] + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + raise SystemExit(f"Build measurement failed in {phase['name']}; inspect {output}.") + report["measurementsExecuted"] = True + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"{'Planned' if args.plan_only else 'Measured'} shared-module build costs: {output / 'results.json'}") + + +if __name__ == "__main__": + main() diff --git a/packages/react-native/ReactShared/scripts/build-apple-framework.sh b/packages/react-native/ReactShared/scripts/build-apple-framework.sh new file mode 100755 index 000000000000..16a5becb27c0 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/build-apple-framework.sh @@ -0,0 +1,52 @@ +#!/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 -euo pipefail + +if [[ "${EFFECTIVE_PLATFORM_NAME:-}" == "-maccatalyst" || "${IS_MACCATALYST:-NO}" == "YES" ]]; then + echo 'React Native KMP: Catalyst uses the existing native gradient implementation.' + exit 0 +fi + +if [[ "${ACTION:-}" == "clean" ]]; then + exit 0 +fi + +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +build_type="${RCT_KMP_BUILD_TYPE:-${CONFIGURATION:-Debug}}" +case "$build_type" in + Debug|*Debug*) build_type=Debug; framework_variant=debugFramework ;; + Release|*Release*) build_type=Release; framework_variant=releaseFramework ;; + *) echo 'error: Set RCT_KMP_BUILD_TYPE=Debug or Release for a custom Xcode configuration.' >&2; exit 1 ;; +esac + +read -r -a architectures <<< "${ARCHS:-arm64}" +gradle_tasks=() +frameworks=() +for architecture in "${architectures[@]}"; do + case "${PLATFORM_NAME:-}:$architecture" in + iphoneos:arm64) kotlin_target=iosArm64; task_target=IosArm64 ;; + iphonesimulator:arm64) kotlin_target=iosSimulatorArm64; task_target=IosSimulatorArm64 ;; + iphonesimulator:x86_64) kotlin_target=iosX64; task_target=IosX64 ;; + *) echo "error: React Native KMP has no framework for ${PLATFORM_NAME:-unknown}:$architecture." >&2; exit 1 ;; + esac + gradle_tasks+=("link${build_type}Framework${task_target}") + frameworks+=("$shared_root/build/bin/$kotlin_target/$framework_variant/ReactNativeShared.framework") +done + +"$shared_root/gradlew" -p "$shared_root" --console=plain "${gradle_tasks[@]}" + +destination="${PODS_CONFIGURATION_BUILD_DIR:?Run this script from the React-KMP CocoaPods build phase}/ReactNativeSharedKMP" +mkdir -p "$destination" +rm -rf "$destination/ReactNativeShared.framework" +ditto "${frameworks[0]}" "$destination/ReactNativeShared.framework" +if [[ ${#frameworks[@]} -gt 1 ]]; then + binaries=() + for framework in "${frameworks[@]}"; do + binaries+=("$framework/ReactNativeShared") + done + xcrun lipo -create "${binaries[@]}" -output "$destination/ReactNativeShared.framework/ReactNativeShared" +fi diff --git a/packages/react-native/ReactShared/scripts/test-android-consumers.py b/packages/react-native/ReactShared/scripts/test-android-consumers.py new file mode 100644 index 000000000000..431df5a5da09 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-android-consumers.py @@ -0,0 +1,474 @@ +#!/usr/bin/env python3 +# 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. + +"""Build fresh Android consumers of the Maven AAR and packed npm source. + +Requires Python 3.12+, Node/Yarn/npm, JDK 17 and the Android SDK/NDK. Run after +the repository's Yarn install. A supplied device runs both release APKs; without +one the report explicitly records compilation/packaging validation only. +The packed-source build also builds Hermes from source, as the standard React +Native composite does; the repository-only stable-Hermes flag does not apply. +""" + +import argparse +from collections import Counter +import hashlib +import io +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tarfile +import tempfile +import textwrap +import time +import tomllib +import uuid +import zipfile + + +SHARED = Path(__file__).resolve().parents[1] +RN = SHARED.parent +REPOSITORY = RN.parent.parent + + +def write(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(content).lstrip(), encoding="utf-8") + + +def groovy_string(value): + return "'" + str(value).replace("\\", "\\\\").replace("'", "\\'") + "'" + + +def run(command, cwd, log, env=None): + print("Running: " + " ".join(map(str, command)), flush=True) + with log.open("w", encoding="utf-8") as output: + subprocess.run(command, cwd=cwd, env=env, stdout=output, + stderr=subprocess.STDOUT, check=True) + + +def properties(path): + return dict(line.strip().split("=", 1) for line in path.read_text().splitlines() + if "=" in line and not line.lstrip().startswith("#")) + + +def pack(package, destination, environment): + result = subprocess.run( + ["npm", "pack", "--ignore-scripts", "--json", "--pack-destination", str(destination)], + cwd=package, env=environment, check=True, capture_output=True, text=True, + ) + metadata = json.loads(result.stdout) + if isinstance(metadata, dict): + metadata = [metadata] if "filename" in metadata else list(metadata.values()) + if len(metadata) != 1: + raise AssertionError(f"Expected one npm package: {metadata}") + return destination / metadata[0]["filename"] + + +def unpack(archive, destination): + destination.mkdir(parents=True, exist_ok=True) + with tarfile.open(archive) as tar: + members = tar.getmembers() + if any(not member.name.startswith("package/") for member in members): + raise AssertionError(f"Unexpected npm archive layout: {archive}") + for member in members: + member.name = member.name.removeprefix("package/") + tar.extractall(destination, members=members, filter="data") + + +def inspect_aar(aar): + classes = Counter() + with zipfile.ZipFile(aar) as archive: + for entry in archive.namelist(): + if entry == "classes.jar" or (entry.startswith("libs/") and entry.endswith(".jar")): + with zipfile.ZipFile(io.BytesIO(archive.read(entry))) as jar: + classes.update(name for name in jar.namelist() + if name.startswith("com/facebook/react/shared/") + and name.endswith(".class")) + required = {f"com/facebook/react/shared/{name}.class" + for name in ["GradientStops", "GradientStopInput", "ResolvedGradientStop", + "MultipartFraming", "MultipartChunk", "MultipartHeaders", "MultipartHeader", + "ScrollSnapOffsets", "ScrollSnapDirection", "ScrollSnapResult"]} + if not required.issubset(classes) or any(count != 1 for count in classes.values()): + raise AssertionError(f"Missing or duplicated shared classes in {aar}: {classes}") + with tempfile.TemporaryDirectory(prefix="react-native-kmp-bytecode-") as directory: + jar = Path(directory) / "classes.jar" + with zipfile.ZipFile(aar) as archive: + jar.write_bytes(archive.read("classes.jar")) + adapters = { + "com.facebook.react.uimanager.style.ColorStopUtils": ("GradientStops.resolve",), + "com.facebook.react.devsupport.MultipartStreamReader": ( + "MultipartFraming.nextChunk", "MultipartHeaders.parse"), + } + for view in ("ReactScrollView", "ReactHorizontalScrollView", "ReactNestedScrollView"): + adapters[f"com.facebook.react.views.scroll.{view}"] = ("ScrollSnapOffsets.resolve",) + for adapter, methods in adapters.items(): + bytecode = subprocess.check_output( + ["javap", "-c", "-p", "-classpath", str(jar), adapter], text=True) + for method in methods: + pattern = r"invoke(?:static|virtual)\s+.*// Method com/facebook/react/shared/" + re.escape(method) + r"(?:\$default)?:" + if not re.search(pattern, bytecode): + raise AssertionError(f"{adapter} does not invoke shared {method} in {aar}") + return {"path": str(aar), "sha256": hashlib.sha256(aar.read_bytes()).hexdigest(), + "shared_class_counts": dict(classes), "adapter_invokes_shared_resolver": True} + + +ACTIVITY = r""" +package com.facebook.react.kmp.consumer; + +import android.app.Activity; +import android.graphics.Color; +import android.os.Bundle; +import android.util.DisplayMetrics; +import android.util.Log; +import android.widget.TextView; +import com.facebook.react.devsupport.MultipartStreamReader; +import com.facebook.react.uimanager.DisplayMetricsHolder; +import com.facebook.react.uimanager.LengthPercentage; +import com.facebook.react.uimanager.LengthPercentageType; +import com.facebook.react.uimanager.style.ColorStop; +import com.facebook.react.uimanager.style.ColorStopUtils; +import com.facebook.react.uimanager.style.ProcessedColorStop; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.io.IOException; +import okio.Buffer; +import okio.BufferedSource; + +// Java deliberately exercises the packaged Android adapter through its JVM API. +// No shared source files or replacement implementation are compiled into this app. +public final class MainActivity extends Activity { + @Override public void onCreate(Bundle state) { + super.onCreate(state); + DisplayMetrics metrics = new DisplayMetrics(); + metrics.setTo(getResources().getDisplayMetrics()); + metrics.density = 2f; + DisplayMetricsHolder.setScreenDisplayMetrics(metrics); + List density = ColorStopUtils.INSTANCE.getFixedColorStops( + Arrays.asList(new ColorStop(Color.RED, + new LengthPercentage(25f, LengthPercentageType.POINT)), + new ColorStop(Color.BLUE, null)), 200f); + if (density.get(0).getPosition() != .25f) throw new AssertionError("Android density"); + List hint = ColorStopUtils.INSTANCE.getFixedColorStops( + Arrays.asList(new ColorStop(Color.argb(128, 255, 0, 0), null), + new ColorStop(null, new LengthPercentage(25f, LengthPercentageType.PERCENT)), + new ColorStop(Color.BLUE, null)), 100f); + if (hint.size() != 11 || hint.get(3).getPosition() != .25f + || hint.get(3).getColor() != Color.argb(191, 127, 0, 127)) { + throw new AssertionError("Shared hint expansion or Android alpha rounding"); + } + checkMultipart(); + String result = "KMP consumer PASS " + BuildConfig.CONSUMER_MODE + + " " + getIntent().getStringExtra("validationToken"); + TextView text = new TextView(this); + text.setText(result); + setContentView(text); + Log.i("KmpConsumer", result); + } + + private static void checkMultipart() { + // The first body ends in CRLF, so a header marker can straddle the boundary. + Buffer input = new Buffer().writeUtf8( + "\r\n--sample\r\nfirst\r\n\r\n--sample\r\n" + + "content-type: text/plain\r\n\r\nsecond\r\n--sample--\r\n"); + int[] parts = {0}; + try { + boolean complete = new MultipartStreamReader(input, "sample").readAllParts( + new MultipartStreamReader.ChunkListener() { + @Override public void onChunkComplete( + Map headers, BufferedSource body, boolean last) throws IOException { + int index = parts[0]++; + String expected = index == 0 ? "first\r\n" : "second"; + if (index > 1 || !expected.equals(body.readUtf8()) || last != (index == 1)) { + throw new AssertionError("Shared multipart body or completion"); + } + if (index == 0 ? !headers.isEmpty() + : !"text/plain".equals(headers.get("CONTENT-TYPE"))) { + throw new AssertionError("Android multipart header policy"); + } + } + @Override public void onChunkProgress( + Map headers, long loaded, long total) {} + }); + if (!complete || parts[0] != 2) throw new AssertionError("Shared multipart framing"); + } catch (IOException error) { + throw new AssertionError(error); + } + } +} +""" + + +def fixture(path, mode, versions, version, hermes_version, maven, abi): + source_builds = """ + includeBuild('node_modules/@react-native/gradle-plugin') + includeBuild('node_modules/react-native') { + name = 'react-native-build-from-source' + dependencySubstitution { + substitute module('com.facebook.react:react-android') using project(':packages:react-native:ReactAndroid') + substitute module('com.facebook.hermes:hermes-android') using project(':packages:react-native:ReactAndroid:hermes-engine') + } + } + """ if mode == "source" else "" + write(path / "settings.gradle", f""" + pluginManagement {{ repositories {{ google(); mavenCentral(); gradlePluginPortal() }} }} + dependencyResolutionManagement {{ + repositories {{ + exclusiveContent {{ + forRepository {{ maven {{ url = uri({groovy_string(maven)}) }} }} + filter {{ includeModule('com.facebook.react', 'react-android') }} + }} + google() + mavenCentral() + }} + }} + rootProject.name = 'kmp-{mode}-consumer' + include ':app' + {source_builds} + """) + write(path / "gradle.properties", """ + android.useAndroidX=true + org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g + org.gradle.caching=true + """) + if mode == "source": + write(path / "build.gradle", """ + tasks.register('prepareSourceAars') { + dependsOn gradle.includedBuild('react-native-build-from-source').task(':packages:react-native:ReactAndroid:bundleDebugAar') + dependsOn gradle.includedBuild('react-native-build-from-source').task(':packages:react-native:ReactAndroid:bundleReleaseAar') + } + """) + write(path / "app/build.gradle", f""" + import groovy.json.JsonOutput + import org.gradle.api.artifacts.component.ModuleComponentIdentifier + import org.gradle.api.artifacts.component.ProjectComponentIdentifier + + plugins {{ id 'com.android.application' version '{versions['agp']}' }} + android {{ + namespace 'com.facebook.react.kmp.consumer' + compileSdk {versions['compileSdk']} + ndkVersion '{versions['ndkVersion']}' + defaultConfig {{ + applicationId 'com.facebook.react.kmp.consumer.{mode}' + minSdk {versions['minSdk']} + targetSdk {versions['targetSdk']} + versionCode 1 + versionName '1.0' + ndk {{ abiFilters '{abi}' }} + buildConfigField 'String', 'CONSUMER_MODE', '"{mode}"' + }} + buildFeatures {{ buildConfig true }} + // Match React Native's Gradle plugin rules for shared Prefab libraries. + packaging {{ + jniLibs.pickFirsts += ['**/libfbjni.so', '**/libreactnative.so', '**/libjsi.so', + '**/libc++_shared.so', '**/libhermesvm.so', '**/libhermestooling.so'] + }} + compileOptions {{ + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + }} + buildTypes {{ + release {{ + minifyEnabled true + shrinkResources true + signingConfig signingConfigs.debug + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt') + }} + }} + }} + dependencies {{ + implementation 'com.facebook.react:react-android:{version}' + implementation 'com.facebook.hermes:hermes-android:{hermes_version}' + }} + tasks.register('verifyResolution') {{ + dependsOn 'assembleDebug', 'assembleRelease' + {"dependsOn ':prepareSourceAars'" if mode == "source" else ""} + doLast {{ + def result = ['debug', 'release'].collectEntries {{ variant -> + def configuration = configurations.getByName(variant + 'RuntimeClasspath') + def components = configuration.incoming.resolutionResult.allComponents.findAll {{ component -> + def id = component.id + (id instanceof ModuleComponentIdentifier && id.group == 'com.facebook.react' && id.module == 'react-android') || + (id instanceof ProjectComponentIdentifier && id.projectPath.endsWith(':ReactAndroid')) + }} + assert components.size() == 1 : components + def id = components.first().id + assert {str(mode == 'source').lower()} == (id instanceof ProjectComponentIdentifier) : id + if (id instanceof ModuleComponentIdentifier) assert id.version == '{version}' : id + def artifacts = configuration.incoming.artifactView {{ + componentFilter {{ component -> component == id }} + {"attributes.attribute(org.gradle.api.artifacts.type.ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, 'android-classes-jar')" if mode == "source" else ""} + }}.artifacts.artifacts + assert !artifacts.empty + def engines = configuration.incoming.resolutionResult.allComponents.findAll {{ component -> + def engine = component.id + (engine instanceof ModuleComponentIdentifier && engine.group == 'com.facebook.hermes' && engine.module == 'hermes-android') || + (engine instanceof ProjectComponentIdentifier && engine.projectPath.endsWith(':hermes-engine')) + }} + assert engines.size() == 1 : engines + def engine = engines.first().id + assert {str(mode == 'source').lower()} == (engine instanceof ProjectComponentIdentifier) : engine + if (engine instanceof ModuleComponentIdentifier) assert engine.version == '{hermes_version}' : engine + [(variant): [component: id.displayName, artifacts: artifacts.collect {{ it.file.absolutePath }}, hermes_component: engine.displayName]] + }} + file(layout.buildDirectory.file('consumer-resolution.json')).text = JsonOutput.prettyPrint(JsonOutput.toJson(result)) + }} + }} + """) + write(path / "app/src/main/AndroidManifest.xml", """ + + + + + + + + + + + """) + write(path / "app/src/main/java/com/facebook/react/kmp/consumer/MainActivity.java", ACTIVITY) + + +def device_check(adb, serial, fixture_dir, mode, log): + package = f"com.facebook.react.kmp.consumer.{mode}" + apk = fixture_dir / "app/build/outputs/apk/release/app-release.apk" + prefix = [adb, "-s", serial] + token = uuid.uuid4().hex + with log.open("w", encoding="utf-8") as output: + subprocess.run(prefix + ["install", "-r", str(apk)], stdout=output, + stderr=subprocess.STDOUT, check=True) + try: + subprocess.run(prefix + ["shell", "am", "start", "-W", "-n", + package + "/com.facebook.react.kmp.consumer.MainActivity", + "--es", "validationToken", token], + stdout=output, stderr=subprocess.STDOUT, check=True) + for _ in range(20): + text = subprocess.check_output(prefix + ["logcat", "-d", "-s", "KmpConsumer:I", "*:S"], text=True) + if f"KMP consumer PASS {mode} {token}" in text: + output.write(text) + return {"serial": serial, "release_adapter_assertions": "passed"} + time.sleep(0.5) + raise AssertionError(f"Release app did not report successful adapter checks: {mode}") + finally: + subprocess.run(prefix + ["shell", "am", "force-stop", package], check=False) + subprocess.run(prefix + ["uninstall", package], stdout=output, + stderr=subprocess.STDOUT, check=False) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--maven-repository", type=Path, help="Use an existing real ReactAndroid Maven publication instead of publishing locally") + parser.add_argument("--device", help="adb serial for executing both minified release APKs") + parser.add_argument("--abi", default="arm64-v8a") + parser.add_argument("--max-workers", type=int, default=4, help="Maximum concurrent Gradle workers") + parser.add_argument("--prepare-only", action="store_true", help="Pack and prepare fixtures; do not claim build or runtime validation") + args = parser.parse_args() + if args.max_workers < 1: + parser.error("--max-workers must be positive") + output = args.output_dir.resolve() if args.output_dir else Path(tempfile.mkdtemp(prefix="react-native-kmp-android-")) + output.mkdir(parents=True, exist_ok=True) + if any((output / name).exists() for name in ["binary", "source"]): + parser.error("Use a fresh output directory; existing consumer fixtures are never overwritten") + environment = dict(os.environ, npm_config_cache=str(output / "npm-cache"), + npm_config_fetch_timeout="30000", npm_config_fetch_retries="2") + packages = output / "packages" + packages.mkdir() + run(["yarn", "--cwd", str(REPOSITORY / "packages/react-native-codegen"), "build"], REPOSITORY, output / "codegen.log", environment) + archives = {name: pack(path, packages, environment) for name, path in { + "react-native": RN, "@react-native/codegen": REPOSITORY / "packages/react-native-codegen", + "@react-native/gradle-plugin": REPOSITORY / "packages/gradle-plugin", + }.items()} + source = output / "source" + for name, archive in archives.items(): + unpack(archive, source / "node_modules" / name) + packed_rn = source / "node_modules/react-native" + excluded_parts = {"build", ".build", ".gradle", ".kotlin", ".cxx", ".swiftpm", "__pycache__"} + leaked = [str(path.relative_to(packed_rn)) for path in (packed_rn / "ReactShared").rglob("*") + if any(part in excluded_parts for part in path.relative_to(packed_rn / "ReactShared").parts) + or path.suffix in {".pyc", ".o", ".a", ".so", ".dylib", ".class", ".framework", ".xcframework"}] + if leaked: + raise AssertionError(f"Generated ReactShared outputs leaked into the npm archive: {leaked}") + versions = tomllib.loads((packed_rn / "gradle/libs.versions.toml").read_text())["versions"] + version = properties(packed_rn / "ReactAndroid/gradle.properties")["VERSION_NAME"] + hermes = properties(packed_rn / "sdks/hermes-engine/version.properties")["HERMES_VERSION_NAME"] + maven = args.maven_repository.resolve() if args.maven_repository else output / "maven" + for mode in ["binary", "source"]: + fixture(output / mode, mode, versions, version, hermes, maven, args.abi) + report = {"status": "prepared", "archives": {name: {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} for name, path in archives.items()}, + "maven_repository": str(maven), "abi": args.abi, + "hermes_build": {"publication": "stable Maven dependency", "packed_source": "standard Hermes source build"}, + "consumers": {}} + report_file = output / "results.json" + report_file.write_text(json.dumps(report, indent=2) + "\n") + if args.prepare_only: + print(f"Prepared fixtures only; no Android builds or device tests ran. Report: {report_file}") + return + gradle = [str(REPOSITORY / "gradlew"), f"--max-workers={args.max_workers}", "--console=plain", + f"-PreactNativeArchitectures={args.abi}", + "-Dorg.gradle.internal.http.connectionTimeout=30000", "-Dorg.gradle.internal.http.socketTimeout=30000"] + try: + if not args.maven_repository: + init = output / "publication.gradle" + write(init, f""" + gradle.projectsEvaluated {{ + rootProject.allprojects.each {{ project -> + def publishing = project.extensions.findByType(org.gradle.api.publish.PublishingExtension) + publishing?.repositories?.withType(org.gradle.api.artifacts.repositories.MavenArtifactRepository)?.each {{ repository -> + if (repository.name == 'mavenTempLocal') repository.url = project.uri({groovy_string(maven)}) + }} + }} + }} + """) + run(gradle + ["-Preact.internal.useHermesStable=true", "--init-script", str(init), ":packages:react-native:ReactAndroid:publishReleasePublicationToMavenTempLocalRepository"], REPOSITORY, output / "publication.log") + aars = list((maven / "com/facebook/react/react-android" / version).glob("*.aar")) + if not aars: + raise AssertionError("The Maven publication contains no ReactAndroid AARs") + report["published_aars"] = [inspect_aar(aar) for aar in aars] + # Install dependencies for the packed tools, without installing an unpublished + # React Native version or replacing the extracted React Native source package. + write(source / "package.json", json.dumps({"private": True, "dependencies": { + name: f"file:{archives[name]}" for name in ["@react-native/codegen", "@react-native/gradle-plugin"]}}, indent=2)) + run(["npm", "install", "--ignore-scripts", "--no-audit", "--no-fund"], source, output / "source-dependencies.log", environment) + # npm may prune the manually extracted package because it is deliberately not + # installed from the registry. Re-extract the same immutable npm archive. + if (source / "node_modules/react-native").exists(): + shutil.rmtree(source / "node_modules/react-native") + unpack(archives["react-native"], source / "node_modules/react-native") + for mode in ["binary", "source"]: + consumer = output / mode + run(gradle + [":app:verifyResolution"], consumer, output / f"{mode}-build.log") + resolution = json.loads((consumer / "app/build/consumer-resolution.json").read_text()) + report["consumers"][mode] = {"debug_and_minified_release": "passed", "resolution": resolution, + "runtime": "not run: no --device supplied"} + if mode == "source": + built = list((packed_rn / "ReactAndroid/build/outputs/aar").glob("*.aar")) + if not built: + raise AssertionError("Packed-source consumer did not build a ReactAndroid AAR") + report["source_aars"] = [inspect_aar(aar) for aar in built] + if args.device: + sdk = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") + adb = str(Path(sdk) / "platform-tools/adb") if sdk else shutil.which("adb") + if not adb: + raise RuntimeError("adb is required for --device") + report["consumers"][mode]["runtime"] = device_check(adb, args.device, consumer, mode, output / f"{mode}-device.log") + report["status"] = "passed" + except Exception as error: + report["status"] = "failed" + report["error"] = str(error) + raise + finally: + report_file.write_text(json.dumps(report, indent=2) + "\n") + print(f"Android consumer report: {report_file}") + + +if __name__ == "__main__": + main() diff --git a/packages/react-native/ReactShared/scripts/test-android-multipart.py b/packages/react-native/ReactShared/scripts/test-android-multipart.py new file mode 100755 index 000000000000..54dd21744f73 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-android-multipart.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# 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. + +"""Run the real Android multipart adapter's JVM tests without building ReactAndroid. + +An optional benchmark compares the adapter with an explicitly selected native Git +baseline. This measures a host JVM, not Android ART or network throughput. +""" + +import argparse +import json +import pathlib +import re +import shutil +import subprocess +import tomllib + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=pathlib.Path) + parser.add_argument("--baseline-ref", help="Git revision of the native adapter") + parser.add_argument("--benchmark", action="store_true") + parser.add_argument("--offline", action="store_true") + parser.add_argument("--max-workers", type=int, default=2) + args = parser.parse_args() + if args.benchmark and not args.baseline_ref: + parser.error("--benchmark requires an explicit --baseline-ref") + + shared = pathlib.Path(__file__).resolve().parents[1] + react_native = shared.parent + repo = react_native.parents[1] + adapter = react_native / "ReactAndroid/src/main/java/com/facebook/react/devsupport/MultipartStreamReader.kt" + tests = react_native / "ReactAndroid/src/test/java/com/facebook/react/devsupport/MultipartStreamReaderTest.kt" + if not tests.is_file(): + parser.error("This fixture requires a React Native repository checkout; Android test sources are not included in the npm package.") + versions = tomllib.loads((react_native / "gradle/libs.versions.toml").read_text())["versions"] + language_version = ".".join(versions["kotlin"].split(".")[:2]) + output = (args.output or shared / "build/android-multipart-test").resolve() + output.mkdir(parents=True, exist_ok=True) + gradle = [str(shared / "gradlew"), "--console=plain", f"--max-workers={args.max_workers}"] + if args.offline: + gradle.append("--offline") + subprocess.run(gradle + ["-p", str(shared), "exportAndroidJar"], check=True) + + version = re.search(r'kotlin\("multiplatform"\) version "([^"]+)"', (shared / "build.gradle.kts").read_text()) + if not version: + raise RuntimeError("Could not find the shared module's Kotlin compiler version") + (output / "settings.gradle.kts").write_text(''' +pluginManagement { + resolutionStrategy { eachPlugin { + if (requested.id.id == "org.jetbrains.kotlin.jvm") + useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${requested.version}") + } } + repositories { mavenCentral(); gradlePluginPortal() } +} +dependencyResolutionManagement { repositories { mavenCentral() } } +rootProject.name = "multipart-adapter-tests" +''') + # Keep the standalone compiler compatible with its Gradle wrapper while + # matching ReactAndroid's language/API level and runtime dependencies. + (output / "gradle.properties").write_text("kotlin.stdlib.default.dependency=false\n") + (output / "build.gradle.kts").write_text(''' +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion + +plugins { kotlin("jvm") version %s } +kotlin { + jvmToolchain(17) + compilerOptions { + languageVersion.set(KotlinVersion.fromVersion(%s)) + apiVersion.set(KotlinVersion.fromVersion(%s)) + } +} +sourceSets { + main { kotlin.srcDir("main") } + test { kotlin.srcDir("test") } +} +dependencies { + implementation(files(%s)) + implementation("org.jetbrains.kotlin:kotlin-stdlib:%s") + implementation("com.squareup.okio:okio:%s") + testImplementation("junit:junit:%s") + testImplementation("org.assertj:assertj-core:%s") +} +tasks.test { testLogging { events("passed", "failed", "skipped") } } +tasks.register("benchmark") { + classpath = sourceSets.main.get().runtimeClasspath + mainClass.set("com.facebook.react.devsupport.AndroidMultipartBenchmarkKt") +} +''' % (json.dumps(version[1]), json.dumps(language_version), json.dumps(language_version), + json.dumps(str(shared / "build/android/react-native-shared.jar")), + versions["kotlin"], versions["okio"], versions["junit"], versions["assertj"])) + + # Keep only this runner's generated fixture inputs when reusing an output path. + generated = { + "main": ("MultipartStreamReader.kt", "MultipartStreamReaderBaseline.kt", "AndroidMultipartBenchmark.kt"), + "test": ("MultipartStreamReaderTest.kt", "MultipartStreamReaderBaselineTest.kt"), + } + for name, files in generated.items(): + directory = output / name + directory.mkdir(exist_ok=True) + for source in files: + (directory / source).unlink(missing_ok=True) + shutil.copyfile(adapter, output / "main" / adapter.name) + shutil.copyfile(tests, output / "test" / tests.name) + if args.baseline_ref: + baseline_commit = subprocess.check_output( + ["git", "rev-parse", "--verify", f"{args.baseline_ref}^{{commit}}"], cwd=repo, text=True + ).strip() + print(f"Native baseline: {baseline_commit}", flush=True) + baseline = subprocess.check_output( + ["git", "show", f"{baseline_commit}:{adapter.relative_to(repo)}"], cwd=repo, text=True + ) + if "com.facebook.react.shared" in baseline: + raise RuntimeError("The selected baseline already uses shared Kotlin code") + (output / "main/MultipartStreamReaderBaseline.kt").write_text( + baseline.replace("MultipartStreamReader", "MultipartStreamReaderBaseline") + ) + (output / "test/MultipartStreamReaderBaselineTest.kt").write_text( + tests.read_text().replace("MultipartStreamReader", "MultipartStreamReaderBaseline") + ) + if args.benchmark: + shutil.copyfile(shared / "tests/AndroidMultipartBenchmark.kt", output / "main/AndroidMultipartBenchmark.kt") + subprocess.run(gradle + ["-p", str(output), "test"], check=True) + if args.benchmark: + # Keep test compilation/execution out of the measurement window. + subprocess.run(gradle + ["-p", str(output), "benchmark"], check=True) + + +if __name__ == "__main__": + main() diff --git a/packages/react-native/ReactShared/scripts/test-apple-app.sh b/packages/react-native/ReactShared/scripts/test-apple-app.sh new file mode 100755 index 000000000000..5a849575d57a --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-app.sh @@ -0,0 +1,268 @@ +#!/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 -euo pipefail + +platform="${1:-simulator}" +case "$platform" in + simulator|device|catalyst) ;; + *) echo 'usage: test-apple-app.sh [simulator|device|catalyst] [--prepare-only]' >&2; exit 1 ;; +esac +if [[ $# -gt 2 || ( $# -eq 2 && "$2" != --prepare-only ) ]]; then + echo 'error: The only optional second argument is --prepare-only.' >&2 + exit 1 +fi + +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +repo_root="$(cd "$shared_root/../../.." && pwd)" +original="$repo_root/packages/rn-tester" +if [[ ! -f "$original/Podfile" ]]; then + echo 'error: This application test requires a React Native repository checkout with RNTester.' >&2 + exit 1 +fi +output="${RCT_KMP_APP_OUTPUT_DIR:-$shared_root/build/apple-app-$platform-${USE_FRAMEWORKS:-libraries}}" +mkdir -p "$output" +output="$(cd "$output" && pwd)" +if [[ -e "$output/DerivedData" || -e "$output/Tests.xcresult" ]]; then + echo 'error: Choose a fresh RCT_KMP_APP_OUTPUT_DIR; existing products must not count as this run.' >&2 + exit 1 +fi +# A sibling preserves RNTester's relative references to the other packages. +fixture="$(mktemp -d "$repo_root/packages/.rn-tester-kmp.XXXXXX")" +simulator="" +metro_pid="" +websocket_pid="" +cleanup() { + result=$? + trap - EXIT ERR + set +e + for pid in "$metro_pid" "$websocket_pid"; do + if [[ -n "$pid" ]]; then kill "$pid" 2>/dev/null; wait "$pid" 2>/dev/null; fi + done + if [[ -n "$simulator" ]]; then + xcrun simctl shutdown "$simulator" >/dev/null 2>&1 + xcrun simctl delete "$simulator" >/dev/null 2>&1 + fi + # Keep the generated configuration for diagnosis, without leaving a second app project. + cp "$fixture/Podfile" "$output/Podfile" 2>/dev/null + cp "$fixture/Podfile.lock" "$output/Podfile.lock" 2>/dev/null + cp "$fixture/package.json" "$output/package.json" 2>/dev/null + cp "$fixture/RNTesterPods.xcodeproj/project.pbxproj" "$output/project.pbxproj" 2>/dev/null + rm -rf "$fixture" + exit "$result" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +trap 'echo "error: RNTester validation failed; logs: $output" >&2' ERR + +rsync -a --exclude Pods --exclude build --exclude node_modules --exclude .xcode.env.local \ + "$original/" "$fixture/" +if [[ -d "$original/node_modules" ]]; then + ln -s "$original/node_modules" "$fixture/node_modules" +fi +# The source dependency graph can differ from the normally prebuilt Podfile.lock. +rm -f "$fixture/Podfile.lock" +python3 - "$fixture/Podfile" "$platform" <<'PY' +import pathlib +import json +import sys + +podfile = pathlib.Path(sys.argv[1]) +# The copy must not introduce a duplicate workspace package when Metro follows +# node_modules symlinks while bundling the original or copied app. +package_path = podfile.parent / 'package.json' +package = json.loads(package_path.read_text()) +package['name'] = '@react-native/tester-kmp-' + podfile.parent.name.rsplit('.', 1)[1].lower() +package_path.write_text(json.dumps(package, indent=2) + '\n') +source = podfile.read_text() +if sys.argv[2] == 'catalyst': + setting = ':mac_catalyst_enabled => false' + if source.count(setting) != 1: + sys.exit('error: RNTester Catalyst setting changed; update the fixture.') + source = source.replace(setting, ':mac_catalyst_enabled => true') +podfile.write_text(source) +PY +if [[ "${2:-}" == --prepare-only ]]; then + echo "RNTester $platform fixture prepared successfully; no dependencies, builds or tests were run." + exit 0 +fi + +export RCT_USE_KMP=1 RCT_USE_PREBUILT_RNCORE=0 RCT_USE_RN_DEP=0 +export RCT_NO_LAUNCH_PACKAGER=1 +export NODE_BINARY="$(command -v node)" +# Use the same bundle for the repository check and the copied app's Podfile. +export BUNDLE_GEMFILE="${BUNDLE_GEMFILE:-$repo_root/Gemfile}" +cd "$repo_root" +bundle check > "$output/bundle-check.log" 2>&1 +if [[ "$platform" == catalyst ]]; then + # Xcode selects destinations before applying command-line build settings. + # Enable Catalyst in the copied application project as well as in its pods. + bundle exec ruby - "$fixture/RNTesterPods.xcodeproj" <<'RUBY' +require 'xcodeproj' +project = Xcodeproj::Project.open(ARGV.fetch(0)) +project.targets.each do |target| + target.build_configurations.each do |configuration| + configuration.build_settings['SUPPORTS_MACCATALYST'] = 'YES' + end +end +project.save +RUBY +fi +yarn --cwd packages/react-native-codegen build > "$output/codegen.log" 2>&1 +cd "$fixture" +bundle exec pod install > "$output/pod-install.log" 2>&1 + +build=(xcodebuild -workspace "$fixture/RNTesterPods.xcworkspace" -scheme RNTester + -derivedDataPath "$output/DerivedData" -jobs "${RCT_KMP_APP_JOBS:-4}" CODE_SIGNING_ALLOWED=NO) +if [[ "$platform" == simulator ]]; then + # Own the servers and simulator so cleanup never stops a developer's processes. + for port in 8081 5555; do + if lsof -n -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then + echo "error: Port $port is in use; stop its server before running the application test." >&2 + exit 1 + fi + done + cd "$original" + "$repo_root/node_modules/.bin/react-native" start --max-workers 2 > "$output/metro.log" 2>&1 & + metro_pid=$! + node IntegrationTests/websocket_integration_test_server.js > "$output/websocket.log" 2>&1 & + websocket_pid=$! + ready=0 + for ((attempt=0; attempt<60; attempt++)); do + if curl --silent --fail --max-time 1 http://localhost:8081/status | grep -q 'packager-status:running' && \ + curl --silent --max-time 1 http://localhost:5555 | grep -q 'Upgrade Required'; then ready=1; break; fi + sleep 1 + done + if [[ "$ready" != 1 ]]; then echo 'error: Test servers did not become ready.' >&2; exit 1; fi + curl --silent --show-error --fail \ + 'http://localhost:8081/js/RNTesterApp.bundle?platform=ios&dev=true' -o "$output/RNTesterApp.bundle" + xcrun simctl list -j > "$output/simulators.json" + read -r device_type runtime < <(python3 - "$output/simulators.json" <<'PY' +import json +import sys + +state = json.load(open(sys.argv[1])) +runtimes = [item for item in state['runtimes'] if item.get('isAvailable') and '.iOS-' in item['identifier']] +if not runtimes: + sys.exit('error: Install an iOS Simulator runtime before running application tests.') +for runtime in sorted(runtimes, key=lambda item: tuple(map(int, item['version'].split('.'))), reverse=True): + devices = [item for item in state['devices'].get(runtime['identifier'], []) + if item.get('isAvailable') and item['name'].startswith('iPhone') and item.get('deviceTypeIdentifier')] + if devices: + print(devices[0]['deviceTypeIdentifier'], runtime['identifier']) + break +else: + sys.exit('error: Create an available iPhone simulator in Xcode before running application tests.') +PY +) + simulator="$(xcrun simctl create 'React Native KMP application test' "$device_type" "$runtime")" + xcrun simctl boot "$simulator" + xcrun simctl bootstatus "$simulator" -b + "${build[@]}" test -configuration Debug -sdk iphonesimulator \ + -destination "platform=iOS Simulator,id=$simulator" -parallel-testing-enabled NO \ + -resultBundlePath "$output/Tests.xcresult" > "$output/xcodebuild.log" 2>&1 + xcrun xcresulttool get test-results summary --path "$output/Tests.xcresult" > "$output/test-summary.json" + python3 - "$output/test-summary.json" <<'PY' +import json +import sys + +summary = json.load(open(sys.argv[1])) +if summary.get('failedTests', 0) or not summary.get('passedTests', 0): + sys.exit('error: RNTester must execute passing tests; an empty test run is not validation.') +PY + # The existing test plan enables sanitizers, so Xcode may add a Variant-ASan-UBSan directory. + product="$(python3 - "$output/DerivedData/Build/Products" <<'PY' +import pathlib +import sys + +apps = list(pathlib.Path(sys.argv[1]).glob('**/Debug-iphonesimulator/RNTester.app')) +if len(apps) != 1: + sys.exit(f'error: Expected one tested RNTester.app, found {apps}; use a fresh output directory.') +print(apps[0]) +PY +)" + identifier=$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$product/Info.plist") + xcrun simctl install "$simulator" "$product" + xcrun simctl launch --terminate-running-process "$simulator" "$identifier" > "$output/app-launch.log" 2>&1 +elif [[ "$platform" == device ]]; then + "${build[@]}" build -configuration Release -sdk iphoneos -destination 'generic/platform=iOS' \ + > "$output/xcodebuild.log" 2>&1 +else + "${build[@]}" build -configuration Debug -destination 'generic/platform=macOS,variant=Mac Catalyst' \ + SUPPORTS_MACCATALYST=YES > "$output/xcodebuild.log" 2>&1 +fi + +# Check the actual object compiled by the pod target: just finding Kotlin in the +# app would not prove that each adapter selected the shared implementation. +python3 - "$output/DerivedData" "$platform" "$output/shared-adapter-symbols.txt" <<'PY' +import pathlib +import subprocess +import sys + +expected_kmp = sys.argv[2] != 'catalyst' +reports = [] +for filename, classes in ( + ('RCTGradientUtils.o', ('RNSGradientStops',)), + ('RCTEnhancedScrollView.o', ('RNSScrollSnapOffsets',)), + ('RCTMultipartStreamReader.o', ('RNSMultipartFraming', 'RNSMultipartHeaders')), +): + objects = list(pathlib.Path(sys.argv[1]).rglob(filename)) + if not objects: + sys.exit(f'error: RNTester did not compile {filename} from source.') + symbols = [subprocess.check_output(['xcrun', 'nm', '-u', str(item)], text=True) for item in objects] + reports.extend([filename, *symbols]) + for class_name in classes: + if any((f'OBJC_CLASS_$_{class_name}' in item) != expected_kmp for item in symbols): + sys.exit(f'error: {filename} selected an unexpected implementation for {class_name}.') +pathlib.Path(sys.argv[3]).write_text('\n'.join(reports)) +PY +if [[ "$platform" == simulator ]]; then + # Hosted test bundles must resolve Kotlin classes through their app, even when + # their Podfile target independently declares the same pods. Standalone tests + # run in a different process and may link their own runtime. + python3 - "$product" "$output/shared-runtime-ownership.json" <<'PY' +import json +import pathlib +import plistlib +import subprocess +import sys + +app = pathlib.Path(sys.argv[1]) +def executable(bundle): + with (bundle / 'Info.plist').open('rb') as info: + return bundle / plistlib.load(info)['CFBundleExecutable'] + +def owns_runtime(binary): + symbols = subprocess.check_output(['xcrun', 'nm', '-gU', str(binary)], text=True) + return any(line.endswith(' _OBJC_CLASS_$_RNSBase') for line in symbols.splitlines()) + +main = executable(app) +candidates = [main, app / (main.name + '.debug.dylib')] +candidates.extend(executable(bundle) for bundle in (app / 'Frameworks').glob('*.framework')) +owners = [binary for binary in candidates if binary.exists() and owns_runtime(binary)] +if len(owners) != 1: + sys.exit(f'error: Expected one shared runtime owner in RNTester, found {owners}') +owner = owners[0] +hosted = [] +for bundle in (app / 'PlugIns').glob('*.xctest'): + if owns_runtime(executable(bundle)): + sys.exit(f'error: Hosted test bundle duplicates the app shared runtime: {bundle}') + # CocoaPods may also package an identical dynamic framework for XCTest. + for framework in (bundle / 'Frameworks').glob('*.framework'): + copy = executable(framework) + if owns_runtime(copy) and (framework.name != owner.parent.name or copy.read_bytes() != owner.read_bytes()): + sys.exit(f'error: Hosted test bundle has a different shared runtime framework: {copy}') + hosted.append(str(bundle.relative_to(app))) +pathlib.Path(sys.argv[2]).write_text(json.dumps({ + 'runtimeOwner': str(owner.relative_to(app)), + 'hostedBundlesWithoutOwnRuntime': hosted, +}, indent=2) + '\n') +PY + echo "RNTester tests and simulator launch passed (${USE_FRAMEWORKS:-static libraries}); reports: $output" +else + echo "RNTester $platform unsigned build passed; no device tests were run. Reports: $output" +fi diff --git a/packages/react-native/ReactShared/scripts/test-apple-distribution.sh b/packages/react-native/ReactShared/scripts/test-apple-distribution.sh new file mode 100755 index 000000000000..b33c93fcdbfa --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-distribution.sh @@ -0,0 +1,117 @@ +#!/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 -euo pipefail + +mode="${1:-}" +case "$mode" in + ''|--build-only|--package-only) ;; + *) echo "Usage: $0 [--build-only|--package-only]" >&2; exit 1 ;; +esac +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +build_type="${RCT_KMP_BUILD_TYPE:-Release}" +case "$build_type" in + Debug) variant=debugFramework ;; + Release) variant=releaseFramework ;; + *) echo 'error: RCT_KMP_BUILD_TYPE must be Debug or Release.' >&2; exit 1 ;; +esac +output="${RCT_KMP_DISTRIBUTION_OUTPUT_DIR:-$shared_root/build/apple-distribution/$build_type}" +mkdir -p "$output" +output="$(cd "$output" && pwd)" +# A fresh fixture avoids stale architecture slices or outputs from another build. +fixture="$(mktemp -d "$output/consumer.XXXXXX")" +cp -R "$shared_root/tests/distribution/." "$fixture/" + +if [[ "$mode" != --package-only ]]; then + "$shared_root/gradlew" -p "$shared_root" --console=plain \ + "link${build_type}FrameworkIosArm64" \ + "link${build_type}FrameworkIosSimulatorArm64" \ + "link${build_type}FrameworkIosX64" +fi + +device="$shared_root/build/bin/iosArm64/$variant/ReactNativeShared.framework" +sim_arm="$shared_root/build/bin/iosSimulatorArm64/$variant/ReactNativeShared.framework" +sim_intel="$shared_root/build/bin/iosX64/$variant/ReactNativeShared.framework" +for framework in "$device" "$sim_arm" "$sim_intel"; do + test -f "$framework/ReactNativeShared" + cmp "$device/Headers/ReactNativeShared.h" "$framework/Headers/ReactNativeShared.h" +done +ditto "$sim_arm" "$fixture/simulator/ReactNativeShared.framework" +xcrun lipo -create "$sim_arm/ReactNativeShared" "$sim_intel/ReactNativeShared" \ + -output "$fixture/simulator/ReactNativeShared.framework/ReactNativeShared" +xcodebuild -create-xcframework -framework "$device" \ + -framework "$fixture/simulator/ReactNativeShared.framework" \ + -output "$fixture/ReactNativeShared.xcframework" > "$fixture/package.log" 2>&1 + +# Include the matching Kotlin runtime's license bundle in any packaged experiment. +python3 - "$shared_root" "$fixture" "$mode" <<'PY' +import hashlib, json, os, pathlib, platform, plistlib, re, shutil, sys +root, fixture = map(pathlib.Path, sys.argv[1:3]) +compiler = re.search(r'version "([^"]+)"', (root / 'build.gradle.kts').read_text())[1] +host = 'aarch64' if platform.machine() == 'arm64' else 'x86_64' +konan = pathlib.Path(os.environ.get('KONAN_DATA_DIR', pathlib.Path.home() / '.konan')) +native_home = pathlib.Path(os.environ.get('KONAN_HOME', konan / f'kotlin-native-prebuilt-macos-{host}-{compiler}')) +licenses = native_home / 'licenses' +if not (licenses / 'LICENSE.txt').is_file(): + sys.exit(f'error: Matching Kotlin {compiler} licenses missing at {licenses}; set KONAN_HOME.') +shutil.copytree(licenses, fixture / 'licenses' / 'kotlin') +shutil.copyfile(root.parent / 'LICENSE', fixture / 'licenses' / 'ReactNative-LICENSE') +xcf = fixture / 'ReactNativeShared.xcframework' +info = plistlib.loads((xcf / 'Info.plist').read_bytes()) +slices = {(item['SupportedPlatform'], item.get('SupportedPlatformVariant', ''), + tuple(sorted(item['SupportedArchitectures']))) for item in info['AvailableLibraries']} +expected = {('ios', '', ('arm64',)), ('ios', 'simulator', ('arm64', 'x86_64'))} +if slices != expected: + sys.exit(f'error: Unexpected XCFramework slices: {slices}') +manifest = { + 'kotlinVersion': compiler, + 'reusedExistingFrameworks': sys.argv[3] == '--package-only', + 'files': {str(p.relative_to(fixture)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(xcf.rglob('*')) if p.is_file()}, + 'scope': 'Isolated binary consumer; not the React Native core SwiftPM/prebuilt integration', +} +(fixture / 'distribution.json').write_text(json.dumps(manifest, indent=2) + '\n') +PY + +if [[ "$mode" == --package-only ]]; then + echo "XCFramework slices and licenses checked using existing frameworks; consumer build/execution pending: $fixture" + exit 0 +fi + +(cd "$fixture" && swift package describe --type json) > "$fixture/package-description.json" 2> "$fixture/package-description.log" +for platform in 'iOS' 'iOS Simulator' 'macOS,variant=Mac Catalyst'; do + name="${platform// /-}" + (cd "$fixture" && xcodebuild -scheme KMPDistributionProbe \ + -destination "generic/platform=$platform" -derivedDataPath "$fixture/derived/$name" \ + -configuration "$build_type" CLANG_ENABLE_CODE_COVERAGE=NO CODE_SIGNING_ALLOWED=NO build) > "$fixture/$name.log" 2>&1 +done +if [[ "$mode" != --build-only ]]; then + simulator="${RCT_KMP_SIMULATOR_UDID:-}" + if [[ -z "$simulator" ]]; then + simulator="$(xcrun simctl list devices available -j | python3 -c ' +import json, sys +for runtime, devices in json.load(sys.stdin)["devices"].items(): + if ".iOS-" in runtime and devices: + print(devices[0]["udid"]) + break +')" + fi + : "${simulator:?Install an iOS simulator runtime or set RCT_KMP_SIMULATOR_UDID}" + (cd "$fixture" && xcodebuild -scheme KMPDistributionProbe \ + -destination "id=$simulator" -derivedDataPath "$fixture/derived/iOS-Simulator" \ + -configuration "$build_type" -resultBundlePath "$fixture/consumer.xcresult" \ + -enableCodeCoverage NO CODE_SIGNING_ALLOWED=NO test) > "$fixture/consumer-test.log" 2>&1 + xcrun xcresulttool get test-results summary --path "$fixture/consumer.xcresult" > "$fixture/test-summary.json" + python3 - "$fixture/test-summary.json" <<'PY' +import json +import sys + +summary = json.load(open(sys.argv[1])) +if summary.get('failedTests', 0) or not summary.get('passedTests', 0): + sys.exit('error: The distribution consumer must execute passing tests.') +PY +fi +echo "Apple distribution checks completed ($mode): $fixture" diff --git a/packages/react-native/ReactShared/scripts/test-apple-gradient.sh b/packages/react-native/ReactShared/scripts/test-apple-gradient.sh new file mode 100755 index 000000000000..76546496098c --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-gradient.sh @@ -0,0 +1,119 @@ +#!/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 -euo pipefail + +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +react_native_root="$(cd "$shared_root/.." && pwd)" +test_root="${RCT_KMP_TEST_OUTPUT_DIR:-$shared_root/build/apple-gradient-test}" +architecture="$(uname -m)" +sdk_root="$(xcrun --sdk iphonesimulator --show-sdk-path)" +mkdir -p "$test_root/include/React" + +# Build and stage through the same helper that the CocoaPods build phase uses. +PLATFORM_NAME=iphonesimulator ARCHS="$architecture" CONFIGURATION=Debug \ + PODS_CONFIGURATION_BUILD_DIR="$test_root" "$shared_root/scripts/build-apple-framework.sh" + +for header in "$react_native_root"/React/Base/*.h; do + ln -sf "$header" "$test_root/include/React/$(basename "$header")" +done +ln -sf "$react_native_root/Libraries/NativeAnimation/RCTAnimationUtils.h" "$test_root/include/React/RCTAnimationUtils.h" +ln -sf "$react_native_root/React/Fabric/Utils/RCTGradientUtils.h" "$test_root/include/React/RCTGradientUtils.h" + +# Use the real inline color conversion without pulling unrelated renderer/Folly +# headers into this standalone test. Fail if its declaration can no longer be extracted. +python3 - "$react_native_root/React/Fabric/RCTConversions.h" "$test_root/include/React/RCTConversions.h" <<'PY' +import pathlib +import re +import sys + +source = pathlib.Path(sys.argv[1]).read_text() +helpers = re.findall( + r"(?m)^inline UIColor \*_Nullable RCTUIColorFromSharedColor\([^\n]*\)\n\{[^{}]*\n\}", source +) +if len(helpers) != 1: + sys.exit("error: RCTUIColorFromSharedColor changed; update the standalone parity header extraction.") +pathlib.Path(sys.argv[2]).write_text( + "#import \n" + "#import \n" + helpers[0] + "\n" +) +PY + +graphics="$react_native_root/ReactCommon/react/renderer/graphics" +ios_graphics="$graphics/platform/ios/react/renderer/graphics" +flags=( + -std=c++20 -fobjc-arc -DREACT_NATIVE_PRODUCTION -DRCTLOG_ENABLED=0 -include memory -include vector + -target "$architecture-apple-ios15.1-simulator" -isysroot "$sdk_root" + -I "$test_root/include" -I "$react_native_root/ReactCommon" -I "$graphics/platform/ios" + -F "$test_root/ReactNativeSharedKMP" +) +if [[ "${RCT_KMP_BUILD_TYPE:-Debug}" == "Release" ]]; then + flags+=(-O2) +fi +adapter="$react_native_root/React/Fabric/Utils/RCTGradientUtils.mm" +xcrun clang++ "${flags[@]}" -DRCT_USE_KMP=1 -c "$adapter" -o "$test_root/adapter.o" +xcrun clang++ "${flags[@]}" -DRCT_USE_KMP=0 -DRCTGradientUtils=RCTGradientUtilsBaseline \ + -c "$adapter" -o "$test_root/baseline.o" +native_sources=( + "$react_native_root/Libraries/NativeAnimation/RCTAnimationUtils.mm" + "$graphics/Color.cpp" "$graphics/ColorComponents.cpp" + "$ios_graphics/HostPlatformColor.mm" "$ios_graphics/RCTPlatformColorUtils.mm" + "$react_native_root/ReactCommon/react/utils/ManagedObjectWrapper.mm" +) +native_objects=() +for source in "${native_sources[@]}"; do + object="$test_root/$(basename "$source").o" + xcrun clang++ "${flags[@]}" -x objective-c++ -c "$source" -o "$object" + native_objects+=("$object") +done +frameworks=(-framework Foundation -framework UIKit -framework QuartzCore -framework CoreGraphics) +xcrun clang++ "${flags[@]}" "$shared_root/tests/AppleGradientParity.mm" \ + "$test_root/adapter.o" "$test_root/baseline.o" "${native_objects[@]}" \ + -framework ReactNativeShared "${frameworks[@]}" \ + -o "$test_root/AppleGradientParity" + +# Exercise the dynamic RCTFabric linkage model too: Kotlin is linked into this +# library only, and the caller links the library without another Kotlin runtime. +xcrun clang++ "${flags[@]}" -dynamiclib "$test_root/adapter.o" "${native_objects[@]}" \ + -framework ReactNativeShared "${frameworks[@]}" \ + -Wl,-install_name,@rpath/libKMPGradientAdapter.dylib -o "$test_root/libKMPGradientAdapter.dylib" +xcrun clang++ "${flags[@]}" "$shared_root/tests/AppleGradientParity.mm" "$test_root/baseline.o" \ + -L "$test_root" -lKMPGradientAdapter "${frameworks[@]}" -Wl,-rpath,"$test_root" \ + -o "$test_root/AppleGradientParityDynamic" + +# Catalyst must compile the original path even when the pilot flag is defined, +# without a framework header search path or a nonexistent Catalyst K/N slice. +mac_sdk_root="$(xcrun --sdk macosx --show-sdk-path)" +xcrun clang++ -std=c++20 -fobjc-arc -DREACT_NATIVE_PRODUCTION -DRCT_USE_KMP=1 \ + -target "$architecture-apple-ios15.1-macabi" -isysroot "$mac_sdk_root" \ + -isystem "$mac_sdk_root/System/iOSSupport/usr/include" \ + -iframework "$mac_sdk_root/System/iOSSupport/System/Library/Frameworks" \ + -include memory -include vector -I "$test_root/include" \ + -I "$react_native_root/ReactCommon" -I "$graphics/platform/ios" -fsyntax-only "$adapter" + +if [[ "${RCT_KMP_BUILD_ONLY:-0}" == "1" ]]; then + echo "Apple gradient harnesses compiled; execution was not requested: $test_root" + exit 0 +fi + +simulator="${RCT_KMP_SIMULATOR_UDID:-}" +if [[ -z "$simulator" ]]; then + simulator="$(xcrun simctl list devices available -j | python3 -c ' +import json, sys +devices = json.load(sys.stdin)["devices"] +for runtime, entries in devices.items(): + if ".iOS-" in runtime and entries: + print(entries[0]["udid"]) + break +')" +fi +if [[ -z "$simulator" ]]; then + echo 'error: Install an iOS Simulator runtime in Xcode before running the Apple gradient parity test.' >&2 + exit 1 +fi +# Standalone spawn runs the executable without booting or modifying the simulator. +xcrun simctl spawn --standalone "$simulator" "$test_root/AppleGradientParity" +xcrun simctl spawn --standalone "$simulator" "$test_root/AppleGradientParityDynamic" diff --git a/packages/react-native/ReactShared/scripts/test-apple-multipart.sh b/packages/react-native/ReactShared/scripts/test-apple-multipart.sh new file mode 100755 index 000000000000..ce6bce09acb2 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-multipart.sh @@ -0,0 +1,95 @@ +#!/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 -euo pipefail + +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +react_native_root="$(cd "$shared_root/.." && pwd)" +repo_root="$(cd "$react_native_root/../.." && pwd)" +tests="$repo_root/packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m" +if [[ ! -f "$tests" ]]; then + echo 'error: This fixture requires a React Native repository checkout with RNTester test sources.' >&2 + exit 1 +fi +test_root="${RCT_KMP_TEST_OUTPUT_DIR:-$shared_root/build/apple-multipart-test}" +architecture="$(uname -m)" +sdk_root="$(xcrun --sdk iphonesimulator --show-sdk-path)" +developer="$(xcode-select -p)/Platforms/iPhoneSimulator.platform/Developer" +mkdir -p "$test_root/include/React" +ln -sf "$react_native_root/React/Base/RCTMultipartStreamReader.h" "$test_root/include/React/RCTMultipartStreamReader.h" + +PLATFORM_NAME=iphonesimulator ARCHS="$architecture" CONFIGURATION=Release \ + PODS_CONFIGURATION_BUILD_DIR="$test_root" "$shared_root/scripts/build-apple-framework.sh" + +flags=( + -fobjc-arc -O2 -target "$architecture-apple-ios15.1-simulator" -isysroot "$sdk_root" + -I "$test_root/include" -F "$test_root/ReactNativeSharedKMP" +) +adapter="$react_native_root/React/Base/RCTMultipartStreamReader.m" +xcrun clang "${flags[@]}" -DRCT_USE_KMP=1 -c "$adapter" -o "$test_root/adapter.o" +xcrun clang "${flags[@]}" -DRCT_USE_KMP=0 -DRCTMultipartStreamReader=RCTMultipartStreamReaderBaseline \ + -c "$adapter" -o "$test_root/baseline.o" + +# Check that the opt-in actually calls the shared framing/header types. +nm -u "$test_root/adapter.o" | grep -q 'OBJC_CLASS_\$_RNSMultipartFraming' +nm -u "$test_root/adapter.o" | grep -q 'OBJC_CLASS_\$_RNSMultipartHeaders' +if nm -u "$test_root/baseline.o" | grep -q 'OBJC_CLASS_\$_RNS'; then + echo 'error: Native fallback unexpectedly references Kotlin classes.' >&2 + exit 1 +fi + +# Compile the actual RNTester XCTest source, then run the same tests on both paths. +for mode in native kmp; do + bundle="$test_root/Multipart-$mode.xctest" + mkdir -p "$bundle" + use_kmp=0 + if [[ "$mode" == kmp ]]; then use_kmp=1; fi + xcrun clang "${flags[@]}" -DRCT_USE_KMP="$use_kmp" -bundle \ + -F "$developer/Library/Frameworks" -framework XCTest \ + -Wl,-rpath,"$developer/Library/Frameworks" \ + "$adapter" "$tests" \ + -framework Foundation -framework QuartzCore -framework ReactNativeShared -o "$bundle/MultipartTests" + /usr/libexec/PlistBuddy -c Clear "$bundle/Info.plist" >/dev/null + /usr/libexec/PlistBuddy -c 'Add :CFBundleExecutable string MultipartTests' "$bundle/Info.plist" + /usr/libexec/PlistBuddy -c 'Add :CFBundleIdentifier string com.facebook.react.MultipartTests' "$bundle/Info.plist" + /usr/libexec/PlistBuddy -c 'Add :CFBundlePackageType string BNDL' "$bundle/Info.plist" +done + +xcrun clang "${flags[@]}" "$shared_root/tests/AppleMultipartParity.m" \ + "$test_root/adapter.o" "$test_root/baseline.o" \ + -framework Foundation -framework QuartzCore -framework ReactNativeShared -o "$test_root/AppleMultipartParity" + +# Catalyst keeps the Foundation implementation, including when opt-in is set. +mac_sdk_root="$(xcrun --sdk macosx --show-sdk-path)" +xcrun clang -fobjc-arc -DRCT_USE_KMP=1 \ + -target "$architecture-apple-ios15.1-macabi" -isysroot "$mac_sdk_root" \ + -isystem "$mac_sdk_root/System/iOSSupport/usr/include" \ + -iframework "$mac_sdk_root/System/iOSSupport/System/Library/Frameworks" \ + -fsyntax-only "$adapter" + +if [[ "${RCT_KMP_BUILD_ONLY:-0}" == "1" ]]; then exit 0; fi +simulator="${RCT_KMP_SIMULATOR_UDID:-}" +if [[ -z "$simulator" ]]; then + simulator="$(xcrun simctl list devices available -j | python3 -c ' +import json, sys +for runtime, entries in json.load(sys.stdin)["devices"].items(): + if ".iOS-" in runtime and entries: + print(entries[0]["udid"]) + break +')" +fi +if [[ -z "$simulator" ]]; then + echo 'error: Install an iOS Simulator runtime before running multipart tests.' >&2 + exit 1 +fi +for mode in native kmp; do + xcrun simctl spawn --standalone "$simulator" "$developer/Library/Xcode/Agents/xctest" \ + "$test_root/Multipart-$mode.xctest" +done +xcrun simctl spawn --standalone "$simulator" "$test_root/AppleMultipartParity" +if [[ "${RCT_KMP_BENCHMARK:-0}" == "1" ]]; then + xcrun simctl spawn --standalone "$simulator" "$test_root/AppleMultipartParity" --benchmark +fi diff --git a/packages/react-native/ReactShared/scripts/test-apple-scroll-snap.py b/packages/react-native/ReactShared/scripts/test-apple-scroll-snap.py new file mode 100755 index 000000000000..925317278558 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-scroll-snap.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +# 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. + +"""Compile the real Apple scroll adapter in both modes, compare it, and measure Release calls. + +Uses an iOS simulator; does not build RNTester or change an existing simulator's state. +Measurements are isolated simulator observations, not device interaction or app startup results. +""" + +import argparse +import hashlib +import json +import os +import pathlib +import platform +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=pathlib.Path) + parser.add_argument("--build-only", action="store_true") + parser.add_argument("--benchmark-repeats", type=int, default=3) + args = parser.parse_args() + if not 0 <= args.benchmark_repeats <= 20: + parser.error("benchmark-repeats must be 0..20") + shared = pathlib.Path(__file__).resolve().parent.parent + react = shared.parent + output = (args.output or shared / "build/apple-scroll-snap").resolve() + output.mkdir(parents=True, exist_ok=False) + command_number = 0 + + def run(command, **kwargs): + nonlocal command_number + command_number += 1 + result = subprocess.run(command, capture_output=True, text=True, **kwargs) + (output / f"command-{command_number}.log").write_text( + repr(command) + "\n" + result.stdout + result.stderr + ) + if result.returncode: + raise RuntimeError(f"Command failed; see {output}/command-{command_number}.log\n{result.stderr[-4000:]}") + return result.stdout + + architecture = platform.machine() + task_target = {"arm64": "IosSimulatorArm64", "x86_64": "IosX64"}[architecture] + native_target = {"arm64": "iosSimulatorArm64", "x86_64": "iosX64"}[architecture] + run([str(shared / "gradlew"), "-p", str(shared), f"linkReleaseFramework{task_target}", + "--max-workers=2", "--console=plain"]) + framework_parent = shared / f"build/bin/{native_target}/releaseFramework" + include = output / "include/React" + include.mkdir(parents=True) + for header in (react / "React/Base").glob("*.h"): + (include / header.name).symlink_to(header) + scroll = react / "React/Fabric/Mounting/ComponentViews/ScrollView" + splitter = react / "React/Fabric/Utils" + for header in [scroll / "RCTEnhancedScrollView.h", splitter / "RCTGenericDelegateSplitter.h"]: + (include / header.name).symlink_to(header) + # EnhancedScrollView.h includes this header without using any of its declarations. + # Keep unrelated Fabric/Folly dependencies out of the standalone UIKit fixture. + (include / "RCTViewComponentView.h").write_text("// Unused transitive Fabric header in this standalone fixture.\n") + sdk = run(["xcrun", "--sdk", "iphonesimulator", "--show-sdk-path"]).strip() + flags = ["-std=c++20", "-O2", "-fobjc-arc", "-DREACT_NATIVE_PRODUCTION", "-DRCTLOG_ENABLED=0", + "-target", f"{architecture}-apple-ios15.1-simulator", "-isysroot", sdk, + "-I", str(output / "include"), "-I", str(react / "ReactCommon"), "-F", str(framework_parent)] + frameworks = ["-framework", "Foundation", "-framework", "UIKit", "-framework", "QuartzCore", "-framework", "CoreGraphics"] + adapter = scroll / "RCTEnhancedScrollView.mm" + harness = shared / "tests/AppleScrollSnapParity.mm" + splitter_object = output / "splitter.o" + run(["xcrun", "clang++", *flags, "-c", str(splitter / "RCTGenericDelegateSplitter.mm"), "-o", str(splitter_object)]) + for mode, defines in { + "kmp": ["-DRCT_USE_KMP=1"], + "baseline": ["-DRCT_USE_KMP=0", "-DRCTEnhancedScrollView=RCTEnhancedScrollViewBaseline"], + "native": ["-DRCT_USE_KMP=0"], + }.items(): + run(["xcrun", "clang++", *flags, *defines, "-c", str(adapter), "-o", str(output / f"{mode}.o")]) + # Control for the benefit of caching alone: compile the actual native implementation + # with vector storage/access, leaving its selection algorithm unchanged. This staged + # file is a measurement fixture, never a production source edit. + cached_source = adapter.read_text() + edits = { + '#import "RCTEnhancedScrollView.h"': '#import \n#include ', + ' BOOL _isSetContentOffsetDisabled;': ' BOOL _isSetContentOffsetDisabled;\n std::vector _cachedNativeOffsets;', + '}\n\n#if RCT_SCROLL_SNAP_USE_KMP\n@synthesize': '''} +@synthesize snapToOffsets = _snapToOffsets; +- (void)setSnapToOffsets:(NSArray *)snapToOffsets +{ + _snapToOffsets = [snapToOffsets copy]; + _cachedNativeOffsets.clear(); + _cachedNativeOffsets.reserve(_snapToOffsets.count); + for (NSNumber *offset in _snapToOffsets) { + _cachedNativeOffsets.push_back(offset.floatValue); + } +} + +#if RCT_SCROLL_SNAP_USE_KMP +@synthesize''', + 'i < self.snapToOffsets.count': 'i < _cachedNativeOffsets.size()', + '[[self.snapToOffsets objectAtIndex:i] floatValue]': '_cachedNativeOffsets[i]', + '[[self.snapToOffsets firstObject] floatValue]': '_cachedNativeOffsets.front()', + '[[self.snapToOffsets lastObject] floatValue]': '_cachedNativeOffsets.back()', + } + for before, after in edits.items(): + if cached_source.count(before) != 1: + raise RuntimeError(f"Native cache control requires review after adapter change: {before}") + cached_source = cached_source.replace(before, after) + cached_path = output / "CachedNativeScrollView.mm" + cached_path.write_text(cached_source) + for name, defines in {"cached": [], "cached-parity": ["-DRCTEnhancedScrollView=RCTEnhancedScrollViewCached"]}.items(): + run(["xcrun", "clang++", *flags, "-DRCT_USE_KMP=0", *defines, "-c", str(cached_path), "-o", str(output / f"{name}.o")]) + symbols = {mode: run(["xcrun", "nm", "-u", str(output / f"{mode}.o")]) for mode in ("kmp", "native")} + if "RNSScrollSnapOffsets" not in symbols["kmp"] or "RNS" in symbols["native"]: + raise RuntimeError("Compiled adapters did not use the expected KMP/native paths") + parity = output / "AppleScrollSnapParity" + run(["xcrun", "clang++", *flags, str(harness), str(output / "kmp.o"), str(output / "baseline.o"), str(output / "cached-parity.o"), + str(splitter_object), *frameworks, "-framework", "ReactNativeShared", "-o", str(parity)]) + executables = {} + for mode in ("native", "cached", "kmp"): + executable = output / f"AppleScrollSnapBenchmark-{mode}" + run(["xcrun", "clang++", *flags, "-DRCT_SCROLL_BENCHMARK=1", str(harness), str(output / f"{mode}.o"), + str(splitter_object), *frameworks, *(["-framework", "ReactNativeShared"] if mode == "kmp" else []), + "-Wl,-dead_strip", "-o", str(executable)]) + executables[mode] = executable + mac_sdk = run(["xcrun", "--sdk", "macosx", "--show-sdk-path"]).strip() + catalyst = output / "catalyst.o" + run(["xcrun", "clang++", "-std=c++20", "-fobjc-arc", "-DRCT_USE_KMP=1", "-DREACT_NATIVE_PRODUCTION", + "-target", f"{architecture}-apple-ios15.1-macabi", "-isysroot", mac_sdk, + "-isystem", f"{mac_sdk}/System/iOSSupport/usr/include", + "-iframework", f"{mac_sdk}/System/iOSSupport/System/Library/Frameworks", + "-I", str(output / "include"), "-I", str(react / "ReactCommon"), "-c", str(adapter), "-o", str(catalyst)]) + if "RNS" in run(["xcrun", "nm", "-u", str(catalyst)]): + raise RuntimeError("Catalyst unexpectedly references Kotlin/Native") + sources = [adapter, harness, shared / "src/commonMain/kotlin/com/facebook/react/shared/ScrollSnapOffsets.kt"] + report = { + "configuration": "Release; actual UIKit adapter compiled with KMP enabled and disabled", + "platform": f"{architecture} iOS simulator", "sdk": sdk, + "cachedNativeControlSha256": hashlib.sha256(cached_path.read_bytes()).hexdigest(), + "sourceSha256": {str(path.relative_to(react)): hashlib.sha256(path.read_bytes()).hexdigest() for path in sources}, + "catalystNativeFallbackCompiled": True, "runtimeExecuted": False, + "executableBytes": {mode: path.stat().st_size for mode, path in executables.items()}, + "benchmarks": [], + "limitations": [ + "Not physical-device performance, gesture interaction, or full-application startup/size.", + "First property assignment includes snapshot conversion and lazy Kotlin initialization.", + "Repeated flings reuse the property snapshot; each sample includes an autorelease pool per call.", + "Cached-native control changes only property storage/access in a staged native adapter copy.", + "Runs share the host with unrelated processes; timing is observational, with no pass/fail threshold.", + "One unrelated unused Fabric header is omitted; RN logging sanitizer is replaced by a finite-input assertion.", + ], + } + simulator = os.environ.get("RCT_KMP_SIMULATOR_UDID") + owned = None + try: + if not args.build_only: + if not simulator: + inventory = json.loads(run(["xcrun", "simctl", "list", "-j"])) + runtime = next((item for item in inventory["runtimes"] + if item.get("isAvailable") and "iOS" in item["identifier"]), None) + device = next((item["identifier"] for item in (runtime or {}).get("supportedDeviceTypes", []) + if "iPhone" in item["name"]), None) + if not device: + raise RuntimeError("Install a compatible iOS simulator runtime") + owned = run(["xcrun", "simctl", "create", "KMP Scroll Snap Validation", device, runtime["identifier"]]).strip() + simulator = owned + report["parity"] = json.loads(run(["xcrun", "simctl", "spawn", "--standalone", simulator, str(parity)])) + report["runtimeExecuted"] = True + for repetition in range(args.benchmark_repeats): + for count in (3, 16, 256): + for mode in (("native", "cached", "kmp") if repetition % 2 == 0 else ("kmp", "cached", "native")): + measurement = json.loads(run(["xcrun", "simctl", "spawn", "--standalone", simulator, + str(executables[mode]), str(count)])) + measurement.update(mode=mode, repetition=repetition) + report["benchmarks"].append(measurement) + finally: + if owned: + run(["xcrun", "simctl", "delete", owned]) + (output / "results.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/packages/react-native/ReactShared/scripts/test-apple-smoke.sh b/packages/react-native/ReactShared/scripts/test-apple-smoke.sh new file mode 100755 index 000000000000..81ed4afe4c4e --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-apple-smoke.sh @@ -0,0 +1,51 @@ +#!/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 -euo pipefail + +shared_root="$(cd "$(dirname "$0")/.." && pwd)" +architecture="$(uname -m)" +case "$architecture" in + arm64) target=IosSimulatorArm64; kotlin_target=iosSimulatorArm64 ;; + x86_64) target=IosX64; kotlin_target=iosX64 ;; + *) echo "error: Unsupported simulator architecture: $architecture" >&2; exit 1 ;; +esac + +"$shared_root/gradlew" -p "$shared_root" -PreactNativeSharedSmoke=true \ + "linkDebugFramework$target" "linkReleaseFramework$target" --max-workers=2 --console=plain + +output="$shared_root/build/smoke/apple-interop" +mkdir -p "$output" +sdk="$(xcrun --sdk iphonesimulator --show-sdk-path)" +simulator="${RCT_KMP_SIMULATOR_UDID:-}" +if [[ -z "$simulator" ]]; then + simulator="$(xcrun simctl list -j | python3 -c ' +import json, sys +state = json.load(sys.stdin) +runtimes = sorted((r for r in state["runtimes"] if r.get("isAvailable") and ".iOS-" in r["identifier"]), + key=lambda r: tuple(map(int, r["version"].split("."))), reverse=True) +for runtime in runtimes: + devices = [d for d in state["devices"].get(runtime["identifier"], []) if d.get("isAvailable")] + if devices: + print(devices[0]["udid"]) + break +')" +fi +if [[ -z "$simulator" ]]; then + echo 'error: Install an iOS simulator runtime and create a device in Xcode.' >&2 + exit 1 +fi + +for configuration in debug release; do + frameworks="$shared_root/build/smoke/bin/$kotlin_target/${configuration}Framework" + executable="$output/AppleKmpSmoke-$configuration" + xcrun clang++ -std=c++20 -fobjc-arc -target "$architecture-apple-ios15.1-simulator" \ + -isysroot "$sdk" -F "$frameworks" "$shared_root/tests/smoke/AppleKmpSmoke.mm" \ + -framework ReactNativeShared -framework Foundation -o "$executable" + # Standalone execution does not boot or alter the selected simulator. + xcrun simctl spawn --standalone "$simulator" "$executable" 2>&1 | tee "$output/$configuration.log" + grep -q '^Kotlin Objective-C smoke passed: 5 cases$' "$output/$configuration.log" +done diff --git a/packages/react-native/ReactShared/scripts/test-cocoapods-linking.rb b/packages/react-native/ReactShared/scripts/test-cocoapods-linking.rb new file mode 100644 index 000000000000..a84e91918087 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-cocoapods-linking.rb @@ -0,0 +1,200 @@ +# 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 'cocoapods' +require 'fileutils' +require 'json' +require 'open3' +require 'tmpdir' + +shared_root = File.expand_path('..', __dir__) +helper = File.expand_path('../scripts/cocoapods/kmp.rb', shared_root) +output_root = ENV['RCT_KMP_LINKING_TEST_OUTPUT_DIR'] || Dir.mktmpdir('react-native-kmp-linking-') +FileUtils.mkdir_p(output_root) +results = [] + +# These local pods exercise CocoaPods' real dependency and target-inheritance +# handling without downloading dependencies or compiling a Kotlin framework. +[nil, 'static', 'dynamic', 'mixed'].each do |linkage| + name = linkage || 'static-library' + fixture = File.join(output_root, name) + FileUtils.mkdir_p(fixture) + project = Xcodeproj::Project.new(File.join(fixture, 'Fixture.xcodeproj')) + host = project.new_target(:application, 'Host', :ios, '15.1') + project.new_target(:application, 'CoreOnly', :ios, '15.1') + hosted = project.new_target(:unit_test_bundle, 'HostedTests', :ios, '15.1') + sibling = project.new_target(:unit_test_bundle, 'SiblingHostedTests', :ios, '15.1') + without_metadata = project.new_target(:unit_test_bundle, 'SiblingWithoutMetadata', :ios, '15.1') + standalone = project.new_target(:unit_test_bundle, 'StandaloneTests', :ios, '15.1') + plain_host = project.new_target(:application, 'PlainHost', :ios, '15.1') + separate = project.new_target(:unit_test_bundle, 'TestsWithNonKMPHost', :ios, '15.1') + stale = project.new_target(:unit_test_bundle, 'StaleHostMetadataTests', :ios, '15.1') + mismatched = project.new_target(:unit_test_bundle, 'MismatchedLoaderTests', :ios, '15.1') + sdk_hosted = project.new_target(:unit_test_bundle, 'SDKHostedTests', :ios, '15.1') + unresolved = project.new_target(:unit_test_bundle, 'UnresolvedHostTests', :ios, '15.1') + renamed = project.new_target(:application, 'OriginalName', :ios, '15.1') + renamed.name = 'Renamed Host' + renamed_test = project.new_target(:unit_test_bundle, 'RenamedHostTests', :ios, '15.1') + + # Neither a mere app dependency nor an unrelated KMP app is the test's host. + [standalone, separate, stale].each { |test| test.add_dependency(host) } + sdk_hosted.add_dependency(plain_host) + unresolved.add_dependency(plain_host) + [[hosted, host], [sibling, host], [without_metadata, host], [separate, plain_host], + [stale, plain_host], [mismatched, host], [renamed_test, renamed], [sdk_hosted, host], + [unresolved, host]].each do |test, app| + test.add_dependency(app) + test.build_configurations.each do |config| + config.build_settings['TEST_HOST'] = "$(BUILT_PRODUCTS_DIR)/#{app.name}.app/#{app.name}" + config.build_settings['BUNDLE_LOADER'] = '$(TEST_HOST)' + end + end + [hosted, sibling, stale].each do |test| + (project.root_object.attributes['TargetAttributes'] ||= {})[test.uuid] = { 'TestTargetID' => host.uuid } + end + mismatched.build_configurations.each do |config| + config.build_settings['BUNDLE_LOADER'] = '$(BUILT_PRODUCTS_DIR)/PlainHost.app/PlainHost' + end + sdk_hosted.build_configurations.each do |config| + config.build_settings['TEST_HOST[sdk=iphonesimulator*]'] = '$(BUILT_PRODUCTS_DIR)/PlainHost.app/PlainHost' + end + unresolved.build_configurations.each do |config| + # An unresolved qualifier must not be overwritten by a later matching SDK key. + config.build_settings['TEST_HOST[arch=arm64]'] = '$(BUILT_PRODUCTS_DIR)/PlainHost.app/PlainHost' + config.build_settings['TEST_HOST[sdk=iphonesimulator*]'] = '$(BUILT_PRODUCTS_DIR)/Host.app/Host' + end + renamed.build_configurations.each do |config| + product_config = File.join(fixture, "products-#{config.name}.xcconfig") + File.write(product_config, <<~XCCONFIG) + #include? "Pods/Target Support Files/Pods-Renamed Host/Pods-Renamed Host.#{config.name.downcase}.xcconfig" + APP_BUNDLE_BASE = $(PROJECT_NAME) #{config.name} + XCCONFIG + config.base_configuration_reference = project.new_file(product_config) + config.build_settings['PRODUCT_NAME'] = '$(APP_BUNDLE_BASE) Product' + config.build_settings['PRODUCT_NAME[sdk=iphonesimulator*]'] = '$(APP_BUNDLE_BASE) Simulator Product' + config.build_settings['EXECUTABLE_NAME'] = '$(TARGET_NAME) Binary' + test_config = renamed_test.build_configuration_list[config.name] + test_config.build_settings['TEST_HOST'] = "\"${BUILT_PRODUCTS_DIR}/Fixture #{config.name} Product.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Renamed Host Binary\"" + test_config.build_settings['BUNDLE_LOADER'] = "$(BUILT_PRODUCTS_DIR)/Fixture #{config.name} Product.app/Renamed Host Binary" + test_config.build_settings['TEST_HOST[sdk=iphonesimulator*]'] = "${BUILT_PRODUCTS_DIR}/Fixture #{config.name} Simulator Product.app/Renamed Host Binary" + test_config.build_settings['BUNDLE_LOADER[sdk=iphonesimulator*]'] = '$(TEST_HOST)' + end + project.save + + %w[React-Core React-RCTFabric TestSupport].each do |pod_name| + pod_dir = File.join(fixture, pod_name) + FileUtils.mkdir_p(pod_dir) + File.write(File.join(pod_dir, 'Fixture.m'), "#import \n") + File.write(File.join(pod_dir, "#{pod_name}.podspec"), <<~PODSPEC) + Pod::Spec.new do |s| + s.name = #{pod_name.dump} + s.version = '1.0.0' + s.summary = 'Local CocoaPods linking fixture.' + s.homepage = 'https://reactnative.dev/' + s.license = { :type => 'MIT', :text => 'Test fixture' } + s.author = 'React Native' + s.source = { :git => 'https://example.invalid/fixture.git' } + s.platform = :ios, '15.1' + s.source_files = 'Fixture.m' + #{"s.dependency 'React-KMP'" if pod_name == 'React-Core'} + #{"s.dependency 'React-Core'" if pod_name == 'React-RCTFabric'} + end + PODSPEC + end + + File.write(File.join(fixture, 'helpers.rb'), <<~HELPERS) + require #{helper.dump} + def min_supported_versions + { :ios => '15.1' } + end + HELPERS + File.write(File.join(fixture, 'Podfile'), <<~PODFILE) + require_relative './helpers' + platform :ios, '15.1' + install! 'cocoapods', :warn_for_unused_master_specs_repo => false + project 'Fixture.xcodeproj' + #{"use_frameworks! :linkage => :#{linkage}" if linkage && linkage != 'mixed'} + target 'Host' do + #{"use_frameworks! :linkage => :dynamic" if linkage == 'mixed'} + pod 'React-KMP', :path => #{shared_root.dump} + pod 'React-Core', :path => './React-Core' + pod 'React-RCTFabric', :path => './React-RCTFabric' + target 'HostedTests' do + inherit! :search_paths + pod 'TestSupport', :path => './TestSupport' + end + end + #{['StandaloneTests', 'SiblingHostedTests', 'SiblingWithoutMetadata', 'Renamed Host', 'RenamedHostTests', + 'TestsWithNonKMPHost', 'StaleHostMetadataTests', 'MismatchedLoaderTests', 'SDKHostedTests', 'UnresolvedHostTests'].map do |target| + <<~TARGET + target #{target.dump} do + #{'use_frameworks! :linkage => :static' if linkage == 'mixed'} + pod 'React-KMP', :path => #{shared_root.dump} + pod 'React-Core', :path => './React-Core' + pod 'React-RCTFabric', :path => './React-RCTFabric' + end + TARGET + end.join} + target 'CoreOnly' do + #{'use_frameworks! :linkage => :static' if linkage == 'mixed'} + pod 'React-KMP', :path => #{shared_root.dump} + pod 'React-Core', :path => './React-Core' + end + target 'PlainHost' do + pod 'TestSupport', :path => './TestSupport' + end + post_install do |installer| + installer.aggregate_targets.each do |aggregate| + aggregate.xcconfigs.each_key do |configuration| + %w[iphoneos iphonesimulator].each do |sdk| + target = aggregate.user_targets.first.name + expected = %w[HostedTests SiblingHostedTests SiblingWithoutMetadata RenamedHostTests].include?(target) || (target == 'SDKHostedTests' && sdk == 'iphoneos') + actual = ReactNativeKMPUtils.test_host_links_kmp?(aggregate, configuration, installer.aggregate_targets, sdk) + raise "Wrong KMP host detection for \#{aggregate.label}/\#{configuration}/\#{sdk}: \#{actual}" unless actual == expected + end + end + end + ReactNativeKMPUtils.configure_aggregate_xcconfig(installer) + ReactNativeKMPUtils.configure_aggregate_xcconfig(installer) + end + PODFILE + + output, status = Open3.capture2e( + { 'COCOAPODS_DISABLE_STATS' => 'true', 'COCOAPODS_NO_BUNDLER' => 'true' }, + RbConfig.ruby, Gem.bin_path('cocoapods', 'pod'), 'install', + "--project-directory=#{fixture}", '--no-repo-update' + ) + File.write(File.join(fixture, 'pod-install.log'), output) + raise "CocoaPods #{name} fixture failed: #{output}" unless status.success? + + ['Host', 'HostedTests', 'SiblingHostedTests', 'SiblingWithoutMetadata', 'Renamed Host', 'RenamedHostTests', + 'CoreOnly', 'StandaloneTests', 'TestsWithNonKMPHost', 'StaleHostMetadataTests', 'MismatchedLoaderTests', 'SDKHostedTests', 'UnresolvedHostTests', 'PlainHost'].each do |target| + %w[debug release].each do |configuration| + config_path = File.join(fixture, 'Pods', 'Target Support Files', "Pods-#{target}", "Pods-#{target}.#{configuration}.xcconfig") + config = Xcodeproj::Config.new(Pathname.new(config_path)).attributes + dynamic = linkage == 'dynamic' || (linkage == 'mixed' && target == 'Host') + counts = {} + %w[iphoneos iphonesimulator].each do |sdk| + hosted_kmp = %w[HostedTests SiblingHostedTests SiblingWithoutMetadata RenamedHostTests].include?(target) || (target == 'SDKHostedTests' && sdk == 'iphoneos') + expected = target == 'PlainHost' || hosted_kmp || dynamic ? 0 : 1 + flags = config["OTHER_LDFLAGS[sdk=#{sdk}*]"].to_s + count = flags.scan('-framework ReactNativeShared').length + raise "#{name}/#{target}/#{configuration}/#{sdk}: expected #{expected} Kotlin links, got #{count}" unless count == expected + search_paths = config["FRAMEWORK_SEARCH_PATHS[sdk=#{sdk}*]"].to_s + if target != 'PlainHost' && !search_paths.include?('ReactNativeSharedKMP') + raise "Missing inherited framework search path for #{name}/#{target}" + end + counts[sdk] = count + end + raise "Unconditional Kotlin link leaks into Catalyst for #{name}/#{target}" if config['OTHER_LDFLAGS'].to_s.include?('ReactNativeShared') + results << { :linkage => name, :target => target, :configuration => configuration, + :kotlin_links_per_ios_sdk => counts } + end + end +end + +File.write(File.join(output_root, 'results.json'), JSON.pretty_generate(results) + "\n") +puts "Passed #{results.length} CocoaPods configurations across static libraries, static frameworks, dynamic frameworks, and mixed per-target linkage." +puts "Generated fixture configs and logs: #{output_root}" diff --git a/packages/react-native/ReactShared/scripts/test-kotlin-coexistence.py b/packages/react-native/ReactShared/scripts/test-kotlin-coexistence.py new file mode 100644 index 000000000000..71e740b20676 --- /dev/null +++ b/packages/react-native/ReactShared/scripts/test-kotlin-coexistence.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +# 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. + +"""Check two independent Kotlin/Native frameworks built with the same compiler. + +Tests all four combinations of static and dynamic runtime ownership. No +Kotlin classes are cast between frameworks. This does not promise compatibility +with arbitrary third-party compiler versions or exported Kotlin dependencies. +""" + +import argparse +import json +import os +import pathlib +import platform +import re +import subprocess + + +def run(command, log): + result = subprocess.run([str(item) for item in command], capture_output=True, text=True) + log.write_text(result.stdout + result.stderr) + if result.returncode: + raise RuntimeError(f"Command failed with exit {result.returncode}; inspect {log}") + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-only", action="store_true", help="Compile and inspect linkage without simulator execution.") + parser.add_argument("--output", type=pathlib.Path) + args = parser.parse_args() + shared = pathlib.Path(__file__).resolve().parent.parent + output = (args.output or shared / "build/kotlin-coexistence").resolve() + output.mkdir(parents=True, exist_ok=True) + fixture = shared / "tests/coexistence" + version_matches = re.findall(r'kotlin\("multiplatform"\) version "([^"]+)"', (shared / "build.gradle.kts").read_text()) + if len(version_matches) != 1: + raise RuntimeError("Cannot identify the shared module's Kotlin compiler version.") + version = version_matches[0] + architecture = platform.machine() + host = "macos-aarch64" if architecture == "arm64" else "macos-x86_64" + target = "ios_simulator_arm64" if architecture == "arm64" else "ios_x64" + konan = pathlib.Path(os.environ.get("KONAN_DATA_DIR", pathlib.Path.home() / ".konan")) + compiler = pathlib.Path(os.environ.get("RCT_KMP_KONANC", konan / f"kotlin-native-prebuilt-{host}-{version}/bin/konanc")) + if not compiler.is_file(): + raise RuntimeError("Build ReactShared once to install its compiler, or set RCT_KMP_KONANC to the matching konanc.") + compiler_version = run([compiler, "-version"], output / "compiler-version.log") + if not re.search(rf'(?, + epsilon: Double, + useDoublePrecision: Boolean = false, + ): List { + if (stops.isEmpty()) { + return emptyList() + } + + val math = Arithmetic(useDoublePrecision) + val positions = arrayOfNulls(stops.size) + var maxPositionSoFar = math.round(stops[0].position ?: 0.0) + var hasNullPositions = false + + // Set default endpoint positions and prevent specified positions from moving backwards. + for (i in stops.indices) { + val position = + stops[i].position?.let(math::round) + ?: when (i) { + 0 -> 0.0 + stops.lastIndex -> 1.0 + else -> null + } + if (position != null) { + val fixedPosition = math.max(position, maxPositionSoFar) + positions[i] = fixedPosition + maxPositionSoFar = fixedPosition + } else { + hasNullPositions = true + } + } + + // Evenly distribute each run of unpositioned stops between its own surrounding positions. + if (hasNullPositions) { + var lastDefinedIndex = 0 + for (i in 1 until positions.size) { + val endPosition = positions[i] ?: continue + val startPosition = checkNotNull(positions[lastDefinedIndex]) + val unpositionedStops = i - lastDefinedIndex - 1 + if (unpositionedStops > 0) { + val increment = + math.divide( + math.subtract(endPosition, startPosition), + (unpositionedStops + 1).toDouble(), + ) + for (j in 1..unpositionedStops) { + positions[lastDefinedIndex + j] = + math.add(startPosition, math.multiply(increment, j.toDouble())) + } + } + lastDefinedIndex = i + } + } + + val resolved = + stops.indices + .map { i -> ResolvedGradientStop(checkNotNull(positions[i]), i, i, 0.0) } + .toMutableList() + var indexOffset = 0 + for (i in 1 until stops.lastIndex) { + if (stops[i].hasColor) { + continue + } + + val index = i + indexOffset + val left = resolved[index - 1] + val right = resolved[index + 1] + val position = resolved[index].position + val leftDistance = math.subtract(position, left.position) + val rightDistance = math.subtract(right.position, position) + val totalDistance = math.subtract(right.position, left.position) + + if (math.equal(leftDistance, rightDistance, epsilon)) { + resolved.removeAt(index) + --indexOffset + continue + } + if (math.equal(leftDistance, 0.0, epsilon)) { + resolved[index] = right.copy(position = position) + continue + } + if (math.equal(rightDistance, 0.0, epsilon)) { + resolved[index] = left.copy(position = position) + continue + } + + // Use the same nine sample positions as the platform implementations, derived from Blink. + val samples = ArrayList(9) + if (leftDistance > rightDistance) { + for (y in 0..6) { + samples.add(math.sample(left.position, leftDistance, (7f + y) / 13f)) + } + samples.add(math.sample(position, rightDistance, 1f / 3f)) + samples.add(math.sample(position, rightDistance, 2f / 3f)) + } else { + samples.add(math.sample(left.position, leftDistance, 1f / 3f)) + samples.add(math.sample(left.position, leftDistance, 2f / 3f)) + for (y in 0..6) { + samples.add(math.sample(position, rightDistance, y / 13f)) + } + } + + val hintRelativeOffset = math.divide(leftDistance, totalDistance) + val hintLogarithm = math.log(hintRelativeOffset) + val logRatio = ln(0.5) / hintLogarithm + val intermediateStops = + samples.map { sample -> + val pointRelativeOffset = + math.divide(math.subtract(sample, left.position), totalDistance) + ResolvedGradientStop( + sample, + left.leftColorIndex, + right.rightColorIndex, + pointRelativeOffset.pow(logRatio), + ) + } + resolved.removeAt(index) + resolved.addAll(index, intermediateStops) + indexOffset += 8 + } + return resolved + } + + /** Keeps every platform operation at its original precision without duplicating the algorithm. */ + private class Arithmetic(private val doublePrecision: Boolean) { + fun round(value: Double): Double = if (doublePrecision) value else value.toFloat().toDouble() + + fun add(first: Double, second: Double): Double = + if (doublePrecision) first + second else (first.toFloat() + second.toFloat()).toDouble() + + fun subtract(first: Double, second: Double): Double = + if (doublePrecision) first - second else (first.toFloat() - second.toFloat()).toDouble() + + fun multiply(first: Double, second: Double): Double = + if (doublePrecision) first * second else (first.toFloat() * second.toFloat()).toDouble() + + fun divide(first: Double, second: Double): Double = + if (doublePrecision) first / second else (first.toFloat() / second.toFloat()).toDouble() + + fun max(first: Double, second: Double): Double = + if (doublePrecision) { + // Match std::max, including its behavior for NaN and signed zero. + if (first < second) second else first + } else { + maxOf(first.toFloat(), second.toFloat()).toDouble() + } + + fun log(value: Double): Double = + if (doublePrecision) ln(value) else ln(value.toFloat()).toDouble() + + fun equal(first: Double, second: Double, epsilon: Double): Boolean = + if (first.isNaN() || second.isNaN()) { + first.isNaN() && second.isNaN() + } else { + abs(subtract(second, first)) < epsilon + } + + fun sample(start: Double, distance: Double, fraction: Float): Double = + // Both native implementations originally compute these sample fractions as Float. + add(start, multiply(distance, fraction.toDouble())) + } +} diff --git a/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/MultipartFraming.kt b/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/MultipartFraming.kt new file mode 100644 index 000000000000..70ec180d0390 --- /dev/null +++ b/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/MultipartFraming.kt @@ -0,0 +1,79 @@ +/* + * 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.shared + +/** A completed region in the caller's current buffer. The first region is the preamble. */ +public class MultipartChunk( + public val start: Long, + public val end: Long, + public val isPart: Boolean, + public val isLast: Boolean, +) + +/** + * Incremental multipart framing, independent of stream and buffer ownership. + * + * The caller searches its native buffer for delimiters starting at [searchStart], then passes their + * indices to [nextChunk]. After a chunk, it may discard bytes before the delimiter and advance + * bufferOffset by the same amount. Offsets let both sliding and retained buffers use the same state + * machine without copying body bytes into Kotlin. + */ +public class MultipartFraming( + private val delimiterLength: Int, + private val closeDelimiterLength: Int, +) { + private var chunkStart: Long = 0 + private var bytesSeen: Long = 0 + private var hasBoundary: Boolean = false + + /** Retain enough overlap to find a delimiter split between two reads. */ + public fun searchStart(bufferOffset: Long): Long = + maxOf(bytesSeen - closeDelimiterLength, chunkStart) - bufferOffset + + /** Start of the current part in the caller's buffer, including its headers. */ + public fun partStart(bufferOffset: Long): Long = chunkStart - bufferOffset + + /** + * Returns a completed region, or null when another read is needed. A negative index means that + * delimiter was not found. Normal delimiters take precedence, matching both adapters. + */ + public fun nextChunk( + bufferLength: Long, + bufferOffset: Long, + delimiterIndex: Long, + closeDelimiterIndex: Long, + ): MultipartChunk? { + val isClosing = delimiterIndex < 0 + val end = if (isClosing) closeDelimiterIndex else delimiterIndex + if (end < 0) { + bytesSeen = bufferOffset + bufferLength + return null + } + + val chunk = MultipartChunk(chunkStart - bufferOffset, end, hasBoundary, isClosing) + if (!isClosing) { + hasBoundary = true + chunkStart = bufferOffset + end + delimiterLength + bytesSeen = chunkStart + } + return chunk + } +} + +/** An untrimmed header. Native adapters retain their whitespace and map-key policies. */ +public class MultipartHeader(public val name: String, public val value: String) + +public object MultipartHeaders { + /** Split CRLF-delimited headers at the first colon, ignoring lines without a separator. */ + public fun parse(text: String): List = + text.split("\r\n").mapNotNull { line -> + val separator = line.indexOf(':') + if (separator < 0) null + else MultipartHeader(line.substring(0, separator), line.substring(separator + 1)) + } +} diff --git a/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/ScrollSnapOffsets.kt b/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/ScrollSnapOffsets.kt new file mode 100644 index 000000000000..753232d99f3d --- /dev/null +++ b/packages/react-native/ReactShared/src/commonMain/kotlin/com/facebook/react/shared/ScrollSnapOffsets.kt @@ -0,0 +1,131 @@ +/* + * 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.shared + +import kotlin.math.abs + +/** Why a fling selected an offset; platforms retain their own velocity adjustments. */ +public enum class ScrollSnapDirection { + NONE, + FORWARD, + BACKWARD, +} + +/** The bounded target and the original snap point used by native fling physics. */ +public class ScrollSnapResult +internal constructor( + public val targetOffset: Double, + public val selectedOffset: Double, + public val direction: ScrollSnapDirection, +) + +/** + * Selects explicit scroll snap offsets in platform-resolved coordinates. + * + * The DoubleArray constructor copies its input for an Apple property snapshot. Android uses + * [fromIntegerOffsets] to retain its existing native list and 32-bit pixel arithmetic. Inputs are + * never sorted: the first and last elements define free-scrolling boundaries. Callers retain + * density conversion, RTL coordinates, target prediction and interval snapping. + */ +public class ScrollSnapOffsets +private constructor( + private val fractionalOffsets: DoubleArray?, + private val integerOffsets: List?, +) { + public constructor(offsets: DoubleArray) : this(offsets.copyOf(), null) + + public companion object { + /** + * Retains the caller's list so native mutations remain visible on the next fling. The list must + * be nonempty when resolving; platforms keep their existing empty-list fallback policy. + */ + public fun fromIntegerOffsets(offsets: List): ScrollSnapOffsets = + ScrollSnapOffsets(null, offsets) + } + + private fun offsetAt(index: Int): Double = + if (integerOffsets != null) integerOffsets[index].toDouble() + else checkNotNull(fractionalOffsets)[index] + + private fun distance(left: Double, right: Double): Double = + if (integerOffsets != null) (left.toInt() - right.toInt()).toDouble() else left - right + + /** + * Coordinates must be finite and [maximumOffset] nonnegative. An empty DoubleArray leaves the + * predicted target unchanged apart from bounding it. A midpoint tie selects the larger offset. + * [ScrollSnapResult.selectedOffset] precedes bounding for Android's native velocity adjustment. + */ + public fun resolve( + currentOffset: Double, + targetOffset: Double, + maximumOffset: Double, + velocity: Double, + snapToStart: Boolean, + snapToEnd: Boolean, + ): ScrollSnapResult { + val count = integerOffsets?.size ?: checkNotNull(fractionalOffsets).size + if (integerOffsets == null && count == 0) { + return ScrollSnapResult( + targetOffset.coerceIn(0.0, maximumOffset), + targetOffset, + ScrollSnapDirection.NONE, + ) + } + val firstOffset = offsetAt(0) + val lastOffset = offsetAt(count - 1) + var smallerOffset = 0.0 + var largerOffset = maximumOffset + for (i in 0 until count) { + val offset = offsetAt(i) + if ( + offset <= targetOffset && + distance(targetOffset, offset) < distance(targetOffset, smallerOffset) + ) { + smallerOffset = offset + } + if ( + offset >= targetOffset && + distance(offset, targetOffset) < distance(largerOffset, targetOffset) + ) { + largerOffset = offset + } + } + + var selectedOffset = targetOffset + var direction = ScrollSnapDirection.NONE + if (!snapToEnd && targetOffset >= lastOffset) { + if (currentOffset < lastOffset) { + selectedOffset = lastOffset + } + } else if (!snapToStart && targetOffset <= firstOffset) { + if (currentOffset > firstOffset) { + selectedOffset = firstOffset + } + } else if (velocity > 0) { + selectedOffset = largerOffset + direction = ScrollSnapDirection.FORWARD + } else if (velocity < 0) { + selectedOffset = smallerOffset + direction = ScrollSnapDirection.BACKWARD + } else { + val preferSmaller = + if (integerOffsets != null) { + abs(targetOffset.toInt() - smallerOffset.toInt()) < + abs(largerOffset.toInt() - targetOffset.toInt()) + } else { + targetOffset - smallerOffset < largerOffset - targetOffset + } + selectedOffset = if (preferSmaller) smallerOffset else largerOffset + } + return ScrollSnapResult( + targetOffset = selectedOffset.coerceIn(0.0, maximumOffset), + selectedOffset = selectedOffset, + direction = direction, + ) + } +} diff --git a/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/GradientStopsTest.kt b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/GradientStopsTest.kt new file mode 100644 index 000000000000..e8b89637630f --- /dev/null +++ b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/GradientStopsTest.kt @@ -0,0 +1,262 @@ +/* + * 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.shared + +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class GradientStopsTest { + @Test + fun emptyGradientHasNoStops() { + assertEquals(emptyList(), GradientStops.resolve(emptyList(), ANDROID_EPSILON)) + } + + @Test + fun singleColorDefaultsToStart() { + assertEquals(listOf(original(0f, 0)), resolve(colors(null))) + } + + @Test + fun positionedColorsKeepTheirInputReferences() { + assertEquals( + listOf(original(0f, 0), original(.42f, 1)), + resolve(colors(0f, .42f)), + ) + } + + @Test + fun missingEndpointsDefaultToZeroAndOne() { + assertEquals( + listOf(original(0f, 0), original(.3f, 1), original(1f, 2)), + resolve(colors(null, .3f, null)), + ) + } + + @Test + fun allUnpositionedColorsAreEvenlySpaced() { + assertEquals( + listOf(original(0f, 0), original(1f / 3f, 1), original(2f / 3f, 2), original(1f, 3)), + resolve(colors(null, null, null, null)), + ) + } + + @Test + fun decreasingPositionsUseTheLargestPreviousPosition() { + assertEquals( + listOf(0f, .3f, .3f, .6f, .6f), + resolve(colors(null, .3f, .2f, .6f, .5f)).map { it.position.toFloat() }, + ) + } + + @Test + fun positionsOutsideTheGradientArePreserved() { + assertEquals( + listOf(-1f, 0f, 1f, 2f), + resolve(colors(-1f, null, 1f, 2f)).map { it.position.toFloat() }, + ) + assertEquals(listOf(2f, 2f), resolve(colors(2f, null)).map { it.position.toFloat() }) + } + + @Test + fun eachUnpositionedRunUsesItsOwnAdjacentStops() { + assertEquals( + listOf(0f, .2f, .5f, .8f, .9f, 1f), + resolve(colors(0f, .2f, null, .8f, null, 1f)).map { it.position.toFloat() }, + ) + } + + @Test + fun centeredHintDoesNotAddAnInterpolationStop() { + assertEquals( + listOf(original(0f, 0), original(1f, 2)), + resolve(listOf(color(0f), hint(.5f), color(1f))), + ) + } + + @Test + fun hintInCollapsedIntervalIsRemovedBeforeEndpointReplacement() { + assertEquals( + listOf(original(.3f, 0), original(.3f, 2)), + resolve(listOf(color(.3f), hint(.2f), color(.1f))), + ) + } + + @Test + fun hintAtLeftEndpointReusesRightColor() { + assertEquals( + listOf(original(0f, 0), original(0f, 2), original(1f, 2)), + resolve(listOf(color(0f), hint(0f), color(1f))), + ) + } + + @Test + fun hintAtRightEndpointReusesLeftColor() { + assertEquals( + listOf(original(0f, 0), original(1f, 0), original(1f, 2)), + resolve(listOf(color(0f), hint(1f), color(1f))), + ) + } + + @Test + fun platformTolerancePreservesNearCenteredHintBehavior() { + val inputs = listOf(color(0f), hint(.502f), color(1f)) + assertEquals(11, resolve(inputs).size) + assertEquals(2, GradientStops.resolve(inputs, APPLE_EPSILON).size) + } + + @Test + fun platformTolerancePreservesNearEndpointHintBehavior() { + val inputs = listOf(color(0f), hint(.002f), color(1f)) + assertEquals(11, resolve(inputs).size) + assertEquals( + listOf(original(0f, 0), original(.002f, 2), original(1f, 2)), + GradientStops.resolve(inputs, APPLE_EPSILON), + ) + } + + @Test + fun leftHintUsesNineSamplesAndTheExpectedPowerCurve() { + val resolved = resolve(listOf(color(0f), hint(.25f), color(1f))) + assertEquals(11, resolved.size) + assertEquals(original(0f, 0), resolved.first()) + assertEquals(original(1f, 2), resolved.last()) + val samples = resolved.subList(1, 10) + val expectedPositions = + listOf( + .083333336f, + .16666667f, + .25f, + .30769232f, + .36538464f, + .42307693f, + .48076925f, + .53846157f, + .59615386f, + ) + assertEquals(expectedPositions, samples.map { it.position.toFloat() }) + for (sample in samples) { + assertEquals(0, sample.leftColorIndex) + assertEquals(2, sample.rightColorIndex) + // A quarter-position hint has exponent 1/2; Float logarithm rounding is retained. + assertEquals(sqrt(sample.position.toDouble()), sample.weight, absoluteTolerance = 1e-7) + } + } + + @Test + fun rightHintUsesNineSamplesAndEqualMixAtTheHint() { + val resolved = resolve(listOf(color(0f), hint(.75f), color(1f))) + val samples = resolved.subList(1, 10) + assertEquals( + listOf( + .40384617f, + .4615385f, + .5192308f, + .5769231f, + .6346154f, + .6923077f, + .75f, + .8333333f, + .9166667f, + ), + samples.map { it.position.toFloat() }, + ) + assertEquals(.5, samples[6].weight, absoluteTolerance = 1e-7) + assertTrue(samples.all { it.leftColorIndex == 0 && it.rightColorIndex == 2 }) + assertTrue(samples.all { it.weight.isFinite() && it.weight in 0.0..1.0 }) + assertTrue(samples.zipWithNext().all { (left, right) -> left.weight < right.weight }) + } + + @Test + fun appleLogarithmKeepsDoublePrecision() { + val inputs = listOf(color(0f), hint(.25f), color(1f)) + val apple = GradientStops.resolve(inputs, APPLE_EPSILON, useDoublePrecision = true) + val android = resolve(inputs) + + assertEquals(.5, apple[3].weight) + assertTrue(android[3].weight != apple[3].weight) + for (sample in apple.subList(1, 10)) { + assertEquals(sqrt(sample.position.toDouble()), sample.weight, absoluteTolerance = 1e-15) + } + } + + @Test + fun appleUnpositionedStopsKeepDoublePrecision() { + val inputs = colors(null, null, null, null) + val apple = GradientStops.resolve(inputs, APPLE_EPSILON, useDoublePrecision = true) + + assertEquals(listOf(0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0), apple.map { it.position }) + assertTrue(apple[1].position != resolve(inputs)[1].position) + } + + @Test + fun applePointDivisionDoesNotRoundAcrossTheCenteredHintThreshold() { + // Native point positions use CGFloat division: 100.5 points / 200 points. + // Rounding that position to Float changes whether the hint falls inside Apple's tolerance. + val inputs = + listOf( + GradientStopInput(0.0, true), + GradientStopInput(100.5 / 200.0, false), + GradientStopInput(1.0, true), + ) + + assertEquals(11, GradientStops.resolve(inputs, APPLE_EPSILON, useDoublePrecision = true).size) + assertEquals(2, GradientStops.resolve(inputs, APPLE_EPSILON).size) + } + + @Test + fun appleSamplesRetainDoublePositionsWithNativeFloatFractions() { + val inputs = listOf(color(0f), hint(.25f), color(1f)) + val apple = GradientStops.resolve(inputs, APPLE_EPSILON, useDoublePrecision = true) + + assertEquals(.25 * (1f / 3f).toDouble(), apple[1].position) + assertEquals(.25 + .75 * (6f / 13f).toDouble(), apple[9].position) + assertTrue(apple[9].position != resolve(inputs)[9].position) + } + + @Test + fun multipleHintsReferenceOriginalColorsAfterInsertionsAndRemoval() { + val inputs = + listOf(color(0f), hint(.1f), color(.5f), hint(.6f), color(.7f), hint(.9f), color(1f)) + val resolved = resolve(inputs) + assertEquals(22, resolved.size) + assertEquals(original(.5f, 2), resolved[10]) + assertEquals(original(.7f, 4), resolved[11]) + assertEquals(original(1f, 6), resolved[21]) + assertTrue(resolved.subList(1, 10).all { it.leftColorIndex == 0 && it.rightColorIndex == 2 }) + assertTrue(resolved.subList(12, 21).all { it.leftColorIndex == 4 && it.rightColorIndex == 6 }) + } + + @Test + fun repeatedResolutionDoesNotChangeTheInputs() { + val inputs = listOf(color(null), hint(.2f), color(null), color(.8f), color(null)) + val snapshot = inputs.toList() + assertEquals(resolve(inputs), resolve(inputs)) + assertEquals(snapshot, inputs) + } + + private fun resolve(stops: List): List = + GradientStops.resolve(stops, ANDROID_EPSILON) + + private fun colors(vararg positions: Float?): List = positions.map(::color) + + private fun color(position: Float?): GradientStopInput = + GradientStopInput(position?.toDouble(), true) + + private fun hint(position: Float): GradientStopInput = + GradientStopInput(position.toDouble(), false) + + private fun original(position: Float, colorIndex: Int): ResolvedGradientStop = + ResolvedGradientStop(position.toDouble(), colorIndex, colorIndex, 0.0) + + private companion object { + val ANDROID_EPSILON = .00001f.toDouble() + val APPLE_EPSILON = .005f.toDouble() + } +} diff --git a/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/MultipartFramingTest.kt b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/MultipartFramingTest.kt new file mode 100644 index 000000000000..9e67686648de --- /dev/null +++ b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/MultipartFramingTest.kt @@ -0,0 +1,139 @@ +/* + * 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.shared + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class MultipartFramingTest { + @Test + fun framingIsIndependentOfReadBoundariesAndBufferRetention() { + val input = + "preamble\r\n--sample\r\nA: b\r\n\r\none\r\n--sample\r\ntwo\r\n--sample--\r\nepilogue" + for (readSize in 1..input.length) { + for (discard in listOf(false, true)) { + assertEquals( + listOf("A: b\r\n\r\none", "two") to true, + parse(input, "sample", readSize, discard), + "readSize=$readSize discard=$discard", + ) + } + } + } + + @Test + fun missingDelimiterDoesNotComplete() { + assertEquals(emptyList() to false, parse("no delimiter", "sample", 1, true)) + } + + @Test + fun missingClosingDelimiterDoesNotComplete() { + assertEquals(emptyList() to false, parse("\r\n--sample\r\nbody", "sample", 1, false)) + } + + @Test + fun incompleteFinalPartKeepsPreviouslyCompletedParts() { + val input = "\r\n--s\r\nfirst\r\n--s\r\nincomplete" + assertEquals(listOf("first") to false, parse(input, "s", 2, true)) + } + + @Test + fun closingDelimiterWithoutPartsOnlyDiscardsPreamble() { + assertEquals(emptyList() to true, parse("preamble\r\n--s--\r\n", "s", 1, false)) + } + + @Test + fun nearMatchesRemainInTheBody() { + val body = "binary\u0000\r\n--samplX\r\n\r\n--sample-\r\n" + val input = "\r\n--sample\r\n$body\r\n--sample--\r\n" + for (readSize in 1..input.length) { + assertEquals(listOf(body) to true, parse(input, "sample", readSize, true)) + } + } + + @Test + fun overlapStartsAtThePartUntilMoreBytesArrive() { + val framing = MultipartFraming(7, 9) + assertEquals(0L, framing.searchStart(0)) + val preamble = framing.nextChunk(7, 0, 0, -1)!! + assertFalse(preamble.isPart) + assertEquals(7L, framing.partStart(0)) + assertEquals(7L, framing.searchStart(0)) + assertNull(framing.nextChunk(30, 0, -1, -1)) + assertEquals(21L, framing.searchStart(0)) + } + + @Test + fun offsetsRemainExactBeyondIntRange() { + val framing = MultipartFraming(7, 9) + val offset = Int.MAX_VALUE.toLong() + 100 + framing.nextChunk(offset + 7, 0, offset, -1) + assertEquals(7L, framing.partStart(offset)) + assertNull(framing.nextChunk(30, offset, -1, -1)) + assertEquals(21L, framing.searchStart(offset)) + val part = framing.nextChunk(40, offset, -1, 31)!! + assertEquals(7L, part.start) + assertEquals(31L, part.end) + assertTrue(part.isPart) + assertTrue(part.isLast) + } + + @Test + fun normalDelimiterRetainsExistingSearchPrecedence() { + val framing = MultipartFraming(7, 9) + assertFalse(framing.nextChunk(40, 0, 20, 5)!!.isLast) + } + + @Test + fun headersRetainNativeWhitespaceCaseAndDuplicatePolicies() { + val headers = + MultipartHeaders.parse( + " Content-Type : text/plain:extra \r\ninvalid\r\nx:1\r\nX:2\r\n:empty\r\n" + ) + assertEquals(listOf(" Content-Type ", "x", "X", ""), headers.map { it.name }) + assertEquals(listOf(" text/plain:extra ", "1", "2", "empty"), headers.map { it.value }) + assertTrue(MultipartHeaders.parse("").isEmpty()) + } + + private fun parse( + input: String, + boundary: String, + readSize: Int, + discard: Boolean, + ): Pair, Boolean> { + val delimiter = "\r\n--$boundary\r\n" + val closeDelimiter = "\r\n--$boundary--\r\n" + val framing = MultipartFraming(delimiter.length, closeDelimiter.length) + var buffer = "" + var offset = 0L + var read = 0 + val parts = mutableListOf() + while (true) { + val start = framing.searchStart(offset).toInt() + val normal = buffer.indexOf(delimiter, start) + val close = if (normal < 0) buffer.indexOf(closeDelimiter, start) else -1 + val chunk = framing.nextChunk(buffer.length.toLong(), offset, normal.toLong(), close.toLong()) + if (chunk == null) { + if (read == input.length) return parts to false + val end = minOf(input.length, read + readSize) + buffer += input.substring(read, end) + read = end + } else { + if (chunk.isPart) parts += buffer.substring(chunk.start.toInt(), chunk.end.toInt()) + if (chunk.isLast) return parts to true + if (discard) { + buffer = buffer.substring(chunk.end.toInt()) + offset += chunk.end + } + } + } + } +} diff --git a/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/ScrollSnapOffsetsTest.kt b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/ScrollSnapOffsetsTest.kt new file mode 100644 index 000000000000..e8b75c435a89 --- /dev/null +++ b/packages/react-native/ReactShared/src/commonTest/kotlin/com/facebook/react/shared/ScrollSnapOffsetsTest.kt @@ -0,0 +1,83 @@ +/* + * 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.shared + +import kotlin.test.Test +import kotlin.test.assertEquals + +class ScrollSnapOffsetsTest { + private val offsets = ScrollSnapOffsets(doubleArrayOf(20.0, 60.0, 100.0)) + + @Test + fun directionAndMidpointTies() { + assertEquals(20.0, offsets.resolve(20.0, 39.0, 120.0, 0.0, true, true).targetOffset) + assertEquals(60.0, offsets.resolve(20.0, 40.0, 120.0, 0.0, true, true).targetOffset) + val forward = offsets.resolve(20.0, 21.0, 120.0, 0.01, true, true) + assertEquals(60.0, forward.targetOffset) + assertEquals(ScrollSnapDirection.FORWARD, forward.direction) + val backward = offsets.resolve(100.0, 99.0, 120.0, -0.01, true, true) + assertEquals(60.0, backward.targetOffset) + assertEquals(ScrollSnapDirection.BACKWARD, backward.direction) + assertEquals(60.0, offsets.resolve(20.0, 60.0, 120.0, 1.0, true, true).targetOffset) + } + + @Test + fun disabledBoundariesAllowFreeScrollingOnlyAfterCrossing() { + assertEquals(20.0, offsets.resolve(30.0, 10.0, 120.0, -1.0, false, false).targetOffset) + val freeStart = offsets.resolve(20.0, 10.0, 120.0, -1.0, false, false) + assertEquals(10.0, freeStart.targetOffset) + assertEquals(ScrollSnapDirection.NONE, freeStart.direction) + assertEquals(100.0, offsets.resolve(90.0, 110.0, 120.0, 1.0, false, false).targetOffset) + val freeEnd = offsets.resolve(100.0, 110.0, 120.0, 1.0, false, false) + assertEquals(110.0, freeEnd.targetOffset) + assertEquals(ScrollSnapDirection.NONE, freeEnd.direction) + } + + @Test + fun boundingDoesNotChangeThePointUsedForVelocityAdjustment() { + val result = + ScrollSnapOffsets(doubleArrayOf(20.0, 140.0)).resolve(0.0, 150.0, 120.0, -1.0, true, true) + assertEquals(120.0, result.targetOffset) + assertEquals(140.0, result.selectedOffset) + assertEquals(ScrollSnapDirection.BACKWARD, result.direction) + assertEquals(0.0, offsets.resolve(0.0, -50.0, 0.0, 0.0, true, true).targetOffset) + } + + @Test + fun fractionalDuplicateAndEmptyOffsets() { + val fractional = ScrollSnapOffsets(doubleArrayOf(0.25, 0.25, 1.75)) + assertEquals(1.75, fractional.resolve(0.0, 1.0, 2.0, 0.0, true, true).targetOffset) + assertEquals(0.25, fractional.resolve(0.0, 0.25, 2.0, -1.0, true, true).targetOffset) + assertEquals( + 1.0, + ScrollSnapOffsets(doubleArrayOf()).resolve(0.0, 1.0, 2.0, 1.0, true, true).targetOffset, + ) + } + + @Test + fun propertySnapshotPreservesOrderAndIgnoresLaterInputMutation() { + val input = doubleArrayOf(100.0, 20.0, 60.0) + val snapshot = ScrollSnapOffsets(input) + input[0] = 0.0 + // The first property value is 100, not the sorted minimum of 20. + assertEquals(100.0, snapshot.resolve(110.0, 50.0, 120.0, 0.0, false, true).targetOffset) + assertEquals(60.0, snapshot.resolve(0.0, 50.0, 120.0, 0.0, true, true).targetOffset) + } + + @Test + fun integerListsRetainNativeMutationsAndWrappingArithmetic() { + val input = mutableListOf(20, 60, 100) + val retained = ScrollSnapOffsets.fromIntegerOffsets(input) + input[1] = 90 + assertEquals(90.0, retained.resolve(0.0, 40.0, 300.0, 1.0, true, true).targetOffset) + input.add(50) + assertEquals(50.0, retained.resolve(0.0, 40.0, 300.0, 1.0, true, true).targetOffset) + val extreme = ScrollSnapOffsets.fromIntegerOffsets(listOf(Int.MIN_VALUE, 20, 100)) + assertEquals(300.0, extreme.resolve(0.0, 150.0, 300.0, 0.0, true, true).targetOffset) + } +} diff --git a/packages/react-native/ReactShared/tests/AndroidMultipartBenchmark.kt b/packages/react-native/ReactShared/tests/AndroidMultipartBenchmark.kt new file mode 100644 index 000000000000..3c2f64003645 --- /dev/null +++ b/packages/react-native/ReactShared/tests/AndroidMultipartBenchmark.kt @@ -0,0 +1,125 @@ +/* + * 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 java.lang.management.ManagementFactory +import okio.Buffer +import okio.BufferedSource +import okio.ByteString +import okio.ByteString.Companion.toByteString + +// Compiled with the actual adapter and the explicitly selected, renamed Git baseline. +private fun read(native: Boolean, source: BufferedSource, capture: Boolean): Any { + var bytes = 0L + var calls = 0 + var result: ByteString? = null + fun complete(body: BufferedSource, last: Boolean) { + check(last) + calls++ + if (capture) { + result = body.readByteString() + } else { + val scratch = Buffer() + while (body.read(scratch, 8192) != -1L) { + bytes += scratch.size + scratch.clear() + } + } + } + val success = + if (native) { + MultipartStreamReaderBaseline(source, "sample") + .readAllParts( + object : MultipartStreamReaderBaseline.ChunkListener { + override fun onChunkComplete( + headers: Map, + body: BufferedSource, + isLastChunk: Boolean, + ) = complete(body, isLastChunk) + + override fun onChunkProgress( + headers: Map, + loaded: Long, + total: Long, + ) = Unit + } + ) + } else { + MultipartStreamReader(source, "sample") + .readAllParts( + object : MultipartStreamReader.ChunkListener { + override fun onChunkComplete( + headers: Map, + body: BufferedSource, + isLastChunk: Boolean, + ) = complete(body, isLastChunk) + + override fun onChunkProgress( + headers: Map, + loaded: Long, + total: Long, + ) = Unit + } + ) + } + check(success && calls == 1) + return result ?: bytes +} + +fun main() { + val bean = ManagementFactory.getThreadMXBean() as com.sun.management.ThreadMXBean + check(bean.isThreadAllocatedMemorySupported) + bean.isThreadAllocatedMemoryEnabled = true + val thread = Thread.currentThread().id + for (megabytes in listOf(2, 20)) { + val size = megabytes * 1024 * 1024 + val body = ByteArray(size) { (it % 251).toByte() } + val response = + Buffer() + .apply { + writeUtf8("preamble\r\n--sample\r\nContent-Length: $size\r\n\r\n") + write(body) + writeUtf8("\r\n--sample--\r\nepilogue") + } + .readByteArray() + val nativeBody = read(true, Buffer().write(response), true) + val sharedBody = read(false, Buffer().write(response), true) + check(nativeBody == sharedBody && sharedBody == body.toByteString()) + + fun measure(native: Boolean): Pair { + val source = Buffer().write(response) + val allocated = bean.getThreadAllocatedBytes(thread) + val start = System.nanoTime() + val result = read(native, source, false) + val elapsed = (System.nanoTime() - start) / 1_000_000.0 + val bytes = bean.getThreadAllocatedBytes(thread) - allocated + check(result == size.toLong()) + return elapsed to bytes + } + repeat(30) { + measure(true) + measure(false) + } + val native = mutableListOf>() + val shared = mutableListOf>() + repeat(41) { i -> + if (i % 2 == 0) { + native += measure(true) + shared += measure(false) + } else { + shared += measure(false) + native += measure(true) + } + } + val baselineMs = native.map { it.first }.sorted()[20] + val sharedMs = shared.map { it.first }.sorted()[20] + println( + """{"bytes":$size,"iterations":41,"nativeMedianMs":$baselineMs,"kmpMedianMs":$sharedMs,"ratio":${sharedMs / baselineMs},"nativeMedianAllocatedBytes":${native.map { it.second }.sorted()[20]},"kmpMedianAllocatedBytes":${shared.map { it.second }.sorted()[20]},"nativeSamplesMs":${native.map { it.first }},"kmpSamplesMs":${shared.map { it.first }}}""" + ) + } +} diff --git a/packages/react-native/ReactShared/tests/AppleGradientBenchmark.mm b/packages/react-native/ReactShared/tests/AppleGradientBenchmark.mm new file mode 100644 index 000000000000..ae51335288f3 --- /dev/null +++ b/packages/react-native/ReactShared/tests/AppleGradientBenchmark.mm @@ -0,0 +1,154 @@ +/* + * 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 +#import + +#include +#include +#include +#include + +using namespace facebook::react; +using Clock = std::chrono::steady_clock; + +#if !RCT_BENCHMARK_KMP +@interface RCTGradientUtilsBaseline : NSObject ++ (std::vector)getFixedColorStops:(const std::vector &)colorStops + gradientLineLength:(CGFloat)gradientLineLength; +@end +#endif + +static volatile double checksum = 0; + +static void calculate(const std::vector &input) +{ +#if RCT_BENCHMARK_KMP + auto result = [RCTGradientUtils getFixedColorStops:input gradientLineLength:240]; +#else + auto result = [RCTGradientUtilsBaseline getFixedColorStops:input gradientLineLength:240]; +#endif + // Observe the output without timing another traversal or color conversion. + checksum = checksum + result.size() + result.front().position.value() + result.back().position.value(); +} + +static double nanosecondsSince(Clock::time_point start) +{ + return std::chrono::duration(Clock::now() - start).count(); +} + +static NSDictionary *memoryUsage() +{ + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + auto status = task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast(&info), &count); + if (status != KERN_SUCCESS) { + return @{@"taskInfoError" : @(status)}; + } + return @{@"residentBytes" : @(info.resident_size), @"physicalFootprintBytes" : @(info.phys_footprint)}; +} + +static std::vector inputForCase(const std::string &name) +{ + auto red = colorFromRGBA(255, 0, 0, 255); + auto blue = colorFromRGBA(0, 0, 255, 127); + if (name == "two_stops") { + return {{red, {}}, {blue, {}}}; + } + if (name == "asymmetric_hint") { + return {{red, {0, UnitType::Percent}}, {{}, {15, UnitType::Percent}}, {blue, {100, UnitType::Percent}}}; + } + std::vector result; + if (name == "implicit_16" || name == "explicit_64") { + const int count = name == "implicit_16" ? 16 : 64; + for (int i = 0; i < count; ++i) { + ValueUnit position = count == 16 ? ValueUnit{} : ValueUnit{100.f * i / (count - 1), UnitType::Percent}; + result.push_back({i % 2 == 0 ? red : blue, position}); + } + return result; + } + if (name == "multiple_hints") { + for (int i = 0; i < 8; ++i) { + result.push_back({i % 2 == 0 ? red : blue, {100.f * i / 7, UnitType::Percent}}); + if (i < 7) { + result.push_back({{}, {100.f * (i + 0.3f) / 7, UnitType::Percent}}); + } + } + return result; + } + fprintf(stderr, "Unknown gradient benchmark case: %s\n", name.c_str()); + exit(1); +} + +int main(int argc, char **argv) +{ + const bool firstCallOnly = argc == 5 && std::string(argv[4]) == "--first-call-only"; + if (argc != 4 && !firstCallOnly) { + fprintf(stderr, "Usage: AppleGradientBenchmark CASE ITERATIONS SAMPLES [--first-call-only]\n"); + return 1; + } + char *iterationsEnd = nullptr; + char *samplesEnd = nullptr; + const auto iterations = strtoul(argv[2], &iterationsEnd, 10); + const auto samples = strtoul(argv[3], &samplesEnd, 10); + if (*iterationsEnd != '\0' || *samplesEnd != '\0' || iterations == 0 || iterations > 1000000 || samples == 0 || + samples > 100) { + fprintf(stderr, "Iterations must be 1..1000000; samples must be 1..100.\n"); + return 1; + } + @autoreleasepool { + auto input = inputForCase(argv[1]); + auto beforeFirstCall = memoryUsage(); + auto start = Clock::now(); + @autoreleasepool { + calculate(input); + } + const auto firstCallNanoseconds = nanosecondsSince(start); + auto afterFirstCall = memoryUsage(); + const int warmupCalls = firstCallOnly ? 0 : 1000; + for (int i = 0; i < warmupCalls; ++i) { + @autoreleasepool { + calculate(input); + } + } + auto afterWarmup = memoryUsage(); + NSMutableArray *timings = [NSMutableArray new]; + for (unsigned long sample = 0; sample < (firstCallOnly ? 0 : samples); ++sample) { + start = Clock::now(); + for (unsigned long iteration = 0; iteration < iterations; ++iteration) { + @autoreleasepool { + calculate(input); + } + } + [timings addObject:@(nanosecondsSince(start) / iterations)]; + } + auto afterMeasurement = memoryUsage(); + NSDictionary *result = @{ + @"variant" : RCT_BENCHMARK_KMP ? @"kmp" : @"native", + @"case" : @(argv[1]), + @"iterationsPerSample" : @(iterations), + @"warmupCalls" : @(warmupCalls), + @"firstCallNanoseconds" : @(firstCallNanoseconds), + @"nanosecondsPerCall" : timings, + @"memoryBeforeFirstCall" : beforeFirstCall, + @"memoryAfterFirstCall" : afterFirstCall, + @"memoryAfterWarmup" : afterWarmup, + @"memoryAfterMeasurement" : afterMeasurement, + @"checksum" : @(checksum), + }; + NSError *error = nil; + NSData *json = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:&error]; + if (json == nil) { + fprintf(stderr, "Unable to serialize benchmark result: %s\n", error.localizedDescription.UTF8String); + return 1; + } + fwrite(json.bytes, 1, json.length, stdout); + putchar('\n'); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/AppleGradientParity.mm b/packages/react-native/ReactShared/tests/AppleGradientParity.mm new file mode 100644 index 000000000000..8b8350298805 --- /dev/null +++ b/packages/react-native/ReactShared/tests/AppleGradientParity.mm @@ -0,0 +1,106 @@ +/* + * 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 + +#include +#include +#include +#include + +using namespace facebook::react; + +// The test runner compiles the unchanged native path under this class name. +@interface RCTGradientUtilsBaseline : NSObject ++ (std::vector)getFixedColorStops:(const std::vector &)colorStops + gradientLineLength:(CGFloat)gradientLineLength; +@end + +static size_t checkedCases = 0; + +static void checkParity(const std::vector &input, CGFloat lineLength = 240) +{ + auto expected = [RCTGradientUtilsBaseline getFixedColorStops:input gradientLineLength:lineLength]; + auto actual = [RCTGradientUtils getFixedColorStops:input gradientLineLength:lineLength]; + if (expected.size() != actual.size()) { + fprintf(stderr, "Gradient case %zu: expected %zu stops, got %zu\n", checkedCases, expected.size(), actual.size()); + exit(1); + } + for (size_t i = 0; i < expected.size(); ++i) { + if (std::abs(expected[i].position.value() - actual[i].position.value()) > 1e-12 || + static_cast(expected[i].color) != static_cast(actual[i].color) || + (expected[i].color && (*expected[i].color).getColor() != (*actual[i].color).getColor())) { + fprintf( + stderr, + "Gradient case %zu: stop %zu differs (positions %.9g / %.9g, colors %x / %x)\n", + checkedCases, + i, + expected[i].position.value(), + actual[i].position.value(), + expected[i].color ? (*expected[i].color).getColor() : 0, + actual[i].color ? (*actual[i].color).getColor() : 0); + exit(1); + } + } + ++checkedCases; +} + +int main() +{ + @autoreleasepool { + auto red = colorFromRGBA(255, 0, 0, 255); + auto blue = colorFromRGBA(0, 0, 255, 127); + auto green = colorFromRGBA(0, 255, 0, 255); + checkParity({}); + checkParity({{red, {}}}); + checkParity({{red, {}}, {green, {}}, {blue, {}}}); + checkParity({{red, {75, UnitType::Percent}}, {green, {25, UnitType::Percent}}, {blue, {}}}); + checkParity({{red, {-50, UnitType::Percent}}, {green, {}}, {blue, {150, UnitType::Percent}}}); + checkParity({{red, {10, UnitType::Point}}, {green, {}}, {blue, {220, UnitType::Point}}}); + // CGFloat precision matters here: Float rounding crosses the centered-hint epsilon. + checkParity({{red, {0, UnitType::Point}}, {{}, {100.5f, UnitType::Point}}, {blue, {200, UnitType::Point}}}, 200); + + // Symmetric, endpoint, near-epsilon and asymmetric transition hints. + for (float hint : {0.f, 0.49f, 0.51f, 1.f, 20.f, 49.8f, 50.f, 50.2f, 80.f, 99.49f, 99.51f, 100.f}) { + checkParity({{red, {0, UnitType::Percent}}, {{}, {hint, UnitType::Percent}}, {blue, {100, UnitType::Percent}}}); + } + checkParity( + {{red, {0, UnitType::Percent}}, + {{}, {15, UnitType::Percent}}, + {green, {40, UnitType::Percent}}, + {{}, {85, UnitType::Percent}}, + {blue, {100, UnitType::Percent}}}); + + // Retaining an original stop must retain its native dynamic color object. + SharedColor dynamicColor{Color( + DynamicColor{.lightColor = static_cast(0xffff0000), .darkColor = static_cast(0xff0000ff)})}; + auto dynamicResult = [RCTGradientUtils getFixedColorStops:{ + {dynamicColor, {}}, + {blue, {}} + } + gradientLineLength:240]; + if ((*dynamicResult[0].color).getUIColor() != (*dynamicColor).getUIColor()) { + fprintf(stderr, "KMP gradient adapter replaced an original dynamic UIColor\n"); + return 1; + } + checkParity({{dynamicColor, {}}, {blue, {}}}); + + std::mt19937 random(8675309); + for (int i = 0; i < 250; ++i) { + float hint = 1 + random() % 99; + auto left = colorFromRGBA(random() % 256, random() % 256, random() % 256, random() % 256); + auto right = colorFromRGBA(random() % 256, random() % 256, random() % 256, random() % 256); + checkParity({{left, {0, UnitType::Percent}}, {{}, {hint, UnitType::Percent}}, {right, {100, UnitType::Percent}}}); + checkParity( + {{left, {0, UnitType::Point}}, {{}, {hint * 1.7f, UnitType::Point}}, {right, {170, UnitType::Point}}}, + 237.25); + } + printf("Apple gradient parity passed: %zu cases; native colors and KMP positions/weights agree.\n", checkedCases); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/AppleMultipartParity.m b/packages/react-native/ReactShared/tests/AppleMultipartParity.m new file mode 100644 index 000000000000..df627767a9d1 --- /dev/null +++ b/packages/react-native/ReactShared/tests/AppleMultipartParity.m @@ -0,0 +1,177 @@ +/* + * 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 +#import + +@interface RCTMultipartStreamReaderBaseline : NSObject +- (instancetype)initWithInputStream:(NSInputStream *)stream boundary:(NSString *)boundary; +- (BOOL)readAllPartsWithCompletionCallback:(RCTMultipartCallback)callback + progressCallback:(RCTMultipartProgressCallback)progressCallback; +@end + +@interface FragmentedMultipartStream : NSInputStream +- (instancetype)initWithData:(NSData *)data readSize:(NSUInteger)readSize; +@end + +@implementation FragmentedMultipartStream { + NSData *_data; + NSUInteger _offset; + NSUInteger _readSize; +} +- (instancetype)initWithData:(NSData *)data readSize:(NSUInteger)readSize +{ + if (self = [super init]) { + _data = data; + _readSize = readSize; + } + return self; +} +- (void)open +{ +} +- (NSError *)streamError +{ + return nil; +} +- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)length +{ + NSUInteger count = MIN(MIN(length, _readSize), _data.length - _offset); + [_data getBytes:buffer range:NSMakeRange(_offset, count)]; + _offset += count; + return count; +} +@end + +static NSDictionary *Read(Class readerClass, NSData *data, NSUInteger readSize, BOOL retainBodies) +{ + NSInputStream *stream = [[FragmentedMultipartStream alloc] initWithData:data readSize:readSize]; + RCTMultipartStreamReader *reader = [[readerClass alloc] initWithInputStream:stream boundary:@"sample"]; + NSMutableArray *parts = [NSMutableArray new]; + NSMutableArray *completedProgress = [NSMutableArray new]; + __block NSArray *progress; + BOOL success = [reader + readAllPartsWithCompletionCallback:^(NSDictionary *headers, NSData *body, BOOL done) { + [parts addObject:@[ headers ?: @{}, retainBodies ? (id)body : @(body.length), @(done) ]]; + [completedProgress addObject:progress ?: @[]]; + progress = nil; + } + progressCallback:^(NSDictionary *headers, NSNumber *length, NSNumber *loaded) { + progress = @[ headers, length, loaded ]; + }]; + return @{@"success" : @(success), @"parts" : parts, @"finalProgress" : completedProgress}; +} + +static void Require(BOOL condition, NSString *message) +{ + if (!condition) { + fprintf(stderr, "FAIL: %s\n", message.UTF8String); + exit(1); + } +} + +static NSData *Response(NSUInteger size) +{ + NSMutableData *data = [[NSString stringWithFormat:@"preamble\r\n--sample\r\nContent-Length: %lu\r\n\r\n", + (unsigned long)size] dataUsingEncoding:NSUTF8StringEncoding] + .mutableCopy; + NSMutableData *body = [NSMutableData dataWithLength:size]; + // Deterministic binary content, without a valid delimiter or header separator. + uint8_t *bytes = body.mutableBytes; + for (NSUInteger i = 0; i < size; i++) + bytes[i] = (uint8_t)(i % 251); + [data appendData:body]; + [data appendData:[@"\r\n--sample--\r\nepilogue" dataUsingEncoding:NSUTF8StringEncoding]]; + return data; +} + +static double Measure(Class readerClass, NSData *data, NSUInteger size) +{ + CFTimeInterval start = CACurrentMediaTime(); + @autoreleasepool { + NSDictionary *result = Read(readerClass, data, 4096, NO); + Require([result[@"success"] boolValue], @"benchmark completion"); + Require( + [result[@"parts"] count] == 1 && [result[@"parts"][0][1] unsignedIntegerValue] == size, + @"benchmark body length"); + } + return (CACurrentMediaTime() - start) * 1000; +} + +int main(int argc, const char *argv[]) +{ + @autoreleasepool { + Class native = RCTMultipartStreamReaderBaseline.class; + Class shared = RCTMultipartStreamReader.class; + if (argc == 2 && strcmp(argv[1], "--benchmark") == 0) { + for (NSNumber *megabytes in @[ @2, @20 ]) { + NSUInteger size = megabytes.unsignedIntegerValue * 1024 * 1024; + NSData *data = Response(size); + Require([Read(native, data, 4096, YES) isEqual:Read(shared, data, 4096, YES)], @"large body exact parity"); + for (NSUInteger i = 0; i < 5; i++) { + Measure(native, data, size); + Measure(shared, data, size); + } + NSMutableArray *nativeSamples = [NSMutableArray new]; + NSMutableArray *sharedSamples = [NSMutableArray new]; + for (NSUInteger i = 0; i < 21; i++) { + if (i % 2 == 0) { + [nativeSamples addObject:@(Measure(native, data, size))]; + [sharedSamples addObject:@(Measure(shared, data, size))]; + } else { + [sharedSamples addObject:@(Measure(shared, data, size))]; + [nativeSamples addObject:@(Measure(native, data, size))]; + } + } + double baseline = [[nativeSamples sortedArrayUsingSelector:@selector(compare:)][10] doubleValue]; + double kmp = [[sharedSamples sortedArrayUsingSelector:@selector(compare:)][10] doubleValue]; + NSDictionary *result = @{ + @"bytes" : @(size), + @"iterations" : @21, + @"nativeMedianMs" : @(baseline), + @"kmpMedianMs" : @(kmp), + @"ratio" : @(kmp / baseline), + @"nativeSamplesMs" : nativeSamples, + @"kmpSamplesMs" : sharedSamples + }; + puts([[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:result options:0 error:nil] + encoding:NSUTF8StringEncoding] + .UTF8String); + } + return 0; + } + + NSArray *inputs = @[ + @"Yolo", + @"preamble\r\n--sample--\r\n", + @"\r\n--sample\r\none\r\n--sample\r\ntwo\r\n--sample--\r\nepilogue", + @"\r\n--sample\r\nX: a:b\r\nx: c\r\n invalid \r\n\r\nbody\r\n--sample--\r\n", + @"\r\n--sample\r\nfirst\r\n--sample\r\nincomplete", + @"\r\n--sample\r\nbinary\0\r\n--samplX\r\n--sample-\r\n--sample--\r\n" + ]; + NSUInteger cases = 0; + for (NSString *input in inputs) { + NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding]; + for (NSUInteger readSize = 1; readSize <= data.length; readSize++) { + Require( + [Read(native, data, readSize, YES) isEqual:Read(shared, data, readSize, YES)], + [NSString stringWithFormat:@"native/KMP parity case %lu read %lu", + (unsigned long)cases, + (unsigned long)readSize]); + cases++; + } + } + for (NSNumber *size in @[ @4095, @4096, @4097, @65536 ]) { + NSData *data = Response(size.unsignedIntegerValue); + Require([Read(native, data, 4096, YES) isEqual:Read(shared, data, 4096, YES)], @"binary body/progress parity"); + cases++; + } + printf("PASS: %lu real Apple multipart adapter parity cases\n", (unsigned long)cases); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/AppleScrollSnapParity.mm b/packages/react-native/ReactShared/tests/AppleScrollSnapParity.mm new file mode 100644 index 000000000000..7151fbc1e3a9 --- /dev/null +++ b/packages/react-native/ReactShared/tests/AppleScrollSnapParity.mm @@ -0,0 +1,181 @@ +/* + * 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 +#import +#include +#include +#include +#include + +// This fixture links the actual scroll view and delegate splitter. The only omitted +// implementation is RN's logging sanitizer; every test coordinate is finite. +double RCTSanitizeNaNValue(double value, NSString *property) +{ + if (!std::isfinite(value)) { + std::abort(); + } + return value; +} + +static RCTEnhancedScrollView *makeView(NSString *className, BOOL horizontal) +{ + auto view = (RCTEnhancedScrollView *)[[NSClassFromString(className) alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; + if (!view) { + std::abort(); + } + view.contentSize = horizontal ? CGSizeMake(500, 200) : CGSizeMake(200, 500); + view.snapToStart = YES; + view.snapToEnd = YES; + return view; +} + +static CGPoint target(RCTEnhancedScrollView *view, BOOL horizontal, double predicted, double velocity) +{ + CGPoint result = horizontal ? CGPointMake(predicted, 17) : CGPointMake(17, predicted); + CGPoint speed = horizontal ? CGPointMake(velocity, 0) : CGPointMake(0, velocity); + [(id)view scrollViewWillEndDragging:view withVelocity:speed targetContentOffset:&result]; + return result; +} + +static void requireEqual(CGPoint actual, CGPoint expected, NSUInteger index) +{ + if (actual.x != expected.x || actual.y != expected.y) { + std::fprintf( + stderr, "case %lu: (%g, %g) != (%g, %g)\n", (unsigned long)index, actual.x, actual.y, expected.x, expected.y); + std::exit(1); + } +} + +static void checkViews( + RCTEnhancedScrollView *actual, + RCTEnhancedScrollView *baseline, + RCTEnhancedScrollView *cached, + BOOL horizontal, + double predicted, + double velocity, + NSUInteger index) +{ + auto expected = target(baseline, horizontal, predicted, velocity); + requireEqual(target(actual, horizontal, predicted, velocity), expected, index); + requireEqual(target(cached, horizontal, predicted, velocity), expected, index); +} + +static double nanos(uint64_t elapsed) +{ + mach_timebase_info_data_t scale; + mach_timebase_info(&scale); + return (double)elapsed * scale.numer / scale.denom; +} + +int main(int argc, const char **argv) +{ + @autoreleasepool { +#if RCT_SCROLL_BENCHMARK + const NSUInteger count = argc > 1 ? strtoul(argv[1], nullptr, 10) : 16; + const NSUInteger iterations = 10000; + auto view = makeView(@"RCTEnhancedScrollView", YES); + NSMutableArray *offsets = [NSMutableArray new]; + for (NSUInteger i = 0; i < count; i++) { + [offsets addObject:@(300.0 * i / MAX(count - 1, 1UL))]; + } + const auto propertyStart = mach_continuous_time(); + view.snapToOffsets = offsets; + const double firstPropertyNanos = nanos(mach_continuous_time() - propertyStart); + const auto firstStart = mach_continuous_time(); + auto first = target(view, YES, 151.0, 1.0); + const double firstFlingNanos = nanos(mach_continuous_time() - firstStart); + NSMutableArray *samples = [NSMutableArray new]; + double checksum = first.x; + for (NSUInteger sample = 0; sample < 7; sample++) { + const auto start = mach_continuous_time(); + for (NSUInteger i = 0; i < iterations; i++) { + @autoreleasepool { + checksum += target(view, YES, (double)(i % 301), (int)(i % 3) - 1).x; + } + } + [samples addObject:@(nanos(mach_continuous_time() - start) / iterations)]; + } + NSDictionary *report = @{ + @"offsetCount" : @(count), + @"iterationsPerSample" : @(iterations), + @"firstPropertyNanos" : @(firstPropertyNanos), + @"firstFlingNanos" : @(firstFlingNanos), + @"nanosPerFling" : samples, + @"checksum" : @(checksum), + }; +#else + NSUInteger cases = 0; + NSArray *> *lists = @[ + @[], + @[ @60 ], + @[ @20, @60, @100 ], + @[ @0.25, @0.25, @60.1, @100.75 ], + @[ @100, @20, @60 ], + @[ @-20, @60, @350 ], + ]; + for (BOOL horizontal : {NO, YES}) { + auto actual = makeView(@"RCTEnhancedScrollView", horizontal); + auto baseline = makeView(@"RCTEnhancedScrollViewBaseline", horizontal); + auto cached = makeView(@"RCTEnhancedScrollViewCached", horizontal); + for (double maximum : {0.0, 120.0, 300.0}) { + actual.contentSize = baseline.contentSize = cached.contentSize = + horizontal ? CGSizeMake(200 + maximum, 200) : CGSizeMake(200, 200 + maximum); + for (NSArray *offsets in lists) { + actual.snapToOffsets = baseline.snapToOffsets = cached.snapToOffsets = offsets; + for (int flags = 0; flags < 4; flags++) { + actual.snapToStart = baseline.snapToStart = cached.snapToStart = flags & 1; + actual.snapToEnd = baseline.snapToEnd = cached.snapToEnd = flags & 2; + for (double current : {-20.0, 0.0, 20.0, 60.0, 100.0, 150.0, 320.0}) { + actual.contentOffset = baseline.contentOffset = cached.contentOffset = + horizontal ? CGPointMake(current, 0) : CGPointMake(0, current); + for (double predicted : {-50.0, 0.0, 20.0, 39.9, 40.0, 60.0, 100.0, 120.0, 150.0, 320.0}) { + for (double velocity : {-1.0, 0.0, 1.0}) { + checkViews(actual, baseline, cached, horizontal, predicted, velocity, ++cases); + } + } + } + } + } + } + // Replacing/clearing the property must invalidate the cached selector. + NSMutableArray *mutableOffsets = [@[ @20, @60, @100 ] mutableCopy]; + actual.snapToOffsets = baseline.snapToOffsets = cached.snapToOffsets = mutableOffsets; + mutableOffsets[1] = @90; + checkViews(actual, baseline, cached, horizontal, 40, 1, ++cases); + for (NSArray *replacement in @[ @[ @30, @70 ], @[] ]) { + actual.snapToOffsets = baseline.snapToOffsets = cached.snapToOffsets = replacement; + checkViews(actual, baseline, cached, horizontal, 40, 1, ++cases); + } + [actual setValue:nil forKey:@"snapToOffsets"]; + [baseline setValue:nil forKey:@"snapToOffsets"]; + [cached setValue:nil forKey:@"snapToOffsets"]; + // Interval snapping remains a native operation, including alignment and momentum policy. + actual.contentSize = baseline.contentSize = cached.contentSize = + horizontal ? CGSizeMake(500, 200) : CGSizeMake(200, 500); + actual.snapToInterval = baseline.snapToInterval = cached.snapToInterval = 60; + actual.contentOffset = baseline.contentOffset = cached.contentOffset = + horizontal ? CGPointMake(75, 0) : CGPointMake(0, 75); + for (NSString *alignment in @[ @"start", @"center", @"end" ]) { + actual.snapToAlignment = baseline.snapToAlignment = cached.snapToAlignment = alignment; + for (BOOL disableMomentum : {NO, YES}) { + actual.disableIntervalMomentum = baseline.disableIntervalMomentum = cached.disableIntervalMomentum = + disableMomentum; + for (double velocity : {-1.0, 0.0, 1.0}) { + checkViews(actual, baseline, cached, horizontal, 130, velocity, ++cases); + } + } + } + } + NSDictionary *report = @{@"passedCases" : @(cases), @"cachedNativeControlCases" : @(cases), @"failedCases" : @0}; +#endif + NSData *json = [NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingSortedKeys error:nil]; + std::puts([[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding].UTF8String); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/coexistence/AppleKotlinCoexistence.mm b/packages/react-native/ReactShared/tests/coexistence/AppleKotlinCoexistence.mm new file mode 100644 index 000000000000..eeff8e3e198c --- /dev/null +++ b/packages/react-native/ReactShared/tests/coexistence/AppleKotlinCoexistence.mm @@ -0,0 +1,69 @@ +/* + * 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 +#import + +#include +#include + +extern "C" NSArray *ReactNativeSharedFixtureStops(); + +static void check(bool condition, const char *message) +{ + if (!condition) { + fprintf(stderr, "Kotlin framework coexistence failed: %s\n", message); + abort(); + } +} + +static void exercise(int32_t seed) +{ + // Each framework keeps ownership of its Kotlin objects. Only primitive values + // are copied between their APIs; these are not cast across Kotlin runtimes. + auto independent = IndependentKotlinIndependentProbe.shared; + auto token = [independent makeTokenSeed:seed]; + auto stops = ReactNativeSharedFixtureStops(); + check(stops.count == 3, "shared resolver returned the wrong number of stops"); + @autoreleasepool { + NSArray *values = @[ + [[IndependentKotlinDouble alloc] initWithDouble:stops[0].position], + [[IndependentKotlinDouble alloc] initWithDouble:stops[1].position], + [[IndependentKotlinDouble alloc] initWithDouble:stops[2].position], + ]; + check([independent sumValues:values] == 1.5, "independent framework could not use copied numeric values"); + for (int i = 0; i < 10; ++i) { + @autoreleasepool { + check(ReactNativeSharedFixtureStops().count == 3, "shared framework changed while another framework was alive"); + check( + [independent verifyTokenToken:[independent makeTokenSeed:i] seed:i], + "independent token did not round-trip"); + } + } + } + check(stops[1].position == 0.5, "retained shared result changed after inner autorelease pools drained"); + check([independent verifyTokenToken:token seed:seed], "retained independent object lost its state"); +} + +int main() +{ + @autoreleasepool { + for (int32_t i = 0; i < 100; ++i) { + @autoreleasepool { + exercise(i); + } + } + dispatch_apply(64, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^(size_t index) { + @autoreleasepool { + exercise(static_cast(index)); + } + }); + puts("Kotlin framework coexistence passed: 100 serial and 64 concurrent object-lifetime/value checks."); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/coexistence/IndependentKotlin.kt b/packages/react-native/ReactShared/tests/coexistence/IndependentKotlin.kt new file mode 100644 index 000000000000..a54d9403a43d --- /dev/null +++ b/packages/react-native/ReactShared/tests/coexistence/IndependentKotlin.kt @@ -0,0 +1,20 @@ +/* + * 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.shared.fixture + +// Deliberately compiled as an independent framework, without ReactNativeShared. +public class IndependentToken(public val value: String) + +public object IndependentProbe { + public fun makeToken(seed: Int): IndependentToken = IndependentToken("independent-$seed") + + public fun verifyToken(token: IndependentToken, seed: Int): Boolean = + token.value == "independent-$seed" + + public fun sum(values: List): Double = values.sum() +} diff --git a/packages/react-native/ReactShared/tests/coexistence/ReactNativeRuntimeOwner.mm b/packages/react-native/ReactShared/tests/coexistence/ReactNativeRuntimeOwner.mm new file mode 100644 index 000000000000..16e7403c84d8 --- /dev/null +++ b/packages/react-native/ReactShared/tests/coexistence/ReactNativeRuntimeOwner.mm @@ -0,0 +1,20 @@ +/* + * 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 + +// Linked into the host for static React Native, or into one dedicated dylib for +// dynamic React Native. The dynamic host never links ReactNativeShared again. +extern "C" NSArray *ReactNativeSharedFixtureStops() +{ + NSArray *input = @[ + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + ]; + return [RNSGradientStops.shared resolveStops:input epsilon:0.005 useDoublePrecision:YES]; +} diff --git a/packages/react-native/ReactShared/tests/distribution/Package.swift b/packages/react-native/ReactShared/tests/distribution/Package.swift new file mode 100644 index 000000000000..f4b166522094 --- /dev/null +++ b/packages/react-native/ReactShared/tests/distribution/Package.swift @@ -0,0 +1,25 @@ +// swift-tools-version: 6.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 PackageDescription + +let package = Package( + name: "KMPDistributionProbe", + platforms: [.iOS(.v15), .macCatalyst(.v15)], + products: [.library(name: "KMPDistributionProbe", type: .dynamic, targets: ["Probe"])], + targets: [ + .binaryTarget(name: "ReactNativeShared", path: "ReactNativeShared.xcframework"), + .target( + name: "Probe", + dependencies: [.target(name: "ReactNativeShared", condition: .when(platforms: [.iOS]))], + cSettings: [.unsafeFlags(["-fobjc-arc"])], + linkerSettings: [.linkedFramework("Foundation")] + ), + .testTarget(name: "ProbeTests", dependencies: ["Probe"]), + ] +) diff --git a/packages/react-native/ReactShared/tests/distribution/Sources/Probe/Probe.m b/packages/react-native/ReactShared/tests/distribution/Sources/Probe/Probe.m new file mode 100644 index 000000000000..00cb0052e629 --- /dev/null +++ b/packages/react-native/ReactShared/tests/distribution/Sources/Probe/Probe.m @@ -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. + */ + +#import "Probe.h" +#import + +#if !TARGET_OS_MACCATALYST +#import +#endif + +int RNSDistributionProbe(void) +{ +#if TARGET_OS_MACCATALYST + return 1; +#else + @autoreleasepool { + NSArray *input = @[ + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + [[RNSGradientStopInput alloc] initWithPosition:nil hasColor:YES], + ]; + NSArray *stops = [RNSGradientStops.shared resolveStops:input + epsilon:0.00001 + useDoublePrecision:YES]; + return stops.count == 3 && stops[0].position == 0 && stops[1].position == 0.5 && stops[2].position == 1 && + stops[1].leftColorIndex == 1; + } +#endif +} diff --git a/packages/react-native/ReactShared/tests/distribution/Sources/Probe/include/Probe.h b/packages/react-native/ReactShared/tests/distribution/Sources/Probe/include/Probe.h new file mode 100644 index 000000000000..05ea4b723bc9 --- /dev/null +++ b/packages/react-native/ReactShared/tests/distribution/Sources/Probe/include/Probe.h @@ -0,0 +1,8 @@ +/* + * 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. + */ + +int RNSDistributionProbe(void); diff --git a/packages/react-native/ReactShared/tests/distribution/Tests/ProbeTests/ProbeTests.swift b/packages/react-native/ReactShared/tests/distribution/Tests/ProbeTests/ProbeTests.swift new file mode 100644 index 000000000000..e116f7df5f42 --- /dev/null +++ b/packages/react-native/ReactShared/tests/distribution/Tests/ProbeTests/ProbeTests.swift @@ -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. + */ + +import Probe +import XCTest + +final class ProbeTests: XCTestCase { + func testPackagedGradientCalculation() { + XCTAssertEqual(RNSDistributionProbe(), 1) + } +} diff --git a/packages/react-native/ReactShared/tests/smoke/AppleKmpSmoke.mm b/packages/react-native/ReactShared/tests/smoke/AppleKmpSmoke.mm new file mode 100644 index 000000000000..9227fd266193 --- /dev/null +++ b/packages/react-native/ReactShared/tests/smoke/AppleKmpSmoke.mm @@ -0,0 +1,31 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import + +#include +#include + +int main() +{ + @autoreleasepool { + struct Case { + int32_t left; + int32_t right; + int32_t expected; + }; + const Case cases[] = {{19, 23, 42}, {-7, 4, -3}, {0, 0, 0}, {INT32_MAX, 0, INT32_MAX}, {INT32_MIN, 0, INT32_MIN}}; + for (const auto &test : cases) { + if ([RNSKmpSmoke.shared addLeft:test.left right:test.right] != test.expected) { + fprintf(stderr, "Kotlin Objective-C integer interop failed\n"); + return 1; + } + } + puts("Kotlin Objective-C smoke passed: 5 cases"); + } + return 0; +} diff --git a/packages/react-native/ReactShared/tests/smoke/kotlin/KmpSmoke.kt b/packages/react-native/ReactShared/tests/smoke/kotlin/KmpSmoke.kt new file mode 100644 index 000000000000..f8e52f414e2a --- /dev/null +++ b/packages/react-native/ReactShared/tests/smoke/kotlin/KmpSmoke.kt @@ -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. + */ + +package com.facebook.react.shared.smoke + +// Unpublished compiler/interop fixture, included only with reactNativeSharedSmoke=true. +public object KmpSmoke { + public fun add(left: Int, right: Int): Int = left + right +} diff --git a/packages/react-native/ReactShared/tests/smoke/kotlinTest/KmpSmokeTest.kt b/packages/react-native/ReactShared/tests/smoke/kotlinTest/KmpSmokeTest.kt new file mode 100644 index 000000000000..73325f799788 --- /dev/null +++ b/packages/react-native/ReactShared/tests/smoke/kotlinTest/KmpSmokeTest.kt @@ -0,0 +1,34 @@ +/* + * 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.shared.smoke + +import kotlin.test.Test +import kotlin.test.assertEquals + +class KmpSmokeTest { + @Test + fun positiveIntegers() { + assertEquals(42, KmpSmoke.add(19, 23)) + } + + @Test + fun signedIntegers() { + assertEquals(-3, KmpSmoke.add(-7, 4)) + } + + @Test + fun zero() { + assertEquals(0, KmpSmoke.add(0, 0)) + } + + @Test + fun integerBoundaries() { + assertEquals(Int.MAX_VALUE, KmpSmoke.add(Int.MAX_VALUE, 0)) + assertEquals(Int.MIN_VALUE, KmpSmoke.add(Int.MIN_VALUE, 0)) + } +} diff --git a/packages/react-native/package.json b/packages/react-native/package.json index a09745bf963c..3c0c18ef6032 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -93,6 +93,19 @@ "!ReactAndroid/src/test", "ReactApple", "ReactCommon", + "ReactShared/*.gradle.kts", + "ReactShared/*.podspec", + "ReactShared/cocoapods", + "ReactShared/gradle.properties", + "ReactShared/gradle/wrapper", + "ReactShared/gradlew", + "ReactShared/gradlew.bat", + "ReactShared/README.md", + "ReactShared/scripts", + "ReactShared/src", + "ReactShared/tests", + "!ReactShared/**/__pycache__", + "!ReactShared/**/*.pyc", "README.md", "scripts/replace-rncore-version.js", "scripts/bundle.js", diff --git a/packages/react-native/scripts/cocoapods/kmp.rb b/packages/react-native/scripts/cocoapods/kmp.rb new file mode 100644 index 000000000000..1d4ba752a8aa --- /dev/null +++ b/packages/react-native/scripts/cocoapods/kmp.rb @@ -0,0 +1,133 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +class ReactNativeKMPUtils + def self.configure_aggregate_xcconfig(installer) + installer.aggregate_targets.each do |aggregate_target| + aggregate_target.xcconfigs.each do |config_name, config_file| + # CocoaPods excludes the host's static pods from search-path-only test + # targets here. user_target_xcconfig does not perform that exclusion. + linked_pods = aggregate_target.build_settings(config_name).pod_targets_to_link + next unless linked_pods.any? { |pod| pod.pod_name == 'React-KMP' } + + # Dynamic React-Core already contains the static Kotlin runtime. Other + # consumers use their existing React-Core dependency to share that owner. + next if linked_pods.any? { |pod| pod.pod_name == 'React-Core' && pod.build_as_dynamic? } + %w[iphoneos iphonesimulator].each do |sdk| + # Full-pod sibling tests also reuse their host's runtime. Resolve each + # SDK separately because TEST_HOST and product settings can be conditional. + next if test_host_links_kmp?(aggregate_target, config_name, installer.aggregate_targets, sdk) + + key = "OTHER_LDFLAGS[sdk=#{sdk}*]" + flags = config_file.attributes[key] || '$(inherited)' + unless flags.include?('-framework ReactNativeShared') + config_file.attributes[key] = "#{flags} -framework ReactNativeShared" + end + end + config_file.save_as(aggregate_target.xcconfig_path(config_name)) + end + end + end + + def self.test_host_links_kmp?(aggregate_target, config_name, aggregate_targets, sdk) + user_targets = aggregate_target.user_targets + !user_targets.empty? && user_targets.all? do |target| + next false unless target.symbol_type == :unit_test_bundle + + settings = target_settings(target, config_name, sdk) + test_host = expand_build_setting(settings['TEST_HOST'], settings) + bundle_loader = expand_build_setting(settings['BUNDLE_LOADER'], settings) + next false if test_host.to_s.empty? || bundle_loader.to_s.empty? + next false unless Pathname.new(test_host).cleanpath == Pathname.new(bundle_loader).cleanpath + + project = aggregate_target.user_project + host_uuid = project.root_object.attributes.dig('TargetAttributes', target.uuid, 'TestTargetID') + # TestTargetID is optional. A dependency is only a candidate, not evidence + # of hosting: both loader settings must identify its actual app executable. + candidates = host_uuid ? project.targets.select { |app| app.uuid == host_uuid } : target.dependencies.map(&:target).compact + hosts = candidates.select do |app| + next false unless app.project == project && app.symbol_type == :application + app_settings = target_settings(app, config_name, sdk) + executable = expand_build_setting(app_settings['EXECUTABLE_PATH'], app_settings) + next false if executable.to_s.empty? || executable.include?('$') + path = expand_build_setting("$(BUILT_PRODUCTS_DIR)/#{executable}", app_settings) + path && Pathname.new(path).cleanpath == Pathname.new(test_host).cleanpath + end + next false unless hosts.one? + + aggregate_targets.any? do |candidate| + candidate.user_project == project && candidate.user_target_uuids.include?(hosts.first.uuid) && + candidate.build_settings(config_name).pod_targets_to_link.any? { |pod| pod.pod_name == 'React-KMP' } + end + end + end + + def self.target_settings(target, config_name, sdk) + # Xcodeproj's resolved_build_setting drops unknown SDK variables and does + # not supply product defaults. Preserve those variables for exact path matching. + settings = { + 'TARGET_NAME' => target.name, 'CONFIGURATION' => config_name, + 'PROJECT_NAME' => target.project.path.basename('.xcodeproj').to_s, + 'SRCROOT' => target.project.project_dir.to_s, 'PROJECT_DIR' => target.project.project_dir.to_s, + 'PRODUCT_NAME' => '$(TARGET_NAME)', 'EXECUTABLE_PREFIX' => '', 'EXECUTABLE_SUFFIX' => '', + 'EXECUTABLE_NAME' => '$(EXECUTABLE_PREFIX)$(PRODUCT_NAME)$(EXECUTABLE_SUFFIX)', + 'WRAPPER_NAME' => '$(PRODUCT_NAME).app', 'FULL_PRODUCT_NAME' => '$(WRAPPER_NAME)', + 'EXECUTABLE_FOLDER_PATH' => '$(FULL_PRODUCT_NAME)', + 'EXECUTABLE_PATH' => '$(EXECUTABLE_FOLDER_PATH)/$(EXECUTABLE_NAME)', + 'BUNDLE_EXECUTABLE_FOLDER_PATH' => '', + 'BUILT_PRODUCTS_DIR' => '$(CONFIGURATION_BUILD_DIR)', + 'TARGET_BUILD_DIR' => '$(CONFIGURATION_BUILD_DIR)', + } + [target.project.build_configuration_list[config_name], target.build_configuration_list[config_name]].compact.each do |config| + path = config.base_configuration_reference&.real_path + xcconfig = path&.file? ? Xcodeproj::Config.new(path).to_hash : {} + [xcconfig, config.build_settings].each do |layer| + # Conditional values override their unqualified value within the layer. + uncertain = [] + layer.sort_by { |key, _| key.count('[') }.each do |key, value| + next unless value.is_a?(String) + name = key.split('[').first + conditions = key.scan(/\[([^=]+)=([^\]]+)\]/).map do |qualifier, pattern| + case qualifier + when 'config' then File.fnmatch?(pattern, config_name) + when 'sdk' + if File.fnmatch?(pattern, sdk) + true + else + # A partial/version-specific match cannot be resolved at pod install. + prefix = pattern.split(/[*?\[]/, 2).first.to_s + (sdk.start_with?(prefix) || prefix.start_with?(sdk)) ? nil : false + end + end + end + next if conditions.include?(false) + # Do not guess the host if an unsupported qualifier affects its path. + uncertain << name if conditions.include?(nil) + inherited = /\$\(inherited\)|\$\{inherited\}/ + unresolved_inheritance = settings.key?(name) && settings[name].nil? && value.match?(inherited) + settings[name] = unresolved_inheritance ? nil : value.gsub(inherited) { settings[name].to_s } + end + # Unknown precedence must not depend on the order of equally qualified keys. + uncertain.each { |name| settings[name] = nil } + end + end + settings + end + + def self.expand_build_setting(value, settings, expanding = []) + return nil if value.nil? + + value.to_s.sub(/\A(["'])(.*)\1\z/m, '\\2').gsub(/\$\((\w+)\)|\$\{(\w+)\}/) do + key = Regexp.last_match(1) || Regexp.last_match(2) + if settings.key?(key) && !expanding.include?(key) + expanded = expand_build_setting(settings[key], settings, expanding + [key]) + return nil if expanded.nil? + expanded + else + "$(#{key})" + end + end + end +end diff --git a/packages/react-native/scripts/react_native_pods.rb b/packages/react-native/scripts/react_native_pods.rb index c0c13480dadd..35cf97b2dbff 100644 --- a/packages/react-native/scripts/react_native_pods.rb +++ b/packages/react-native/scripts/react_native_pods.rb @@ -11,6 +11,7 @@ require_relative './cocoapods/rndependencies.rb' require_relative './cocoapods/rncore.rb' require_relative './cocoapods/fabric.rb' +require_relative './cocoapods/kmp.rb' require_relative './cocoapods/codegen.rb' require_relative './cocoapods/codegen_utils.rb' require_relative './cocoapods/utils.rb' @@ -115,6 +116,11 @@ def use_react_native! ( # Users can still turn them off and build from source by setting the environment variable to 0. ENV['RCT_USE_RN_DEP'] = ENV['RCT_USE_RN_DEP'] == '0' ? '0' : '1' ENV['RCT_USE_PREBUILT_RNCORE'] = ENV['RCT_USE_PREBUILT_RNCORE'] == '0' ? '0' : '1' + if ENV['RCT_USE_KMP'] == '1' + # The published core binaries do not contain the opt-in shared gradient adapter. + ENV['RCT_USE_PREBUILT_RNCORE'] = '0' + Pod::UI.puts 'React Native KMP pilot: building React Native core from source.' + end # Make `REMOVE_LEGACY_ARCH` enabled by default. This will build React Native # excluding the legacy arch unless the user turns this flag off explicitly. ENV['RCT_REMOVE_LEGACY_ARCH'] = ENV['RCT_REMOVE_LEGACY_ARCH'] == '0' ? '0' : '1' @@ -164,6 +170,9 @@ def use_react_native! ( rncore_pod 'RCTRequired', :path => "#{prefix}/Libraries/Required" pod 'RCTTypeSafety', :path => "#{prefix}/Libraries/TypeSafety", :modular_headers => true pod 'React', :path => "#{prefix}/" + if ENV['RCT_USE_KMP'] == '1' + pod 'React-KMP', :path => "#{prefix}/ReactShared" + end if !ReactNativeCoreUtils.build_rncore_from_source() pod 'React-Core-prebuilt', :podspec => "#{prefix}/React-Core-prebuilt.podspec", :modular_headers => true end @@ -632,6 +641,7 @@ def react_native_post_install( ReactNativePodsUtils.updateOSDeploymentTarget(installer) ReactNativePodsUtils.set_dynamic_frameworks_flags(installer) ReactNativePodsUtils.add_ndebug_flag_to_pods_in_release(installer) + ReactNativeKMPUtils.configure_aggregate_xcconfig(installer) if !ReactNativeCoreUtils.build_rncore_from_source() # The Xcode-26 SWIFT_ENABLE_EXPLICIT_MODULES=NO workaround (#53457) is removed: diff --git a/packages/react-native/settings.gradle.kts b/packages/react-native/settings.gradle.kts index 15a03c394345..61d6d86c5d12 100644 --- a/packages/react-native/settings.gradle.kts +++ b/packages/react-native/settings.gradle.kts @@ -21,6 +21,8 @@ pluginManagement { rootProject.name = "react-native-build-from-source" +includeBuild("ReactShared") { name = "react-native-shared" } + include(":packages:react-native:ReactAndroid") project(":packages:react-native:ReactAndroid").projectDir = file("ReactAndroid/") diff --git a/packages/rn-tester/RCTTest/React-RCTTest.podspec b/packages/rn-tester/RCTTest/React-RCTTest.podspec index e96768635781..b662ace742b5 100644 --- a/packages/rn-tester/RCTTest/React-RCTTest.podspec +++ b/packages/rn-tester/RCTTest/React-RCTTest.podspec @@ -38,8 +38,10 @@ Pod::Spec.new do |s| s.dependency "React-Core", version s.dependency "React-CoreModules", version s.dependency "ReactCommon/turbomodule/core", version + s.dependency "React-NativeModulesApple", version s.dependency "React-jsi", version + depend_on_js_engine(s) add_rn_third_party_dependencies(s) add_rncore_dependency(s) end diff --git a/packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m b/packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m index 4e711d03f56e..84688e4fdaf5 100644 --- a/packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m +++ b/packages/rn-tester/RNTesterUnitTests/RCTMultipartStreamReaderTests.m @@ -9,6 +9,44 @@ #import +@interface RCTMultipartFragmentedInputStream : NSInputStream +- (instancetype)initWithData:(NSData *)data readSize:(NSUInteger)readSize; +@end + +@implementation RCTMultipartFragmentedInputStream { + NSData *_data; + NSUInteger _offset; + NSUInteger _readSize; +} + +- (instancetype)initWithData:(NSData *)data readSize:(NSUInteger)readSize +{ + if (self = [super init]) { + _data = data; + _readSize = readSize; + } + return self; +} + +- (void)open +{ +} + +- (NSError *)streamError +{ + return nil; +} + +- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)length +{ + NSUInteger count = MIN(MIN(length, _readSize), _data.length - _offset); + [_data getBytes:buffer range:NSMakeRange(_offset, count)]; + _offset += count; + return count; +} + +@end + @interface RCTMultipartStreamReaderTests : XCTestCase @end @@ -115,4 +153,76 @@ - (void)testNoCloseDelimiter XCTAssertEqual(count, 1); } +- (void)testDelimitersAcrossEveryReadBoundary +{ + NSString *body = @"binary\0\r\n--samplX\r\n--sample-\r\n"; + NSString *response = + [NSString stringWithFormat:@"preamble\r\n--sample\r\n%@\r\n--sample\r\nsecond\r\n--sample--\r\nepilogue", body]; + NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding]; + for (NSUInteger readSize = 1; readSize <= data.length; readSize++) { + NSInputStream *stream = [[RCTMultipartFragmentedInputStream alloc] initWithData:data readSize:readSize]; + RCTMultipartStreamReader *reader = [[RCTMultipartStreamReader alloc] initWithInputStream:stream boundary:@"sample"]; + NSMutableArray *parts = [NSMutableArray new]; + NSMutableArray *last = [NSMutableArray new]; + BOOL success = [reader + readAllPartsWithCompletionCallback:^(__unused NSDictionary *headers, NSData *content, BOOL done) { + [parts addObject:content]; + [last addObject:@(done)]; + } + progressCallback:nil]; + XCTAssertTrue(success, @"read size %lu", (unsigned long)readSize); + XCTAssertEqualObjects( + parts, + (@[ [body dataUsingEncoding:NSUTF8StringEncoding], [@"second" dataUsingEncoding:NSUTF8StringEncoding] ])); + XCTAssertEqualObjects(last, (@[ @NO, @YES ])); + } +} + +- (void)testHeaderWhitespaceDuplicatesAndColonValues +{ + NSString *response = + @"\r\n--sample\r\n X-Name : first\r\nx-name: second:extra \r\nx-name: last:extra \r\ninvalid\r\n\r\nbody\r\n--sample--\r\n"; + NSInputStream *stream = [NSInputStream inputStreamWithData:[response dataUsingEncoding:NSUTF8StringEncoding]]; + RCTMultipartStreamReader *reader = [[RCTMultipartStreamReader alloc] initWithInputStream:stream boundary:@"sample"]; + __block NSUInteger calls = 0; + BOOL success = [reader + readAllPartsWithCompletionCallback:^(NSDictionary *headers, NSData *content, BOOL done) { + calls++; + // Apple keeps header names verbatim and only trims values. + XCTAssertEqualObjects(headers, (@{@" X-Name " : @"first", @"x-name" : @"last:extra"})); + XCTAssertEqualObjects(content, [@"body" dataUsingEncoding:NSUTF8StringEncoding]); + XCTAssertTrue(done); + } + progressCallback:nil]; + XCTAssertTrue(success); + XCTAssertEqual(calls, 1); +} + +- (void)testFinalProgressForFragmentedBody +{ + NSString *body = [@"" stringByPaddingToLength:64 * 1024 withString:@"x" startingAtIndex:0]; + NSString *response = [NSString stringWithFormat:@"\r\n--sample\r\nContent-Length: %lu\r\n\r\n%@\r\n--sample--\r\n", + (unsigned long)body.length, + body]; + NSInputStream *stream = [NSInputStream inputStreamWithData:[response dataUsingEncoding:NSUTF8StringEncoding]]; + RCTMultipartStreamReader *reader = [[RCTMultipartStreamReader alloc] initWithInputStream:stream boundary:@"sample"]; + __block NSUInteger calls = 0; + __block NSNumber *lastLength; + __block NSNumber *lastLoaded; + BOOL success = [reader + readAllPartsWithCompletionCallback:^( + __unused NSDictionary *headers, __unused NSData *content, __unused BOOL done) { + calls++; + } + progressCallback:^(__unused NSDictionary *headers, NSNumber *length, NSNumber *loaded) { + lastLength = length; + lastLoaded = loaded; + }]; + XCTAssertTrue(success); + XCTAssertEqual(calls, 1); + XCTAssertEqualObjects(lastLength, @(body.length)); + // Preserve Apple's existing progress accounting, including the header/body separator. + XCTAssertEqualObjects(lastLoaded, @(body.length + 4)); +} + @end diff --git a/settings.gradle.kts b/settings.gradle.kts index 702a042a1088..f93a0eb604b8 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -25,6 +25,8 @@ include( includeBuild("packages/gradle-plugin/") +includeBuild("packages/react-native/ReactShared") { name = "react-native-shared" } + dependencyResolutionManagement { versionCatalogs { create("libs") { from(files("packages/react-native/gradle/libs.versions.toml")) }