浏览代码

[v2] Refactor peek and pop [ready to merge] (#3620)

* Refactor peek and pop

* Rollback some XCode stuff

* Added tests for touchablePreview event

* Also fixing searchbarcancelpressed event
Birkir Rafn Guðjónsson 6 年前
父节点
当前提交
4c519acae8

+ 32
- 0
docs/docs/animations.md 查看文件

@@ -32,4 +32,36 @@ Navigation.push(this.props.componentId, {
32 32
     }
33 33
   }
34 34
 });
35
+```
36
+
37
+## Peek and Pop (iOS 11.4+)
38
+
39
+react-native-navigation supports the [Peek and pop](
40
+https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/Adopting3DTouchOniPhone/#//apple_ref/doc/uid/TP40016543-CH1-SW3) feature in iOS 11.4 and newer.
41
+
42
+This works by passing a ref a componentent you would want to transform into a peek view. We have included a handly component to handle all the touches and ref for you.
43
+
44
+```jsx
45
+const handlePress ({ reactTag }) => {
46
+  Navigation.push(this.props.componentId, {
47
+    component {
48
+      name: 'previewed.screen',
49
+      options: {
50
+        preview: {
51
+          reactTag,
52
+        },
53
+      },
54
+    },
55
+  });
56
+};
57
+
58
+const Button = (
59
+  <Navigation.TouchablePreview
60
+    touchableComponent={TouchableHighlight}
61
+    onPress={handlePress}
62
+    onPressIn={handlePress}
63
+  >
64
+    <Text>My button</Text>
65
+  </Navigation.TouchablePreview>
66
+);
35 67
 ```

+ 16
- 0
docs/docs/events.md 查看文件

@@ -166,3 +166,19 @@ class MyComponent extends Component {
166 166
   }
167 167
 }
168 168
 ```
169
+
170
+## previewCompleted (iOS 11.4+ only)
171
+Called when preview peek is completed
172
+
173
+```js
174
+class MyComponent extends Component {
175
+  constructor(props) {
176
+    super(props);
177
+    Navigation.events().bindComponent(this);
178
+  }
179
+
180
+  previewCompleted({ previewComponentId }) {
181
+
182
+  }
183
+}
184
+```

+ 1
- 1
docs/docs/styling.md 查看文件

@@ -149,7 +149,7 @@ Navigation.mergeOptions(this.props.componentId, {
149 149
     interceptTouchOutside: true
150 150
   },
151 151
   preview: {
152
-    elementId: 'PreviewId',
152
+    reactTag: 0, // result from findNodeHandle(ref)
153 153
     width: 100,
154 154
     height: 100,
155 155
     commit: false,

+ 19
- 6
lib/ios/RNNCommandsHandler.m 查看文件

@@ -98,16 +98,26 @@ static NSString* const setDefaultOptions	= @"setDefaultOptions";
98 98
 	RNNRootViewController *newVc = (RNNRootViewController *)[_controllerFactory createLayoutAndSaveToStore:layout];
99 99
 	UIViewController *fromVC = [_store findComponentForId:componentId];
100 100
 	
101
-	if (newVc.options.preview.elementId) {
101
+	if ([newVc.options.preview.reactTag floatValue] > 0) {
102 102
 		UIViewController* vc = [_store findComponentForId:componentId];
103 103
 
104 104
 		if([vc isKindOfClass:[RNNRootViewController class]]) {
105 105
 			RNNRootViewController* rootVc = (RNNRootViewController*)vc;
106 106
 			rootVc.previewController = newVc;
107
-
108
-			RNNElementFinder* elementFinder = [[RNNElementFinder alloc] initWithFromVC:vc];
109
-			RNNElementView* elementView = [elementFinder findElementForId:newVc.options.preview.elementId];
110
-
107
+			rootVc.previewCallback = ^(UIViewController *vcc) {
108
+				RNNRootViewController* rvc  = (RNNRootViewController*)vcc;
109
+				[self->_eventEmitter sendOnPreviewCompleted:componentId previewComponentId:newVc.componentId];
110
+				if ([newVc.options.preview.commit floatValue] > 0) {
111
+					[CATransaction begin];
112
+					[CATransaction setCompletionBlock:^{
113
+						[self->_eventEmitter sendOnNavigationCommandCompletion:push params:@{@"componentId": componentId}];
114
+						completion();
115
+					}];
116
+					[rvc.navigationController pushViewController:newVc animated:YES];
117
+					[CATransaction commit];
118
+				}
119
+			};
120
+			
111 121
 			CGSize size = CGSizeMake(rootVc.view.frame.size.width, rootVc.view.frame.size.height);
112 122
 			
113 123
 			if (newVc.options.preview.width) {
@@ -122,7 +132,10 @@ static NSString* const setDefaultOptions	= @"setDefaultOptions";
122 132
 				newVc.preferredContentSize = size;
123 133
 			}
124 134
 
125
-			[rootVc registerForPreviewingWithDelegate:(id)rootVc sourceView:elementView];
135
+			RCTExecuteOnMainQueue(^{
136
+				UIView *view = [[ReactNativeNavigation getBridge].uiManager viewForReactTag:newVc.options.preview.reactTag];
137
+				[rootVc registerForPreviewingWithDelegate:(id)rootVc sourceView:view];
138
+			});
126 139
 		}
127 140
 	} else {
128 141
 		id animationDelegate = (newVc.options.animations.push.hasCustomAnimation || newVc.isCustomTransitioned) ? newVc : nil;

+ 2
- 0
lib/ios/RNNEventEmitter.h 查看文件

@@ -22,4 +22,6 @@
22 22
 
23 23
 -(void)sendOnSearchBarCancelPressed:(NSString *)componentId;
24 24
 
25
+-(void)sendOnPreviewCompleted:(NSString *)componentId previewComponentId:(NSString *)previewComponentId;
26
+
25 27
 @end

+ 10
- 1
lib/ios/RNNEventEmitter.m 查看文件

@@ -16,6 +16,7 @@ static NSString* const ComponentDidDisappear	= @"RNN.ComponentDidDisappear";
16 16
 static NSString* const NavigationButtonPressed	= @"RNN.NavigationButtonPressed";
17 17
 static NSString* const SearchBarUpdated 		= @"RNN.SearchBarUpdated";
18 18
 static NSString* const SearchBarCancelPressed 	= @"RNN.SearchBarCancelPressed";
19
+static NSString* const PreviewCompleted         = @"RNN.PreviewCompleted";
19 20
 
20 21
 -(NSArray<NSString *> *)supportedEvents {
21 22
 	return @[AppLaunched,
@@ -25,7 +26,8 @@ static NSString* const SearchBarCancelPressed 	= @"RNN.SearchBarCancelPressed";
25 26
 			 ComponentDidDisappear,
26 27
 			 NavigationButtonPressed,
27 28
 			 SearchBarUpdated,
28
-			 SearchBarCancelPressed];
29
+			 SearchBarCancelPressed,
30
+			 PreviewCompleted];
29 31
 }
30 32
 
31 33
 # pragma mark public
@@ -90,6 +92,13 @@ static NSString* const SearchBarCancelPressed 	= @"RNN.SearchBarCancelPressed";
90 92
 											}];
91 93
 }
92 94
 
