@solidnative-dev/fabric-host 0.0.0-stage → 0.1.0-beta.0

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +87 -2
  3. package/dist/fatal-error-handler.d.ts +27 -0
  4. package/dist/fatal-error-handler.d.ts.map +1 -0
  5. package/dist/fatal-error-handler.js +106 -0
  6. package/dist/fatal-error-handler.js.map +1 -0
  7. package/dist/index.d.ts +7 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +7 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/native-binding.d.ts +183 -0
  12. package/dist/native-binding.d.ts.map +1 -0
  13. package/dist/native-binding.js +554 -0
  14. package/dist/native-binding.js.map +1 -0
  15. package/dist/native-fabric-host.d.ts +32 -0
  16. package/dist/native-fabric-host.d.ts.map +1 -0
  17. package/dist/native-fabric-host.js +275 -0
  18. package/dist/native-fabric-host.js.map +1 -0
  19. package/dist/native-transaction.d.ts +17 -0
  20. package/dist/native-transaction.d.ts.map +1 -0
  21. package/dist/native-transaction.js +124 -0
  22. package/dist/native-transaction.js.map +1 -0
  23. package/dist/react-native-0.88.d.ts +77 -0
  24. package/dist/react-native-0.88.d.ts.map +1 -0
  25. package/dist/react-native-0.88.js +79 -0
  26. package/dist/react-native-0.88.js.map +1 -0
  27. package/dist/surface-readiness.d.ts +18 -0
  28. package/dist/surface-readiness.d.ts.map +1 -0
  29. package/dist/surface-readiness.js +43 -0
  30. package/dist/surface-readiness.js.map +1 -0
  31. package/native/README.md +502 -0
  32. package/native/SolidNativeFabric.podspec +84 -0
  33. package/native/android/SolidNativeBindingsInstaller.cpp +4218 -0
  34. package/native/android/SolidNativeBindingsInstaller.h +8 -0
  35. package/native/android/SolidNativeRuntime.cmake +61 -0
  36. package/native/android/java/dev/solidnative/runtime/SolidNativeBindingsInstaller.kt +239 -0
  37. package/native/android/java/dev/solidnative/runtime/SolidNativeDebugModule.kt +191 -0
  38. package/native/android/java/dev/solidnative/runtime/SolidNativePackage.kt +43 -0
  39. package/native/android/java/dev/solidnative/runtime/SolidNativePlatformModule.kt +81 -0
  40. package/native/android/java/dev/solidnative/runtime/SolidNativeStartupFailureView.kt +93 -0
  41. package/native/android/java/dev/solidnative/runtime/SolidNativeSurface.kt +423 -0
  42. package/native/android/solid-native.gradle +90 -0
  43. package/native/apple/SolidNativeDebugRequest.mm +421 -0
  44. package/native/fabric/SolidNativeDebugRequest.h +12 -0
  45. package/native/fabric/SolidNativeDirtyNodes.h +26 -0
  46. package/native/fabric/SolidNativeFabricApi.cpp +224 -0
  47. package/native/fabric/SolidNativeFabricApi.h +107 -0
  48. package/native/fabric/SolidNativeFabricApplication.h +32 -0
  49. package/native/fabric/SolidNativeFabricApplication.mm +373 -0
  50. package/native/fabric/SolidNativeFabricJSIBinding.h +43 -0
  51. package/native/fabric/SolidNativeFabricJSIBinding.mm +4491 -0
  52. package/native/fabric/SolidNativeFabricSmokeApplication.h +26 -0
  53. package/native/fabric/SolidNativeFabricSmokeApplication.mm +331 -0
  54. package/native/fabric/SolidNativeFabricSurface.h +63 -0
  55. package/native/fabric/SolidNativeFabricSurface.mm +549 -0
  56. package/native/fabric/SolidNativeFabricTransactionCoordinator.cpp +1275 -0
  57. package/native/fabric/SolidNativeFabricTransactionCoordinator.h +90 -0
  58. package/native/fabric/SolidNativeFabricTransactionCoordinatorApple.mm +97 -0
  59. package/native/fabric/SolidNativeRootViewController.h +20 -0
  60. package/native/fabric/SolidNativeRootViewController.mm +83 -0
  61. package/native/fabric/SolidNativeStagedNodeMap.h +104 -0
  62. package/native/fabric/SolidNativeStartupFailureView.h +17 -0
  63. package/native/fabric/SolidNativeStartupFailureView.mm +77 -0
  64. package/native/react-native-boundary.json +106 -0
  65. package/native/worklets/SolidNativeUIWorklet.cpp +1080 -0
  66. package/native/worklets/SolidNativeUIWorklet.h +245 -0
  67. package/package.json +41 -3
  68. package/scripts/verify-react-native-boundary.mjs +282 -0
