@react-native-windows/codegen 0.0.0-canary.100 → 0.0.0-canary.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +20 -4
  2. package/lib-commonjs/Cli.js +11 -0
  3. package/lib-commonjs/Cli.js.map +1 -1
  4. package/lib-commonjs/generators/AliasGen.js +1 -2
  5. package/lib-commonjs/generators/AliasGen.js.map +1 -1
  6. package/lib-commonjs/generators/AliasManaging.d.ts +3 -3
  7. package/lib-commonjs/generators/AliasManaging.js.map +1 -1
  8. package/lib-commonjs/generators/GenerateComponentWindows.d.ts +13 -0
  9. package/lib-commonjs/generators/GenerateComponentWindows.js +337 -0
  10. package/lib-commonjs/generators/GenerateComponentWindows.js.map +1 -0
  11. package/lib-commonjs/generators/GenerateTypeScript.js +1 -1
  12. package/lib-commonjs/generators/GenerateTypeScript.js.map +1 -1
  13. package/lib-commonjs/generators/ObjectTypes.d.ts +2 -2
  14. package/lib-commonjs/generators/ObjectTypes.js +3 -1
  15. package/lib-commonjs/generators/ObjectTypes.js.map +1 -1
  16. package/lib-commonjs/generators/ParamTypes.js +3 -1
  17. package/lib-commonjs/generators/ParamTypes.js.map +1 -1
  18. package/lib-commonjs/generators/PropObjectTypes.d.ts +18 -0
  19. package/lib-commonjs/generators/PropObjectTypes.js +217 -0
  20. package/lib-commonjs/generators/PropObjectTypes.js.map +1 -0
  21. package/lib-commonjs/index.d.ts +3 -1
  22. package/lib-commonjs/index.js +16 -13
  23. package/lib-commonjs/index.js.map +1 -1
  24. package/package.json +1 -1
  25. package/src/Cli.ts +11 -0
  26. package/src/generators/AliasGen.ts +1 -1
  27. package/src/generators/AliasManaging.ts +12 -12
  28. package/src/generators/GenerateComponentWindows.ts +393 -0
  29. package/src/generators/GenerateTypeScript.ts +3 -2
  30. package/src/generators/ObjectTypes.ts +5 -2
  31. package/src/generators/ParamTypes.ts +6 -3
  32. package/src/generators/PropObjectT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E,OAAO,CAAC,IAAI,EAAC,CACrC,CAAC;AACJ,CAAC;AApCD,gCAoCC","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * @format\n */\n\nimport path from 'path';\nimport fs from '@react-native-windows/fs';\nimport globby from 'globby';\nimport type {CppStringTypes} from './generators/GenerateNM2';\nimport {createNM2Generator} from './generators/GenerateNM2';\nimport {\n generateTypeScript,\n setOptionalTurboModule,\n} from './generators/GenerateTypeScript';\nimport type {SchemaType} from '@react-native/codegen/lib/CodegenSchema';\nimport type {Parser} from '@react-native/codegen/lib/parsers/parser';\n\nexport type {CppStringTypes} from './generators/GenerateNM2';\n\n// Load @react-native/codegen from react-native\nconst rnPath = path.dirname(require.resolve('react-native/package.json'));\nconst rncodegenPath = path.dirname(\n require.resolve('@react-native/codegen/package.json', {paths: [rnPath]}),\n);\n\nfunction getParser(isTypeScript: boolean): Parser {\n if (isTypeScript) {\n const fp = require(path.resolve(\n rncodegenPath,\n 'lib/parsers/typescript/parser',\n ));\n return new fp.TypeScriptParser();\n } else {\n const fp = require(path.resolve(rncodegenPath, 'lib/parsers/flow/parser'));\n return new fp.FlowParser();\n }\n}\n\nconst schemaValidator = require(path.resolve(\n rncodegenPath,\n 'lib/SchemaValidator',\n));\n\nexport interface SharedOptions {\n libraryName: string;\n methodOnly: boolean;\n modulesCxx: boolean;\n modulesTypeScriptTypes: boolean;\n modulesWindows: boolean;\n namespace: string;\n outputDirectory: string;\n cppStringType: CppStringTypes;\n separateDataTypes: boolean;\n}\n\ninterface Options extends SharedOptions {\n moduleSpecName: string;\n schema: SchemaType;\n}\n\ninterface Config {\n generators: any[] /*Generators[]*/;\n test?: boolean;\n}\n\nfunction normalizeFileMap(\n map: Map<string, string>,\n outputDir: string,\n outMap: Map<string, string>,\n): void {\n for (const [fileName, contents] of map) {\n const location = path.join(outputDir, fileName);\n outMap.set(path.normalize(location), contents);\n }\n}\n\nfunction checkFilesForChanges(\n map: Map<string, string>,\n outputDir: string,\n): boolean {\n let hasChanges = false;\n\n outputDir = path.resolve(outputDir);\n const globbyDir = outputDir.replace(/\\\\/g, '/');\n const allExistingFiles = globby\n .sync([`${globbyDir}/**`, `${globbyDir}/**/.*`], {absolute: true})\n .map(_ => path.normalize(_));\n const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();\n\n if (\n allExistingFiles.length !== allGeneratedFiles.length ||\n !allGeneratedFiles.every(filepath =>\n allExistingFiles.includes(\n path.normalize(path.resolve(process.cwd(), filepath)),\n ),\n )\n )\n return true;\n\n for (const [fileName, contents] of map) {\n if (!fs.existsSync(fileName)) {\n hasChanges = true;\n continue;\n }\n\n const currentContents = fs.readFileSync(fileName, 'utf8');\n if (currentContents !== contents) {\n console.log(`- ${fileName} has changed`);\n hasChanges = true;\n continue;\n }\n }\n\n return hasChanges;\n}\n\nfunction writeMapToFiles(map: Map<string, string>, outputDir: string) {\n let success = true;\n\n outputDir = path.resolve(outputDir);\n const globbyDir = outputDir.replace(/\\\\/g, '/');\n\n // This ensures that we delete any generated files from modules that have been deleted\n const allExistingFiles = globby.sync(\n [`${globbyDir}/**`, `${globbyDir}/**/.*`],\n {absolute: true},\n );\n\n const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();\n allExistingFiles.forEach(existingFile => {\n if (!allGeneratedFiles.includes(path.normalize(existingFile))) {\n console.log('Deleting ', existingFile);\n fs.unlinkSync(existingFile);\n }\n });\n\n for (const [fileName, contents] of map) {\n try {\n fs.mkdirSync(path.dirname(fileName), {recursive: true});\n\n if (fs.existsSync(fileName)) {\n const currentContents = fs.readFileSync(fileName, 'utf8');\n // Don't update the files if there are no changes as this breaks incremental builds\n if (currentContents === contents) {\n continue;\n }\n }\n\n console.log('Writing ', fileName);\n fs.writeFileSync(fileName, contents);\n } catch (error) {\n success = false;\n console.error(`Failed to write ${fileName} to ${fileName}`, error);\n }\n }\n\n return success;\n}\n\nexport function parseFile(filename: string): SchemaType {\n try {\n const isTypeScript =\n path.extname(filename) === '.ts' || path.extname(filename) === '.tsx';\n const contents = fs.readFileSync(filename, 'utf8');\n const schema = getParser(isTypeScript).parseString(contents, filename);\n // there will be at most one turbo module per file\n const moduleName = Object.keys(schema.modules)[0];\n if (moduleName) {\n const spec = schema.modules[moduleName];\n if (spec.type === 'NativeModule') {\n if (contents) {\n // This is a temporary implementation until such information is added to the schema in facebook/react-native\n if (contents.includes('TurboModuleRegistry.get<')) {\n setOptionalTurboModule(spec, true);\n } else if (contents.includes('TurboModuleRegistry.getEnforcing<')) {\n setOptionalTurboModule(spec, false);\n }\n }\n }\n }\n return schema;\n } catch (e) {\n if (e instanceof Error) {\n e.message = `(${filename}): ${e.message}`;\n }\n throw e;\n }\n}\n\nexport function combineSchemas(files: string[]): SchemaType {\n return files.reduce(\n (merged, filename) => {\n const contents = fs.readFileSync(filename, 'utf8');\n if (\n contents &&\n (/export\\s+default\\s+\\(?codegenNativeComponent</.test(contents) ||\n contents.includes('extends TurboModule'))\n ) {\n const schema = parseFile(filename);\n merged.modules = {...merged.modules, ...schema.modules};\n }\n return merged;\n },\n {modules: {}},\n );\n}\n\nexport function generate(\n {\n libraryName,\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n moduleSpecName,\n schema,\n }: Options,\n {/*generators,*/ test}: Config,\n): boolean {\n schemaValidator.validate(schema);\n\n const componentOutputdir = path.join(\n outputDirectory,\n 'react/components',\n libraryName,\n );\n\n const generatedFiles = new Map<string, string>();\n\n generatedFiles.set(\n path.join(outputDirectory, '.clang-format'),\n 'DisableFormat: true\\nSortIncludes: false',\n );\n\n const generateNM2 = createNM2Generator({\n methodOnly,\n namespace,\n cppStringType,\n separateDataTypes,\n });\n\n const generateJsiModuleH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/modules/GenerateModuleH',\n )).generate;\n const generateJsiModuleCpp = require(path.resolve(\n rncodegenPath,\n 'lib/generators/modules/GenerateModuleCpp',\n )).generate;\n const generatorPropsH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GeneratePropsH',\n )).generate;\n const generatorPropsCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GeneratePropsCpp',\n )).generate;\n const generatorShadowNodeH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateShadowNodeH',\n )).generate;\n const generatorShadowNodeCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateShadowNodeCpp',\n )).generate;\n const generatorComponentDescriptorH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateComponentDescriptorH',\n )).generate;\n const generatorEventEmitterH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateEventEmitterH',\n )).generate;\n const generatorEventEmitterCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateEventEmitterCpp',\n )).generate;\n const generatorStateCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateStateCpp',\n )).generate;\n const generatorStateH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateStateH',\n )).generate;\n\n const moduleGenerators = [];\n\n if (modulesWindows) {\n moduleGenerators.push(generateNM2);\n }\n\n if (modulesCxx) {\n moduleGenerators.push(generateJsiModuleH);\n moduleGenerators.push(generateJsiModuleCpp);\n }\n\n if (modulesTypeScriptTypes) {\n moduleGenerators.push(generateTypeScript);\n }\n\n moduleGenerators.forEach(generator => {\n const generated: Map<string, string> = generator(\n libraryName,\n schema,\n moduleSpecName,\n );\n normalizeFileMap(generated, outputDirectory, generatedFiles);\n });\n\n if (\n Object.keys(schema.modules).some(\n moduleName => schema.modules[moduleName].type === 'Component',\n )\n ) {\n const componentGenerators = [\n generatorComponentDescriptorH,\n generatorEventEmitterCPP,\n generatorEventEmitterH,\n generatorPropsCPP,\n generatorPropsH,\n generatorShadowNodeCPP,\n generatorShadowNodeH,\n generatorStateCPP,\n generatorStateH,\n ];\n\n componentGenerators.forEach(generator => {\n const generated: Map<string, string> = generator(\n libraryName,\n schema,\n moduleSpecName,\n );\n normalizeFileMap(generated, componentOutputdir, generatedFiles);\n });\n }\n\n if (test === true) {\n return checkFilesForChanges(generatedFiles, outputDirectory);\n }\n\n return writeMapToFiles(generatedFiles, outputDirectory);\n}\n\nexport interface CodeGenOptions extends SharedOptions {\n file?: string;\n files?: string[];\n test: boolean;\n}\n\nexport function runCodeGen(options: CodeGenOptions): boolean {\n if (!options.file && !options.files)\n throw new Error('Must specify file or files option');\n\n const schema = options.file\n ? parseFile(options.file)\n : combineSchemas(globby.sync(options.files!));\n\n const libraryName = options.libraryName;\n const moduleSpecName = 'moduleSpecName';\n const {\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n } = options;\n return generate(\n {\n libraryName,\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n moduleSpecName,\n schema,\n },\n {generators: [], test: options.test},\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;AAEH,gDAAwB;AACxB,kEAA0C;AAC1C,oDAA4B;AAE5B,0DAA4D;AAC5D,oFAA+E;AAC/E,wEAGyC;AAMzC,+CAA+C;AAC/C,MAAM,MAAM,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC,CAAC;AAC1E,MAAM,aAAa,GAAG,cAAI,CAAC,OAAO,CAChC,OAAO,CAAC,OAAO,CAAC,oCAAoC,EAAE,EAAC,KAAK,EAAE,CAAC,MAAM,CAAC,EAAC,CAAC,CACzE,CAAC;AAEF,SAAS,SAAS,CAAC,YAAqB;IACtC,IAAI,YAAY,EAAE;QAChB,MAAM,EAAE,GAAG,OAAO,CAAC,cAAI,CAAC,OAAO,CAC7B,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,IAAI,EAAE;QACjB,OAAO,oBAAoB,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;KAC9D;IAED,OAAO,eAAe,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;AAC1D,CAAC;AA3JD,4BA2JC;AAQD,SAAgB,UAAU,CAAC,OAAuB;IAChD,IAAI,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK;QACjC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAEvD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI;QACzB,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC;QACzB,CAAC,CAAC,cAAc,CAAC,gBAAM,CAAC,IAAI,CAAC,OAAO,CAAC,KAAM,CAAC,CAAC,CAAC;IAEhD,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IACxC,MAAM,cAAc,GAAG,gBAAgB,CAAC;IACxC,MAAM,EACJ,UAAU,EACV,UAAU,EACV,sBAAsB,EACtB,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,SAAS,EACT,eAAe,EACf,aAAa,EACb,iBAAiB,GAClB,GAAG,OAAO,CAAC;IACZ,OAAO,QAAQ,CACb;QACE,WAAW;QACX,UAAU;QACV,UAAU;QACV,sBAAsB;QACtB,cAAc;QACd,iBAAiB;QACjB,kBAAkB;QAClB,SAAS;QACT,eAAe;QACf,aAAa;QACb,iBAAiB;QACjB,cAAc;QACd,MAAM;KACP,EACD,EAAC,UAAU,EAAE,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAC,CACrC,CAAC;AACJ,CAAC;AAxCD,gCAwCC","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * @format\n */\n\nimport path from 'path';\nimport fs from '@react-native-windows/fs';\nimport globby from 'globby';\nimport type {CppStringTypes} from './generators/GenerateNM2';\nimport {createNM2Generator} from './generators/GenerateNM2';\nimport {createComponentGenerator} from './generators/GenerateComponentWindows';\nimport {\n generateTypeScript,\n setOptionalTurboModule,\n} from './generators/GenerateTypeScript';\nimport type {SchemaType} from '@react-native/codegen/lib/CodegenSchema';\nimport type {Parser} from '@react-native/codegen/lib/parsers/parser';\n\nexport type {CppStringTypes} from './generators/GenerateNM2';\n\n// Load @react-native/codegen from react-native\nconst rnPath = path.dirname(require.resolve('react-native/package.json'));\nconst rncodegenPath = path.dirname(\n require.resolve('@react-native/codegen/package.json', {paths: [rnPath]}),\n);\n\nfunction getParser(isTypeScript: boolean): Parser {\n if (isTypeScript) {\n const fp = require(path.resolve(\n rncodegenPath,\n 'lib/parsers/typescript/parser',\n ));\n return new fp.TypeScriptParser();\n } else {\n const fp = require(path.resolve(rncodegenPath, 'lib/parsers/flow/parser'));\n return new fp.FlowParser();\n }\n}\n\nconst schemaValidator = require(path.resolve(\n rncodegenPath,\n 'lib/SchemaValidator',\n));\n\nexport interface SharedOptions {\n libraryName: string;\n methodOnly: boolean;\n modulesCxx: boolean;\n modulesTypeScriptTypes: boolean;\n modulesWindows: boolean;\n componentsWindows: boolean,\n internalComponents: boolean,\n namespace: string;\n outputDirectory: string;\n cppStringType: CppStringTypes;\n separateDataTypes: boolean;\n}\n\ninterface Options extends SharedOptions {\n moduleSpecName: string;\n schema: SchemaType;\n}\n\ninterface Config {\n generators: any[] /*Generators[]*/;\n test?: boolean;\n}\n\nfunction normalizeFileMap(\n map: Map<string, string>,\n outputDir: string,\n outMap: Map<string, string>,\n): void {\n for (const [fileName, contents] of map) {\n const location = path.join(outputDir, fileName);\n outMap.set(path.normalize(location), contents);\n }\n}\n\nfunction checkFilesForChanges(\n map: Map<string, string>,\n outputDir: string,\n): boolean {\n let hasChanges = false;\n\n outputDir = path.resolve(outputDir);\n const globbyDir = outputDir.replace(/\\\\/g, '/');\n const allExistingFiles = globby\n .sync([`${globbyDir}/**`, `${globbyDir}/**/.*`], {absolute: true})\n .map(_ => path.normalize(_));\n const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();\n\n if (\n allExistingFiles.length !== allGeneratedFiles.length ||\n !allGeneratedFiles.every(filepath =>\n allExistingFiles.includes(\n path.normalize(path.resolve(process.cwd(), filepath)),\n ),\n )\n )\n return true;\n\n for (const [fileName, contents] of map) {\n if (!fs.existsSync(fileName)) {\n hasChanges = true;\n continue;\n }\n\n const currentContents = fs.readFileSync(fileName, 'utf8');\n if (currentContents !== contents) {\n console.log(`- ${fileName} has changed`);\n hasChanges = true;\n continue;\n }\n }\n\n return hasChanges;\n}\n\nfunction writeMapToFiles(map: Map<string, string>, outputDir: string) {\n let success = true;\n\n outputDir = path.resolve(outputDir);\n const globbyDir = outputDir.replace(/\\\\/g, '/');\n\n // This ensures that we delete any generated files from modules that have been deleted\n const allExistingFiles = globby.sync(\n [`${globbyDir}/**`, `${globbyDir}/**/.*`],\n {absolute: true},\n );\n\n const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();\n allExistingFiles.forEach(existingFile => {\n if (!allGeneratedFiles.includes(path.normalize(existingFile))) {\n console.log('Deleting ', existingFile);\n fs.unlinkSync(existingFile);\n }\n });\n\n for (const [fileName, contents] of map) {\n try {\n fs.mkdirSync(path.dirname(fileName), {recursive: true});\n\n if (fs.existsSync(fileName)) {\n const currentContents = fs.readFileSync(fileName, 'utf8');\n // Don't update the files if there are no changes as this breaks incremental builds\n if (currentContents === contents) {\n continue;\n }\n }\n\n console.log('Writing ', fileName);\n fs.writeFileSync(fileName, contents);\n } catch (error) {\n success = false;\n console.error(`Failed to write ${fileName} to ${fileName}`, error);\n }\n }\n\n return success;\n}\n\nexport function parseFile(filename: string): SchemaType {\n try {\n const isTypeScript =\n path.extname(filename) === '.ts' || path.extname(filename) === '.tsx';\n const contents = fs.readFileSync(filename, 'utf8');\n const schema = getParser(isTypeScript).parseString(contents, filename);\n // there will be at most one turbo module per file\n const moduleName = Object.keys(schema.modules)[0];\n if (moduleName) {\n const spec = schema.modules[moduleName];\n if (spec.type === 'NativeModule') {\n if (contents) {\n // This is a temporary implementation until such information is added to the schema in facebook/react-native\n if (contents.includes('TurboModuleRegistry.get<')) {\n setOptionalTurboModule(spec, true);\n } else if (contents.includes('TurboModuleRegistry.getEnforcing<')) {\n setOptionalTurboModule(spec, false);\n }\n }\n }\n }\n return schema;\n } catch (e) {\n if (e instanceof Error) {\n e.message = `(${filename}): ${e.message}`;\n }\n throw e;\n }\n}\n\nexport function combineSchemas(files: string[]): SchemaType {\n return files.reduce(\n (merged, filename) => {\n const contents = fs.readFileSync(filename, 'utf8');\n if (\n contents &&\n (/export\\s+default\\s+\\(?codegenNativeComponent</.test(contents) ||\n contents.includes('extends TurboModule'))\n ) {\n const schema = parseFile(filename);\n merged.modules = {...merged.modules, ...schema.modules};\n }\n return merged;\n },\n {modules: {}},\n );\n}\n\nexport function generate(\n {\n libraryName,\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n internalComponents,\n componentsWindows,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n moduleSpecName,\n schema,\n }: Options,\n {/*generators,*/ test}: Config,\n): boolean {\n schemaValidator.validate(schema);\n\n const componentOutputdir = path.join(\n outputDirectory,\n 'react/components',\n libraryName,\n );\n\n const generatedFiles = new Map<string, string>();\n\n generatedFiles.set(\n path.join(outputDirectory, '.clang-format'),\n 'DisableFormat: true\\nSortIncludes: false',\n );\n\n const generateNM2 = createNM2Generator({\n methodOnly,\n namespace,\n cppStringType,\n separateDataTypes,\n });\n\n const generateJsiModuleH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/modules/GenerateModuleH',\n )).generate;\n const generateJsiModuleCpp = require(path.resolve(\n rncodegenPath,\n 'lib/generators/modules/GenerateModuleCpp',\n )).generate;\n const generatorPropsH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GeneratePropsH',\n )).generate;\n const generatorPropsCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GeneratePropsCpp',\n )).generate;\n const generatorShadowNodeH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateShadowNodeH',\n )).generate;\n const generatorShadowNodeCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateShadowNodeCpp',\n )).generate;\n const generatorComponentDescriptorH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateComponentDescriptorH',\n )).generate;\n const generatorEventEmitterH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateEventEmitterH',\n )).generate;\n const generatorEventEmitterCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateEventEmitterCpp',\n )).generate;\n const generatorStateCPP = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateStateCpp',\n )).generate;\n const generatorStateH = require(path.resolve(\n rncodegenPath,\n 'lib/generators/components/GenerateStateH',\n )).generate;\n\n const moduleGenerators = [];\n\n if (modulesWindows) {\n moduleGenerators.push(generateNM2);\n }\n\n if (modulesCxx) {\n moduleGenerators.push(generateJsiModuleH);\n moduleGenerators.push(generateJsiModuleCpp);\n }\n\n if (modulesTypeScriptTypes) {\n moduleGenerators.push(generateTypeScript);\n }\n\n moduleGenerators.forEach(generator => {\n const generated: Map<string, string> = generator(\n libraryName,\n schema,\n moduleSpecName,\n );\n normalizeFileMap(generated, outputDirectory, generatedFiles);\n });\n\n if (\n Object.keys(schema.modules).some(\n moduleName => schema.modules[moduleName].type === 'Component',\n )\n ) {\n const componentGenerators = [\n ];\n\n if (internalComponents) {\n componentGenerators.push(\n generatorComponentDescriptorH,\n generatorEventEmitterCPP,\n generatorEventEmitterH,\n generatorPropsCPP,\n generatorPropsH,\n generatorShadowNodeCPP,\n generatorShadowNodeH,\n generatorStateCPP,\n generatorStateH\n );\n }\n\n if (componentsWindows) {\n const generateComponentWindows = createComponentGenerator({\n namespace,\n cppStringType,\n });\n\n componentGenerators.push(generateComponentWindows);\n }\n\n componentGenerators.forEach(generator => {\n const generated: Map<string, string> = generator(\n libraryName,\n schema,\n moduleSpecName,\n );\n normalizeFileMap(generated, componentOutputdir, generatedFiles);\n });\n }\n\n if (test === true) {\n return checkFilesForChanges(generatedFiles, outputDirectory);\n }\n\n return writeMapToFiles(generatedFiles, outputDirectory);\n}\n\nexport interface CodeGenOptions extends SharedOptions {\n file?: string;\n files?: string[];\n test: boolean;\n}\n\nexport function runCodeGen(options: CodeGenOptions): boolean {\n if (!options.file && !options.files)\n throw new Error('Must specify file or files option');\n\n const schema = options.file\n ? parseFile(options.file)\n : combineSchemas(globby.sync(options.files!));\n\n const libraryName = options.libraryName;\n const moduleSpecName = 'moduleSpecName';\n const {\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n componentsWindows,\n internalComponents,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n } = options;\n return generate(\n {\n libraryName,\n methodOnly,\n modulesCxx,\n modulesTypeScriptTypes,\n modulesWindows,\n componentsWindows,\n internalComponents,\n namespace,\n outputDirectory,\n cppStringType,\n separateDataTypes,\n moduleSpecName,\n schema,\n },\n {generators: [], test: options.test},\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-native-windows/codegen",
