@datadog/mobile-react-native-navigation 1.2.0 → 1.3.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 (45) hide show
  1. package/README.md +2 -0
  2. package/lib/commonjs/rum/instrumentation/DdRumReactNativeNavigationTracking.js +50 -32
  3. package/lib/commonjs/rum/instrumentation/DdRumReactNativeNavigationTracking.js.map +1 -1
  4. package/lib/module/rum/instrumentation/DdRumReactNativeNavigationTracking.js +51 -30
  5. package/lib/module/rum/instrumentation/DdRumReactNativeNavigationTracking.js.map +1 -1
  6. package/lib/typescript/core/src/DdSdkReactNative.d.ts +7 -3
  7. package/lib/typescript/core/src/DdSdkReactNativeConfiguration.d.ts +22 -0
  8. package/lib/typescript/core/src/foundation.d.ts +2 -4
  9. package/lib/typescript/core/src/index.d.ts +5 -3
  10. package/lib/typescript/core/src/logs/DdLogs.d.ts +14 -0
  11. package/lib/typescript/core/src/logs/eventMapper.d.ts +11 -0
  12. package/lib/typescript/core/src/logs/types.d.ts +54 -0
  13. package/lib/typescript/core/src/nativeModulesTypes.d.ts +1 -1
  14. package/lib/typescript/core/src/rum/DdRum.d.ts +36 -0
  15. package/lib/typescript/core/src/rum/eventMappers/actionEventMapper.d.ts +21 -0
  16. package/lib/typescript/core/src/rum/eventMappers/errorEventMapper.d.ts +21 -0
  17. package/lib/typescript/core/src/rum/eventMappers/resourceEventMapper.d.ts +25 -0
  18. package/lib/typescript/core/src/rum/instrumentation/{DdEventsInterceptor.d.ts → interactionTracking/DdEventsInterceptor.d.ts} +0 -0
  19. package/lib/typescript/core/src/rum/instrumentation/{DdRumUserInteractionTracking.d.ts → interactionTracking/DdRumUserInteractionTracking.d.ts} +0 -0
  20. package/lib/typescript/core/src/rum/instrumentation/{EventsInterceptor.d.ts → interactionTracking/EventsInterceptor.d.ts} +0 -0
  21. package/lib/typescript/core/src/rum/instrumentation/{NoOpEventsInterceptor.d.ts → interactionTracking/NoOpEventsInterceptor.d.ts} +0 -0
  22. package/lib/typescript/core/src/rum/instrumentation/{ShallowObjectEqualityChecker.d.ts → interactionTracking/ShallowObjectEqualityChecker.d.ts} +0 -0
  23. package/lib/typescript/core/src/rum/instrumentation/{getJsxRuntime.d.ts → interactionTracking/getJsxRuntime.d.ts} +0 -0
  24. package/lib/typescript/core/src/rum/instrumentation/resourceTracking/domain/interfaces/RumResource.d.ts +3 -1
  25. package/lib/typescript/core/src/rum/types.d.ts +110 -0
  26. package/lib/typescript/core/src/sdk/AttributesSingleton/AttributesSingleton.d.ts +12 -0
  27. package/lib/typescript/core/src/sdk/AttributesSingleton/types.d.ts +3 -0
  28. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/Buffer/BoundedBuffer.d.ts +0 -0
  29. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/Buffer/BufferSingleton.d.ts +0 -0
  30. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/Buffer/DatadogBuffer.d.ts +0 -0
  31. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/Buffer/PassThroughBuffer.d.ts +0 -0
  32. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/Buffer/bufferNativeCall.d.ts +0 -0
  33. package/lib/typescript/core/src/{DatadogProvider → sdk/DatadogProvider}/DatadogProvider.d.ts +2 -2
  34. package/lib/typescript/core/src/sdk/EventMappers/EventMapper.d.ts +24 -0
  35. package/lib/typescript/core/src/sdk/EventMappers/utils/deepClone.d.ts +10 -0
  36. package/lib/typescript/core/src/sdk/UserInfoSingleton/UserInfoSingleton.d.ts +12 -0
  37. package/lib/typescript/core/src/sdk/UserInfoSingleton/types.d.ts +6 -0
  38. package/lib/typescript/core/src/types.d.ts +0 -139
  39. package/lib/typescript/core/src/version.d.ts +1 -1
  40. package/lib/typescript/react-native-navigation/src/rum/instrumentation/DdRumReactNativeNavigationTracking.d.ts +5 -3
  41. package/package.json +6 -4
  42. package/src/__tests__/rum/instrumentation/DdRumReactNativeNavigationTracking.test.tsx +182 -109
  43. package/src/__tests__/rum/instrumentation/__utils__/AppStateMock.ts +75 -0
  44. package/src/__tests__/rum/instrumentation/__utils__/AppStateMockLegacy.ts +61 -0
  45. package/src/rum/instrumentation/DdRumReactNativeNavigationTracking.tsx +87 -54
@@ -1,3 +1,4 @@
1
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
1
2
  /*
2
3
  * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
4
  * This product includes software developed at Datadog (https://www.datadoghq.com/).
@@ -5,12 +6,22 @@
5
6
  */
6
7
 
7
8
  import { DdRum } from '@datadog/mobile-react-native';
9
+ import { fireEvent, render, waitFor } from '@testing-library/react-native';
10
+ import {
11
+ ApplicationMock,
12
+ mockNativeComponents
13
+ } from 'react-native-navigation/Mock';
8
14
  import type { ComponentDidAppearEvent } from 'react-native-navigation';
15
+ import { Navigation } from 'react-native-navigation';
16
+ import { AppState, Button } from 'react-native';
9
17
  import React from 'react';
10
18
 
11
19
  import type { ViewNamePredicate } from '../../../rum/instrumentation/DdRumReactNativeNavigationTracking';
12
20
  import { DdRumReactNativeNavigationTracking } from '../../../rum/instrumentation/DdRumReactNativeNavigationTracking';
13
21
 
22
+ import { AppStateMockLegacy } from './__utils__/AppStateMockLegacy';
23
+ import { AppStateMock } from './__utils__/AppStateMock';
24
+
14
25
  jest.mock('@datadog/mobile-react-native', () => {
15
26
  return {
16
27
  DdRum: {
@@ -19,156 +30,218 @@ jest.mock('@datadog/mobile-react-native', () => {
19
30
  }
20
31
  };
21
32
  });
22
- jest.useFakeTimers();
23
-
24
- const mockRegisterComponentListener = jest.fn().mockImplementation(() => {});
25
- jest.mock('react-native-navigation', () => {
26
- return {
27
- Navigation: {
28
- events: jest.fn().mockImplementation(() => {
29
- return {
30
- registerComponentListener: mockRegisterComponentListener
31
- };
32
- })
33
- }
34
- };
35
- });
36
33
 
37
- let originalCreateMethod: typeof React.createElement;
34
+ // TODO: remove this when available in jest 29
35
+ function mocked<T extends (...args: any[]) => any>(item: T) {
36
+ return (item as unknown) as jest.MockedFunction<typeof item>;
37
+ }
38
+
39
+ const startPlayground = () => {
40
+ Navigation.registerComponent('Home', () => HomeScreen);
41
+ Navigation.registerComponent('About', () => AboutScreen);
42
+ Navigation.events().registerAppLaunchedListener(async () => {
43
+ Navigation.setRoot({
44
+ root: {
45
+ stack: {
46
+ children: [{ component: { name: 'Home' } }]
47
+ }
48
+ }
49
+ });
50
+ });
51
+ };
52
+
53
+ const HomeScreen = props => {
54
+ return (
55
+ <>
56
+ <Button
57
+ title="Go to About"
58
+ onPress={() => {
59
+ Navigation.push(props.componentId, {
60
+ component: { name: 'About' }
61
+ });
62
+ }}
63
+ />
64
+ </>
65
+ );
66
+ };
67
+
68
+ const AboutScreen = props => {
69
+ return (
70
+ <>
71
+ <Button
72
+ title="Go to Home"
73
+ onPress={() =>
74
+ Navigation.push(props.componentId, {
75
+ component: { name: 'Home' }
76
+ })
77
+ }
78
+ />
79
+ </>
80
+ );
81
+ };
38
82
 
39
83
  beforeEach(() => {
40
- jest.setTimeout(20000);
41
- DdRum.startView.mockClear();
42
- DdRum.stopView.mockClear();
43
- mockRegisterComponentListener.mockClear();
44
-
45
- DdRumReactNativeNavigationTracking['trackedComponentIds'] = [];
46
- DdRumReactNativeNavigationTracking['isTracking'] = false;
47
- originalCreateMethod = React.createElement;
84
+ jest.clearAllMocks();
85
+ mockNativeComponents();
48
86
  });
49
87
 
50
88
  afterEach(() => {
51
- React.createElement = originalCreateMethod;
89
+ DdRumReactNativeNavigationTracking.stopTracking();
52
90
  });
53
91
 
54
92
  // Unit tests
55
93
 
56
- it('M not register W props are missing + startTracking()', async () => {
94
+ it('M send a RUM ViewEvent W startTracking() for the first view', async () => {
57
95
  // GIVEN
58
96
  DdRumReactNativeNavigationTracking.startTracking();
59
97
 
60
98
  // WHEN
61
- React.createElement('View', null);
99
+ render(<ApplicationMock entryPoint={() => startPlayground()} />);
62
100
 
63
101
  // THEN
64
- expect(mockRegisterComponentListener).toBeCalledTimes(0);
102
+ await waitFor(() =>
103
+ expect(DdRum.startView).toHaveBeenCalledWith(expect.any(String), 'Home')
104
+ );
65
105
  });
66
106
 
67
- it('M not register W componentId is missing + startTracking()', async () => {
107
+ it('M send a RUM ViewEvent W startTracking() componentDidAppear { custom viewPredicate }', async () => {
68
108
  // GIVEN
69
- DdRumReactNativeNavigationTracking.startTracking();
109
+ const predicate: ViewNamePredicate = function (
110
+ _event: ComponentDidAppearEvent,
111
+ _trackedName: string
112
+ ) {
113
+ if (_trackedName === 'About') {
114
+ return 'customViewName';
115
+ }
116
+ return _trackedName;
117
+ };
118
+ DdRumReactNativeNavigationTracking.startTracking(predicate);
70
119
 
71
120
  // WHEN
72
- React.createElement('View', { foo: 'bar' });
121
+ const { findByText } = render(
122
+ <ApplicationMock entryPoint={() => startPlayground()} />
123
+ );
124
+ const button = await findByText('Go to About');
125
+ await fireEvent(button, 'press');
73
126
 
74
127
  // THEN
75
- expect(mockRegisterComponentListener).toBeCalledTimes(0);
128
+ await waitFor(() => expect(DdRum.startView).toHaveBeenCalledTimes(2));
129
+ expect(DdRum.startView).toHaveBeenCalledWith(expect.any(String), 'Home');
130
+ expect(DdRum.startView).toHaveBeenCalledWith(
131
+ expect.any(String),
132
+ 'customViewName'
133
+ );
76
134
  });
77
135
 
78
- it('M register only once W startTracking()', async () => {
136
+ it('M not send a RUM ViewEvent W startTracking() componentDidAppear { viewPredicate returns null }', async () => {
79
137
  // GIVEN
80
- const componentId = 'component42';
81
- DdRumReactNativeNavigationTracking.startTracking();
138
+ let viewDropped = false;
139
+ const predicate: ViewNamePredicate = function (
140
+ _event: ComponentDidAppearEvent,
141
+ _trackedName: string
142
+ ) {
143
+ if (_trackedName === 'About') {
144
+ viewDropped = true;
145
+ return null;
146
+ }
147
+ return _trackedName;
148
+ };
149
+ DdRumReactNativeNavigationTracking.startTracking(predicate);
82
150
 
83
151
  // WHEN
84
- React.createElement('View', {
85
- componentId
86
- });
87
- React.createElement('View', {
88
- componentId,
89
- something: 'else'
90
- });
152
+ const { findByText } = render(
153
+ <ApplicationMock entryPoint={() => startPlayground()} />
154
+ );
155
+ const button = await findByText('Go to About');
156
+ await fireEvent(button, 'press');
157
+ await waitFor(() => viewDropped);
91
158
 
92
159
  // THEN
93
- expect(mockRegisterComponentListener.mock.calls.length).toBe(1);
160
+ expect(DdRum.startView).toHaveBeenCalledTimes(1);
161
+ expect(DdRum.startView).toHaveBeenCalledWith(expect.any(String), 'Home');
94
162
  });
95
163
 
96
- it('M restore original createElement method W stopTracking()', async () => {
97
- // GIVEN
98
- const componentId = 'component42';
99
- DdRumReactNativeNavigationTracking.startTracking();
100
-
101
- // WHEN
102
- DdRumReactNativeNavigationTracking.stopTracking();
103
- React.createElement('View', {
104
- componentId
164
+ describe.each([
165
+ ['react-native 0.63-0.64', AppStateMockLegacy],
166
+ ['react-native 0.65+', AppStateMock]
167
+ ])('AppState listener on %s', (reactNativeVersion, AppStateMockVersion) => {
168
+ let appStateMock;
169
+ beforeEach(() => {
170
+ appStateMock = new AppStateMockVersion();
171
+ mocked(AppState.addEventListener).mockImplementation(
172
+ // @ts-ignore
173
+ appStateMock.addEventListener
174
+ );
175
+ // @ts-ignore
176
+ if (appStateMock.removeEventListener) {
177
+ AppState.removeEventListener = jest.fn(
178
+ appStateMock.removeEventListener
179
+ );
180
+ }
181
+ });
182
+ it('registers and unregisters AppState', async () => {
183
+ // GIVEN
184
+ DdRumReactNativeNavigationTracking.startTracking();
185
+ render(<ApplicationMock entryPoint={() => startPlayground()} />);
186
+ await waitFor(() =>
187
+ expect(DdRum.startView).toHaveBeenCalledWith(
188
+ expect.any(String),
189
+ 'Home'
190
+ )
191
+ );
192
+
193
+ // WHEN
194
+ appStateMock.changeValue('background');
195
+
196
+ // THEN
197
+ expect(appStateMock.listeners.change).toHaveLength(1);
198
+ expect(DdRum.stopView).toHaveBeenCalledTimes(1);
105
199
  });
106
200
 
107
- // THEN
108
- expect(mockRegisterComponentListener.mock.calls.length).toBe(0);
109
- });
201
+ it('does not log AppState changes when tracking is stopped', async () => {
202
+ // GIVEN
203
+ DdRumReactNativeNavigationTracking.startTracking();
204
+ DdRumReactNativeNavigationTracking.stopTracking();
110
205
 
111
- it('M send a RUM ViewEvent W startTracking() componentDidAppear', async () => {
112
- // GIVEN
113
- const componentId = 'component42';
114
- DdRumReactNativeNavigationTracking.startTracking();
206
+ // WHEN
207
+ appStateMock.changeValue('background');
115
208
 
116
- // WHEN
117
- React.createElement('View', {
118
- componentId
209
+ // THEN
210
+ expect(DdRum.stopView).not.toHaveBeenCalled();
119
211
  });
120
- const listener = mockRegisterComponentListener.mock.calls[0][0];
121
- const componentName = 'some-name';
122
- listener.componentDidAppear({ componentName });
123
-
124
- // THEN
125
- expect(DdRum.startView.mock.calls.length).toBe(1);
126
- expect(DdRum.startView.mock.calls[0][0]).toBe(componentId);
127
- expect(DdRum.startView.mock.calls[0][1]).toBe(componentName);
128
- expect(DdRum.startView.mock.calls[0][2]).toBeUndefined();
129
- });
130
212
 
131
- it('M send a RUM ViewEvent W startTracking() componentDidAppear { custom viewPredicate }', async () => {
132
- // GIVEN
133
- const componentId = 'component42';
134
- const customViewName = 'custom_view_name';
135
- const predicate: ViewNamePredicate = function (
136
- _event: ComponentDidAppearEvent,
137
- _trackedName: string
138
- ) {
139
- return customViewName;
140
- };
141
- DdRumReactNativeNavigationTracking.startTracking(predicate);
142
-
143
- // WHEN
144
- React.createElement('View', {
145
- componentId
213
+ it('starts last view when app goes into foreground', async () => {
214
+ // GIVEN
215
+ DdRumReactNativeNavigationTracking.startTracking();
216
+ const { findByText } = render(
217
+ <ApplicationMock entryPoint={() => startPlayground()} />
218
+ );
219
+ const button = await findByText('Go to About');
220
+ await fireEvent(button, 'press');
221
+ await waitFor(() => expect(DdRum.startView).toHaveBeenCalledTimes(2));
222
+
223
+ // WHEN
224
+ appStateMock.changeValue('background');
225
+ appStateMock.changeValue('active');
226
+
227
+ // THEN
228
+ expect(DdRum.stopView).toHaveBeenCalledTimes(1);
229
+ expect(DdRum.startView).toHaveBeenCalledTimes(3);
230
+ expect(DdRum.startView).toHaveBeenNthCalledWith(
231
+ 3,
232
+ expect.any(String),
233
+ 'About'
234
+ );
146
235
  });
147
- const listener = mockRegisterComponentListener.mock.calls[0][0];
148
- const componentName = 'some-name';
149
- listener.componentDidAppear({ componentName });
150
236
 
151
- // THEN
152
- expect(DdRum.startView.mock.calls.length).toBe(1);
153
- expect(DdRum.startView.mock.calls[0][0]).toBe(componentId);
154
- expect(DdRum.startView.mock.calls[0][1]).toBe(customViewName);
155
- expect(DdRum.startView.mock.calls[0][2]).toBeUndefined();
156
- });
237
+ it('does not stop view when no navigator attached', async () => {
238
+ // GIVEN
239
+ DdRumReactNativeNavigationTracking.startTracking();
157
240
 
158
- it('M send a RUM ViewEvent W startTracking() componentDidDisappear', async () => {
159
- // GIVEN
160
- const componentId = 'component42';
161
- DdRumReactNativeNavigationTracking.startTracking();
241
+ // WHEN
242
+ appStateMock.changeValue('background');
162
243
 
163
- // WHEN
164
- React.createElement('View', {
165
- componentId
244
+ // THEN
245
+ expect(DdRum.stopView).not.toHaveBeenCalled();
166
246
  });
167
- const listener = mockRegisterComponentListener.mock.calls[0][0];
168
- listener.componentDidDisappear();
169
-
170
- // THEN
171
- expect(DdRum.stopView.mock.calls.length).toBe(1);
172
- expect(DdRum.stopView.mock.calls[0][0]).toBe(componentId);
173
- expect(DdRum.stopView.mock.calls[0][1]).toBeUndefined();
174
247
  });
@@ -0,0 +1,75 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import type {
8
+ AppStateEvent,
9
+ AppStateStatus,
10
+ NativeEventSubscription
11
+ } from 'react-native';
12
+
13
+ type handler = (type: AppStateStatus) => void;
14
+
15
+ export class AppStateMock {
16
+ private listeners: {
17
+ [eventType: string]: {
18
+ callback: handler;
19
+ subscription: NativeEventSubscription;
20
+ }[];
21
+ } = {};
22
+
23
+ addEventListener = (type: AppStateEvent, callback: handler) => {
24
+ if (!this.listeners[type]) {
25
+ this.listeners[type] = [];
26
+ }
27
+ const subscription = {
28
+ remove: () => this.removeListeners(type, callback)
29
+ };
30
+ this.listeners[type].push({
31
+ callback,
32
+ subscription
33
+ });
34
+
35
+ return subscription;
36
+ };
37
+
38
+ private removeListeners = (type: string, callback: handler) => {
39
+ if (!this.listeners[type]) {
40
+ return;
41
+ }
42
+ const callbackIndex = this.listeners[type].findIndex(
43
+ handler => handler.callback === callback
44
+ );
45
+ if (callbackIndex === -1) {
46
+ return;
47
+ }
48
+ this.listeners[type] = [
49
+ ...this.listeners[type].slice(0, callbackIndex),
50
+ ...this.listeners[type].slice(
51
+ callbackIndex + 1,
52
+ this.listeners[type].length
53
+ )
54
+ ];
55
+ };
56
+
57
+ changeValue = (value: AppStateStatus) => {
58
+ if (!this.listeners.change) {
59
+ return;
60
+ }
61
+ this.listeners.change.forEach(handler => {
62
+ try {
63
+ handler.callback(value);
64
+ } catch (e) {
65
+ console.warn(
66
+ `Failure while executing callback for value ${value}`
67
+ );
68
+ }
69
+ });
70
+ };
71
+
72
+ removeAllListeners = () => {
73
+ this.listeners = {};
74
+ };
75
+ }
@@ -0,0 +1,61 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import type { AppStateEvent, AppStateStatus } from 'react-native';
8
+
9
+ type handler = (type: AppStateStatus) => void;
10
+
11
+ /**
12
+ * This is a mock of legacy implementation of AppState (up until RN 0.65).
13
+ * In the new version, removeEventListener has been deprecated and addEventListener
14
+ * now returns a subscription.
15
+ */
16
+ export class AppStateMockLegacy {
17
+ private listeners: { [eventType: string]: handler[] } = {};
18
+
19
+ addEventListener = (type: AppStateEvent, callback: handler) => {
20
+ if (!this.listeners[type]) {
21
+ this.listeners[type] = [];
22
+ }
23
+ this.listeners[type].push(callback);
24
+ };
25
+
26
+ removeEventListener = (type: string, callback: handler) => {
27
+ if (!this.listeners[type]) {
28
+ return;
29
+ }
30
+ const callbackIndex = this.listeners[type].indexOf(callback);
31
+ if (callbackIndex === -1) {
32
+ return;
33
+ }
34
+ this.listeners[type] = [
35
+ ...this.listeners[type].slice(0, callbackIndex),
36
+ ...this.listeners[type].slice(
37
+ callbackIndex + 1,
38
+ this.listeners[type].length
39
+ )
40
+ ];
41
+ };
42
+
43
+ changeValue = (value: AppStateStatus) => {
44
+ if (!this.listeners.change) {
45
+ return;
46
+ }
47
+ this.listeners.change.forEach(callback => {
48
+ try {
49
+ callback(value);
50
+ } catch (e) {
51
+ console.warn(
52
+ `Failure while executing callback for value ${value}`
53
+ );
54
+ }
55
+ });
56
+ };
57
+
58
+ removeAllListeners = () => {
59
+ this.listeners = {};
60
+ };
61
+ }
@@ -4,25 +4,46 @@
4
4
  * Copyright 2016-Present Datadog, Inc.
5
5
  */
6
6
 
7
- import { DdRum } from '@datadog/mobile-react-native';
7
+ import { DdRum, InternalLog, SdkVerbosity } from '@datadog/mobile-react-native';
8
8
  import type { ComponentDidAppearEvent } from 'react-native-navigation';
9
9
  import { Navigation } from 'react-native-navigation';
10
- import React from 'react';
10
+ import type {
11
+ AppStateStatus,
12
+ EmitterSubscription,
13
+ NativeEventSubscription
14
+ } from 'react-native';
15
+ import { AppState } from 'react-native';
11
16
 
12
17
  export type ViewNamePredicate = (
13
18
  event: ComponentDidAppearEvent,
14
19
  trackedName: string
15
- ) => string;
20
+ ) => string | null;
21
+
22
+ // AppStateStatus can have values:
23
+ // 'active' - The app is running in the foreground
24
+ // 'background' - The app is running in the background. The user is either in another app or on the home screen
25
+ // 'inactive' [iOS] - This is a transition state that currently never happens for typical React Native apps.
26
+ // 'unknown' [iOS] - Initial value until the current app state is determined
27
+ // 'extension' [iOS] - The app is running as an app extension
28
+ declare type AppStateListener = (appStateStatus: AppStateStatus) => void | null;
16
29
 
17
30
  /**
18
31
  * Provides RUM integration for the [React Native Navigation](https://wix.github.io/react-native-navigation) API.
19
32
  */
20
33
  export class DdRumReactNativeNavigationTracking {
21
34
  private static isTracking = false;
22
- private static trackedComponentIds: Array<any> = [];
23
- private static originalCreateElement: any = undefined;
35
+ private static eventSubscription:
36
+ | EmitterSubscription
37
+ | undefined = undefined;
38
+ private static appStateSubscription?: NativeEventSubscription;
24
39
 
25
40
  private static viewNamePredicate: ViewNamePredicate;
41
+ private static lastView?:
42
+ | {
43
+ key: string;
44
+ name: string;
45
+ }
46
+ | 'tracking_not_started' = 'tracking_not_started';
26
47
 
27
48
  /**
28
49
  * Starts tracking the Navigation and sends a RUM View event every time a root View component appear/disappear.
@@ -39,49 +60,28 @@ export class DdRumReactNativeNavigationTracking {
39
60
  if (DdRumReactNativeNavigationTracking.isTracking) {
40
61
  return;
41
62
  }
42
- const original = React.createElement;
43
- DdRumReactNativeNavigationTracking.originalCreateElement = original;
44
- React.createElement = (
45
- element: any,
46
- props: any,
47
- ...children: any
48
- ): any => {
49
- if (
50
- props &&
51
- props.componentId !== undefined &&
52
- props.componentId !== null &&
53
- !DdRumReactNativeNavigationTracking.trackedComponentIds.includes(
54
- props.componentId
55
- )
56
- ) {
57
- const componentId = props.componentId;
58
- Navigation.events().registerComponentListener(
59
- {
60
- componentDidAppear: (
61
- event: ComponentDidAppearEvent
62
- ) => {
63
- const predicate =
64
- DdRumReactNativeNavigationTracking.viewNamePredicate;
65
- const screenName =
66
- predicate(event, event.componentName) ??
67
- event.componentName;
68
- DdRum.startView(componentId, screenName);
69
- },
70
- componentDidDisappear: () => {
71
- DdRum.stopView(componentId);
72
- }
73
- },
74
- componentId
75
- );
76
- DdRumReactNativeNavigationTracking.trackedComponentIds.push(
77
- componentId
78
- );
63
+
64
+ DdRumReactNativeNavigationTracking.eventSubscription = Navigation.events().registerComponentDidAppearListener(
65
+ (event: ComponentDidAppearEvent) => {
66
+ const predicate =
67
+ DdRumReactNativeNavigationTracking.viewNamePredicate;
68
+ const screenName = predicate(event, event.componentName);
69
+ if (screenName !== null) {
70
+ DdRum.startView(event.componentId, screenName);
71
+ DdRumReactNativeNavigationTracking.lastView = {
72
+ key: event.componentId,
73
+ name: screenName
74
+ };
75
+ }
79
76
  }
77
+ );
80
78
 
81
- return original(element, props, ...children);
82
- };
83
79
  DdRumReactNativeNavigationTracking.isTracking = true;
84
80
  DdRumReactNativeNavigationTracking.viewNamePredicate = viewNamePredicate;
81
+ this.appStateSubscription = AppState.addEventListener(
82
+ 'change',
83
+ DdRumReactNativeNavigationTracking.appStateListener
84
+ );
85
85
  }
86
86
 
87
87
  /**
@@ -91,17 +91,21 @@ export class DdRumReactNativeNavigationTracking {
91
91
  if (!DdRumReactNativeNavigationTracking.isTracking) {
92
92
  return;
93
93
  }
94
- if (
95
- DdRumReactNativeNavigationTracking.originalCreateElement !==
96
- undefined
97
- ) {
98
- React.createElement =
99
- DdRumReactNativeNavigationTracking.originalCreateElement;
94
+ if (DdRumReactNativeNavigationTracking.eventSubscription) {
95
+ DdRumReactNativeNavigationTracking.eventSubscription.remove();
100
96
  }
101
- DdRumReactNativeNavigationTracking.trackedComponentIds.splice(
102
- 0,
103
- DdRumReactNativeNavigationTracking.trackedComponentIds.length
104
- );
97
+ // For versions of React Native below 0.65, addEventListener does not return a subscription.
98
+ // We have to call AppState.removeEventListener instead.
99
+ if (this.appStateSubscription) {
100
+ this.appStateSubscription.remove();
101
+ } else {
102
+ AppState.removeEventListener(
103
+ 'change',
104
+ DdRumReactNativeNavigationTracking.appStateListener
105
+ );
106
+ }
107
+
108
+ DdRumReactNativeNavigationTracking.lastView = undefined;
105
109
  DdRumReactNativeNavigationTracking.isTracking = false;
106
110
  DdRumReactNativeNavigationTracking.viewNamePredicate = function (
107
111
  _event: ComponentDidAppearEvent,
@@ -110,4 +114,33 @@ export class DdRumReactNativeNavigationTracking {
110
114
  return trackedName;
111
115
  };
112
116
  }
117
+
118
+ private static appStateListener: AppStateListener = (
119
+ appStateStatus: AppStateStatus
120
+ ) => {
121
+ const lastView = DdRumReactNativeNavigationTracking.lastView;
122
+ if (lastView === undefined) {
123
+ InternalLog.log(
124
+ `We could not determine the route when changing the application state to: ${appStateStatus}. No RUM View event will be sent in this case.`,
125
+ SdkVerbosity.ERROR
126
+ );
127
+ return;
128
+ }
129
+
130
+ if (lastView === 'tracking_not_started') {
131
+ // Do nothing as no view has been tracked already
132
+ return;
133
+ }
134
+
135
+ if (appStateStatus === 'background') {
136
+ DdRum.stopView(lastView.key);
137
+ } else if (
138
+ appStateStatus === 'active' ||
139
+ appStateStatus === undefined
140
+ ) {
141
+ // case when app goes into foreground,
142
+ // in that case navigation listener won't be called
143
+ DdRum.startView(lastView.key, lastView.name);
144
+ }
145
+ };
113
146
  }