From e4a136d3ae6d211505287a6559eef60a447769b1 Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Mon, 26 Oct 2026 17:31:11 +0100 Subject: [PATCH 1/3] Add native KeyboardAvoidingView --- .../Keyboard/KeyboardAvoidingView.js | 134 ++++++++- .../RCTKeyboardAvoidingViewComponentView.h | 21 ++ .../RCTKeyboardAvoidingViewComponentView.mm | 262 ++++++++++++++++++ .../RCTFabricComponentsPlugins.h | 1 + .../RCTFabricComponentsPlugins.mm | 1 + .../facebook/react/shell/MainReactPackage.kt | 4 + .../KeyboardInsetChangeEvent.kt | 32 +++ .../ReactKeyboardAvoidingView.kt | 161 +++++++++++ .../ReactKeyboardAvoidingViewManager.kt | 45 +++ .../CoreComponentsRegistry.cpp | 3 + .../KeyboardAvoidingViewNativeComponent.js | 36 +++ .../KeyboardAvoidingViewExample.js | 31 ++- .../api-snapshots/ReactAndroidDebugCxx.api | 22 ++ .../ReactAndroidFrameworksCxx.api | 22 ++ .../api-snapshots/ReactAndroidNewarchCxx.api | 22 ++ .../api-snapshots/ReactAndroidReleaseCxx.api | 22 ++ .../api-snapshots/ReactAppleDebugCxx.api | 26 ++ .../api-snapshots/ReactAppleFrameworksCxx.api | 26 ++ .../api-snapshots/ReactAppleNewarchCxx.api | 26 ++ .../api-snapshots/ReactAppleReleaseCxx.api | 26 ++ 20 files changed, 921 insertions(+), 2 deletions(-) create mode 100644 packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.h create mode 100644 packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.mm create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/KeyboardInsetChangeEvent.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingView.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingViewManager.kt create mode 100644 packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js diff --git a/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js b/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js index d2fff116cc32..7c34eadfcc5f 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'; @@ -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. @@ -79,6 +138,9 @@ class KeyboardAvoidingView extends React.Component< viewRef: {current: React.ElementRef | null, ...}; _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); constructor(props: KeyboardAvoidingViewProps) { super(props); @@ -125,6 +187,19 @@ class KeyboardAvoidingView extends React.Component< this._updateBottomIfNecessary(); }; + _onKeyboardInsetChange: (...args: ReadonlyArray) => void = + Animated.event( + [ + { + nativeEvent: { + inset: this._keyboardInset, + maxHeight: this._keyboardMaxHeight, + }, + }, + ], + {useNativeDriver: true}, + ); + _onKeyboardHide = (event: ?KeyboardEvent) => { this._keyboardEvent = null; // $FlowFixMe[unused-promise] @@ -161,6 +236,10 @@ class KeyboardAvoidingView extends React.Component< }; _updateBottomIfNecessary = async () => { + if (shouldUseNative(this.props)) { + return; + } + if (this._keyboardEvent == null) { this._setBottom(0); return; @@ -196,6 +275,7 @@ class KeyboardAvoidingView extends React.Component< if (enabled && this._bottom !== prevState.bottom) { this.setState({bottom: this._bottom}); } + this._updateSubscriptions(); } componentDidMount(): void { @@ -203,6 +283,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 +340,39 @@ 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': diff --git a/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.h b/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.h new file mode 100644 index 000000000000..7087433ab353 --- /dev/null +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.h @@ -0,0 +1,21 @@ +/* + * 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 + +#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..73147d4af64f --- /dev/null +++ b/packages/react-native/React/Fabric/Mounting/ComponentViews/KeyboardAvoidingView/RCTKeyboardAvoidingViewComponentView.mm @@ -0,0 +1,262 @@ +/* + * 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 { + RCTKeyboardTrackingView *_trackingView; + // Window subview, so no other code manages it and its frames are in window coordinates. + UIView *_trackingContainerView; + // The window guide never updates, and the guide of this view moves on resize. + __weak UIView *_guideOwnerView; + BOOL _isUpdateScheduled; + CGFloat _minTrackingHeight; + CGSize _guideOwnerSize; + CGFloat _guideOwnerBottomSafeArea; + BOOL _isTrackingViewLaidOut; + CGFloat _keyboardInset; + // `height` shrinks this view, so measure it while the keyboard doesn't overlap. + CGFloat _restingHeight; +} + +- (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]; + + [UIView animateWithDuration:duration + delay:0 + options:(UIViewAnimationOptions)curve << 16 | UIViewAnimationOptionBeginFromCurrentState + animations:^{ + [trackingContainerView layoutIfNeeded]; + } + completion:nil]; +} + +- (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) { + _restingHeight = _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 + _restingHeight - keyboardY, 0); + } + + if (inset == _keyboardInset) { + return; + } + + _keyboardInset = inset; + CGFloat maxHeight = inset > 0 ? MAX(_restingHeight - inset, 0) : INFINITY; + + // A `folly::dynamic` payload, which C++ Native Animated can read. + _eventEmitter->dispatchUniqueEvent( + "keyboardInsetChange", folly::dynamic::object("inset", inset)("maxHeight", maxHeight)); +} + +#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; + _restingHeight = 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..b0c43aac1c0b --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/KeyboardInsetChangeEvent.kt @@ -0,0 +1,32 @@ +/* + * 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, +) : Event(surfaceId, viewTag) { + + override fun getEventName(): String = EVENT_NAME + + override fun getEventData(): WritableMap = + Arguments.createMap().apply { + putDouble("inset", inset.toDouble()) + putDouble("maxHeight", maxHeight.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..76151daf8b0e --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/keyboardavoidingview/ReactKeyboardAvoidingView.kt @@ -0,0 +1,161 @@ +/* + * 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 + // `height` shrinks this view, so measure it while the keyboard doesn't overlap. + private var restingHeight = 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 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 + restingHeight - keyboardY, 0f) + } + + @UiThread + private fun updateKeyboardInset(keyboardHeight: Float) { + if (keyboardInset == 0f) { + restingHeight = height.toFloat().pxToDp() + } + + val inset = if (isAvoidanceEnabled) keyboardOverlap(keyboardHeight) else 0f + + if (inset == keyboardInset) { + return + } + + val reactContext = context as? ReactContext ?: return + val eventDispatcher = UIManagerHelper.getEventDispatcher(reactContext) ?: return + keyboardInset = inset + val maxHeight = if (inset > 0f) maxOf(restingHeight - inset, 0f) else Float.POSITIVE_INFINITY + + eventDispatcher.dispatchEvent( + KeyboardInsetChangeEvent(UIManagerHelper.getSurfaceId(this), id, inset, maxHeight) + ) + } +} 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/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js b/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js new file mode 100644 index 000000000000..9f4029d0b9c2 --- /dev/null +++ b/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js @@ -0,0 +1,36 @@ +/** + * 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, +}>; + +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..8b1a9b201a0a 100644 --- a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js +++ b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js @@ -22,6 +22,7 @@ import { Pressable, ScrollView, StyleSheet, + Switch, Text, TextInput, TouchableOpacity, @@ -72,6 +73,22 @@ 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, @@ -114,11 +131,16 @@ const BehaviorPicker = (props: { const KeyboardAvoidingViewBehaviour = () => { const [modalOpen, setModalOpen] = useState(false); const [behavior, setBehavior] = useState('padding'); + const [native, setNative] = useState(false); return ( - + + @@ -305,6 +327,13 @@ const styles = StyleSheet.create({ fontWeight: '500', color: 'blue', }, + nativeToggle: { + alignItems: 'center', + flexDirection: 'row', + gap: 8, + justifyContent: 'center', + marginBottom: 8, + }, behaviorDescription: { textAlign: 'center', alignSelf: 'center', diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index b1f8d72fcfb7..f557a736ae8c 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -422,6 +422,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -679,6 +682,7 @@ JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::AndroidDrawerLayoutComponentName[]; JSI_EXPORT const char facebook::react::AndroidSwipeRefreshLayoutComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -1706,6 +1710,24 @@ struct facebook::react::JavaTurboModule::InitParams { public std::string moduleName; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; + public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const override; + public virtual folly::dynamic getDiffProps(const facebook::react::Props* prevProps) const override; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 7b33432309db..3ac0304d1359 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -532,6 +532,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::ConcreteComponentDescriptor; using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; @@ -995,6 +998,7 @@ JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::AndroidDrawerLayoutComponentName[]; JSI_EXPORT const char facebook::react::AndroidSwipeRefreshLayoutComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -2541,6 +2545,24 @@ struct facebook::react::JsErrorHandler::ProcessedError::StackFrame { public std::string methodName; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; + public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const override; + public virtual folly::dynamic getDiffProps(const facebook::react::Props* prevProps) const override; +} + class facebook::react::LayoutAnimationCallbackWrapper { public LayoutAnimationCallbackWrapper(); public LayoutAnimationCallbackWrapper(facebook::jsi::Function&& callback); diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 2e76b6de8216..ee36dafb8177 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -422,6 +422,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -679,6 +682,7 @@ JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::AndroidDrawerLayoutComponentName[]; JSI_EXPORT const char facebook::react::AndroidSwipeRefreshLayoutComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -1705,6 +1709,24 @@ struct facebook::react::JavaTurboModule::InitParams { public std::string moduleName; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; + public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const override; + public virtual folly::dynamic getDiffProps(const facebook::react::Props* prevProps) const override; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 2e76b6de8216..ee36dafb8177 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -422,6 +422,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -679,6 +682,7 @@ JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::AndroidDrawerLayoutComponentName[]; JSI_EXPORT const char facebook::react::AndroidSwipeRefreshLayoutComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -1705,6 +1709,24 @@ struct facebook::react::JavaTurboModule::InitParams { public std::string moduleName; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; + public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const override; + public virtual folly::dynamic getDiffProps(const facebook::react::Props* prevProps) const override; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 25ee74c97f74..f5355d5c2ff4 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -1240,6 +1240,9 @@ interface RCTKeyCommands : public NSObject { public virtual void unregisterKeyCommandWithInput:modifierFlags:(NSString* input, UIKeyModifierFlags flags); } +interface RCTKeyboardAvoidingViewComponentView : public RCTViewComponentView { +} + interface RCTKeyboardObserver : public RCTEventEmitter { } @@ -2764,6 +2767,9 @@ protocol RCTJSRuntimeConfiguratorProtocol { public virtual JSRuntimeFactoryRef createJSRuntimeFactory(); } +protocol RCTKeyboardAvoidingViewViewProtocol : public NSObject { +} + protocol RCTLocalizationProtocol : public NSObject { public virtual NSString* localizedString:withDescription:(NSString* oldString, NSString* description); } @@ -3159,6 +3165,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3383,6 +3392,7 @@ template facebook::react::RectangleEdges facebook::react::operator-(const facebook::react::RectangleEdges& lhs, const facebook::react::RectangleEdges& rhs) noexcept; JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -3960,6 +3970,22 @@ class facebook::react::JSBigString : public facebook::jsi::Buffer { public ~JSBigString() override = default; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index aeaed7df09a0..6be1d5304093 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -1283,6 +1283,9 @@ interface RCTKeyCommands : public NSObject { public virtual void unregisterKeyCommandWithInput:modifierFlags:(NSString* input, UIKeyModifierFlags flags); } +interface RCTKeyboardAvoidingViewComponentView : public RCTViewComponentView { +} + interface RCTKeyboardObserver : public RCTEventEmitter { } @@ -2845,6 +2848,9 @@ protocol RCTJSRuntimeConfiguratorProtocol { public virtual JSRuntimeFactoryRef createJSRuntimeFactory(); } +protocol RCTKeyboardAvoidingViewViewProtocol : public NSObject { +} + protocol RCTLocalizationProtocol : public NSObject { public virtual NSString* localizedString:withDescription:(NSString* oldString, NSString* description); } @@ -3309,6 +3315,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::ConcreteComponentDescriptor; using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; @@ -3742,6 +3751,7 @@ template facebook::react::RectangleEdges facebook::react::operator-(const facebook::react::RectangleEdges& lhs, const facebook::react::RectangleEdges& rhs) noexcept; JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -4727,6 +4737,22 @@ struct facebook::react::JsErrorHandler::ProcessedError::StackFrame { public std::string methodName; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; +} + class facebook::react::LayoutAnimationCallbackWrapper { public LayoutAnimationCallbackWrapper(); public LayoutAnimationCallbackWrapper(facebook::jsi::Function&& callback); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index d505b7fcfd0d..db0c84792850 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -1240,6 +1240,9 @@ interface RCTKeyCommands : public NSObject { public virtual void unregisterKeyCommandWithInput:modifierFlags:(NSString* input, UIKeyModifierFlags flags); } +interface RCTKeyboardAvoidingViewComponentView : public RCTViewComponentView { +} + interface RCTKeyboardObserver : public RCTEventEmitter { } @@ -2757,6 +2760,9 @@ protocol RCTJSRuntimeConfiguratorProtocol { public virtual JSRuntimeFactoryRef createJSRuntimeFactory(); } +protocol RCTKeyboardAvoidingViewViewProtocol : public NSObject { +} + protocol RCTLocalizationProtocol : public NSObject { public virtual NSString* localizedString:withDescription:(NSString* oldString, NSString* description); } @@ -3152,6 +3158,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3376,6 +3385,7 @@ template facebook::react::RectangleEdges facebook::react::operator-(const facebook::react::RectangleEdges& lhs, const facebook::react::RectangleEdges& rhs) noexcept; JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -3952,6 +3962,22 @@ class facebook::react::JSBigString : public facebook::jsi::Buffer { public ~JSBigString() override = default; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 3feedc079438..0ed5219eb2be 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -1240,6 +1240,9 @@ interface RCTKeyCommands : public NSObject { public virtual void unregisterKeyCommandWithInput:modifierFlags:(NSString* input, UIKeyModifierFlags flags); } +interface RCTKeyboardAvoidingViewComponentView : public RCTViewComponentView { +} + interface RCTKeyboardObserver : public RCTEventEmitter { } @@ -2764,6 +2767,9 @@ protocol RCTJSRuntimeConfiguratorProtocol { public virtual JSRuntimeFactoryRef createJSRuntimeFactory(); } +protocol RCTKeyboardAvoidingViewViewProtocol : public NSObject { +} + protocol RCTLocalizationProtocol : public NSObject { public virtual NSString* localizedString:withDescription:(NSString* oldString, NSString* description); } @@ -3159,6 +3165,9 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::KeyboardAvoidingViewComponentDescriptor = facebook::react::ConcreteComponentDescriptor; +using facebook::react::KeyboardAvoidingViewShadowNode = facebook::react::ConcreteViewShadowNode; +using facebook::react::KeyboardAvoidingViewState = facebook::react::StateData; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3383,6 +3392,7 @@ template facebook::react::RectangleEdges facebook::react::operator-(const facebook::react::RectangleEdges& lhs, const facebook::react::RectangleEdges& rhs) noexcept; JSI_EXPORT const char facebook::react::ActivityIndicatorViewComponentName[]; JSI_EXPORT const char facebook::react::DebuggingOverlayComponentName[]; +JSI_EXPORT const char facebook::react::KeyboardAvoidingViewComponentName[]; JSI_EXPORT const char facebook::react::PullToRefreshViewComponentName[]; JSI_EXPORT const char facebook::react::UnimplementedNativeViewComponentName[]; @@ -3959,6 +3969,22 @@ class facebook::react::JSBigString : public facebook::jsi::Buffer { public ~JSBigString() override = default; } +class facebook::react::KeyboardAvoidingViewEventEmitter : public facebook::react::BaseViewEventEmitter { + public void onKeyboardInsetChange(facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange value) const; +} + +struct facebook::react::KeyboardAvoidingViewEventEmitter::OnKeyboardInsetChange { + public facebook::react::Float inset; + public facebook::react::Float maxHeight; +} + +class facebook::react::KeyboardAvoidingViewProps : public facebook::react::HostPlatformViewProps { + public KeyboardAvoidingViewProps() = default; + public KeyboardAvoidingViewProps(const facebook::react::PropsParserContext& context, const facebook::react::KeyboardAvoidingViewProps& sourceProps, const facebook::react::RawProps& rawProps); + public bool enabled; + public facebook::react::Float keyboardVerticalOffset; +} + class facebook::react::LayoutableShadowNode : public facebook::react::ShadowNode { public LayoutableShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public LayoutableShadowNode(const facebook::react::ShadowNodeFragment& fragment, const facebook::react::ShadowNodeFamily::Shared& family, facebook::react::ShadowNodeTraits traits); From 1e5ef7e507f89d2a40660e961ff38fea9779d11f Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 19 Nov 2026 14:29:42 +0100 Subject: [PATCH 2/3] Add translate-with-padding # Conflicts: # packages/react-native/ReactNativeApi.d.ts --- .../Keyboard/KeyboardAvoidingView.js | 14 +- .../RCTKeyboardAvoidingViewComponentView.mm | 50 ++-- .../KeyboardInsetChangeEvent.kt | 2 + .../ReactKeyboardAvoidingView.kt | 43 +++- packages/react-native/ReactNativeApi.d.ts | 11 +- .../KeyboardAvoidingViewNativeComponent.js | 1 + .../KeyboardAvoidingViewExample.js | 213 +++++++++++++++++- .../api-snapshots/ReactAndroidDebugCxx.api | 1 + .../ReactAndroidFrameworksCxx.api | 1 + .../api-snapshots/ReactAndroidNewarchCxx.api | 1 + .../api-snapshots/ReactAndroidReleaseCxx.api | 1 + .../api-snapshots/ReactAppleDebugCxx.api | 1 + .../api-snapshots/ReactAppleFrameworksCxx.api | 1 + .../api-snapshots/ReactAppleNewarchCxx.api | 1 + .../api-snapshots/ReactAppleReleaseCxx.api | 1 + 15 files changed, 312 insertions(+), 30 deletions(-) diff --git a/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js b/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js index 7c34eadfcc5f..e0580a77bdd5 100644 --- a/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js +++ b/packages/react-native/Libraries/Components/Keyboard/KeyboardAvoidingView.js @@ -34,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'. @@ -138,9 +138,15 @@ class KeyboardAvoidingView extends React.Component< viewRef: {current: React.ElementRef | null, ...}; _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); @@ -194,6 +200,7 @@ class KeyboardAvoidingView extends React.Component< nativeEvent: { inset: this._keyboardInset, maxHeight: this._keyboardMaxHeight, + settledInset: this._keyboardSettledInset, }, }, ], @@ -359,6 +366,10 @@ class KeyboardAvoidingView extends React.Component< style, behavior === 'height' && {maxHeight: this._keyboardMaxHeight}, behavior === 'padding' && {paddingBottom: this._keyboardInset}, + behavior === 'translate-with-padding' && { + paddingTop: this._keyboardSettledInset, + transform: [{translateY: this._keyboardTranslateY}], + }, ]} {...props}> {behavior === 'position' ? ( @@ -414,6 +425,7 @@ class KeyboardAvoidingView extends React.Component< ); case 'padding': + case 'translate-with-padding': return ( _keyboardAnimationCount--; + + if (strongSelf->_keyboardAnimationCount == 0) { + [strongSelf _updateKeyboardInset]; + } + }]; } - (CGFloat)_hiddenKeyboardTrackingHeight @@ -210,7 +228,7 @@ - (void)_updateKeyboardInset const auto &props = static_cast(*_props); if (_keyboardInset == 0) { - _restingHeight = _layoutMetrics.frame.size.height; + _heightWithoutKeyboard = _layoutMetrics.frame.size.height; } CGFloat inset = 0; @@ -218,19 +236,24 @@ - (void)_updateKeyboardInset if (props.enabled && isKeyboardVisible) { CGFloat keyboardY = CGRectGetMinY(_trackingView.frame) - props.keyboardVerticalOffset; - inset = MAX(_layoutMetrics.frame.origin.y + _restingHeight - keyboardY, 0); + inset = MAX(_layoutMetrics.frame.origin.y + _heightWithoutKeyboard - keyboardY, 0); } - if (inset == _keyboardInset) { + // 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; - CGFloat maxHeight = inset > 0 ? MAX(_restingHeight - inset, 0) : INFINITY; + _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)); + "keyboardInsetChange", + folly::dynamic::object("inset", inset)("maxHeight", maxHeight)("settledInset", settledInset)); } #pragma mark - RCTComponentViewProtocol @@ -251,7 +274,8 @@ - (void)prepareForRecycle { [super prepareForRecycle]; _keyboardInset = 0; - _restingHeight = 0; + _settledInset = 0; + _heightWithoutKeyboard = 0; } @end 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 index b0c43aac1c0b..871db6f1cd0c 100644 --- 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 @@ -16,6 +16,7 @@ internal class KeyboardInsetChangeEvent( viewTag: Int, private val inset: Float, private val maxHeight: Float, + private val settledInset: Float, ) : Event(surfaceId, viewTag) { override fun getEventName(): String = EVENT_NAME @@ -24,6 +25,7 @@ internal class KeyboardInsetChangeEvent( Arguments.createMap().apply { putDouble("inset", inset.toDouble()) putDouble("maxHeight", maxHeight.toDouble()) + putDouble("settledInset", settledInset.toDouble()) } companion object { 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 index 76151daf8b0e..0164dbb9fe47 100644 --- 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 @@ -42,8 +42,10 @@ internal class ReactKeyboardAvoidingView(context: Context) : ReactViewGroup(cont // 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 restingHeight = 0f + private var heightWithoutKeyboard = 0f private val updateRunnable = Runnable { isUpdateScheduled = false @@ -68,6 +70,21 @@ internal class ReactKeyboardAvoidingView(context: Context) : ReactViewGroup(cont } } + 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, @@ -134,28 +151,42 @@ internal class ReactKeyboardAvoidingView(context: Context) : ReactViewGroup(cont val frameY = top.toFloat().pxToDp() val keyboardY = rootView.height.toFloat().pxToDp() - keyboardHeight - keyboardVerticalOffset - return maxOf(frameY + restingHeight - keyboardY, 0f) + return maxOf(frameY + heightWithoutKeyboard - keyboardY, 0f) } @UiThread private fun updateKeyboardInset(keyboardHeight: Float) { if (keyboardInset == 0f) { - restingHeight = height.toFloat().pxToDp() + heightWithoutKeyboard = height.toFloat().pxToDp() } val inset = if (isAvoidanceEnabled) keyboardOverlap(keyboardHeight) else 0f + dispatchInsetChange(inset, if (!isAnimating || inset == 0f) inset else settledInset) + } - if (inset == keyboardInset) { + @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 - val maxHeight = if (inset > 0f) maxOf(restingHeight - inset, 0f) else Float.POSITIVE_INFINITY + settledInset = settled + + val maxHeight = + if (inset > 0f) maxOf(heightWithoutKeyboard - inset, 0f) else Float.POSITIVE_INFINITY eventDispatcher.dispatchEvent( - KeyboardInsetChangeEvent(UIManagerHelper.getSurfaceId(this), id, inset, maxHeight) + KeyboardInsetChangeEvent( + UIManagerHelper.getSurfaceId(this), + id, + inset, + maxHeight, + settled, + ) ) } } 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 index 9f4029d0b9c2..080a90c9f78f 100644 --- a/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js +++ b/packages/react-native/src/private/components/keyboardavoidingview/specs/KeyboardAvoidingViewNativeComponent.js @@ -21,6 +21,7 @@ import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNa type KeyboardInsetChangeEvent = Readonly<{ inset: Float, maxHeight: Float, + settledInset: Float, }>; type KeyboardAvoidingViewNativeProps = Readonly<{ diff --git a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js index 8b1a9b201a0a..a643dc5307b4 100644 --- a/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js +++ b/packages/rn-tester/js/examples/KeyboardAvoidingView/KeyboardAvoidingViewExample.js @@ -11,12 +11,14 @@ '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, @@ -95,11 +97,7 @@ const BehaviorPicker = (props: { }) => { return ( - + {BEHAVIORS.map(behavior => { const selected = props.behavior === behavior; return ( @@ -265,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} + /> + + + + +