Shivam Verma
03/29/2024, 3:18 PMCompositionLocal
values from a custom modifier ? It seems a CompositionLocalConsumerModifierNode
can only read CompositionLocal
values.Halil Ozercan
03/29/2024, 4:22 PMZach Klippenstein (he/him) [MOD]
03/29/2024, 5:00 PMZach Klippenstein (he/him) [MOD]
03/29/2024, 5:01 PMShivam Verma
03/30/2024, 7:40 AMShivam Verma
03/30/2024, 1:29 PMalpha = 0.5
. If an ancestor was already disabled using this modifier, I'd like to prevent alpha from being applied to a descendant again.
I would also like to know whether this modifier is applied inside of the composable, so that I can further add disabling behaviors to the composable. I updated the node as follows where I now provide a ModifierLocal
in addition to applying the alpha. A Composable can then read this ModifierLocal
and check if the modifier was applied. Is this a good approach? Are there any improvements I could make?
private class DisabledNode : Modifier.Node(),
ModifierLocalModifierNode,
TraversableNode,
LayoutModifierNode {
private var alphaLayerBlock: GraphicsLayerScope.() -> Unit = { alpha = 0.5f }
private var defaultLayerBlock: GraphicsLayerScope.() -> Unit = {}
override val providedValues: ModifierLocalMap = modifierLocalMapOf(ModifierLocalDisabledState)
override fun MeasureScope.measure(measurable: Measurable, constraints: Constraints): MeasureResult {
val hasDisabledAncestor = findNearestAncestor(traverseKey) != null
if (!hasDisabledAncestor) provide(ModifierLocalDisabledState, State.Disabled)
val placeable = measurable.measure(constraints)
return layout(placeable.width, placeable.height) {
placeable.placeWithLayer(
x = 0,
y = 0,
layerBlock = if (!hasDisabledAncestor) alphaLayerBlock else defaultLayerBlock
)
}
}
override val traverseKey: Any = DragAndDropTraversableKey
companion object {
private object DragAndDropTraversableKey
}
}
Shivam Verma
03/30/2024, 2:20 PMdisabled
modifier is applied to any ancestor.
fun CustomButton() {
var enabled by remember { mutableStateOf(true) }
TextButton(
enabled = enabled,
onClick = {},
modifier = Modifier.modifierLocalConsumer { enabled = ModifierLocalDisabledState.current == State.Enabled }) {
Text(text = "Button")
}
}
Zach Klippenstein (he/him) [MOD]
03/30/2024, 7:28 PMZach Klippenstein (he/him) [MOD]
03/30/2024, 7:28 PMZach Klippenstein (he/him) [MOD]
03/30/2024, 7:29 PMShivam Verma
03/30/2024, 7:42 PMfun Modifier.disabled() = this
.then(Modifier.alpha(0.5f))
.then(Modifier.modifierLocalProvider(ModifierLocalDisabled) { State.Disabled })
@Composable
fun CustomButton(
text: String,
modifier: Modifier = Modifier
) {
var enabled by remember { mutableStateOf(true) }
OutlinedButton(
enabled = enabled,
onClick = {},
modifier = modifier.modifierLocalConsumer { enabled = ModifierLocalDisabled.current == State.Enabled }) {
Text(text = text)
}
}
Zach Klippenstein (he/him) [MOD]
04/01/2024, 1:48 PM