Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PoC: use raw jsi::Value prop w/ fabric views #386

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
9 changes: 9 additions & 0 deletions example/android/settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,12 @@ rootProject.name = 'NitroExample'

include ':app'
includeBuild('../../node_modules/@react-native/gradle-plugin')

includeBuild('../../node_modules/react-native') {
dependencySubstitution {
substitute(module("com.facebook.react:react-android")).using(project(":packages:react-native:ReactAndroid"))
substitute(module("com.facebook.react:react-native")).using(project(":packages:react-native:ReactAndroid"))
substitute(module("com.facebook.react:hermes-android")).using(project(":packages:react-native:ReactAndroid:hermes-engine"))
substitute(module("com.facebook.react:hermes-engine")).using(project(":packages:react-native:ReactAndroid:hermes-engine"))
}
}
10 changes: 2 additions & 8 deletions example/ios/NitroExample.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -624,10 +624,7 @@
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = (
"$(inherited)",
" ",
);
OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG";
Expand Down Expand Up @@ -701,10 +698,7 @@
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = (
"$(inherited)",
" ",
);
OTHER_LDFLAGS = "$(inherited) ";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../../node_modules/react-native";
SDKROOT = iphoneos;
SWIFT_OBJC_INTEROP_MODE = objcxx;
Expand Down
2 changes: 1 addition & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"lint": "eslint \"**/*.{js,ts,tsx}\" --fix",
"lint-ci": "eslint \"**/*.{js,ts,tsx}\" -f @jamesacarr/github-actions",
"bundle-install": "bundle install",
"pods": "cd ios && bundle exec pod install && rm -rf .xcode.env.local",
"pods": "cd ios && bundle exec pod install",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw: without this change i can't run the example app. I am pretty sure that deleting the .xcode.env.local is wrong.
Will remove this change in a moment though

"build:android": "cd android && ./gradlew assembleDebug --no-daemon --console=plain -PreactNativeArchitectures=arm64-v8a",
"build:ios": "cd ios && xcodebuild -workspace NitroExample.xcworkspace -scheme NitroExample -configuration Debug -sdk iphonesimulator CC=clang CPLUSPLUS=clang++ LD=clang LDPLUSPLUS=clang++ GCC_OPTIMIZATION_LEVEL=0 GCC_PRECOMPILE_PREFIX_HEADER=YES ASSETCATALOG_COMPILER_OPTIMIZATION=time DEBUG_INFORMATION_FORMAT=dwarf COMPILER_INDEX_STORE_ENABLE=NO"
},
Expand Down
8 changes: 8 additions & 0 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import { useColors } from './useColors'
import { Image } from 'react-native'
import { BenchmarksScreen } from './screens/BenchmarksScreen'
import { CustomViewScreen } from './screens/CustomViewScreen'

const dna = require('./img/dna.png')
const rocket = require('./img/rocket.png')
Expand Down Expand Up @@ -51,6 +52,13 @@ export default function App() {
),
}}
/>
<Tabs.Screen
name="Custom View"
component={CustomViewScreen}
options={{
tabBarLabel: 'Custom View',
}}
/>
</Tabs.Navigator>
</NavigationContainer>
)
Expand Down
23 changes: 23 additions & 0 deletions example/src/components/CustomView.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type HostComponent, type ViewProps } from 'react-native'
import { type TestObjectSwiftKotlin } from 'react-native-nitro-image'

// This has no type exports :/
import * as NativeComponentRegistry from 'react-native/Libraries/NativeComponent/NativeComponentRegistry'

// TODO: types for this are not exported / only exist in flow
const viewConfig = {
uiViewClassName: 'CustomView',
bubblingEventTypes: {},
directEventTypes: {},
validAttributes: {
nativeProp: true,
},
}

// TODO: try passing a nitro object here and casting it on the native side!
type NativeProps = ViewProps & {
nativeProp: TestObjectSwiftKotlin
}

export const CustomView: HostComponent<NativeProps> =
NativeComponentRegistry.get<NativeProps>('CustomView', () => viewConfig)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does requireNativeComponent(..) not work here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it might, we'd have to test this

44 changes: 44 additions & 0 deletions example/src/screens/CustomViewScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import React from 'react'
import { Button, View } from 'react-native'
import { CustomView } from '../components/CustomView'
import { type TestObjectSwiftKotlin } from 'react-native-nitro-image'
import { NitroModules } from 'react-native-nitro-modules'

function makeObject() {
const obj = NitroModules.createHybridObject<TestObjectSwiftKotlin>(
'TestObjectSwiftKotlin'
)
obj.bigintValue = BigInt(Math.random() * 1000000000000000000 + '')
console.log('makeObject', obj)
return obj
}

export function CustomViewScreen() {
const [state, setState] = React.useState(makeObject)

return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'lightblue',
}}
>
<CustomView
nativeProp={state}
style={{
width: 200,
height: 200,
backgroundColor: 'red',
}}
/>
<Button
title="Increment"
onPress={() => {
setState(makeObject())
}}
/>
</View>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

