diff --git a/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js b/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js index d2fff116cc32..e0580a77bdd5 100644 --- a/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js +++ b/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js @@ -16,8 +16,12 @@ import type { } from '../View/ViewPropTypes'; import type {KeyboardEvent, KeyboardMetrics} from './Keyboard'; +import KeyboardAvoidingViewNativeComponent from '../../../src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent'; +import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags'; +import Animated from '../../Animated/Animated'; import LayoutAnimation from '../../LayoutAnimation/LayoutAnimation'; import StyleSheet from '../../StyleSheet/StyleSheet'; +import NativeDeviceInfo from '../../Utilities/NativeDeviceInfo'; import Platform from '../../Utilities/Platform'; import {type EventSubscription} from '../../vendor/emitter/EventEmitter'; import AccessibilityInfo from '../AccessibilityInfo/AccessibilityInfo'; @@ -30,7 +34,7 @@ type KeyboardAvoidingViewPropsCore = Readonly<{ /** * Specify how to react to the presence of the keyboard. */ - behavior?: ?('height' | 'position' | 'padding'), + behavior?: ?('height' | 'position' | 'padding' | 'translate-with-padding'), /** * The style of the content container (View) when `behavior` is 'position'. @@ -44,6 +48,15 @@ type KeyboardAvoidingViewPropsCore = Readonly<{ */ enabled?: ?boolean, + /** + * Follow the keyboard natively. Requires the shared animation backend, and + * on Android, an edge-to-edge app. Before Android 11, the view animates on + * its own curve once the keyboard insets change. + * + * @default `false` + */ + experimental_native?: ?boolean, + /** * Distance between the top of the user screen and the React Native view, * may be non-zero in some use cases. @@ -63,6 +76,52 @@ type KeyboardAvoidingViewState = { bottom: number, }; +const AnimatedKeyboardAvoidingViewNativeComponent = + Animated.createAnimatedComponent(KeyboardAvoidingViewNativeComponent); + +let isNativeSupported: ?boolean = null; + +function shouldUseNative(props: KeyboardAvoidingViewProps): boolean { + if (props.experimental_native !== true || props.behavior == null) { + return false; + } + if (isNativeSupported != null) { + return isNativeSupported; + } + + isNativeSupported = false; + + if ( + !ReactNativeFeatureFlags.cxxNativeAnimatedEnabled() || + // eslint-disable-next-line react-hooks/rules-of-hooks + !ReactNativeFeatureFlags.useSharedAnimatedBackend() + ) { + if (__DEV__) { + console.warn( + 'KeyboardAvoidingView: `experimental_native` has no effect because ' + + 'the shared animation backend is disabled.', + ); + } + return false; + } + + if ( + Platform.OS === 'android' && + NativeDeviceInfo.getConstants().isEdgeToEdge !== true + ) { + if (__DEV__) { + console.warn( + 'KeyboardAvoidingView: `experimental_native` has no effect because ' + + 'the app is not edge-to-edge.', + ); + } + return false; + } + + isNativeSupported = true; + return true; +} + /** * Automatically adjusts its height, position, or bottom padding based on the * keyboard height to remain visible while the virtual keyboard is displayed. @@ -80,6 +139,15 @@ class KeyboardAvoidingView extends React.Component< _initialFrameHeight: number = 0; _bottom: number = 0; + _keyboardInset: Animated.Value = new Animated.Value(0); + // Yoga reads an infinite `maxHeight` as unset, unlike 0. + _keyboardMaxHeight: Animated.Value = new Animated.Value(Infinity); + _keyboardSettledInset: Animated.Value = new Animated.Value(0); + _keyboardTranslateY: Animated.Node = Animated.multiply( + this._keyboardInset, + -1, + ); + constructor(props: KeyboardAvoidingViewProps) { super(props); this.state = {bottom: 0}; @@ -125,6 +193,20 @@ class KeyboardAvoidingView extends React.Component< this._updateBottomIfNecessary(); }; + _onKeyboardInsetChange: (...args: ReadonlyArray) => void = + Animated.event( + [ + { + nativeEvent: { + inset: this._keyboardInset, + maxHeight: this._keyboardMaxHeight, + settledInset: this._keyboardSettledInset, + }, + }, + ], + {useNativeDriver: true}, + ); + _onKeyboardHide = (event: ?KeyboardEvent) => { this._keyboardEvent = null; // $FlowFixMe[unused-promise] @@ -161,6 +243,10 @@ class KeyboardAvoidingView extends React.Component< }; _updateBottomIfNecessary = async () => { + if (shouldUseNative(this.props)) { + return; + } + if (this._keyboardEvent == null) { this._setBottom(0); return; @@ -196,6 +282,7 @@ class KeyboardAvoidingView extends React.Component< if (enabled && this._bottom !== prevState.bottom) { this.setState({bottom: this._bottom}); } + this._updateSubscriptions(); } componentDidMount(): void { @@ -203,6 +290,31 @@ class KeyboardAvoidingView extends React.Component< this._keyboardEvent = null; this._setBottom(0); } + this._updateSubscriptions(); + } + + _updateSubscriptions(): void { + const shouldSubscribe = !shouldUseNative(this.props); + + if (shouldSubscribe === this._subscriptions.length > 0) { + return; + } + + if (!shouldSubscribe) { + this._subscriptions.forEach(subscription => { + subscription.remove(); + }); + + this._subscriptions = []; + // The last event goes stale while unsubscribed. + this._keyboardEvent = null; + + if (this._bottom !== 0) { + this._setBottom(0); + } + + return; + } if (Platform.OS === 'ios') { this._subscriptions = [ @@ -235,12 +347,43 @@ class KeyboardAvoidingView extends React.Component< children, contentContainerStyle, enabled = true, - // eslint-disable-next-line no-unused-vars + experimental_native, keyboardVerticalOffset = 0, style, onLayout, ...props } = this.props; + + if (shouldUseNative(this.props)) { + return ( + + {behavior === 'position' ? ( + + {children} + + ) : ( + children + )} + + ); + } + const bottomHeight = enabled === true ? this.state.bottom : 0; switch (behavior) { case 'height': @@ -282,6 +425,7 @@ class KeyboardAvoidingView extends React.Component< ); case 'padding': + case 'translate-with-padding': return ( + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + * UIView class for , driven by `UIKeyboardLayoutGuide`. + */ +@interface RCTKeyboardAvoidingViewComponentView : RCTViewComponentView + +@end + +NS_ASSUME_NONNULL_END diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.mm new file mode 100644 index 000000000000..196abbcc105a --- /dev/null +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.mm @@ -0,0 +1,287 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import "RCTKeyboardAvoidingViewComponentView.h" + +#import +#import + +#import "RCTFabricComponentsPlugins.h" + +using namespace facebook::react; + +// Hidden view from the keyboard top to the guide owner bottom. +@interface RCTKeyboardTrackingView : UIView + +@property (nonatomic, copy, nullable) void (^onLayout)(void); + +@end + +@implementation RCTKeyboardTrackingView + +- (void)layoutSubviews +{ + [super layoutSubviews]; + if (self.onLayout != nil) { + self.onLayout(); + } +} + +@end + +@implementation RCTKeyboardAvoidingViewComponentView { + BOOL _isTrackingViewLaidOut; + BOOL _isUpdateScheduled; + CGFloat _guideOwnerBottomSafeArea; + CGFloat _keyboardInset; + CGFloat _minTrackingHeight; + CGSize _guideOwnerSize; + NSUInteger _keyboardAnimationCount; + RCTKeyboardTrackingView *_trackingView; + + // The window guide never updates, and the guide of this view moves on resize. + __weak UIView *_guideOwnerView; + // `height` shrinks this view, so measure it while the keyboard doesn't overlap. + CGFloat _heightWithoutKeyboard; + // Changes once per keyboard animation: at its end, or at the start of a hide. + CGFloat _settledInset; + // Window subview, so no other code manages it and its frames are in window coordinates. + UIView *_trackingContainerView; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + _props = KeyboardAvoidingViewShadowNode::defaultSharedProps(); + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(_keyboardWillChangeFrame:) + name:UIKeyboardWillChangeFrameNotification + object:nil]; + } + + return self; +} + +- (void)dealloc +{ + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [_trackingContainerView removeFromSuperview]; +} + +- (void)didMoveToWindow +{ + [super didMoveToWindow]; + + [_trackingContainerView removeFromSuperview]; + _trackingContainerView = nil; + _trackingView = nil; + + UIWindow *window = self.window; + + if (window == nil) { + return; + } + + UIView *guideOwnerView = window.rootViewController.view; + + for (UIResponder *responder = self.nextResponder; responder != nil; responder = responder.nextResponder) { + if ([responder isKindOfClass:[UIViewController class]]) { + guideOwnerView = ((UIViewController *)responder).view; + break; + } + } + + if (guideOwnerView == nil) { + return; + } + + _guideOwnerView = guideOwnerView; + _guideOwnerSize = CGSizeZero; + _isTrackingViewLaidOut = NO; + + _trackingContainerView = [[UIView alloc] initWithFrame:window.bounds]; + _trackingContainerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + _trackingContainerView.hidden = YES; + _trackingContainerView.userInteractionEnabled = NO; + [window addSubview:_trackingContainerView]; + + _trackingView = [RCTKeyboardTrackingView new]; + _trackingView.translatesAutoresizingMaskIntoConstraints = NO; + __weak __typeof(self) weakSelf = self; + + _trackingView.onLayout = ^{ + __typeof(self) strongSelf = weakSelf; + + if (strongSelf == nil) { + return; + } + + strongSelf->_isTrackingViewLaidOut = YES; + [strongSelf _updateKeyboardInset]; + }; + + [_trackingContainerView addSubview:_trackingView]; + + [NSLayoutConstraint activateConstraints:@[ + [_trackingView.leadingAnchor constraintEqualToAnchor:_trackingContainerView.leadingAnchor], + [_trackingView.trailingAnchor constraintEqualToAnchor:_trackingContainerView.trailingAnchor], + [_trackingView.topAnchor constraintEqualToAnchor:guideOwnerView.keyboardLayoutGuide.topAnchor], + [_trackingView.bottomAnchor constraintEqualToAnchor:guideOwnerView.bottomAnchor], + ]]; + + [self _scheduleUpdate]; +} + +#pragma mark - Keyboard tracking + +// UIKit only animates the guide owner, so lay out the tracking view in the keyboard animation. +- (void)_keyboardWillChangeFrame:(NSNotification *)notification +{ + UIView *trackingContainerView = _trackingContainerView; + + if (trackingContainerView == nil) { + return; + } + + NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; + UIViewAnimationCurve curve = + (UIViewAnimationCurve)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]; + + _keyboardAnimationCount++; + __weak __typeof(self) weakSelf = self; + + [UIView animateWithDuration:duration + delay:0 + options:(UIViewAnimationOptions)curve << 16 | UIViewAnimationOptionBeginFromCurrentState + animations:^{ + [trackingContainerView layoutIfNeeded]; + } + completion:^(__unused BOOL finished) { + __typeof(self) strongSelf = weakSelf; + + if (strongSelf == nil) { + return; + } + + strongSelf->_keyboardAnimationCount--; + + if (strongSelf->_keyboardAnimationCount == 0) { + [strongSelf _updateKeyboardInset]; + } + }]; +} + +- (CGFloat)_hiddenKeyboardTrackingHeight +{ + // Capped at the bottom safe area, for when the keyboard was never hidden. + UIView *guideOwnerView = _guideOwnerView; + + if (guideOwnerView == nil) { + return 0; + } + + CGFloat bottomSafeArea = + MAX(CGRectGetMaxY(guideOwnerView.bounds) - CGRectGetMaxY(guideOwnerView.safeAreaLayoutGuide.layoutFrame), 0); + + // The hidden guide follows the bottom safe area, which can change without a resize. + if (!CGSizeEqualToSize(guideOwnerView.bounds.size, _guideOwnerSize) || bottomSafeArea != _guideOwnerBottomSafeArea) { + _guideOwnerSize = guideOwnerView.bounds.size; + _guideOwnerBottomSafeArea = bottomSafeArea; + _minTrackingHeight = CGFLOAT_MAX; + } + + _minTrackingHeight = MIN(_minTrackingHeight, _trackingView.bounds.size.height); + return MIN(bottomSafeArea, _minTrackingHeight); +} + +- (void)_scheduleUpdate +{ + if (_isUpdateScheduled) { + return; + } + + _isUpdateScheduled = YES; + __weak __typeof(self) weakSelf = self; + + dispatch_async(dispatch_get_main_queue(), ^{ + __typeof(self) strongSelf = weakSelf; + + if (strongSelf == nil) { + return; + } + + strongSelf->_isUpdateScheduled = NO; + [strongSelf _updateKeyboardInset]; + }); +} + +- (void)_updateKeyboardInset +{ + if (_trackingView == nil || !_isTrackingViewLaidOut || _eventEmitter == nullptr) { + return; + } + + const auto &props = static_cast(*_props); + + if (_keyboardInset == 0) { + _heightWithoutKeyboard = _layoutMetrics.frame.size.height; + } + + CGFloat inset = 0; + BOOL isKeyboardVisible = _trackingView.bounds.size.height > [self _hiddenKeyboardTrackingHeight]; + + if (props.enabled && isKeyboardVisible) { + CGFloat keyboardY = CGRectGetMinY(_trackingView.frame) - props.keyboardVerticalOffset; + inset = MAX(_layoutMetrics.frame.origin.y + _heightWithoutKeyboard - keyboardY, 0); + } + + // During an animation, `inset` is already the end value. + CGFloat settledInset = (_keyboardAnimationCount == 0 || inset == 0) ? inset : _settledInset; + + if (inset == _keyboardInset && settledInset == _settledInset) { + return; + } + + _keyboardInset = inset; + _settledInset = settledInset; + CGFloat maxHeight = inset > 0 ? MAX(_heightWithoutKeyboard - inset, 0) : INFINITY; + + // A `folly::dynamic` payload, which C++ Native Animated can read. + _eventEmitter->dispatchUniqueEvent( + "keyboardInsetChange", + folly::dynamic::object("inset", inset)("maxHeight", maxHeight)("settledInset", settledInset)); +} + +#pragma mark - RCTComponentViewProtocol + ++ (ComponentDescriptorProvider)componentDescriptorProvider +{ + return concreteComponentDescriptorProvider(); +} + +- (void)finalizeUpdates:(RNComponentViewUpdateMask)updateMask +{ + [super finalizeUpdates:updateMask]; + // Can't commit inside a mount. + [self _scheduleUpdate]; +} + +- (void)prepareForRecycle +{ + [super prepareForRecycle]; + _keyboardInset = 0; + _settledInset = 0; + _heightWithoutKeyboard = 0; +} + +@end + +Class RCTKeyboardAvoidingViewCls(void) +{ + return RCTKeyboardAvoidingViewComponentView.class; +} diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h index 943d2383da1e..d1ad18c3f07f 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.h @@ -32,6 +32,7 @@ Class RCTFabricComponentsProvider(const char *name); Class RCTActivityIndicatorViewCls(void) __attribute__((used)); Class RCTDebuggingOverlayCls(void) __attribute__((used)); Class RCTInputAccessoryCls(void) __attribute__((used)); +Class RCTKeyboardAvoidingViewCls(void) __attribute__((used)); Class RCTParagraphCls(void) __attribute__((used)); Class RCTPullToRefreshViewCls(void) __attribute__((used)); Class RCTSafeAreaViewCls(void) __attribute__((used)); diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.mm b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.mm index afd45feecc43..de6f2108e3bd 100644 --- a/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.mm +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/RCTFabricComponentsPlugins.mm @@ -21,6 +21,7 @@ {"ActivityIndicatorView", RCTActivityIndicatorViewCls}, {"DebuggingOverlay", RCTDebuggingOverlayCls}, {"InputAccessoryView", RCTInputAccessoryCls}, + {"KeyboardAvoidingView", RCTKeyboardAvoidingViewCls}, {"Paragraph", RCTParagraphCls}, {"PullToRefreshView", RCTPullToRefreshViewCls}, {"SafeAreaView", RCTSafeAreaViewCls}, diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt index 14b053b4196f..6311b9a5506b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt @@ -48,6 +48,7 @@ import com.facebook.react.modules.websocket.WebSocketModule import com.facebook.react.uimanager.ViewManager import com.facebook.react.views.drawer.ReactDrawerLayoutManager import com.facebook.react.views.image.ReactImageManager +import com.facebook.react.views.keyboardavoidingview.ReactKeyboardAvoidingViewManager import com.facebook.react.views.modal.ReactModalHostManager import com.facebook.react.views.progressbar.ReactProgressBarViewManager import com.facebook.react.views.safeareaview.ReactSafeAreaViewManager @@ -144,6 +145,7 @@ constructor(private val config: MainPackageConfig? = null) : ReactDrawerLayoutManager(), ReactHorizontalScrollViewManager(), ReactHorizontalScrollContainerViewManager(), + ReactKeyboardAvoidingViewManager(), ReactProgressBarViewManager(), if (ReactNativeFeatureFlags.useNestedScrollViewAndroid()) ReactNestedScrollViewManager() else ReactScrollViewManager(), @@ -176,6 +178,8 @@ constructor(private val config: MainPackageConfig? = null) : ModuleSpec.viewManagerSpec { ReactHorizontalScrollViewManager() }, ReactHorizontalScrollContainerViewManager.REACT_CLASS to ModuleSpec.viewManagerSpec { ReactHorizontalScrollContainerViewManager() }, + ReactKeyboardAvoidingViewManager.REACT_CLASS to + ModuleSpec.viewManagerSpec { ReactKeyboardAvoidingViewManager() }, ReactProgressBarViewManager.REACT_CLASS to ModuleSpec.viewManagerSpec { ReactProgressBarViewManager() }, ReactSafeAreaViewManager.REACT_CLASS to diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/KeyboardInsetChangeEvent.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/KeyboardInsetChangeEvent.kt new file mode 100644 index 000000000000..871db6f1cd0c --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/KeyboardInsetChangeEvent.kt @@ -0,0 +1,34 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.keyboardavoidingview + +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.WritableMap +import com.facebook.react.uimanager.events.Event + +internal class KeyboardInsetChangeEvent( + surfaceId: Int, + viewTag: Int, + private val inset: Float, + private val maxHeight: Float, + private val settledInset: Float, +) : Event(surfaceId, viewTag) { + + override fun getEventName(): String = EVENT_NAME + + override fun getEventData(): WritableMap = + Arguments.createMap().apply { + putDouble("inset", inset.toDouble()) + putDouble("maxHeight", maxHeight.toDouble()) + putDouble("settledInset", settledInset.toDouble()) + } + + companion object { + const val EVENT_NAME: String = "topKeyboardInsetChange" + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingView.kt new file mode 100644 index 000000000000..0164dbb9fe47 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingView.kt @@ -0,0 +1,192 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.keyboardavoidingview + +import android.content.Context +import android.view.ViewTreeObserver +import androidx.annotation.UiThread +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsAnimationCompat +import androidx.core.view.WindowInsetsCompat +import com.facebook.react.bridge.ReactContext +import com.facebook.react.uimanager.PixelUtil.pxToDp +import com.facebook.react.uimanager.UIManagerHelper +import com.facebook.react.views.view.ReactViewGroup + +internal class ReactKeyboardAvoidingView(context: Context) : ReactViewGroup(context) { + + internal var isAvoidanceEnabled: Boolean = true + set(value) { + if (field != value) { + field = value + scheduleUpdate() + } + } + + /** In dp. */ + internal var keyboardVerticalOffset: Float = 0f + set(value) { + if (field != value) { + field = value + scheduleUpdate() + } + } + + private var isAnimating = false + private var isUpdateScheduled = false + + // All values below are in dp. + private var keyboardInset = 0f + // Changes once per keyboard animation: at its end, or at the start of a hide. + private var settledInset = 0f + // `height` shrinks this view, so measure it while the keyboard doesn't overlap. + private var heightWithoutKeyboard = 0f + + private val updateRunnable = Runnable { + isUpdateScheduled = false + if (!isAnimating) { + updateKeyboardInset(currentKeyboardHeight()) + } + } + + // An insets change lays out the window, even when an ancestor consumes the insets. + private val globalLayoutListener = + ViewTreeObserver.OnGlobalLayoutListener { + if (!isAnimating) { + scheduleUpdate() + } + } + + private val insetsAnimationCallback = + object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) { + override fun onPrepare(animation: WindowInsetsAnimationCompat) { + if (animation.isImeAnimation()) { + isAnimating = true + } + } + + override fun onStart( + animation: WindowInsetsAnimationCompat, + bounds: WindowInsetsAnimationCompat.BoundsCompat, + ): WindowInsetsAnimationCompat.BoundsCompat { + // Root insets hold the end value. + if ( + animation.isImeAnimation() && + settledInset != 0f && + (!isAvoidanceEnabled || keyboardOverlap(currentKeyboardHeight()) == 0f) + ) { + dispatchInsetChange(keyboardInset, 0f) + } + return bounds + } + + override fun onProgress( + insets: WindowInsetsCompat, + runningAnimations: MutableList, + ): WindowInsetsCompat { + if (runningAnimations.any { it.isImeAnimation() }) { + updateKeyboardInset( + insets.getInsets(WindowInsetsCompat.Type.ime()).bottom.toFloat().pxToDp() + ) + } + return insets + } + + override fun onEnd(animation: WindowInsetsAnimationCompat) { + if (animation.isImeAnimation()) { + isAnimating = false + updateKeyboardInset(currentKeyboardHeight()) + } + } + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + ViewCompat.setWindowInsetsAnimationCallback(this, insetsAnimationCallback) + viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener) + scheduleUpdate() + } + + override fun onDetachedFromWindow() { + ViewCompat.setWindowInsetsAnimationCallback(this, null) + viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener) + removeCallbacks(updateRunnable) + isAnimating = false + isUpdateScheduled = false + super.onDetachedFromWindow() + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + // Can't commit inside a mount. + if (changed) { + scheduleUpdate() + } + } + + private fun scheduleUpdate() { + if (!isUpdateScheduled && isAttachedToWindow) { + isUpdateScheduled = true + post(updateRunnable) + } + } + + private fun WindowInsetsAnimationCompat.isImeAnimation(): Boolean = + (typeMask and WindowInsetsCompat.Type.ime()) != 0 + + private fun currentKeyboardHeight(): Float { + val insets = ViewCompat.getRootWindowInsets(this) ?: return 0f + return insets.getInsets(WindowInsetsCompat.Type.ime()).bottom.toFloat().pxToDp() + } + + private fun keyboardOverlap(keyboardHeight: Float): Float { + if (keyboardHeight <= 0f) { + return 0f + } + + val frameY = top.toFloat().pxToDp() + val keyboardY = rootView.height.toFloat().pxToDp() - keyboardHeight - keyboardVerticalOffset + return maxOf(frameY + heightWithoutKeyboard - keyboardY, 0f) + } + + @UiThread + private fun updateKeyboardInset(keyboardHeight: Float) { + if (keyboardInset == 0f) { + heightWithoutKeyboard = height.toFloat().pxToDp() + } + + val inset = if (isAvoidanceEnabled) keyboardOverlap(keyboardHeight) else 0f + dispatchInsetChange(inset, if (!isAnimating || inset == 0f) inset else settledInset) + } + + @UiThread + private fun dispatchInsetChange(inset: Float, settled: Float) { + if (inset == keyboardInset && settled == settledInset) { + return + } + + val reactContext = context as? ReactContext ?: return + val eventDispatcher = UIManagerHelper.getEventDispatcher(reactContext) ?: return + + keyboardInset = inset + settledInset = settled + + val maxHeight = + if (inset > 0f) maxOf(heightWithoutKeyboard - inset, 0f) else Float.POSITIVE_INFINITY + + eventDispatcher.dispatchEvent( + KeyboardInsetChangeEvent( + UIManagerHelper.getSurfaceId(this), + id, + inset, + maxHeight, + settled, + ) + ) + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingViewManager.kt new file mode 100644 index 000000000000..acd3b3bbbaf0 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingViewManager.kt @@ -0,0 +1,45 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.keyboardavoidingview + +import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.annotations.ReactProp +import com.facebook.react.views.view.ReactViewGroup +import com.facebook.react.views.view.ReactViewManager + +@ReactModule(name = ReactKeyboardAvoidingViewManager.REACT_CLASS) +internal class ReactKeyboardAvoidingViewManager : ReactViewManager() { + + override fun getName(): String = REACT_CLASS + + override fun createViewInstance(context: ThemedReactContext): ReactViewGroup = + ReactKeyboardAvoidingView(context) + + override fun getExportedCustomDirectEventTypeConstants(): Map = + (super.getExportedCustomDirectEventTypeConstants() ?: mutableMapOf()).apply { + put( + KeyboardInsetChangeEvent.EVENT_NAME, + mapOf("registrationName" to "onKeyboardInsetChange"), + ) + } + + @ReactProp(name = "enabled", defaultBoolean = true) + fun setEnabled(view: ReactViewGroup, enabled: Boolean) { + (view as ReactKeyboardAvoidingView).isAvoidanceEnabled = enabled + } + + @ReactProp(name = "keyboardVerticalOffset", defaultFloat = 0f) + fun setKeyboardVerticalOffset(view: ReactViewGroup, offset: Float) { + (view as ReactKeyboardAvoidingView).keyboardVerticalOffset = offset + } + + internal companion object { + const val REACT_CLASS: String = "KeyboardAvoidingView" + } +} diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CoreComponentsRegistry.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CoreComponentsRegistry.cpp index 5eacbff0b81d..7ca9e7d7cc76 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CoreComponentsRegistry.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/newarchdefaults/CoreComponentsRegistry.cpp @@ -58,6 +58,9 @@ void addCoreComponents( concreteComponentDescriptorProvider()); providerRegistry->add( concreteComponentDescriptorProvider()); + providerRegistry->add( + concreteComponentDescriptorProvider< + KeyboardAvoidingViewComponentDescriptor>()); providerRegistry->add( concreteComponentDescriptorProvider()); providerRegistry->add( diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 2835ab8241ea..b4b00e0e3f5a 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -2810,7 +2810,8 @@ declare interface KeyboardAvoidingViewProps extends Readonly< ViewProps & KeyboardAvoidingViewPropsCore > {} declare type KeyboardAvoidingViewPropsCore = { - readonly behavior?: "height" | "padding" | "position" + readonly behavior?: + "height" | "padding" | "position" | "translate-with-padding" readonly contentContainerStyle?: ViewStyleProp readonly enabled?: boolean readonly keyboardVerticalOffset?: number @@ -5969,9 +5970,9 @@ export { KeyEvent, // 20fa4267 KeyUpEvent, // e45aac1c Keyboard, // a26f7bd4 - KeyboardAvoidingView, // dcc15389 - KeyboardAvoidingViewInstance, // 68298dc9 - KeyboardAvoidingViewProps, // 5ef2146b + KeyboardAvoidingView, // a4584dd3 + KeyboardAvoidingViewInstance, // e5e77319 + KeyboardAvoidingViewProps, // 7fb7513a KeyboardEvent, // c3f895d4 KeyboardEventEasing, // af4091c8 KeyboardEventName, // 59299ad6 diff --git a/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js b/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js new file mode 100644 index 000000000000..080a90c9f78f --- /dev/null +++ b/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js @@ -0,0 +1,37 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; +import type { + DirectEventHandler, + Float, + WithDefault, +} from '../../../../../Libraries/Types/CodegenTypes'; +import type {HostComponent} from '../../../types/HostComponent'; + +import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; + +type KeyboardInsetChangeEvent = Readonly<{ + inset: Float, + maxHeight: Float, + settledInset: Float, +}>; + +type KeyboardAvoidingViewNativeProps = Readonly<{ + ...ViewProps, + + enabled?: WithDefault, + keyboardVerticalOffset?: WithDefault, + onKeyboardInsetChange?: ?DirectEventHandler, +}>; + +export default codegenNativeComponent( + 'KeyboardAvoidingView', +) as HostComponent; diff --git a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js index c4db571ca9a3..a643dc5307b4 100644 --- a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js +++ b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js @@ -11,17 +11,20 @@ 'use strict'; import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; +import type {SafeAreaInsets} from 'react-native'; import * as React from 'react'; import {useState} from 'react'; import { Alert, Button, + FlatList, KeyboardAvoidingView, Modal, Pressable, ScrollView, StyleSheet, + Switch, Text, TextInput, TouchableOpacity, @@ -72,17 +75,29 @@ const BEHAVIOR_DESCRIPTIONS: {[key: KeyboardAvoidingBehavior]: string} = { height: 'Shrinks the view height by the keyboard overlap.', }; +const NativeToggle = (props: { + native: boolean, + setNative: (value: boolean) => void, +}) => { + return ( + + experimental_native + + + ); +}; + const BehaviorPicker = (props: { behavior: KeyboardAvoidingBehavior, setBehavior: (v: KeyboardAvoidingBehavior) => void, }) => { return ( - + {BEHAVIORS.map(behavior => { const selected = props.behavior === behavior; return ( @@ -114,11 +129,16 @@ const BehaviorPicker = (props: { const KeyboardAvoidingViewBehaviour = () => { const [modalOpen, setModalOpen] = useState(false); const [behavior, setBehavior] = useState('padding'); + const [native, setNative] = useState(false); return ( - + + @@ -243,6 +263,144 @@ const KeyboardAvoidingScrollView = () => { ); }; +type ChatMessage = { + id: string, + text: string, + isSent: boolean, +}; + +const CHAT_LINES = [ + 'Hey! Are we still on for tonight?', + 'Yes, 8pm works for me.', + 'Great. Same place as last time?', + 'Sure. Should I book a table?', + 'Please do, it gets busy on Fridays.', + 'Done, table for four.', + 'Who else is coming?', + 'Sam and Alex.', +]; + +const INITIAL_CHAT_MESSAGES: Array = Array.from( + {length: 40}, + (_, index) => ({ + id: String(index), + text: CHAT_LINES[index % CHAT_LINES.length], + isSent: index % 3 === 0, + }), +); + +const ChatBubble = ({message}: {message: ChatMessage}) => { + return ( + + + {message.text} + + + ); +}; + +const KeyboardAvoidingChat = () => { + const [modalOpen, setModalOpen] = useState(false); + const [native, setNative] = useState(true); + const [messages, setMessages] = useState(INITIAL_CHAT_MESSAGES); + const [draft, setDraft] = useState(''); + const [insets, setInsets] = useState(null); + const [keyboardVerticalOffset, setKeyboardVerticalOffset] = useState(0); + + const sendMessage = () => { + const text = draft.trim(); + + if (text === '') { + return; + } + + setMessages(prevMessages => [ + {id: String(Date.now()), text, isSent: true}, + ...prevMessages, + ]); + + setDraft(''); + }; + + return ( + + + { + setInsets(event.nativeEvent.insets); + }} + style={[ + styles.chatContainer, + insets != null && { + paddingBottom: insets.bottom, + paddingLeft: insets.left, + paddingRight: insets.right, + paddingTop: insets.top, + }, + ]}> + + + + + + { + setKeyboardVerticalOffset(event.nativeEvent.layout.y); + }} + style={styles.chatClip}> + + item.id} + renderItem={({item}) => } + contentContainerStyle={styles.chatListContent} + /> + + + + +