react-native-reanimated 4.7.0 → 4.7.2

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 (85) hide show
  1. package/Common/cpp/reanimated/CSS/common/values/CSSNumber.cpp +5 -9
  2. package/Common/cpp/reanimated/CSS/common/values/CSSNumber.h +2 -6
  3. package/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.cpp +34 -2
  4. package/Common/cpp/reanimated/Fabric/ReanimatedCommitHook.h +15 -1
  5. package/Common/cpp/reanimated/Fabric/ReanimatedMountHook.cpp +9 -0
  6. package/Common/cpp/reanimated/Fabric/ReanimatedMountHook.h +3 -0
  7. package/Common/cpp/reanimated/Fabric/updates/AnimatedPropsRegistry.cpp +135 -33
  8. package/Common/cpp/reanimated/Fabric/updates/AnimatedPropsRegistry.h +37 -3
  9. package/Common/cpp/reanimated/Fabric/updates/SynchronousWritesTracker.cpp +103 -0
  10. package/Common/cpp/reanimated/Fabric/updates/SynchronousWritesTracker.h +74 -0
  11. package/Common/cpp/reanimated/Fabric/updates/UpdatesRegistry.cpp +43 -0
  12. package/Common/cpp/reanimated/Fabric/updates/UpdatesRegistry.h +13 -0
  13. package/Common/cpp/reanimated/Fabric/updates/UpdatesRegistryManager.cpp +14 -1
  14. package/Common/cpp/reanimated/Fabric/updates/UpdatesRegistryManager.h +3 -0
  15. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxy.cpp +318 -134
  16. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxy.h +27 -6
  17. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxyCommon.cpp +32 -17
  18. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxyCommon.h +17 -1
  19. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxy_Legacy.cpp +14 -13
  20. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsProxy_Legacy.h +5 -2
  21. package/Common/cpp/reanimated/LayoutAnimations/LayoutAnimationsUtils.h +57 -9
  22. package/Common/cpp/reanimated/LayoutAnimations/PropsDiffer.h +2 -2
  23. package/Common/cpp/reanimated/LayoutAnimations/SharedTransitions.cpp +11 -11
  24. package/Common/cpp/reanimated/NativeModules/ReanimatedModuleProxy.cpp +114 -11
  25. package/Common/cpp/reanimated/NativeModules/ReanimatedModuleProxy.h +12 -2
  26. package/Common/cpp/reanimated/Tools/PlatformDepMethodsHolder.h +17 -1
  27. package/Common/cpp/reanimated/Tools/TextMetrics.h +22 -0
  28. package/android/src/main/cpp/reanimated/android/NativeProxy.cpp +32 -3
  29. package/android/src/main/cpp/reanimated/android/NativeProxy.h +3 -0
  30. package/android/src/main/java/com/swmansion/reanimated/NativeProxy.kt +108 -9
  31. package/android/src/main/java/com/swmansion/reanimated/NodesManager.kt +2 -4
  32. package/android/src/main/java/com/swmansion/reanimated/nativeProxy/EventHandler.kt +4 -3
  33. package/android/src/main/java/com/swmansion/reanimated/sensor/ReanimatedSensor.kt +1 -1
  34. package/android/src/main/java/com/swmansion/reanimated/sensor/ReanimatedSensorListener.kt +44 -33
  35. package/apple/reanimated/apple/REAReducedMotion.h +1 -3
  36. package/apple/reanimated/apple/REASynchronousPropsRewriter.h +18 -0
  37. package/apple/reanimated/apple/REASynchronousPropsRewriter.mm +37 -0
  38. package/apple/reanimated/apple/ReanimatedModule.mm +7 -0
  39. package/apple/reanimated/apple/keyboardObserver/REAKeyboardEventObserver.mm +20 -3
  40. package/apple/reanimated/apple/native/PlatformDepMethodsHolderImpl.mm +52 -1
  41. package/jest/resolver.js +4 -1
  42. package/lib/module/PropsRegistryGarbageCollector.js +43 -25
  43. package/lib/module/PropsRegistryGarbageCollector.js.map +1 -1
  44. package/lib/module/ReanimatedModule/NativeReanimated.js +2 -2
  45. package/lib/module/ReanimatedModule/NativeReanimated.js.map +1 -1
  46. package/lib/module/animation/timing.js +15 -2
  47. package/lib/module/animation/timing.js.map +1 -1
  48. package/lib/module/commonTypes.js.map +1 -1
  49. package/lib/module/createAnimatedComponent/AnimatedComponent.js +1 -1
  50. package/lib/module/createAnimatedComponent/AnimatedComponent.js.map +1 -1
  51. package/lib/module/createAnimatedComponent/AnimatedComponent.native.js +10 -34
  52. package/lib/module/createAnimatedComponent/AnimatedComponent.native.js.map +1 -1
  53. package/lib/module/platform-specific/jsVersion.js +1 -1
  54. package/lib/module/platformFunctions/setNativeProps.native.js +2 -1
  55. package/lib/module/platformFunctions/setNativeProps.native.js.map +1 -1
  56. package/lib/module/updateProps/updateProps.native.js +5 -4
  57. package/lib/module/updateProps/updateProps.native.js.map +1 -1
  58. package/lib/typescript/PropsRegistryGarbageCollector.d.ts +2 -2
  59. package/lib/typescript/PropsRegistryGarbageCollector.d.ts.map +1 -1
  60. package/lib/typescript/ReanimatedModule/reanimatedModuleProxy.d.ts +1 -1
  61. package/lib/typescript/ReanimatedModule/reanimatedModuleProxy.d.ts.map +1 -1
  62. package/lib/typescript/animation/timing.d.ts.map +1 -1
  63. package/lib/typescript/commonTypes.d.ts +3 -1
  64. package/lib/typescript/commonTypes.d.ts.map +1 -1
  65. package/lib/typescript/createAnimatedComponent/AnimatedComponent.d.ts +1 -1
  66. package/lib/typescript/createAnimatedComponent/AnimatedComponent.d.ts.map +1 -1
  67. package/lib/typescript/createAnimatedComponent/AnimatedComponent.native.d.ts +1 -1
  68. package/lib/typescript/createAnimatedComponent/AnimatedComponent.native.d.ts.map +1 -1
  69. package/lib/typescript/createAnimatedComponent/commonTypes.d.ts +1 -1
  70. package/lib/typescript/createAnimatedComponent/commonTypes.d.ts.map +1 -1
  71. package/lib/typescript/platform-specific/jsVersion.d.ts +1 -1
  72. package/lib/typescript/updateProps/updateProps.native.d.ts.map +1 -1
  73. package/package.json +9 -7
  74. package/src/PropsRegistryGarbageCollector.ts +46 -25
  75. package/src/ReanimatedModule/NativeReanimated.ts +2 -2
  76. package/src/ReanimatedModule/reanimatedModuleProxy.ts +1 -1
  77. package/src/animation/timing.ts +20 -2
  78. package/src/commonTypes.ts +3 -1
  79. package/src/createAnimatedComponent/AnimatedComponent.native.tsx +5 -30
  80. package/src/createAnimatedComponent/AnimatedComponent.tsx +1 -1
  81. package/src/createAnimatedComponent/commonTypes.ts +1 -1
  82. package/src/platform-specific/jsVersion.ts +1 -1
  83. package/src/platformFunctions/setNativeProps.native.ts +3 -1
  84. package/src/privateGlobals.d.ts +1 -0
  85. package/src/updateProps/updateProps.native.ts +10 -3