#include "NitroImageOnLoad.hpp"



JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
return facebook::jni::initialize(vm, [=] { margelo::nitro::image::initialize(vm); });
return facebook::jni::initialize(vm, [=] {
margelo::nitro::image::initialize(vm);
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.margelo.nitro.image;

import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.fabric.StateWrapperImpl;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.bridge.ReadableNativeMap;

public class NitroExampleViewManager extends SimpleViewManager<View> {
@NonNull
@Override
public String getName() {
return "CustomView";
}

@NonNull
@Override
protected View createViewInstance(@NonNull ThemedReactContext reactContext) {
return new View(reactContext);
}

@Nullable
@Override
public Object updateState(@NonNull View view, ReactStylesDiffMap props, StateWrapper stateWrapper) {
StateWrapperImpl stateWrapperImpl = (StateWrapperImpl) stateWrapper;

// TODO: i am sure there is a way to make this casting a bit better
// HybridTestObjectKotlin nativeProp = ValueFromStateWrapper.getNativeProp(stateWrapper, "nativeProp", HybridTestObjectKotlin.class);
HybridTestObjectSwiftKotlinSpec nativeProp = ValueFromStateWrapper.valueFromStateWrapper(stateWrapperImpl);
long value = nativeProp.getBigintValue();
Log.d("NitroExampleViewManager", "Value from state: " + value);

// TODO: @Marc - here we could call a method that the user has to implement for the prop update

return super.updateState(view, props, stateWrapper);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.BaseReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.TurboReactPackage;
import com.facebook.react.uimanager.ViewManager;
import com.margelo.nitro.core.HybridObject;
import com.margelo.nitro.core.HybridObjectRegistry;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Supplier;

public class NitroImagePackage extends TurboReactPackage {
Expand All @@ -28,6 +33,15 @@ public ReactModuleInfoProvider getReactModuleInfoProvider() {
};
}

@Override
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
List<ViewManager> viewManagers = new ArrayList<>();

viewManagers.add(new NitroExampleViewManager());

return viewManagers;
}

static {
System.loadLibrary("NitroImage");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.margelo.nitro.image;

import com.facebook.jni.annotations.DoNotStrip;
import com.facebook.react.fabric.StateWrapperImpl;

@DoNotStrip
public class ValueFromStateWrapper {
@DoNotStrip
public static native HybridTestObjectSwiftKotlinSpec valueFromStateWrapper(StateWrapperImpl stateWrapper);
}
90 changes: 90 additions & 0 deletions packages/react-native-nitro-image/ios/NitroExampleView.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#import <React/RCTComponentViewFactory.h>
#import <React/UIView+ComponentViewProtocol.h>
#import <UIKit/UIKit.h>
#import <react/renderer/componentregistry/ComponentDescriptorRegistry.h>

#import <React/RCTViewComponentView.h>
#import <jsi/jsi.h>
#import <react/renderer/components/view/ConcreteViewShadowNode.h>
#import <react/renderer/components/view/ViewEventEmitter.h>
#import <react/renderer/components/view/ViewProps.h>
#import <react/renderer/core/ConcreteComponentDescriptor.h>
#import <react/renderer/core/PropsParserContext.h>

#import "HybridTestObjectCppSpec.hpp"
//#import "JSIConverter.hpp"

// for prop conversion
#import <react/renderer/core/propsConversions.h>


using namespace facebook;
using namespace facebook::react;
using namespace margelo::nitro;

// We have to inherit from ViewProps so that we can
class CustomViewProps final : public ViewProps {
public:
CustomViewProps() = default;
CustomViewProps(const PropsParserContext& context, const CustomViewProps& sourceProps, const RawProps& rawProps)
: ViewProps(context, sourceProps, rawProps) {
if (rawProps.isEmpty()) {
// There is some code path in RawPropsParser.cpp where we expect to collect all possible keys (prop names) upfront
// during the init phase. Calling this .at() method while the rawProps is empty, will cause this prop value to be indexed …
// Otherwise we'd get a crash when trying to access it later.
// We should really also try to merge the PR i have for providing alternative RawProps parser !!
rawProps.at("nativeProp", nullptr, nullptr);
Comment on lines +32 to +36
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if I fully understand - is this still needed? Do I need to do this for every prop?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think just calling rawProps.at() and check if it is null or not should be enough. It should never be null, except for when the internally the ui manager creates those once without the values from JS (thats when 'isEmpty() will return true)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but yeah, it has to be called at this point once, as the .at() method will insert the props key into a map. If later on the prop name is not in this key map it will always return null. Super weird I know.
my main idea is that we are able to write our own prop parser to work around this

return;
}

const RawValue* rawValue = rawProps.at("nativeProp", nullptr, nullptr);
// Option 1: Manually cast it
const auto& [runtime, value] = (std::pair<jsi::Runtime*, const jsi::Value&>)*rawValue;
std::shared_ptr<HybridTestObjectCppSpec> prop = margelo::nitro::JSIConverter<std::shared_ptr<HybridTestObjectCppSpec>>::fromJSI(*runtime, value);
auto test = prop;
}

std::shared_ptr<HybridTestObjectCppSpec> nativeProp;
};

class CustomViewState {
public:
CustomViewState() = default;
};

extern const char CustomViewComponentName[] = "CustomView";
using ComponentShadowNode = ConcreteViewShadowNode<CustomViewComponentName, CustomViewProps,
ViewEventEmitter, // default one
CustomViewState>;

class CustomViewComponentDescriptor : public ConcreteComponentDescriptor<ComponentShadowNode> {
public:
CustomViewComponentDescriptor(const ComponentDescriptorParameters& parameters)
// Construct a new RawPropsParser to which we pass true which enables JSI prop parsing
: ConcreteComponentDescriptor(parameters, std::make_unique<RawPropsParser>(true)) {}
};


@interface ManualFabricComponentView : RCTViewComponentView // UIView <RCTComponentViewProtocol>

@end

@implementation ManualFabricComponentView

// Adds the component to the known components
+ (void)load {
[RCTComponentViewFactory.currentComponentViewFactory registerComponentViewClass:[ManualFabricComponentView class]];
}

+ (ComponentDescriptorProvider)componentDescriptorProvider {
return concreteComponentDescriptorProvider<CustomViewComponentDescriptor>();
}

- (void)updateProps:(const facebook::react::Props::Shared&)props oldProps:(const facebook::react::Props::Shared&)oldProps {
const auto& newViewProps = *std::static_pointer_cast<CustomViewProps const>(props);
// NSLog(@"NativeProp value: %s", newViewProps.nativeProp.c_str());

[super updateProps:props oldProps:oldProps];
}

@end
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ target_sources(
../nitrogen/generated/android/c++/JHybridTestObjectSwiftKotlinSpec.cpp
../nitrogen/generated/android/c++/JHybridBaseSpec.cpp
../nitrogen/generated/android/c++/JHybridChildSpec.cpp
# Utility
../nitrogen/generated/android/c++/JValueFromStateWrapper.cpp
../nitrogen/generated/android/c++/CustomComponentDescriptor.cpp
)

# Add all libraries required by the generated specs
Expand Down Expand Up @@ -66,3 +69,20 @@ else()
ReactAndroid::react_nativemodule_core # <-- RN: TurboModules Core
)
endif()

# From node_modules/react-native/ReactAndroid/cmake-utils/folly-flags.cmake
# Used in node_modules/react-native/ReactAndroid/cmake-utils/ReactNative-application.cmake
target_compile_definitions(
NitroImage
PRIVATE
-DFOLLY_NO_CONFIG=1
-DFOLLY_HAVE_CLOCK_GETTIME=1
-DFOLLY_USE_LIBCPP=1
-DFOLLY_CFG_NO_COROUTINES=1
-DFOLLY_MOBILE=1
-DFOLLY_HAVE_RECVMMSG=1
-DFOLLY_HAVE_PTHREAD=1
# Once we target android-23 above, we can comment
# the following line. NDK uses GNU style stderror_r() after API 23.
-DFOLLY_HAVE_XSI_STRERROR_R=1
)
Comment on lines +73 to +88
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do I really need those..? @hannojg

Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@
#include <NitroModules/DefaultConstructableObject.hpp>
#include "HybridTestObjectCpp.hpp"

// For Components:
#include <react/fabric/CoreComponentsRegistry.h>
#include <react/renderer/core/ConcreteComponentDescriptor.h>
#include "CustomComponentDescriptor.h"
#include "JValueFromStateWrapper.h"

namespace margelo::nitro::image {

int initialize(JavaVM* vm) {
Expand All @@ -50,6 +56,7 @@ int initialize(JavaVM* vm) {
margelo::nitro::image::JFunc_void_std__string::registerNatives();
margelo::nitro::image::JHybridBaseSpec::registerNatives();
margelo::nitro::image::JHybridChildSpec::registerNatives();
margelo::nitro::image::JValueFromStateWrapper::registerNatives();

// Register Nitro Hybrid Objects
HybridObjectRegistry::registerHybridObjectConstructor(
Expand Down Expand Up @@ -97,6 +104,11 @@ int initialize(JavaVM* vm) {
return JNISharedPtr::make_shared_from_jni<JHybridChildSpec>(globalRef);
}
);

// Register view components
auto provider = concreteComponentDescriptorProvider<CustomViewComponentDescriptor>();
auto providerRegistry = facebook::react::CoreComponentsRegistry::sharedProviderRegistry();
providerRegistry->add(provider);
});
}

Expand Down
Loading