95
+- (void)sendOnPreviewCompleted:(NSString *)componentId previewComponentId:(NSString *)previewComponentId {
96
+	[self send:PreviewCompleted body:@{
97
+											 @"componentId": componentId,
98
+											 @"previewComponentId": previewComponentId
99
+											 }];
100
+}
101
+
93 102
 - (void)addListener:(NSString *)eventName {
94 103
 	[super addListener:eventName];
95 104
 	if ([eventName isEqualToString:AppLaunched]) {

+ 1
- 1
lib/ios/RNNPreviewOptions.h 查看文件

@@ -2,7 +2,7 @@
2 2
 
3 3
 @interface RNNPreviewOptions : RNNOptions
4 4
 
5
-@property (nonatomic, strong) NSString* elementId;
5
+@property (nonatomic, strong) NSNumber* reactTag;
6 6
 @property (nonatomic, strong) NSNumber* width;
7 7
 @property (nonatomic, strong) NSNumber* height;
8 8
 @property (nonatomic, strong) NSNumber* commit;

+ 2
- 1
lib/ios/RNNRootViewController.h 查看文件

@@ -7,6 +7,7 @@
7 7
 #import "RNNAnimator.h"
8 8
 
9 9
 typedef void (^RNNReactViewReadyCompletionBlock)(void);
10
+typedef void (^PreviewCallback)(UIViewController *vc);
10 11
 
11 12
 @interface RNNRootViewController : UIViewController	<UIViewControllerPreviewingDelegate, UISearchResultsUpdating, UISearchBarDelegate, UINavigationControllerDelegate, UISplitViewControllerDelegate>
12 13
 
@@ -16,7 +17,7 @@ typedef void (^RNNReactViewReadyCompletionBlock)(void);
16 17
 @property (nonatomic) id<RNNRootViewCreator> creator;
17 18
 @property (nonatomic, strong) RNNAnimator* animator;
18 19
 @property (nonatomic, strong) UIViewController* previewController;
19
-
20
+@property (nonatomic, copy) PreviewCallback previewCallback;
20 21
 
21 22
 - (instancetype)initWithName:(NSString*)name
22 23
 				withOptions:(RNNNavigationOptions*)options

+ 4
- 17
lib/ios/RNNRootViewController.m 查看文件

@@ -22,6 +22,8 @@
22 22
 
23 23
 @implementation RNNRootViewController
24 24
 
25
+@synthesize previewCallback;
26
+
25 27
 -(instancetype)initWithName:(NSString*)name
26 28
 				withOptions:(RNNNavigationOptions*)options
27 29
 			withComponentId:(NSString*)componentId
@@ -286,28 +288,13 @@
286 288
 }
287 289
 
288 290
 - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location{
289
-	if (self.previewController) {
290
-//		RNNRootViewController * vc = (RNNRootViewController*) self.previewController;
291
-//		[_eventEmitter sendOnNavigationEvent:@"previewContext" params:@{
292
-//																		@"previewComponentId": vc.componentId,
293
-//																		@"componentId": self.componentId
294
-//																		}];
295
-	}
296 291
 	return self.previewController;
297 292
 }
298 293
 
299 294
 
300 295
 - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
301
-	RNNRootViewController * vc = (RNNRootViewController*) self.previewController;
302
-//	NSDictionary * params = @{
303
-//							  @"previewComponentId": vc.componentId,
304
-//							  @"componentId": self.componentId
305
-//							  };
306
-	if (vc.options.preview.commit) {
307
-//		[_eventEmitter sendOnNavigationEvent:@"previewCommit" params:params];
308
-		[self.navigationController pushViewController:vc animated:false];
309
-	} else {
310
-//		[_eventEmitter sendOnNavigationEvent:@"previewDismissed" params:params];
296
+	if (self.previewCallback) {
297
+		self.previewCallback(self);
311 298
 	}
312 299
 }
313 300
 

+ 1
- 0
lib/ios/ReactNativeNavigation.h 查看文件

@@ -1,6 +1,7 @@
1 1
 #import <Foundation/Foundation.h>
2 2
 #import <UIKit/UIKit.h>
3 3
 #import <React/RCTBridge.h>
4
+#import <React/RCTUIManager.h>
4 5
 #import "RNNBridgeManagerDelegate.h"
5 6
 
6 7
 typedef UIViewController * (^RNNExternalViewCreator)(NSDictionary* props, RCTBridge* bridge);

+ 3
- 0
lib/src/Navigation.ts 查看文件

@@ -13,9 +13,11 @@ import { CommandsObserver } from './events/CommandsObserver';
13 13
 import { Constants } from './adapters/Constants';
14 14
 import { ComponentType } from 'react';
15 15
 import { ComponentEventsObserver } from './events/ComponentEventsObserver';
16
+import { TouchablePreview, Props as TouchablePreviewProps } from './adapters/TouchablePreview';
16 17
 
17 18
 export class Navigation {
18 19
   public readonly Element: React.ComponentType<{ elementId: any; resizeMode?: any; }>;
20
+  public readonly TouchablePreview: React.ComponentType<TouchablePreviewProps>;
19 21
   public readonly store: Store;
20 22
   private readonly nativeEventsReceiver: NativeEventsReceiver;
21 23
   private readonly uniqueIdProvider: UniqueIdProvider;
@@ -30,6 +32,7 @@ export class Navigation {
30 32
 
31 33
   constructor() {
32 34
     this.Element = Element;
35
+    this.TouchablePreview = TouchablePreview;
33 36
     this.store = new Store();
34 37
     this.nativeEventsReceiver = new NativeEventsReceiver();
35 38
     this.uniqueIdProvider = new UniqueIdProvider();

+ 6
- 1
lib/src/adapters/NativeEventsReceiver.ts 查看文件

@@ -5,7 +5,8 @@ import {
5 5
   ComponentDidDisappearEvent,
6 6
   NavigationButtonPressedEvent,
7 7
   SearchBarUpdatedEvent,
8
-  SearchBarCancelPressedEvent
8
+  SearchBarCancelPressedEvent,
9
+  PreviewCompletedEvent
9 10
 } from '../interfaces/ComponentEvents';
10 11
 import { CommandCompletedEvent, BottomTabSelectedEvent } from '../interfaces/Events';
11 12
 
@@ -49,6 +50,10 @@ export class NativeEventsReceiver {
49 50
     return this.emitter.addListener('RNN.SearchBarCancelPressed', callback);
50 51
   }
51 52
 
53
+  public registerPreviewCompletedListener(callback: (event: PreviewCompletedEvent) => void): EventSubscription {
54
+    return this.emitter.addListener('RNN.PreviewCompleted', callback);
55
+  }
56
+
52 57
   public registerCommandCompletedListener(callback: (data: CommandCompletedEvent) => void): EventSubscription {
53 58
     return this.emitter.addListener('RNN.CommandCompleted', callback);
54 59
   }

+ 144
- 0
lib/src/adapters/TouchablePreview.tsx 查看文件

@@ -0,0 +1,144 @@
1
+import * as React from 'react';
2
+import * as PropTypes from 'prop-types';
3
+import {
4
+  View,
5
+  Platform,
6
+  findNodeHandle,
7
+  TouchableOpacity,
8
+  TouchableHighlight,
9
+  TouchableNativeFeedback,
10
+  TouchableWithoutFeedback,
11
+  GestureResponderEvent,
12
+  NativeTouchEvent,
13
+  NativeSyntheticEvent,
14
+} from 'react-native';
15
+
16
+// Polyfill GestureResponderEvent type with additional `force` property (iOS)
17
+interface NativeTouchEventWithForce extends NativeTouchEvent { force: number; }
18
+interface GestureResponderEventWithForce extends NativeSyntheticEvent<NativeTouchEventWithForce> {}
19
+
20
+export interface Props {
21
+  children: React.ReactNode;
22
+  touchableComponent?: TouchableHighlight | TouchableOpacity | TouchableNativeFeedback | TouchableWithoutFeedback | React.ReactNode;
23
+  onPress?: () => void;
24
+  onPressIn?: (reactTag?) => void;
25
+  onPeekIn?: () => void;
26
+  onPeekOut?: () => void;
27
+}
28
+
29
+const PREVIEW_DELAY = 350;
30
+const PREVIEW_MIN_FORCE = 0.1;
31
+const PREVIEW_TIMEOUT = 1250;
32
+
33
+export class TouchablePreview extends React.PureComponent<Props, any> {
34
+
35
+  static propTypes = {
36
+    children: PropTypes.node,
37
+    touchableComponent: PropTypes.func,
38
+    onPress: PropTypes.func,
39
+    onPressIn: PropTypes.func,
40
+    onPeekIn: PropTypes.func,
41
+    onPeekOut: PropTypes.func,
42
+  };
43
+
44
+  static defaultProps = {
45
+    touchableComponent: TouchableWithoutFeedback,
46
+  };
47
+
48
+  static peeking = false;
49
+
50
+  private ref: React.Component<any> | null = null;
51
+  private timeout: number | undefined;
52
+  private ts: number = 0;
53
+
54
+  onRef = (ref: React.Component<any>) => {
55
+    this.ref = ref;
56
+  }
57
+
58
+  onPress = () => {
59
+    const { onPress } = this.props;
60
+
61
+    if (typeof onPress !== 'function' || TouchablePreview.peeking) {
62
+      return;
63
+    }
64
+
65
+    return onPress();
66
+  }
67
+
68
+  onPressIn = () => {
69
+    if (Platform.OS === 'ios') {
70
+      const { onPressIn } = this.props;
71
+
72
+      if (!onPressIn) {
73
+        return;
74
+      }
75
+
76
+      const reactTag = findNodeHandle(this.ref);
77
+
78
+      return onPressIn({ reactTag });
79
+    }
80
+
81
+    // Other platforms don't support 3D Touch Preview API
82
+    return null;
83
+  }
84
+
85
+  onTouchStart = (event: GestureResponderEvent) => {
86
+    // Store a timstamp of the initial touch start
87
+    this.ts = event.nativeEvent.timestamp;
88
+  }
89
+
90
+  onTouchMove = (event: GestureResponderEventWithForce) => {
91
+    clearTimeout(this.timeout);
92
+    const { force, timestamp } = event.nativeEvent;
93
+    const diff = (timestamp - this.ts);
94
+
95
+    if (force > PREVIEW_MIN_FORCE && diff > PREVIEW_DELAY) {
96
+      TouchablePreview.peeking = true;
97
+
98
+      if (typeof this.props.onPeekIn === 'function') {
99
+        this.props.onPeekIn();
100
+      }
101
+    }
102
+
103
+    this.timeout = setTimeout(this.onTouchEnd, PREVIEW_TIMEOUT);
104
+  }
105
+
106
+  onTouchEnd = () => {
107
+    clearTimeout(this.timeout);
108
+    TouchablePreview.peeking = false;
109
+
110
+    if (typeof this.props.onPeekOut === 'function') {
111
+      this.props.onPeekOut();
112
+    }
113
+  }
114
+
115
+  render() {
116
+    const { children, touchableComponent, onPress, onPressIn, ...props } = this.props;
117
+
118
+    // Default to TouchableWithoutFeedback for iOS if set to TouchableNativeFeedback
119
+    const Touchable = (
120
+      Platform.OS === 'ios' && touchableComponent instanceof TouchableNativeFeedback
121
+        ? TouchableWithoutFeedback
122
+        : touchableComponent
123
+    ) as typeof TouchableWithoutFeedback;
124
+
125
+    // Wrap component with Touchable for handling platform touches
126
+    // and a single react View for detecting force and timing.
127
+    return (
128
+      <Touchable
129
+        ref={this.onRef}
130
+        onPress={this.onPress}
131
+        onPressIn={this.onPressIn}
132
+        {...props}
133
+      >
134
+        <View
135
+          onTouchStart={this.onTouchStart}
136
+          onTouchMove={this.onTouchMove as (event: GestureResponderEvent) => void}
137
+          onTouchEnd={this.onTouchEnd}
138
+        >
139
+          {children}
140
+        </View>
141
+      </Touchable>
142
+    );
143
+  }
144
+}

+ 11
- 0
lib/src/events/ComponentEventsObserver.test.tsx 查看文件

@@ -13,6 +13,7 @@ describe('ComponentEventsObserver', () => {
13 13
   const navigationButtonPressedFn = jest.fn();
14 14
   const searchBarUpdatedFn = jest.fn();
15 15
   const searchBarCancelPressedFn = jest.fn();
16
+  const previewCompletedFn = jest.fn();
16 17
   let subscription;
17 18
 
18 19
   class SimpleScreen extends React.Component<any, any> {
@@ -55,6 +56,10 @@ describe('ComponentEventsObserver', () => {
55 56
       searchBarCancelPressedFn(event);
56 57
     }
57 58
 
59
+    previewCompleted(event) {
60
+      previewCompletedFn(event);
61
+    }
62
+
58 63
     render() {
59 64
       return 'Hello';
60 65
     }
@@ -93,6 +98,10 @@ describe('ComponentEventsObserver', () => {
93 98
     expect(searchBarCancelPressedFn).toHaveBeenCalledTimes(1);
94 99
     expect(searchBarCancelPressedFn).toHaveBeenCalledWith({ componentId: 'myCompId' });
95 100
 
101
+    uut.notifyPreviewCompleted({ componentId: 'myCompId' });
102
+    expect(previewCompletedFn).toHaveBeenCalledTimes(1);
103
+    expect(previewCompletedFn).toHaveBeenCalledWith({ componentId: 'myCompId' });
104
+
96 105
     tree.unmount();
97 106
     expect(willUnmountFn).toHaveBeenCalledTimes(1);
98 107
   });
@@ -168,6 +177,7 @@ describe('ComponentEventsObserver', () => {
168 177
     expect(mockEventsReceiver.registerNavigationButtonPressedListener).not.toHaveBeenCalled();
169 178
     expect(mockEventsReceiver.registerSearchBarUpdatedListener).not.toHaveBeenCalled();
170 179
     expect(mockEventsReceiver.registerSearchBarCancelPressedListener).not.toHaveBeenCalled();
180
+    expect(mockEventsReceiver.registerPreviewCompletedListener).not.toHaveBeenCalled();
171 181
     uut.registerOnceForAllComponentEvents();
172 182
     uut.registerOnceForAllComponentEvents();
173 183
     uut.registerOnceForAllComponentEvents();
@@ -177,5 +187,6 @@ describe('ComponentEventsObserver', () => {
177 187
     expect(mockEventsReceiver.registerNavigationButtonPressedListener).toHaveBeenCalledTimes(1);
178 188
     expect(mockEventsReceiver.registerSearchBarUpdatedListener).toHaveBeenCalledTimes(1);
179 189
     expect(mockEventsReceiver.registerSearchBarCancelPressedListener).toHaveBeenCalledTimes(1);
190
+    expect(mockEventsReceiver.registerPreviewCompletedListener).toHaveBeenCalledTimes(1);
180 191
   });
181 192
 });

+ 8
- 1
lib/src/events/ComponentEventsObserver.ts 查看文件

@@ -6,7 +6,8 @@ import {
6 6
   NavigationButtonPressedEvent,
7 7
   SearchBarUpdatedEvent,
8 8
   SearchBarCancelPressedEvent,
9
-  ComponentEvent
9
+  ComponentEvent,
10
+  PreviewCompletedEvent
10 11
 } from '../interfaces/ComponentEvents';
11 12
 import { NativeEventsReceiver } from '../adapters/NativeEventsReceiver';
12 13
 
@@ -20,6 +21,7 @@ export class ComponentEventsObserver {
20 21
     this.notifyNavigationButtonPressed = this.notifyNavigationButtonPressed.bind(this);
21 22
     this.notifySearchBarUpdated = this.notifySearchBarUpdated.bind(this);
22 23
     this.notifySearchBarCancelPressed = this.notifySearchBarCancelPressed.bind(this);
24
+    this.notifyPreviewCompleted = this.notifyPreviewCompleted.bind(this);
23 25
   }
24 26
 
25 27
   public registerOnceForAllComponentEvents() {
@@ -30,6 +32,7 @@ export class ComponentEventsObserver {
30 32
     this.nativeEventsReceiver.registerNavigationButtonPressedListener(this.notifyNavigationButtonPressed);
31 33
     this.nativeEventsReceiver.registerSearchBarUpdatedListener(this.notifySearchBarUpdated);
32 34
     this.nativeEventsReceiver.registerSearchBarCancelPressedListener(this.notifySearchBarCancelPressed);
35
+    this.nativeEventsReceiver.registerPreviewCompletedListener(this.notifyPreviewCompleted);
33 36
   }
34 37
 
35 38
   public bindComponent(component: React.Component<any>): EventSubscription {
@@ -70,6 +73,10 @@ export class ComponentEventsObserver {
70 73
     this.triggerOnAllListenersByComponentId(event, 'searchBarCancelPressed');
71 74
   }
72 75
 
76
+  notifyPreviewCompleted(event: PreviewCompletedEvent) {
77
+    this.triggerOnAllListenersByComponentId(event, 'previewCompleted');
78
+  }
79
+
73 80
   private triggerOnAllListenersByComponentId(event: ComponentEvent, method: string) {
74 81
     _.forEach(this.listeners[event.componentId], (component) => {
75 82
       if (_.isObject(component) && _.isFunction(component[method])) {

+ 7
- 0
lib/src/events/EventsRegistry.test.tsx 查看文件

@@ -74,6 +74,13 @@ describe('EventsRegistry', () => {
74 74
     expect(mockNativeEventsReceiver.registerSearchBarCancelPressedListener).toHaveBeenCalledWith(cb);
75 75
   });
76 76
 
77
+  it('delegates previewCompleted to nativeEventsReceiver', () => {
78
+    const cb = jest.fn();
79
+    uut.registerPreviewCompletedListener(cb);
80
+    expect(mockNativeEventsReceiver.registerPreviewCompletedListener).toHaveBeenCalledTimes(1);
81
+    expect(mockNativeEventsReceiver.registerPreviewCompletedListener).toHaveBeenCalledWith(cb);
82
+  });
83
+
77 84
   it('delegates registerCommandListener to commandObserver', () => {
78 85
     const cb = jest.fn();
79 86
     const result = uut.registerCommandListener(cb);

+ 6
- 1
lib/src/events/EventsRegistry.ts 查看文件

@@ -7,7 +7,8 @@ import {
7 7
   ComponentDidDisappearEvent,
8 8
   NavigationButtonPressedEvent,
9 9
   SearchBarUpdatedEvent,
10
-  SearchBarCancelPressedEvent
10
+  SearchBarCancelPressedEvent,
11
+  PreviewCompletedEvent
11 12
 } from '../interfaces/ComponentEvents';
12 13
 import { CommandCompletedEvent, BottomTabSelectedEvent } from '../interfaces/Events';
13 14
 
@@ -46,6 +47,10 @@ export class EventsRegistry {
46 47
     return this.nativeEventsReceiver.registerSearchBarCancelPressedListener(callback);
47 48
   }
48 49
 
50
+  public registerPreviewCompletedListener(callback: (event: PreviewCompletedEvent) => void): EventSubscription {
51
+    return this.nativeEventsReceiver.registerPreviewCompletedListener(callback);
52
+  }
53
+
49 54
   public registerCommandListener(callback: (name: string, params: any) => void): EventSubscription {
50 55
     return this.commandsObserver.register(callback);
51 56
   }

+ 5
- 0
lib/src/interfaces/ComponentEvents.ts 查看文件

@@ -22,3 +22,8 @@ export interface SearchBarUpdatedEvent extends ComponentEvent {
22 22
 export interface SearchBarCancelPressedEvent extends ComponentEvent {
23 23
   componentName?: string;
24 24
 }
25
+
26
+export interface PreviewCompletedEvent extends ComponentEvent {
27
+  componentName?: string;
28
+  previewComponentId?: string;
29
+}

+ 7
- 1
playground/src/screens/Button.js 查看文件

@@ -2,6 +2,7 @@ const React = require('react');
2 2
 const { Component } = require('react');
3 3
 const PropTypes = require('prop-types');
4 4
 const { Platform, ColorPropType, StyleSheet, TouchableNativeFeedback, TouchableOpacity, View, Text } = require('react-native');
5
+const { Navigation } = require('react-native-navigation');
5 6
 
6 7
 class Button extends Component {
7 8
 
@@ -47,8 +48,13 @@ class Button extends Component {
47 48
 
48 49
     const formattedTitle =
49 50
       Platform.OS === 'android' ? title.toUpperCase() : title;
50
-    const Touchable =
51
+    let Touchable =
51 52
       Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;
53
+
54
+    if (typeof onPressIn === 'function') {
55
+      Touchable = Navigation.TouchablePreview;
56
+    }
57
+
52 58
     return (
53 59
       <Touchable
54 60
         accessibilityComponentType='button'

+ 3
- 7
playground/src/screens/PushedScreen.js 查看文件

@@ -79,11 +79,7 @@ class PushedScreen extends Component {
79 79
         <Text testID={testIDs.PUSHED_SCREEN_HEADER} style={styles.h1}>{`Pushed Screen`}</Text>
80 80
         <Text style={styles.h2}>{`Stack Position: ${stackPosition}`}</Text>
81 81
         <Button title='Push' testID={testIDs.PUSH_BUTTON} onPress={this.onClickPush} />
82
-        {Platform.OS === 'ios' && (
83
-          <Navigation.Element elementId='PreviewElement'>
84
-            <Button testID={testIDs.SHOW_PREVIEW_BUTTON} onPress={this.onClickPush} onPressIn={this.onClickShowPreview} title='Push Preview' />
85
-          </Navigation.Element>
86
-        )}
82
+        {Platform.OS === 'ios' && <Button testID={testIDs.SHOW_PREVIEW_BUTTON} onPress={this.onClickPush} onPressIn={this.onClickShowPreview} title='Push Preview' />}
87 83
         <Button title='Pop' testID={testIDs.POP_BUTTON} onPress={this.onClickPop} />
88 84
         <Button title='Pop Previous' testID={testIDs.POP_PREVIOUS_BUTTON} onPress={this.onClickPopPrevious} />
89 85
         <Button title='Pop To Root' testID={testIDs.POP_TO_ROOT} onPress={this.onClickPopToRoot} />
@@ -95,7 +91,7 @@ class PushedScreen extends Component {
95 91
     );
96 92
   }
97 93
 
98
-  onClickShowPreview = async () => {
94
+  onClickShowPreview = async ({ reactTag }) => {
99 95
     await Navigation.push(this.props.componentId, {
100 96
       component: {
101 97
         name: 'navigation.playground.PushedScreen',
@@ -115,7 +111,7 @@ class PushedScreen extends Component {
115 111
             }
116 112
           },
117 113
           preview: {
118
-            elementId: 'PreviewElement',
114
+            reactTag,
119 115
             height: 400,
120 116
             commit: true,
121 117
             actions: [{

+ 5
- 9
playground/src/screens/WelcomeScreen.js 查看文件

@@ -41,11 +41,7 @@ class WelcomeScreen extends Component {
41 41
           <Button title='Push Lifecycle Screen' testID={testIDs.PUSH_LIFECYCLE_BUTTON} onPress={this.onClickLifecycleScreen} />
42 42
           <Button title='Static Lifecycle Events' testID={testIDs.PUSH_STATIC_LIFECYCLE_BUTTON} onPress={this.onClickShowStaticLifecycleOverlay} />
43 43
           <Button title='Push' testID={testIDs.PUSH_BUTTON} onPress={this.onClickPush} />
44
-          {Platform.OS === 'ios' && (
45
-            <Navigation.Element elementId='PreviewElement'>
46
-              <Button testID={testIDs.SHOW_PREVIEW_BUTTON} onPressIn={this.onClickShowPreview} title='Push Preview' />
47
-            </Navigation.Element>
48
-          )}
44
+          {Platform.OS === 'ios' && <Button testID={testIDs.SHOW_PREVIEW_BUTTON} onPress={this.onClickPush} onPressIn={this.onClickShowPreview} title='Push Preview' />}
49 45
           <Button title='Push Options Screen' testID={testIDs.PUSH_OPTIONS_BUTTON} onPress={this.onClickPushOptionsScreen} />
50 46
           <Button title='Push External Component' testID={testIDs.PUSH_EXTERNAL_COMPONENT_BUTTON} onPress={this.onClickPushExternalComponent} />
51 47
           {Platform.OS === 'android' && <Button title='Push Top Tabs screen' testID={testIDs.PUSH_TOP_TABS_BUTTON} onPress={this.onClickPushTopTabsScreen} />}
@@ -334,7 +330,7 @@ class WelcomeScreen extends Component {
334 330
     undefined();
335 331
   }
336 332
 
337
-  onClickShowPreview = async () => {
333
+  onClickShowPreview = async ({ reactTag }) => {
338 334
     await Navigation.push(this.props.componentId, {
339 335
       component: {
340 336
         name: 'navigation.playground.PushedScreen',
@@ -344,8 +340,8 @@ class WelcomeScreen extends Component {
344 340
               enable: false
345 341
             }
346 342
           },
347
-          preview: {
348
-            elementId: 'PreviewElement',
343
+          preview: reactTag ? {
344
+            reactTag,
349 345
             height: 300,
350 346
             commit: true,
351 347
             actions: [{
@@ -360,7 +356,7 @@ class WelcomeScreen extends Component {
360 356
                 style: 'destructive'
361 357
               }]
362 358
             }]
363
-          }
359
+          } : undefined,
364 360
         }
365 361
       }
366 362
     });