1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | #include "EventEmitter.h"
|
9 |
|
10 | #include <folly/dynamic.h>
|
11 | #include <jsi/JSIDynamic.h>
|
12 | #include <jsi/jsi.h>
|
13 | #include <react/debug/SystraceSection.h>
|
14 |
|
15 | #include "RawEvent.h"
|
16 |
|
17 | namespace facebook {
|
18 | namespace react {
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | static std::string normalizeEventType(const std::string &type) {
|
26 | auto prefixedType = type;
|
27 | if (type.find("top", 0) != 0) {
|
28 | prefixedType.insert(0, "top");
|
29 | prefixedType[3] = toupper(prefixedType[3]);
|
30 | }
|
31 | return prefixedType;
|
32 | }
|
33 |
|
34 | std::mutex &EventEmitter::DispatchMutex() {
|
35 | static std::mutex mutex;
|
36 | return mutex;
|
37 | }
|
38 |
|
39 | ValueFactory EventEmitter::defaultPayloadFactory() {
|
40 | static auto payloadFactory =
|
41 | ValueFactory{[](jsi::Runtime &runtime) { return jsi::Object(runtime); }};
|
42 | return payloadFactory;
|
43 | }
|
44 |
|
45 | EventEmitter::EventEmitter(
|
46 | SharedEventTarget eventTarget,
|
47 | Tag tag,
|
48 | WeakEventDispatcher eventDispatcher)
|
49 | : eventTarget_(std::move(eventTarget)),
|
50 | eventDispatcher_(std::move(eventDispatcher)) {}
|
51 |
|
52 | void EventEmitter::dispatchEvent(
|
53 | const std::string &type,
|
54 | const folly::dynamic &payload,
|
55 | const EventPriority &priority) const {
|
56 | dispatchEvent(
|
57 | type,
|
58 | [payload](jsi::Runtime &runtime) {
|
59 | return valueFromDynamic(runtime, payload);
|
60 | },
|
61 | priority);
|
62 | }
|
63 |
|
64 | void EventEmitter::dispatchEvent(
|
65 | const std::string &type,
|
66 | const ValueFactory &payloadFactory,
|
67 | const EventPriority &priority) const {
|
68 | SystraceSection s("EventEmitter::dispatchEvent");
|
69 |
|
70 | auto eventDispatcher = eventDispatcher_.lock();
|
71 | if (!eventDispatcher) {
|
72 | return;
|
73 | }
|
74 |
|
75 | eventDispatcher->dispatchEvent(
|
76 | RawEvent(normalizeEventType(type), payloadFactory, eventTarget_),
|
77 | priority);
|
78 | }
|
79 |
|
80 | void EventEmitter::setEnabled(bool enabled) const {
|
81 | enableCounter_ += enabled ? 1 : -1;
|
82 |
|
83 | bool shouldBeEnabled = enableCounter_ > 0;
|
84 | if (isEnabled_ != shouldBeEnabled) {
|
85 | isEnabled_ = shouldBeEnabled;
|
86 | if (eventTarget_) {
|
87 | eventTarget_->setEnabled(isEnabled_);
|
88 | }
|
89 | }
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | bool shouldBeRetained = enableCounter_ > 0;
|
96 | if (shouldBeRetained != (eventTarget_ != nullptr)) {
|
97 | if (!shouldBeRetained) {
|
98 | eventTarget_.reset();
|
99 | }
|
100 | }
|
101 | }
|
102 |
|
103 | }
|
104 | }
|