Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions packages/react-native/Libraries/Modal/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,13 @@ type ModalBasePropsCore = {
onShow?: ?DirectEventHandler<null>,

/**
* 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,

Expand Down Expand Up @@ -155,6 +160,27 @@ 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,

/**
* 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.
*
Expand Down Expand Up @@ -285,15 +311,17 @@ class Modal extends React.Component<ModalProps, ModalState> {
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';
Expand Down Expand Up @@ -330,6 +358,8 @@ class Modal extends React.Component<ModalProps, ModalState> {
animationType={animationType}
presentationStyle={presentationStyle}
transparent={this.props.transparent}
dimAmount={this.props.dimAmount}
contentSized={Platform.OS === 'android' && this.props.contentSized}
hardwareAccelerated={this.props.hardwareAccelerated}
onRequestClose={this.props.onRequestClose}
onShow={this.props.onShow}
Expand All @@ -351,7 +381,13 @@ class Modal extends React.Component<ModalProps, ModalState> {
<ScrollView.Context.Provider value={null}>
<View
// $FlowFixMe[incompatible-type]
style={[styles.container, this.props.style, containerStyles]}
style={[
Platform.OS === 'android' && this.props.contentSized === true
? null
: styles.container,
this.props.style,
containerStyles,
]}
collapsable={false}>
{innerChildren}
</View>
Expand Down
115 changes: 115 additions & 0 deletions packages/react-native/Libraries/Modal/__tests__/Modal-itest.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,121 @@ describe('<Modal>', () => {
</rn-modalHostView>,
);
});

describe('dimAmount', () => {
it('forwards a custom dim amount and resets to the default when removed', () => {
Fantom.runTask(() => {
root.render(<Modal dimAmount={0.6} />);
});

expect(root.getRenderedOutput({props: ['dimAmount']}).toJSX()).toEqual(
<rn-modalHostView dimAmount="0.6">
<rn-view />
</rn-modalHostView>,
);

Fantom.runTask(() => {
root.render(<Modal />);
});

expect(root.getRenderedOutput({props: ['dimAmount']}).toJSX()).toEqual(
<rn-modalHostView>
<rn-view />
</rn-modalHostView>,
);
});

it('defaults the container to a transparent background', () => {
Fantom.runTask(() => {
root.render(<Modal dimAmount={0.6} />);
});

expect(
root.getRenderedOutput({props: ['backgroundColor']}).toJSX(),
).toEqual(
<rn-modalHostView>
<rn-view />
</rn-modalHostView>,
);
});

it('keeps an explicit backdropColor', () => {
Fantom.runTask(() => {
root.render(<Modal dimAmount={0.6} backdropColor="red" />);
});

expect(
root.getRenderedOutput({props: ['backgroundColor']}).toJSX(),
).toEqual(
<rn-modalHostView>
<rn-view backgroundColor="rgba(255, 0, 0, 1)" />
</rn-modalHostView>,
);
});
});

describe('contentSized', () => {
it('forwards content sizing and resets when removed', () => {
Fantom.runTask(() => {
root.render(<Modal contentSized={true} />);
});

expect(
root.getRenderedOutput({props: ['contentSized']}).toJSX(),
).toEqual(
<rn-modalHostView contentSized="true">
<rn-view />
</rn-modalHostView>,
);

Fantom.runTask(() => {
root.render(<Modal />);
});

expect(
root.getRenderedOutput({props: ['contentSized']}).toJSX(),
).toEqual(
<rn-modalHostView>
<rn-view />
</rn-modalHostView>,
);
});

it('does not apply the default container style', () => {
Fantom.runTask(() => {
root.render(<Modal contentSized={true} />);
});

expect(
root
.getRenderedOutput({
props: ['backgroundColor', 'flex', 'left', 'top'],
})
.toJSX(),
).toEqual(
<rn-modalHostView>
<rn-view />
</rn-modalHostView>,
);
});

it('keeps a style backgroundColor', () => {
Fantom.runTask(() => {
root.render(
<Modal contentSized={true} style={{backgroundColor: 'red'}} />,
);
});

expect(
root.getRenderedOutput({props: ['backgroundColor']}).toJSX(),
).toEqual(
<rn-modalHostView>
<rn-view backgroundColor="rgba(255, 0, 0, 1)" />
</rn-modalHostView>,
);
});
});

describe('animationType', () => {
it('renders a Modal with animationType="none" by default', () => {
Fantom.runTask(() => {
Expand Down
2 changes: 2 additions & 0 deletions packages/react-native/ReactAndroid/api/ReactAndroid.api
Original file line number Diff line number Diff line change
Expand Up @@ -5128,6 +5128,8 @@ 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 setHardwareAccelerated (Landroid/view/View;Z)V
public abstract fun setIdentifier (Landroid/view/View;I)V
public abstract fun setNavigationBarTranslucent (Landroid/view/View;Z)V
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -69,6 +74,11 @@ internal class ReactModalHostManager :
// iOS only
}

@ReactProp(name = "contentSized", defaultBoolean = false)
override fun setContentSized(view: ReactModalHostView, value: Boolean) {
view.contentSized = value
}

@ReactProp(name = "presentationStyle")
override fun setPresentationStyle(view: ReactModalHostView, value: String?): Unit = Unit

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Build
import android.view.Gravity
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
Expand Down Expand Up @@ -77,9 +78,18 @@ 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
}
}

public var statusBarTranslucent: Boolean = false
get() = field || isEdgeToEdgeFeatureFlagOn
set(value) {
Expand Down Expand Up @@ -125,6 +135,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)
Expand All @@ -137,7 +148,36 @@ 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 {
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) {
return
}
val attributes = window.attributes
if (attributes.width == width && attributes.height == height) {
return
}
// Fabric can deliver the new bounds before a just-shown dialog's decor attaches.
try {
window.setLayout(width, height)
} catch (e: IllegalArgumentException) {
FLog.e(TAG, "ReactModalHostView: error while resizing dialog: ", e.message)
}
}

override fun setId(id: Int) {
Expand All @@ -149,7 +189,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() {
Expand Down Expand Up @@ -190,6 +234,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()
}
Expand Down Expand Up @@ -257,6 +302,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) {
Expand All @@ -280,7 +332,6 @@ public class ReactModalHostView(context: ThemedReactContext) :
else -> R.style.Theme_FullScreenDialog
}

val currentActivity = getCurrentActivity()
val newDialog = ComponentDialog(currentActivity ?: context, theme)
dialog = newDialog
val window = requireNotNull(newDialog.window)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading