This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTextFieldImpl.kt
348 lines (317 loc) · 13.2 KB
/
TextFieldImpl.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
/*
* Copyright 2022 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
*
* http://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 androidx.compose.material3
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.material3.Strings.Companion.DefaultErrorMessage
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.layout.IntrinsicMeasurable
import androidx.compose.ui.layout.LayoutIdParentData
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.semantics.error
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.lerp
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
internal enum class TextFieldType {
Filled, Outlined
}
/**
* Implementation of the [TextField] and [OutlinedTextField]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun CommonDecorationBox(
type: TextFieldType,
value: String,
innerTextField: @Composable () -> Unit,
visualTransformation: VisualTransformation,
label: @Composable (() -> Unit)?,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
singleLine: Boolean = false,
enabled: Boolean = true,
isError: Boolean = false,
interactionSource: InteractionSource,
contentPadding: PaddingValues,
colors: TextFieldColors,
border: @Composable (() -> Unit)? = null
) {
val transformedText = remember(value, visualTransformation) {
visualTransformation.filter(AnnotatedString(value))
}.text.text
val isFocused = interactionSource.collectIsFocusedAsState().value
val inputState = when {
isFocused -> InputPhase.Focused
transformedText.isEmpty() -> InputPhase.UnfocusedEmpty
else -> InputPhase.UnfocusedNotEmpty
}
val labelColor: @Composable (InputPhase) -> Color = {
colors.labelColor(enabled, isError, interactionSource).value
}
val typography = MaterialTheme.typography
val bodyLarge = typography.bodyLarge
val bodySmall = typography.bodySmall
val shouldOverrideTextStyleColor =
(bodyLarge.color == Color.Unspecified && bodySmall.color != Color.Unspecified) ||
(bodyLarge.color != Color.Unspecified && bodySmall.color == Color.Unspecified)
TextFieldTransitionScope.Transition(
inputState = inputState,
focusedTextStyleColor = with(MaterialTheme.typography.bodySmall.color) {
if (shouldOverrideTextStyleColor) this.takeOrElse { labelColor(inputState) } else this
},
unfocusedTextStyleColor = with(MaterialTheme.typography.bodyLarge.color) {
if (shouldOverrideTextStyleColor) this.takeOrElse { labelColor(inputState) } else this
},
contentColor = labelColor,
showLabel = label != null
) { labelProgress, labelTextStyleColor, labelContentColor, placeholderAlphaProgress ->
val decoratedLabel: @Composable (() -> Unit)? = label?.let {
@Composable {
val labelTextStyle = lerp(
MaterialTheme.typography.bodyLarge,
MaterialTheme.typography.bodySmall,
labelProgress
).let {
if (shouldOverrideTextStyleColor) it.copy(color = labelTextStyleColor) else it
}
Decoration(labelContentColor, labelTextStyle, it)
}
}
val decoratedPlaceholder: @Composable ((Modifier) -> Unit)? =
if (placeholder != null && transformedText.isEmpty()) {
@Composable { modifier ->
Box(modifier.alpha(placeholderAlphaProgress)) {
Decoration(
contentColor = colors.placeholderColor(enabled).value,
typography = MaterialTheme.typography.bodyLarge,
content = placeholder
)
}
}
} else null
// Developers need to handle invalid input manually. But since we don't provide error
// message slot API, we can set the default error message in case developers forget about
// it.
val defaultErrorMessage = getString(DefaultErrorMessage)
val decorationBoxModifier = Modifier.semantics { if (isError) error(defaultErrorMessage) }
val leadingIconColor = colors.leadingIconColor(enabled, isError, interactionSource).value
val decoratedLeading: @Composable (() -> Unit)? = leadingIcon?.let {
@Composable {
Decoration(contentColor = leadingIconColor, content = it)
}
}
val trailingIconColor = colors.trailingIconColor(enabled, isError, interactionSource).value
val decoratedTrailing: @Composable (() -> Unit)? = trailingIcon?.let {
@Composable {
Decoration(contentColor = trailingIconColor, content = it)
}
}
when (type) {
TextFieldType.Filled -> {
TextFieldLayout(
modifier = decorationBoxModifier,
textField = innerTextField,
placeholder = decoratedPlaceholder,
label = decoratedLabel,
leading = decoratedLeading,
trailing = decoratedTrailing,
singleLine = singleLine,
animationProgress = labelProgress,
paddingValues = contentPadding
)
}
TextFieldType.Outlined -> {
// Outlined cutout
val labelSize = remember { mutableStateOf(Size.Zero) }
val drawBorder: @Composable () -> Unit = {
Box(
Modifier.layoutId(BorderId).outlineCutout(labelSize.value, contentPadding),
propagateMinConstraints = true
) {
border?.invoke()
}
}
OutlinedTextFieldLayout(
modifier = decorationBoxModifier,
textField = innerTextField,
placeholder = decoratedPlaceholder,
label = decoratedLabel,
leading = decoratedLeading,
trailing = decoratedTrailing,
singleLine = singleLine,
onLabelMeasured = {
val labelWidth = it.width * labelProgress
val labelHeight = it.height * labelProgress
if (labelSize.value.width != labelWidth ||
labelSize.value.height != labelHeight
) {
labelSize.value = Size(labelWidth, labelHeight)
}
},
animationProgress = labelProgress,
border = drawBorder,
paddingValues = contentPadding
)
}
}
}
}
/**
* Set content color, typography and emphasis for [content] composable
*/
@Composable
internal fun Decoration(
contentColor: Color,
typography: TextStyle? = null,
content: @Composable () -> Unit
) {
val contentWithColor: @Composable () -> Unit = @Composable {
CompositionLocalProvider(
LocalContentColor provides contentColor,
content = content
)
}
if (typography != null) ProvideTextStyle(typography, contentWithColor) else contentWithColor()
}
internal fun widthOrZero(placeable: Placeable?) = placeable?.width ?: 0
internal fun heightOrZero(placeable: Placeable?) = placeable?.height ?: 0
private object TextFieldTransitionScope {
@Composable
fun Transition(
inputState: InputPhase,
focusedTextStyleColor: Color,
unfocusedTextStyleColor: Color,
contentColor: @Composable (InputPhase) -> Color,
showLabel: Boolean,
content: @Composable (
labelProgress: Float,
labelTextStyleColor: Color,
labelContentColor: Color,
placeholderOpacity: Float
) -> Unit
) {
// Transitions from/to InputPhase.Focused are the most critical in the transition below.
// UnfocusedEmpty <-> UnfocusedNotEmpty are needed when a single state is used to control
// multiple text fields.
val transition = updateTransition(inputState, label = "TextFieldInputState")
val labelProgress by transition.animateFloat(
label = "LabelProgress",
transitionSpec = { tween(durationMillis = AnimationDuration) }
) {
when (it) {
InputPhase.Focused -> 1f
InputPhase.UnfocusedEmpty -> 0f
InputPhase.UnfocusedNotEmpty -> 1f
}
}
val placeholderOpacity by transition.animateFloat(
label = "PlaceholderOpacity",
transitionSpec = {
if (InputPhase.Focused isTransitioningTo InputPhase.UnfocusedEmpty) {
tween(
durationMillis = PlaceholderAnimationDelayOrDuration,
easing = LinearEasing
)
} else if (InputPhase.UnfocusedEmpty isTransitioningTo InputPhase.Focused ||
InputPhase.UnfocusedNotEmpty isTransitioningTo InputPhase.UnfocusedEmpty
) {
tween(
durationMillis = PlaceholderAnimationDuration,
delayMillis = PlaceholderAnimationDelayOrDuration,
easing = LinearEasing
)
} else {
spring()
}
}
) {
when (it) {
InputPhase.Focused -> 1f
InputPhase.UnfocusedEmpty -> if (showLabel) 0f else 1f
InputPhase.UnfocusedNotEmpty -> 0f
}
}
val labelTextStyleColor by transition.animateColor(
transitionSpec = { tween(durationMillis = AnimationDuration) },
label = "LabelTextStyleColor"
) {
when (it) {
InputPhase.Focused -> focusedTextStyleColor
else -> unfocusedTextStyleColor
}
}
val labelContentColor by transition.animateColor(
transitionSpec = { tween(durationMillis = AnimationDuration) },
label = "LabelContentColor",
targetValueByState = contentColor
)
content(
labelProgress,
labelTextStyleColor,
labelContentColor,
placeholderOpacity
)
}
}
/**
* An internal state used to animate a label and an indicator.
*/
private enum class InputPhase {
// Text field is focused
Focused,
// Text field is not focused and input text is empty
UnfocusedEmpty,
// Text field is not focused but input text is not empty
UnfocusedNotEmpty
}
internal val IntrinsicMeasurable.layoutId: Any?
get() = (parentData as? LayoutIdParentData)?.layoutId
internal const val TextFieldId = "TextField"
internal const val PlaceholderId = "Hint"
internal const val LabelId = "Label"
internal const val LeadingId = "Leading"
internal const val TrailingId = "Trailing"
internal val ZeroConstraints = Constraints(0, 0, 0, 0)
internal const val AnimationDuration = 150
private const val PlaceholderAnimationDuration = 83
private const val PlaceholderAnimationDelayOrDuration = 67
internal val TextFieldPadding = 16.dp
internal val HorizontalIconPadding = 12.dp
internal val IconDefaultSizeModifier = Modifier.defaultMinSize(48.dp, 48.dp)