Skip to content

Commit f90e387

Browse files
nakamboSaadnajmi
andauthored
[Key handling] pass through all keys; allow specifying modifiers for validKeys[Down|Up] (#1867)
* [Key handling] pass through all keys; allow specifying modifiers for validKeys[Down|Up] There are scenarios where it might be necessary to look at the incoming events without removing from the system queue. Currently that's impossible today on React Native macOS, since views are required to specify `validKeysDown` or `validKeysUp`, and such events are always removed from the queue. To mitigate, let's add a new `passthroughAllKeyEvents` prop to `RCTView`. We could keep it forever (towards an interest to reduce event spam from native to JS), or we could use it towards the path to making it the default behavior (stage 1: default false, i.e. opt in, stage 2: default true, i.e. opt out, stage 3: remove, is default behavior). - React/Views/RCTView.h - React/Views/RCTView.m - React/Views/RCTViewManager.m Note that this doesn't properly work with `RCTUITextField` (i.e. single line text fields). From what I can tell, that would need us to possibly provide a custom field editor for the window. I am scoping this out for this PR. Another peculiarity to note is regarding `RCTUITextView` (i.e. multi line text fields). Here, it looks like the text view itself isn't exposed to the JS (this view doesn't have a `nativeTag`), so there's a `RCTView` holding a child `RCTUITextView` where the former dispatches events to JS on behalf for the latter. The reason this matters (specifically for "pass through" events) is because the latter can dispatch certain events to the JS, and then depending on the super class implementation (`NSTextView`), it may or may not *also* pass the `NSEvent` to the next responder (i.e. parent view, i.e. `RCTView`). Passing the action to the next responder *can* cause us to send duplicate JS events for the same `NSEvent`. I couldn't find anything in macOS APIs to determine if the view the event was generated for is a specific view, so I am introducing a book-keeping mechanism to not send duplicate events. Introduce `RCTHandledKey` for specifying modifiers for `validKeysDown` and `validKeysUp`. Behavior noted in type definitions. - Libraries/Text/TextInput/RCTBaseTextInputView.m - React/Base/RCTConvert.h - React/Base/RCTConvert.m - React/Views/RCTHandledKey.h - React/Views/RCTHandledKey.m - React/Views/RCTView.h - React/Views/RCTView.m - React/Views/RCTViewKeyboardEvent.m - React/Views/RCTViewManager.m - React/Views/ScrollView/RCTScrollView.m macOS *usually* does things on key down (as opposed to, say, Win32, which seems to *usually* does things on key up). Like `RCTUITextField`, passs `performKeyEquivalent:` to `textInputDelegate` so we can handle the alternate `keyDown:` path (e.g. Cmd+A). This will be needed for properly handling keystrokes that go through said alternate path. There are probably several other selectors that also need implementing (`deleteBackward:`) to full pass through every possible key, but I am leaving that for some other time. - Libraries/Text/TextInput/Multiline/RCTUITextView.m Make a totally unrelated fix to `RCTSwitch`. In a test page where I added an on-by-default switch, I noticed the first toggle (ON->OFF) doesn't do anything. The second toggle (OFF->ON) then doesn't (expectedly) do anything. Found wrong behavior on the switch test page -- tempted to instead remove `wasOn`, but for now repeating the pattern in `setOn:animated:` - React/Views/RCTSwitch.m Flow stuff. `passthroughAllKeyEvents` is now a valid thing to pass to `View` types. - Libraries/Components/View/ReactNativeViewAttributes.js - Libraries/Components/View/ViewPropTypes.js - Libraries/NativeComponent/BaseViewConfig.macos.js Update signatures for `validKeysDown` and `validKeysUp` - Libraries/Components/View/ViewPropTypes.js Remove duplicated specifications on `Pressable`. Just use the one from `View`. As a benefit, future changes allow us to not have to touch `Pressable` anymore. - Libraries/Components/Pressable/Pressable.js - Libraries/Components/View/ViewPropTypes.js Update test pages with `passthoughAllKeyEvents` and the keyboard events page with an example modifier usage. - packages/rn-tester/js/examples/KeyboardEventsExample/KeyboardEventsExample.js - packages/rn-tester/js/examples/TextInput/TextInputSharedExamples.js Testing: * Using the keyboard events test page, validate "pass through" of all events for simple view, single line text input, multi line text input. Sanity test existing (non-"pass through") behavior. * Using the text input test page, ordering of `keyDown` and `keyUp` events w.r.t. other events (such as `keyPress` -- which isn't dispatched for every key) * Using the switch test page, sanity test switch behaviors * feedback * feedback #2 * PR feedback --------- Co-authored-by: Saad Najmi <saadnajmi2@gmail.com>
1 parent 28dd130 commit f90e387

File tree

17 files changed

+620
-115
lines changed

17 files changed

+620
-115
lines changed

Libraries/Components/Pressable/Pressable.js

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import type {
2626
AccessibilityState,
2727
AccessibilityValue,
2828
} from '../View/ViewAccessibility';
29+
import type {HandledKeyboardEvent} from '../View/ViewPropTypes'; // [macOS]
2930

3031
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
3132
import usePressability from '../../Pressability/usePressability';
@@ -185,16 +186,27 @@ type Props = $ReadOnly<{|
185186
onKeyUp?: ?(event: KeyEvent) => void,
186187

187188
/**
188-
* Array of keys to receive key down events for
189-
* For arrow keys, add "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
189+
* When `true`, allows `onKeyDown` and `onKeyUp` to receive events not specified in
190+
* `validKeysDown` and `validKeysUp`, respectively. Events matching `validKeysDown` and `validKeysUp`
191+
* still have their native default behavior prevented, but the others do not.
192+
*
193+
* @platform macos
190194
*/
191-
validKeysDown?: ?Array<string>,
195+
passthroughAllKeyEvents?: ?boolean,
192196

193197
/**
194-
* Array of keys to receive key up events for
195-
* For arrow keys, add "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
198+
* Array of keys to receive key down events for. These events have their default native behavior prevented.
199+
*
200+
* @platform macos
201+
*/
202+
validKeysDown?: ?Array<string | HandledKeyboardEvent>,
203+
204+
/**
205+
* Array of keys to receive key up events for. These events have their default native behavior prevented.
206+
*
207+
* @platform macos
196208
*/
197-
validKeysUp?: ?Array<string>,
209+
validKeysUp?: ?Array<string | HandledKeyboardEvent>,
198210

199211
/**
200212
* Specifies whether the view should receive the mouse down event when the

Libraries/Components/View/ReactNativeViewAttributes.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ const UIView = {
4747
onDrop: true,
4848
onKeyDown: true,
4949
onKeyUp: true,
50+
passthroughAllKeyEvents: true,
5051
validKeysDown: true,
5152
validKeysUp: true,
5253
draggedTypes: true,

Libraries/Components/View/ViewPropTypes.js

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,22 +100,58 @@ type DirectEventProps = $ReadOnly<{|
100100
|}>;
101101

102102
// [macOS
103-
type KeyboardEventProps = $ReadOnly<{|
103+
/**
104+
* Represents a key that could be passed to `validKeysDown` and `validKeysUp`.
105+
*
106+
* `key` is the actual key, such as "a", or one of the special values:
107+
* "Tab", "Escape", "Enter", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
108+
* "Backspace", "Delete", "Home", "End", "PageUp", "PageDown".
109+
*
110+
* The rest are modifiers that when absent mean false.
111+
*
112+
* @platform macos
113+
*/
114+
export type HandledKeyboardEvent = $ReadOnly<{|
115+
altKey?: ?boolean,
116+
ctrlKey?: ?boolean,
117+
metaKey?: ?boolean,
118+
shiftKey?: ?boolean,
119+
key: string,
120+
|}>;
121+
122+
export type KeyboardEventProps = $ReadOnly<{|
123+
/**
124+
* Called after a key down event is detected.
125+
*/
104126
onKeyDown?: ?(event: KeyEvent) => void,
127+
128+
/**
129+
* Called after a key up event is detected.
130+
*/
105131
onKeyUp?: ?(event: KeyEvent) => void,
132+
133+
/**
134+
* When `true`, allows `onKeyDown` and `onKeyUp` to receive events not specified in
135+
* `validKeysDown` and `validKeysUp`, respectively. Events matching `validKeysDown` and `validKeysUp`
136+
* are still removed from the event queue, but the others are not.
137+
*
138+
* @platform macos
139+
*/
140+
passthroughAllKeyEvents?: ?boolean,
141+
106142
/**
107-
* Array of keys to receive key down events for
143+
* Array of keys to receive key down events for. These events have their default native behavior prevented.
108144
*
109145
* @platform macos
110146
*/
111-
validKeysDown?: ?Array<string>,
147+
validKeysDown?: ?Array<string | HandledKeyboardEvent>,
112148

113149
/**
114-
* Array of keys to receive key up events for
150+
* Array of keys to receive key up events for. These events have their default native behavior prevented.
115151
*
116152
* @platform macos
117153
*/
118-
validKeysUp?: ?Array<string>,
154+
validKeysUp?: ?Array<string | HandledKeyboardEvent>,
119155
|}>;
120156
// macOS]
121157

Libraries/NativeComponent/BaseViewConfig.macos.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ const validAttributesForNonEventProps = {
5252
draggedTypes: true,
5353
enableFocusRing: true,
5454
tooltip: true,
55+
passthroughAllKeyEvents: true,
5556
validKeysDown: true,
5657
validKeysUp: true,
5758
mouseDownCanMoveWindow: true,

Libraries/Text/TextInput/Multiline/RCTUITextView.m

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,14 @@ - (void)deleteBackward {
555555
}
556556
}
557557
#else // [macOS
558+
- (BOOL)performKeyEquivalent:(NSEvent *)event {
559+
if (!self.hasMarkedText && ![self.textInputDelegate textInputShouldHandleKeyEvent:event]) {
560+
return YES;
561+
}
562+
563+
return [super performKeyEquivalent:event];
564+
}
565+
558566
- (void)keyDown:(NSEvent *)event {
559567
// If has marked text, handle by native and return
560568
// Do this check before textInputShouldHandleKeyEvent as that one attempts to send the event to JS

Libraries/Text/TextInput/RCTBaseTextInputView.m

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#import <React/RCTTextSelection.h>
2222
#import <React/RCTUITextView.h> // [macOS]
2323
#import "../RCTTextUIKit.h" // [macOS]
24+
#import <React/RCTHandledKey.h> // [macOS]
2425

2526
@implementation RCTBaseTextInputView {
2627
__weak RCTBridge *_bridge;
@@ -668,7 +669,8 @@ - (BOOL)textInputShouldHandleDeleteForward:(__unused id)sender {
668669
}
669670

670671
- (BOOL)hasValidKeyDownOrValidKeyUp:(NSString *)key {
671-
return [self.validKeysDown containsObject:key] || [self.validKeysUp containsObject:key];
672+
return [RCTHandledKey key:key matchesFilter:self.validKeysDown]
673+
|| [RCTHandledKey key:key matchesFilter:self.validKeysUp];
672674
}
673675

674676
- (NSDragOperation)textInputDraggingEntered:(id<NSDraggingInfo>)draggingInfo

React/Base/RCTConvert.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
#import <WebKit/WebKit.h>
2121
#endif
2222

23+
@class RCTHandledKey; // [macOS]
24+
2325
/**
2426
* This class provides a collection of conversion functions for mapping
2527
* JSON objects to native types and classes. These are useful when writing
@@ -147,6 +149,8 @@ typedef BOOL css_backface_visibility_t;
147149

148150
#if TARGET_OS_OSX // [macOS
149151
+ (NSString *)accessibilityRoleFromTraits:(id)json;
152+
153+
+ (NSArray<RCTHandledKey *> *)RCTHandledKeyArray:(id)json;
150154
#endif // macOS]
151155
@end
152156

React/Base/RCTConvert.m

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#import <CoreText/CoreText.h>
1313

1414
#import "RCTDefines.h"
15+
#import "RCTHandledKey.h" // [macOS]
1516
#import "RCTImageSource.h"
1617
#import "RCTParserUtils.h"
1718
#import "RCTUtils.h"
@@ -1500,6 +1501,9 @@ + (NSString *)accessibilityRoleFromTraits:(id)json
15001501
}
15011502
return NSAccessibilityUnknownRole;
15021503
}
1504+
1505+
RCT_JSON_ARRAY_CONVERTER(RCTHandledKey);
1506+
15031507
#endif // macOS]
15041508

15051509
@end

React/Views/RCTHandledKey.h

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
// [macOS]
9+
10+
#if TARGET_OS_OSX
11+
#import <React/RCTConvert.h>
12+
13+
// This class is used for specifying key filtering e.g. for -[RCTView validKeysDown] and -[RCTView validKeysUp]
14+
// Also see RCTViewKeyboardEvent, which is a React representation of an actual NSEvent that is dispatched to JS.
15+
@interface RCTHandledKey : NSObject
16+
17+
+ (BOOL)event:(NSEvent *)event matchesFilter:(NSArray<RCTHandledKey *> *)filter;
18+
+ (BOOL)key:(NSString *)key matchesFilter:(NSArray<RCTHandledKey *> *)filter;
19+
20+
- (instancetype)initWithKey:(NSString *)key;
21+
- (BOOL)matchesEvent:(NSEvent *)event;
22+
23+
@property (nonatomic, copy) NSString *key;
24+
25+
// For the following modifiers, nil means we don't care about the presence of the modifier when filtering the key
26+
// They are still expected to be only boolean when not nil.
27+
@property (nonatomic, assign) NSNumber *altKey;
28+
@property (nonatomic, assign) NSNumber *ctrlKey;
29+
@property (nonatomic, assign) NSNumber *metaKey;
30+
@property (nonatomic, assign) NSNumber *shiftKey;
31+
32+
@end
33+
34+
@interface RCTConvert (RCTHandledKey)
35+
36+
+ (RCTHandledKey *)RCTHandledKey:(id)json;
37+
38+
@end
39+
40+
#endif

React/Views/RCTHandledKey.m

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
// [macOS]
9+
10+
#import "objc/runtime.h"
11+
#import <React/RCTAssert.h>
12+
#import <React/RCTUtils.h>
13+
#import <RCTConvert.h>
14+
#import <RCTHandledKey.h>
15+
#import <RCTViewKeyboardEvent.h>
16+
17+
#if TARGET_OS_OSX
18+
19+
@implementation RCTHandledKey
20+
21+
+ (NSArray<NSString *> *)validModifiers {
22+
// keep in sync with actual properties and RCTViewKeyboardEvent
23+
return @[@"altKey", @"ctrlKey", @"metaKey", @"shiftKey"];
24+
}
25+
26+
+ (BOOL)event:(NSEvent *)event matchesFilter:(NSArray<RCTHandledKey *> *)filter {
27+
for (RCTHandledKey *key in filter) {
28+
if ([key matchesEvent:event]) {
29+
return YES;
30+
}
31+
}
32+
33+
return NO;
34+
}
35+
36+
+ (BOOL)key:(NSString *)key matchesFilter:(NSArray<RCTHandledKey *> *)filter {
37+
for (RCTHandledKey *aKey in filter) {
38+
if ([[aKey key] isEqualToString:key]) {
39+
return YES;
40+
}
41+
}
42+
43+
return NO;
44+
}
45+
46+
- (instancetype)initWithKey:(NSString *)key {
47+
if ((self = [super init])) {
48+
self.key = key;
49+
}
50+
return self;
51+
}
52+
53+
- (BOOL)matchesEvent:(NSEvent *)event
54+
{
55+
NSEventType type = [event type];
56+
if (type != NSEventTypeKeyDown && type != NSEventTypeKeyUp) {
57+
RCTFatal(RCTErrorWithMessage([NSString stringWithFormat:@"Wrong event type (%d) sent to -[RCTHandledKey matchesEvent:]", (int)type]));
58+
return NO;
59+
}
60+
61+
NSDictionary *body = [RCTViewKeyboardEvent bodyFromEvent:event];
62+
NSString *key = body[@"key"];
63+
if (key == nil) {
64+
RCTFatal(RCTErrorWithMessage(@"Event body has missing value for 'key'"));
65+
return NO;
66+
}
67+
68+
if (![key isEqualToString:self.key]) {
69+
return NO;
70+
}
71+
72+
NSArray<NSString *> *modifiers = [RCTHandledKey validModifiers];
73+
for (NSString *modifier in modifiers) {
74+
NSNumber *myValue = [self valueForKey:modifier];
75+
76+
if (myValue == nil) {
77+
continue;
78+
}
79+
80+
NSNumber *eventValue = (NSNumber *)body[modifier];
81+
if (eventValue == nil) {
82+
RCTFatal(RCTErrorWithMessage([NSString stringWithFormat:@"Event body has missing value for '%@'", modifier]));
83+
return NO;
84+
}
85+
86+
if (![eventValue isKindOfClass:[NSNumber class]]) {
87+
RCTFatal(RCTErrorWithMessage([NSString stringWithFormat:@"Event body has unexpected value of class '%@' for '%@'",
88+
NSStringFromClass(object_getClass(eventValue)), modifier]));
89+
return NO;
90+
}
91+
92+
if (![myValue isEqualToNumber:body[modifier]]) {
93+
return NO;
94+
}
95+
}
96+
97+
return YES; // keys matched; all present modifiers matched
98+
}
99+
100+
@end
101+
102+
@implementation RCTConvert (RCTHandledKey)
103+
104+
+ (RCTHandledKey *)RCTHandledKey:(id)json
105+
{
106+
// legacy way of specifying validKeysDown and validKeysUp -- here we ignore the modifiers when comparing to the NSEvent
107+
if ([json isKindOfClass:[NSString class]]) {
108+
return [[RCTHandledKey alloc] initWithKey:(NSString *)json];
109+
}
110+
111+
// modern way of specifying validKeys and validKeysUp -- here we assume missing modifiers to mean false\NO
112+
if ([json isKindOfClass:[NSDictionary class]]) {
113+
NSDictionary *dict = (NSDictionary *)json;
114+
NSString *key = dict[@"key"];
115+
if (key == nil) {
116+
RCTLogConvertError(dict, @"a RCTHandledKey -- must include \"key\"");
117+
return nil;
118+
}
119+
120+
RCTHandledKey *handledKey = [[RCTHandledKey alloc] initWithKey:key];
121+
NSArray<NSString *> *modifiers = RCTHandledKey.validModifiers;
122+
for (NSString *key in modifiers) {
123+
id value = dict[key];
124+
if (value == nil) {
125+
value = @NO; // assume NO -- instead of nil i.e. "don't care" unlike the string case above.
126+
}
127+
128+
if (![value isKindOfClass:[NSNumber class]]) {
129+
RCTLogConvertError(value, @"a boolean");
130+
return nil;
131+
}
132+
133+
[handledKey setValue:@([(NSNumber *)value boolValue]) forKey:key];
134+
}
135+
136+
return handledKey;
137+
}
138+
139+
RCTLogConvertError(json, @"a RCTHandledKey -- allowed types are string and object");
140+
return nil;
141+
}
142+
143+
@end
144+
145+
#endif

0 commit comments

Comments
 (0)