@@ -78,6 +78,14 @@ constexpr bool shouldUseSynchronousUpdatesInPerformOperations() {
78
78
  }
79
79
  #endif
80
80
 
81
+ std::shared_ptr<SynchronousWritesTracker> makeSynchronousWritesTracker() {
82
+ if constexpr (
83
+ shouldUseSynchronousUpdatesInPerformOperations() && !StaticFeatureFlags::getFlag("USE_ANIMATION_BACKEND")) {
84
+ return std::make_shared<SynchronousWritesTracker>();
85
+ }
86
+ return nullptr;
87
+ }
88
+
81
89
  std::pair<UpdatesBatch, UpdatesBatch> partitionUpdates(UpdatesBatch &&updatesBatch, const bool allowPartialUpdates) {
82
90
  const auto isSynchronous = [&](const std::string &keyStr, [[maybe_unused]] const folly::dynamic &value) {
83
91
  if (!isSynchronousPropName(keyStr)) {
@@ -162,6 +170,7 @@ ReanimatedModuleProxy::ReanimatedModuleProxy(
162
170
  getAnimationTimestamp_(platformDepMethodsHolder.getAnimationTimestamp),
163
171
  #ifdef __APPLE__
164
172
  forceScreenSnapshot_(platformDepMethodsHolder.forceScreenSnapshotFunction),
173
+ readMountedViewProps_(platformDepMethodsHolder.readMountedViewPropsFunction),
165
174
  #endif
166
175
  staticPropsRegistry_(std::make_shared<StaticPropsRegistry>()),
167
176
  updatesRegistryManager_(std::make_shared<UpdatesRegistryManager>(staticPropsRegistry_)),
@@ -193,6 +202,7 @@ ReanimatedModuleProxy::ReanimatedModuleProxy(
193
202
  #ifdef ANDROID
194
203
  filterUnmountedTagsFunction_(platformDepMethodsHolder.filterUnmountedTagsFunction),
195
204
  #endif // ANDROID
205
+ synchronousWritesTracker_(makeSynchronousWritesTracker()),
196
206
  subscribeForKeyboardEventsFunction_(platformDepMethodsHolder.subscribeForKeyboardEvents),
197
207
  unsubscribeFromKeyboardEventsFunction_(platformDepMethodsHolder.unsubscribeFromKeyboardEvents) {
198
208
  // Add registries in order of their priority (from the lowest to the
@@ -347,6 +357,26 @@ void ReanimatedModuleProxy::init(const PlatformDepMethodsHolder &platformDepMeth
347
357
  endLayoutAnimation,
348
358
  platformDepMethodsHolder.maybeFlushUIUpdatesQueueFunction,
349
359
  requestAnimationFrame);
360
+
361
+ if constexpr (StaticFeatureFlags::getFlag("RUNTIME_TEST_FLAG")) {
362
+ jsi_utils::installJsiFunction(
363
+ uiRuntime,
364
+ "_obtainMountedViewProps",
365
+ [obtainMountedViewProps = platformDepMethodsHolder.obtainMountedViewProps](
366
+ jsi::Runtime &rt, const jsi::Value &tag) -> jsi::Value {
367
+ const auto props = obtainMountedViewProps(static_cast<Tag>(tag.asNumber()));
368
+ if (!props) {
369
+ return jsi::Value::null();
370
+ }
371
+ jsi::Object result(rt);
372
+ result.setProperty(rt, "x", props->x);
373
+ result.setProperty(rt, "y", props->y);
374
+ result.setProperty(rt, "width", props->width);
375
+ result.setProperty(rt, "height", props->height);
376
+ result.setProperty(rt, "opacity", props->opacity);
377
+ return result;
378
+ });
379
+ }
350
380
  }
351
381
 
352
382
  ReanimatedModuleProxy::~ReanimatedModuleProxy() {
@@ -620,7 +650,7 @@ void ReanimatedModuleProxy::unregisterPseudoStyles(jsi::Runtime &, const jsi::Va
620
650
  pseudoStylesRegistry_->remove(viewTag.asNumber());
621
651
  }
622
652
 
623
- jsi::Value ReanimatedModuleProxy::getSettledUpdates(jsi::Runtime &rt) {
653
+ jsi::Value ReanimatedModuleProxy::getSettledUpdates(jsi::Runtime &rt, const jsi::Value &registeredViewTags) {
624
654
  react_native_assert(
625
655
  StaticFeatureFlags::getFlag("FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS") &&
626
656
  "getSettledUpdates requires FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS static feature flag to be enabled");
@@ -630,9 +660,15 @@ jsi::Value ReanimatedModuleProxy::getSettledUpdates(jsi::Runtime &rt) {
630
660
  // TODO(future): use unified timestamp
631
661
  const auto currentTimestamp = getAnimationTimestamp_();
632
662
 
663
+ const auto viewTagsArray = registeredViewTags.asObject(rt).asArray(rt);
664
+ std::unordered_set<Tag> viewTags;
665
+ for (size_t i = 0, length = viewTagsArray.size(rt); i < length; ++i) {
666
+ viewTags.insert(static_cast<Tag>(viewTagsArray.getValueAtIndex(rt, i).asNumber()));
667
+ }
668
+
633
669
  // TODO(future): flush updates from CSS animations and CSS transitions registries
634
670
  auto lock = updatesRegistryManager_->lock();
635
- return animatedPropsRegistry_->collectSettledUpdates(rt, currentTimestamp - SETTLED_ANIMATION_THRESHOLD_MS);
671
+ return animatedPropsRegistry_->collectSettledUpdates(rt, currentTimestamp - SETTLED_ANIMATION_THRESHOLD_MS, viewTags);
636
672
  }
637
673
 
638
674
  bool ReanimatedModuleProxy::handleEvent(
@@ -868,6 +904,30 @@ void ReanimatedModuleProxy::performNonLayoutOperations() {
868
904
  applySynchronousUpdates(partitionUpdates(std::move(updatesBatch), true).first);
869
905
  }
870
906
 
907
+ bool ReanimatedModuleProxy::hasSynchronousWritesTracker() const {
908
+ return synchronousWritesTracker_ != nullptr;
909
+ }
910
+
911
+ void ReanimatedModuleProxy::rewriteSynchronousProps() {
912
+ if (!synchronousWritesTracker_) {
913
+ return;
914
+ }
915
+ const auto families = synchronousWritesTracker_->getFamiliesToRewrite();
916
+ if (!families.empty()) {
917
+ UpdatesBatch registryValues;
918
+ {
919
+ auto lock = updatesRegistryManager_->lock();
920
+ for (const auto &family : families) {
921
+ folly::dynamic props = folly::dynamic::object;
922
+ updatesRegistryManager_->mergeRegistryProps(family->getTag(), props);
923
+ registryValues.emplace_back(family, std::move(props));
924
+ }
925
+ }
926
+ writeSynchronousPropsToViews(partitionUpdates(std::move(registryValues), true).first);
927
+ }
928
+ synchronousWritesTracker_->onRewrite();
929
+ }
930
+
871
931
  AnimationMutations ReanimatedModuleProxy::collectNonLayoutAnimationUpdates() {
872
932
  ReanimatedSystraceSection s("ReanimatedModuleProxy::collectNonLayoutAnimationUpdates");
873
933
 
@@ -1040,7 +1100,13 @@ void ReanimatedModuleProxy::applySynchronousUpdates(const UpdatesBatch &synchron
1040
1100
  layoutAnimationsProxyRegistry_->applySynchronousProps(
1041
1101
  synchronousUpdatesBatch, DynamicFeatureFlags::getFlag("TRACK_SYNCHRONOUS_PROPS_IN_LAYOUT_ANIMATIONS"));
1042
1102
  }
1103
+ if (synchronousWritesTracker_) {
1104
+ synchronousWritesTracker_->onSynchronousWrite(synchronousUpdatesBatch);
1105
+ }
1106
+ writeSynchronousPropsToViews(synchronousUpdatesBatch);
1107
+ }
1043
1108
 
1109
+ void ReanimatedModuleProxy::writeSynchronousPropsToViews(const UpdatesBatch &synchronousUpdatesBatch) {
1044
1110
  #ifdef ANDROID
1045
1111
  if (!synchronousUpdatesBatch.empty()) {
1046
1112
  serializeSynchronousPropsToBuffers(
@@ -1201,10 +1267,19 @@ void ReanimatedModuleProxy::initializeFabric(const std::shared_ptr<UIManager> &u
1201
1267
  // TODO: with the animation backend we still need a way to handleNodeRemovals,
1202
1268
  // for now we leave this to leak the memory, a fix will come in a follow-up
1203
1269
  mountHook_ = std::make_shared<ReanimatedMountHook>(
1204
- uiManager_, updatesRegistryManager_, viewStylesRepository_, layoutAnimationsProxyRegistry_, request);
1270
+ uiManager_,
1271
+ updatesRegistryManager_,
1272
+ viewStylesRepository_,
1273
+ layoutAnimationsProxyRegistry_,
1274
+ synchronousWritesTracker_,
1275
+ request);
1205
1276
 
1206
1277
  commitHook_ = std::make_shared<ReanimatedCommitHook>(
1207
- uiManager_, updatesRegistryManager_, viewStylesRepository_, layoutAnimationsProxyRegistry_);
1278
+ uiManager_,
1279
+ updatesRegistryManager_,
1280
+ viewStylesRepository_,
1281
+ layoutAnimationsProxyRegistry_,
1282
+ synchronousWritesTracker_);
1208
1283
  }
1209
1284
 
1210
1285
  void ReanimatedModuleProxy::initializeLayoutAnimationsProxyRegistry() {
@@ -1234,6 +1309,9 @@ void ReanimatedModuleProxy::initializeLayoutAnimationsProxyRegistry() {
1234
1309
  });
1235
1310
  };
1236
1311
 
1312
+ constexpr bool keepsSynchronousPropsInReinserts =
1313
+ shouldUseSynchronousUpdatesInPerformOperations() && !StaticFeatureFlags::getFlag("USE_ANIMATION_BACKEND");
1314
+
1237
1315
  const LayoutAnimationsProxyDependencies dependencies{
1238
1316
  layoutAnimationsManager_,
1239
1317
  componentDescriptorRegistry,
@@ -1245,9 +1323,11 @@ void ReanimatedModuleProxy::initializeLayoutAnimationsProxyRegistry() {
1245
1323
  #ifdef ANDROID
1246
1324
  filterUnmountedTagsFunction_,
1247
1325
  jsInvoker_,
1326
+ keepsSynchronousPropsInReinserts ? makeSynchronousPropsReader() : nullptr,
1248
1327
  #endif
1249
1328
  #ifdef __APPLE__
1250
1329
  forceScreenSnapshot_,
1330
+ keepsSynchronousPropsInReinserts ? readMountedViewProps_ : nullptr,
1251
1331
  #endif
1252
1332
  };
1253
1333
 
@@ -1258,6 +1338,25 @@ void ReanimatedModuleProxy::initializeLayoutAnimationsProxyRegistry() {
1258
1338
  }
1259
1339
  }
1260
1340
 
1341
+ #ifdef ANDROID
1342
+ SynchronousPropsReader ReanimatedModuleProxy::makeSynchronousPropsReader() {
1343
+ if (!ReactNativeFeatureFlags::enableAccumulatedUpdatesInRawPropsAndroid()) {
1344
+ return nullptr;
1345
+ }
1346
+ return [weakThis = weak_from_this()](const Tag tag) {
1347
+ const auto strongThis = weakThis.lock();
1348
+ return strongThis ? strongThis->readSynchronousProps(tag) : folly::dynamic::object();
1349
+ };
1350
+ }
1351
+
1352
+ folly::dynamic ReanimatedModuleProxy::readSynchronousProps(const Tag tag) {
1353
+ folly::dynamic synchronousProps = folly::dynamic::object;
1354
+ auto lock = updatesRegistryManager_->lock();
1355
+ updatesRegistryManager_->mergeRegistryProps(tag, synchronousProps, isSynchronousPropName);
1356
+ return synchronousProps;
1357
+ }
1358
+ #endif // ANDROID
1359
+
1261
1360
  #ifdef IS_REANIMATED_EXAMPLE_APP
1262
1361
 
1263
1362
  std::string format(bool b) {
@@ -1580,13 +1679,17 @@ jsi::Object ReanimatedModuleProxy::toOptimizedObject(jsi::Runtime &rt) {
1580
1679
  strongThis->unregisterCSSTransition(rt, at<0>(args));
1581
1680
  });
1582
1681
 
1583
- addMethod<0>(rt, obj, "getSettledUpdates", [weakThis = weak_from_this()](jsi::Runtime &rt, const jsi::Value &) {
1584
- auto strongThis = weakThis.lock();
1585
- if (!strongThis) {
1586
- return jsi::Value::undefined();
1587
- }
1588
- return strongThis->getSettledUpdates(rt);
1589
- });
1682
+ addMethod<1>(
1683
+ rt,
1684
+ obj,
1685
+ "getSettledUpdates",
1686
+ [weakThis = weak_from_this()](jsi::Runtime &rt, const jsi::Value &, const jsi::Value(&args)[1]) {
1687
+ auto strongThis = weakThis.lock();
1688
+ if (!strongThis) {
1689
+ return jsi::Value::undefined();
1690
+ }
1691
+ return strongThis->getSettledUpdates(rt, at<0>(args));
1692
+ });
1590
1693
 
1591
1694
  addMethod<2>(
1592
1695
  rt,
@@ -21,6 +21,7 @@
21
21
  #include <reanimated/Fabric/ShadowTreeCloner.h>
22
22
  #include <reanimated/Fabric/updates/AnimatedPropsRegistry.h>
23
23
  #include <reanimated/Fabric/updates/OperationsLoop.h>
24
+ #include <reanimated/Fabric/updates/SynchronousWritesTracker.h>
24
25
  #include <reanimated/Fabric/updates/UpdatesRegistryManager.h>
25
26
  #include <reanimated/LayoutAnimations/LayoutAnimationsManager.h>
26
27
  #include <reanimated/LayoutAnimations/LayoutAnimationsProxyRegistry.h>
@@ -108,6 +109,8 @@ class ReanimatedModuleProxy : public std::enable_shared_from_this<ReanimatedModu
108
109
 
109
110
  void performOperations();
110
111
  void performNonLayoutOperations();
112
+ bool hasSynchronousWritesTracker() const;
113
+ void rewriteSynchronousProps();
111
114
  void flushLayoutAnimationOperations();
112
115
  void executeLayoutAnimationsRequests();
113
116
 
@@ -152,7 +155,7 @@ class ReanimatedModuleProxy : public std::enable_shared_from_this<ReanimatedModu
152
155
  void registerPseudoStyles(jsi::Runtime &rt, const jsi::Value &shadowNodeWrapper, const jsi::Value &config);
153
156
  void unregisterPseudoStyles(jsi::Runtime &rt, const jsi::Value &viewTag);
154
157
 
155
- jsi::Value getSettledUpdates(jsi::Runtime &rt);
158
+ jsi::Value getSettledUpdates(jsi::Runtime &rt, const jsi::Value &registeredViewTags);
156
159
 
157
160
  void dispatchCommand(
158
161
  jsi::Runtime &rt,
@@ -205,6 +208,11 @@ class ReanimatedModuleProxy : public std::enable_shared_from_this<ReanimatedModu
205
208
 
206
209
  void commitUpdates(const std::unordered_map<SurfaceId, PropsMap> &propsMapBySurface);
207
210
  void applySynchronousUpdates(const UpdatesBatch &synchronousUpdatesBatch);
211
+ void writeSynchronousPropsToViews(const UpdatesBatch &synchronousUpdatesBatch);
212
+ #ifdef ANDROID
213
+ SynchronousPropsReader makeSynchronousPropsReader();
214
+ folly::dynamic readSynchronousProps(Tag tag);
215
+ #endif
208
216
 
209
217
  std::shared_ptr<UIManagerAnimationBackend> getAnimationBackend();
210
218
  AnimationMutations runGrandCallback(AnimationTimestamp timestamp, GrandCallbackSource source);
@@ -239,6 +247,7 @@ class ReanimatedModuleProxy : public std::enable_shared_from_this<ReanimatedModu
239
247
 
240
248
  #ifdef __APPLE__
241
249
  ForceScreenSnapshotFunction forceScreenSnapshot_;
250
+ ReadMountedViewPropsFunction readMountedViewProps_;
242
251
  #endif
243
252
  const std::shared_ptr<StaticPropsRegistry> staticPropsRegistry_;
244
253
  const std::shared_ptr<UpdatesRegistryManager> updatesRegistryManager_;
@@ -253,9 +262,10 @@ class ReanimatedModuleProxy : public std::enable_shared_from_this<ReanimatedModu
253
262
 
254
263
  const SynchronouslyUpdateUIPropsFunction synchronouslyUpdateUIPropsFunction_;
255
264
  const PreserveMountedTagsFunction filterUnmountedTagsFunction_;
265
+ const std::shared_ptr<SynchronousWritesTracker> synchronousWritesTracker_;
256
266
 
257
267
  #ifdef ANDROID
258
- // Reused across `applySynchronousUpdates` calls to avoid per-frame heap
268
+ // Reused across `writeSynchronousPropsToViews` calls to avoid per-frame heap
259
269
  // allocations. Access only on the UI thread.
260
270
  std::vector<int> synchronousPropsIntBuffer_;
261
271
  std::vector<double> synchronousPropsDoubleBuffer_;
@@ -6,9 +6,11 @@
6
6
 
7
7
  #include <folly/dynamic.h>
8
8
  #include <jsi/jsi.h>
9
+ #include <react/renderer/core/Props.h>
9
10
  #include <react/renderer/core/ReactPrimitives.h>
10
11
 
11
12
  #include <memory>
13
+ #include <optional>
12
14
  #include <string>
13
15
  #include <utility>
14
16
  #include <vector>
@@ -47,7 +49,19 @@ using KeyboardEventSubscribeFunction = std::function<int(std::function<void(int,
47
49
  using KeyboardEventUnsubscribeFunction = std::function<void(int)>;
48
50
  using MaybeFlushUIUpdatesQueueFunction = std::function<void()>;
49
51
 
50
- using ForceScreenSnapshotFunction = std::function<void(Tag tag)>;
52
+ using ForceScreenSnapshotFunction = std::function<bool(Tag tag)>;
53
+ using ReadMountedViewPropsFunction = std::function<Props::Shared(Tag tag)>;
54
+
55
+ // A view is mounted while it is attached to the window. The frame is in points, relative to the parent and without
56
+ // transforms.
57
+ struct MountedViewProps {
58
+ double x;
59
+ double y;
60
+ double width;
61
+ double height;
62
+ double opacity;
63
+ };
64
+ using ObtainMountedViewPropsFunction = std::function<std::optional<MountedViewProps>(Tag tag)>;
51
65
 
52
66
  using PlatformAttachPseudoSelectorFunction = std::function<void(Tag, PseudoSelector, std::function<void(bool)>)>;
53
67
  using PlatformDetachPseudoSelectorFunction = std::function<void(Tag, PseudoSelector)>;
@@ -59,6 +73,7 @@ struct PlatformDepMethodsHolder {
59
73
  #endif // ANDROID
60
74
  #ifdef __APPLE__
61
75
  ForceScreenSnapshotFunction forceScreenSnapshotFunction;
76
+ ReadMountedViewPropsFunction readMountedViewPropsFunction;
62
77
  #endif
63
78
  SynchronouslyUpdateUIPropsFunction synchronouslyUpdateUIPropsFunction;
64
79
  GetAnimationTimestampFunction getAnimationTimestamp;
@@ -70,6 +85,7 @@ struct PlatformDepMethodsHolder {
70
85
  MaybeFlushUIUpdatesQueueFunction maybeFlushUIUpdatesQueueFunction;
71
86
  PlatformAttachPseudoSelectorFunction attachPseudoSelector;
72
87
  PlatformDetachPseudoSelectorFunction detachPseudoSelector;
88
+ ObtainMountedViewPropsFunction obtainMountedViewProps;
73
89
  // Optional and last, so a platform without them just omits them; null keeps
74
90
  // CSS transitions and animations on the C++ loop.
75
91
  std::shared_ptr<css::CSSPlatformTransitionBackend> platformTransitionBackend;
@@ -0,0 +1,22 @@
1
+ #pragma once
2
+
3
+ #include <react/utils/FloatComparison.h>
4
+
5
+ #include <array>
6
+ #include <cmath>
7
+
8
+ namespace reanimated {
9
+
10
+ /// React Native compares text attributes with kDefaultEpsilon but lays them out
11
+ /// exactly, so a smaller step moves the frame while the text keeps its old
12
+ /// metrics. Rounding to a coarser grid makes every change exceed the epsilon.
13
+ /// https://github.com/facebook/react-native/blob/v0.87.0/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.cpp#L174-L177
14
+ inline constexpr std::array<const char *, 3> TEXT_METRIC_PROP_NAMES = {"fontSize", "letterSpacing", "lineHeight"};
15
+
16
+ inline double roundTextMetric(const double value) {
17
+ constexpr double stepsPerUnit = 100;
18
+ static_assert(1 / stepsPerUnit > facebook::react::kDefaultEpsilon);
19
+ return std::round(value * stepsPerUnit) / stepsPerUnit;
20
+ }
21
+
22
+ } // namespace reanimated
@@ -138,6 +138,14 @@ void NativeProxy::performNonLayoutOperations() {
138
138
  reanimatedModuleProxy_->performNonLayoutOperations();
139
139
  }
140
140
 
141
+ bool NativeProxy::hasSynchronousWritesTracker() {
142
+ return reanimatedModuleProxy_->hasSynchronousWritesTracker();
143
+ }
144
+
145
+ void NativeProxy::rewriteSynchronousProps() {
146
+ reanimatedModuleProxy_->rewriteSynchronousProps();
147
+ }
148
+
141
149
  bool NativeProxy::getIsReducedMotion() {
142
150
  static const auto method = getJniMethod<jboolean()>("getIsReducedMotion");
143
151
  return method(javaPart_.get());
@@ -151,9 +159,11 @@ void NativeProxy::registerNatives() {
151
159
  registerHybrid(
152
160
  {makeNativeMethod("initHybrid", NativeProxy::initHybrid),
153
161
  makeNativeMethod("installJSIBindings", NativeProxy::installJSIBindings),
154
- makeNativeMethod("isAnyHandlerWaitingForEvent", NativeProxy::isAnyHandlerWaitingForEvent),
155
- makeNativeMethod("performOperations", NativeProxy::performOperations),
156
- makeNativeMethod("performNonLayoutOperations", NativeProxy::performNonLayoutOperations),
162
+ makeNativeMethod("isAnyHandlerWaitingForEventCpp", NativeProxy::isAnyHandlerWaitingForEvent),
163
+ makeNativeMethod("performOperationsCpp", NativeProxy::performOperations),
164
+ makeNativeMethod("performNonLayoutOperationsCpp", NativeProxy::performNonLayoutOperations),
165
+ makeNativeMethod("hasSynchronousWritesTracker", NativeProxy::hasSynchronousWritesTracker),
166
+ makeNativeMethod("rewriteSynchronousProps", NativeProxy::rewriteSynchronousProps),
157
167
  makeNativeMethod("invalidateCpp", NativeProxy::invalidateCpp),
158
168
  makeNativeMethod("toggleSlowAnimationsOnUIRuntime", NativeProxy::toggleSlowAnimationsOnUIRuntime)});
159
169
  }
@@ -196,6 +206,22 @@ std::optional<std::unique_ptr<int[]>> NativeProxy::preserveMountedTags(std::vect
196
206
  return region;
197
207
  }
198
208
 
209
+ std::optional<MountedViewProps> NativeProxy::obtainMountedViewProps(Tag tag) {
210
+ static const auto method = getJniMethod<jni::local_ref<jni::JArrayFloat>(int)>("obtainMountedViewProps");
211
+ auto values = method(javaPart_.get(), tag);
212
+ if (!values) {
213
+ return std::nullopt;
214
+ }
215
+ const auto region = values->getRegion(0, 5);
216
+ return MountedViewProps{
217
+ .x = region[0],
218
+ .y = region[1],
219
+ .width = region[2],
220
+ .height = region[3],
221
+ .opacity = region[4],
222
+ };
223
+ }
224
+
199
225
  void NativeProxy::synchronouslyUpdateUIProps(
200
226
  const std::vector<int> &intBuffer,
201
227
  const std::vector<double> &doubleBuffer) {
@@ -379,6 +405,8 @@ PlatformDepMethodsHolder NativeProxy::getPlatformDependentMethods() {
379
405
 
380
406
  auto detachPseudoSelectorFunction = bindThis(&NativeProxy::detachPseudoSelector);
381
407
 
408
+ auto obtainMountedViewPropsFunction = bindThis(&NativeProxy::obtainMountedViewProps);
409
+
382
410
  auto platformTransitionBackend = makePlatformTransitionBackend();
383
411
 
384
412
  return {
@@ -394,6 +422,7 @@ PlatformDepMethodsHolder NativeProxy::getPlatformDependentMethods() {
394
422
  maybeFlushUiUpdatesQueueFunction,
395
423
  attachPseudoSelectorFunction,
396
424
  detachPseudoSelectorFunction,
425
+ obtainMountedViewPropsFunction,
397
426
  platformTransitionBackend,
398
427
  };
399
428
  }
@@ -48,6 +48,7 @@ class NativeProxy : public jni::HybridClass<NativeProxy>, std::enable_shared_fro
48
48
  // std::shared_ptr<EventListener> eventListener_;
49
49
  void installJSIBindings();
50
50
  std::optional<std::unique_ptr<int[]>> preserveMountedTags(std::vector<int> &tags);
51
+ std::optional<MountedViewProps> obtainMountedViewProps(Tag tag);
51
52
  void synchronouslyUpdateUIProps(const std::vector<int> &intBuffer, const std::vector<double> &doubleBuffer);
52
53
  PlatformDepMethodsHolder getPlatformDependentMethods();
53
54
 
@@ -55,6 +56,8 @@ class NativeProxy : public jni::HybridClass<NativeProxy>, std::enable_shared_fro
55
56
  bool isAnyHandlerWaitingForEvent(const std::string &eventName, const int emitterReactTag);
56
57
  void performOperations();
57
58
  void performNonLayoutOperations();
59
+ bool hasSynchronousWritesTracker();
60
+ void rewriteSynchronousProps();
58
61
  bool getIsReducedMotion();
59
62
  void requestRender(std::function<void(double)> onRender);
60
63
  void registerEventHandler();
@@ -8,11 +8,15 @@ import com.facebook.jni.HybridData
8
8
  import com.facebook.proguard.annotations.DoNotStrip
9
9
  import com.facebook.react.bridge.NativeModule
10
10
  import com.facebook.react.bridge.ReactApplicationContext
11
+ import com.facebook.react.bridge.UIManager
12
+ import com.facebook.react.bridge.UIManagerListener
11
13
  import com.facebook.react.bridge.UiThreadUtil
12
14
  import com.facebook.react.common.annotations.FrameworkAPI
15
+ import com.facebook.react.common.annotations.UnstableReactNativeAPI
13
16
  import com.facebook.react.fabric.FabricUIManager
14
17
  import com.facebook.react.turbomodule.core.CallInvokerHolderImpl
15
18
  import com.facebook.react.uimanager.IllegalViewOperationException
19
+ import com.facebook.react.uimanager.PixelUtil
16
20
  import com.facebook.react.uimanager.UIManagerHelper
17
21
  import com.facebook.react.uimanager.common.UIManagerType
18
22
  import com.facebook.soloader.SoLoader
@@ -30,6 +34,8 @@ import com.swmansion.reanimated.sensor.ReanimatedSensorContainer
30
34
  import com.swmansion.reanimated.sensor.ReanimatedSensorType
31
35
  import java.lang.ref.WeakReference
32
36
  import java.util.concurrent.atomic.AtomicBoolean
37
+ import java.util.concurrent.locks.ReentrantReadWriteLock
38
+ import kotlin.concurrent.write
33
39
 
34
40
  @Suppress("KotlinJniMissingFunction")
35
41
  @OptIn(FrameworkAPI::class)
@@ -64,10 +70,27 @@ open class NativeProxy {
64
70
  */
65
71
  private val mInvalidated = AtomicBoolean(false)
66
72
 
73
+ // Guards the C++ state that invalidateCpp() destroys against calls from the UI thread.
74
+ private val mNativeStateLock = ReentrantReadWriteLock()
75
+
67
76
  @field:DoNotStrip
68
77
  @Suppress("unused")
69
78
  private val mHybridData: HybridData
70
79
 
80
+ @OptIn(UnstableReactNativeAPI::class)
81
+ private val mountListener =
82
+ object : UIManagerListener {
83
+ override fun willDispatchViewUpdates(uiManager: UIManager) = Unit
84
+
85
+ override fun willMountItems(uiManager: UIManager) = Unit
86
+
87
+ override fun didMountItems(uiManager: UIManager) = ifNotInvalidated(Unit) { rewriteSynchronousProps() }
88
+
89
+ override fun didDispatchMountItems(uiManager: UIManager) = Unit
90
+
91
+ override fun didScheduleMountItems(uiManager: UIManager) = Unit
92
+ }
93
+
71
94
  constructor(context: ReactApplicationContext, nodesManager: NodesManager) {
72
95
  context.assertOnJSQueueThread()
73
96
 
@@ -109,6 +132,10 @@ open class NativeProxy {
109
132
  if (BuildConfig.DEBUG) {
110
133
  checkCppVersion() // injectCppVersion should be called during initHybrid above
111
134
  }
135
+ if (hasSynchronousWritesTracker()) {
136
+ @OptIn(UnstableReactNativeAPI::class)
137
+ mFabricUIManager.addUIManagerEventListener(mountListener)
138
+ }
112
139
  }
113
140
 
114
141
  private external fun initHybrid(
@@ -117,31 +144,67 @@ open class NativeProxy {
117
144
  fabricUIManager: FabricUIManager,
118
145
  ): HybridData
119
146
 
120
- external fun isAnyHandlerWaitingForEvent(
147
+ private external fun isAnyHandlerWaitingForEventCpp(
121
148
  eventName: String,
122
149
  emitterReactTag: Int,
123
150
  ): Boolean
124
151
 
125
- external fun performOperations()
152
+ private external fun performOperationsCpp()
153
+
154
+ private external fun performNonLayoutOperationsCpp()
126
155
 
127
- external fun performNonLayoutOperations()
156
+ private external fun hasSynchronousWritesTracker(): Boolean
157
+
158
+ private external fun rewriteSynchronousProps()
128
159
 
129
160
  external fun installJSIBindings()
130
161
 
131
162
  private external fun invalidateCpp()
132
163
 
133
- external fun toggleSlowAnimationsOnUIRuntime()
164
+ private external fun toggleSlowAnimationsOnUIRuntime()
134
165
 
135
166
  protected fun getHybridData(): HybridData = mHybridData
136
167
 
168
+ // tryLock, because the UI thread may hold the UI runtime lock, which could deadlock with invalidate()
169
+ private inline fun <T> ifNotInvalidated(
170
+ fallback: T,
171
+ block: () -> T,
172
+ ): T {
173
+ val readLock = mNativeStateLock.readLock()
174
+ if (!readLock.tryLock()) {
175
+ return fallback
176
+ }
177
+ try {
178
+ if (mInvalidated.get()) {
179
+ return fallback
180
+ }
181
+ return block()
182
+ } finally {
183
+ readLock.unlock()
184
+ }
185
+ }
186
+
187
+ fun isAnyHandlerWaitingForEvent(
188
+ eventName: String,
189
+ emitterReactTag: Int,
190
+ ): Boolean = ifNotInvalidated(false) { isAnyHandlerWaitingForEventCpp(eventName, emitterReactTag) }
191
+
192
+ fun performOperations() = ifNotInvalidated(Unit) { performOperationsCpp() }
193
+
194
+ fun performNonLayoutOperations() = ifNotInvalidated(Unit) { performNonLayoutOperationsCpp() }
195
+
137
196
  fun invalidate() {
138
197
  if (mInvalidated.getAndSet(true)) {
139
198
  return
140
199
  }
200
+ @OptIn(UnstableReactNativeAPI::class)
201
+ mFabricUIManager.removeUIManagerEventListener(mountListener)
141
202
  pseudoSelectorManager.invalidate()
142
203
  cssPlatformTransitionsManager.invalidate()
143
- if (mHybridData.isValid) {
144
- invalidateCpp()
204
+ mNativeStateLock.write {
205
+ if (mHybridData.isValid) {
206
+ invalidateCpp()
207
+ }
145
208
  }
146
209
  }
147
210
 
@@ -152,7 +215,7 @@ open class NativeProxy {
152
215
  }
153
216
  mNodesManager!!.enableSlowAnimations(slowAnimationsEnabled, animationsDragFactor)
154
217
  cssPlatformTransitionsManager.enableSlowAnimations(slowAnimationsEnabled, animationsDragFactor)
155
- toggleSlowAnimationsOnUIRuntime()
218
+ ifNotInvalidated(Unit) { toggleSlowAnimationsOnUIRuntime() }
156
219
  }
157
220
 
158
221
  private fun addDevMenuOption() {
@@ -175,8 +238,12 @@ open class NativeProxy {
175
238
 
176
239
  @DoNotStrip
177
240
  fun requestRender(callback: AnimationFrameCallback) {
241
+ val guardedCallback =
242
+ object : NodesManager.OnAnimationFrame {
243
+ override fun onAnimationFrame(timestampMs: Double) = ifNotInvalidated(Unit) { callback.onAnimationFrame(timestampMs) }
244
+ }
178
245
  UiThreadUtil.assertOnUiThread()
179
- mNodesManager!!.postOnAnimation(callback)
246
+ mNodesManager!!.postOnAnimation(guardedCallback)
180
247
  }
181
248
 
182
249
  @DoNotStrip fun getReanimatedJavaVersion(): String = BuildConfig.REANIMATED_VERSION_JAVA
@@ -203,6 +270,29 @@ open class NativeProxy {
203
270
  }
204
271
  }
205
272
 
273
+ @DoNotStrip
274
+ fun obtainMountedViewProps(tag: Int): FloatArray? {
275
+ if (!UiThreadUtil.isOnUiThread()) {
276
+ return null
277
+ }
278
+ val view =
279
+ try {
280
+ mFabricUIManager.resolveView(tag)
281
+ } catch (e: IllegalViewOperationException) {
282
+ null
283
+ } ?: return null
284
+ if (!view.isAttachedToWindow) {
285
+ return null
286
+ }
287
+ return floatArrayOf(
288
+ PixelUtil.toDIPFromPixel(view.left.toFloat()),
289
+ PixelUtil.toDIPFromPixel(view.top.toFloat()),
290
+ PixelUtil.toDIPFromPixel(view.width.toFloat()),
291
+ PixelUtil.toDIPFromPixel(view.height.toFloat()),
292
+ view.alpha,
293
+ )
294
+ }
295
+
206
296
  @DoNotStrip
207
297
  fun preserveMountedTags(tags: IntArray): Boolean {
208
298
  if (!UiThreadUtil.isOnUiThread()) {
@@ -250,6 +340,10 @@ open class NativeProxy {
250
340
  }.apply { isAccessible = true }
251
341
  }
252
342
 
343
+ private val getViewExistsMethod by lazy {
344
+ runCatching { mountingManager.javaClass.getMethod("getViewExists", Int::class.javaPrimitiveType) }.getOrNull()
345
+ }
346
+
253
347
  @DoNotStrip
254
348
  fun synchronouslyUpdateUIProps(
255
349
  intBuffer: IntArray,
@@ -258,9 +352,13 @@ open class NativeProxy {
258
352
  cssPlatformTransitionsManager.onPropsWrittenSynchronously()
259
353
  SynchronousPropsBufferParser.parse(intBuffer, doubleBuffer) { viewTag, props ->
260
354
  try {
355
+ // The props stay in the registry, and the commit hook applies them to the shadow tree.
356
+ if (getViewExistsMethod?.invoke(mountingManager, viewTag) == false) {
357
+ return@parse
358
+ }
261
359
  updatePropsSynchronouslyMethod.invoke(mountingManager, viewTag, props)
262
360
  } catch (e: Exception) {
263
- Log.w("Reanimated", "synchronouslyUpdateUIProps failed for tag $viewTag", e)
361
+ Log.w("Reanimated", "synchronouslyUpdateUIProps failed for tag $viewTag: ${e.cause ?: e}")
264
362
  }
265
363
  }
266
364
  }
@@ -330,6 +428,7 @@ open class NativeProxy {
330
428
  fun registerEventHandler(handler: EventHandler) {
331
429
  handler.mCustomEventNamesResolver = mNodesManager!!.getEventNameResolver()
332
430
  handler.isInDrawPassProvider = { mNodesManager!!.isInDrawPass() }
431
+ handler.nativeCallGuard = { receive -> ifNotInvalidated(Unit, receive) }
333
432
  mNodesManager!!.registerEventHandler(handler)
334
433
  }
335
434
 
@@ -199,9 +199,7 @@ class NodesManager(
199
199
  Trace.beginSection("onEventDispatch")
200
200
  }
201
201
 
202
- if (mNativeProxy == null) {
203
- return
204
- }
202
+ val nativeProxy = mNativeProxy ?: return
205
203
  // Events can be dispatched from any thread so we have to make sure handleEvent is run from
206
204
  // the UI thread.
207
205
  if (UiThreadUtil.isOnUiThread()) {
@@ -213,7 +211,7 @@ class NodesManager(
213
211
  } else {
214
212
  val eventName = mCustomEventNamesResolver.resolveCustomEventName(event.eventName) ?: return
215
213
  val viewTag = event.viewTag
216
- val shouldSaveEvent = mNativeProxy!!.isAnyHandlerWaitingForEvent(eventName, viewTag)
214
+ val shouldSaveEvent = nativeProxy.isAnyHandlerWaitingForEvent(eventName, viewTag)
217
215
  if (shouldSaveEvent) {
218
216
  mEventQueue.offer(CopiedEvent(event))
219
217
  }