Commit Graph

129 Commits

Author SHA1 Message Date
Arushi Kesarwani b417b0c2d5 Extract out FBReactNativeSpec's core components including Unimplemented from auto-generated registry (#51941)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51941

Changelog:
[Android][Fixed] - Extract out FBReactNativeSpec's core components including Unimplemented from auto-generated registry

Extracting out `FBReactNativeSpec`'s core components including `UnimplementedNativeView` from auto-generated registry. Using this `libraryName` to skip merging those modules

Reviewed By: RSNara

Differential Revision: D76371796

fbshipit-source-id: 4cfee0fe80a661f159a5f17e0d4abc60f601ea74
2025-06-13 10:18:50 -07:00
David Vacca 79354eb0b5 Update documentation for codegen options interfaceOnly (#51924)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51924

In this diff I'm updating the documentation for codegen options `interfaceOnly`

changelog: [internal] internal

Reviewed By: arushikesarwani94, cortinico

Differential Revision: D76293414

fbshipit-source-id: 9a8fd752302d4167c8764ce76c0038cd5cc47d7f
2025-06-10 08:03:23 -07:00
Pieter De Baets 9073817925 Add more test coverage for $ReadOnlyArray<UnsafeMixed> in component codegen (#49349)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/49349

Follow-up on D69454101 to add more test coverage for `$ReadOnlyArray<UnsafeMixed>` as a component prop. The new type was missing from the CodegenSchema, which revealed some gaps in tests.

Changelog: [Internal]

Reviewed By: fabriziocucci

Differential Revision: D69488035

fbshipit-source-id: 19895e55e5ec4d89a790f1c388de9eea025a316c
2025-02-12 04:20:08 -08:00
Eli White 25c673e357 Fixing schema types for component command params of Arrays (#48476)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48476

Command param array types were generating invalid schemas due to untyped parser code. The invalid schemas occurred for any alias type, including custom objects and basics like Int32. This was also inconsistent between Flow and TypeScript.

We already had one component utilizing this issue, so this just codifies that support into the schema so it reflects reality. This is only a partial solution. The more full solution would be to fully encode the custom types in the schemas like we do for Native Modules.

# More Information:

Tl;dr, DebuggingOverlay is abusing a FlowFixMe in codegen commands.

## The problem:

The [CodegenSchema](https://www.internalfb.com/code/fbsource/[d3ab2f79b377]/xplat/js/react-native-github/packages/react-native-codegen/src/CodegenSchema.js?lines=220) should be the source of truth for anything that can be in the schema. If something is in the schema that isn't allowed by the types, that's a bug. We have a bug. I'm adding compat-check support for components and it's blowing up on prod schemas because DebuggingOverlay causes an invalid schema.

## The details:

Support for Arrays as arguments in commands was added to the Codegen in D51866557. [Code Pointer](https://fburl.com/code/8yy1rm0p)

The intention appears to be to support arrays of primitives. There is a TODO for supporting complex types.

```
interface NativeCommands {
  +addOverlays: (
    viewRef: React.ElementRef<NativeType>,
    overlayColorsReadOnly: $ReadOnlyArray<string>,
  )
}
```

This support was added to TypeScript in D52046165 where it types the allowed Array arguments to be only

```
{
    readonly type: 'ArrayTypeAnnotation';
    readonly elementType:
    | Int32TypeAnnotation
    | DoubleTypeAnnotation
    | FloatTypeAnnotation
    | BooleanTypeAnnotation
    | StringTypeAnnotation
  };
```

However, because the Parsers are treating the input type as `any`, it isn't safe to pass through an input value into the schema as Flow won't catch mismatches.

The Flow parser just passes it through:

```
{
    type: 'ArrayTypeAnnotation',
    elementType: {
    // TODO: T172453752 support complex type annotation for array element
    type: paramValue.typeParameters.params[0].type,
}
```

Whereas the TypeScript parser has the more correct behavior of validating the inputs and returning specific outputs. Unfortunately, the return type is also typed here as $FlowFixMe, losing most of the benefits.

```
function getPrimitiveTypeAnnotation(type: string): $FlowFixMe {
  switch (type) {
    case 'Int32':
      return {
        type: 'Int32TypeAnnotation',
      };
    case 'Double':
      return {
        type: 'DoubleTypeAnnotation',
      };
    case 'Float':
      return {
        type: 'FloatTypeAnnotation',
      };
    case 'TSBooleanKeyword':
      return {
        type: 'BooleanTypeAnnotation',
      };
    case 'Stringish':
    case 'TSStringKeyword':
      return {
        type: 'StringTypeAnnotation',
      };
    default:
      throw new Error(`Unknown primitive type "${type}"`);
  }
}
```

[DebuggingOverlay](https://fburl.com/code/zfe3ipq7) is abusing this gap in the Flow parser by sticking an Array of Objects in.

```
export type ElementRectangle = {
  x: number,
  y: number,
  width: number,
  height: number,
};

...
  +highlightElements: (
    viewRef: React.ElementRef<DebuggingOverlayNativeComponentType>,
    elements: $ReadOnlyArray<ElementRectangle>,
  ) => void;
...
```

This isn't allowed in the schema, but it seems to fall through the holes of the flow parser and generators.

The resulting schema from Flow is this. Note the GenericTypeAnnotation which isn't allowed to be in the schema.

```
{
    "name": "highlightElements",
    "optional": false,
    "typeAnnotation": {
    "type": "FunctionTypeAnnotation",
    "params": [
        {
            "name": "elements",
            "optional": false,
            "typeAnnotation": {
                "type": "ArrayTypeAnnotation",
                "elementType": {
                    "type": "GenericTypeAnnotation"
                }
            }
        }
    ],
    "returnTypeAnnotation": {
        "type": "VoidTypeAnnotation"
    }
},
```

The TypeScript parser fails with `Error: Unsupported type annotation: GenericTypeAnnotation`.

The generators don't seem to check beyond the ArrayTypeAnnotation so they fall through to generating generic arrays.

```
// ios
elements:(const NSArray *)elements

// android
ReadableArray locations
```

## So how do I fix this?

I think there are a couple of different options here. The key problem is that the Schema types need to represent reality of what can be in the schema.

1. We revert DebuggingOverlay to not use features that aren't supported (I assume nobody would be happy with this, but the change shouldn't have been made in the first place)
2. **(This is the approach taken in this diff)** We add MixedTypeAnnotation to the allowed types in Command arrays and have it generate that and add official support for that to the TypeScript parser as well. That is probably the quickest and easiest approach. It leaves the same type unsafety we have today on the native side.
3. NativeModules seem to have a lot more complex type safety here. They persist the alias type in the schema so that the CompatCheck can check them on changes. And then in C++ they generate structs and RCTConvert functions although for Java and ObjC it looks like they just use the same untyped native code. The matching approach here would be to add `aliasMap` and the whole data to the schema for commands, use that for the compat check, and still generate the same unsafe native code.

```
export type ObjectAlias = {|
  x: number,
  y: number,
|};

export interface Spec extends TurboModule {
  +getAlias: (a: ObjectAlias) => string;
}
```

stores the ObjectAlias in the schema

```
{
  "aliasMap": {
    "ObjectAlias": {
      "type": "ObjectTypeAnnotation",
      "properties": [
        {
          "name": "x",
          "optional": false,
          "typeAnnotation": {
            "type": "NumberTypeAnnotation"
          }
        },
        {
          "name": "y",
          "optional": false,
          "typeAnnotation": {
            "type": "NumberTypeAnnotation"
          }
        },
      ]
    }
  },
  "spec": {
    "methods": [
      {
        "name": "getAlias",
        "optional": false,
        "typeAnnotation": {
          "type": "FunctionTypeAnnotation",
          "returnTypeAnnotation": {
            "type": "StringTypeAnnotation"
          },
          "params": [
            {
              "name": "a",
              "optional": false,
              "typeAnnotation": {
                "type": "TypeAliasTypeAnnotation",
                "name": "ObjectAlias"
              }
            }
          ]
        }
      }
    ]
  }
}
```

and then generates the appropriate structs on the native side and generates [this](https://www.internalfb.com/code/fbsource/[d3ab2f79b377]/xplat/js/react-native-github/packages/react-native-codegen/src/generators/modules/__tests__/__snapshots__/GenerateModuleHObjCpp-test.js.snap?lines=818)

```

Reviewed By: hoxyq

Differential Revision: D67806838

fbshipit-source-id: 31f20455c816fdb6b1a86f8f9d0f6f7d0a452754
2025-01-06 18:42:37 -08:00
Eli White c748b44183 Add command type to CompleteTypeAnnotation (#48475)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48475

This will be needed for the compat-check.

Changelog: [Internal]

Reviewed By: cipolleschi

Differential Revision: D67806831

fbshipit-source-id: b660c9557cafbfa2e713e85a0fd2bdc9edabf537
2025-01-06 18:42:37 -08:00
Eli White 825492b199 Separate component array types and command array types (#48474)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48474

The previous definition said that you could put prop types into commands, which definitely isn't allowed.

For example, the schema would have allowed `WithDefault` types.

```
interface NativeCommands {
  +methodInt: (viewRef: React.ElementRef<NativeType>, a: WithDefault<string, 'hi'>) => void;
}
```

This change separates out the things that are allowed in commands from what's allowed in props.

Commands should be very similar to what's allowed in native modules, but it isn't exact enough to be able to merge those.

## Changelog:
[General][Breaking] - Codegen: Separate component array types and command array types

Reviewed By: cipolleschi

Differential Revision: D67806818

fbshipit-source-id: 58e504fe2e2e5efa612e836b18af22a167e7ae2f
2025-01-06 18:42:37 -08:00
Eli White c91cfd1ec1 Simplify CompleteTypeAnnotation (#48473)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48473

This is such a simpler approach lol.

I'll need this later for when I want to pass in arrays or objects of these types to the compat check

Changelog: [internal]

Reviewed By: cipolleschi

Differential Revision: D67806812

fbshipit-source-id: 5cc361815fea901098d2931ba78293693ecc0a35
2025-01-06 18:42:37 -08:00
Eli White 02c6790842 Make CompleteType contain module and component reserved names (#48477)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48477

Over the years of copying and moving and renaming types through CodegenSchema, this type ended up in the Command params, although the Command parser doesn't allow it.

I made this change to a fixture:

{F1974104959}

and got this error

```
 FAIL  xplat/js/react-native-github/packages/react-native-codegen/src/parsers/flow/components/__tests__/component-parser-test.js
  ● RN Codegen Flow Parser › can generate fixture COMMANDS_DEFINED_WITH_ALL_TYPES

    Unsupported param type for method "scrollTo", param "speed". Found UnionTypeAnnotation

      127 |       default:
      128 |         (type: empty);
    > 129 |         throw new Error(
          |               ^
      130 |           `Unsupported param type for method "${name}", param "${paramName}". Found ${type}`,
      131 |         );
      132 |     }
```

Also, a default value for enum an argument of a Command doesn't make sense anyways.

Commands should probably have support for enums and string literal unions, but that's out of scope here.

Still need to add to this vec\concat on www: https://www.internalfb.com/code/www/[ebfa58f888a6064e17879934d447f59bcc2b6951]/flib/intern/sandcastle/react_native/ota_steps/SandcastleOTACompatibilityCheckReportingStep.php?lines=62

Changelog: [internal]

Reviewed By: cipolleschi

Differential Revision: D67806808

fbshipit-source-id: f0f31cca30abbf61f569933ea7c49cf6bfd18a3f
2025-01-06 18:42:37 -08:00
Eli White 9e0a7e3263 Converge component's bespoke StringEnumTypeAnnotation into StringLiteralUnionTypeAnnotation (#48343)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48343

components store unions as 'StringEnumTypeAnnotation' even though it isn't actually a union, it's a literal.

Native Modules store these as 'StringLiteralTypeAnnotation' so this converges those and reuses the same types.

Changelog: [Internal]

Reviewed By: cipolleschi

Differential Revision: D67427656

fbshipit-source-id: e39028114285588584596012d07db40c117b4b94
2025-01-02 13:20:02 -08:00
Eli White b691122afc Share ArrayTypeAnnotation between components and modules (#48318)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48318

These structures were the same, but the component side didn't use generics and just had duplicates. Making a base one to be shared.

I need to follow up to this and constrain the types that components allow.

Changelog: [Internal]

Reviewed By: javache

Differential Revision: D67371894

fbshipit-source-id: bb1a30fcd0efe6cc567b88bc6f11e7b385bd7c41
2025-01-02 13:20:02 -08:00
Eli White 4dac99cf6d Fix FlowFixMes in CodegenVersionDiffing (#48312)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48312

I figured out how to fix these FlowFixMes

Changelog: [Internal]

Reviewed By: yungsters

Differential Revision: D67313962

fbshipit-source-id: 21b109824411c1537f397aca45b7cdc2495f5e11
2024-12-17 20:23:24 -08:00
Eli White 949d229b5f Apply enum changes to new codegen version (#48000)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48000

Adding this type to CompleteTypes

Changelog: [Internal]

Reviewed By: GijsWeterings

Differential Revision: D65305755

fbshipit-source-id: 962297ba21b3b88f0117631fb4192c111e903fc6
2024-12-03 16:41:36 -08:00
Eli White fa8a25eb6b Make enum types annotation objects instead of literal strings and numbers (#47349)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/47349

This is needed to be able to recurse into the literals and compare them.

I'm primarily unsure if there is a problem representing doubles/floats as numbers instead of strings though.

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D65284058

fbshipit-source-id: b2de9ed5fb7f079a432c94aaea69027863879909
2024-12-02 14:32:35 -08:00
Eli White 35f0e1cca2 Fix CodegenSchema Enum type to not export array (#47324)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/47324

I need to reference this type somewhere else, but not an array of the type.

Generally we prefer that all exported types are the object itself, and it used as a member type of arrays when used.

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D65259014

fbshipit-source-id: 35fb5fe03a44bed61ad87337d0fc5c198744c0e9
2024-11-04 12:58:49 -08:00
Eli White dd472101b7 Add NumberLiteralTypeAnnotation support (#47323)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/47323

This change adds support for number literals as a type.

The codegen already has parsing support for these types
```
  +passNumber: (arg: number) => void;
  +passString: (arg: string) => void;
  +passStringLiteral: (arg: 'A String Literal') => void;
```

This change now also supports
```
  +passNumberLiteral: (arg: 4) => void;
```

On the native side this is treated the same as `number`. It could be strengthened in the future.

This is a pre-requisite for number literal unions and enums.

Changelog: [Added] Codegen: Added support for Number literals in native module specs

Reviewed By: makovkastar

Differential Revision: D65249334

fbshipit-source-id: 98b051d2a6bd1ad5cc6473ac88acfcbe82bd5c7d
2024-11-04 12:58:49 -08:00
Eli White 4c37431c7f Support new codegen schema for native modules (#47114)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/47114

Export the EventEmitter annotation from the codegen

Changelog: [Internal]

Reviewed By: GijsWeterings

Differential Revision: D63995813

fbshipit-source-id: 0211c21d7813da03bf8b6680095e016a621c188b
2024-10-21 16:43:49 -07:00
Eli White a669de1dd2 Parse string unions as StringLiteralUnionTypeAnnotation (#46845)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46845

Previously, the parser was throwing away the values of a string union when storing it in the schema. It would only store the union as

```
{
  type: 'UnionTypeAnnotation',
  memberType: 'StringTypeAnnotation'
}
```

We now track the string literals through the parser and store them in the schema:

```
{
  type: 'StringLiteralUnionTypeAnnotation',
  types: [
    {
      type: 'StringLiteralTypeAnnotation'
      value: 'light'
    },
    {
      type: 'StringLiteralTypeAnnotation'
      value: 'dark'
    },
  ],
}
```

We aren't changing the generators, those still just output "string". They could eventually be made smarter.

The value of this is that the compat checker can now error when the union changes.

Changelog: [Internal]

Reviewed By: yungsters

Differential Revision: D63917685

fbshipit-source-id: 34a10e1f1910d2935837a3659f66049fd4473134
2024-10-07 16:56:04 -07:00
Eli White d2f3f06826 Add support for StringLiteralTypeAnnotation (#46827)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46827

You can now define a native module that takes an argument that is a specific string literal:

Like this:
```
export interface Spec extends TurboModule {
  +passString: (arg: string) => void;
  +passStringLiteral: (arg: 'A String Literal') => void;
}
```

On the native side, this will still generate `string`, but the schema will now store the string literal, and it will be allowed in JS. This should allow more strict flow / typescript types for modules.

This will also allow the compatibility check to fail if the literal changes.

This is a step towards accepting a union of string literals.

Changelog: [General][Added] Codegen for Native Modules now supports string literals

Reviewed By: GijsWeterings

Differential Revision: D63872440

fbshipit-source-id: e54b97d34af4a3d1af51727db0777f26fb7b778c
2024-10-07 12:35:19 -07:00
Eli White 86cac68365 Promise annotations must specify their elementType (#46727)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46727

It makes scripts operating on the schema complicated when the elementType might be there or might not. Let's make it required, but VoidTypeAnnotation if it's unknown.

Arguably we shouldn't allow it to be unknown at all, but that's out of scope here.

Changelog: [Internal]

Reviewed By: GijsWeterings

Differential Revision: D63616703

fbshipit-source-id: 290586384b911928e55344aa522bd296f23a074c
2024-09-30 11:19:44 -07:00
Eli White 6666df9fb8 Add a union of all the types (#46528)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46528

This is needed for a script that needs to switch over all possible type annotations in the codegen schema.

Reviewed By: GijsWeterings

Differential Revision: D62805189

fbshipit-source-id: 8fd113f4ad0b695b38e92b8d0fc45a991f597fb8
2024-09-17 13:20:04 -07:00
Eli White 84ec424e8a Remove superflous {type:string} from CodegenSchema (#46237)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46237

I can't find any uses of this, it's not referenced in any fixtures, and flow and typescript both pass without it.

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D61892355

fbshipit-source-id: 8ebb4da3e104109c740d90c2495dbcc89d3978e5
2024-08-29 10:51:31 -07:00
Eli White a5363113f1 Fix NativeModuleEnumMembers type (#46222)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46222

This value was typed as always being a string, even though it  was containing both strings and numbers in the fixtures. This was because on this line https://fburl.com/code/9j7gh4av the input type is $FlowFixMe (from the source AST), which wasn't catching that it couldn't flow into just `string`.

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D61830075

fbshipit-source-id: 0d5a0239d7c0209049184ca858a7ceb1ada02f79
2024-08-29 10:51:31 -07:00
Eli White 0b56ccab2a Array's with unparsable element type's are explicitly Any vs missing (#46221)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46221

Previously the schema special cased unparseable elementType with elementType just being undefined. This causes issues for logic that requires recursively matching types. Instead of being implicit, this makes them explicitly an AnyTypeAnnotation

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D61825742

fbshipit-source-id: 47bf70d32d21647896d8f5319087378cc8ac8d4f
2024-08-29 10:51:31 -07:00
Eli White 851037d144 Dedupe trivial types between modules and components (#46220)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46220

We'll want to eventually combine the module and component capabilities more, but these are at least the trivially shared ones.

More work is required to merge the more complex object types.

This change also makes it more clear where capabilities are different between native modules and components

Changelog: [Internal]

Reviewed By: makovkastar

Differential Revision: D61740140

fbshipit-source-id: 9e7bf740cf6cd2431be8cad822ec69903dbbc71f
2024-08-26 17:34:40 -07:00
Christoph Purrer 85dc2e393f Allow map type objects in Java/ObjC TM EventEmitter (#45271)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45271

Changelog: [Internal] Allow map type objects in Java/ObjC TM EventEmitter

Reviewed By: rshest

Differential Revision: D59360044

fbshipit-source-id: 6fce094586ed2ad55a0d83a8a83ff554e2ba000e
2024-07-05 12:37:47 -07:00
Christoph Purrer 6daccf75da Enable EventEmitter parsing for TypeScript TM Specs (#45118)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/45118

## Changelog:

[General] [Fixed] - Enable EventEmitter parsing for TypeScript TM Specs

Reviewed By: rshest

Differential Revision: D58929364

fbshipit-source-id: 0f95aee2f387edf0a148b368d71b0325c805f724
2024-06-24 11:36:49 -07:00
Christoph Purrer 810a516475 Call Turbo Module methods 'methods' in the Turbo Module JSON schema (#44919)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44919

## Changelog:

[Internal] [Fixed] - Call Turbo Module methods 'methods' in the Turbo Module JSON schema

We don't support `properties` on Turbo Modules. We only support methods (even eventEmitters are just methods)

Reviewed By: javache

Differential Revision: D58510557

fbshipit-source-id: 02b1dc93a37b58b47bb9fd94a9658b5a7301bf55
2024-06-14 10:36:31 -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
Christoph Purrer ea3a7143b9 Align CodegenSchema.d.ts with CodegenSchema.js (#44629)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/44629

Changelog: [General][Fixed] Align CodegenSchema.d.ts with CodegenSchema.js

Reviewed By: yungsters

Differential Revision: D57594059

fbshipit-source-id: 554afcb1520e291d5452f330137ea577000f2428
2024-05-27 19:15:42 -07:00
Zeya Peng c848bf9545 support Array param for native component command in codegen (#41894)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/41894

Changelog: [Internal]

Reviewed By: rshest

Differential Revision: D51866557

fbshipit-source-id: 595de8d49c0654b36d70a2c8872173fd6232a2be
2023-12-12 18:48:47 -08:00
Sam Zhou 0191d16712 Fix bad utility type definitions (#37662)
Reviewed By: panagosg7

Differential Revision: D46364595

fbshipit-source-id: 5dcd484cd292d5b83b0b114675ec3c8059aefe6b
2023-06-01 14:41:00 -07:00
Zihan Chen (MSFT) 4fd8f405be Recognize dictionary type in codegen (#37206)
Summary:
Previously we allow `{[key:string]:Something}` in codegen, `Something` is type-checked but thrown away, generating a `GenericObjectTypeAnnotation`.
In this change, `Something` is added to `GenericObjectTypeAnnotation` as an optional field.
For downstream code such as C++ codegen, this change is **backward compatible**. It allows C++ codegen to produce a more precious type optionally.

## Changelog:

[General] [Added] - Recognize dictionary type in codegen

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

Test Plan:
```
yarn jest react-native-codegen
yarn jest react-native-codegen-typescript-test
```

Reviewed By: cipolleschi

Differential Revision: D45563340

Pulled By: dmytrorykun

fbshipit-source-id: 9a9ce36df6ded6d42d35c3dcb6fb0eaca16c4458
2023-05-04 05:04:12 -07:00
Riccardo Cipolleschi 6168701887 Support Array parsing in events (#37142)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/37142

This diff introduce support to parse arrays in events.

We support parsing Arrays of:
- Boolean
- Double
- Float
- Int32
- String Enums
- String
- Objects
- Arrays

## Changelog:
[General][Added] - Add generic support for Arrays in Events parsing

Reviewed By: dmytrorykun, RSNara

Differential Revision: D45268779

fbshipit-source-id: 0c6eae65eb2b41ebf7b47a4cc3e0f0e5fa20d871
2023-05-04 04:11:49 -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
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
Vitali Zaidman 39bdb34178 Parse and collect enum members in turbo module specs (#36044)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36044

> **Notice**: This commit does not change any behaviour.

Parse and collect enum members in module specs instead of the current behaviour of parsing enum members as 'string' / 'number' and ignoring the member names.

This commit would allow us to generate native Enums corresponding to the schema's enums.

Prior to this commit, enum params were parsed as:
```
                {
                  'name': 'qualityParam',
                  'optional': false,
                  'typeAnnotation': {
                    'type': 'EnumDeclaration',
                    'memberType': 'StringTypeAnnotation'
                  }
                },
```

The name of the enum type and the members of the enum type were ignored.

After this commit, parsed modules would hold a new object member called `enumMap` that would look like this:
```

      'enumMap': {
        'QualityEnum': {
          'name': 'QualityEnum',
          'type': 'EnumDeclarationWithMembers',
          'memberType': 'StringTypeAnnotation',
          'members': [
            {
              'name': 'SD',
              'value': 'sd'
            },
            {
              'name': 'HD',
              'value': 'hd'
            }
          ]
        },
        // ...
      }
```
And enum params would be exported as:
```
	        {
                  'name': 'qualityParam',
                  'optional': false,
                  'typeAnnotation': {
                    'name': 'NativeModuleEnumTypeAnnotation',
                    'type': 'EnumDeclaration',
                    'memberType': 'StringTypeAnnotation'
                  }
                },
```

Combining the two new outputs would allow us to generate Native enums in the Native generators.

Changelog: [Internal] Parse and collect enum members in turbo module specs

Reviewed By: cipolleschi

Differential Revision: D42778258

fbshipit-source-id: 56479342e085bc4e13c5a3e12b265b140e49893c
2023-02-03 03:03:41 -08:00
Vitali Zaidman 69494a7b1f rename module exports from "aliases" to "aliasMap" (#36042)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/36042

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

Use aliasMap both in parsers and generators instead of using aliasMap in half of the places and aliases in the other.

This would also allow us to introduce "enumMap" more easily in the next commit.

Changelog: [Internal] rename module exports from "aliases" to "aliasMap"

Reviewed By: christophpurrer, cipolleschi

Differential Revision: D42888752

fbshipit-source-id: cf1929fcebde994d07e5c6bda5ab71106d417b21
2023-02-02 09:58:01 -08:00
Zihan Chen (MSFT) bf34810c5c Turbo module codegen support interface with inheritance in module (#36011)
Summary:
The [previous pull request](https://github.com/facebook/react-native/pull/35812) enables defining interfaces and using them in a turbo module, but all members are flattened, this is not the best option for codegen for object oriented languages.

In this pull request, an optional member `baseTypes` is added to aliased objects. Members are still flattened for backward compatibility, if a codegen doesn't care about that nothing needs to be changed.

### Example

```typescript
interface A {
  a : string;
}

interface B extends A {
  b : number;
}
```

#### Before the previous pull request

`interface` is not allowed here, you must use type alias.

#### At the previous pull request

`interface` is allowed, but it is translated to

```typescript
type A = {a : string};
type B = {a : string, b : number};
```

#### At this pull request

Extra information is provided so that you know `B` extends `A`. By comparing `B` to `A` it is easy to know that `B::a` is obtained from `A`.

## Changelog

[GENERAL] [CHANGED] - Turbo module codegen support interface with inheritance in module

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

Test Plan: `yarn jest react-native-codegen` passed

Reviewed By: rshest

Differential Revision: D42882650

Pulled By: cipolleschi

fbshipit-source-id: 32d502e8a99c4151fae0a1f4dfa60db9ac827963
2023-01-31 12:05:46 -08:00
Genki Kondo d3cc48d9a6 Add codegen support for DimensionValue for components (#35953)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/35953

DimensionValue is a reserved prop type that can be a number or string (such as '50%'). On Java, it will get converted to a YogaValue (converter added to this diff); on C++ it will get converted to a YGValue (converter already exists as it's used in Fabric).

Changelog:
[Internal][Added] - Add codegen support for DimensionValue for components

Reviewed By: cipolleschi

Differential Revision: D42650799

fbshipit-source-id: 1d2bc30bbd93837dedbbb4c74f814963c8140957
2023-01-26 18:52:10 -08:00
Pieter De Baets 90538909f9 Emit name constant as part of Java codegen
Summary:
We have the expected module name available as part of the codegen schema, so we can remove the need for developers to implement the `getName` method as part of their module implementation.

Note that this method is not actually used when the TurboModules infra is used, as the moduleName from the turbo module manager is passed through to the TurboModule base class instead. Moving the method to codegen will make it easier to remove this method altogether once the old architecture is fully removed.

Changelog: [Android][Added] Support generating `getName` in react-native-codegen for Java TurboModules

Reviewed By: mdvacca

Differential Revision: D41615387

fbshipit-source-id: 6b117645fa39e5e9ab014b21198496a52f6f2ae2
2022-12-07 06:35:01 -08:00
Zihan Chen (MSFT) 8a38e03e0f Fix codegen to add T of Promise<T> in CodegenSchema.js (#35345)
Summary:
`Promise<T>` is used very often in turbo module as function return types. So `T` is a critical thing for type safety. To enable future generator to produce more specific type for `Promise`, `T` is added to the schema.

## Changelog

[General] [Changed] - Fix codegen to add `T` of `Promise<T>` in CodegenSchema.js

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

Test Plan: `yarn jest react-native-codegen` passed

Reviewed By: lunaleaps

Differential Revision: D41304647

Pulled By: cipolleschi

fbshipit-source-id: 6cdd2357b83d4d8007c881a7090cbb8969f3ae9d
2022-11-29 03:37:59 -08:00
Riccardo Cipolleschi 62da9b8ce2 Backout Generate Custom Native State from Codegen
Summary:
This is the second diffs that backs out the Custom Native State from the Codegen. The reason why we are backing it out are:

1. It forces users to create new types in JS that are not ctually used there. For example, the NativeState you define, and eventually exports, in JS is not used anywhere in your JS code.
2. You need to put in the JS native state some types that does not exists in JS, only to have them generated by the Codegen. ImageRequest, for example, does not exists in JS, but you need it in your (iOS) state to load images
3. There are a lot of edge cases due to how C++ handles variables. Some variables needs to be created as pointers. Some others as `const &`. It does not scale to hard code all of them and there is the risk to have the same type that needs to be a pointer in some case and something else in others.
4. It is better to instruct the users on how to properly create a component with Custom State, Shadow Node and Descriptor.

## Changelog:
[General][Removed] - Back out parsing and generation of Custom Native State from Codegen

Reviewed By: cortinico

Differential Revision: D40426134

fbshipit-source-id: c368e122cc31ee8df056fe1bf6cecaab482140a4
2022-10-18 10:30:06 -07:00
Riccardo Cipolleschi d7c41361dd Add ImageSource and ImageRequest to generate custom NativeState (#34910)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/34910

This Diff adds supports on the CustomState generation for ImageSource and ImageRequests, to enable NativeComponents to use the ImageSource loading provided by React Native.

To achieve this, I also had to fox some errors in the imports and to introduce some functions to decorate parameters.

This diff also introduces the tests for thise additional types in both generators and parsers.

## Changelog
[General][Added] - add support for ImageSource and ImageRequest in the State.

Reviewed By: cortinico

Differential Revision: D39884889

fbshipit-source-id: ae3d2d51dfe6a4fe688dc78fec83f428beb8d443
2022-10-10 02:51:06 -07:00
Riccardo Cipolleschi 925b15351f Parse custom NativeState in Flow (#34753)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/34753

This Diff introduce a the capability to parse custom NativeStates in Flow. To achieve this I also had to define the CodegenSchema.

The parsing follows the exact same rules as props, as initial heuristic. This should allow enough customization for the developers who needs a custom state.

There is only a case I was not able to make it work that is STATE_ALIASED_LOCALLY, from the fixtures. I don't know how diffuse it is and I think we can live with some workarounds for the time being.

This diff also adds tests for the custom Native State Flow Parser.

## Changelog
[General][Added] - Implement custom Native State parsing in Flow

Reviewed By: cortinico

Differential Revision: D39686251

fbshipit-source-id: 446997a39b33b7e9351d5ba12cecaeff33df4d16
2022-09-26 07:33:07 -07:00
Christoph Purrer b444f0e44e react-native-code-gen Add Enum Type support for C++ TurboModules
Summary:
There are cases where we want to pass an enum type into a TurboModule method which is handy to restrict certain arguments to a restricted set of values, e.g. restricting quality to ```enum Quality { SD, HD, }```

Approach:
- We are not generating an ```enum``` type in C++ but rather just cast type safe to the corresponding member type.

- We don't support mixed enum types at this time, e.g. ```export enum StringOption { One = 'one', Two = 2, Three = 'three', };``` will not work. See: https://www.typescriptlang.org/docs/handbook/enums.html#heterogeneous-enums

- We only support untyped (default to String), String, and Number enum properties

This is for C++ only, Java and ObjC are not supported atm.

Changelog:
[General][Added] - react-native-code-gen Add Enum Type support for C++ TurboModules

Reviewed By: RSNara

Differential Revision: D38880963

fbshipit-source-id: f2399b29948306bc555429b6f96c43ea4c39c46e
2022-08-30 00:48:06 -07:00
Christoph Purrer 355feafff6 react-native-code-gen Add Union Type support for C++ TurboModules
Summary:
There are cases where we want to pass a union type into a TurboModule method which is handy to restrict certain arguments to a restricted set of values, e.g. restricting quality to ```'low'```, ```high``` or resolution to ```720```, ```1080```.

- We are not generating an ```union``` type in C++ but rather just cast type safe to the corresponding member type.

- We don't support mixed primitive union types at this time, e.g. ```export type ChooseSomething = 'One' | 'Two' | 3 | false;``` does not work.

- We can support mixed object union types such as ... ```export type ChooseObject = {} | {low: string};``` - which need special logic in the C++ TM to correctly parse the resulting jsi::Object

This is for C++ only, Java and ObjC are not supported atm.

Changelog:
[General][Added] - react-native-code-gen Add Union Type support for C++ TurboModules

Reviewed By: javache

Differential Revision: D38919688

fbshipit-source-id: 0fd37545b32b4f2059a8babda62dab4a85de37a9
2022-08-24 14:47:39 -07:00
Scott Kyle 3c569f546c Support mixed types only for C++
Summary:
There are cases where we want to pass arbitrary types to a TurboModule, which may then handle the values appropriately, but we haven't supported this use case. Since C++ TurboModules can accept any `jsi::Value` (unlike Java/ObjC) and we have real-world need for this (otherwise we must require JSON serialization), this now allows `mixed` (`unknown` in TypeScript) for C++-only TurboModules.

Changelog:
[General][Added] C++ TurboModule methods can now use mixed types

Reviewed By: RSNara

Differential Revision: D36611299

fbshipit-source-id: bbf29dfcc6aed67e213bb3eab06537c18c7db1fe
2022-05-24 19:35:29 -07:00
Andres Suarez 8bd3edec88 Update copyright headers from Facebook to Meta
Reviewed By: aaronabramov

Differential Revision: D33367752

fbshipit-source-id: 4ce94d184485e5ee0a62cf67ad2d3ba16e285c8f
2021-12-30 15:11:21 -08:00
Ramanpreet Nara 8461409e88 Generate pojo for Component Props
Summary:
## What This Does
- **Phase 1:** Given a component, convert its props (and all its ObjectTypeAnnotations) into this Pojo data structure under some namespace. This is a recursive operation.
- **Phase 2:** Loop over each Pojo data structure, and serialize it to Java class.

So...
- Each Component has its own namespace (i.e: its hasteModuleName) for Java Pojo objects.
- Each Component generates 1 Pojo object, for its props.
- Each Component generates 1 Pojo object for every ObjectTypeAnnotation in its props.

## Decisions
By design, [JNI can read/write to private properties on Java objects](https://stackoverflow.com/a/12208643). So, each Pojo, which represents an ObjectTypeAnnotation, contains only a private member variable for each of its properties, and a getter to retrieve the data from each of its private members.

## Todos
- Improved type-safety:
   - ReservedTypeAnnotation (e.g: PointPrimitive). These currently map to ReadableMap.
   - String enums, and Int enums don't actually generate Java enums.
- Verify if there are any compilation issues by wiring this up to the Codegen buck infra.
- To actually use the Pojos, we'll need C++/Jni codegen to transform C++ props into these Pojos. Building this out will give a more accurate assessment of the app-size cost of Pojos. However, we can do that if we deem that the app-size increase from adding just the Pojo classes is negligible enough to **not** rule out this entire approach.
- ~~Add some annotations to prevent these Pojo classes from being stripped at compile-time.~~ D26041103

Changelog: [Internal]

Reviewed By: mdvacca

Differential Revision: D26038189

fbshipit-source-id: c137c4ca6b043ee76adb354105aff6e0f270df86
2021-01-26 17:07:00 -08:00
Ramanpreet Nara 00cfb0f919 Remove pipes from Object literal Flow types
Summary:
## Changes
{| ... |} -> { ... }

**Motivation:** In Flow, object literals are exact by default. So, there's no need for the pipes. Also: Now, the syntax for object literals is consistent across react-native-codegen.

Changelog: [Internal]

Reviewed By: hramos

Differential Revision: D24774771

fbshipit-source-id: 24ceb6f5876122aa8ad9e08c7e903215864ad6f5
2020-11-06 16:24:44 -08:00