Skip to content

Instantly share code, notes, and snippets.

@elyesmansour
Created March 11, 2025 22:55
Show Gist options
  • Save elyesmansour/43160ae34f7acbec19441b5c1c6de3ab to your computer and use it in GitHub Desktop.
Save elyesmansour/43160ae34f7acbec19441b5c1c6de3ab to your computer and use it in GitHub Desktop.
Jetpack Compose size modifiers that skip recomposition
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