Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[macOS] Add LongPressGestureHandler #3014

Merged
merged 20 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions MacOSExample/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
import React from 'react';
import {
Text,
View,
StyleSheet,
SectionList,
Platform,
Pressable,
} from 'react-native';
import { Text, View, StyleSheet, SectionList, Platform } from 'react-native';
import {
createStackNavigator,
StackScreenProps,
Expand All @@ -20,6 +13,7 @@ import {
import Draggable from './basic/draggable';
import PinchableBox from './recipes/scaleAndRotate';
import Tap from './basic/tap';
import LongPressExample from './basic/longPress';

interface Example {
name: string;
Expand All @@ -38,6 +32,7 @@ const EXAMPLES: ExamplesSection[] = [
{ name: 'Draggable', component: Draggable },
{ name: 'Pinch & rotate', component: PinchableBox },
{ name: 'Tap', component: Tap },
{ name: 'LongPress', component: LongPressExample },
],
},
];
Expand Down
36 changes: 36 additions & 0 deletions MacOSExample/src/basic/longPress/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { StyleSheet, View } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';

export default function LongPressExample() {
const g = Gesture.LongPress()
.onBegin(() => console.log('onBegin'))
.onStart(() => console.log('onStart'))
j-piasecki marked this conversation as resolved.
Show resolved Hide resolved
.onFinalize((_, success) => console.log('onFinalize', success))
.onTouchesDown(() => console.log('onTouchesDown'))
.onTouchesMove(() => console.log('onTouchesMove'))
.onTouchesUp(() => console.log('onTouchesUp'))
.minDuration(1000);

return (
<View style={styles.container}>
<GestureDetector gesture={g}>
<View style={styles.pressBox} />
</GestureDetector>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},

pressBox: {
width: 100,
height: 100,
borderRadius: 20,
backgroundColor: 'plum',
},
});
128 changes: 108 additions & 20 deletions apple/Handlers/RNLongPressHandler.m
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,36 @@
//

#import "RNLongPressHandler.h"
#import <React/RCTConvert.h>

#if !TARGET_OS_OSX

#import <UIKit/UIGestureRecognizerSubclass.h>

#import <React/RCTConvert.h>

@interface RNBetterLongPressGestureRecognizer : UILongPressGestureRecognizer {
#else
@interface RNBetterLongPressGestureRecognizer : NSGestureRecognizer {
dispatch_block_t block;
#endif

CFTimeInterval startTime;
CFTimeInterval previousTime;
}

#if TARGET_OS_OSX
@property (nonatomic, assign) double minimumPressDuration;
@property (nonatomic, assign) double allowableMovement;
#endif

- (id)initWithGestureHandler:(RNGestureHandler *)gestureHandler;
- (void)handleGesture:(UIGestureRecognizer *)recognizer;
- (NSUInteger)getDuration;

#if !TARGET_OS_OSX
- (void)handleGesture:(UIGestureRecognizer *)recognizer;
#else
- (void)handleGesture:(NSGestureRecognizer *)recognizer;
#endif

@end

@implementation RNBetterLongPressGestureRecognizer {
Expand Down Expand Up @@ -55,6 +69,8 @@ - (CGPoint)translationInView
return CGPointMake(currentPosition.x - _initPosition.x, currentPosition.y - _initPosition.y);
}

#if !TARGET_OS_OSX

- (void)touchesBegan:(NSSet<RNGHUITouch *> *)touches withEvent:(UIEvent *)event
{
[_gestureHandler setCurrentPointerType:event];
Expand All @@ -72,10 +88,7 @@ - (void)touchesMoved:(NSSet<RNGHUITouch *> *)touches withEvent:(UIEvent *)event
[super touchesMoved:touches withEvent:event];
[_gestureHandler.pointerTracker touchesMoved:touches withEvent:event];

CGPoint trans = [self translationInView];
if ((_gestureHandler.shouldCancelWhenOutside && ![_gestureHandler containsPointInView]) ||
(TEST_MAX_IF_NOT_NAN(
fabs(trans.y * trans.y + trans.x * trans.x), self.allowableMovement * self.allowableMovement))) {
if ([self shouldCancelGesture]) {
self.enabled = NO;
self.enabled = YES;
}
Expand All @@ -94,6 +107,83 @@ - (void)touchesCancelled:(NSSet<RNGHUITouch *> *)touches withEvent:(UIEvent *)ev
[self reset];
}

#else
- (void)mouseDown:(NSEvent *)event
{
self.state = NSGestureRecognizerStateBegan;
startTime = CACurrentMediaTime();
j-piasecki marked this conversation as resolved.
Show resolved Hide resolved

[_gestureHandler.pointerTracker touchesBegan:[NSSet setWithObject:event] withEvent:event];

_initPosition = [self locationInView:self.view];

__weak typeof(self) weakSelf = self;

block = dispatch_block_create(0, ^{
__strong typeof(self) strongSelf = weakSelf;

if (strongSelf) {
strongSelf.state = NSGestureRecognizerStateChanged;
strongSelf.state = NSGestureRecognizerStateEnded;
j-piasecki marked this conversation as resolved.
Show resolved Hide resolved
}
});

dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.minimumPressDuration * NSEC_PER_SEC)),
dispatch_get_main_queue(),
block);
}

