@react-native-gpui/nitro-modules 0.0.0-stage → 0.37.0-alpha.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@react-native-gpui/nitro-modules` are listed here. Each version's section becomes the notes of its GitHub release.
4
+
5
+ ## 0.37.0-alpha.1 - 2026-11-27
6
+
7
+ - First release, for `react-native-nitro-modules` 0.37.x.
8
+ - Nitro Hybrid Objects written in C++ run on desktop: `NitroModules.createHybridObject`, promises, callbacks from any thread and `ArrayBuffer`.
9
+ - Nitro Views written in C++ are hosted as C++ host components. A library adds desktop support with `rn_gpui_nitro_library` in its CMake and a view class that inherits `HybridDesktopView`; see `docs/nitro-views.md`.
10
+ - `rn_gpui_nitro_library` accepts a package without `nitro.json`; it then has no autolinked Hybrid Objects.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Streetwriters
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @react-native-gpui/nitro-modules
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Adapter for [`react-native-nitro-modules`](https://github.com/mrousavy/nitro) (MIT): runs Nitro Hybrid Objects and Nitro Views written in C++ on the desktop renderer.
4
+
5
+ Part of [react-native-gpui](https://github.com/streetwriters/react-native-gpui), React Native for macOS, Windows and Linux.
6
+
7
+ ## Install
8
+
9
+ Install it next to `react-native-nitro-modules`:
10
+
11
+ ```sh
12
+ npm install react-native-nitro-modules@0.37.x @react-native-gpui/nitro-modules
13
+ ```
14
+
15
+ Keep using `NitroModules.createHybridObject` and `getHostComponent` as you do on iOS and Android; the JavaScript API is unchanged. Autolinking builds the desktop side when the app is built.
16
+
17
+ A Nitro library needs its own desktop support to run: its Hybrid Objects and views must be implemented in C++ and built through [`rn_gpui_nitro_library`](docs/nitro-views.md). The Swift and Kotlin implementations of a library do not run on desktop.
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { NitroModules } from 'react-native-nitro-modules';
23
+
24
+ const math = NitroModules.createHybridObject<Math>('Math');
25
+ math.add(1, 2);
26
+ ```
27
+
28
+ ## Platforms
29
+
30
+ macOS is tested. Windows and Linux build the same C++ and the platform glue for them is written, but it is not tested. A Nitro View is hosted as a native view on macOS (an `NSView` the library returns), and on Windows and Linux through the composition surface the library draws into.
31
+
32
+ ## Limitations
33
+
34
+ - Only C++ Hybrid Objects and views run. Libraries whose Nitro autolinking is Swift or Kotlin need a C++ implementation for desktop.
35
+
36
+ ## Documentation
37
+
38
+ [Adding desktop support to a Nitro library](docs/nitro-views.md)
39
+
40
+ ## License
41
+
42
+ MIT. See [LICENSE](LICENSE). `react-native-nitro-modules` is MIT, copyright Marc Rousavy.
@@ -0,0 +1,8 @@
1
+ include("${CMAKE_CURRENT_LIST_DIR}/NitroDesktop.cmake")
2
+ get_property(_nitro_core_sources GLOBAL PROPERTY RN_GPUI_NITRO_CORE_SOURCES)
3
+
4
+ file(GLOB _nitro_desktop_sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/cpp/*.cpp")
5
+ rn_gpui_nitro_prelude(${_nitro_core_sources} ${_nitro_desktop_sources})
6
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES
7
+ ${_nitro_core_sources}
8
+ ${_nitro_desktop_sources})
@@ -0,0 +1,140 @@
1
+ # Desktop build support for Nitro libraries. A library's desktop/CMakeLists.txt
2
+ # resolves @react-native-gpui/nitro-modules, includes this file and calls
3
+ # rn_gpui_nitro_library().
4
+ include_guard(GLOBAL)
5
+
6
+ if(NOT RN_GPUI_PROJECT_ROOT)
7
+ message(FATAL_ERROR "RN_GPUI_PROJECT_ROOT must be set by the build of the app")
8
+ endif()
9
+ find_program(_rn_gpui_nitro_node node REQUIRED)
10
+
11
+ # Sets <out> to the root directory of an npm package, resolved from the app.
12
+ function(rn_gpui_nitro_resolve_package out package)
13
+ execute_process(
14
+ COMMAND "${_rn_gpui_nitro_node}" -e
15
+ "process.stdout.write(require.resolve(process.argv[2] + '/package.json', {paths: [process.argv[1]]}))"
16
+ "${RN_GPUI_PROJECT_ROOT}" "${package}"
17
+ RESULT_VARIABLE _result
18
+ OUTPUT_VARIABLE _package_json
19
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
20
+ if(NOT _result EQUAL 0 OR NOT EXISTS "${_package_json}")
21
+ message(FATAL_ERROR "${package} could not be resolved from ${RN_GPUI_PROJECT_ROOT}")
22
+ endif()
23
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_package_json}")
24
+ get_filename_component(_root "${_package_json}" DIRECTORY)
25
+ set(${out} "${_root}" PARENT_SCOPE)
26
+ endfunction()
27
+
28
+ rn_gpui_nitro_resolve_package(RN_GPUI_NITRO_ROOT react-native-nitro-modules)
29
+ execute_process(
30
+ COMMAND "${_rn_gpui_nitro_node}" -e
31
+ "process.stdout.write(require(process.argv[1] + '/package.json').version)"
32
+ "${RN_GPUI_NITRO_ROOT}"
33
+ OUTPUT_VARIABLE _rn_gpui_nitro_version
34
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
35
+ if(NOT _rn_gpui_nitro_version MATCHES "^0\\.37\\.")
36
+ message(FATAL_ERROR
37
+ "@react-native-gpui/nitro-modules supports react-native-nitro-modules 0.37.x, found ${_rn_gpui_nitro_version}")
38
+ endif()
39
+
40
+ get_filename_component(RN_GPUI_NITRO_ADAPTER_DIR "${CMAKE_CURRENT_LIST_DIR}" ABSOLUTE)
41
+ # Included once for the whole build, so what the function and the other
42
+ # directories need is kept in global properties.
43
+ set_property(GLOBAL PROPERTY RN_GPUI_NITRO_ROOT "${RN_GPUI_NITRO_ROOT}")
44
+ set_property(GLOBAL PROPERTY RN_GPUI_NITRO_ADAPTER_DIR "${RN_GPUI_NITRO_ADAPTER_DIR}")
45
+ set(RN_GPUI_NITRO_INCLUDE_ROOT "${CMAKE_BINARY_DIR}/rn-gpui-nitro/include")
46
+ set(RN_GPUI_NITRO_HEADER_DIR "${RN_GPUI_NITRO_INCLUDE_ROOT}/NitroModules")
47
+
48
+ # Libraries include Nitro as <NitroModules/X.hpp>, a flat directory, so the
49
+ # headers are copied there from the package's nested layout.
50
+ file(GLOB_RECURSE _rn_gpui_nitro_headers CONFIGURE_DEPENDS
51
+ "${RN_GPUI_NITRO_ROOT}/cpp/*.hpp" "${RN_GPUI_NITRO_ROOT}/cpp/*.h")
52
+ foreach(_header IN LISTS _rn_gpui_nitro_headers)
53
+ get_filename_component(_name "${_header}" NAME)
54
+ configure_file("${_header}" "${RN_GPUI_NITRO_HEADER_DIR}/${_name}" COPYONLY)
55
+ endforeach()
56
+ # The sources are copied too: a quoted include resolves beside the including
57
+ # file first, and a header must not be reached through two paths.
58
+ set(_rn_gpui_nitro_core_sources "")
59
+ file(GLOB_RECURSE _rn_gpui_nitro_cpp CONFIGURE_DEPENDS "${RN_GPUI_NITRO_ROOT}/cpp/*.cpp")
60
+ foreach(_source IN LISTS _rn_gpui_nitro_cpp)
61
+ get_filename_component(_name "${_source}" NAME)
62
+ set(_copy "${RN_GPUI_NITRO_INCLUDE_ROOT}/../src/${_name}")
63
+ configure_file("${_source}" "${_copy}" COPYONLY)
64
+ list(APPEND _rn_gpui_nitro_core_sources "${_copy}")
65
+ endforeach()
66
+ set_property(GLOBAL PROPERTY RN_GPUI_NITRO_CORE_SOURCES ${_rn_gpui_nitro_core_sources})
67
+ configure_file("${RN_GPUI_NITRO_ADAPTER_DIR}/cpp/GPUINitroHybridView.hpp"
68
+ "${RN_GPUI_NITRO_HEADER_DIR}/GPUINitroHybridView.hpp" COPYONLY)
69
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS
70
+ "${RN_GPUI_NITRO_INCLUDE_ROOT}"
71
+ "${RN_GPUI_NITRO_HEADER_DIR}")
72
+
73
+ # Force-includes NitroDesktopPrelude.hpp into the given sources. The app target
74
+ # is created in the top-level directory, so the property is set there.
75
+ function(rn_gpui_nitro_prelude)
76
+ get_property(_adapter GLOBAL PROPERTY RN_GPUI_NITRO_ADAPTER_DIR)
77
+ set(_prelude "${_adapter}/cpp/NitroDesktopPrelude.hpp")
78
+ if(MSVC)
79
+ set(_options "/FI${_prelude}")
80
+ else()
81
+ set(_options -include "${_prelude}")
82
+ endif()
83
+ if(ARGN)
84
+ set_source_files_properties(${ARGN} DIRECTORY "${CMAKE_SOURCE_DIR}"
85
+ PROPERTIES COMPILE_OPTIONS "${_options}")
86
+ endif()
87
+ endfunction()
88
+
89
+ # rn_gpui_nitro_library(PACKAGE <npm-name>
90
+ # [SOURCES <files>...] [INCLUDE_DIRS <dirs>...]
91
+ # [HYBRIDS "Name=ImplClass"...] [VIEWS "ViewName=ImplClass"...])
92
+ #
93
+ # Adds the nitrogen output of PACKAGE and its C++ sources to the app, registers
94
+ # the Hybrid Objects `nitro.json` autolinks for C++ (and HYBRIDS; a package
95
+ # without nitro.json has no autolinked ones) and hosts each
96
+ # of VIEWS as a C++ host component. The package's react-native.config.js must
97
+ # declare every view under hostComponents with `cpp: true`.
98
+ function(rn_gpui_nitro_library)
99
+ cmake_parse_arguments(ARG "" "PACKAGE" "SOURCES;INCLUDE_DIRS;HYBRIDS;VIEWS" ${ARGN})
100
+ if(NOT ARG_PACKAGE)
101
+ message(FATAL_ERROR "rn_gpui_nitro_library requires PACKAGE")
102
+ endif()
103
+ get_property(RN_GPUI_NITRO_ADAPTER_DIR GLOBAL PROPERTY RN_GPUI_NITRO_ADAPTER_DIR)
104
+ rn_gpui_nitro_resolve_package(_package_root "${ARG_PACKAGE}")
105
+ set(_nitro_json "${_package_root}/nitro.json")
106
+ set(_generated "${_package_root}/nitrogen/generated/shared/c++")
107
+ file(GLOB_RECURSE _generated_sources CONFIGURE_DEPENDS "${_generated}/*.cpp")
108
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_nitro_json}")
109
+
110
+ string(REGEX REPLACE "[^A-Za-z0-9_]" "_" _sanitized "${ARG_PACKAGE}")
111
+ set(_init_source "${CMAKE_BINARY_DIR}/rn-gpui-nitro/${_sanitized}/NitroDesktopInit.cpp")
112
+ set(_generator_args "")
113
+ foreach(_hybrid IN LISTS ARG_HYBRIDS)
114
+ list(APPEND _generator_args --hybrid "${_hybrid}")
115
+ endforeach()
116
+ foreach(_view IN LISTS ARG_VIEWS)
117
+ list(APPEND _generator_args --view "${_view}")
118
+ string(REGEX REPLACE "=.*$" "" _view_name "${_view}")
119
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
120
+ "${_generated}/views/Hybrid${_view_name}Component.hpp")
121
+ endforeach()
122
+ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
123
+ "${RN_GPUI_NITRO_ADAPTER_DIR}/generate-nitro-desktop.mjs")
124
+ execute_process(
125
+ COMMAND "${_rn_gpui_nitro_node}" "${RN_GPUI_NITRO_ADAPTER_DIR}/generate-nitro-desktop.mjs"
126
+ "${_package_root}" "${_init_source}" "${_sanitized}" ${_generator_args}
127
+ RESULT_VARIABLE _generate_result
128
+ ERROR_VARIABLE _generate_error)
129
+ if(NOT _generate_result EQUAL 0)
130
+ message(FATAL_ERROR "Nitro desktop registration for ${ARG_PACKAGE} failed: ${_generate_error}")
131
+ endif()
132
+
133
+ rn_gpui_nitro_prelude(${_generated_sources} ${ARG_SOURCES} "${_init_source}")
134
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_SOURCES
135
+ ${_generated_sources} ${ARG_SOURCES} "${_init_source}")
136
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INCLUDE_DIRS
137
+ "${_generated}" "${_generated}/views" ${ARG_INCLUDE_DIRS})
138
+ set_property(GLOBAL APPEND PROPERTY RN_GPUI_APP_CPP_INIT_FUNCTIONS
139
+ "rn_gpui_nitro_init_${_sanitized}")
140
+ endfunction()
@@ -0,0 +1,25 @@
1
+ #pragma once
2
+
3
+ #include "GpuiCppHostComponent.h"
4
+
5
+ namespace margelo::nitro::gpui {
6
+
7
+ /// The desktop half of a Nitro View, mixed into the library's view class beside
8
+ /// its generated `Hybrid<Name>Spec`. The host calls these on the main thread,
9
+ /// as the iOS view calls the `HybridView` lifecycle hooks.
10
+ class HybridDesktopView {
11
+ public:
12
+ virtual ~HybridDesktopView() = default;
13
+ /// Before a batch of prop setters.
14
+ virtual void beforeUpdate() {}
15
+ /// After a batch of prop setters.
16
+ virtual void afterUpdate() {}
17
+ /// Once, when the node is first painted.
18
+ virtual rngpui::extension::NativeView createNativeView(const rngpui::extension::NativeViewParent& parent) {
19
+ return {};
20
+ }
21
+ /// When the node unmounts.
22
+ virtual void onDropView() {}
23
+ };
24
+
25
+ } // namespace margelo::nitro::gpui
@@ -0,0 +1,41 @@
1
+ #include "CallInvokerDispatcher.hpp"
2
+ #include "InstallNitro.hpp"
3
+
4
+ #include <ReactCommon/TurboModule.h>
5
+
6
+ #include <exception>
7
+ #include <memory>
8
+ #include <string>
9
+
10
+ namespace {
11
+ using facebook::jsi::Runtime;
12
+ using facebook::jsi::Value;
13
+
14
+ class NitroModules final : public facebook::react::TurboModule {
15
+ public:
16
+ explicit NitroModules(std::shared_ptr<facebook::react::CallInvoker> jsInvoker)
17
+ : TurboModule("NitroModules", std::move(jsInvoker)) {
18
+ methodMap_["install"] = MethodMetadata{0, &NitroModules::install};
19
+ }
20
+
21
+ private:
22
+ static Value install(Runtime& runtime, facebook::react::TurboModule& turboModule, const Value*, size_t) {
23
+ auto& self = static_cast<NitroModules&>(turboModule);
24
+ try {
25
+ margelo::nitro::install(runtime, std::make_shared<margelo::nitro::CallInvokerDispatcher>(self.jsInvoker_));
26
+ return Value::undefined();
27
+ } catch (const std::exception& error) {
28
+ return facebook::jsi::String::createFromUtf8(runtime, error.what());
29
+ }
30
+ }
31
+ };
32
+ } // namespace
33
+
34
+ std::shared_ptr<facebook::react::TurboModule> create_gpui_nitro_modules(
35
+ const std::string& name,
36
+ std::shared_ptr<facebook::react::CallInvoker> jsInvoker) {
37
+ if (name != "NitroModules") {
38
+ return nullptr;
39
+ }
40
+ return std::make_shared<NitroModules>(std::move(jsInvoker));
41
+ }
@@ -0,0 +1,105 @@
1
+ #include "Dispatcher.hpp"
2
+ #include "GpuiTurboModule.h"
3
+ #include "NitroLogger.hpp"
4
+ #include "ThreadUtils.hpp"
5
+
6
+ #include <glog/logging.h>
7
+
8
+ #include <functional>
9
+ #include <memory>
10
+ #include <sstream>
11
+ #include <string>
12
+ #include <thread>
13
+
14
+ #if defined(_WIN32)
15
+ #include <windows.h>
16
+ #else
17
+ #include <pthread.h>
18
+ #endif
19
+
20
+ #include "rn-gpui-sys/src/lib.rs.h"
21
+
22
+ namespace margelo::nitro {
23
+
24
+ namespace {
25
+ class UIThreadDispatcher final : public Dispatcher {
26
+ public:
27
+ void runAsync(std::function<void()>&& function) override {
28
+ rngpui::dispatchMain(std::move(function));
29
+ }
30
+
31
+ void runSync(std::function<void()>&& function) override {
32
+ if (rngpui::rn_gpui_is_main_thread()) {
33
+ function();
34
+ return;
35
+ }
36
+ throw std::runtime_error("UIThreadDispatcher::runSync() is not implemented off the UI thread");
37
+ }
38
+ };
39
+ } // namespace
40
+
41
+ std::string ThreadUtils::getThreadName() {
42
+ #if defined(_WIN32)
43
+ PWSTR description = nullptr;
44
+ if (SUCCEEDED(GetThreadDescription(GetCurrentThread(), &description)) && description != nullptr) {
45
+ std::wstring wide(description);
46
+ LocalFree(description);
47
+ if (!wide.empty()) {
48
+ const int size = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, nullptr, 0, nullptr, nullptr);
49
+ std::string name(size > 0 ? size - 1 : 0, '\0');
50
+ if (size > 1) {
51
+ WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, name.data(), size, nullptr, nullptr);
52
+ }
53
+ return name;
54
+ }
55
+ }
56
+ #else
57
+ char name[64] = {};
58
+ if (pthread_getname_np(pthread_self(), name, sizeof(name)) == 0 && name[0] != '\0') {
59
+ return std::string(name);
60
+ }
61
+ #endif
62
+ std::stringstream stream;
63
+ stream << std::this_thread::get_id();
64
+ return std::string("Thread #") + stream.str();
65
+ }
66
+
67
+ void ThreadUtils::setThreadName(const std::string& name) {
68
+ #if defined(_WIN32)
69
+ const int size = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0);
70
+ if (size > 0) {
71
+ std::wstring wide(size - 1, L'\0');
72
+ MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, wide.data(), size);
73
+ SetThreadDescription(GetCurrentThread(), wide.c_str());
74
+ }
75
+ #elif defined(__APPLE__)
76
+ pthread_setname_np(name.c_str());
77
+ #else
78
+ pthread_setname_np(pthread_self(), name.substr(0, 15).c_str());
79
+ #endif
80
+ }
81
+
82
+ bool ThreadUtils::isUIThread() {
83
+ return rngpui::rn_gpui_is_main_thread();
84
+ }
85
+
86
+ std::shared_ptr<Dispatcher> ThreadUtils::createUIThreadDispatcher() {
87
+ return std::make_shared<UIThreadDispatcher>();
88
+ }
89
+
90
+ void Logger::nativeLog(LogLevel level, const char* tag, const std::string& message) {
91
+ switch (level) {
92
+ case LogLevel::Debug:
93
+ case LogLevel::Info:
94
+ LOG(INFO) << "[" << tag << "] " << message;
95
+ break;
96
+ case LogLevel::Warning:
97
+ LOG(WARNING) << "[" << tag << "] " << message;
98
+ break;
99
+ case LogLevel::Error:
100
+ LOG(ERROR) << "[" << tag << "] " << message;
101
+ break;
102
+ }
103
+ }
104
+
105
+ } // namespace margelo::nitro
@@ -0,0 +1,19 @@
1
+ // Force-included into the Nitro sources this adapter compiles. Nitro and the
2
+ // libraries built on it rely on standard headers that Apple's and Android's
3
+ // libc++ include transitively and libstdc++ does not.
4
+ #pragma once
5
+
6
+ #ifdef __cplusplus
7
+ #include <algorithm>
8
+ #include <cstdint>
9
+ #include <functional>
10
+ #include <memory>
11
+ #include <mutex>
12
+ #include <optional>
13
+ #include <string>
14
+ #include <unordered_map>
15
+ #include <unordered_set>
16
+ #include <utility>
17
+ #include <variant>
18
+ #include <vector>
19
+ #endif
@@ -0,0 +1,181 @@
1
+ // Writes the desktop registration file of one Nitro library: its C++ Hybrid
2
+ // Objects, and a host view manager for each Nitro View.
3
+ //
4
+ // node generate-nitro-desktop.mjs <package-root> <output.cpp> <init-suffix> [--hybrid Name=Impl]... [--view View=Impl]...
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ const [packageRoot, output, initSuffix, ...rest] = process.argv.slice(2);
10
+ const hybrids = new Map();
11
+ const views = [];
12
+ for (let i = 0; i < rest.length; i += 2) {
13
+ const [name, impl] = (rest[i + 1] ?? '').split('=');
14
+ if (!name || !impl) {
15
+ throw new Error(`${rest[i]} expects Name=ImplClass`);
16
+ }
17
+ if (rest[i] === '--hybrid') {
18
+ hybrids.set(name, impl);
19
+ } else if (rest[i] === '--view') {
20
+ views.push({ name, impl });
21
+ } else {
22
+ throw new Error(`unknown argument ${rest[i]}`);
23
+ }
24
+ }
25
+
26
+ const nitroJsonPath = path.join(packageRoot, 'nitro.json');
27
+ const nitroJson = fs.existsSync(nitroJsonPath)
28
+ ? JSON.parse(fs.readFileSync(nitroJsonPath, 'utf8'))
29
+ : { cxxNamespace: [], autolinking: {} };
30
+ const namespace = `margelo::nitro::${nitroJson.cxxNamespace.join('::')}`;
31
+
32
+ const registrations = new Map();
33
+ for (const [name, platforms] of Object.entries(nitroJson.autolinking ?? {})) {
34
+ for (const key of ['all', 'desktop']) {
35
+ const entry = platforms[key];
36
+ if (entry?.language === 'c++') {
37
+ registrations.set(name, entry.implementationClassName);
38
+ }
39
+ }
40
+ }
41
+ for (const [name, impl] of hybrids) {
42
+ registrations.set(name, impl);
43
+ }
44
+
45
+ const capitalize = text => text[0].toUpperCase() + text.slice(1);
46
+
47
+ function viewProps(viewName) {
48
+ const header = path.join(
49
+ packageRoot,
50
+ 'nitrogen/generated/shared/c++/views',
51
+ `Hybrid${viewName}Component.hpp`,
52
+ );
53
+ const source = fs.readFileSync(header, 'utf8');
54
+ const start = source.indexOf(`class Hybrid${viewName}Props`);
55
+ if (start < 0) {
56
+ throw new Error(`${header}: no Hybrid${viewName}Props class`);
57
+ }
58
+ const body = source.slice(start, source.indexOf('};', start));
59
+ return [...body.matchAll(/^\s*nitro::ReactProp<(.+)>\s+(\w+);\s*$/gmu)].map(
60
+ match => match[2],
61
+ );
62
+ }
63
+
64
+ function viewManager({ name, impl }) {
65
+ const props = `${namespace}::views::Hybrid${name}Props`;
66
+ const spec = `${namespace}::Hybrid${name}Spec`;
67
+ const setters = viewProps(name)
68
+ .map(prop => {
69
+ if (prop === 'hybridRef') {
70
+ return ` if (oldViewProps == nullptr
71
+ ? newViewProps.hybridRef.isProvided()
72
+ : !newViewProps.hybridRef.hasSameValue(oldViewProps->hybridRef)) {
73
+ const auto& maybeFunc = newViewProps.hybridRef.get();
74
+ if (maybeFunc.has_value()) {
75
+ maybeFunc.value()(std::static_pointer_cast<${spec}>(view_));
76
+ }
77
+ }`;
78
+ }
79
+ return ` if (oldViewProps == nullptr
80
+ ? newViewProps.${prop}.isProvided()
81
+ : !newViewProps.${prop}.hasSameValue(oldViewProps->${prop})) {
82
+ view_->set${capitalize(prop)}(newViewProps.${prop}.get());
83
+ }`;
84
+ })
85
+ .join('\n');
86
+ return `class ${name}DesktopHostView final : public rngpui::extension::CppHostView {
87
+ public:
88
+ ${name}DesktopHostView() : view_(std::make_shared<${namespace}::${impl}>()) {}
89
+
90
+ void update(
91
+ const std::shared_ptr<const facebook::react::Props>& props,
92
+ const std::shared_ptr<const facebook::react::Props>& oldProps) override {
93
+ didDropView_ = false;
94
+ const auto& newViewProps = *std::static_pointer_cast<const ${props}>(props);
95
+ const auto* oldViewProps = static_cast<const ${props}*>(oldProps.get());
96
+ const bool hasChanges = oldViewProps == nullptr
97
+ ? newViewProps.hasAnyProvidedProps()
98
+ : !newViewProps.hasSameProps(*oldViewProps);
99
+ if (!hasChanges) {
100
+ return;
101
+ }
102
+ view_->beforeUpdate();
103
+ ${setters}
104
+ view_->afterUpdate();
105
+ }
106
+
107
+ rngpui::extension::NativeView createNativeView(
108
+ const rngpui::extension::NativeViewParent& parent) override {
109
+ return view_->createNativeView(parent);
110
+ }
111
+
112
+ void unmount() override {
113
+ if (didDropView_) {
114
+ return;
115
+ }
116
+ didDropView_ = true;
117
+ view_->onDropView();
118
+ }
119
+
120
+ private:
121
+ std::shared_ptr<${namespace}::${impl}> view_;
122
+ bool didDropView_ = false;
123
+ };
124
+ `;
125
+ }
126
+
127
+ const includes = new Set();
128
+ for (const impl of registrations.values())
129
+ includes.add(`#include "${impl}.hpp"`);
130
+ for (const view of views) {
131
+ includes.add(`#include "${view.impl}.hpp"`);
132
+ includes.add(`#include "Hybrid${view.name}Component.hpp"`);
133
+ includes.add(`#include "Hybrid${view.name}Spec.hpp"`);
134
+ }
135
+
136
+ const hybridCalls = [...registrations]
137
+ .map(
138
+ ([name, impl]) => ` HybridObjectRegistry::registerHybridObjectConstructor(
139
+ ${JSON.stringify(name)},
140
+ []() -> std::shared_ptr<HybridObject> {
141
+ return std::make_shared<${namespace}::${impl}>();
142
+ });`,
143
+ )
144
+ .join('\n');
145
+
146
+ const viewCalls = views
147
+ .map(
148
+ ({ name }) => ` rngpui::extension::registerCppHostComponent({
149
+ ${JSON.stringify(name)},
150
+ ${namespace}::views::Hybrid${name}ShadowNode::Handle(),
151
+ &facebook::react::concreteComponentDescriptorProvider<${namespace}::views::Hybrid${name}ComponentDescriptor>,
152
+ [](int32_t) { return std::make_unique<${name}DesktopHostView>(); }});`,
153
+ )
154
+ .join('\n');
155
+
156
+ const source = `// Generated by @react-native-gpui/nitro-modules; do not edit.
157
+ #include "GPUINitroHybridView.hpp"
158
+ #include "GpuiCppHostComponent.h"
159
+
160
+ #include <NitroModules/HybridObjectRegistry.hpp>
161
+ #include <react/renderer/core/ConcreteComponentDescriptor.h>
162
+
163
+ ${[...includes].join('\n')}
164
+
165
+ namespace {
166
+ using margelo::nitro::HybridObject;
167
+ using margelo::nitro::HybridObjectRegistry;
168
+
169
+ ${views.map(viewManager).join('\n')}
170
+ } // namespace
171
+
172
+ extern "C" void rn_gpui_nitro_init_${initSuffix}() {
173
+ ${hybridCalls}
174
+ ${viewCalls}
175
+ }
176
+ `;
177
+
178
+ fs.mkdirSync(path.dirname(output), { recursive: true });
179
+ if (!fs.existsSync(output) || fs.readFileSync(output, 'utf8') !== source) {
180
+ fs.writeFileSync(output, source);
181
+ }
@@ -0,0 +1,73 @@
1
+ # Adding desktop support to a Nitro library
2
+
3
+ A Nitro library supports desktop through a `desktop` folder with a CMake file, a `cpp: true` entry in `react-native.config.js` for each view, and C++ implementations of its Hybrid Objects and views. Desktop builds everything through the app's single C++ target, so nothing is built as a separate library.
4
+
5
+ ## react-native.config.js
6
+
7
+ ```js
8
+ module.exports = {
9
+ dependency: {
10
+ platforms: {
11
+ desktop: {
12
+ cmake: 'desktop',
13
+ hostComponents: [{ name: 'MyView', nativeSurface: true, cpp: true }],
14
+ },
15
+ },
16
+ },
17
+ };
18
+ ```
19
+
20
+ `name` is the view's Fabric component name, the string in `Hybrid<Name>ComponentName` in the generated `HybridMyViewComponent.cpp` (the key of the view in `nitro.json`'s `autolinking`, or the spec's type name). A library without views omits `hostComponents`.
21
+
22
+ ## desktop/CMakeLists.txt
23
+
24
+ ```cmake
25
+ find_program(_node node REQUIRED)
26
+ execute_process(
27
+ COMMAND "${_node}" -e "process.stdout.write(require.resolve('@react-native-gpui/nitro-modules/package.json', {paths: [process.argv[1]]}))" "${RN_GPUI_PROJECT_ROOT}"
28
+ OUTPUT_VARIABLE _nitro_adapter_json OUTPUT_STRIP_TRAILING_WHITESPACE)
29
+ get_filename_component(_nitro_adapter "${_nitro_adapter_json}" DIRECTORY)
30
+ include("${_nitro_adapter}/desktop/NitroDesktop.cmake")
31
+
32
+ rn_gpui_nitro_library(
33
+ PACKAGE my-nitro-library
34
+ SOURCES "${CMAKE_CURRENT_LIST_DIR}/../cpp/HybridMath.cpp" "${CMAKE_CURRENT_LIST_DIR}/../cpp/HybridMyView.cpp"
35
+ INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/../cpp"
36
+ VIEWS "MyView=HybridMyView")
37
+ ```
38
+
39
+ `rn_gpui_nitro_library` takes:
40
+
41
+ - `PACKAGE`: the library's npm name. Its `nitro.json` (optional; without it nothing is autolinked) and `nitrogen/generated/shared/c++` are used; run `nitrogen` before building.
42
+ - `SOURCES`, `INCLUDE_DIRS`: the library's own C++, compiled into the app.
43
+ - `HYBRIDS`: `Name=ImplClass` pairs for Hybrid Objects that `nitro.json` does not autolink in C++. Every `autolinking` entry whose `all` or `desktop` language is `c++` is registered without being listed.
44
+ - `VIEWS`: `ViewName=ImplClass` pairs. Each view is hosted as a C++ host component, and the generated registration reads the props of `Hybrid<ViewName>Component.hpp` to forward them to the implementation.
45
+
46
+ Headers of `react-native-nitro-modules` are available as `<NitroModules/...>`.
47
+
48
+ ## The view class
49
+
50
+ The implementation inherits its generated spec and `HybridDesktopView`:
51
+
52
+ ```cpp
53
+ #include "HybridMyViewSpec.hpp"
54
+ #include <NitroModules/GPUINitroHybridView.hpp>
55
+
56
+ namespace margelo::nitro::mylib {
57
+ class HybridMyView : public HybridMyViewSpec, public gpui::HybridDesktopView {
58
+ public:
59
+ void setColor(const std::string& color) override { color_ = color; }
60
+ void afterUpdate() override { /* apply color_ */ }
61
+ rngpui::extension::NativeView createNativeView(const rngpui::extension::NativeViewParent& parent) override;
62
+ void onDropView() override {}
63
+ };
64
+ }
65
+ ```
66
+
67
+ The host calls on the main thread:
68
+
69
+ - the generated `set<Prop>` for each prop that changed, between `beforeUpdate()` and `afterUpdate()`;
70
+ - `createNativeView(parent)` once, when the node is first painted. Return an `NSView` (+1 retained) on macOS, a child window or a composited view elsewhere; see [C++ host components](https://streetwriters.github.io/react-native-gpui/docs/native-views#c-host-components);
71
+ - `onDropView()` when the node unmounts.
72
+
73
+ Methods of the view's `HybridView` spec run on the thread JavaScript calls them from, so a method that touches the native view hops to the main thread.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@react-native-gpui/nitro-modules",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.37.0-alpha.1",
4
+ "description": "Adapter for react-native-nitro-modules (MIT): runs Nitro Hybrid Objects and Nitro Views written in C++ on the desktop renderer",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/streetwriters/react-native-gpui-modules.git",
9
+ "directory": "modules/nitro-modules"
10
+ },
11
+ "homepage": "https://github.com/streetwriters/react-native-gpui-modules/tree/main/modules/nitro-modules#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/streetwriters/react-native-gpui-modules/issues"
14
+ },
15
+ "files": [
16
+ "desktop",
17
+ "docs",
18
+ "src",
19
+ "react-native.config.js",
20
+ "README.md",
21
+ "LICENSE",
22
+ "CHANGELOG.md",
23
+ "!**/*.test.js",
24
+ "!**/*.test.mjs",
25
+ "!**/*.test.ts",
26
+ "!**/*.test.cjs"
27
+ ],
28
+ "peerDependencies": {
29
+ "react-native": "0.87.x",
30
+ "react-native-nitro-modules": "0.37.x"
31
+ },
32
+ "codegenConfig": {
33
+ "name": "GPUINitroModulesSpec",
34
+ "type": "modules",
35
+ "jsSrcsDir": "src"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "tag": "latest"
40
+ }
41
+ }
@@ -0,0 +1,10 @@
1
+ module.exports = {
2
+ dependency: {
3
+ platforms: {
4
+ desktop: {
5
+ cmake: 'desktop',
6
+ cppProvider: 'create_gpui_nitro_modules',
7
+ },
8
+ },
9
+ },
10
+ };
@@ -0,0 +1,8 @@
1
+ import type { TurboModule } from 'react-native';
2
+ import { TurboModuleRegistry } from 'react-native';
3
+
4
+ export interface Spec extends TurboModule {
5
+ install(): string | undefined;
6
+ }
7
+
8
+ export default TurboModuleRegistry.getEnforcing<Spec>('NitroModules');