-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathNativeReanimatedModule.cpp
More file actions
682 lines (604 loc) · 23.2 KB
/
NativeReanimatedModule.cpp
File metadata and controls
682 lines (604 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
#include "NativeReanimatedModule.h"
#ifdef RCT_NEW_ARCH_ENABLED
#include <react/renderer/uimanager/UIManagerBinding.h>
#include <react/renderer/uimanager/primitives.h>
#endif
#include <functional>
#include <memory>
#include <thread>
#include <unordered_map>
#ifdef RCT_NEW_ARCH_ENABLED
#include "FabricUtils.h"
#include "NewestShadowNodesRegistry.h"
#include "ReanimatedUIManagerBinding.h"
#include "ShadowTreeCloner.h"
#endif
#include "EventHandlerRegistry.h"
#include "FeaturesConfig.h"
#include "ReanimatedHiddenHeaders.h"
#include "RuntimeDecorator.h"
#include "Shareables.h"
#include "WorkletEventHandler.h"
using namespace facebook;
namespace reanimated {
NativeReanimatedModule::NativeReanimatedModule(
const std::shared_ptr<CallInvoker> &jsInvoker,
const std::shared_ptr<Scheduler> &scheduler,
const std::shared_ptr<jsi::Runtime> &rt,
const std::shared_ptr<ErrorHandler> &errorHandler,
#ifdef RCT_NEW_ARCH_ENABLED
// nothing
#else
std::function<jsi::Value(jsi::Runtime &, const int, const jsi::String &)>
propObtainer,
#endif
PlatformDepMethodsHolder platformDepMethodsHolder)
: NativeReanimatedModuleSpec(jsInvoker),
RuntimeManager(rt, errorHandler, scheduler, RuntimeType::UI),
eventHandlerRegistry(std::make_unique<EventHandlerRegistry>()),
requestRender(platformDepMethodsHolder.requestRender),
#ifdef RCT_NEW_ARCH_ENABLED
// nothing
#else
propObtainer(propObtainer),
#endif
animatedSensorModule(platformDepMethodsHolder),
#ifdef RCT_NEW_ARCH_ENABLED
synchronouslyUpdateUIPropsFunction(
platformDepMethodsHolder.synchronouslyUpdateUIPropsFunction)
#else
configurePropsPlatformFunction(
platformDepMethodsHolder.configurePropsFunction)
#endif
{
auto requestAnimationFrame = [=](jsi::Runtime &rt, const jsi::Value &fn) {
auto jsFunction = std::make_shared<jsi::Value>(rt, fn);
frameCallbacks.push_back([=](double timestamp) {
runtimeHelper->runOnUIGuarded(*jsFunction, jsi::Value(timestamp));
});
maybeRequestRender();
};
auto scheduleOnJS = [this](
jsi::Runtime &rt,
const jsi::Value &remoteFun,
const jsi::Value &argsValue) {
auto shareableRemoteFun = extractShareableOrThrow<ShareableRemoteFunction>(
rt,
remoteFun,
"Incompatible object passed to scheduleOnJS. It is only allowed to schedule functions defined on the React Native JS runtime this way.");
auto shareableArgs = argsValue.isUndefined()
? nullptr
: extractShareableOrThrow(rt, argsValue);
auto jsRuntime = this->runtimeHelper->rnRuntime();
this->scheduler->scheduleOnJS([=] {
jsi::Runtime &rt = *jsRuntime;
auto remoteFun = shareableRemoteFun->getJSValue(rt);
if (shareableArgs == nullptr) {
// fast path for remote function w/o arguments
remoteFun.asObject(rt).asFunction(rt).call(rt);
} else {
auto argsArray = shareableArgs->getJSValue(rt).asObject(rt).asArray(rt);
auto argsSize = argsArray.size(rt);
// number of arguments is typically relatively small so it is ok to
// to use VLAs here, hence disabling the lint rule
jsi::Value args[argsSize]; // NOLINT(runtime/arrays)
for (size_t i = 0; i < argsSize; i++) {
args[i] = argsArray.getValueAtIndex(rt, i);
}
remoteFun.asObject(rt).asFunction(rt).call(rt, args, argsSize);
}
});
};
auto makeShareableClone = [this](jsi::Runtime &rt, const jsi::Value &value) {
return this->makeShareableClone(rt, value);
};
auto updateDataSynchronously =
[this](
jsi::Runtime &rt,
const jsi::Value &synchronizedDataHolderRef,
const jsi::Value &newData) {
return this->updateDataSynchronously(
rt, synchronizedDataHolderRef, newData);
};
#ifdef RCT_NEW_ARCH_ENABLED
auto updateProps = [this](
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue,
const jsi::Value &props) {
this->updateProps(rt, shadowNodeValue, props);
};
auto removeShadowNodeFromRegistry =
[this](jsi::Runtime &rt, const jsi::Value &shadowNodeValue) {
this->removeShadowNodeFromRegistry(rt, shadowNodeValue);
};
auto measure = [this](jsi::Runtime &rt, const jsi::Value &shadowNodeValue) {
return this->measure(rt, shadowNodeValue);
};
auto dispatchCommand = [this](
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue,
const jsi::Value &commandNameValue,
const jsi::Value &argsValue) {
this->dispatchCommand(rt, shadowNodeValue, commandNameValue, argsValue);
};
#endif
RuntimeDecorator::decorateUIRuntime(
*runtime,
#ifdef RCT_NEW_ARCH_ENABLED
updateProps,
measure,
removeShadowNodeFromRegistry,
dispatchCommand,
#else
platformDepMethodsHolder.updatePropsFunction,
platformDepMethodsHolder.measureFunction,
platformDepMethodsHolder.scrollToFunction,
#endif
requestAnimationFrame,
scheduleOnJS,
makeShareableClone,
updateDataSynchronously,
platformDepMethodsHolder.getCurrentTime,
platformDepMethodsHolder.registerSensor,
platformDepMethodsHolder.unregisterSensor,
platformDepMethodsHolder.setGestureStateFunction,
platformDepMethodsHolder.progressLayoutAnimation,
platformDepMethodsHolder.endLayoutAnimation);
onRenderCallback = [this](double timestampMs) {
this->renderRequested = false;
this->onRender(timestampMs);
};
#ifdef RCT_NEW_ARCH_ENABLED
// nothing
#else
updatePropsFunction = platformDepMethodsHolder.updatePropsFunction;
#endif
subscribeForKeyboardEventsFunction =
platformDepMethodsHolder.subscribeForKeyboardEvents;
unsubscribeFromKeyboardEventsFunction =
platformDepMethodsHolder.unsubscribeFromKeyboardEvents;
}
void NativeReanimatedModule::installCoreFunctions(
jsi::Runtime &rt,
const jsi::Value &callGuard,
const jsi::Value &valueUnpacker) {
if (!runtimeHelper) {
// initialize runtimeHelper here if not already present. We expect only one
// instace of the helper to exists.
runtimeHelper =
std::make_shared<JSRuntimeHelper>(&rt, this->runtime.get(), scheduler);
}
runtimeHelper->callGuard =
std::make_unique<CoreFunction>(runtimeHelper.get(), callGuard);
runtimeHelper->valueUnpacker =
std::make_unique<CoreFunction>(runtimeHelper.get(), valueUnpacker);
}
NativeReanimatedModule::~NativeReanimatedModule() {
if (runtimeHelper) {
runtimeHelper->callGuard = nullptr;
runtimeHelper->valueUnpacker = nullptr;
// event handler registry and frame callbacks store some JSI values from UI
// runtime, so they have to go away before we tear down the runtime
eventHandlerRegistry.reset();
frameCallbacks.clear();
runtime.reset();
// make sure uiRuntimeDestroyed is set after the runtime is deallocated
runtimeHelper->uiRuntimeDestroyed = true;
}
}
void NativeReanimatedModule::scheduleOnUI(
jsi::Runtime &rt,
const jsi::Value &worklet) {
auto shareableWorklet = extractShareableOrThrow(rt, worklet);
assert(
shareableWorklet->valueType() == Shareable::WorkletType &&
"only worklets can be scheduled to run on UI");
frameCallbacks.push_back([=](double timestamp) {
jsi::Runtime &rt = *runtimeHelper->uiRuntime();
auto workletValue = shareableWorklet->getJSValue(rt);
runtimeHelper->runOnUIGuarded(workletValue);
});
maybeRequestRender();
}
jsi::Value NativeReanimatedModule::makeSynchronizedDataHolder(
jsi::Runtime &rt,
const jsi::Value &initialShareable) {
auto dataHolder = std::make_shared<ShareableSynchronizedDataHolder>(
runtimeHelper, rt, initialShareable);
return dataHolder->getJSValue(rt);
}
void NativeReanimatedModule::updateDataSynchronously(
jsi::Runtime &rt,
const jsi::Value &synchronizedDataHolderRef,
const jsi::Value &newData) {
auto dataHolder = extractShareableOrThrow<ShareableSynchronizedDataHolder>(
rt, synchronizedDataHolderRef);
dataHolder->set(rt, newData);
}
jsi::Value NativeReanimatedModule::getDataSynchronously(
jsi::Runtime &rt,
const jsi::Value &synchronizedDataHolderRef) {
auto dataHolder = extractShareableOrThrow<ShareableSynchronizedDataHolder>(
rt, synchronizedDataHolderRef);
return dataHolder->get(rt);
}
jsi::Value NativeReanimatedModule::makeShareableClone(
jsi::Runtime &rt,
const jsi::Value &value) {
std::shared_ptr<Shareable> shareable;
if (value.isObject()) {
auto object = value.asObject(rt);
if (!object.getProperty(rt, "__workletHash").isUndefined()) {
shareable = std::make_shared<ShareableWorklet>(runtimeHelper, rt, object);
} else if (!object.getProperty(rt, "__init").isUndefined()) {
shareable = std::make_shared<ShareableHandle>(runtimeHelper, rt, object);
} else if (object.isFunction(rt)) {
shareable = std::make_shared<ShareableRemoteFunction>(
runtimeHelper, rt, object.asFunction(rt));
} else if (object.isArray(rt)) {
shareable = std::make_shared<ShareableArray>(
runtimeHelper, rt, object.asArray(rt));
#ifdef RCT_NEW_ARCH_ENABLED
} else if (object.isHostObject<ShadowNodeWrapper>(rt)) {
shareable = std::make_shared<ShareableShadowNodeWrapper>(
runtimeHelper, rt, object);
#endif
} else {
shareable = std::make_shared<ShareableObject>(runtimeHelper, rt, object);
}
} else if (value.isString()) {
shareable = std::make_shared<ShareableString>(rt, value.asString(rt));
} else if (value.isUndefined()) {
shareable = std::make_shared<ShareableScalar>();
} else if (value.isNull()) {
shareable = std::make_shared<ShareableScalar>(nullptr);
} else if (value.isBool()) {
shareable = std::make_shared<ShareableScalar>(value.getBool());
} else if (value.isNumber()) {
shareable = std::make_shared<ShareableScalar>(value.getNumber());
} else {
throw std::runtime_error("attempted to convert an unsupported value type");
}
return ShareableJSRef::newHostObject(rt, shareable);
}
jsi::Value NativeReanimatedModule::registerEventHandler(
jsi::Runtime &rt,
const jsi::Value &eventHash,
const jsi::Value &worklet) {
static unsigned long EVENT_HANDLER_ID = 1;
unsigned long newRegistrationId = EVENT_HANDLER_ID++;
auto eventName = eventHash.asString(rt).utf8(rt);
auto handlerShareable = extractShareableOrThrow(rt, worklet);
scheduler->scheduleOnUI([=] {
jsi::Runtime &rt = *runtimeHelper->uiRuntime();
auto handlerFunction =
handlerShareable->getJSValue(rt).asObject(rt).asFunction(rt);
auto handler = std::make_shared<WorkletEventHandler>(
newRegistrationId, eventName, std::move(handlerFunction));
eventHandlerRegistry->registerEventHandler(handler);
});
return jsi::Value(static_cast<double>(newRegistrationId));
}
void NativeReanimatedModule::unregisterEventHandler(
jsi::Runtime &rt,
const jsi::Value ®istrationId) {
unsigned long id = registrationId.asNumber();
scheduler->scheduleOnUI(
[=] { eventHandlerRegistry->unregisterEventHandler(id); });
}
jsi::Value NativeReanimatedModule::getViewProp(
jsi::Runtime &rt,
const jsi::Value &viewTag,
const jsi::Value &propName,
const jsi::Value &callback) {
const int viewTagInt = static_cast<int>(viewTag.asNumber());
std::string propNameStr = propName.asString(rt).utf8(rt);
jsi::Function fun = callback.getObject(rt).asFunction(rt);
std::shared_ptr<jsi::Function> funPtr =
std::make_shared<jsi::Function>(std::move(fun));
scheduler->scheduleOnUI([&rt, viewTagInt, funPtr, this, propNameStr]() {
const jsi::String propNameValue =
jsi::String::createFromUtf8(rt, propNameStr);
jsi::Value result = propObtainer(rt, viewTagInt, propNameValue);
std::string resultStr = result.asString(rt).utf8(rt);
scheduler->scheduleOnJS([&rt, resultStr, funPtr]() {
const jsi::String resultValue =
jsi::String::createFromUtf8(rt, resultStr);
funPtr->call(rt, resultValue);
});
});
return jsi::Value::undefined();
}
jsi::Value NativeReanimatedModule::enableLayoutAnimations(
jsi::Runtime &rt,
const jsi::Value &config) {
FeaturesConfig::setLayoutAnimationEnabled(config.getBool());
return jsi::Value::undefined();
}
jsi::Value NativeReanimatedModule::configureProps(
jsi::Runtime &rt,
const jsi::Value &uiProps,
const jsi::Value &nativeProps) {
#ifdef RCT_NEW_ARCH_ENABLED
jsi::Array array = nativeProps.asObject(rt).asArray(rt);
for (int i = 0; i < array.size(rt); ++i) {
std::string name = array.getValueAtIndex(rt, i).asString(rt).utf8(rt);
nativePropNames_.insert(name);
}
#else
configurePropsPlatformFunction(rt, uiProps, nativeProps);
#endif // RCT_NEW_ARCH_ENABLED
return jsi::Value::undefined();
}
jsi::Value NativeReanimatedModule::configureLayoutAnimation(
jsi::Runtime &rt,
const jsi::Value &viewTag,
const jsi::Value &type,
const jsi::Value &config) {
layoutAnimationsManager_.configureAnimation(
viewTag.asNumber(),
type.asString(rt).utf8(rt),
extractShareableOrThrow(rt, config));
return jsi::Value::undefined();
}
void NativeReanimatedModule::onEvent(
std::string eventName,
#ifdef RCT_NEW_ARCH_ENABLED
jsi::Value &&payload
#else
std::string eventAsString
#endif
/**/) {
try {
#ifdef RCT_NEW_ARCH_ENABLED
eventHandlerRegistry->processEvent(*runtime, eventName, payload);
#else
eventHandlerRegistry->processEvent(*runtime, eventName, eventAsString);
#endif
} catch (std::exception &e) {
std::string str = e.what();
this->errorHandler->setError(str);
this->errorHandler->raise();
} catch (...) {
std::string str = "OnEvent error";
this->errorHandler->setError(str);
this->errorHandler->raise();
}
}
bool NativeReanimatedModule::isAnyHandlerWaitingForEvent(
std::string eventName) {
return eventHandlerRegistry->isAnyHandlerWaitingForEvent(eventName);
}
void NativeReanimatedModule::maybeRequestRender() {
if (!renderRequested) {
renderRequested = true;
requestRender(onRenderCallback, *this->runtime);
}
}
void NativeReanimatedModule::onRender(double timestampMs) {
try {
std::vector<FrameCallback> callbacks = frameCallbacks;
frameCallbacks.clear();
for (auto &callback : callbacks) {
callback(timestampMs);
}
} catch (std::exception &e) {
std::string str = e.what();
this->errorHandler->setError(str);
this->errorHandler->raise();
} catch (...) {
std::string str = "OnRender error";
this->errorHandler->setError(str);
this->errorHandler->raise();
}
}
jsi::Value NativeReanimatedModule::registerSensor(
jsi::Runtime &rt,
const jsi::Value &sensorType,
const jsi::Value &interval,
const jsi::Value &sensorDataHandler) {
return animatedSensorModule.registerSensor(
rt, runtimeHelper, sensorType, interval, sensorDataHandler);
}
void NativeReanimatedModule::unregisterSensor(
jsi::Runtime &rt,
const jsi::Value &sensorId) {
animatedSensorModule.unregisterSensor(sensorId);
}
#ifdef RCT_NEW_ARCH_ENABLED
bool NativeReanimatedModule::isThereAnyLayoutProp(
jsi::Runtime &rt,
const jsi::Value &props) {
const jsi::Array propNames = props.asObject(rt).getPropertyNames(rt);
for (size_t i = 0; i < propNames.size(rt); ++i) {
const std::string propName =
propNames.getValueAtIndex(rt, i).asString(rt).utf8(rt);
bool isLayoutProp =
nativePropNames_.find(propName) != nativePropNames_.end();
if (isLayoutProp) {
return true;
}
}
return false;
}
bool NativeReanimatedModule::handleEvent(
const std::string &eventName,
jsi::Value &&payload,
double currentTime) {
jsi::Runtime &rt = *runtime.get();
jsi::Object global = rt.global();
jsi::String eventTimestampName =
jsi::String::createFromAscii(rt, "_eventTimestamp");
global.setProperty(rt, eventTimestampName, currentTime);
onEvent(eventName, std::move(payload));
global.setProperty(rt, eventTimestampName, jsi::Value::undefined());
// TODO: return true if Reanimated successfully handled the event
// to avoid sending it to JavaScript
return false;
}
bool NativeReanimatedModule::handleRawEvent(
const RawEvent &rawEvent,
double currentTime) {
const EventTarget *eventTarget = rawEvent.eventTarget.get();
if (eventTarget == nullptr) {
// after app reload scrollview is unmounted and its content offset is set to
// 0 and view is thrown into recycle pool setting content offset triggers
// scroll event eventTarget is null though, because it's unmounting we can
// just ignore this event, because it's an event on unmounted component
return false;
}
const std::string &type = rawEvent.type;
const ValueFactory &payloadFactory = rawEvent.payloadFactory;
int tag = eventTarget->getTag();
std::string eventType = type;
if (eventType.rfind("top", 0) == 0) {
eventType = "on" + eventType.substr(3);
}
std::string eventName = std::to_string(tag) + eventType;
jsi::Runtime &rt = *runtime.get();
jsi::Value payload = payloadFactory(rt);
return handleEvent(eventName, std::move(payload), currentTime);
}
void NativeReanimatedModule::updateProps(
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue,
const jsi::Value &props) {
ShadowNode::Shared shadowNode = shadowNodeFromValue(rt, shadowNodeValue);
// TODO: support multiple surfaces
surfaceId_ = shadowNode->getSurfaceId();
if (isThereAnyLayoutProp(rt, props)) {
operationsInBatch_.emplace_back(
shadowNode, std::make_unique<jsi::Value>(rt, props));
} else {
// TODO: batch with layout props changes?
Tag tag = shadowNode->getTag();
synchronouslyUpdateUIPropsFunction(rt, tag, props);
}
}
void NativeReanimatedModule::performOperations() {
if (operationsInBatch_.empty()) {
return;
}
auto copiedOperationsQueue = std::move(operationsInBatch_);
operationsInBatch_ =
std::vector<std::pair<ShadowNode::Shared, std::unique_ptr<jsi::Value>>>();
auto copiedTagsToRemove = std::move(tagsToRemove_);
tagsToRemove_ = std::vector<Tag>();
react_native_assert(uiManager_ != nullptr);
const auto &shadowTreeRegistry = uiManager_->getShadowTreeRegistry();
jsi::Runtime &rt = *runtime.get();
shadowTreeRegistry.visit(surfaceId_, [&](ShadowTree const &shadowTree) {
shadowTree.commit([&](RootShadowNode const &oldRootShadowNode) {
auto rootNode = oldRootShadowNode.ShadowNode::clone(ShadowNodeFragment{});
ShadowTreeCloner shadowTreeCloner{
newestShadowNodesRegistry_, uiManager_, surfaceId_};
{
// lock once due to performance reasons
auto lock = newestShadowNodesRegistry_->createLock();
for (const auto &pair : copiedOperationsQueue) {
const ShadowNodeFamily &family = pair.first->getFamily();
react_native_assert(family.getSurfaceId() == surfaceId_);
auto newRootNode = shadowTreeCloner.cloneWithNewProps(
rootNode, family, RawProps(rt, *pair.second));
if (newRootNode == nullptr) {
// this happens when React removed the component but Reanimated
// still tries to animate it, let's skip update for this specific
// component
continue;
}
rootNode = newRootNode;
}
// remove ShadowNodes and its ancestors from NewestShadowNodesRegistry
for (auto tag : copiedTagsToRemove) {
newestShadowNodesRegistry_->remove(tag);
}
}
shadowTreeCloner.updateYogaChildren();
return std::static_pointer_cast<RootShadowNode>(rootNode);
});
});
}
void NativeReanimatedModule::removeShadowNodeFromRegistry(
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue) {
auto shadowNode = shadowNodeFromValue(rt, shadowNodeValue);
tagsToRemove_.push_back(shadowNode->getTag());
}
void NativeReanimatedModule::dispatchCommand(
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue,
const jsi::Value &commandNameValue,
const jsi::Value &argsValue) {
ShadowNode::Shared shadowNode = shadowNodeFromValue(rt, shadowNodeValue);
std::string commandName = stringFromValue(rt, commandNameValue);
folly::dynamic args = commandArgsFromValue(rt, argsValue);
// TODO: use uiManager_->dispatchCommand once it's public
UIManager_dispatchCommand(uiManager_, shadowNode, commandName, args);
}
jsi::Value NativeReanimatedModule::measure(
jsi::Runtime &rt,
const jsi::Value &shadowNodeValue) {
// based on implementation from UIManagerBinding.cpp
auto shadowNode = shadowNodeFromValue(rt, shadowNodeValue);
// TODO: use uiManager_->getRelativeLayoutMetrics once it's public
// auto layoutMetrics = uiManager_->getRelativeLayoutMetrics(
// *shadowNode, nullptr, {/* .includeTransform = */ true});
auto layoutMetrics = UIManager_getRelativeLayoutMetrics(
uiManager_, *shadowNode, nullptr, {/* .includeTransform = */ true});
if (layoutMetrics == EmptyLayoutMetrics) {
// Originally, in this case React Native returns `{0, 0, 0, 0, 0, 0}`, most
// likely due to the type of measure callback function which accepts just an
// array of numbers (not null). In Reanimated, `measure` returns
// `MeasuredDimensions | null`.
return jsi::Value::null();
}
auto newestCloneOfShadowNode =
uiManager_->getNewestCloneOfShadowNode(*shadowNode);
auto layoutableShadowNode =
traitCast<LayoutableShadowNode const *>(newestCloneOfShadowNode.get());
facebook::react::Point originRelativeToParent = layoutableShadowNode
? layoutableShadowNode->getLayoutMetrics().frame.origin
: facebook::react::Point();
auto frame = layoutMetrics.frame;
jsi::Object result(rt);
result.setProperty(
rt, "x", jsi::Value(static_cast<double>(originRelativeToParent.x)));
result.setProperty(
rt, "y", jsi::Value(static_cast<double>(originRelativeToParent.y)));
result.setProperty(
rt, "width", jsi::Value(static_cast<double>(frame.size.width)));
result.setProperty(
rt, "height", jsi::Value(static_cast<double>(frame.size.height)));
result.setProperty(
rt, "pageX", jsi::Value(static_cast<double>(frame.origin.x)));
result.setProperty(
rt, "pageY", jsi::Value(static_cast<double>(frame.origin.y)));
return result;
}
void NativeReanimatedModule::setUIManager(
std::shared_ptr<UIManager> uiManager) {
uiManager_ = uiManager;
}
void NativeReanimatedModule::setNewestShadowNodesRegistry(
std::shared_ptr<NewestShadowNodesRegistry> newestShadowNodesRegistry) {
newestShadowNodesRegistry_ = newestShadowNodesRegistry;
}
#endif // RCT_NEW_ARCH_ENABLED
jsi::Value NativeReanimatedModule::subscribeForKeyboardEvents(
jsi::Runtime &rt,
const jsi::Value &handlerWorklet) {
auto shareableHandler = extractShareableOrThrow(rt, handlerWorklet);
auto uiRuntime = runtimeHelper->uiRuntime();
return subscribeForKeyboardEventsFunction([=](int keyboardState, int height) {
jsi::Runtime &rt = *uiRuntime;
auto handler = shareableHandler->getJSValue(rt);
handler.asObject(rt).asFunction(rt).call(
rt, jsi::Value(keyboardState), jsi::Value(height));
});
}
void NativeReanimatedModule::unsubscribeFromKeyboardEvents(
jsi::Runtime &rt,
const jsi::Value &listenerId) {
unsubscribeFromKeyboardEventsFunction(listenerId.asNumber());
}
} // namespace reanimated