-
Notifications
You must be signed in to change notification settings - Fork 136
/
CustomModifierSnippets.kt
353 lines (309 loc) · 11.8 KB
/
CustomModifierSnippets.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.snippets.modifiers
import android.annotation.SuppressLint
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.tween
import androidx.compose.animation.splineBasedDecay
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.node.CompositionLocalConsumerModifierNode
import androidx.compose.ui.node.DelegatableNode
import androidx.compose.ui.node.DelegatingNode
import androidx.compose.ui.node.DrawModifierNode
import androidx.compose.ui.node.LayoutModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.node.ObserverModifierNode
import androidx.compose.ui.node.currentValueOf
import androidx.compose.ui.node.invalidateDraw
import androidx.compose.ui.node.invalidateMeasurement
import androidx.compose.ui.node.observeReads
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.constrain
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.offset
import kotlinx.coroutines.launch
private object ClipModifierExample {
@SuppressLint("ModifierFactoryUnreferencedReceiver") // graphics layer does the reference
// [START android_compose_custom_modifiers_1]
fun Modifier.clip(shape: Shape) = graphicsLayer(shape = shape, clip = true)
// [END android_compose_custom_modifiers_1]
}
// [START android_compose_custom_modifiers_2]
fun Modifier.myBackground(color: Color) = padding(16.dp)
.clip(RoundedCornerShape(8.dp))
.background(color)
// [END android_compose_custom_modifiers_2]
// [START android_compose_custom_modifiers_3]
@Composable
fun Modifier.fade(enable: Boolean): Modifier {
val alpha by animateFloatAsState(if (enable) 0.5f else 1.0f)
return this then Modifier.graphicsLayer { this.alpha = alpha }
}
// [END android_compose_custom_modifiers_3]
// [START android_compose_custom_modifiers_4]
@Composable
fun Modifier.fadedBackground(): Modifier {
val color = LocalContentColor.current
return this then Modifier.background(color.copy(alpha = 0.5f))
}
// [END android_compose_custom_modifiers_4]
private object CustomModifierSnippets5 {
// [START android_compose_custom_modifiers_5]
@Composable
fun Modifier.myBackground(): Modifier {
val color = LocalContentColor.current
return this then Modifier.background(color.copy(alpha = 0.5f))
}
@Composable
fun MyScreen() {
CompositionLocalProvider(LocalContentColor provides Color.Green) {
// Background modifier created with green background
val backgroundModifier = Modifier.myBackground()
// LocalContentColor updated to red
CompositionLocalProvider(LocalContentColor provides Color.Red) {
// Box will have green background, not red as expected.
Box(modifier = backgroundModifier)
}
}
}
// [END android_compose_custom_modifiers_5]
}
// [START android_compose_custom_modifiers_6]
val extractedModifier = Modifier.background(Color.Red) // Hoisted to save allocations
@Composable
fun Modifier.composableModifier(): Modifier {
val color = LocalContentColor.current.copy(alpha = 0.5f)
return this then Modifier.background(color)
}
@Composable
fun MyComposable() {
val composedModifier = Modifier.composableModifier() // Cannot be extracted any higher
}
// [END android_compose_custom_modifiers_6]
// [START android_compose_custom_modifiers_7]
// Modifier.Node
private class CircleNode(var color: Color) : DrawModifierNode, Modifier.Node() {
override fun ContentDrawScope.draw() {
drawCircle(color)
}
}
// [END android_compose_custom_modifiers_7]
// [START android_compose_custom_modifiers_8]
// ModifierNodeElement
private data class CircleElement(val color: Color) : ModifierNodeElement<CircleNode>() {
override fun create() = CircleNode(color)
override fun update(node: CircleNode) {
node.color = color
}
}
// [END android_compose_custom_modifiers_8]
// [START android_compose_custom_modifiers_9]
// Modifier factory
fun Modifier.circle(color: Color) = this then CircleElement(color)
// [END android_compose_custom_modifiers_9]
private object CustomModifierSnippets10 {
// [START android_compose_custom_modifiers_10]
// Modifier factory
fun Modifier.circle(color: Color) = this then CircleElement(color)
// ModifierNodeElement
private data class CircleElement(val color: Color) : ModifierNodeElement<CircleNode>() {
override fun create() = CircleNode(color)
override fun update(node: CircleNode) {
node.color = color
}
}
// Modifier.Node
private class CircleNode(var color: Color) : DrawModifierNode, Modifier.Node() {
override fun ContentDrawScope.draw() {
drawCircle(color)
}
}
// [END android_compose_custom_modifiers_10]
}
// [START android_compose_custom_modifiers_11]
fun Modifier.fixedPadding() = this then FixedPaddingElement
data object FixedPaddingElement : ModifierNodeElement<FixedPaddingNode>() {
override fun create() = FixedPaddingNode()
override fun update(node: FixedPaddingNode) {}
}
class FixedPaddingNode : LayoutModifierNode, Modifier.Node() {
private val PADDING = 16.dp
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val paddingPx = PADDING.roundToPx()
val horizontal = paddingPx * 2
val vertical = paddingPx * 2
val placeable = measurable.measure(constraints.offset(-horizontal, -vertical))
val width = constraints.constrainWidth(placeable.width + horizontal)
val height = constraints.constrainHeight(placeable.height + vertical)
return layout(width, height) {
placeable.place(paddingPx, paddingPx)
}
}
}
// [END android_compose_custom_modifiers_11]
// [START android_compose_custom_modifiers_12]
class BackgroundColorConsumerNode :
Modifier.Node(),
DrawModifierNode,
CompositionLocalConsumerModifierNode {
override fun ContentDrawScope.draw() {
val currentColor = currentValueOf(LocalContentColor)
drawRect(color = currentColor)
drawContent()
}
}
// [END android_compose_custom_modifiers_12]
private object UnityDensity : Density {
override val density: Float
get() = 1f
override val fontScale: Float
get() = 1f
}
data class DefaultFlingBehavior(var flingDecay: DecayAnimationSpec<Density>)
// [START android_compose_custom_modifiers_13]
class ScrollableNode :
Modifier.Node(),
ObserverModifierNode,
CompositionLocalConsumerModifierNode {
// Place holder fling behavior, we'll initialize it when the density is available.
val defaultFlingBehavior = DefaultFlingBehavior(splineBasedDecay(UnityDensity))
override fun onAttach() {
updateDefaultFlingBehavior()
observeReads { currentValueOf(LocalDensity) } // monitor change in Density
}
override fun onObservedReadsChanged() {
// if density changes, update the default fling behavior.
updateDefaultFlingBehavior()
}
private fun updateDefaultFlingBehavior() {
val density = currentValueOf(LocalDensity)
defaultFlingBehavior.flingDecay = splineBasedDecay(density)
}
}
// [END android_compose_custom_modifiers_13]
object CustomModifierSnippets14 {
// [START android_compose_custom_modifiers_14]
class CircleNode(var color: Color) : Modifier.Node(), DrawModifierNode {
private val alpha = Animatable(1f)
override fun ContentDrawScope.draw() {
drawCircle(color = color, alpha = alpha.value)
drawContent()
}
override fun onAttach() {
coroutineScope.launch {
alpha.animateTo(
0f,
infiniteRepeatable(tween(1000), RepeatMode.Reverse)
) {
}
}
}
}
// [END android_compose_custom_modifiers_14]
}
class InteractionData
class FocusableNode(val interactionData: InteractionData) : DelegatableNode {
override val node: Modifier.Node
get() = TODO("Not yet implemented")
}
class IndicationNode(val interactionData: InteractionData) : DelegatableNode {
override val node: Modifier.Node
get() = TODO("Not yet implemented")
}
// [START android_compose_custom_modifiers_15]
class ClickableNode : DelegatingNode() {
val interactionData = InteractionData()
val focusableNode = delegate(
FocusableNode(interactionData)
)
val indicationNode = delegate(
IndicationNode(interactionData)
)
}
// [END android_compose_custom_modifiers_15]
class ClickablePointerInputNode(var onClick: () -> Unit) : Modifier.Node(), DelegatableNode {
fun update(onClick: () -> Unit) {
this.onClick = onClick
}
}
// [START android_compose_custom_modifiers_16]
class SampleInvalidatingNode(
var color: Color,
var size: IntSize,
var onClick: () -> Unit
) : DelegatingNode(), LayoutModifierNode, DrawModifierNode {
override val shouldAutoInvalidate: Boolean
get() = false
private val clickableNode = delegate(
ClickablePointerInputNode(onClick)
)
fun update(color: Color, size: IntSize, onClick: () -> Unit) {
if (this.color != color) {
this.color = color
// Only invalidate draw when color changes
invalidateDraw()
}
if (this.size != size) {
this.size = size
// Only invalidate layout when size changes
invalidateMeasurement()
}
// If only onClick changes, we don't need to invalidate anything
clickableNode.update(onClick)
}
override fun ContentDrawScope.draw() {
drawRect(color)
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val size = constraints.constrain(size)
val placeable = measurable.measure(constraints)
return layout(size.width, size.height) {
placeable.place(0, 0)
}
}
}
// [END android_compose_custom_modifiers_16]