3
- "version": "0.0.0-canary.100",
3
+ "version": "0.0.0-canary.102",
4
4
  "description": "Generators for react-native-codegen targeting react-native-windows",
5
5
  "main": "lib-commonjs/index.js",
6
6
  "repository": {
package/src/Cli.ts CHANGED
@@ -69,6 +69,17 @@ const argv = yargs.options({
69
69
  describe: 'generate data types in a separate file',
70
70
  default: false,
71
71
  },
72
+ componentsWindows: {
73
+ type: 'boolean',
74
+ describe: 'generate component cpp files for custom native components',
75
+ default: false,
76
+ },
77
+ internalComponents: {
78
+ type: 'boolean',
79
+ describe: 'generate non-ABI cpp/h for internal usage of built in native components [Only used within RNW itself]',
80
+ default: false,
81
+ hidden: true,
82
+ }
72
83
  }).argv;
73
84
 
74
85
  if ((argv.file && argv.files) || (!argv.file && !argv.files)) {
@@ -71,7 +71,7 @@ interface AliasCodeMap {
71
71
 
72
72
  function getArrayTypeName(
73
73
  type: Nullable<NativeModuleBaseTypeAnnotation>): string {
74
- if (type.type === 'ArrayTypeAnnotation' && type.elementType?.type === 'TypeAliasTypeAnnotation') {
74
+ if (type.type === 'ArrayTypeAnnotation' && type.elementType.type === 'TypeAliasTypeAnnotation') {
75
75
  return type.elementType.name;
76
76
  }
77
77
 
@@ -18,20 +18,20 @@ export function getAliasCppName(typeName: string): string {
18
18
  return `${preferredModuleName}Spec_${typeName}`;
19
19
  }
20
20
 
21
- export interface AliasMap {
22
- types: {[name: string]: NativeModuleObjectTypeAnnotation | undefined};
21
+ export interface AliasMap<T = NativeModuleObjectTypeAnnotation> {
22
+ types: {[name: string]: T | undefined};
23
23
  jobs: string[];
24
24
  }
25
25
 
26
26
  const ExtendedObjectKey = '$RNW-TURBOMODULE-ALIAS';
27
- interface ExtendedObject extends NativeModuleObjectTypeAnnotation {
27
+ type ExtendedObject<T> = {
28
28
  '$RNW-TURBOMODULE-ALIAS'?: string;
29
- }
29
+ } & T;
30
30
 
31
- function recordAnonymousAlias(
32
- aliases: AliasMap,
31
+ function recordAnonymousAlias<T = NativeModuleObjectTypeAnnotation>(
32
+ aliases: AliasMap<T>,
33
33
  baseAliasName: string,
34
- extended: ExtendedObject,
34
+ extended: ExtendedObject<T>,
35
35
  ): string {
36
36
  extended[ExtendedObjectKey] = baseAliasName;
37
37
  aliases.types[baseAliasName] = extended;
@@ -39,16 +39,16 @@ function recordAnonymousAlias(
39
39
  return baseAliasName;
40
40
  }
41
41
 
42
- export function getAnonymousAliasCppName(
43
- aliases: AliasMap,
42
+ export function getAnonymousAliasCppName<T = NativeModuleObjectTypeAnnotation>(
43
+ aliases: AliasMap<T>,
44
44
  baseAliasName: string,
45
- objectType: NativeModuleObjectTypeAnnotation,
45
+ objectType: T,
46
46
  ): string {
47
47
  // someone found an anonymous object literal type
48
48
  // if the ExtendedObjectKey flag has been set
49
49
  // then it is a known one
50
50
  // this happens because method signatures are generate twice in spec and error messages
51
- const extended = <ExtendedObject>objectType;
51
+ const extended = <ExtendedObject<T>>objectType;
52
52
  const key = extended[ExtendedObjectKey];
53
53
  if (key !== undefined) {
54
54
  return getAliasCppName(key);
@@ -59,7 +59,7 @@ export function getAnonymousAliasCppName(
59
59
  // associate the name with this object literal type and return
60
60
  if (aliases.types[baseAliasName] === undefined) {
61
61
  return getAliasCppName(
62
- recordAnonymousAlias(aliases, baseAliasName, extended),
62
+ recordAnonymousAlias<T>(aliases, baseAliasName, extended),
63
63
  );
64
64
  }
65
65
 
@@ -0,0 +1,393 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ import type {SchemaType, EventTypeAnnotation, PropTypeAnnotation, ObjectTypeAnnotation, CommandParamTypeAnnotation} from '@react-native/codegen/lib/CodegenSchema';
10
+ import {getAliasCppName, setPreferredModuleName} from './AliasManaging';
11
+ import {translateComponentPropsFieldType, translateComponentEventType, translateCommandParamType} from './PropObjectTypes';
12
+ import type {CppStringTypes} from './ObjectTypes';
13
+ import type {AliasMap} from './AliasManaging';
14
+
15
+ export type {CppStringTypes} from './ObjectTypes';
16
+
17
+ type FilesOutput = Map<string, string>;
18
+
19
+ const headerTemplate = `/*
20
+ * This file is auto-generated from ::_COMPONENT_NAME_::NativeComponent spec file in flow / TypeScript.
21
+ */
22
+ #pragma once
23
+
24
+ #include <JSValueComposition.h>
25
+ #include <NativeModules.h>
26
+ #include <winrt/Microsoft.ReactNative.Composition.h>
27
+ #include <winrt/Microsoft.UI.Composition.h>`
28
+
29
+
30
+ const propsTemplate = `REACT_STRUCT(::_PROPS_NAME_::)
31
+ struct ::_PROPS_NAME_:: : winrt::implements<::_PROPS_NAME_::, winrt::Microsoft::ReactNative::IComponentProps> {
32
+ ::_PROPS_NAME_::(winrt::Microsoft::ReactNative::ViewProps props) : ViewProps(props) {}
33
+
34
+ void SetProp(uint32_t hash, winrt::hstring propName, winrt::Microsoft::ReactNative::IJSValueReader value) noexcept {
35
+ winrt::Microsoft::ReactNative::ReadProp(hash, propName, value, *this);
36
+ }
37
+
38
+ ::_PROPS_FIELDS_::
39
+ const winrt::Microsoft::ReactNative::ViewProps ViewProps;
40
+ };`
41
+
42
+ const propsObjectTemplate = `REACT_STRUCT(::_OBJECT_NAME_::)
43
+ struct ::_OBJECT_NAME_:: {
44
+ ::_OBJECT_FIELDS_::};
45
+ `
46
+ const eventsObjectTemplate = `REACT_STRUCT(::_OBJECT_NAME_::)
47
+ struct ::_OBJECT_NAME_:: {
48
+ ::_OBJECT_FIELDS_::};
49
+ `
50
+
51
+ const eventEmitterMethodTemplate = ` void ::_EVENT_NAME_::(::_EVENT_OBJECT_TYPE_:: &value) const {
52
+ m_eventEmitter.DispatchEvent(L"::_EVENT_NAME_NO_ON_::", [value](const winrt::Microsoft::ReactNative::IJSValueWriter writer) {
53
+ winrt::Microsoft::ReactNative::WriteValue(writer, value);
54
+ });
55
+ }`;
56
+
57
+
58
+ const eventEmitterTemplate = `::_COMPONENT_EVENT_OBJECT_TYPES_::
59
+
60
+ struct ::_EVENT_EMITTER_NAME_:: {
61
+ ::_EVENT_EMITTER_NAME_::(const winrt::Microsoft::ReactNative::EventEmitter &eventEmitter)
62
+ : m_eventEmitter(eventEmitter) {}
63
+
64
+ ::_EVENT_EMITTER_USINGS_::
65
+
66
+ ::_EVENT_EMITTER_METHODS_::
67
+
68
+ private:
69
+ winrt::Microsoft::ReactNative::EventEmitter m_eventEmitter{nullptr};
70
+ };`
71
+
72
+ const baseStructTemplate = `
73
+ template<typename TUserData>
74
+ struct Base::_COMPONENT_NAME_:: {
75
+
76
+ virtual void UpdateProps(
77
+ const winrt::Microsoft::ReactNative::ComponentView &/*view*/,
78
+ const winrt::com_ptr<::_COMPONENT_NAME_::Props> &newProps,
79
+ const winrt::com_ptr<::_COMPONENT_NAME_::Props> &/*oldProps*/) noexcept {
80
+ m_props = newProps;
81
+ }
82
+
83
+ // UpdateState will only be called if this method is overridden
84
+ virtual void UpdateState(
85
+ const winrt::Microsoft::ReactNative::ComponentView &/*view*/,
86
+ const winrt::Microsoft::ReactNative::IComponentState &/*newState*/) noexcept {
87
+ }
88
+
89
+ virtual void UpdateEventEmitter(const std::shared_ptr<::_COMPONENT_NAME_::EventEmitter> &eventEmitter) noexcept {
90
+ m_eventEmitter = eventEmitter;
91
+ }
92
+
93
+ // MountChildComponentView will only be called if this method is overridden
94
+ virtual void MountChildComponentView(const winrt::Microsoft::ReactNative::ComponentView &/*view*/,
95
+ const winrt::Microsoft::ReactNative::MountChildComponentViewArgs &/*args*/) noexcept {
96
+ }
97
+
98
+ // UnmountChildComponentView will only be called if this method is overridden
99
+ virtual void UnmountChildComponentView(const winrt::Microsoft::ReactNative::ComponentView &/*view*/,
100
+ const winrt::Microsoft::ReactNative::UnmountChildComponentViewArgs &/*args*/) noexcept {
101
+ }
102
+
103
+ // Initialize will only be called if this method is overridden
104
+ virtual void Initialize(const winrt::Microsoft::ReactNative::ComponentView &/*view*/) noexcept {
105
+ }
106
+
107
+ // CreateVisual will only be called if this method is overridden
108
+ virtual winrt::Microsoft::UI::Composition::Visual CreateVisual(const winrt::Microsoft::ReactNative::ComponentView &view) noexcept {
109
+ return view.as<winrt::Microsoft::ReactNative::Composition::ComponentView>().Compositor().CreateSpriteVisual();
110
+ }
111
+
112
+ // FinalizeUpdate will only be called if this method is overridden
113
+ virtual void FinalizeUpdate(const winrt::Microsoft::ReactNative::ComponentView &/*view*/,
114
+ winrt::Microsoft::ReactNative::ComponentViewUpdateMask /*mask*/) noexcept {
115
+ }
116
+
117
+ ::_COMPONENT_VIEW_COMMAND_HANDLERS_::
118
+
119
+ ::_COMPONENT_VIEW_COMMAND_HANDLER_::
120
+
121
+ const std::shared_ptr<::_COMPONENT_NAME_::EventEmitter>& EventEmitter() const { return m_eventEmitter; }
122
+ const winrt::com_ptr<::_COMPONENT_NAME_::Props>& Props() const { return m_props; }
123
+
124
+ private:
125
+ winrt::com_ptr<::_COMPONENT_NAME_::Props> m_props;
126
+ std::shared_ptr<::_COMPONENT_NAME_::EventEmitter> m_eventEmitter;
127
+ };
128
+ `;
129
+
130
+ const registerTemplate = `
131
+ template <typename TUserData>
132
+ void Register::_COMPONENT_NAME_::NativeComponent(
133
+ winrt::Microsoft::ReactNative::IReactPackageBuilder const &packageBuilder,
134
+ std::function<void(const winrt::Microsoft::ReactNative::Composition::IReactCompositionViewComponentBuilder&)> builderCallback) noexcept {
135
+ packageBuilder.as<winrt::Microsoft::ReactNative::IReactPackageBuilderFabric>().AddViewComponent(
136
+ L"::_COMPONENT_NAME_::", [builderCallback](winrt::Microsoft::ReactNative::IReactViewComponentBuilder const &builder) noexcept {
137
+ auto compBuilder = builder.as<winrt::Microsoft::ReactNative::Composition::IReactCompositionViewComponentBuilder>();
138
+
139
+ builder.SetCreateProps(
140
+ [](winrt::Microsoft::ReactNative::ViewProps props) noexcept { return winrt::make<::_COMPONENT_NAME_::Props>(props); });
141
+
142
+ builder.SetUpdatePropsHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
143
+ const winrt::Microsoft::ReactNative::IComponentProps &newProps,
144
+ const winrt::Microsoft::ReactNative::IComponentProps &oldProps) noexcept {
145
+ auto userData = view.UserData().as<TUserData>();
146
+ userData->UpdateProps(view, newProps ? newProps.as<::_COMPONENT_NAME_::Props>() : nullptr, oldProps ? oldProps.as<::_COMPONENT_NAME_::Props>() : nullptr);
147
+ });
148
+
149
+ builder.SetUpdateEventEmitterHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
150
+ const winrt::Microsoft::ReactNative::EventEmitter &eventEmitter) noexcept {
151
+ auto userData = view.UserData().as<TUserData>();
152
+ userData->UpdateEventEmitter(std::make_shared<::_COMPONENT_NAME_::EventEmitter>(eventEmitter));
153
+ });
154
+
155
+ if constexpr (&TUserData::FinalizeUpdate != &Base::_COMPONENT_NAME_::<TUserData>::FinalizeUpdate) {
156
+ builder.SetFinalizeUpdateHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
157
+ winrt::Microsoft::ReactNative::ComponentViewUpdateMask mask) noexcept {
158
+ auto userData = view.UserData().as<TUserData>();
159
+ userData->FinalizeUpdate(view, mask);
160
+ });
161
+ }
162
+
163
+ if constexpr (&TUserData::UpdateState != &Base::_COMPONENT_NAME_::<TUserData>::UpdateState) {
164
+ builder.SetUpdateStateHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
165
+ const winrt::Microsoft::ReactNative::IComponentState &newState) noexcept {
166
+ auto userData = view.UserData().as<TUserData>();
167
+ userData->member(view, newState);
168
+ });
169
+ }
170
+
171
+ ::_REGISTER_CUSTOM_COMMAND_HANDLER_::
172
+
173
+ if constexpr (&TUserData::MountChildComponentView != &Base::_COMPONENT_NAME_::<TUserData>::MountChildComponentView) {
174
+ builder.SetMountChildComponentViewHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
175
+ const winrt::Microsoft::ReactNative::MountChildComponentViewArgs &args) noexcept {
176
+ auto userData = view.UserData().as<TUserData>();
177
+ return userData->MountChildComponentView(view, args);
178
+ });
179
+ }
180
+
181
+ if constexpr (&TUserData::UnmountChildComponentView != &Base::_COMPONENT_NAME_::<TUserData>::UnmountChildComponentView) {
182
+ builder.SetUnmountChildComponentViewHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
183
+ const winrt::Microsoft::ReactNative::UnmountChildComponentViewArgs &args) noexcept {
184
+ auto userData = view.UserData().as<TUserData>();
185
+ return userData->UnmountChildComponentView(view, args);
186
+ });
187
+ }
188
+
189
+ compBuilder.SetViewComponentViewInitializer([](const winrt::Microsoft::ReactNative::ComponentView &view) noexcept {
190
+ auto userData = winrt::make_self<TUserData>();
191
+ if constexpr (&TUserData::Initialize != &Base::_COMPONENT_NAME_::<TUserData>::Initialize) {
192
+ userData->Initialize(view);
193
+ }
194
+ view.UserData(*userData);
195
+ });
196
+
197
+ if constexpr (&TUserData::CreateVisual != &Base::_COMPONENT_NAME_::<TUserData>::CreateVisual) {
198
+ compBuilder.SetCreateVisualHandler([](const winrt::Microsoft::ReactNative::ComponentView &view) noexcept {
199
+ auto userData = view.UserData().as<TUserData>();
200
+ return userData->CreateVisual(view);
201
+ });
202
+ }
203
+
204
+ // Allow app to further customize the builder
205
+ if (builderCallback) {
206
+ builderCallback(compBuilder);
207
+ }
208
+ });
209
+ }
210
+ `;
211
+
212
+ const fileTemplate = `
213
+ ${headerTemplate}
214
+
215
+ namespace ::_NAMESPACE_:: {
216
+
217
+ ::_COMPONENT_PROP_OBJECT_TYPES_::
218
+ ::_COMPONENT_PROP_TYPES_::
219
+
220
+ ::_COMPONENT_EVENT_EMITTER_::
221
+
222
+ ::_BASE_COMPONENT_STRUCT_::
223
+
224
+ ::_COMPONENT_REGISTRATION_::
225
+ } // namespace ::_NAMESPACE_::
226
+ `;
227
+
228
+ function capitalizeFirstLetter(s: string) {
229
+ return s.charAt(0).toUpperCase() + s.slice(1);
230
+ }
231
+
232
+ export function createComponentGenerator({
233
+ namespace,
234
+ cppStringType,
235
+ }: {
236
+ namespace: string;
237
+ cppStringType: CppStringTypes;
238
+ }) {
239
+ return (
240
+ _libraryName: string,
241
+ schema: SchemaType,
242
+ _moduleSpecName: string,
243
+ ): FilesOutput => {
244
+ const files = new Map<string, string>();
245
+
246
+ const cppCodegenOptions = {cppStringType};
247
+
248
+ for (const componentName of Object.keys(schema.modules)) {
249
+ const component = schema.modules[componentName];
250
+ setPreferredModuleName(componentName);
251
+
252
+ if (component.type === 'Component') {
253
+ console.log(`Generating ${componentName}.g.h`);
254
+
255
+ const componentShape = component.components[componentName];
256
+
257
+ componentShape.extendsProps.forEach(propsBaseType => {
258
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
259
+ if (propsBaseType.type !== 'ReactNativeBuiltInType' || propsBaseType.knownTypeName !== 'ReactNativeCoreViewProps') {
260
+ throw new Error('Currently only supports props extending from ViewProps');
261
+ }
262
+ });
263
+
264
+ // Props
265
+ const propObjectAliases: AliasMap<ObjectTypeAnnotation<PropTypeAnnotation>> = {types:{}, jobs: []};
266
+ const propsName = `${componentName}Props`;
267
+ const propsFields = componentShape.props.map(prop => {
268
+ const propType = translateComponentPropsFieldType(prop.typeAnnotation, propObjectAliases, `${propsName}_${prop.name}`, cppCodegenOptions);
269
+ return ` REACT_FIELD(${prop.name})\n ${(prop.optional && !propType.alreadySupportsOptionalOrHasDefault) ? `std::optional<${propType.type}>` : propType.type} ${prop.name}${propType.initializer};\n`;
270
+ }).join('\n');
271
+
272
+ const propObjectTypes = propObjectAliases.jobs.map(propObjectTypeName => {
273
+ const propObjectType = propObjectAliases.types[propObjectTypeName]!;
274
+ const propsObjectFields = propObjectType.properties.map(property => {
275
+ const propType = translateComponentPropsFieldType(property.typeAnnotation, propObjectAliases, `${propsName}_${property.name}`, cppCodegenOptions);
276
+ return ` REACT_FIELD(${property.name})\n ${(property.optional && !propType.alreadySupportsOptionalOrHasDefault) ? `std::optional<${propType.type}>` : propType.type} ${property.name}${propType.initializer};\n`;
277
+ }).join('\n');
278
+
279
+ return propsObjectTemplate.replace(/::_OBJECT_NAME_::/g, getAliasCppName(propObjectTypeName)).replace(/::_OBJECT_FIELDS_::/g, propsObjectFields);
280
+ }).join('\n');
281
+
282
+
283
+ // Events
284
+ const eventObjectAliases: AliasMap<ObjectTypeAnnotation<EventTypeAnnotation>> = {types:{}, jobs: []};
285
+ const eventEmitterName = `${componentName}EventEmitter`;
286
+ const eventEmitterMethods = componentShape.events.filter(event => event.typeAnnotation.argument).map(event => {
287
+ if (event.typeAnnotation.argument?.baseTypes) {
288
+ throw new Error('Events with base type arguments not currently supported');
289
+ }
290
+
291
+ // Called to collect the eventObjectAliases
292
+ translateComponentEventType(event.typeAnnotation.argument!, eventObjectAliases, `${event.name}`, cppCodegenOptions);
293
+
294
+ // onSomething -> something
295
+ let eventNameLower = event.name.replace('on', '');
296
+ eventNameLower = eventNameLower[0].toLowerCase() + eventNameLower.slice(1);
297
+
298
+ return eventEmitterMethodTemplate
299
+ .replace(/::_EVENT_NAME_::/g,event.name)
300
+ .replace(/::_EVENT_NAME_NO_ON_::/g,eventNameLower)
301
+ .replace(/::_EVENT_OBJECT_TYPE_::/g, event.name.replace('on', 'On'));
302
+ }).join('\n\n');
303
+
304
+ const eventObjects = eventObjectAliases.jobs.map(eventObjectTypeName => {
305
+ const eventObjectType = eventObjectAliases.types[eventObjectTypeName]!;
306
+ const eventObjectFields = eventObjectType.properties.map(property => {
307
+ const eventPropType = translateComponentEventType(property.typeAnnotation, eventObjectAliases, eventObjectTypeName, cppCodegenOptions);
308
+ return ` REACT_FIELD(${property.name})\n ${(property.optional && !eventPropType.alreadySupportsOptionalOrHasDefault) ? `std::optional<${eventPropType.type}>` : eventPropType.type} ${property.name}${eventPropType.initializer};\n`;
309
+ }).join('\n');
310
+ return eventsObjectTemplate.replace(/::_OBJECT_NAME_::/g, `${componentName}_${eventObjectTypeName.replace('on', 'On')}`).replace(/::_OBJECT_FIELDS_::/g, eventObjectFields);
311
+ }).join('\n');
312
+
313
+ const eventObjectUsings = eventObjectAliases.jobs.map(eventObjectTypeName => {
314
+ return ` using ${eventObjectTypeName.replace('on', 'On')} = ${componentName}_${eventObjectTypeName.replace('on', 'On')};`
315
+ }).join('\n');
316
+
317
+ const eventEmitter = eventEmitterTemplate
318
+ .replace(/::_COMPONENT_EVENT_OBJECT_TYPES_::/g, eventObjects)
319
+ .replace(/::_EVENT_EMITTER_METHODS_::/g, eventEmitterMethods)
320
+ .replace(/::_EVENT_EMITTER_USINGS_::/g, eventObjectUsings);
321
+
322
+
323
+ // Commands
324
+ const commandAliases: AliasMap<ObjectTypeAnnotation<CommandParamTypeAnnotation>> = {types:{}, jobs: []};
325
+ const hasAnyCommands = (componentShape.commands.length !== 0);
326
+ const commandHandlers = hasAnyCommands ? componentShape.commands.map(command => {
327
+ const commandArgs = command.typeAnnotation.params.map(param => {
328
+ const commandArgType = translateCommandParamType(param.typeAnnotation, commandAliases, `${componentName}_${command.name}`, cppCodegenOptions);
329
+ return `${(param.optional && !commandArgType.alreadySupportsOptionalOrHasDefault) ? `std::optional<${commandArgType.type}>` : commandArgType.type} ${param.name}`;
330
+ }).join(', ');
331
+
332
+ return ` // You must provide an implementation of this method to handle the "${command.name}" command
333
+ virtual void Handle${capitalizeFirstLetter(command.name)}Command(${commandArgs}) noexcept = 0;`;
334
+ }).join('\n\n') : '';
335
+
336
+
337
+ const commandHandler = hasAnyCommands ? `void HandleCommand(const winrt::Microsoft::ReactNative::ComponentView &view, winrt::hstring commandName, const winrt::Microsoft::ReactNative::IJSValueReader &args) noexcept {
338
+ args;
339
+ auto userData = view.UserData().as<TUserData>();
340
+ ${componentShape.commands.map(command => {
341
+ const commaSeparatedCommandArgs = command.typeAnnotation.params.map(param => param.name).join(', ');
342
+ return ` if (commandName == L"${command.name}") {
343
+ ${command.typeAnnotation.params.length !== 0 ? ` ${command.typeAnnotation.params.map(param => {
344
+ const commandArgType = translateCommandParamType(param.typeAnnotation, commandAliases, `${componentName}_${command.name}`, cppCodegenOptions);
345
+ return `${(param.optional && !commandArgType.alreadySupportsOptionalOrHasDefault) ? `std::optional<${commandArgType.type}>` : commandArgType.type} ${param.name};`;
346
+ }).join('\n')}
347
+ winrt::Microsoft::ReactNative::ReadArgs(args, ${commaSeparatedCommandArgs});` : ''}
348
+ userData->Handle${capitalizeFirstLetter(command.name)}Command(${commaSeparatedCommandArgs});
349
+ return;
350
+ }`
351
+ }).join('\n\n')}
352
+ }` : '';
353
+
354
+ const registerCommandHandler = hasAnyCommands ? ` builder.SetCustomCommandHandler([](const winrt::Microsoft::ReactNative::ComponentView &view,
355
+ winrt::hstring commandName,
356
+ const winrt::Microsoft::ReactNative::IJSValueReader &args) noexcept {
357
+ auto userData = view.UserData().as<TUserData>();
358
+ userData->HandleCommand(view, commandName, args);
359
+ });` : '';
360
+
361
+ const baseType = baseStructTemplate
362
+ .replace(/::_COMPONENT_VIEW_COMMAND_HANDLERS_::/g, commandHandlers)
363
+ .replace(/::_COMPONENT_VIEW_COMMAND_HANDLER_::/g, commandHandler);
364
+
365
+ // Registration
366
+ const componentRegistration = registerTemplate.replace(/::_REGISTER_CUSTOM_COMMAND_HANDLER_::/g, registerCommandHandler);
367
+
368
+ // Final output
369
+ const replaceContent = function (template: string): string {
370
+ return template
371
+ .replace(/::_COMPONENT_PROP_OBJECT_TYPES_::/g, propObjectTypes)
372
+ .replace(/::_COMPONENT_PROP_TYPES_::/g, propsTemplate)
373
+ .replace(/::_COMPONENT_EVENT_EMITTER_::/g, eventEmitter)
374
+ .replace(/::_BASE_COMPONENT_STRUCT_::/g, baseType)
375
+ .replace(/::_COMPONENT_REGISTRATION_::/g, componentRegistration)
376
+ .replace(/::_EVENT_EMITTER_NAME_::/g, eventEmitterName)
377
+ .replace(/::_PROPS_NAME_::/g, propsName)
378
+ .replace(/::_COMPONENT_NAME_::/g, componentName)
379
+ .replace(/::_PROPS_FIELDS_::/g, propsFields)
380
+ .replace(/::_NAMESPACE_::/g, namespace)
381
+ .replace(/\n\n\n+/g, '\n\n');
382
+ };
383
+
384
+ files.set(
385
+ `${componentName}.g.h`,
386
+ replaceContent(fileTemplate),
387
+ );
388
+ }
389
+ }
390
+
391
+ return files;
392
+ };
393
+ }
@@ -14,6 +14,7 @@ import type {
14
14
  NativeModuleParamTypeAnnotation,
15
15
  NativeModuleReturnTypeAnnotation,
16
16
  NativeModuleSchema,
17
+ UnsafeAnyTypeAnnotation,
17
18
  Nullable,
18
19
  SchemaType,
19
20
  } from '@react-native/codegen/lib/CodegenSchema';
@@ -65,7 +66,7 @@ function translateType(
65
66
  | NativeModuleBaseTypeAnnotation
66
67
  | NativeModuleParamTypeAnnotation
67
68
  | NativeModuleReturnTypeAnnotation
68
- >,
69
+ > | UnsafeAnyTypeAnnotation,
69
70
  ): string {
70
71
  // avoid: Property 'type' does not exist on type 'never'
71
72
  const returnType = type.type;
@@ -80,7 +81,7 @@ function translateType(
80
81
  case 'BooleanTypeAnnotation':
81
82
  return 'boolean';
82
83
  case 'ArrayTypeAnnotation':
83
- if (type.elementType) {
84
+ if (type.elementType.type !== 'AnyTypeAnnotation') {
84
85
  return `${translateType(type.elementType)}[]`;
85
86
  } else {
86
87
  return `Array`;
@@ -12,6 +12,7 @@ import type {
12
12
  NativeModuleUnionTypeAnnotation,
13
13
  NativeModuleStringTypeAnnotation,
14
14
  NativeModuleFunctionTypeAnnotation,
15
+ UnsafeAnyTypeAnnotation,
15
16
  Nullable,
16
17
  } from '@react-native/codegen/lib/CodegenSchema';
17
18
  import {
@@ -50,7 +51,7 @@ export function translateFieldOrReturnType(
50
51
  | NativeModuleBaseTypeAnnotation
51
52
  | NativeModuleStringTypeAnnotation
52
53
  | NativeModuleFunctionTypeAnnotation
53
- >,
54
+ > | UnsafeAnyTypeAnnotation,
54
55
  aliases: AliasMap,
55
56
  baseAliasName: string,
56
57
  callerName: 'translateField' | 'translateReturnType',
@@ -70,7 +71,7 @@ export function translateFieldOrReturnType(
70
71
  case 'BooleanTypeAnnotation':
71
72
  return 'bool';
72
73
  case 'ArrayTypeAnnotation':
73
- if (type.elementType) {
74
+ if (type.elementType.type !== 'AnyTypeAnnotation') {
74
75
  return `std::vector<${translateFieldOrReturnType(
75
76
  type.elementType,
76
77
  aliases,
@@ -110,6 +111,8 @@ export function translateFieldOrReturnType(
110
111
  case 'EnumDeclaration':
111
112
  case 'UnionTypeAnnotation':
112
113
  return translateUnionReturnType(type, options);
114
+ case 'AnyTypeAnnotation':
115
+ return '::React::JSValue?';
113
116
  default:
114
117
  throw new Error(`Unhandled type in ${callerName}: ${returnType}`);
115
118
  }