@@ -0,0 +1,1275 @@
1
+ #include "SolidNativeFabricTransactionCoordinator.h"
2
+
3
+ #include <algorithm>
4
+ #include <atomic>
5
+ #include <cmath>
6
+ #include <limits>
7
+ #include <mutex>
8
+ #include <optional>
9
+ #include <stdexcept>
10
+ #include <string>
11
+ #include <unordered_map>
12
+ #include <unordered_set>
13
+ #include <utility>
14
+ #include <vector>
15
+
16
+ #include <folly/dynamic.h>
17
+ #include <react/renderer/core/ReactPrimitives.h>
18
+ #include <react/renderer/core/InstanceHandle.h>
19
+ #include <react/renderer/dom/DOM.h>
20
+ #include <react/renderer/uimanager/UIManager.h>
21
+
22
+ #include "SolidNativeFabricApi.h"
23
+ #include "SolidNativeDirtyNodes.h"
24
+ #include "SolidNativeStagedNodeMap.h"
25
+
26
+ namespace solid_native::fabric::react_native {
27
+ namespace {
28
+
29
+ using Handle = int64_t;
30
+ using NodeMap = std::unordered_map<Handle, struct NodeRecord>;
31
+
32
+ constexpr int64_t HostContractVersion = 1;
33
+ constexpr double MaximumSafeInteger = 9007199254740991.0;
34
+ constexpr size_t MaximumCausalOperationIdLength = 128;
35
+ std::atomic<facebook::react::Tag> NextFabricTag{2};
36
+
37
+ struct NodeRecord {
38
+ enum class Kind { Element, Text };
39
+
40
+ Kind kind{Kind::Element};
41
+ Handle handle{0};
42
+ std::string component;
43
+ folly::dynamic props{folly::dynamic::object};
44
+ std::string text;
45
+ std::vector<std::string> eventListeners;
46
+ std::optional<Handle> parent;
47
+ std::vector<Handle> children;
48
+
49
+ facebook::react::Tag tag{0};
50
+ facebook::react::InstanceHandle::Shared instanceHandle;
51
+ std::string fabricComponent;
52
+ folly::dynamic fabricProps{folly::dynamic::object};
53
+ std::vector<ShadowNodePtr> fabricChildren;
54
+ ShadowNodePtr shadowNode;
55
+ bool dirty{true};
56
+ };
57
+
58
+ using StagedNodes = StagedNodeMap<NodeRecord>;
59
+
60
+ struct Command {
61
+ Handle node;
62
+ std::string name;
63
+ folly::dynamic args;
64
+ };
65
+
66
+ std::string pathMessage(
67
+ const std::string &path,
68
+ const std::string &message) {
69
+ return path + ": " + message;
70
+ }
71
+
72
+ const folly::dynamic &requireObject(
73
+ const folly::dynamic &value,
74
+ const std::string &path) {
75
+ if (!value.isObject()) {
76
+ throw std::invalid_argument(pathMessage(path, "expected an object."));
77
+ }
78
+ return value;
79
+ }
80
+
81
+ const folly::dynamic &requireArray(
82
+ const folly::dynamic &value,
83
+ const std::string &path) {
84
+ if (!value.isArray()) {
85
+ throw std::invalid_argument(pathMessage(path, "expected an array."));
86
+ }
87
+ return value;
88
+ }
89
+
90
+ const folly::dynamic &requireMember(
91
+ const folly::dynamic &object,
92
+ const char *name,
93
+ const std::string &path) {
94
+ requireObject(object, path);
95
+ if (object.count(name) == 0) {
96
+ throw std::invalid_argument(pathMessage(path + "." + name, "is required."));
97
+ }
98
+ return object.at(name);
99
+ }
100
+
101
+ std::string requireString(
102
+ const folly::dynamic &value,
103
+ const std::string &path) {
104
+ if (!value.isString()) {
105
+ throw std::invalid_argument(pathMessage(path, "expected a string."));
106
+ }
107
+ return value.getString();
108
+ }
109
+
110
+ int64_t requireInteger(
111
+ const folly::dynamic &value,
112
+ const std::string &path,
113
+ bool positive = false) {
114
+ if (!value.isInt() && !value.isDouble()) {
115
+ throw std::invalid_argument(pathMessage(path, "expected an integer."));
116
+ }
117
+
118
+ const double number = value.asDouble();
119
+ if (!std::isfinite(number) || std::trunc(number) != number ||
120
+ std::abs(number) > MaximumSafeInteger || (positive && number <= 0)) {
121
+ throw std::invalid_argument(pathMessage(
122
+ path,
123
+ positive ? "expected a positive safe integer."
124
+ : "expected a safe integer."));
125
+ }
126
+ return static_cast<int64_t>(number);
127
+ }
128
+
129
+ void validateCausalContext(const folly::dynamic &transaction) {
130
+ if (transaction.count("causalContext") == 0) return;
131
+ const auto &context = requireObject(
132
+ transaction.at("causalContext"), "transaction.causalContext");
133
+ const auto operationId = requireString(
134
+ requireMember(context, "operationId", "transaction.causalContext"),
135
+ "transaction.causalContext.operationId");
136
+ if (operationId.empty() ||
137
+ operationId.size() > MaximumCausalOperationIdLength ||
138
+ operationId.find('\0') != std::string::npos) {
139
+ throw std::invalid_argument(pathMessage(
140
+ "transaction.causalContext.operationId",
141
+ "expected 1-128 characters without null bytes."));
142
+ }
143
+ }
144
+
145
+ folly::dynamic requireProps(
146
+ const folly::dynamic &value,
147
+ const std::string &path) {
148
+ return requireObject(value, path);
149
+ }
150
+
151
+ const NodeRecord &requireNode(
152
+ const NodeMap &nodes, Handle handle, const char *operation) {
153
+ auto iterator = nodes.find(handle);
154
+ if (iterator == nodes.end()) {
155
+ throw std::invalid_argument(
156
+ std::string("Cannot ") + operation + ": node " +
157
+ std::to_string(handle) + " does not exist.");
158
+ }
159
+ return iterator->second;
160
+ }
161
+
162
+ const NodeRecord &requireNode(
163
+ const StagedNodes &nodes, Handle handle, const char *operation) {
164
+ const auto *node = nodes.get(handle);
165
+ if (node == nullptr) {
166
+ throw std::invalid_argument(
167
+ std::string("Cannot ") + operation + ": node " +
168
+ std::to_string(handle) + " does not exist.");
169
+ }
170
+ return *node;
171
+ }
172
+
173
+ template <typename Nodes>
174
+ const NodeRecord &requireElement(
175
+ const Nodes &nodes,
176
+ Handle handle,
177
+ const char *operation) {
178
+ const auto &node = requireNode(nodes, handle, operation);
179
+ if (node.kind != NodeRecord::Kind::Element) {
180
+ throw std::invalid_argument(
181
+ std::string("Cannot ") + operation + ": node " +
182
+ std::to_string(handle) + " is a text node.");
183
+ }
184
+ return node;
185
+ }
186
+
187
+ NodeRecord &editNode(
188
+ StagedNodes &nodes, Handle handle, const char *operation) {
189
+ (void)requireNode(nodes, handle, operation);
190
+ return *nodes.edit(handle);
191
+ }
192
+
193
+ NodeRecord &editElement(
194
+ StagedNodes &nodes, Handle handle, const char *operation) {
195
+ (void)requireElement(nodes, handle, operation);
196
+ return *nodes.edit(handle);
197
+ }
198
+
199
+ std::string fabricComponentFor(const NodeRecord &node, const StagedNodes &nodes) {
200
+ if (node.kind == NodeRecord::Kind::Text) {
201
+ return "RCTRawText";
202
+ }
203
+ if (node.component == "RootView" || node.component == "View" ||
204
+ node.component == "Pressable") {
205
+ return "RCTView";
206
+ }
207
+ if (node.component == "Text") {
208
+ if (node.parent.has_value()) {
209
+ const auto &parent = requireNode(nodes, *node.parent, "resolve text parent");
210
+ if (parent.kind == NodeRecord::Kind::Element &&
211
+ parent.component == "Text") {
212
+ return "RCTVirtualText";
213
+ }
214
+ }
215
+ return "RCTText";
216
+ }
217
+ if (node.component == "Image") return "RCTImageView";
218
+ if (node.component == "ScrollView") {
219
+ #if defined(__ANDROID__)
220
+ const auto horizontal = node.props.find("horizontal");
221
+ if (horizontal != node.props.items().end() && horizontal->second.isBool() &&
222
+ horizontal->second.asBool()) {
223
+ return "AndroidHorizontalScrollView";
224
+ }
225
+ #endif
226
+ return "RCTScrollView";
227
+ }
228
+ if (node.component == "ScrollContentView") {
229
+ #if defined(__ANDROID__)
230
+ if (node.parent.has_value()) {
231
+ const auto &parent = requireNode(
232
+ nodes, *node.parent, "resolve scroll content parent");
233
+ const auto horizontal = parent.props.find("horizontal");
234
+ if (parent.component == "ScrollView" &&
235
+ horizontal != parent.props.items().end() &&
236
+ horizontal->second.isBool() && horizontal->second.asBool()) {
237
+ return "AndroidHorizontalScrollContentView";
238
+ }
239
+ }
240
+ return "RCTView";
241
+ #else
242
+ return "RCTScrollContentView";
243
+ #endif
244
+ }
245
+ if (node.component == "RefreshControl") {
246
+ #if defined(__ANDROID__)
247
+ return "AndroidSwipeRefreshLayout";
248
+ #else
249
+ return "PullToRefreshView";
250
+ #endif
251
+ }
252
+ if (node.component == "TextInput") {
253
+ #if defined(__ANDROID__)
254
+ return "AndroidTextInput";
255
+ #else
256
+ return "RCTTextInput";
257
+ #endif
258
+ }
259
+ if (node.component == "ActivityIndicator") {
260
+ #if defined(__ANDROID__)
261
+ return "AndroidProgressBar";
262
+ #else
263
+ return "ActivityIndicatorView";
264
+ #endif
265
+ }
266
+ if (node.component == "Switch") {
267
+ #if defined(__ANDROID__)
268
+ return "AndroidSwitch";
269
+ #else
270
+ return "Switch";
271
+ #endif
272
+ }
273
+ if (node.component == "Modal") return "ModalHostView";
274
+ if (node.component == "Screen") {
275
+ #if defined(__ANDROID__)
276
+ return "RNSScreen";
277
+ #else
278
+ const auto presentation = node.props.find("stackPresentation");
279
+ if (presentation != node.props.items().end() &&
280
+ presentation->second.isString() &&
281
+ presentation->second.getString() != "push") {
282
+ return "RNSModalScreen";
283
+ }
284
+ return "RNSScreen";
285
+ #endif
286
+ }
287
+ if (node.component == "ScreenStack") return "RNSScreenStack";
288
+ if (node.component == "ScreenHeader") {
289
+ return "RNSScreenStackHeaderConfig";
290
+ }
291
+ if (node.component == "ScreenHeaderSubview") {
292
+ return "RNSScreenStackHeaderSubview";
293
+ }
294
+ if (node.component == "TabsHost") {
295
+ #if defined(__ANDROID__)
296
+ return "RNSTabsHostAndroid";
297
+ #else
298
+ return "RNSTabsHostIOS";
299
+ #endif
300
+ }
301
+ if (node.component == "TabsScreen") {
302
+ #if defined(__ANDROID__)
303
+ return "RNSTabsScreenAndroid";
304
+ #else
305
+ return "RNSTabsScreenIOS";
306
+ #endif
307
+ }
308
+
309
+ // Generated Fabric component specs use their registered native name as the
310
+ // public component name. Built-ins above retain their Solid-to-RN aliases;
311
+ // every other descriptor is resolved by Fabric's generated registry.
312
+ const auto isIdentifierStart = [](char value) {
313
+ return (value >= 'A' && value <= 'Z') ||
314
+ (value >= 'a' && value <= 'z') || value == '_';
315
+ };
316
+ const auto isIdentifierPart = [&](char value) {
317
+ return isIdentifierStart(value) || (value >= '0' && value <= '9');
318
+ };
319
+ if (node.component.empty() || node.component.size() > 128 ||
320
+ !isIdentifierStart(node.component.front()) ||
321
+ !std::all_of(
322
+ node.component.begin() + 1,
323
+ node.component.end(),
324
+ isIdentifierPart)) {
325
+ throw std::invalid_argument(
326
+ "Generated Fabric component names must be 1-128 identifier characters.");
327
+ }
328
+ return node.component;
329
+ }
330
+
331
+ std::string fabricCommandFor(
332
+ const NodeRecord &node,
333
+ const std::string &command) {
334
+ if (node.component == "Switch" && command == "setValue") {
335
+ #if defined(__ANDROID__)
336
+ return "setNativeValue";
337
+ #else
338
+ return "setValue";
339
+ #endif
340
+ }
341
+ return command;
342
+ }
343
+
344
+ bool acceptsRawText(const NodeRecord &node) {
345
+ return node.kind == NodeRecord::Kind::Element && node.component == "Text";
346
+ }
347
+
348
+ folly::dynamic fabricPropsFor(const NodeRecord &node) {
349
+ if (node.kind == NodeRecord::Kind::Text) {
350
+ return folly::dynamic::object("text", node.text);
351
+ }
352
+
353
+ folly::dynamic result = folly::dynamic::object;
354
+ for (const auto &item : node.props.items()) {
355
+ const auto &name = item.first.asString();
356
+ if (name == "style") {
357
+ if (!item.second.isObject()) {
358
+ throw std::invalid_argument("The style prop must be an object.");
359
+ }
360
+ for (const auto &styleItem : item.second.items()) {
361
+ result[styleItem.first] = styleItem.second;
362
+ }
363
+ } else {
364
+ result[item.first] = item.second;
365
+ }
366
+ }
367
+ if (node.component == "RootView" && result.find("flex") == result.items().end()) {
368
+ result["flex"] = 1.0;
369
+ }
370
+ for (const auto &event : node.eventListeners) {
371
+ if (event == "accessibilityAction") {
372
+ result["onAccessibilityAction"] = true;
373
+ }
374
+ if (event == "accessibilityEscape") {
375
+ result["onAccessibilityEscape"] = true;
376
+ }
377
+ if (event == "accessibilityTap") {
378
+ result["onAccessibilityTap"] = true;
379
+ }
380
+ if (event == "magicTap") {
381
+ result["onAccessibilityMagicTap"] = true;
382
+ }
383
+ }
384
+ if (node.component == "View" || node.component == "Pressable" ||
385
+ node.component == "RNCSafeAreaProvider" ||
386
+ node.component == "RNCSafeAreaView") {
387
+ for (const auto &event : node.eventListeners) {
388
+ if (event == "layout") result["onLayout"] = true;
389
+ }
390
+ }
391
+ if (node.component == "RNCSafeAreaProvider") {
392
+ for (const auto &event : node.eventListeners) {
393
+ if (event == "insetsChange") result["onInsetsChange"] = true;
394
+ }
395
+ }
396
+ if (node.component == "Pressable" || node.component == "Text") {
397
+ for (const auto &event : node.eventListeners) {
398
+ if (event == "press") {
399
+ result["onClick"] = true;
400
+ result["onTouchEnd"] = true;
401
+ }
402
+ if (event == "pressIn") {
403
+ result["onPointerDown"] = true;
404
+ result["onTouchStart"] = true;
405
+ }
406
+ if (event == "pressMove") {
407
+ result["onPointerMove"] = true;
408
+ result["onTouchMove"] = true;
409
+ }
410
+ if (event == "pressOut") {
411
+ result["onPointerUp"] = true;
412
+ result["onTouchEnd"] = true;
413
+ }
414
+ if (event == "pressCancel") {
415
+ result["onTouchCancel"] = true;
416
+ result["onPointerCancel"] = true;
417
+ }
418
+ if (node.component == "Pressable" && event == "focus") {
419
+ result["onFocus"] = true;
420
+ }
421
+ if (node.component == "Pressable" && event == "blur") {
422
+ result["onBlur"] = true;
423
+ }
424
+ if (node.component == "Pressable" && event == "hoverIn") {
425
+ result["onPointerEnter"] = true;
426
+ }
427
+ if (node.component == "Pressable" && event == "hoverOut") {
428
+ result["onPointerLeave"] = true;
429
+ }
430
+ }
431
+ }
432
+ if (node.component == "TextInput") {
433
+ for (const auto &event : node.eventListeners) {
434
+ if (event == "contentSizeChange") result["onContentSizeChange"] = true;
435
+ if (event == "scroll") result["onScroll"] = true;
436
+ #if defined(__ANDROID__)
437
+ if (event == "keyPress") result["onKeyPress"] = true;
438
+ #endif
439
+ if (event == "selectionChange") result["onSelectionChange"] = true;
440
+ }
441
+ }
442
+ #if defined(__ANDROID__)
443
+ if (node.component == "ActivityIndicator") {
444
+ // Android's ProgressBar chooses its platform style in the view
445
+ // constructor and refuses to mount until styleAttr is supplied. Keep this
446
+ // React Native backend detail out of the framework-neutral public props.
447
+ result["styleAttr"] = "Normal";
448
+ result["indeterminate"] = true;
449
+ }
450
+ #endif
451
+ if (node.component == "Switch") {
452
+ #if defined(__ANDROID__)
453
+ const bool disabled = result.count("disabled") != 0 &&
454
+ result["disabled"].isBool() && result["disabled"].getBool();
455
+ const bool value = result.count("value") != 0 &&
456
+ result["value"].isBool() && result["value"].getBool();
457
+ result["enabled"] = !disabled;
458
+ result["on"] = value;
459
+ if (result.count("thumbColor") != 0) {
460
+ result["thumbTintColor"] = result["thumbColor"];
461
+ }
462
+ if (result.count("trackColorForFalse") != 0 ||
463
+ result.count("trackColorForTrue") != 0) {
464
+ const char *name = value ? "trackColorForTrue" : "trackColorForFalse";
465
+ if (result.count(name) != 0) result["trackTintColor"] = result[name];
466
+ }
467
+ #else
468
+ if (result.count("thumbColor") != 0) {
469
+ result["thumbTintColor"] = result["thumbColor"];
470
+ }
471
+ if (result.count("trackColorForFalse") != 0) {
472
+ result["tintColor"] = result["trackColorForFalse"];
473
+ }
474
+ if (result.count("trackColorForTrue") != 0) {
475
+ result["onTintColor"] = result["trackColorForTrue"];
476
+ }
477
+ if (result.count("iosBackgroundColor") != 0) {
478
+ result["backgroundColor"] = result["iosBackgroundColor"];
479
+ if (result.count("borderRadius") == 0) result["borderRadius"] = 16;
480
+ }
481
+ #endif
482
+ result.erase("iosBackgroundColor");
483
+ for (const auto &event : node.eventListeners) {
484
+ if (event == "valueChange") result["onChange"] = true;
485
+ }
486
+ }
487
+ if (node.component == "RefreshControl") {
488
+ for (const auto &event : node.eventListeners) {
489
+ if (event == "refresh") result["onRefresh"] = true;
490
+ }
491
+ }
492
+ if (node.component == "Modal") {
493
+ for (const auto &event : node.eventListeners) {
494
+ if (event == "dismiss") result["onDismiss"] = true;
495
+ if (event == "orientationChange") {
496
+ result["onOrientationChange"] = true;
497
+ }
498
+ if (event == "requestClose") result["onRequestClose"] = true;
499
+ if (event == "show") result["onShow"] = true;
500
+ }
501
+ }
502
+ if (node.component == "Screen") {
503
+ for (const auto &event : node.eventListeners) {
504
+ if (event == "focus") result["onAppear"] = true;
505
+ if (event == "blur") result["onDisappear"] = true;
506
+ if (event == "dismiss") result["onDismissed"] = true;
507
+ if (event == "gestureCancel") result["onGestureCancel"] = true;
508
+ if (event == "nativeDismissCancel") {
509
+ result["onNativeDismissCancelled"] = true;
510
+ }
511
+ if (event == "sheetDetentChange") {
512
+ result["onSheetDetentChanged"] = true;
513
+ }
514
+ }
515
+ }
516
+ if (node.component == "ScreenStack") {
517
+ for (const auto &event : node.eventListeners) {
518
+ if (event == "transitionEnd") result["onFinishTransitioning"] = true;
519
+ }
520
+ }
521
+ if (node.component == "ScreenHeader") {
522
+ for (const auto &event : node.eventListeners) {
523
+ if (event == "pressHeaderBarButtonItem") {
524
+ result["onPressHeaderBarButtonItem"] = true;
525
+ }
526
+ if (event == "pressHeaderBarButtonMenuItem") {
527
+ result["onPressHeaderBarButtonMenuItem"] = true;
528
+ }
529
+ }
530
+ }
531
+ if (node.component == "TabsHost") {
532
+ for (const auto &event : node.eventListeners) {
533
+ if (event == "tabSelected") result["onTabSelected"] = true;
534
+ if (event == "tabSelectionRejected") {
535
+ result["onTabSelectionRejected"] = true;
536
+ }
537
+ if (event == "tabSelectionPrevented") {
538
+ result["onTabSelectionPrevented"] = true;
539
+ }
540
+ if (event == "moreTabSelected") result["onMoreTabSelected"] = true;
541
+ }
542
+ }
543
+ if (node.component == "TabsScreen") {
544
+ for (const auto &event : node.eventListeners) {
545
+ if (event == "willAppear") result["onWillAppear"] = true;
546
+ if (event == "didAppear") result["onDidAppear"] = true;
547
+ if (event == "willDisappear") result["onWillDisappear"] = true;
548
+ if (event == "didDisappear") result["onDidDisappear"] = true;
549
+ }
550
+ }
551
+ return result;
552
+ }
553
+
554
+ bool supportsEvent(const NodeRecord &node, const std::string &event) {
555
+ if (node.kind == NodeRecord::Kind::Element &&
556
+ (event == "accessibilityAction" || event == "accessibilityEscape" ||
557
+ event == "accessibilityTap" || event == "magicTap")) {
558
+ return true;
559
+ }
560
+ if (node.component == "View" || node.component == "RNCSafeAreaView") {
561
+ return event == "layout";
562
+ }
563
+ if (node.component == "RNCSafeAreaProvider") {
564
+ return event == "insetsChange" || event == "layout";
565
+ }
566
+ if (node.component == "Text") return event == "press";
567
+ if (node.component == "Image") return event == "error" || event == "load";
568
+ if (node.component == "Pressable") {
569
+ return event == "blur" || event == "focus" || event == "layout" ||
570
+ event == "hoverIn" || event == "hoverOut" ||
571
+ event == "longPress" || event == "press" ||
572
+ event == "pressCancel" || event == "pressIn" ||
573
+ event == "pressMove" || event == "pressOut";
574
+ }
575
+ if (node.component == "ScrollView") {
576
+ return event == "scroll" || event == "scrollBeginDrag" ||
577
+ event == "scrollEndDrag";
578
+ }
579
+ if (node.component == "RefreshControl") return event == "refresh";
580
+ if (node.component == "TextInput") {
581
+ return event == "blur" || event == "changeText" ||
582
+ event == "contentSizeChange" || event == "endEditing" ||
583
+ event == "focus" || event == "keyPress" || event == "scroll" ||
584
+ event == "selectionChange" || event == "submitEditing";
585
+ }
586
+ if (node.component == "Switch") return event == "valueChange";
587
+ if (node.component == "Modal") {
588
+ return event == "dismiss" || event == "orientationChange" ||
589
+ event == "requestClose" || event == "show";
590
+ }
591
+ if (node.component == "Screen") {
592
+ return event == "blur" || event == "dismiss" || event == "focus" ||
593
+ event == "gestureCancel" || event == "nativeDismissCancel" ||
594
+ event == "sheetDetentChange";
595
+ }
596
+ if (node.component == "ScreenStack") return event == "transitionEnd";
597
+ if (node.component == "ScreenHeader") {
598
+ return event == "pressHeaderBarButtonItem" ||
599
+ event == "pressHeaderBarButtonMenuItem";
600
+ }
601
+ if (node.component == "TabsHost") {
602
+ return event == "tabSelected" || event == "tabSelectionRejected" ||
603
+ event == "tabSelectionPrevented" || event == "moreTabSelected";
604
+ }
605
+ if (node.component == "TabsScreen") {
606
+ return event == "willAppear" || event == "didAppear" ||
607
+ event == "willDisappear" || event == "didDisappear";
608
+ }
609
+ return false;
610
+ }
611
+
612
+ folly::dynamic propsPatch(
613
+ const folly::dynamic &previous,
614
+ const folly::dynamic &next) {
615
+ folly::dynamic patch = folly::dynamic::object;
616
+ for (const auto &item : previous.items()) {
617
+ if (next.find(item.first) == next.items().end()) {
618
+ patch[item.first] = nullptr;
619
+ }
620
+ }
621
+ for (const auto &item : next.items()) {
622
+ const auto previousItem = previous.find(item.first);
623
+ if (previousItem == previous.items().end() ||
624
+ previousItem->second != item.second) {
625
+ patch[item.first] = item.second;
626
+ }
627
+ }
628
+ return patch;
629
+ }
630
+
631
+ facebook::react::Tag nextFabricTag() {
632
+ return NextFabricTag.fetch_add(2, std::memory_order_relaxed);
633
+ }
634
+
635
+ bool sameChildren(
636
+ const std::vector<ShadowNodePtr> &left,
637
+ const std::vector<ShadowNodePtr> &right) {
638
+ if (left.size() != right.size()) return false;
639
+ return std::equal(left.begin(), left.end(), right.begin());
640
+ }
641
+
642
+ ShadowNodePtr materializeNode(
643
+ Handle handle,
644
+ StagedNodes &nodes,
645
+ facebook::react::UIManager &uiManager,
646
+ facebook::react::SurfaceId surfaceId,
647
+ facebook::jsi::Runtime *runtime,
648
+ const NativeResourceResolver *resourceResolver,
649
+ std::unordered_set<Handle> &visiting) {
650
+ const auto &existing = requireNode(nodes, handle, "materialize node");
651
+ if (!existing.dirty && existing.shadowNode) return existing.shadowNode;
652
+ auto &node = editNode(nodes, handle, "materialize node");
653
+ if (!visiting.insert(handle).second) {
654
+ throw std::invalid_argument("The staged native tree contains a cycle.");
655
+ }
656
+
657
+ std::vector<ShadowNodePtr> children;
658
+ children.reserve(node.children.size());
659
+ for (const auto child : node.children) {
660
+ children.push_back(
661
+ materializeNode(
662
+ child,
663
+ nodes,
664
+ uiManager,
665
+ surfaceId,
666
+ runtime,
667
+ resourceResolver,
668
+ visiting));
669
+ }
670
+ visiting.erase(handle);
671
+
672
+ const auto component = fabricComponentFor(node, nodes);
673
+ const auto nextProps = fabricPropsFor(node);
674
+ const bool mustCreate =
675
+ !node.shadowNode || node.fabricComponent != component;
676
+
677
+ if (mustCreate) {
678
+ if (node.tag == 0) node.tag = nextFabricTag();
679
+ auto shadowNode = FabricApi::createNode(
680
+ uiManager,
681
+ node.tag,
682
+ component,
683
+ surfaceId,
684
+ nextProps,
685
+ node.instanceHandle,
686
+ runtime,
687
+ resourceResolver);
688
+ for (const auto &child : children) {
689
+ FabricApi::appendChild(uiManager, shadowNode, child);
690
+ }
691
+ node.shadowNode = std::move(shadowNode);
692
+ } else {
693
+ const bool childrenChanged = !sameChildren(node.fabricChildren, children);
694
+ const bool propsChanged = node.fabricProps != nextProps;
695
+ if (childrenChanged || propsChanged) {
696
+ std::shared_ptr<const ShadowNodeList> nextChildren;
697
+ if (childrenChanged) {
698
+ nextChildren = std::make_shared<const ShadowNodeList>(children);
699
+ }
700
+ node.shadowNode = FabricApi::cloneNode(
701
+ uiManager,
702
+ *node.shadowNode,
703
+ std::move(nextChildren),
704
+ propsChanged ? propsPatch(node.fabricProps, nextProps)
705
+ : folly::dynamic::object(),
706
+ runtime,
707
+ resourceResolver);
708
+ }
709
+ }
710
+
711
+ node.fabricComponent = component;
712
+ node.fabricProps = nextProps;
713
+ node.fabricChildren = std::move(children);
714
+ node.dirty = false;
715
+ return node.shadowNode;
716
+ }
717
+
718
+ template <typename Nodes>
719
+ bool isMounted(const NodeRecord &node, const Nodes &nodes) {
720
+ const NodeRecord *current = &node;
721
+ std::unordered_set<Handle> seen;
722
+ while (true) {
723
+ if (!seen.insert(current->handle).second) return false;
724
+ if (!current->parent.has_value()) {
725
+ return current->kind == NodeRecord::Kind::Element &&
726
+ current->component == "RootView";
727
+ }
728
+ current = &requireNode(nodes, *current->parent, "resolve mounted ancestor");
729
+ }
730
+ }
731
+
732
+ } // namespace
733
+
734
+ class TransactionCoordinator::Impl {
735
+ public:
736
+ explicit Impl(facebook::react::SurfaceId surfaceId) : surfaceId_(surfaceId) {}
737
+
738
+ int64_t apply(
739
+ facebook::react::UIManager &uiManager,
740
+ const folly::dynamic &transaction,
741
+ facebook::jsi::Runtime *runtime,
742
+ const NodeIdentityMap &nodeIdentities,
743
+ const NativeResourceResolver *resourceResolver,
744
+ bool requireNodeIdentities) {
745
+ std::lock_guard lock(mutex_);
746
+ if (transaction.isNull()) {
747
+ throw std::invalid_argument("The host transaction is required.");
748
+ }
749
+ requireObject(transaction, "transaction");
750
+
751
+ const auto contractVersion = requireInteger(
752
+ requireMember(transaction, "contractVersion", "transaction"),
753
+ "transaction.contractVersion");
754
+ if (contractVersion != HostContractVersion) {
755
+ throw std::invalid_argument(
756
+ "Unsupported host contract version " +
757
+ std::to_string(contractVersion) + "; expected " +
758
+ std::to_string(HostContractVersion) + ".");
759
+ }
760
+ const auto surface = requireInteger(
761
+ requireMember(transaction, "surface", "transaction"),
762
+ "transaction.surface",
763
+ true);
764
+ if (surface != surfaceId_) {
765
+ throw std::invalid_argument(
766
+ "Transaction targets surface " + std::to_string(surface) +
767
+ ", but this coordinator owns surface " +
768
+ std::to_string(surfaceId_) + ".");
769
+ }
770
+ const auto sequence = requireInteger(
771
+ requireMember(transaction, "sequence", "transaction"),
772
+ "transaction.sequence",
773
+ true);
774
+ if (sequence <= sequence_) {
775
+ throw std::invalid_argument(
776
+ "Commit sequence " + std::to_string(sequence) +
777
+ " must be greater than " + std::to_string(sequence_) + ".");
778
+ }
779
+
780
+ const auto priority = requireString(
781
+ requireMember(transaction, "priority", "transaction"),
782
+ "transaction.priority");
783
+ if (priority != "immediate" && priority != "user-blocking" &&
784
+ priority != "normal" && priority != "background") {
785
+ throw std::invalid_argument("Unknown commit priority: " + priority + ".");
786
+ }
787
+ validateCausalContext(transaction);
788
+
789
+ StagedNodes staged(nodes_);
790
+ auto roots = roots_;
791
+ std::vector<Command> commands;
792
+ const auto &mutations = requireArray(
793
+ requireMember(transaction, "mutations", "transaction"),
794
+ "transaction.mutations");
795
+ size_t index = 0;
796
+ for (const auto &value : mutations) {
797
+ const auto path =
798
+ "transaction.mutations[" + std::to_string(index++) + "]";
799
+ const auto &mutation = requireObject(value, path);
800
+ const auto type = requireString(
801
+ requireMember(mutation, "type", path), path + ".type");
802
+ applyMutation(
803
+ staged,
804
+ roots,
805
+ commands,
806
+ mutation,
807
+ type,
808
+ path,
809
+ nodeIdentities,
810
+ requireNodeIdentities);
811
+ }
812
+
813
+ if (!commands.empty()) {
814
+ if (commands.size() != 1 || mutations.size() != 1) {
815
+ throw std::invalid_argument(
816
+ "A native command must be the only mutation in its transaction.");
817
+ }
818
+ auto &node = requireElement(staged, commands[0].node, "dispatch command");
819
+ if (!node.shadowNode || !isMounted(node, staged)) {
820
+ throw std::invalid_argument(
821
+ "Cannot dispatch a command to an unmounted node.");
822
+ }
823
+ if (commands[0].name == "accessibilityFocus") {
824
+ if (!commands[0].args.empty()) {
825
+ throw std::invalid_argument(
826
+ "The accessibilityFocus command does not accept arguments.");
827
+ }
828
+ FabricApi::sendAccessibilityFocus(uiManager, node.shadowNode);
829
+ } else {
830
+ FabricApi::dispatchCommand(
831
+ uiManager,
832
+ node.shadowNode,
833
+ fabricCommandFor(node, commands[0].name),
834
+ commands[0].args);
835
+ }
836
+ sequence_ = sequence;
837
+ return sequence_;
838
+ }
839
+
840
+ if (roots.size() > 1) {
841
+ throw std::invalid_argument(
842
+ "A Fabric surface cannot contain multiple RootView nodes.");
843
+ }
844
+
845
+ auto rootChildren = std::make_shared<ShadowNodeList>();
846
+ if (!roots.empty()) {
847
+ std::unordered_set<Handle> visiting;
848
+ rootChildren->push_back(materializeNode(
849
+ *roots.begin(),
850
+ staged,
851
+ uiManager,
852
+ surfaceId_,
853
+ runtime,
854
+ resourceResolver,
855
+ visiting));
856
+ }
857
+ staged.preparePublish();
858
+ FabricApi::completeSurface(uiManager, surfaceId_, rootChildren);
859
+ const auto fabricRevision =
860
+ FabricApi::currentRevisionNumber(uiManager, surfaceId_);
861
+
862
+ staged.publish();
863
+ roots_ = std::move(roots);
864
+ sequence_ = sequence;
865
+ fabricRevision_ = fabricRevision;
866
+ return sequence_;
867
+ }
868
+
869
+ NodeMeasurement measure(
870
+ facebook::react::UIManager &uiManager,
871
+ int64_t handle,
872
+ int64_t afterSequence) {
873
+ std::lock_guard lock(mutex_);
874
+ if (handle <= 0) {
875
+ throw std::invalid_argument(
876
+ "A measured node must be a positive safe integer.");
877
+ }
878
+ if (afterSequence < 0) {
879
+ throw std::invalid_argument(
880
+ "A measurement sequence must be a non-negative safe integer.");
881
+ }
882
+ if (afterSequence > sequence_) {
883
+ throw std::invalid_argument(
884
+ "Measurement requires sequence " + std::to_string(afterSequence) +
885
+ ", but the latest committed sequence is " +
886
+ std::to_string(sequence_) + ".");
887
+ }
888
+
889
+ auto &node = requireElement(nodes_, handle, "measure");
890
+ if (!node.shadowNode || !isMounted(node, nodes_)) {
891
+ throw std::invalid_argument("Cannot measure an unmounted node.");
892
+ }
893
+ auto currentRevision =
894
+ uiManager.getShadowTreeRevisionProvider()->getCurrentRevision(
895
+ surfaceId_);
896
+ if (!currentRevision) {
897
+ throw std::runtime_error(
898
+ "Fabric does not have a current revision for this surface.");
899
+ }
900
+ const auto rect = facebook::react::dom::measure(
901
+ currentRevision, *node.shadowNode);
902
+ return NodeMeasurement{
903
+ .x = rect.x,
904
+ .y = rect.y,
905
+ .width = rect.width,
906
+ .height = rect.height,
907
+ .pageX = rect.pageX,
908
+ .pageY = rect.pageY,
909
+ .observedSequence = sequence_};
910
+ }
911
+
912
+ void reset() {
913
+ std::lock_guard lock(mutex_);
914
+ nodes_.clear();
915
+ roots_.clear();
916
+ sequence_ = 0;
917
+ fabricRevision_ = 0;
918
+ }
919
+
920
+ int64_t lastSequence() const {
921
+ std::lock_guard lock(mutex_);
922
+ return sequence_;
923
+ }
924
+
925
+ int64_t lastFabricRevision() const {
926
+ std::lock_guard lock(mutex_);
927
+ return fabricRevision_;
928
+ }
929
+
930
+ bool empty() const {
931
+ std::lock_guard lock(mutex_);
932
+ return nodes_.empty();
933
+ }
934
+
935
+ private:
936
+ static void applyMutation(
937
+ StagedNodes &nodes,
938
+ std::unordered_set<Handle> &roots,
939
+ std::vector<Command> &commands,
940
+ const folly::dynamic &mutation,
941
+ const std::string &type,
942
+ const std::string &path,
943
+ const NodeIdentityMap &nodeIdentities,
944
+ bool requireNodeIdentities) {
945
+ const auto memberPath = path + ".node";
946
+ if (type == "create-element") {
947
+ const auto handle = requireInteger(
948
+ requireMember(mutation, "node", path), memberPath, true);
949
+ if (nodes.contains(handle)) {
950
+ throw std::invalid_argument(
951
+ "Node " + std::to_string(handle) + " already exists.");
952
+ }
953
+ const auto component = requireString(
954
+ requireMember(mutation, "component", path), path + ".component");
955
+ NodeRecord node;
956
+ node.kind = NodeRecord::Kind::Element;
957
+ node.handle = handle;
958
+ node.component = component;
959
+ node.props = requireProps(
960
+ requireMember(mutation, "props", path), path + ".props");
961
+ // Resolve eagerly so unsupported public components fail before any
962
+ // Fabric shadow node is created.
963
+ (void)fabricComponentFor(node, nodes);
964
+ const auto identity = nodeIdentities.find(handle);
965
+ if (identity != nodeIdentities.end()) {
966
+ if (identity->second.tag <= 0 || !identity->second.instanceHandle) {
967
+ throw std::invalid_argument(
968
+ "Node " + std::to_string(handle) +
969
+ " has an invalid Fabric instance identity.");
970
+ }
971
+ node.tag = identity->second.tag;
972
+ node.instanceHandle = identity->second.instanceHandle;
973
+ } else if (requireNodeIdentities) {
974
+ throw std::invalid_argument(
975
+ "Node " + std::to_string(handle) +
976
+ " is missing its Fabric instance identity.");
977
+ }
978
+ nodes.insert(handle, std::move(node));
979
+ if (component == "RootView") roots.insert(handle);
980
+ return;
981
+ }
982
+ if (type == "create-text") {
983
+ const auto handle = requireInteger(
984
+ requireMember(mutation, "node", path), memberPath, true);
985
+ if (nodes.contains(handle)) {
986
+ throw std::invalid_argument(
987
+ "Node " + std::to_string(handle) + " already exists.");
988
+ }
989
+ NodeRecord node;
990
+ node.kind = NodeRecord::Kind::Text;
991
+ node.handle = handle;
992
+ node.text = requireString(
993
+ requireMember(mutation, "text", path), path + ".text");
994
+ const auto identity = nodeIdentities.find(handle);
995
+ if (identity != nodeIdentities.end()) {
996
+ if (identity->second.tag <= 0 || !identity->second.instanceHandle) {
997
+ throw std::invalid_argument(
998
+ "Node " + std::to_string(handle) +
999
+ " has an invalid Fabric instance identity.");
1000
+ }
1001
+ node.tag = identity->second.tag;
1002
+ node.instanceHandle = identity->second.instanceHandle;
1003
+ } else if (requireNodeIdentities) {
1004
+ throw std::invalid_argument(
1005
+ "Node " + std::to_string(handle) +
1006
+ " is missing its Fabric instance identity.");
1007
+ }
1008
+ nodes.insert(handle, std::move(node));
1009
+ return;
1010
+ }
1011
+ if (type == "update-props") {
1012
+ const auto handle = requireInteger(
1013
+ requireMember(mutation, "node", path), memberPath, true);
1014
+ auto &node = editElement(nodes, handle, "update props");
1015
+ invalidateNodeAncestors(nodes, handle);
1016
+ #if defined(__ANDROID__)
1017
+ const auto previousScrollComponent = node.component == "ScrollView"
1018
+ ? fabricComponentFor(node, nodes)
1019
+ : std::string{};
1020
+ #endif
1021
+ auto props = requireProps(
1022
+ requireMember(mutation, "props", path), path + ".props");
1023
+ const auto &removed = requireArray(
1024
+ requireMember(mutation, "removedProps", path),
1025
+ path + ".removedProps");
1026
+ size_t removedIndex = 0;
1027
+ for (const auto &value : removed) {
1028
+ const auto name = requireString(
1029
+ value,
1030
+ path + ".removedProps[" +
1031
+ std::to_string(removedIndex++) + "]");
1032
+ node.props.erase(name);
1033
+ }
1034
+ for (const auto &item : props.items()) {
1035
+ node.props[item.first] = item.second;
1036
+ }
1037
+ #if defined(__ANDROID__)
1038
+ // Scroll content's native descriptor depends on its parent's horizontal
1039
+ // prop. Its own props need not change when the parent switches axes.
1040
+ if (node.component == "ScrollView" &&
1041
+ previousScrollComponent != fabricComponentFor(node, nodes)) {
1042
+ for (const auto child : node.children) {
1043
+ if (requireNode(nodes, child, "resolve scroll child").component ==
1044
+ "ScrollContentView") {
1045
+ invalidateNodeAncestors(nodes, child);
1046
+ }
1047
+ }
1048
+ }
1049
+ #endif
1050
+ return;
1051
+ }
1052
+ if (type == "update-text") {
1053
+ const auto handle = requireInteger(
1054
+ requireMember(mutation, "node", path), memberPath, true);
1055
+ auto &node = editNode(nodes, handle, "update text");
1056
+ if (node.kind != NodeRecord::Kind::Text) {
1057
+ throw std::invalid_argument(
1058
+ "Cannot update text on an element node.");
1059
+ }
1060
+ invalidateNodeAncestors(nodes, handle);
1061
+ node.text = requireString(
1062
+ requireMember(mutation, "text", path), path + ".text");
1063
+ return;
1064
+ }
1065
+ if (type == "update-event-listeners") {
1066
+ const auto handle = requireInteger(
1067
+ requireMember(mutation, "node", path), memberPath, true);
1068
+ auto &node = editElement(nodes, handle, "update event listeners");
1069
+ invalidateNodeAncestors(nodes, handle);
1070
+ const auto &events = requireArray(
1071
+ requireMember(mutation, "events", path), path + ".events");
1072
+ std::vector<std::string> nextEvents;
1073
+ nextEvents.reserve(events.size());
1074
+ std::string previous;
1075
+ size_t eventIndex = 0;
1076
+ for (const auto &value : events) {
1077
+ const auto event = requireString(
1078
+ value,
1079
+ path + ".events[" + std::to_string(eventIndex++) + "]");
1080
+ if (event.empty()) {
1081
+ throw std::invalid_argument("Event listener names cannot be empty.");
1082
+ }
1083
+ if (!previous.empty() && event <= previous) {
1084
+ throw std::invalid_argument(
1085
+ "Event listener names must be sorted and unique.");
1086
+ }
1087
+ if (!supportsEvent(node, event)) {
1088
+ throw std::invalid_argument(
1089
+ "Component " + node.component + " does not define event " +
1090
+ event + ".");
1091
+ }
1092
+ nextEvents.push_back(event);
1093
+ previous = event;
1094
+ }
1095
+ node.eventListeners = std::move(nextEvents);
1096
+ return;
1097
+ }
1098
+ if (type == "insert-child") {
1099
+ const auto parentHandle = requireInteger(
1100
+ requireMember(mutation, "parent", path), path + ".parent", true);
1101
+ const auto childHandle = requireInteger(
1102
+ requireMember(mutation, "child", path), path + ".child", true);
1103
+ auto &parent = editElement(nodes, parentHandle, "insert child");
1104
+ auto &child = editNode(nodes, childHandle, "insert child");
1105
+ if (parentHandle == childHandle) {
1106
+ throw std::invalid_argument("A node cannot be its own parent.");
1107
+ }
1108
+ for (const NodeRecord *ancestor = &parent; ancestor != nullptr;) {
1109
+ if (ancestor->handle == childHandle) {
1110
+ throw std::invalid_argument(
1111
+ "The child insertion would create a cycle.");
1112
+ }
1113
+ ancestor = ancestor->parent.has_value()
1114
+ ? &requireNode(nodes, *ancestor->parent, "resolve ancestor")
1115
+ : nullptr;
1116
+ }
1117
+ if (child.kind == NodeRecord::Kind::Text && !acceptsRawText(parent)) {
1118
+ throw std::invalid_argument(
1119
+ "Raw text children are only valid inside Text.");
1120
+ }
1121
+ if (child.kind == NodeRecord::Kind::Element &&
1122
+ child.component == "RootView") {
1123
+ throw std::invalid_argument("RootView cannot be inserted into a node.");
1124
+ }
1125
+
1126
+ size_t beforeIndex = parent.children.size();
1127
+ if (mutation.count("before") != 0) {
1128
+ const auto before = requireInteger(
1129
+ mutation.at("before"), path + ".before", true);
1130
+ auto iterator =
1131
+ std::find(parent.children.begin(), parent.children.end(), before);
1132
+ if (iterator == parent.children.end()) {
1133
+ throw std::invalid_argument(
1134
+ "The before-node is not a child of the requested parent.");
1135
+ }
1136
+ beforeIndex = static_cast<size_t>(iterator - parent.children.begin());
1137
+ }
1138
+
1139
+ if (child.parent.has_value()) {
1140
+ auto &oldParent =
1141
+ editElement(nodes, *child.parent, "move child from parent");
1142
+ auto iterator = std::find(
1143
+ oldParent.children.begin(), oldParent.children.end(), childHandle);
1144
+ if (iterator == oldParent.children.end()) {
1145
+ throw std::invalid_argument("The child has inconsistent parent state.");
1146
+ }
1147
+ const auto oldIndex =
1148
+ static_cast<size_t>(iterator - oldParent.children.begin());
1149
+ invalidateNodeAncestors(nodes, oldParent.handle);
1150
+ oldParent.children.erase(iterator);
1151
+ if (oldParent.handle == parent.handle && oldIndex < beforeIndex) {
1152
+ beforeIndex--;
1153
+ }
1154
+ }
1155
+ invalidateNodeAncestors(nodes, parentHandle);
1156
+ // Text and Android scroll-content descriptors depend on their immediate
1157
+ // parent. A moved subtree must recompute its root even if its props did
1158
+ // not change; unchanged descendants can still keep their cached nodes.
1159
+ if (child.parent != parentHandle) child.dirty = true;
1160
+ parent.children.insert(parent.children.begin() + beforeIndex, childHandle);
1161
+ child.parent = parentHandle;
1162
+ return;
1163
+ }
1164
+ if (type == "remove-child") {
1165
+ const auto parentHandle = requireInteger(
1166
+ requireMember(mutation, "parent", path), path + ".parent", true);
1167
+ const auto childHandle = requireInteger(
1168
+ requireMember(mutation, "child", path), path + ".child", true);
1169
+ auto &parent = editElement(nodes, parentHandle, "remove child");
1170
+ auto &child = editNode(nodes, childHandle, "remove child");
1171
+ auto iterator =
1172
+ std::find(parent.children.begin(), parent.children.end(), childHandle);
1173
+ if (iterator == parent.children.end() || child.parent != parentHandle) {
1174
+ throw std::invalid_argument(
1175
+ "The requested node is not a child of the requested parent.");
1176
+ }
1177
+ invalidateNodeAncestors(nodes, parentHandle);
1178
+ parent.children.erase(iterator);
1179
+ child.parent.reset();
1180
+ child.dirty = true;
1181
+ return;
1182
+ }
1183
+ if (type == "delete-node") {
1184
+ const auto handle = requireInteger(
1185
+ requireMember(mutation, "node", path), memberPath, true);
1186
+ auto &node = requireNode(nodes, handle, "delete node");
1187
+ if (node.parent.has_value() || !node.children.empty()) {
1188
+ throw std::invalid_argument(
1189
+ "A node must be detached and childless before deletion.");
1190
+ }
1191
+ if (node.kind == NodeRecord::Kind::Element && node.component == "RootView") {
1192
+ roots.erase(handle);
1193
+ }
1194
+ nodes.erase(handle);
1195
+ return;
1196
+ }
1197
+ if (type == "command") {
1198
+ const auto handle = requireInteger(
1199
+ requireMember(mutation, "node", path), memberPath, true);
1200
+ (void)requireElement(nodes, handle, "dispatch command");
1201
+ commands.push_back({
1202
+ .node = handle,
1203
+ .name = requireString(
1204
+ requireMember(mutation, "command", path), path + ".command"),
1205
+ .args = requireArray(
1206
+ requireMember(mutation, "args", path), path + ".args"),
1207
+ });
1208
+ return;
1209
+ }
1210
+
1211
+ throw std::invalid_argument("Unknown host mutation type: " + type + ".");
1212
+ }
1213
+
1214
+ const facebook::react::SurfaceId surfaceId_;
1215
+ mutable std::mutex mutex_;
1216
+ int64_t sequence_{0};
1217
+ int64_t fabricRevision_{0};
1218
+ NodeMap nodes_;
1219
+ std::unordered_set<Handle> roots_;
1220
+ };
1221
+
1222
+ TransactionCoordinator::TransactionCoordinator(int32_t surfaceId)
1223
+ : impl_(std::make_unique<Impl>(surfaceId)) {}
1224
+
1225
+ TransactionCoordinator::~TransactionCoordinator() = default;
1226
+
1227
+ int64_t TransactionCoordinator::apply(
1228
+ facebook::react::UIManager &uiManager,
1229
+ const folly::dynamic &transaction) {
1230
+ return impl_->apply(uiManager, transaction, nullptr, {}, nullptr, false);
1231
+ }
1232
+
1233
+ int64_t TransactionCoordinator::apply(
1234
+ facebook::react::UIManager &uiManager,
1235
+ const folly::dynamic &transaction,
1236
+ facebook::jsi::Runtime &runtime,
1237
+ const NodeIdentityMap &nodeIdentities,
1238
+ const NativeResourceResolver &resourceResolver) {
1239
+ return impl_->apply(
1240
+ uiManager,
1241
+ transaction,
1242
+ &runtime,
1243
+ nodeIdentities,
1244
+ &resourceResolver,
1245
+ true);
1246
+ }
1247
+
1248
+ NodeMeasurement TransactionCoordinator::measure(
1249
+ facebook::react::UIManager &uiManager,
1250
+ int64_t node,
1251
+ int64_t afterSequence) {
1252
+ return impl_->measure(uiManager, node, afterSequence);
1253
+ }
1254
+
1255
+ facebook::react::Tag TransactionCoordinator::allocateFabricTag() {
1256
+ return nextFabricTag();
1257
+ }
1258
+
1259
+ bool TransactionCoordinator::empty() const {
1260
+ return impl_->empty();
1261
+ }
1262
+
1263
+ int64_t TransactionCoordinator::lastFabricRevision() const {
1264
+ return impl_->lastFabricRevision();
1265
+ }
1266
+
1267
+ int64_t TransactionCoordinator::lastSequence() const {
1268
+ return impl_->lastSequence();
1269
+ }
1270
+
1271
+ void TransactionCoordinator::reset() {
1272
+ impl_->reset();
1273
+ }
1274
+
1275
+ } // namespace solid_native::fabric::react_native