Add GraphNode example for Cxx TMs (#41766)

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

Changelog: [Internal]

Adds a simple example showing a recursive node, stored inside a collection in a Cxx TM.

Currently we can't auto-generate [the necessary C++ Types](https://reactnative.dev/docs/next/the-new-architecture/cxx-custom-types#struct-generator) - but we can add it later if this scenarios becomes really common.

Reviewed By: rshest

Differential Revision: D51783974

fbshipit-source-id: 7352db1a354cd7da32febc650f7cc5e10dd16d2d
This commit is contained in:
Christoph Purrer
2023-12-04 04:19:47 -08:00
committed by Facebook GitHub Bot
parent 385473522c
commit 5754b4a123
4 changed files with 61 additions and 0 deletions
@@ -90,6 +90,42 @@ struct CustomHostObjectRef {
using CustomHostObject = HostObjectWrapper<CustomHostObjectRef>;
#pragma mark - recursive objects
struct GraphNode {
std::string label;
std::optional<std::vector<GraphNode>> neighbors;
};
template <>
struct Bridging<GraphNode> {
static GraphNode fromJs(
jsi::Runtime& rt,
const jsi::Object& value,
const std::shared_ptr<CallInvoker>& jsInvoker) {
GraphNode result{
bridging::fromJs<std::string>(
rt, value.getProperty(rt, "label"), jsInvoker),
bridging::fromJs<std::optional<std::vector<GraphNode>>>(
rt, value.getProperty(rt, "neighbors"), jsInvoker)};
return result;
}
static jsi::Object toJs(
jsi::Runtime& rt,
const GraphNode value,
const std::shared_ptr<CallInvoker>& jsInvoker) {
auto result = facebook::jsi::Object(rt);
result.setProperty(rt, "label", bridging::toJs(rt, value.label, jsInvoker));
if (value.neighbors) {
result.setProperty(
rt,
"neighbors",
bridging::toJs(rt, value.neighbors.value(), jsInvoker));
}
return result;
}
};
#pragma mark - implementation
class NativeCxxModuleExample
: public NativeCxxModuleExampleCxxSpec<NativeCxxModuleExample> {
@@ -120,6 +156,8 @@ class NativeCxxModuleExample
jsi::Runtime& rt,
std::shared_ptr<CustomHostObject> arg);
GraphNode getGraphNode(jsi::Runtime& rt, GraphNode arg);
NativeCxxModuleExampleCxxEnumFloat getNumEnum(
jsi::Runtime& rt,
NativeCxxModuleExampleCxxEnumInt arg);