1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.compose.modifiers
18
19 import androidx.compose.ui.Modifier
20
21 /**
22 * Concatenates this modifier with another if `condition` is true.
23 *
24 * @param condition Whether or not to apply the modifiers.
25 * @param factory Creates the modifier to concatenate with the current one.
26 * @return a Modifier representing this modifier followed by other in sequence.
27 * @see Modifier.then
28 *
29 * This method allows inline conditional addition of modifiers to a modifier chain. Instead of
30 * writing
31 *
32 * ```
33 * val aModifier = Modifier.a()
34 * val bModifier = if(condition) aModifier.b() else aModifier
35 * Composable(modifier = bModifier)
36 * ```
37 *
38 * You can instead write
39 *
40 * ```
41 * Composable(modifier = Modifier.a().thenIf(condition){
42 * Modifier.b()
43 * }
44 * ```
45 *
46 * This makes the modifier chain easier to read.
47 *
48 * Note that unlike the non-factory version, the conditional modifier is recreated each time, and
49 * may never be created at all.
50 */
thenIfnull51 inline fun Modifier.thenIf(condition: Boolean, crossinline factory: () -> Modifier): Modifier =
52 if (condition) this.then(factory()) else this
53