diff --git a/packages/react-native/React/Base/RCTRootView.m b/packages/react-native/React/Base/RCTRootView.m index c31498d8951238..28cebdbaa7a625 100644 --- a/packages/react-native/React/Base/RCTRootView.m +++ b/packages/react-native/React/Base/RCTRootView.m @@ -16,6 +16,7 @@ #import "RCTBridge.h" #import "RCTConstants.h" #import "RCTDevSettings.h" // [macOS] +#import "RCTFocusChangeEvent.h" // [macOS] // [macOS] remove #import "RCTKeyCommands.h" #import "RCTLog.h" #import "RCTPerformanceLogger.h" @@ -432,6 +433,46 @@ - (void)viewDidChangeEffectiveAppearance #endif // macOS] +#pragma mark - Key window blur/focus + +#if TARGET_OS_OSX // [macOS +- (void)viewDidMoveToWindow { + [super viewDidMoveToWindow]; + + NSWindow *window = [self window]; + if (window == nil) { + return; + } + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(containingWindowDidBecomeKey) + name:NSWindowDidBecomeKeyNotification + object:window]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(containingWindowDidResignKey) + name:NSWindowDidResignKeyNotification + object:window]; +} + +- (void)containingWindowDidBecomeKey { + NSResponder *firstResponder = [[self window] firstResponder]; + if ([firstResponder isKindOfClass:[RCTPlatformView class]]) { + NSNumber *reactTag = [(RCTPlatformView *)firstResponder reactTag]; + [[[self bridge] eventDispatcher] sendEvent:[RCTFocusChangeEvent focusEventWithReactTag:reactTag]]; + } +} + +- (void)containingWindowDidResignKey { + NSResponder *firstResponder = [[self window] firstResponder]; + if ([firstResponder isKindOfClass:[RCTPlatformView class]]) { + NSNumber *reactTag = [(RCTPlatformView *)firstResponder reactTag]; + [[[self bridge] eventDispatcher] sendEvent:[RCTFocusChangeEvent blurEventWithReactTag:reactTag]]; + } +} +#endif // macOS] + + #if TARGET_OS_OSX // [macOS - (NSMenu *)menuForEvent:(NSEvent *)event {