diff --git a/packages/react-native/Libraries/Modal/Modal.js b/packages/react-native/Libraries/Modal/Modal.js index dc855add3d06..6441b8f3aa5d 100644 --- a/packages/react-native/Libraries/Modal/Modal.js +++ b/packages/react-native/Libraries/Modal/Modal.js @@ -80,8 +80,13 @@ type ModalBasePropsCore = { onShow?: ?DirectEventHandler, /** - * The backdrop color of the modal's container. Defaults to `white` if - * `transparent` is `false`. Ignored if `transparent` is `true`. + * The backdrop color of the modal's container. Ignored if `transparent` is + * `true`. On Android, this overrides the transparent background implied by + * an explicit `dimAmount`. + * + * @deprecated Prefer `style={{backgroundColor: ...}}` for the container + * color. On Android, keep using `backdropColor` if you need a custom color + * while setting `dimAmount`. */ backdropColor?: ColorValue, @@ -155,6 +160,37 @@ export type ModalPropsIOS = { }; export type ModalPropsAndroid = { + /** + * Size the native window to its content instead of filling the parent. + * The window is not shown and `onShow` does not fire until the content + * measures to a positive width and height. + * + * @default `false` + * @platform android + */ + contentSized?: ?boolean, + + /** + * Request closing on a completed outside tap when `contentSized` is enabled. + * The callback must update `visible` to dismiss the modal. Outside taps + * do not reach the presenting screen, even when dismissal is disabled. + * + * @default `false` + * @platform android + */ + dismissOnClickOutside?: ?boolean, + + /** + * Amount of system dimming behind the modal, between 0 and 1. + * Ignored if `transparent` is `true`. When set, the modal's container + * defaults to a transparent background instead of `white`, unless + * `backdropColor` is set. + * + * @default `0.5` + * @platform android + */ + dimAmount?: ?number, + /** * Controls whether to force hardware acceleration for the underlying window. * @@ -285,15 +321,17 @@ class Modal extends React.Component { return null; } - // Only override backgroundColor when transparent or backdropColor are - // explicitly set, so that these Modal-specific props take precedence - // over the generic style prop. The default backgroundColor ('white') - // is defined in styles.container below. + // Only override backgroundColor when transparent, backdropColor or + // dimAmount are explicitly set, so that these Modal-specific props take + // precedence over the generic style prop. The default backgroundColor + // ('white') is defined in styles.container below. const containerStyles: {backgroundColor?: ColorValue} = {}; if (this.props.transparent === true) { containerStyles.backgroundColor = 'transparent'; } else if (this.props.backdropColor != null) { containerStyles.backgroundColor = this.props.backdropColor; + } else if (Platform.OS === 'android' && this.props.dimAmount != null) { + containerStyles.backgroundColor = 'transparent'; } let animationType = this.props.animationType || 'none'; @@ -330,6 +368,9 @@ class Modal extends React.Component { animationType={animationType} presentationStyle={presentationStyle} transparent={this.props.transparent} + dimAmount={this.props.dimAmount} + contentSized={Platform.OS === 'android' && this.props.contentSized} + dismissOnClickOutside={this.props.dismissOnClickOutside} hardwareAccelerated={this.props.hardwareAccelerated} onRequestClose={this.props.onRequestClose} onShow={this.props.onShow} @@ -351,7 +392,13 @@ class Modal extends React.Component { {innerChildren} diff --git a/packages/react-native/Libraries/Modal/__tests__/Modal-itest.js b/packages/react-native/Libraries/Modal/__tests__/Modal-itest.js index 34e268d2442a..a024f4e95a9b 100644 --- a/packages/react-native/Libraries/Modal/__tests__/Modal-itest.js +++ b/packages/react-native/Libraries/Modal/__tests__/Modal-itest.js @@ -49,6 +49,149 @@ describe('', () => { , ); }); + + describe('dismissOnClickOutside', () => { + it('forwards outside-press dismissal and resets when removed', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['dismissOnClickOutside']}).toJSX(), + ).toEqual( + + + , + ); + + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['dismissOnClickOutside']}).toJSX(), + ).toEqual( + + + , + ); + }); + }); + + describe('dimAmount', () => { + it('forwards a custom dim amount and resets to the default when removed', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect(root.getRenderedOutput({props: ['dimAmount']}).toJSX()).toEqual( + + + , + ); + + Fantom.runTask(() => { + root.render(); + }); + + expect(root.getRenderedOutput({props: ['dimAmount']}).toJSX()).toEqual( + + + , + ); + }); + + it('defaults the container to a transparent background', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['backgroundColor']}).toJSX(), + ).toEqual( + + + , + ); + }); + + it('keeps an explicit backdropColor', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['backgroundColor']}).toJSX(), + ).toEqual( + + + , + ); + }); + }); + + describe('contentSized', () => { + it('forwards content sizing and resets when removed', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['contentSized']}).toJSX(), + ).toEqual( + + + , + ); + + Fantom.runTask(() => { + root.render(); + }); + + expect( + root.getRenderedOutput({props: ['contentSized']}).toJSX(), + ).toEqual( + + + , + ); + }); + + it('does not apply the default container style', () => { + Fantom.runTask(() => { + root.render(); + }); + + expect( + root + .getRenderedOutput({ + props: ['backgroundColor', 'flex', 'left', 'top'], + }) + .toJSX(), + ).toEqual( + + + , + ); + }); + + it('keeps a style backgroundColor', () => { + Fantom.runTask(() => { + root.render( + , + ); + }); + + expect( + root.getRenderedOutput({props: ['backgroundColor']}).toJSX(), + ).toEqual( + + + , + ); + }); + }); + describe('animationType', () => { it('renders a Modal with animationType="none" by default', () => { Fantom.runTask(() => { diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index e5609d383c48..a58702262951 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -5128,6 +5128,9 @@ public class com/facebook/react/viewmanagers/ModalHostViewManagerDelegate : com/ public abstract interface class com/facebook/react/viewmanagers/ModalHostViewManagerInterface : com/facebook/react/uimanager/ViewManagerWithGeneratedInterface { public abstract fun setAllowSwipeDismissal (Landroid/view/View;Z)V public abstract fun setAnimationType (Landroid/view/View;Ljava/lang/String;)V + public abstract fun setContentSized (Landroid/view/View;Z)V + public abstract fun setDimAmount (Landroid/view/View;F)V + public abstract fun setDismissOnClickOutside (Landroid/view/View;Z)V public abstract fun setHardwareAccelerated (Landroid/view/View;Z)V public abstract fun setIdentifier (Landroid/view/View;I)V public abstract fun setNavigationBarTranslucent (Landroid/view/View;Z)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.kt index a1beb0b6922b..fd2201aabdeb 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.kt @@ -49,6 +49,11 @@ internal class ReactModalHostManager : view.transparent = value } + @ReactProp(name = "dimAmount", defaultFloat = 0.5f) + override fun setDimAmount(view: ReactModalHostView, value: Float) { + view.dimAmount = value + } + @ReactProp(name = "statusBarTranslucent") override fun setStatusBarTranslucent(view: ReactModalHostView, value: Boolean) { view.statusBarTranslucent = value @@ -69,6 +74,16 @@ internal class ReactModalHostManager : // iOS only } + @ReactProp(name = "contentSized", defaultBoolean = false) + override fun setContentSized(view: ReactModalHostView, value: Boolean) { + view.contentSized = value + } + + @ReactProp(name = "dismissOnClickOutside", defaultBoolean = false) + override fun setDismissOnClickOutside(view: ReactModalHostView, value: Boolean) { + view.dismissOnClickOutside = value + } + @ReactProp(name = "presentationStyle") override fun setPresentationStyle(view: ReactModalHostView, value: String?): Unit = Unit diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt index 0cd7342ccb7e..68fc2159275a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.kt @@ -15,6 +15,8 @@ import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.os.Build +import android.view.GestureDetector +import android.view.Gravity import android.view.KeyEvent import android.view.MotionEvent import android.view.View @@ -77,9 +79,20 @@ public class ReactModalHostView(context: ThemedReactContext) : private set public var transparent: Boolean = false + internal var dimAmount: Float = 0.5f public var onShowListener: DialogInterface.OnShowListener? = null public var onRequestCloseListener: OnRequestCloseListener? = null + internal var contentSized: Boolean = false + set(value) { + if (field != value) { + field = value + createNewDialog = true + } + } + + internal var dismissOnClickOutside: Boolean = false + public var statusBarTranslucent: Boolean = false get() = field || isEdgeToEdgeFeatureFlagOn set(value) { @@ -125,6 +138,7 @@ public class ReactModalHostView(context: ThemedReactContext) : // creation through the theme // but transparency does not since we can access the window to update the property. private var createNewDialog = false + private var dropped = false init { dialogRootViewGroup = DialogRootViewGroup(context) @@ -137,7 +151,31 @@ public class ReactModalHostView(context: ThemedReactContext) : override fun shouldDelayChildPressedState(): Boolean = false protected override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { - // Do nothing as we are laid out by UIManager + if (!contentSized || !hasContentSizedBounds()) { + return + } + + if (dialog == null) { + showOrUpdate() + } else if (changed) { + resizeContentSizedDialog() + } + } + + private fun hasContentSizedBounds(): Boolean = + isAttachedToWindow && !dropped && width > 0 && height > 0 + + private fun resizeContentSizedDialog() { + val currentDialog = dialog ?: return + val window = currentDialog.window ?: return + if (!currentDialog.isShowing || window.peekDecorView()?.isAttachedToWindow != true) { + return + } + try { + window.setLayout(width, height) + } catch (e: IllegalArgumentException) { + FLog.e(TAG, "ReactModalHostView: error while resizing dialog: ", e.message) + } } override fun setId(id: Int) { @@ -149,7 +187,11 @@ public class ReactModalHostView(context: ThemedReactContext) : protected override fun onAttachedToWindow() { super.onAttachedToWindow() + dropped = false (context as ThemedReactContext).addLifecycleEventListener(this) + if (contentSized && dialog == null) { + showOrUpdate() + } } protected override fun onDetachedFromWindow() { @@ -190,6 +232,7 @@ public class ReactModalHostView(context: ThemedReactContext) : public override fun dispatchPopulateAccessibilityEvent(event: AccessibilityEvent): Boolean = false public fun onDropInstance() { + dropped = true (context as ThemedReactContext).removeLifecycleEventListener(this) dismiss() } @@ -257,6 +300,13 @@ public class ReactModalHostView(context: ThemedReactContext) : public fun showOrUpdate() { UiThreadUtil.assertOnUiThread() + val currentActivity = getCurrentActivity() + val activityCanShow = + currentActivity != null && !currentActivity.isFinishing && !currentActivity.isDestroyed + if (contentSized && (!hasContentSizedBounds() || !activityCanShow)) { + return + } + // If the existing Dialog is currently up, we may need to redraw it or we may be able to update // the property without having to recreate the dialog if (createNewDialog) { @@ -280,8 +330,9 @@ public class ReactModalHostView(context: ThemedReactContext) : else -> R.style.Theme_FullScreenDialog } - val currentActivity = getCurrentActivity() - val newDialog = ComponentDialog(currentActivity ?: context, theme) + val newDialog = + if (contentSized) ReactModalDialog(currentActivity ?: context, theme) + else ComponentDialog(currentActivity ?: context, theme) dialog = newDialog val window = requireNotNull(newDialog.window) window.setFlags( @@ -290,6 +341,11 @@ public class ReactModalHostView(context: ThemedReactContext) : ) newDialog.setContentView(contentView) + if (contentSized) { + newDialog.setCanceledOnTouchOutside(false) + window.setLayout(width, height) + window.setGravity(Gravity.CENTER) + } updateProperties() newDialog.setOnShowListener(onShowListener) @@ -348,7 +404,7 @@ public class ReactModalHostView(context: ThemedReactContext) : WindowManager.LayoutParams.FLAG_SECURE, ) } - if (currentActivity?.isFinishing == false) { + if (activityCanShow) { newDialog.show() updateSystemAppearance() window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) @@ -409,14 +465,12 @@ public class ReactModalHostView(context: ThemedReactContext) : dialogWindow.setStatusBarTranslucency(statusBarTranslucent) } + // Transparent modals are never dimmed. if (transparent) { dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) } else { - dialogWindow.setDimAmount(0.5f) - dialogWindow.setFlags( - WindowManager.LayoutParams.FLAG_DIM_BEHIND, - WindowManager.LayoutParams.FLAG_DIM_BEHIND, - ) + dialogWindow.setDimAmount(dimAmount.coerceIn(0f, 1f)) + dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) } } catch (e: IllegalArgumentException) { // This is to prevent a crash from the following error, without a clear repro steps: @@ -502,6 +556,52 @@ public class ReactModalHostView(context: ThemedReactContext) : private const val TAG = "ReactModalHost" } + private inner class ReactModalDialog(context: Context, theme: Int) : + ComponentDialog(context, theme) { + private var outsideGesture = false + private val outsideTapDetector = + GestureDetector( + context, + object : GestureDetector.SimpleOnGestureListener() { + override fun onDown(event: MotionEvent): Boolean = true + + override fun onSingleTapUp(event: MotionEvent): Boolean { + if (dismissOnClickOutside && isOutsideWindow(event)) { + onRequestCloseListener?.onRequestClose(this@ReactModalDialog) + } + return true + } + }, + ) + .apply { setOnDoubleTapListener(null) } + + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + when (event.actionMasked) { + // Android's outside-cancel API can close on this one-shot notification, which does + // not tell us whether a tap completed. Keep the window modal but don't close here. + MotionEvent.ACTION_OUTSIDE -> return true + MotionEvent.ACTION_DOWN -> outsideGesture = isOutsideWindow(event) + } + if (!outsideGesture) { + return super.dispatchTouchEvent(event) + } + + outsideTapDetector.onTouchEvent(event) + if ( + event.actionMasked == MotionEvent.ACTION_UP || + event.actionMasked == MotionEvent.ACTION_CANCEL + ) { + outsideGesture = false + } + return true + } + + private fun isOutsideWindow(event: MotionEvent): Boolean { + val decor = window?.decorView ?: return false + return event.x < 0 || event.y < 0 || event.x >= decor.width || event.y >= decor.height + } + } + /** * DialogRootViewGroup is the ViewGroup which contains all the children of a Modal. It gets all * child information forwarded from [ReactModalHostView] and uses that to create children. It is diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/ReactModalHostViewContentSizedTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/ReactModalHostViewContentSizedTest.kt new file mode 100644 index 000000000000..afad53a10ef6 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/views/modal/ReactModalHostViewContentSizedTest.kt @@ -0,0 +1,211 @@ +/* + * 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.modal + +import android.app.Activity +import android.app.Dialog +import android.content.DialogInterface +import android.os.Looper +import android.os.SystemClock +import android.view.MotionEvent +import android.view.WindowManager +import android.widget.FrameLayout +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactTestHelper.createTestReactApplicationContext +import com.facebook.react.bridge.queue.MessageQueueThread +import com.facebook.react.bridge.queue.ReactQueueConfiguration +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import com.facebook.react.uimanager.DisplayMetricsHolder +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.soloader.SoLoader +import com.facebook.testutils.shadows.ShadowSoLoader +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(shadows = [ShadowSoLoader::class]) +class ReactModalHostViewContentSizedTest { + private lateinit var controller: ActivityController + private lateinit var reactContext: ReactApplicationContext + private lateinit var parent: FrameLayout + private lateinit var host: ReactModalHostView + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + SoLoader.setInTestMode() + controller = Robolectric.buildActivity(Activity::class.java).setup() + val activity = controller.get() + DisplayMetricsHolder.initDisplayMetrics(activity) + reactContext = createTestReactApplicationContext() + parent = FrameLayout(activity) + activity.setContentView(parent) + val themedContext = ThemedReactContext(reactContext, activity, null, -1) + // This fixture doesn't start a React instance; supply its queues for dialog layout callbacks. + val queueThread = mock() + val queues = mock() + whenever(queues.getUIQueueThread()).thenReturn(queueThread) + whenever(queues.getNativeModulesQueueThread()).thenReturn(queueThread) + whenever(queues.getJSQueueThread()).thenReturn(queueThread) + themedContext.initializeMessageQueueThreads(queues) + host = ReactModalHostView(themedContext) + host.contentSized = true + parent.addView(host, FrameLayout.LayoutParams(120, 0)) + reactContext.onHostResume(activity) + } + + @After + fun tearDown() { + host.onDropInstance() + if (!controller.get().isDestroyed) { + controller.pause().stop().destroy() + } + } + + @Test + fun waitsForPositiveBoundsBeforeShowing() { + var showCount = 0 + host.onShowListener = DialogInterface.OnShowListener { showCount++ } + host.showOrUpdate() + host.layout(0, 0, 120, 0) + shadowOf(Looper.getMainLooper()).idle() + assertThat(host.dialog).isNull() + assertThat(showCount).isZero() + + host.layoutParams = FrameLayout.LayoutParams(120, 80) + host.layout(0, 0, 120, 80) + shadowOf(Looper.getMainLooper()).idle() + assertThat(host.dialog?.isShowing).isTrue() + val dialog = checkNotNull(host.dialog) + assertThat(dialog.window?.attributes?.width).isEqualTo(120) + assertThat(dialog.window?.attributes?.height).isEqualTo(80) + assertThat(showCount).isEqualTo(1) + + host.layoutParams = FrameLayout.LayoutParams(160, 100) + host.layout(0, 0, 160, 100) + shadowOf(Looper.getMainLooper()).idle() + assertThat(host.dialog).isSameAs(dialog) + assertThat(dialog.window?.attributes?.width).isEqualTo(160) + assertThat(dialog.window?.attributes?.height).isEqualTo(100) + assertThat(showCount).isEqualTo(1) + } + + @Test + fun detachedLayoutDoesNotReopenDialog() { + host.showOrUpdate() + host.layout(0, 0, 120, 80) + assertThat(host.dialog?.isShowing).isTrue() + + parent.removeView(host) + host.layout(0, 0, 160, 100) + assertThat(host.dialog).isNull() + } + + @Test + fun layoutAfterHostDestroyDoesNotReopenDialog() { + host.showOrUpdate() + host.layout(0, 0, 120, 80) + assertThat(host.dialog?.isShowing).isTrue() + + host.onHostDestroy() + assertThat(host.isAttachedToWindow).isTrue() + host.layout(0, 0, 160, 100) + assertThat(host.dialog).isNull() + } + + @Test + fun completedOutsideTapRequestsCloseWithoutDismissing() { + val dialog = showContentSizedDialog() + var closeRequests = 0 + host.onRequestCloseListener = ReactModalHostView.OnRequestCloseListener { closeRequests++ } + host.dismissOnClickOutside = true + val down = SystemClock.uptimeMillis() + + assertThat(dialog.sendTouch(down, MotionEvent.ACTION_DOWN)).isTrue() + assertThat(closeRequests).isZero() + assertThat(dialog.sendTouch(down, MotionEvent.ACTION_UP)).isTrue() + + assertThat(closeRequests).isEqualTo(1) + assertThat(dialog.isShowing).isTrue() + } + + @Test + fun outsideNotificationsAndCanceledOrDraggedGesturesDoNotRequestClose() { + val dialog = showContentSizedDialog() + var closeRequests = 0 + host.onRequestCloseListener = ReactModalHostView.OnRequestCloseListener { closeRequests++ } + host.dismissOnClickOutside = true + + val canceledDown = SystemClock.uptimeMillis() + dialog.sendTouch(canceledDown, MotionEvent.ACTION_DOWN) + dialog.sendTouch(canceledDown, MotionEvent.ACTION_CANCEL) + dialog.sendTouch(canceledDown, MotionEvent.ACTION_OUTSIDE) + + val dragDown = canceledDown + 100 + dialog.sendTouch(dragDown, MotionEvent.ACTION_DOWN) + dialog.sendTouch(dragDown, MotionEvent.ACTION_MOVE, x = 10f) + dialog.sendTouch(dragDown, MotionEvent.ACTION_UP) + + assertThat(closeRequests).isZero() + assertThat(dialog.isShowing).isTrue() + } + + @Test + fun disablingOutsideDismissalKeepsDialogTouchModal() { + val dialog = showContentSizedDialog() + var closeRequests = 0 + host.onRequestCloseListener = ReactModalHostView.OnRequestCloseListener { closeRequests++ } + val down = SystemClock.uptimeMillis() + + assertThat(dialog.sendTouch(down, MotionEvent.ACTION_DOWN)).isTrue() + assertThat(dialog.sendTouch(down, MotionEvent.ACTION_UP)).isTrue() + val flags = checkNotNull(dialog.window).attributes.flags + assertThat(flags and WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL).isZero() + assertThat(closeRequests).isZero() + assertThat(dialog.isShowing).isTrue() + } + + private fun showContentSizedDialog(): Dialog { + host.layoutParams = FrameLayout.LayoutParams(120, 80) + host.layout(0, 0, 120, 80) + shadowOf(Looper.getMainLooper()).idle() + val dialog = checkNotNull(host.dialog) + val decor = checkNotNull(dialog.window).decorView + decor.layout(0, 0, 120, 80) + return dialog + } + + private fun Dialog.sendTouch(down: Long, action: Int, x: Float = -40f): Boolean { + val event = MotionEvent.obtain(down, down + 10, action, x, 40f, 0) + try { + return dispatchTouchEvent(event) + } finally { + event.recycle() + } + } + + @Test + fun layoutWithDestroyedCurrentActivityDoesNotCreateDialog() { + // Keep the original, live host view attached while React points at a destroyed Activity. + val destroyed = Robolectric.buildActivity(Activity::class.java).create().destroy().get() + reactContext.onHostResume(destroyed) + host.showOrUpdate() + host.layout(0, 0, 120, 80) + assertThat(host.dialog).isNull() + } +} diff --git a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h index 7300b59588cd..28d5b694594f 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/components/modal/ModalHostViewComponentDescriptor.h @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -28,7 +29,10 @@ class ModalHostViewComponentDescriptor final : public ConcreteComponentDescripto auto &layoutableShadowNode = static_cast(shadowNode); auto &stateData = static_cast(*shadowNode.getState()).getData(); - layoutableShadowNode.setSize(Size{.width = stateData.screenSize.width, .height = stateData.screenSize.height}); + const auto &props = static_cast(*shadowNode.getProps()); + if (!folly::kIsAndroid || !props.contentSized) { + layoutableShadowNode.setSize(Size{.width = stateData.screenSize.width, .height = stateData.screenSize.height}); + } layoutableShadowNode.setPositionType(YGPositionTypeAbsolute); ConcreteComponentDescriptor::adopt(shadowNode); diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index b5127f242a2f..f0116dd81cfd 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<<08c63097104ab811ba2be19ded117820>> + * @generated SignedSource<<3e22e0e6d2cd0efb4e8d08d3970d2315>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -3134,6 +3134,9 @@ declare type ModalProps = ModalBaseProps & ModalPropsAndroid & ViewProps declare type ModalPropsAndroid = { + contentSized?: boolean + dimAmount?: number + dismissOnClickOutside?: boolean hardwareAccelerated?: boolean navigationBarTranslucent?: boolean statusBarTranslucent?: boolean @@ -6027,11 +6030,11 @@ export { MeasureInWindowOnSuccessCallback, // a285f598 MeasureLayoutOnSuccessCallback, // 3592502a MeasureOnSuccessCallback, // 82824e59 - Modal, // 7910201f + Modal, // dc3590eb ModalBaseProps, // 18ba4525 ModalInstance, // c47ff608 - ModalProps, // 9d78b278 - ModalPropsAndroid, // 515fb173 + ModalProps, // 6491f64b + ModalPropsAndroid, // 0dd34549 ModalPropsIOS, // 7943cbd7 ModeChangeEvent, // 9e9a28c4 MouseEvent, // 420b6a25 diff --git a/packages/react-native/src/private/components/modal/specs/RCTModalHostViewNativeComponent.js b/packages/react-native/src/private/components/modal/specs/RCTModalHostViewNativeComponent.js index c8f274c82332..0b2cdc323546 100644 --- a/packages/react-native/src/private/components/modal/specs/RCTModalHostViewNativeComponent.js +++ b/packages/react-native/src/private/components/modal/specs/RCTModalHostViewNativeComponent.js @@ -11,6 +11,7 @@ import type {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; import type { DirectEventHandler, + Float, Int32, WithDefault, } from '../../../../../Libraries/Types/CodegenTypes'; @@ -50,6 +51,9 @@ type RCTModalHostViewNativeProps = Readonly<{ */ transparent?: WithDefault, + /** Amount of Android system dimming behind a non-transparent modal. */ + dimAmount?: WithDefault, + /** * The `statusBarTranslucent` prop determines whether your modal should go under * the system statusbar. @@ -74,6 +78,12 @@ type RCTModalHostViewNativeProps = Readonly<{ */ hardwareAccelerated?: WithDefault, + /** Whether the Android window should match the modal content bounds. */ + contentSized?: WithDefault, + + /** Whether a completed outside tap invokes `onRequestClose` on Android. */ + dismissOnClickOutside?: WithDefault, + /** * The `onRequestClose` callback is called when the user taps the hardware * back button on Android or the menu button on Apple TV. diff --git a/packages/react-native/types_DEPRECATED/Libraries/Modal/Modal.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Modal/Modal.d.ts index e60f63145fa5..486985dde899 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Modal/Modal.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Modal/Modal.d.ts @@ -42,8 +42,13 @@ export interface ModalBaseProps { onShow?: ((event: NativeSyntheticEvent) => void) | undefined; /** - * The `backdropColor` props sets the background color of the modal's container. - * Defaults to `white` if not provided and transparent is `false`. Ignored if `transparent` is `true`. + * The backdrop color of the modal's container. Ignored if `transparent` is + * `true`. On Android, this overrides the transparent background implied by + * an explicit `dimAmount`. + * + * @deprecated Prefer `style={{backgroundColor: ...}}` for the container + * color. On Android, keep using `backdropColor` if you need a custom color + * while setting `dimAmount`. */ backdropColor?: ColorValue | undefined; @@ -94,6 +99,31 @@ export interface ModalPropsIOS { } export interface ModalPropsAndroid { + /** + * Sizes the Android window to its content instead of the parent window. + * The window is not shown and `onShow` does not fire until the content + * measures to a positive width and height. + * @platform android + */ + contentSized?: boolean | undefined; + + /** + * Invokes `onRequestClose` for a completed outside tap on a content-sized window. + * Outside taps do not reach the presenting screen, even when dismissal is disabled. + * @platform android + */ + dismissOnClickOutside?: boolean | undefined; + + /** + * Amount of system dimming behind the modal, between 0 and 1. + * Ignored if `transparent` is `true`. When set, the modal's container + * defaults to a transparent background instead of `white`, unless + * `backdropColor` is set. + * @default 0.5 + * @platform android + */ + dimAmount?: number | undefined; + /** * Controls whether to force hardware acceleration for the underlying window. */ diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index f214d60a07cd..8f736f7e7e45 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -1849,11 +1849,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index f1811b25c34a..65ffcc9fc606 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -2754,11 +2754,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 2ef1680b9010..4d2a1fc0dd37 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -1848,11 +1848,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 2ef1680b9010..4d2a1fc0dd37 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -1848,11 +1848,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 5fb34f123790..5d00d7cbb02a 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -4114,11 +4114,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index c191f3f7f57e..5cb466ee0315 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -4950,11 +4950,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 9f2987431905..e54d4e464b83 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -4106,11 +4106,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 1bfb2638d899..cf89c44ac5a6 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -4113,11 +4113,14 @@ class facebook::react::ModalHostViewProps : public facebook::react::HostPlatform public ModalHostViewProps() = default; public ModalHostViewProps(const facebook::react::PropsParserContext& context, const facebook::react::ModalHostViewProps& sourceProps, const facebook::react::RawProps& rawProps); public bool allowSwipeDismissal; + public bool contentSized; + public bool dismissOnClickOutside; public bool hardwareAccelerated; public bool navigationBarTranslucent; public bool statusBarTranslucent; public bool transparent; public bool visible; + public facebook::react::Float dimAmount; public facebook::react::ModalHostViewAnimationType animationType; public facebook::react::ModalHostViewPresentationStyle presentationStyle; public facebook::react::ModalHostViewSupportedOrientationsMask supportedOrientations;