Commit Graph

151 Commits

Author SHA1 Message Date
Christoph Purrer 0fd24c75a1 Simplify C++ TM base classes (#54059)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/54059

Changelog: [Internal]

Right now for a simple spec as
```
import type {CodegenTypes, TurboModule} from 'react-native';

import {TurboModuleRegistry} from 'react-native';

export type ScreenshotManagerOptions = CodegenTypes.UnsafeObject;

export interface Spec extends TurboModule {
  +getConstants: () => {};
  takeScreenshot(
    id: string,
    options: ScreenshotManagerOptions,
  ): Promise<string>;
}

const NativeModule = TurboModuleRegistry.get<Spec>('ScreenshotManager');
export function takeScreenshot(
  id: string,
  options: ScreenshotManagerOptions,
): Promise<string> {
  if (NativeModule != null) {
    return NativeModule.takeScreenshot(id, options);
  }
  return Promise.reject();
}
```

we generate **TWO** `facebook::react::TurboModule` sub classes (`NativeScreenshotManagerCxxSpecJSI` and `NativeScreenshotManagerCxxSpec`) to construct ONE C++ TM.

In particular header
```
#pragma once

#include <ReactCommon/TurboModule.h>
#include <react/bridging/Bridging.h>

namespace facebook::react {

class JSI_EXPORT NativeScreenshotManagerCxxSpecJSI : public TurboModule {
 protected:
  NativeScreenshotManagerCxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker);

 public:
  virtual jsi::Object getConstants(jsi::Runtime& rt) = 0;
  virtual jsi::Value
  takeScreenshot(jsi::Runtime& rt, jsi::String id, jsi::Object options) = 0;
};

template <typename T>
class JSI_EXPORT NativeScreenshotManagerCxxSpec : public TurboModule {
 public:
  jsi::Value create(jsi::Runtime& rt, const jsi::PropNameID& propName)
      override {
    return delegate_.create(rt, propName);
  }

  std::vector<jsi::PropNameID> getPropertyNames(
      jsi::Runtime& runtime) override {
    return delegate_.getPropertyNames(runtime);
  }

  static constexpr std::string_view kModuleName = "ScreenshotManager";

 protected:
  NativeScreenshotManagerCxxSpec(std::shared_ptr<CallInvoker> jsInvoker)
      : TurboModule(
            std::string{NativeScreenshotManagerCxxSpec::kModuleName},
            jsInvoker),
        delegate_(reinterpret_cast<T*>(this), jsInvoker) {}

 private:
  class Delegate : public NativeScreenshotManagerCxxSpecJSI {
   public:
    Delegate(T* instance, std::shared_ptr<CallInvoker> jsInvoker)
        : NativeScreenshotManagerCxxSpecJSI(std::move(jsInvoker)),
          instance_(instance) {}

    jsi::Object getConstants(jsi::Runtime& rt) override {
      static_assert(
          bridging::getParameterCount(&T::getConstants) == 1,
          "Expected getConstants(...) to have 1 parameters");

      return bridging::callFromJs<jsi::Object>(
          rt, &T::getConstants, jsInvoker_, instance_);
    }
    jsi::Value takeScreenshot(
        jsi::Runtime& rt,
        jsi::String id,
        jsi::Object options) override {
      static_assert(
          bridging::getParameterCount(&T::takeScreenshot) == 3,
          "Expected takeScreenshot(...) to have 3 parameters");

      return bridging::callFromJs<jsi::Value>(
          rt,
          &T::takeScreenshot,
          jsInvoker_,
          instance_,
          std::move(id),
          std::move(options));
    }

   private:
    friend class NativeScreenshotManagerCxxSpec;
    T* instance_;
  };

  Delegate delegate_;
};

} // namespace facebook::react
```
and cpp
```
#include "AppSpecsJSI.h"

namespace facebook::react {

static jsi::Value __hostFunction_NativeScreenshotManagerCxxSpecJSI_getConstants(
    jsi::Runtime& rt,
    TurboModule& turboModule,
    const jsi::Value* args,
    size_t count) {
  return static_cast<NativeScreenshotManagerCxxSpecJSI*>(&turboModule)
      ->getConstants(rt);
}

static jsi::Value
__hostFunction_NativeScreenshotManagerCxxSpecJSI_takeScreenshot(
    jsi::Runtime& rt,
    TurboModule& turboModule,
    const jsi::Value* args,
    size_t count) {
  return static_cast<NativeScreenshotManagerCxxSpecJSI*>(&turboModule)
      ->takeScreenshot(
          rt,
          count <= 0 ? throw jsi::JSError(
                           rt, "Expected argument in position 0 to be passed")
                     : args[0].asString(rt),
          count <= 1 ? throw jsi::JSError(
                           rt, "Expected argument in position 1 to be passed")
                     : args[1].asObject(rt));
}

NativeScreenshotManagerCxxSpecJSI::NativeScreenshotManagerCxxSpecJSI(
    std::shared_ptr<CallInvoker> jsInvoker)
    : TurboModule("ScreenshotManager", jsInvoker) {
  methodMap_["getConstants"] = MethodMetadata{
      0, __hostFunction_NativeScreenshotManagerCxxSpecJSI_getConstants};
  methodMap_["takeScreenshot"] = MethodMetadata{
      2, __hostFunction_NativeScreenshotManagerCxxSpecJSI_takeScreenshot};
}

} // namespace facebook::react
```

The goal of this change is to simplify that and only have **ONE** `facebook::react::TurboModule` base class for a concrete Cxx TM as this header

```
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#pragma once

template <typename T>
class JSI_EXPORT NativeScreenshotManagerCxxSpec : public TurboModule {
public:
  static constexpr std::string_view kModuleName = "ScreenshotManager";

protected:
  NativeScreenshotManagerCxxSpec(std::shared_ptr<CallInvoker> jsInvoker) : TurboModule(std::string{NativeScreenshotManagerCxxSpec::kModuleName}, jsInvoker) {
    methodMap_["getConstants"] = MethodMetadata {.argCount = 0, .invoker = __getConstants};
    methodMap_["takeScreenshot"] = MethodMetadata {.argCount = 2, .invoker = __takeScreenshot};
  }

private:
  static jsi::Value __getConstants(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* /*args*/, size_t /*count*/) {
    static_assert(
      bridging::getParameterCount(&T::getConstants) == 1,
      "Expected getConstants(...) to have 1 parameters");
    return bridging::callFromJs<jsi::Object>(rt, &T::getConstants,  static_cast<NativeScreenshotManagerCxxSpec*>(&turboModule)->jsInvoker_, static_cast<T*>(&turboModule));
  }

  static jsi::Value __takeScreenshot(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {
    static_assert(
      bridging::getParameterCount(&T::takeScreenshot) == 3,
      "Expected takeScreenshot(...) to have 3 parameters");
    return bridging::callFromJs<jsi::Value>(rt, &T::takeScreenshot,  static_cast<NativeScreenshotManagerCxxSpec*>(&turboModule)->jsInvoker_, static_cast<T*>(&turboModule),
      count <= 0 ? throw jsi::JSError(rt, "Expected argument in position 0 to be passed") : args[0].asString(rt),
      count <= 1 ? throw jsi::JSError(rt, "Expected argument in position 1 to be passed") : args[1].asObject(rt));
  }
};
```

This reduces the generated code from 101 lines to 31 - **REDUCTION of 2/3**

Reviewed By: javache

Differential Revision: D83810977

fbshipit-source-id: 6d0c0271846c8544399c7050b7331b0180cbbadf
2025-10-13 20:21:32 -07:00
David Vacca 1a85185cfc Deprecate ShadowNodes on the codegen (#53184)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/53184

Deprecate ShadowNodes on the codegen

changelog: [internal] internal

Reviewed By: shwanton

Differential Revision: D79911692

fbshipit-source-id: ad24488d186fd5b82c3953a75f52be03e4770cc2
2025-08-09 04:39:35 -07:00
Riccardo Cipolleschi e547f466ee Improve codegen to add getDebugProps to components (#53135)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/53135

Our Codegenerated components are not generating code for `getDebugProps`. This change modifies Codegen to add those functions for all the codegen components.

## Changelog:
[General][Added] - Added getDebugProps to codegen

## Facebook:
`getDebugProps` are required by Fantom to write tests. However, we can't generate these function for third party components, because codegen can generate arbitrary structs and we don't have a generic `toString()` method that can be used or automatically generated by C++.

By generating this function only for Core Components, we can ensure that we can write Fantom tests without breaking all the users of React Native.

Reviewed By: rubennorte

Differential Revision: D79805145

fbshipit-source-id: 0e41c65fc30eaa886a05557ca233fb0a9cb18a71
2025-08-08 06:47:23 -07:00
David Vacca c2f39cfdd8 Revert Refactor ViewManagerInterfaces codegen to generate kotlin classes (#52593)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52593

Revert Refactor ViewManagerInterfaces codegen to generate kotlin classes since commands are not respecting nullability

changelog: [internal] internal

Reviewed By: bvanderhoof

Differential Revision: D78308183

fbshipit-source-id: f3d8017d4bc6473deef0fd49c000543913905cd9
2025-07-14 21:22:21 -07:00
David Vacca 79ca9036d3 Refactor ViewManagerInterfaces codegen to generate kotlin classes (#52545)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52545

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

This diff refactors the ViewManagerInterfaces codegen to generate kotlin classes,

As a consequence of this change, there are some ViewManagerInterfaces that have changed their APIs

## Changelog: [Android][Breaking] - Migrate ViewManagerInterfaces to kotlin. Some types in code generated ViewManagerInterfaces might differ. e.g. this will start enforcing nullability in parameters of viewManagerInterface methods (e.g. String commands parameters are not nullable, view params are not nullable in any method, etc)

Reviewed By: cortinico

Differential Revision: D78118738

fbshipit-source-id: cdd9e660e55397bd0936efce1c5aaf90c2946b7a
2025-07-13 19:18:26 -07:00
Nicola Corti 2d0aa1a747 Revert Refactor ViewManagerInterfaces codegen to generate kotlin classes
Summary:
reverting Refactor ViewManagerInterfaces codegen to generate kotlin classes because of warning in OSS, we will reland after 0.81 cut

Changelog: [Android][Breaking] - Revert of Migrate ViewManagerInterfaces to kotlin. Some types in code generated ViewManagerInterfaces might differ. e.g. this will start enforcing nullability in parameters of viewManagerInterface methods (e.g. String commands parameters are not nullable, view params are not nullable in any method, etc)

Reviewed By: lenaic, mlord93

Differential Revision: D77759777

fbshipit-source-id: c24b216b231cdc53296d8c9fca8d789d80daa596
2025-07-04 02:48:42 -07:00
David Vacca 76ff1aa5c6 Refactor ViewManagerInterfaces codegen to generate kotlin classes (#51735)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51735

This diff refactors the ViewManagerInterfaces codegen to generate kotlin classes,

As a consequence of this change, there are some ViewManagerInterfaces that have changed their APIs

## Changelog: [Android][Breaking] - Migrate ViewManagerInterfaces to kotlin. Some types in code generated ViewManagerInterfaces might differ. e.g. this will start enforcing nullability in parameters of viewManagerInterface methods (e.g. String commands parameters are not nullable, view params are not nullable in any method, etc)

Reviewed By: javache

Differential Revision: D75719542

fbshipit-source-id: 7e9aa7ccc24e827bd7b6df72b3302e852932e731
2025-07-03 12:19:42 -07:00
Nick Lefever c6608685cb Mark prop diffing availability for codegen props (#52246)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52246

This diff adds the required override to codegen props to make the `FabricMountingManager` aware of the availability of a prop diffing implementation for native components using codegen props.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234066

fbshipit-source-id: 8e95628348f491c5ee08609bc7d7b3d30bc7151b
2025-06-25 18:28:22 -07:00
Nick Lefever 53ce247dbd Add codegen for MixedType diffing (#52266)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52266

Native components may use `MixedType` properties in rare cases to hold untyped data. This diff adds support for serializing and prop diffing these types of props so that all of the props and object fields would be included in prop diffing results.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77307169

fbshipit-source-id: ae6b00207ef857c9cfa4bdf9c235972915410a29
2025-06-25 18:28:22 -07:00
Nick Lefever e441954c82 Add codegen for ArrayType diffing (#52244)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52244

The ArrayType props converts to std::vector. This prompted the need for `toDynamic(const T&)` conversion functions as this breaks to potential reliance on all type instances having a `toDynamic()` function available. This includes:
- array of arrays types
- array of objects types
- object with arrays

The ArrayType conversion uses the availability of the `toDynamic` conversion methods for all supported types to convert the values stored by the `std::vector` to `folly::dynamic` values to be stored on a `folly::dynamic::array`.

The diff removes unnecessary conversion methods implemented previously for the core components prop diffing. These are now handled by the generic `toDynamic(const std::vector<T>&)` conversion method.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234065

fbshipit-source-id: 97a3b175ff07fe4a6de3adb14ee6cb42db1a2cfe
2025-06-25 18:28:22 -07:00
Nick Lefever b50ad49a4d Add codegen for ObjectType diffing (#52243)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52243

Building on the availability of `toDynamic` conversion methods for all supported property types, this diff adds support for diffing of `ObjectType` props.

The template adds the generation of a default comparator for the generated C++ struct. The struct also gains a `toDynamic` conversion method that will convert each property of the object type to a `folly::dynamic` value.

Primitive types make use of the implicit conversion supported by `folly::dynamic`, all other types are converted using `toDynamic`.

The `toDynamic` logic is implemented as a method defined on the struct to avoid increased binary size when required multiple times by the prop diffing implementation.

The external `toDynamic` conversion function calls the struct method directly. This enables support for converting object types using object types within their props.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234064

fbshipit-source-id: 21deb3104303aa374fb65b969af57a6aca6db38c
2025-06-25 18:28:22 -07:00
Nick Lefever 8c806ec31b Add codegen for DimensionType diffing (#52242)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52242

Codegen supports `DimensionType` props which represents a YGValue. This diff adds a conversion to `folly::dynamic` supporting all the existing value types `YGValue` can represent.

This completes codegen support for all allowed `ReservedPropTypeAnnotation` prop types.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234061

fbshipit-source-id: 6c3aef5e3ab0459d8a68ebd8efaccfecb83b0b08
2025-06-25 18:28:22 -07:00
Nick Lefever a164874b1a Add codegen for EnumType diffing (#52241)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52241

Add support for converting string and int32 enum types to `folly::dynamic` and generating the correct property diffing for it conditionally adding the prop value to the prop diff result.

This diff updates the template to convert the enum back to the original string representation provided from the JS side based on the current generated C++ enum value.

The string enum re-uses the existing `toString` conversion. The number enum generates the switch-case mapping required to map back the C++ enum value to the original value assigned to it.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234070

fbshipit-source-id: 8c669d5b2e21bd6022c6ba36149465495e4d4bf3
2025-06-25 18:28:22 -07:00
Nick Lefever 9b82e706fb Add codegen for PointPrimitive prop type diffing (#52238)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52238

Add prop diffing codegen for `PointPrimitive` prop type by adding a `toDynamic` conversion for the struct and the prop diffing conditional result update.

The addition of the `toDynamic` function will allow for converting the type when used in array and object types.

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234062

fbshipit-source-id: d0f52e8fd78ac7712925ea2a47cdd0fe3392d5b0
2025-06-25 04:33:12 -07:00
Nick Lefever da0938edfd Add toDynamic conversion function for ImageSource (#52237)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/52237

For array props conversion following later in this stack, each type should have a toDynamic conversion available that can be called upon to convert all supported types to a `folly::dynamic` result.

This diff adds the toDynamic conversion function for `ImageSource`

 Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D77234063

fbshipit-source-id: 392cbaf172595936f7f66faa824900dadd58bdcf
2025-06-25 04:33:12 -07:00
David Vacca 3903ce0a48 Update format for codegen prop diffing (#51644)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51644

This diff updates the format for codegen prop diffing in Android

changelog: [internal] internal

Reviewed By: shwanton

Differential Revision: D75476172

fbshipit-source-id: ec1c68ae1eb652fe9986386302969f9258983d39
2025-05-27 17:55:11 -07:00
David Vacca da5d15ba0e Add support to diff ImageSource props (#51643)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51643

Add support to diff ImageSource props

/react-native/ReactCommon/react/renderer/imagemanager/primitives.h

changelog: [internal] internal

Reviewed By: javache

Differential Revision: D69497848

fbshipit-source-id: 56afe1d8601f7f4dc5dab815b6e534d7c63f651b
2025-05-27 17:55:11 -07:00
David Vacca ad0ea17ae9 Add support to diff Point props (#51650)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51650

This diff adds support to diff props with Point type

changelog: [internal] internal

Reviewed By: mlord93

Differential Revision: D75469451

fbshipit-source-id: a6844b691d8e32326d04c2bd51e6509980feb611
2025-05-27 17:55:11 -07:00
David Vacca 20da141f5f Add support for diffing ColorPrimitive props (#51641)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51641

Add support for diffing ColorPrimitive props

changelog: [internal] internal

Reviewed By: rshest

Differential Revision: D69493546

fbshipit-source-id: 7ad6a28bd42014a771c168d8d6a6d2349629f670
2025-05-27 17:55:11 -07:00
David Vacca 26d40e40e1 Add support for diffing primitve type props (#51649)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51649

 Add support for diffing primitve type props

changelog: [internal] internal

Reviewed By: NickGerleman

Differential Revision: D69491368

fbshipit-source-id: 2b882b349e9d1bd3a9012bae3c3e0a06be2fa0e3
2025-05-27 17:55:11 -07:00
David Vacca 2df200db3f Extend getDiffProps method to support no changes of props (#51646)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51646

Extend getDiffProps method to support no changes of props

changelog: [internal] internal

Reviewed By: lenaic

Differential Revision: D69487497

fbshipit-source-id: 2cb91f1cc6cba84100750ce5dda5824824c923fe
2025-05-27 17:55:11 -07:00
David Vacca 3609d070eb Extend getDiffProps method to call HostPlatformViewProps (#51638)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51638

Extend getDiffProps method to call HostPlatformViewProps

changelog: [internal] internal

Reviewed By: lenaic

Differential Revision: D69487495

fbshipit-source-id: 4d2b508f116ec0618b42981c0880361c3d8a871a
2025-05-27 17:55:11 -07:00
David Vacca 1a43fd7927 Prototype to create getDiff method using codegen (#51637)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51637

Start prototype to create getDiff method using js codegen

changelog: [internal] internal

Reviewed By: rshest

Differential Revision: D69487496

fbshipit-source-id: 1547a7302381333bf9b005153b44de5621bc56c4
2025-05-27 17:55:11 -07:00
Tim Yung 1977dd6596 RN: Sort Pragmas in Headers (#51554)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51554

Sorts pragma directives file headers in React Native.

Changelog:
[Internal]

Reviewed By: SamChou19815

Differential Revision: D75264593

fbshipit-source-id: 9e4b253dd0fc94dc2fc469d7114b93a8aae305f4
2025-05-22 21:18:53 -07:00
Yannick Loriot 12ced22f70 Improve error messages when enum members are missing (#51502)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51502

While working on a case for Editor on mac, it took me a while to figure out what enum was the root cause:

 {F1978470518}

Adding the blaming enum name in the error message would have made my life much easier.

## Changelog:

[GENERAL][Added] - Improve error messages when enum members are missing

Reviewed By: rshest

Differential Revision: D75141414

fbshipit-source-id: 3625d817b218788891252add225f8fffb99e3145
2025-05-21 14:31:25 -07:00
Tim Yung 84de8a075e RN: Delete @oncall Annotations (#51416)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51416

Deletes `oncall` annotations from the `facebook/react-native` repository.

Changelog:
[Internal]

Reviewed By: javache

Differential Revision: D74902524

fbshipit-source-id: 32a6a5b2ff27281792d572f151e2b094d9a79029
2025-05-17 16:18:05 -07:00
Jakub Grzywacz 4d7c4bd6e8 Fix ImageSource require (#50963)
Summary:
In react-native-svg, I found that the `Image` component stopped working starting with `react-native@0.79`. After some debugging, I traced the issue to the migration of `Libraries/Image` to the new export syntax (see https://github.com/facebook/react-native/commit/8783196ee540f8f78ce60ad20800338cc7645194). To fix this, I updated the import to match other requires, similar to https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js#L84.

## Changelog:

[GENERAL] [FIXED] - Fix codegen ImageSource require

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

Test Plan:
`validAttributes` process should be a function instead of object with a default property.

Before:
<img width="1041" alt="image" src="https://github.com/user-attachments/assets/9fbc9e9f-6c45-4b0b-adb8-2eb911676fe1" />

After:
<img width="1005" alt="image" src="https://github.com/user-attachments/assets/ee594103-90da-4917-8252-72f4ecfc28e1" />

Reviewed By: Abbondanzo

Differential Revision: D73778127

Pulled By: huntie

fbshipit-source-id: ae80c770e8e578794ae1356751f170ff955e1f5a
2025-04-28 10:30:21 -07:00
Jakub Piasecki 5349b7c7b5 Update codegen to support namespaced types (#49950)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49950

Changelog: [GENERAL][CHANGED] - Changed `react-native-codegen` to support types under `CodegenTypes` namespace

## Summary

Currently, codegen relies on deep importing types under `react-native/Libraries/Types/CodegenTypes` to be properly type-checked. Updating codegen to support types under a single namespace will enable us to provide a single import from the package with access to all relevant types.

Reviewed By: huntie

Differential Revision: D70967809

fbshipit-source-id: 41241dcc51965f4243acd34e8b63475cb56ca67a
2025-03-17 07:26:17 -07:00
Phil Pluckthun 8f19201c5e refactor(react-native-codegen): Replace jscodeshift with @babel/core (#49641)
Summary:
`jscodeshift` is only used in one module (`src/generators/components/GenerateViewConfigJs.js`, but depends on a rather complex dependency chain and has a rather large maintenance burden relative to what it's used for and the value it adds in the codebase.

Since the `GenerateViewConfigJs` module creates simple templates, using `babel/core` (and implicitly `babel/template` and `babel/types`) is a lot simpler and changes little code. The only change this introduces to the output are formatting changes (`singleQuote` and `trailingCommas` options are discarded). The code is otherwise functionally identical.

## Changelog:

[INTERNAL] [CHANGED] - Drop jscodeshift dependency from react-native/codegen

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

Test Plan:
This was tested against a React Native build with the `react-native/babel-plugin-codegen` plugina active and using the snapshots in the repo itself. While the snapshots have changed in formatting, none of the outputs change the code's AST.

<details>
<summary>
Example output from <code>react-native/babel-plugin-codegen</code> to supplement the snapshot tests
</summary>

This is the example bundling output of `AndroidSwipeRefreshLayout`. This demonstrates that both the view config output and the `Commands` export continue to be generated correctly.

```js
var _interopRequireDefault = require(_dependencyMap[0]);
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.__INTERNAL_VIEW_CONFIG = exports.Commands = undefined;
var _codegenNativeCommands = _interopRequireDefault(require(_dependencyMap[1]));
var _codegenNativeComponent = _interopRequireDefault(require(_dependencyMap[2]));
var React = _interopRequireWildcard(require(_dependencyMap[3]));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
var NativeComponentRegistry = require(_dependencyMap[4]);
var _require = require(_dependencyMap[5]),
  ConditionallyIgnoredEventHandlers = _require.ConditionallyIgnoredEventHandlers;
var _require2 = require(_dependencyMap[6]),
  dispatchCommand = _require2.dispatchCommand;
var nativeComponentName = 'AndroidSwipeRefreshLayout';
var __INTERNAL_VIEW_CONFIG = exports.__INTERNAL_VIEW_CONFIG = {
  uiViewClassName: "AndroidSwipeRefreshLayout",
  directEventTypes: {
    topRefresh: {
      registrationName: "onRefresh"
    }
  },
  validAttributes: {
    enabled: true,
    colors: {
      process: (req => 'default' in req ? req.default : req)(require(_dependencyMap[7]))
    },
    progressBackgroundColor: {
      process: require(_dependencyMap[8]).default
    },
    size: true,
    progressViewOffset: true,
    refreshing: true,
    ...ConditionallyIgnoredEventHandlers({
      onRefresh: true
    })
  }
};
var _default = exports.default = NativeComponentRegistry.get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG);
var Commands = exports.Commands = {
  setNativeRefreshing(ref, value) {
    dispatchCommand(ref, "setNativeRefreshing", [value]);
  }
};
```

</details>

Reviewed By: yungsters

Differential Revision: D70580474

Pulled By: elicwhite

fbshipit-source-id: 85bc6578b685f19a1565ded8d7e56dc2a1ff1999
2025-03-05 14:06:46 -08:00
Nicola Corti c4c3d3bfbe Do not use $ in identifiers for event emitters. (#49792)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49792

This removes the `$` from the `event` and `payload` identifier inside codegen.
This is causing the `-Wdollar-in-identifier-extension` warning to fire.

As I'm looking into enabling `-Wall -Werror` for React Common, this should be addressed as well.

Changelog:
[Internal] [Changed] -

Reviewed By: cipolleschi

Differential Revision: D70500543

fbshipit-source-id: c593680961b1b98561c3985f92ade5d6ba448ac9
2025-03-03 16:47:46 -08:00
Rubén Norte e630b2ca18 Create specific module in RN to define the types for host instances and host components that ReactNativeTypes defines (#49601)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49601

Changelog: [internal]

This creates a new module in React Native to define some of the types related to `HostInstance` that are currently defined in `ReactNativeTypes` (synced from the React repo).

We want to remove the types from `ReactNativeTypes` so this is a necessary initial step.

Reviewed By: huntie

Differential Revision: D69996010

fbshipit-source-id: 21cfed4c222e22332936e56aca895fe578809792
2025-02-24 05:32:43 -08:00
Iwo Plaza 2b30aa5cc8 Migrate Libraries/Utilities/differ/*.js to export syntax (#49332)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49332

## Motivation
Modernising the RN codebase to allow for modern Flow tooling to process it.

## This diff
- Migrates `Libraries/Utilities/differ/*.js` to use the export syntax.
- Updates deep-imports of these files to use `.default`
- Updates codegen with a compat layer
- Updates the current iteration of API snapshots (intended).

Changelog:
[General][Breaking] - Deep imports to `Libraries/Utilities/differ/...` with `require` syntax need to be appended with '.default'.

Reviewed By: yungsters

Differential Revision: D69467423

fbshipit-source-id: 2e58a0b9711e9bdf5ca907a5b2252584f6fec9bc
2025-02-12 05:30:20 -08:00
Pieter De Baets abd7259de4 Allow UnsafeMixed as Array value in codegen (#49324)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49324

Provide Android component codegen a bit more flexibility by allowing `$ReadOnlyArray<UnsafeMixed>` and avoid casting in the view manager.

Changelog: [General][Added]

Reviewed By: fabriziocucci

Differential Revision: D69454101

fbshipit-source-id: c210647deffeb01b7db8aa07266e58c42acf14ba
2025-02-11 07:11:18 -08:00
Iwo Plaza 4101a2f0b6 Add compat layer for react-native-codegen and processColorArray (#49063)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49063

## Motivation
Modernising the RN codebase to allow for modern Flow tooling to process it.

## This diff
- Updates react-native-codegen to generate ViewConfigs that are compatible with react-native both before and after the export syntax migration.

Changelog: [Internal]

Reviewed By: huntie

Differential Revision: D68894819

fbshipit-source-id: fca46c1b91c15e22f1e1128ce8621c05341e2fe6
2025-01-30 07:16:54 -08:00
Iwo Plaza 156ee5bee7 Migrate StyleSheet/processColorArray.js to use export syntax (#48905)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48905

## Motivation
Modernising the react-native codebase to allow for ingestion by modern Flow tooling.

## This diff
- Updates `Libraries/StyleSheet/processColorArray.js` to use `export` syntax.
- Appends `.default` to requires of the changed files.
- Updates test files.
- Updated View Config codegen (requires an MSDK bump).
- Updates the public API snapshot *(intented breaking change)*

Changelog:
[General][Breaking] - Files inside `Libraries/Text`, `Libraries/Share` and `Libraries/Settings` use `export` syntax, which requires the addition of `.default` when imported with the CJS `require` syntax.

Reviewed By: robhogan

Differential Revision: D68564304

fbshipit-source-id: 2fbd058be1a715cccfce4f2a68146118d8ac66ad
2025-01-28 09:46:50 -08:00
Dawid Małecki f36bfe5dfa Remove redundant {||} syntax (#48686)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48686

Changelog:
[Internal] - Removed redundant `{||}` syntax

Reviewed By: javache

Differential Revision: D68205038

fbshipit-source-id: f7d3271142b6443a5859c3b668b7aebd3ce3ef3f
2025-01-15 07:07:01 -08:00
Rayner Kristanto 0f1d4704df Revert D68017325: Migrate StyleSheet/*.js to use export statements
Differential Revision:
D68017325

Original commit changeset: 3c5b94742f10

Original Phabricator Diff: D68017325

fbshipit-source-id: d7ea1edfe9cca151560e9c0e5554a07153cdb8da
2025-01-14 15:22:26 -08:00
Iwo Plaza e4d969a4ab Migrate StyleSheet/*.js to use export statements (#48609)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48609

# Motivation
This is an attempt at modernizing the export syntax in some of the files in `Libraries/StyleSheet/`. It will allow these files to get properly ingested by modern Flow tooling.

# This diff
- Migrates the use of `module.exports` into `export default` for files located in `Libraries/StyleSheet/*.js`. Some files were omitted due to ballooning complexity, but will be addressed in other Diffs.
- Updating internal *require*s to use ".default", no product code seems to be affected.
- Migrating `require`s into `import`s where applicable, taking into account the performance implications (context: https://fb.workplace.com/groups/react.technologies.discussions/permalink/3638114866420225/)
- Updates the current iteration of API snapshots (intended).
- Updates `react-native-codegen`'s require of processColorArray, analogous to D42346452.

Changelog:
[General][Breaking] - Deep imports from some files in `StyleSheet/` can break when using the `require()` syntax, but can be easily fixed by appending `.default`

Reviewed By: javache

Differential Revision: D68017325

fbshipit-source-id: 3c5b94742f101db0b2914c91efab6003dba2b61a
2025-01-14 05:34:18 -08:00
David Vacca db57080e08 Refactor ViewManager codegen to use new ViewManagerInterface (#48549)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48549

Refactor ViewManager codegen to use new ViewManagerInterface

changelog: [internal] internal

Reviewed By: javache

Differential Revision: D67957884

fbshipit-source-id: 7abcd453580ab2219770fd1aff780ba2977dfc8a
2025-01-10 13:58:28 -08:00
Tom Van Laerhoven 13780126d3 Fix generated EventEmitter code for nested objects in arrays. (#47514)
Summary:
This PR fixes the code for generating EventEmitter C++ code in case nested objects in arrays are used.

```typescript
export interface NativeProps extends ViewProps {
  onEvent: DirectEventHandler<
    Readonly<{
      payloadArray: Readonly<
        {
          obj: Readonly<{ str: string }>
        }[]
      >
    }>
  >;
}

export default codegenNativeComponent<NativeProps>('SomeComponent');
```

In this case the generated `EventEmitters.cpp` code would contain:

```c
obj.setProperty(runtime, "str", payloadArrayValue,obj.str);
```

while

```c
obj.setProperty(runtime, "str", payloadArrayValue.obj.str);
```

is expected.

## Changelog:

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

Pick one each for the category and type tags:

[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message

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

[GENERAL] [FIXED] - Codegen: Support nested objects in arrays

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

Test Plan: Tested with the reproduction case above to verify correct output.

Reviewed By: javache

Differential Revision: D65848670

Pulled By: elicwhite

fbshipit-source-id: 0021e87bc7213fff615465cab8554cc1a2159522
2024-11-20 16:25:34 -08:00
Nick Gerleman 7fb3d830be Breaking: Remove BaseViewManagerInterface (#46809)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46809

BaseViewManagerInterface isn't adding much value right now. It was added in D16984121 to allow codegen generated ViewManager delegates to apply to view managers which derive from ViewMangager instead of BaseViewManager (if they did some cleverness, to make VM delegate apply to a no-op class, still implementing all of BaseViewManager's methods).

All of the cases where that was used have since been moved to `SimpleViewManager`, and `BaseViewManagerAdapter` (needed to wire this together) doesn't exist anymore, so it's not possible to take any advantage of this interface existing. We should remove it, since its existence  is a source of error (e.g. it was missing setters for `accessibilityValue` or those related to pointer events), and is more generally confusing for anyone adding to `BaseViewManager` in the future.

This is a breaking change, because there are some libraries which vendor a copy of generated ViewManagerDelegate when building against legacy arch to be able to share code normally generated at build time. That means these will need to be updated to maintain compatibility with RN versions of 0.77+ with new arch disabled. This will not effect compatibility of these libraries against the default new arch, and the updated delegate is still compatible with older RN version.

```
    sourceSets.main {
        java {
            if (!isNewArchitectureEnabled()) {
                srcDirs += [
                    "src/paper/java",
                ]
            }
        }
    }
```

1. `react-native-picker/picker`
2. `rnmapbox/maps`
3. `react-native-gesture-handler`
4. `react-native-screens`
5. `react-native-svg`
6. `react-native-safe-area-context`
7. `react-native-pdf`

Changelog:
[Android][Breaking] - Remove BaseViewManagerInterface

Reviewed By: cortinico

Differential Revision: D63819044

fbshipit-source-id: 7e4935c8e43706b168f0f599a6676e8abfa66937
2024-10-09 14:49:01 -07:00
Rubén Norte 4b82922ac5 Fix reported properties for native modules (#46788)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46788

Changelog: [internal]

This fixes the reported keys for C++ TurboModules:
```
import MyNativeCppModule from 'MyNativeCppModule';

Object.keys(MyNativeCppModule); // [] - expected
Object.keys(Object.getPrototypeOf(MyNativeCppModule)); // [] - NOT expected
```

Before, we were trying to read the properties from the method map in the public `TurboModule`, but in this implementation all the logic is actually in its delegate (also a `TurboModule` instance, yeah, confusing).

This fixes the issue by forwarding the call to the delegate that has the right information.

Reviewed By: javache

Differential Revision: D63761381

fbshipit-source-id: 90bd216efa0f60352c5ca341d210d83239c80dba
2024-10-02 12:25:06 -07:00
Pieter De Baets 5b5e150eaf Fix Cxx TurboModule methods not being cached (#46751)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46751

rubennorte noticed that some turbo module methods were not getting cached on the jsRepresentation as expected. This is caused by the react-native-codegen wrappers we generate overriding the `get` method and bypassing this caching layer. Instead they should be overriding `create` to lazily allocate new properties. To prevent this from re-occuring, I've made `get` final so no other overrides can happen.

## Changelog:

[General][Fixed] Properties for C++ TurboModules using codegen were not correctly cached
[General][Breaking] TurboModule::get is now a final method, override `create` to customize property lookup

Reviewed By: rubennorte

Differential Revision: D63665966

fbshipit-source-id: c614901c2f0d698147ec9ba36a4b592ed3d37652
2024-10-02 05:10:33 -07:00
Christoph Purrer ad3df84668 Add EventEmitter Code-gen support for Java and ObjC Turbo Modules (#45119)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45119

## Changelog:

[iOS][Added] - Add EventEmitter Code-gen support for Java and ObjC Turbo Modules

Reviewed By: RSNara

Differential Revision: D58929417

fbshipit-source-id: 5208ba5ecb5882d47c3827c2aa8e3a54a3d7f2b6
2024-07-01 14:42:46 -07:00
Christoph Purrer ed5f558a6c Code-generate an optional base class to use for every NativeModule (#45113)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45113

## Changelog:

[iOS][Added] - Code-generate an optional base class to use for every NativeModule

Extend RN Code-gen to generate a NativeModule base class for each ObjC Turbo Modules.

Its usage is not mandatory now, but would become for future features to add

A practial first step would be to migrate

https://github.com/facebook/react-native/blob/main/packages/react-native/ReactCommon/react/nativemodule/core/platform/ios/ReactCommon/RCTTurboModule.h#L157-L160

from the `protocol` to the default `interface` and then provide a default implementation for it

Reviewed By: RSNara

Differential Revision: D58907395

fbshipit-source-id: a6b0ef97a5c7f5bb0c53a4cb6fd83d2e55306953
2024-06-28 13:29:15 -07:00
Christoph Purrer fd618819c7 Add EventEmitter code-gen support for C++ Turbo Modules (#44809)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44809

Adding react-native-codegen parser support for a new `EventEmitter` property type on C++ Turbo Modules.

It is possible to later expand this feature to other languages (Java, ObjC).

## Characteristics

An `EventEmitter` must:
- be non null:
 `EventEmitter<string>` works, `?EventEmitter<string>` does NOT
- have a non null eventType:
  `EventEmitter<number>` works, `EventEmitter<?number>` does NOT
- have at most 1 eventType, `void` is possible as well:
  `EventEmitter<>` or `EventEmitter<MyObject>` work - `EventEmitter<number, string>` do NOT
- have a concrete eventType, `{}` is not allowed
  `EventEmitter<{}>` does NOT work
- be used in `Cxx` Turbo Modules only at this time

## Example

For these 4 eventEmitters in on an RN JS TM spec
```
  +onPress: EventEmitter<void>;
  +onClick: EventEmitter<string>;
  +onChange: EventEmitter<ObjectStruct>;
  +onSubmit: EventEmitter<ObjectStruct[]>;
```
We now generate this code:
1.) in the spec based header `{MyModuleName}CxxSpec` in the constructor:
```
      ... // existing code
      eventEmitterMap_["onPress"] = std::make_shared<AsyncEventEmitter<>>();
      eventEmitterMap_["onClick"] = std::make_shared<AsyncEventEmitter<OnClickType>>();
      eventEmitterMap_["onChange"] = std::make_shared<AsyncEventEmitter<OnChangeType>>();
      eventEmitterMap_["onSubmit"] = std::make_shared<AsyncEventEmitter<OnSubmitType>>();
```
2.) as `protected` functions
```
  void emitOnPress() {
      std::static_pointer_cast<AsyncEventEmitter<>>(delegate_.eventEmitterMap_["onPress"])->emit();
  }

  void emitOnClick(const OnClickType& value) {
      std::static_pointer_cast<AsyncEventEmitter<OnClickType>>(delegate_.eventEmitterMap_["onClick"])->emit(value);
  }

  void emitOnChange(const OnChangeType& value) {
      std::static_pointer_cast<AsyncEventEmitter<OnChangeType>>(delegate_.eventEmitterMap_["onChange"])->emit(value);
  }

  void emitOnSubmit(const OnSubmitType& value) {
      std::static_pointer_cast<AsyncEventEmitter<OnSubmitType>>(delegate_.eventEmitterMap_["onSubmit"])->emit(value);
  }
```

## Changelog:

[General] [Added] - Add EventEmitter code-gen support for C++ Turbo Modules

Reviewed By: javache

Differential Revision: D57407871

fbshipit-source-id: 2345cc6dacf0cb0d45f8a374ad9d4cbf8082f9d6
2024-06-11 19:19:22 -07:00
zhongwuzw 1a1795a537 Fixes enum codegen value cases (#44654)
Summary:
Fixes https://github.com/facebook/react-native/issues/44632

## Changelog:

[GENERAL] [FIXED] - [codegen] Fixes enum codegen value cases

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

Test Plan: https://github.com/facebook/react-native/issues/44632

Reviewed By: cipolleschi, dmytrorykun

Differential Revision: D58135645

Pulled By: cortinico

fbshipit-source-id: 5c0634ef1d1d7375d2ecfcf7f916d67fd39b7300
2024-06-07 07:53:59 -07:00
Christoph Purrer 07261d0408 Use hasteModuleName for C++ Turbo Module structs (#44630)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44630

Changelog:
[General][Breaking] Use hasteModuleName for C++ Turbo Module structs

This changes the names of C++ Turbo Modules structs to use the `hasteModuleName`.

Example: `NativeMyAbcModule.js` with this spec:
```
export type ValueStruct = {
  x: number,
  y: string,
  z: ObjectStruct,
};

export interface Spec extends TurboModule {
  +getValueStruct: () => ValueStruct
}

export default (TurboModuleRegistry.get<Spec>('MyAbcModuleCxx'): ?Spec);
```

Before now we generated a base C++ struct with the name:
```
MyAbcModuleCxxValueStruct
           ^^^
```

Now the generate name is:
```
NativeMyAbcModuleValueStruct
^^^^^^
```

## Changes:
- No `Cxx` injected anymore
- Ensure base struct is `Native` prefixed (all RN JS TM specs start with it)

## Why?
- The `Cxx` extension is a temporary hint to react-native-codegen to enable extra capabilities and might disappear eventually
- The C++ base struct name should be 'stable'
- The name of the exported TM JS spec `TurboModuleRegistry.get<Spec>(...)` is abritrary, the hasteName is not
- The name of the RN JS TM spec must start with `Native` which better guarantees a consistent naming scheme for these generated base class
- The C++ Turbo Module base class has now the same prefix as the generated structs - `NativeMyAbcModule` for the example above

Reviewed By: cipolleschi

Differential Revision: D57599257

fbshipit-source-id: 4fafe6c7e920737fa766bd7e8e68e521f608e775
2024-05-23 03:28:52 -07:00
Christoph Purrer eb1b42fa8b Sort spec members
Summary:
The motiviation of this change is to produce sorted / stable native module schemas which members are alphabetically sorted. The benefit is mainly for verifying test fixtures as now new test cases will be inserted at predicatable spots.

Changelog: [Internal]

Reviewed By: rshest

Differential Revision: D56741776

fbshipit-source-id: 842af73cac3b4859d2074e6a5206015924e87201
2024-05-02 20:31:50 -07:00
Christoph Purrer 536edf3726 Don't support float enums
Summary:
Changelog: [General][BREAKING] Don't support 'float' enums in Turbo Modules

- The current implementation of 'float enums' in C++ does not work as invalid results are returned.
- At potential fix could still cause rounding errors when crossing language bounaries, e.g. `4.6` can become `4.5599999942..`
- C++ enum classes don't support float: https://eel.is/c++draft/dcl.enum#2.sentence-4

> The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored.

Hence removing the feature of `float enums` for now

Reviewed By: NickGerleman

Differential Revision: D52120405

fbshipit-source-id: 3685ad0629e16ff9db424ba67e07d09df6027553
2024-04-30 21:52:09 -07:00