Repository navigation
Expand file tree
/
Copy pathTextFieldMigrationSnippets.kt
More file actions
345 lines (317 loc) · 12.3 KB
/
Copy pathTextFieldMigrationSnippets.kt
File metadata and controls
345 lines (317 loc) · 12.3 KB
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
/*
* Copyright 2025 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.text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.input.InputTransformation
import androidx.compose.foundation.text.input.OutputTransformation
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.foundation.text.input.delete
import androidx.compose.foundation.text.input.insert
import androidx.compose.foundation.text.input.maxLength
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.SecureTextField
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.Text
//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.substring
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.compose.snippets.touchinput.Button
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
// [START android_compose_text_textfield_migration_old_simple]
@Composable
fun OldSimpleTextField() {
var state by rememberSaveable { mutableStateOf("") }
TextField(
value = state,
onValueChange = { state = it },
singleLine = true,
)
}
// [END android_compose_text_textfield_migration_old_simple]
// [START android_compose_text_textfield_migration_new_simple]
@Composable
fun NewSimpleTextField() {
TextField(
state = rememberTextFieldState(),
lineLimits = TextFieldLineLimits.SingleLine
)
}
// [END android_compose_text_textfield_migration_new_simple]
// [START android_compose_text_textfield_migration_old_filtering]
@Composable
fun OldNoLeadingZeroes() {
var input by rememberSaveable { mutableStateOf("") }
TextField(
value = input,
onValueChange = { newText ->
input = newText.trimStart { it == '0' }
}
)
}
// [END android_compose_text_textfield_migration_old_filtering]
// [START android_compose_text_textfield_migration_new_filtering]
@Preview
@Composable
fun NewNoLeadingZeros() {
TextField(
state = rememberTextFieldState(),
inputTransformation = InputTransformation {
while (length > 0 && charAt(0) == '0') delete(0, 1)
}
)
}
// [END android_compose_text_textfield_migration_new_filtering]
// [START android_compose_text_textfield_migration_old_credit_card_formatter]
@Composable
fun OldTextFieldCreditCardFormatter() {
var state by remember { mutableStateOf("") }
TextField(
value = state,
onValueChange = { if (it.length <= 16) state = it },
visualTransformation = VisualTransformation { text ->
// Making XXXX-XXXX-XXXX-XXXX string.
var out = ""
for (i in text.indices) {
out += text[i]
if (i % 4 == 3 && i != 15) out += "-"
}
TransformedText(
text = AnnotatedString(out),
offsetMapping = object : OffsetMapping {
override fun originalToTransformed(offset: Int): Int {
if (offset <= 3) return offset
if (offset <= 7) return offset + 1
if (offset <= 11) return offset + 2
if (offset <= 16) return offset + 3
return 19
}
override fun transformedToOriginal(offset: Int): Int {
if (offset <= 4) return offset
if (offset <= 9) return offset - 1
if (offset <= 14) return offset - 2
if (offset <= 19) return offset - 3
return 16
}
}
)
}
)
}
// [END android_compose_text_textfield_migration_old_credit_card_formatter]
// [START android_compose_text_textfield_migration_new_credit_card_formatter]
@Composable
fun NewTextFieldCreditCardFormatter() {
val state = rememberTextFieldState()
TextField(
state = state,
inputTransformation = InputTransformation.maxLength(16),
outputTransformation = OutputTransformation {
if (length > 4) insert(4, "-")
if (length > 9) insert(9, "-")
if (length > 14) insert(14, "-")
},
)
}
// [END android_compose_text_textfield_migration_new_credit_card_formatter]
private object StateUpdateSimpleSnippet {
object UserRepository {
suspend fun fetchUsername(): String = TODO()
}
// [START android_compose_text_textfield_migration_old_update_state_simple]
@Composable
fun OldTextFieldStateUpdate(userRepository: UserRepository) {
var username by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
username = userRepository.fetchUsername()
}
TextField(
value = username,
onValueChange = { username = it }
)
}
// [END android_compose_text_textfield_migration_old_update_state_simple]
// [START android_compose_text_textfield_migration_new_update_state_simple]
@Composable
fun NewTextFieldStateUpdate(userRepository: UserRepository) {
val usernameState = rememberTextFieldState()
LaunchedEffect(Unit) {
usernameState.setTextAndPlaceCursorAtEnd(userRepository.fetchUsername())
}
TextField(state = usernameState)
}
// [END android_compose_text_textfield_migration_new_update_state_simple]
}
// [START android_compose_text_textfield_migration_old_state_update_complex]
@Composable
fun OldTextFieldAddMarkdownEmphasis() {
var markdownState by remember { mutableStateOf(TextFieldValue()) }
Button(onClick = {
// add ** decorations around the current selection, also preserve the selection
markdownState = with(markdownState) {
copy(
text = buildString {
append(text.take(selection.min))
append("**")
append(text.substring(selection))
append("**")
append(text.drop(selection.max))
},
selection = TextRange(selection.min + 2, selection.max + 2)
)
}
}) {
Text("Bold")
}
TextField(
value = markdownState,
onValueChange = { markdownState = it },
maxLines = 10
)
}
// [END android_compose_text_textfield_migration_old_state_update_complex]
// [START android_compose_text_textfield_migration_new_state_update_complex]
@Composable
fun NewTextFieldAddMarkdownEmphasis() {
val markdownState = rememberTextFieldState()
LaunchedEffect(Unit) {
// add ** decorations around the current selection
markdownState.edit {
insert(originalSelection.max, "**")
insert(originalSelection.min, "**")
selection = TextRange(originalSelection.min + 2, originalSelection.max + 2)
}
}
TextField(
state = markdownState,
lineLimits = TextFieldLineLimits.MultiLine(1, 10)
)
}
// [END android_compose_text_textfield_migration_new_state_update_complex]
private object ViewModelMigrationOldSnippet {
// [START android_compose_text_textfield_migration_old_viewmodel]
class LoginViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState>
get() = _uiState.asStateFlow()
fun updateUsername(username: String) = _uiState.update { it.copy(username = username) }
fun updatePassword(password: String) = _uiState.update { it.copy(password = password) }
}
data class UiState(
val username: String = "",
val password: String = ""
)
@Composable
fun LoginForm(
loginViewModel: LoginViewModel,
modifier: Modifier = Modifier
) {
val uiState by loginViewModel.uiState.collectAsStateWithLifecycle()
Column(modifier) {
TextField(
value = uiState.username,
onValueChange = { loginViewModel.updateUsername(it) }
)
TextField(
value = uiState.password,
onValueChange = { loginViewModel.updatePassword(it) },
visualTransformation = PasswordVisualTransformation()
)
}
}
// [END android_compose_text_textfield_migration_old_viewmodel]
}
private object ViewModelMigrationNewSimpleSnippet {
// [START android_compose_text_textfield_migration_new_viewmodel_simple]
class LoginViewModel : ViewModel() {
val usernameState = TextFieldState()
val passwordState = TextFieldState()
}
@Composable
fun LoginForm(
loginViewModel: LoginViewModel,
modifier: Modifier = Modifier
) {
Column(modifier) {
TextField(state = loginViewModel.usernameState,)
SecureTextField(state = loginViewModel.passwordState)
}
}
// [END android_compose_text_textfield_migration_new_viewmodel_simple]
}
private object ViewModelMigrationNewConformingSnippet {
// [START android_compose_text_textfield_migration_new_viewmodel_conforming]
class LoginViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState>
get() = _uiState.asStateFlow()
fun updateUsername(username: String) = _uiState.update { it.copy(username = username) }
fun updatePassword(password: String) = _uiState.update { it.copy(password = password) }
}
data class UiState(
val username: String = "",
val password: String = ""
)
@Composable
fun LoginForm(
loginViewModel: LoginViewModel,
modifier: Modifier = Modifier
) {
val initialUiState = remember(loginViewModel) { loginViewModel.uiState.value }
Column(modifier) {
val usernameState = rememberTextFieldState(initialUiState.username)
LaunchedEffect(usernameState) {
snapshotFlow { usernameState.text.toString() }.collectLatest {
loginViewModel.updateUsername(it)
}
}
TextField(usernameState)
val passwordState = rememberTextFieldState(initialUiState.password)
LaunchedEffect(passwordState) {
snapshotFlow { passwordState.text.toString() }.collectLatest {
loginViewModel.updatePassword(it)
}
}
SecureTextField(passwordState)
}
}
// [END android_compose_text_textfield_migration_new_viewmodel_conforming]
}