- (void)mouseDragged:(NSEvent *)event
{
[_gestureHandler.pointerTracker touchesMoved:[NSSet setWithObject:event] withEvent:event];

if (block == nil) {
return;
}

if ([self shouldCancelGesture]) {
dispatch_block_cancel(block);
block = nil;

[self failOrCancelGesture];
}
}

- (void)mouseUp:(NSEvent *)event
{
[_gestureHandler.pointerTracker touchesEnded:[NSSet setWithObject:event] withEvent:event];

if (block) {
dispatch_block_cancel(block);
block = nil;
}

[self failOrCancelGesture];
}

- (void)failOrCancelGesture
{
if (self.state == NSGestureRecognizerStateChanged) {
self.state = NSGestureRecognizerStateCancelled;
} else {
self.state = NSGestureRecognizerStateFailed;
j-piasecki marked this conversation as resolved.
Show resolved Hide resolved
}
}

#endif

- (BOOL)shouldCancelGesture
{
CGPoint trans = [self translationInView];

BOOL shouldBeCancelledOutside = _gestureHandler.shouldCancelWhenOutside && ![_gestureHandler containsPointInView];
BOOL distanceExceeded =
TEST_MAX_IF_NOT_NAN(fabs(trans.y * trans.y + trans.x * trans.x), self.allowableMovement * self.allowableMovement);

return shouldBeCancelledOutside || distanceExceeded;
}

- (void)reset
{
if (self.state == UIGestureRecognizerStateFailed) {
Expand Down Expand Up @@ -126,7 +216,7 @@ - (instancetype)initWithTag:(NSNumber *)tag
- (void)resetConfig
{
[super resetConfig];
UILongPressGestureRecognizer *recognizer = (UILongPressGestureRecognizer *)_recognizer;
RNBetterLongPressGestureRecognizer *recognizer = (RNBetterLongPressGestureRecognizer *)_recognizer;

recognizer.minimumPressDuration = 0.5;
recognizer.allowableMovement = 10;
Expand All @@ -135,7 +225,7 @@ - (void)resetConfig
- (void)configure:(NSDictionary *)config
{
[super configure:config];
UILongPressGestureRecognizer *recognizer = (UILongPressGestureRecognizer *)_recognizer;
RNBetterLongPressGestureRecognizer *recognizer = (RNBetterLongPressGestureRecognizer *)_recognizer;

id prop = config[@"minDurationMs"];
if (prop != nil) {
Expand All @@ -148,6 +238,8 @@ - (void)configure:(NSDictionary *)config
}
}

#if !TARGET_OS_OSX

- (RNGestureHandlerState)state
{
// For long press recognizer we treat "Began" state as "active"
Expand Down Expand Up @@ -178,21 +270,17 @@ - (RNGestureHandlerEventExtraData *)eventExtraData:(UIGestureRecognizer *)recogn
withDuration:[(RNBetterLongPressGestureRecognizer *)recognizer getDuration]
withPointerType:_pointerType];
}
@end

#else

@implementation RNLongPressGestureHandler

- (instancetype)initWithTag:(NSNumber *)tag
- (RNGestureHandlerEventExtraData *)eventExtraData:(NSGestureRecognizer *)recognizer
{
RCTLogWarn(@"LongPressGestureHandler is not supported on macOS");
if ((self = [super initWithTag:tag])) {
_recognizer = [NSGestureRecognizer alloc];
}
return self;
return [RNGestureHandlerEventExtraData forPosition:[recognizer locationInView:recognizer.view]
withAbsolutePosition:[recognizer locationInView:recognizer.view.window.contentView]
withNumberOfTouches:1
withDuration:[(RNBetterLongPressGestureRecognizer *)recognizer getDuration]
withPointerType:RNGestureHandlerMouse];
}

@end

#endif
@end
Loading