Commit Graph

118 Commits

Author SHA1 Message Date
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
Alan Lee 639d890dff add missing struct member initialization in Props.h (#44294)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44294

**Problem:**

It was discovered while testing 3 party library, generated member variables in a C++ `struct` in `Props.h` is not initialized.
Also `WithDefault` would not work as well.
(For the problematic case it was a `boolean` but would also apply to other primitive types.)

If there is no default initialization and the component prop is optional and the user of the native component does not set the prop then the variable is never initialized and this is problematic for primitive types in C++ where no initialization results in an undefined behavior.

**Proposed solution:**

(Following C++Core Guideline of [always initialize](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-always).)
Reusing `generatePropsString()` used by `ClassTemplate` to generate props for `StructTemplate` as well.
updated relevant test snapshots.
This change is only concerning the `Props.h` file.

**Changelog:**
[General][Fixed] - fixed `Props.h` created from codegen missing default initializers in C++ `struct`

Reviewed By: cipolleschi

Differential Revision: D56659457

fbshipit-source-id: 0d21ad20c0491a7e8bb718cd3156da65def72f23
2024-04-30 18:29:31 -07:00
Nizam 99f3c241ad fix array enum prop parsing for array enum types (#44123)
Summary:
codegen generates type alias for  array enum props with uint32_t which cause wrong overloaded fromRawValue to call at runtime eventually app to terminate
more detailed info at issue https://github.com/facebook/react-native/issues/43821

## Changelog:

[Internal] [Fixed] - Codegen for array enum props

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

Test Plan: TODO

Reviewed By: cipolleschi

Differential Revision: D56414554

Pulled By: dmytrorykun

fbshipit-source-id: 0ec1b65951bc16ff58dd2b119c97a4e3fac2b161
2024-04-22 10:55:36 -07:00
Riccardo Cipolleschi 46b6453eb6 Fix the Redefinition of 'NativeXXXSpecJSI' error with Frameworks (#44005)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44005

When using frameworks on iOS, there is a possibility that modules import the Spec.h file twice and this might end up in a Redefinition of some symbols and duplication of symbols which ends up in build errors, as reported here: https://github.com/facebook/react-native/issues/42670.

This change adds some [`#include guards`](https://en.wikipedia.org/wiki/Include_guard) in codegen to avoid the redefinition of those symbols if the header is imported/included multiple times.

Note: I also experimented with `#pragma once`, but it looks like Apple is not happy with that directive. [It seems](https://forums.developer.apple.com/forums/thread/739964) that it started working flakely from Xcode 15.

## Changelog:
[General][Fixed] - Make sure that we can't include Codegen symbols multiple times

Reviewed By: cortinico

Differential Revision: D55925605

fbshipit-source-id: 15ca076aace2ffbd03ab8fa8a68a3d8ce0d1ea65
2024-04-11 11:39:43 -07:00
Christoph Purrer 04bf8cfb23 Clean up old Cxx TM member generation (#43710)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/43710

As we had already cut a branch for RN 0.74
https://github.com/facebook/react-native/releases/tag/v0.74.0-rc.1

We can delete this code already

Changelog: [Internal]

Reviewed By: shwanton

Differential Revision: D55511382

fbshipit-source-id: 3ef15af338b5ad31b02e0a1eed7ac873566d9562
2024-03-29 14:39:24 -07:00
Rubén Norte 67b9628af5 Modify native module codegen to throw JS errors when passing null values for non-nullable arguments
Summary:
Changelog: [General][Breaking] Native modules using the codegen now throw an error when called with `null` for optional but not nullable arguments.

## Context

Right now, if you have a native module using the codegen with a method like this:

```
someMethod(value?: number): void;
```

And you call it like this:

```
NativeModule.someMethod(null);
```

The app doesn't throw an error, but it should because this method shouldn't accept `null` according to its type definition.

## Changes

This modifies the codegen to only check for `undefined` in those cases, otherwise trying to cast the value to the expected type and failing if it's `null`.

NOTE: this is technically a breaking change, but if people are using Flow or TypeScript in their projects they're very unlikely to hit this case, because they would've complained if you tried to pass `null` in these cases.

Reviewed By: cipolleschi

Differential Revision: D54206289

fbshipit-source-id: 58f2f2f3009d203b96189d3c66d1ae98a9e4fb36
2024-02-29 13:12:49 -08:00
Rubén Norte 179b684e76 Modify native module codegen to throw JS errors instead of crashing when not passing required parameters
Summary:
Changelog: [General][Fixed] Fixed crash when passing fewer arguments than expected in native modules using codegen

## Context

Right now, if you have a native module using the codegen with a method like this:

```
someMethod(value: number): void;
```

And you call it like this:

```
NativeModule.someMethod();
```

The app crashes.

This happens because the codegen tries to cast the value to the expected type without checking if the argument is within the bounds of the arguments array.

## Changes

This fixes that issue with a change in the codegen to guard against this in the generated code (see changes in the snapshot tests).

Reviewed By: RSNara

Differential Revision: D54206287

fbshipit-source-id: 575af462725515928f8634fccc7a9cb51ca0ce4f
2024-02-27 09:29:53 -08:00
Rubén Norte abbc6eb022 Modify codegen to throw JS errors instead of crashing when passing non-number arguments where RootTags are expected
Summary:
Changelog: [General][Fixed] Fixed crash when passing non-numeric values where RootTag is expected to methods in native modules using codegen

## Context

Right now, if you have a native module using the codegen with a method like this:

```
someMethod(value: RootTag): void;
```

And you call it like this:

```
NativeModule.someMethod('');
```

The app crashes.

This happens because we cast the JS value to a C++ value using the method that asserts (`toNumber`) instead of the one that throws a JS error (`asNumber`).

## Changes

This fixes the crash by using `asNumber` instead of `toNumber`.

Reviewed By: RSNara

Differential Revision: D54206288

fbshipit-source-id: 9398112667e0f26edaf4f8f3b32e79fa8aafde62
2024-02-27 09:29:53 -08:00
Nicola Corti 1e49f93b19 Fix autolinking for local app Fabric components
Summary:
Autolinking local app fabric component requires user to manipulate the C++ code.
This removes this requirement by generating the code necessary to register all the discovered Fabric Components.

I've updated the RN-Tester Android setup to use this mechanism also.

Changelog:
[Android] [Fixed] - Fix autolinking for local app Fabric components

Reviewed By: cipolleschi

Differential Revision: D53710676

fbshipit-source-id: 667af4bcf7fa99563081330aa64d072faf50863b
2024-02-13 11:29:13 -08:00
Nicola Corti b366b4b42e Back out "Fix autolinking for local app Fabric components"
Summary:
Original commit changeset: 28c376fbd08c

Original Phabricator Diff: D53661231

Reviewed By: cipolleschi

Differential Revision: D53709386

fbshipit-source-id: aab2d99327460cc82591f7de5e6e0296f7695cd6
2024-02-13 07:27:54 -08:00
Nicola Corti f9a5b30e5a Fix autolinking for local app Fabric components (#42962)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42962

Autolinking local app fabric component requires user to manipulate the C++ code.
This removes this requirement by generating the code necessary to register all the discovered Fabric Components.

I've updated the RN-Tester Android setup to use this mechanism also.

Changelog:
[Android] [Fixed] - Fix autolinking for local app Fabric components

Reviewed By: RSNara

Differential Revision: D53661231

fbshipit-source-id: 28c376fbd08c326f117f8d420485d63e2b4b1241
2024-02-13 05:29:24 -08:00
Dmitry Rykun 6974697b04 Use paperTopLevelNameDeprecated in generated EventEmitters if defined (#42812)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42812

There is a way of defining events where you specify additional string type parameter in the EventHandler in the spec. This additional type parameter is an overridden top level event name, that can be completely unrelated to the event handler name.
More context here D16042065.

Let's say we have
```
onLegacyStyleEvent?: ?BubblingEventHandler<LegacyStyleEvent, 'alternativeLegacyName'>
```
This will produce the following entry in the view config:
```
topAlternativeLegacyName: {
  phasedRegistrationNames: {
    captured: 'onLegacyStyleEventCapture',
    bubbled: 'onLegacyStyleEvent'
  }
}
```
This means that React expects `topAlternativeLegacyName`.
But the generated EventEmitter looks like this:
```
void RNTMyNativeViewEventEmitter::onLegacyStyleEvent(OnLegacyStyleEvent $event) const {
  dispatchEvent("legacyStyleEvent", [$event=std::move($event)](jsi::Runtime &runtime) {
    auto $payload = jsi::Object(runtime);
    $payload.setProperty(runtime, "string", $event.string);
    return $payload;
  });
}
```
The native component will emit `legacyStyleEvent` (`topLegacyStyleEvent` after normalization) that React will not be able to handle.

This issue only happens on iOS because Android doesn't use EventEmitter currently.

To address this issue we'll use `paperTopLevelNameDeprecated` for the generated EventEmitters if it is defined.

Changelog: [iOS][Fixed] - Fixed support for event name override in component specs.

Reviewed By: cortinico, mdvacca, cipolleschi

Differential Revision: D53310654

fbshipit-source-id: 018d5b11d8d36e2ecf900b9d8d6fe3e2ed71f80b
2024-02-13 04:31:25 -08:00
Dmitry Rykun b32c6c2cc1 Event name normalization (#42586)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42586

Every event name must be normalized.

The normalization strategy is:
1. If it starts with `top` -> do nothing.
2. If it starts with `on` -> replace `on` with `top`.
3. Else -> capitalize the first character and prepend `top`.

We have it for the old renderer on iOS [here](https://github.com/facebook/react-native/blob/a7586947d719a9cd2344ad346d271e7ca900de87/packages/react-native/React/Base/RCTEventDispatcher.m#L12-L21). This one is also used by the interop layer.
Static ViewConfigs being a part of the new renderer [replicate](https://github.com/facebook/react-native/blob/a7586947d719a9cd2344ad346d271e7ca900de87/packages/react-native-codegen/src/generators/components/GenerateViewConfigJs.js#L164-L172) this behavior to match the old rendered.

The Android that we have is incomplete, it is missing the [*2. If it starts with `on` -> replace `on` with `top`*]. This means that some events names that worked with the old renderer would not be compatible with the new renderer + Static ViewConfigs. Specifically every event names that start with `on`.

This diff implements event name normalization on Android.

Changelog: [Internal] - Update event normalization algorithm to match SVCs.

Reviewed By: cortinico

Differential Revision: D50604571

fbshipit-source-id: cef34d8baa2cf31f641be423a16bca7ea9fa20c4
2024-01-29 07:01:26 -08:00
Dmitry Rykun 82f8cf1836 Introduce TypeUtils (#42122)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/42122

This diff introduces the `TypeUtils` directory where we can put platform-specific, context-independent type transformations.

Changelog: [Internal]

Reviewed By: cipolleschi

Differential Revision: D52291837

fbshipit-source-id: 561b9c494aab5bfee3b3c668d3346bbd320e5266
2024-01-03 08:58:30 -08:00
Dmitry Rykun dae4a11e90 Introduce "headerPrefix" codegen option (#41956)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41956

By default, generated Cxx sources for components all end up in same directory. However the include declarations in them look like this:
```
#include <react/renderer/components/${libraryName}/ShadowNodes.h>
```
And not like this:
```
#include "ShadowNodes.h"
```
This works fine with Buck because it supports header prefixes.
To get this working with CocoaPods we define additional `HEADER_SEARCH_PATHS` for our `React-Codegen` pod.
This approach will not work if we want to generate code at the library level and check in the artifacts. That's because we don't have control over the Podspec there, and can't inject those additional `HEADER_SEARCH_PATHS`.

This diff adds the `headerPrefix` argument to the codegen entry point. It is `react/renderer/components/${libraryName}` by default, but can become empty if we want to generate code at the library level, and don't want to deal with this nested header structure.

*Note:* `RNCodegen` runs all the generators [in a loop](https://github.com/facebook/react-native/blob/main/packages/react-native-codegen/src/generators/RNCodegen.js#L263-L275), assuming that the all have same function signature So I had to add the `headerPrefix` argument to all the generators, even to the ones that don't really need it.

Changelog: [General][Added] - Introduce "headerPrefix" codegen option.

Reviewed By: zeyap

Differential Revision: D51811596

fbshipit-source-id: c5c3e1e571c7c4ea2f5354eb9a7b0df6b917fc0c
2023-12-20 09:25:05 -08:00
Christoph Purrer 8183afeb81 Use enum classes in C++ Turbo Modules (#41923)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41923

Changelog: [Internal][BREAKING] Use C++ enum classes in C++ Turbo Modules

Problem:
Using **C styles** `enums` can easily cause compiliation errors if symbol names collide. This code does not compile:
```
enum CustomEnumInt { A = 23, B = 42 };

static int A = 22;
```

This **C++ code**, using `enum classes` compiles:
```
enum class CustomEnumInt : int32_t { A = 23, B = 42 };

static int A = 22;
```

Reviewed By: rshest

Differential Revision: D52098598

fbshipit-source-id: c919bd2e41970c83a032fec91b0537cd6fae8397
2023-12-14 06:54:49 -08:00
Christoph Purrer 19420b7e68 Use C++17 namespace for compoments (#41791)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41791

Same as https://github.com/facebook/react-native/pull/41771 - but this time for compoments

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D51804740

fbshipit-source-id: 87f4db5dabfce4639f16fdcb1b1df0fee338a555
2023-12-05 07:31:57 -08:00
Christoph Purrer b101dd0e34 Use C++17 namespace (#41771)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41771

Changelog: [Internal]

Since we are already enforcing C++20 (and 17), we can set the namespace declaration to the C++17 style

Reviewed By: NickGerleman

Differential Revision: D51789991

fbshipit-source-id: 165d7d4e652d60ab200e2355e084010a02f470a4
2023-12-04 19:07:51 -08:00
Christoph Purrer ef9c164f5f Simplify C++ TM struct generation (#41645)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41645

Right now, when defining concrete structs and Bridging headers for Cxx TMs we need to define their member types twice:
```
using ConstantsStruct =
    NativeCxxModuleExampleCxxBaseConstantsStruct<bool, int32_t, std::string>;

template <>
struct Bridging<ConstantsStruct>
    : NativeCxxModuleExampleCxxBaseConstantsStructBridging<
          bool,
          int32_t,
          std::string> {};
```
Now we only need to define those once
```
using ConstantsStruct =
    NativeCxxModuleExampleCxxConstantsStruct<bool, int32_t, std::string>;

template <>
struct Bridging<ConstantsStruct>
    : NativeCxxModuleExampleCxxConstantsStructBridging<ConstantsStruct> {};
```

This change keeps the existing base types untouched - but they will be removed in the next RN version.

Changelog: [Internal]

Reviewed By: rshest

Differential Revision: D51571453

fbshipit-source-id: 2783bd48bf786ffa80d322d06456b5d6f2d7ba8a
2023-11-27 03:43:28 -08:00
Christoph Purrer c2ac0cc72a react-native-codegen: Cxx TMs > Fixed Undefined Behavior exception when running ASAN builds (#41401)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41401

Changelog: [Internal]

When build Cxx Turbo Modules with Clang's ASAN build mode the apps are crashing at runtime due to, e.g.:
```
runtime error: downcast of address 0x00010dafd618 which does not point to an object of type 'facebook::react::NativePerformance'
0x00010dafd618: note: object is of type 'facebook::react::NativePerformanceCxxSpec<facebook::react::NativePerformance>'
 00 00 00 00  f0 08 49 06 01 00 00 00  4e 61 74 69 76 65 50 65  72 66 6f 72 6d 61 6e 63  65 43 78 78
              ^~~~~~~~~~~~~~~~~~~~~~~
              vptr for 'facebook::react::NativePerformanceCxxSpec<facebook::react::NativePerformance>'
UndefinedBehaviorSanitizer: undefined-behavior FBReactNativeSpecJSI.h:6122:17
```

Where the corresponding generated code looks like

```
NativePerformanceCxxSpec(std::shared_ptr<CallInvoker> jsInvoker)
    : TurboModule(std::string{NativePerformanceCxxSpec::kModuleName}, jsInvoker),
      delegate_(static_cast<T*>(this), jsInvoker) {}
```

This change fixes that problem

AddressSanitizer: stack-use-after-scope shared_ptr.h:634 in std::__1::shared_ptr<facebook::react::InstanceHandle const>::shared_ptr[abi:v160006](std::__1::shared_ptr<facebook::react::InstanceHandle const> const&)
Shadow bytes around the buggy address:
  0x00016cea4a80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4b00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4b80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00016cea4c00: 00 00 00 00 00 00 00 00 f1 f1 f1 f1 f8 f8 f8 f8
  0x00016cea4c80: f8 f8 f2 f2 f2 f2 f8 f8 f2 f2 00 00 f2 f2 f8 f8
=>0x00016cea4d00: f2 f2 f8 f8 f2 f2 00 00 f2 f2[f8]f8 f2 f2 00 00
  0x00016cea4d80: f2 f2 f8 f8 f2 f2 f8 f8 f2 f2 f8 f8 f8 f2 f2 f2
  0x00016cea4e00: f2 f2 f8 f8 f2 f2 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8
  0x00016cea4e80: f8 f8 f8 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f2 f2 f2
  0x00016cea4f00: f2 f2 f8 f8 f3 f3 f3 f3 00 00 00 00 00 00 00 00
  0x00016cea4f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==41992==ABORTING

```

Reviewed By: rshest

Differential Revision: D51183328

fbshipit-source-id: 5aff5b5eecb9d78f9b7438fbdda2c01625c9a4d9
2023-11-09 22:14:57 -08:00
Moti Zilberman d6e0bc714a Enable lint/sort-imports everywhere (#41334)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41334

TSIA.

Changelog: [Internal]

Reviewed By: robhogan

Differential Revision: D51025812

fbshipit-source-id: e10d437be775a6b80946483aa96460f34927f870
2023-11-06 12:59:38 -08:00
Sunbreak af7bf9371c Fix typo of JSI module Cpp codegen (#39604)
Summary:
Fix code generatetion comment from `GenerateModuleH.js` to `GenerateModuleCpp.js`

## Changelog:

[GENERAL] [FIXED] - Fix typo of JSI module Cpp codegen

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

Test Plan: None

Reviewed By: christophpurrer

Differential Revision: D49558245

Pulled By: cortinico

fbshipit-source-id: 28b6a6f4da0f5f973717f785fe21db86179f1996
2023-09-25 12:30:34 -07:00
Samuel Susla 7c928fffcc Remove use of folly::F14FastMap from React Native (#39496)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/39496

changelog: [internal]

Remove use of folly::F14FastMap in favour of std::unordered_map.

Reviewed By: fkgozali

Differential Revision: D48968297

fbshipit-source-id: fa1e80534f817e1e37f932558c09e418a23383e8
2023-09-18 06:27:45 -07:00
Ruslan Shestopalyuk 0c292f3934 Fix bad formatting of generated C++ code (#39212)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/39212

## Changelog:
[Internal] -

Some of the generated C++ code was badly formatted - even though it's normally not supposed to be read by humans, sometimes it's still useful/needed, so it helps when it's more readable.

Reviewed By: christophpurrer

Differential Revision: D48827010

fbshipit-source-id: 3481af68ee6158902007c431e72e631d852c8b3c
2023-08-30 10:40:47 -07:00
Roy Berger f396067cca Add module name constant to class for downstream use (#38295)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/38295

Move constant to class instance so customers can use strongly typed name, feedback from D46159001

Changelog:
[Internal] [Changed] - Add module name constant to codegen'd class for downstream use

Reviewed By: christophpurrer

Differential Revision: D47095993

fbshipit-source-id: 741d0d837bf912d6b32e5f12c5df871563d46686
2023-07-11 13:03:17 -07:00
Nicola Corti 3a246ed024 Remove CallInvoker parameter from toJs method in Codegen (#37832)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37832

This parameter is currently unused and is causing Android builds to fail
as they compile with `-Wall`

This is a follow-up to https://github.com/facebook/react-native/pull/37454/ as that PR updated only the `fromJs` and not the `toJs` method as well.

Changelog:
[Internal] [Changed] - Remove CallInvoker parameter from toJs method in Codegen

Reviewed By: rshest

Differential Revision: D46647110

fbshipit-source-id: 1f3e22aca7a3df11ac02b5c4b89c9311b8b1798c
2023-06-12 12:46:00 -07:00
Christoph Purrer f7dcc65a3f Remove unused jsInvoker from Cxx TM enums (#37454)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37454

Raised here: https://github.com/reactwg/react-native-releases/discussions/54#discussioncomment-5914928

Changelog: [Internal]

Reviewed By: rshest

Differential Revision: D45918922

fbshipit-source-id: 931d2017c37e7327ba472c36e3ac0b29b74d093d
2023-05-17 08:33:36 -07:00
Samuel Susla fc5a7f7567 Remove use of JSI_EXPORT from codegen (#37085)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37085

changelog: [internal]

Props and event emitter does not need to use JSI_EXPORT. Therefore we can remove include of jsi.h as well.

Reviewed By: cortinico, rshest

Differential Revision: D45274824

fbshipit-source-id: dd756258767f787e49d86dc31e18ce581f444362
2023-04-25 12:39:37 -07:00
Genki Kondo b68f53d44f Support events with mixed payloads in codegen (#36942)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36942

Changelog:
[General][Changed] - Support mixed props for events in codegen

Reviewed By: javache

Differential Revision: D44580879

fbshipit-source-id: 52f3b12795af767c038e2db7a4faf46cf2906b95
2023-04-18 13:35:45 -07:00
Pieter De Baets 3759a26214 Avoid property name conflicts in event-emitter codegen (#36591)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36591

If any of the properties used in event-emitter codegen conflict with `event` or `payload`, the generated code will fail to build, even if this generated code isn't used. Since these are quite common keys, prefix them with `$` (still valid C++) to avoid conflicts.

Changelog: [General][Fixed] Resolved property name conflicts in event-emitter codegen

Reviewed By: cipolleschi

Differential Revision: D44274619

fbshipit-source-id: 45e67850c49e082d8f9b1f85bb632d45a9fd4f1d
2023-03-23 09:05:16 -07:00
Pieter De Baets 0a8164d993 Fix off-by-one error in cxx codegen (#36574)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36574

We would previously generate the following codegen for optional args

```
return static_cast<NativeAudioModuleCxxSpecJSI *>(&turboModule)->playAudio(
    rt,
    args[0].asString(rt),
    args[1].isNull() || args[1].isUndefined() ? std::nullopt : std::make_optional(args[1].asString(rt)),
    args[2].isNull() || args[2].isUndefined() ? std::nullopt : std::make_optional(args[2].asString(rt)),
    args[3].asNumber(),
    count < 4 || args[4].isNull() || args[4].isUndefined() ? std::nullopt : std::make_optional(args[4].asObject(rt)),
    count < 5 || args[5].isNull() || args[5].isUndefined() ? std::nullopt : std::make_optional(args[5].asObject(rt)),
    count < 6 || args[6].isNull() || args[6].isUndefined() ? std::nullopt : std::make_optional(args[6].asBool())
);
```

However, the counts checked are off-by-one, causing us to incorrectly process args.

Changelog: [General][Fixed] Issue with TurboModule C++ codegen with optional args

Differential Revision: D44299193

fbshipit-source-id: f00b9f5e09c2f524f9393137346c256d8b6b2979
2023-03-22 16:57:40 -07:00
Genki Kondo 0ae5e50e37 Support mixed props for components
Summary:
Changelog:
[Changed][General] - Support mixed props for components in codegen

Reviewed By: rickhanlonii

Differential Revision: D43894460

fbshipit-source-id: e5faf2f83e6829170cdce550e923c3c09ddff0b0
2023-03-19 16:47:22 -07:00
Ruslan Lesiutin 714b502b0c | RN Monorepo | Migrate to package (#36434)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36434

Changelog: [Internal]

This is a squashed stack of 18 commits, starting from D43202126

allow-large-files

Reviewed By: cortinico

Differential Revision: D43977381

fbshipit-source-id: 0da552ddb85f2f61a0be0ef071915b35f3f8555c
2023-03-17 05:03:25 -07:00
George Zahariev 7fee407564 Update React Native codegen to support Partial as alias of $Partial
Summary:
`Partial` is the new name of `$Partial`

Changelog: [Internal]

Reviewed By: SamChou19815

Differential Revision: D43993220

fbshipit-source-id: 38e8a6bcfa559857b2ab88efee6b904b387bdc0d
2023-03-15 12:13:36 -07:00