Generate Custom Native State (#34796)

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

This diff introduces the generation of custom native states using basic types as we do with the Props.

To make it work, the custom types are already writte in the Props.h file, therefore the State.h file must import that other file to have access to the required types.

This diff adds and updates the tests for the State.

## Changelog
[General][Added] - Generate custom Native State

Reviewed By: cortinico

Differential Revision: D39816763

fbshipit-source-id: 42d1aa9a6df23145f4a46ae8ccfb43d81fa651fb
This commit is contained in:
Riccardo Cipolleschi
2022-10-10 02:51:06 -07:00
committed by Facebook GitHub Bot
parent 5fa51e665f
commit 7490ad4a21
22 changed files with 8222 additions and 289 deletions
@@ -10,17 +10,23 @@
'use strict';
import type {SchemaType} from '../../CodegenSchema';
import type {
NamedShape,
SchemaType,
StateTypeAnnotation,
} from '../../CodegenSchema';
const {capitalize} = require('../Utils.js');
const {getStateConstituents} = require('./ComponentsGeneratorUtils.js');
// File path -> contents
type FilesOutput = Map<string, string>;
const FileTemplate = ({
libraryName,
stateClasses,
stateGetters,
}: {
libraryName: string,
stateClasses: string,
stateGetters: string,
}) => `
/**
* This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).
@@ -35,13 +41,32 @@ const FileTemplate = ({
namespace facebook {
namespace react {
${stateClasses}
${stateGetters}
} // namespace react
} // namespace facebook
`;
const StateTemplate = ({stateName}: {stateName: string}) => '';
function generateStrings(
componentName: string,
state: $ReadOnlyArray<NamedShape<StateTypeAnnotation>>,
) {
let getters = '';
state.forEach(stateShape => {
const {name, varName, type} = getStateConstituents(
componentName,
stateShape,
);
getters += `
${type} ${componentName}::get${capitalize(name)}() const {
return ${varName};
}
`;
});
return getters.trim();
}
module.exports = {
generate(
@@ -52,7 +77,7 @@ module.exports = {
): FilesOutput {
const fileName = 'States.cpp';
const stateClasses = Object.keys(schema.modules)
const stateGetters = Object.keys(schema.modules)
.map(moduleName => {
const module = schema.modules[moduleName];
if (module.type !== 'Component') {
@@ -67,12 +92,16 @@ module.exports = {
return Object.keys(components)
.map(componentName => {
if (components[componentName].interfaceOnly === true) {
const component = components[componentName];
if (component.interfaceOnly === true) {
return null;
}
return StateTemplate({
stateName: `${componentName}State`,
});
const state = component.state;
if (!state) {
return '';
}
return generateStrings(componentName, state);
})
.filter(Boolean)
.join('\n');
@@ -82,7 +111,7 @@ module.exports = {
const replacedTemplate = FileTemplate({
libraryName,
stateClasses,
stateGetters,
});
return new Map([[fileName, replacedTemplate]]);