Forked from elyesmansour/NonRecomposingSizeModifiers.kt
Created
August 28, 2025 20:58
-
-
Save andreiverdes/e8f45f0c62628cebe9ee131e774de202 to your computer and use it in GitHub Desktop.
Jetpack Compose size modifiers that skip recomposition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.elyesmsr.sizemodifier | |
| import androidx.compose.ui.Modifier | |
| import androidx.compose.ui.layout.layout | |
| import androidx.compose.ui.unit.Constraints | |
| import androidx.compose.ui.unit.Density | |
| import androidx.compose.ui.unit.Dp | |
| import androidx.compose.ui.unit.DpSize | |
| import androidx.compose.ui.unit.constrain | |
| fun Modifier.width(width: () -> Dp) = dpSize { DpSize(width = width(), height = Dp.Unspecified) } | |
| fun Modifier.height(height: () -> Dp) = dpSize { DpSize(height = height(), width = Dp.Unspecified) } | |
| fun Modifier.size(width: () -> Dp, height: () -> Dp) = dpSize { DpSize(width = width(), height = height()) } | |
| fun Modifier.size(size: () -> Dp) = dpSize { DpSize(size(), size()) } | |
| fun Modifier.dpSize(size: () -> DpSize) = layout { measurable, constraints -> | |
| val width = size().width | |
| val height = size().height | |
| val targetConstraints = targetConstraints( | |
| width = width, | |
| height = height, | |
| incomingConstraints = constraints | |
| ) | |
| val placeable = measurable.measure(targetConstraints) | |
| layout(placeable.width, placeable.height) { | |
| placeable.placeRelative(0, 0) | |
| } | |
| } | |
| /** | |
| * Modified version of the code in androidx.compose.foundation.layout.SizeNode | |
| */ | |
| private fun Density.targetConstraints(width: Dp, height: Dp, incomingConstraints: Constraints): Constraints { | |
| val maxWidth = if (width != Dp.Unspecified) { | |
| width.roundToPx().coerceAtLeast(0) | |
| } else { | |
| Constraints.Infinity | |
| } | |
| val maxHeight = if (height != Dp.Unspecified) { | |
| height.roundToPx().coerceAtLeast(0) | |
| } else { | |
| Constraints.Infinity | |
| } | |
| val minWidth = if (width != Dp.Unspecified) { | |
| width.roundToPx().coerceAtMost(maxWidth).coerceAtLeast(0).let { | |
| if (it != Constraints.Infinity) it else 0 | |
| } | |
| } else { | |
| 0 | |
| } | |
| val minHeight = if (height != Dp.Unspecified) { | |
| height.roundToPx().coerceAtMost(maxHeight).coerceAtLeast(0).let { | |
| if (it != Constraints.Infinity) it else 0 | |
| } | |
| } else { | |
| 0 | |
| } | |
| return incomingConstraints.constrain( | |
| Constraints( | |
| minWidth = minWidth, | |
| minHeight = minHeight, | |
| maxWidth = maxWidth, | |
| maxHeight = maxHeight | |
| ) | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment