From 6b43b83555687849d298794bac3315d78498b3e3 Mon Sep 17 00:00:00 2001 From: xelon Date: Thu, 3 Dec 2026 15:39:30 +0200 Subject: [PATCH 1/2] docs: design the migration off APIs deprecated in Compose 1.13.0 --- ...-12-03-compose-1.13-deprecations-design.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-03-compose-1.13-deprecations-design.md diff --git a/docs/superpowers/specs/2026-12-03-compose-1.13-deprecations-design.md b/docs/superpowers/specs/2026-12-03-compose-1.13-deprecations-design.md new file mode 100644 index 0000000..80ba1ee --- /dev/null +++ b/docs/superpowers/specs/2026-12-03-compose-1.13-deprecations-design.md @@ -0,0 +1,35 @@ +# Migrate off APIs deprecated in Compose 1.13.0 + +Status: approved 2026-12-03. + +## Intent + +Build without the deprecation warnings Compose Multiplatform / Material 3 1.13.0 introduced, without breaking +consumers' source. Only `@Deprecated` public overloads kept for compatibility may still use the old APIs. + +Non-goals: removing the old API (4.0), clearing unrelated warnings, a public `TextFieldState` API. + +## Approaches + +1. **`value` + `outputTransformation` (chosen).** Overloads of `TableTextField`, `TableCellTextField` and + `TableCellTextFieldWithTooltipError` take `outputTransformation: OutputTransformation? = null` in place of + `visualTransformation`. Only callers passing a transformation migrate. Cost: an internal bridge between + `value` / `onValueChange` and `TextFieldState`. +2. `TextFieldState` overloads, all value overloads deprecated. No bridge in the public fields, but every consumer + migrates and the filter fields need the same synchronisation. +3. Both. Twice the API to maintain. + +## Design + +- The new overload runs on `BasicTextField(state)` with `OutlinedTextFieldDefaults.decorator`. The bridge reports + user edits through `onValueChange`, writes a differing `value` back into the state, and treats a value the caller + rejects or rewrites as the truth. A value change from the caller is not reported back. +- The old overload is `@Deprecated` (warning), keeps today's `BasicTextField(value)` implementation under a local + suppression, and has `visualTransformation` without a default; two overloads with every default would be + ambiguous. Source stays compatible; binaries built against the old default must be recompiled. +- `TableDatePicker` text input uses `OutlinedTextField(state)`: an `InputTransformation` keeps digits up to the + format's maximum, an `OutputTransformation` inserts the separators. +- `RangeSlider`, `ListItem`, `runComposeUiTest` and `compose.desktop.currentOs` move to their replacements. +- Tests pin the current text-field and date-input behaviour before the change; CHANGELOG and the docs follow the API. + +Builder's call: how the bridge detects edits, and the internal split between the overloads. From 8b857f5cfcf092d0e04704b9f43603c6366600c0 Mon Sep 17 00:00:00 2001 From: xelon Date: Thu, 3 Dec 2026 15:56:59 +0200 Subject: [PATCH 2/2] refactor: migrate off APIs deprecated in Compose 1.13.0 Compose 1.13.0 deprecated VisualTransformation and the value-based BasicTextField. The table's text fields now run on TextFieldState behind the same value / onValueChange, and take an OutputTransformation. The overloads with visualTransformation stay, deprecated, on the old implementation until 4.0. RangeSlider, ListItem, runComposeUiTest and compose.desktop.currentOs move to their replacements. ListItem no longer gives its slots a minimum touch target, so the format dialog restores it. --- CHANGELOG.md | 10 + table-core/build.gradle.kts | 2 +- .../table/component/TableCellTextField.kt | 66 ++++- .../TableCellTextFieldWithTooltipError.kt | 129 +++++++-- .../wwind/table/component/TableDatePicker.kt | 86 +++--- .../wwind/table/component/TableTextField.kt | 139 ++++++++-- .../table/component/ValueTextFieldState.kt | 114 ++++++++ .../component/main/number/NumberFilter.kt | 12 +- .../wwind/table/platform/DateInputFormat.kt | 51 +--- .../ua/wwind/table/RowBlockTestFixtures.kt | 3 +- .../component/TableDatePickerInputTest.kt | 137 ++++++++++ .../component/TableTextFieldValueTest.kt | 246 ++++++++++++++++++ .../interaction/HeaderPointerFocusTest.kt | 4 +- .../table/platform/DateInputFormatTest.kt | 8 +- table-format/build.gradle.kts | 2 +- .../ua/wwind/table/format/DialogListItem.kt | 42 +++ .../ua/wwind/table/format/FormatDialogBody.kt | 5 +- .../table/format/FormatDialogConditionTab.kt | 16 +- .../table/format/FormatDialogFieldTab.kt | 5 +- table-paging/build.gradle.kts | 2 +- table-sample/build.gradle.kts | 1 - .../table/sample/filter/NumericRangeFilter.kt | 9 +- 22 files changed, 925 insertions(+), 164 deletions(-) create mode 100644 table-core/src/commonMain/kotlin/ua/wwind/table/component/ValueTextFieldState.kt create mode 100644 table-core/src/commonTest/kotlin/ua/wwind/table/component/TableDatePickerInputTest.kt create mode 100644 table-core/src/commonTest/kotlin/ua/wwind/table/component/TableTextFieldValueTest.kt create mode 100644 table-format/src/commonMain/kotlin/ua/wwind/table/format/DialogListItem.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 970710f..0ac17f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. +### Unreleased + +The table's text fields run on Compose's state-based text field. Source compatible; recompile libraries that call +these text fields. + +- Added: `outputTransformation: OutputTransformation?` on `TableTextField`, `TableCellTextField` and + `TableCellTextFieldWithTooltipError`. It changes how the text is shown and leaves `value` as is. +- Deprecated: the overloads with `visualTransformation`, because Compose 1.13.0 deprecated `VisualTransformation`. Pass + an `OutputTransformation` instead; the overloads will be removed in 4.0. + ### 3.11.0 — 2026-12-03 The library builds against Compose Multiplatform 1.13.0 and stable Material 3. No API change. diff --git a/table-core/build.gradle.kts b/table-core/build.gradle.kts index 2932f97..279fe5c 100644 --- a/table-core/build.gradle.kts +++ b/table-core/build.gradle.kts @@ -19,7 +19,7 @@ kotlin { implementation(libs.compose.ui.test) } jvmTest.dependencies { - implementation(compose.desktop.currentOs) + implementation(libs.compose.desktop.jvm) } } } diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextField.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextField.kt index 04d39eb..cdd1c93 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextField.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextField.kt @@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.OutputTransformation import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.TextFieldColors import androidx.compose.material3.TextFieldDefaults @@ -39,7 +40,70 @@ public fun TableCellTextField( suffix: @Composable (() -> Unit)? = null, supportingText: @Composable (() -> Unit)? = null, isError: Boolean = false, - visualTransformation: VisualTransformation = VisualTransformation.None, + outputTransformation: OutputTransformation? = null, + keyboardOptions: KeyboardOptions = KeyboardOptions.Default, + keyboardActions: KeyboardActions = KeyboardActions.Default, + singleLine: Boolean = false, + maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE, + minLines: Int = 1, + interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, + shape: Shape = RectangleShape, + colors: TextFieldColors = TextFieldDefaults.colors(), + contentPadding: PaddingValues = TableTextFieldDefaults.reducedContentPadding(), +) { + TableTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier.syncEditCellFocus().fillMaxSize(), + enabled = enabled, + readOnly = readOnly, + textStyle = textStyle, + label = label, + placeholder = placeholder, + leadingIcon = leadingIcon, + trailingIcon = trailingIcon, + prefix = prefix, + suffix = suffix, + supportingText = supportingText, + isError = isError, + outputTransformation = outputTransformation, + keyboardOptions = keyboardOptions, + keyboardActions = keyboardActions, + singleLine = singleLine, + maxLines = maxLines, + minLines = minLines, + interactionSource = interactionSource, + shape = shape, + colors = colors, + contentPadding = contentPadding, + showBorder = false, + ) +} + +@Deprecated( + message = + "Compose deprecated VisualTransformation. Use the overload with outputTransformation; " + + "this one will be removed in 4.0.", +) +// The parameter order is that of the released signature. +@Suppress("DEPRECATION", "ComposableParamOrder") +@Composable +public fun TableCellTextField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + readOnly: Boolean = false, + textStyle: TextStyle = LocalTextStyle.current, + label: @Composable (() -> Unit)? = null, + placeholder: @Composable (() -> Unit)? = null, + leadingIcon: @Composable (() -> Unit)? = null, + trailingIcon: @Composable (() -> Unit)? = null, + prefix: @Composable (() -> Unit)? = null, + suffix: @Composable (() -> Unit)? = null, + supportingText: @Composable (() -> Unit)? = null, + isError: Boolean = false, + visualTransformation: VisualTransformation, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextFieldWithTooltipError.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextFieldWithTooltipError.kt index ebef493..bf8530c 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextFieldWithTooltipError.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableCellTextFieldWithTooltipError.kt @@ -1,5 +1,6 @@ package ua.wwind.table.component +import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Box @@ -7,6 +8,7 @@ import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.OutputTransformation import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme @@ -50,7 +52,7 @@ import ua.wwind.table.strings.currentStrings * @param trailingIcon the optional trailing icon to be displayed at the end of the text field container * @param prefix the optional prefix to be displayed before the input text in the text field * @param suffix the optional suffix to be displayed after the input text in the text field - * @param visualTransformation transforms the visual representation of the input value + * @param outputTransformation changes how the text is shown, leaving [value] as is * @param keyboardOptions software keyboard options that contains configuration * @param keyboardActions when the input service emits an IME action, the corresponding callback is called * @param singleLine when true, this text field becomes a single horizontally scrolling text field @@ -61,7 +63,6 @@ import ua.wwind.table.strings.currentStrings * @param colors [TextFieldColors] that will be used to resolve the colors used for this text field in different states * @param contentPadding the padding applied to the inner text field */ -@OptIn(ExperimentalMaterial3Api::class) @Composable public fun TableCellTextFieldWithTooltipError( value: String, @@ -77,7 +78,7 @@ public fun TableCellTextFieldWithTooltipError( trailingIcon: @Composable (() -> Unit)? = null, prefix: @Composable (() -> Unit)? = null, suffix: @Composable (() -> Unit)? = null, - visualTransformation: VisualTransformation = VisualTransformation.None, + outputTransformation: OutputTransformation? = null, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, @@ -87,6 +88,103 @@ public fun TableCellTextFieldWithTooltipError( shape: Shape = RectangleShape, colors: TextFieldColors = TextFieldDefaults.colors(), contentPadding: PaddingValues = TableTextFieldDefaults.reducedContentPadding(), +) { + TooltipErrorBox(errorMessage, interactionSource, modifier) { + TableCellTextField( + value = value, + onValueChange = onValueChange, + enabled = enabled, + readOnly = readOnly, + textStyle = textStyle, + label = label, + placeholder = placeholder, + leadingIcon = leadingIcon, + trailingIcon = trailingIcon, + prefix = prefix, + suffix = suffix, + isError = errorMessage.isNotEmpty(), + outputTransformation = outputTransformation, + keyboardOptions = keyboardOptions, + keyboardActions = keyboardActions, + singleLine = singleLine, + maxLines = maxLines, + minLines = minLines, + interactionSource = interactionSource, + shape = shape, + colors = colors, + contentPadding = contentPadding, + ) + } +} + +@Deprecated( + message = + "Compose deprecated VisualTransformation. Use the overload with outputTransformation; " + + "this one will be removed in 4.0.", +) +// The parameter order is that of the released signature. +@Suppress("DEPRECATION", "ComposableParamOrder") +@Composable +public fun TableCellTextFieldWithTooltipError( + value: String, + onValueChange: (String) -> Unit, + errorMessage: String, + modifier: Modifier = Modifier, + enabled: Boolean = true, + readOnly: Boolean = false, + textStyle: TextStyle = LocalTextStyle.current, + label: @Composable (() -> Unit)? = null, + placeholder: @Composable (() -> Unit)? = null, + leadingIcon: @Composable (() -> Unit)? = null, + trailingIcon: @Composable (() -> Unit)? = null, + prefix: @Composable (() -> Unit)? = null, + suffix: @Composable (() -> Unit)? = null, + visualTransformation: VisualTransformation, + keyboardOptions: KeyboardOptions = KeyboardOptions.Default, + keyboardActions: KeyboardActions = KeyboardActions.Default, + singleLine: Boolean = false, + maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE, + minLines: Int = 1, + interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, + shape: Shape = RectangleShape, + colors: TextFieldColors = TextFieldDefaults.colors(), + contentPadding: PaddingValues = TableTextFieldDefaults.reducedContentPadding(), +) { + TooltipErrorBox(errorMessage, interactionSource, modifier) { + TableCellTextField( + value = value, + onValueChange = onValueChange, + enabled = enabled, + readOnly = readOnly, + textStyle = textStyle, + label = label, + placeholder = placeholder, + leadingIcon = leadingIcon, + trailingIcon = trailingIcon, + prefix = prefix, + suffix = suffix, + isError = errorMessage.isNotEmpty(), + visualTransformation = visualTransformation, + keyboardOptions = keyboardOptions, + keyboardActions = keyboardActions, + singleLine = singleLine, + maxLines = maxLines, + minLines = minLines, + interactionSource = interactionSource, + shape = shape, + colors = colors, + contentPadding = contentPadding, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun TooltipErrorBox( + errorMessage: String, + interactionSource: InteractionSource, + modifier: Modifier = Modifier, + content: @Composable () -> Unit, ) { val tooltipState = rememberTooltipState(isPersistent = true) val hasError = errorMessage.isNotEmpty() @@ -135,30 +233,7 @@ public fun TableCellTextFieldWithTooltipError( hasAction = true, focusable = true, ) { - TableCellTextField( - value = value, - onValueChange = onValueChange, - enabled = enabled, - readOnly = readOnly, - textStyle = textStyle, - label = label, - placeholder = placeholder, - leadingIcon = leadingIcon, - trailingIcon = trailingIcon, - prefix = prefix, - suffix = suffix, - isError = hasError, - visualTransformation = visualTransformation, - keyboardOptions = keyboardOptions, - keyboardActions = keyboardActions, - singleLine = singleLine, - maxLines = maxLines, - minLines = minLines, - interactionSource = interactionSource, - shape = shape, - colors = colors, - contentPadding = contentPadding, - ) + content() } } } diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableDatePicker.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableDatePicker.kt index 515a0b8..5275719 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableDatePicker.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableDatePicker.kt @@ -9,6 +9,13 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.InputTransformation +import androidx.compose.foundation.text.input.OutputTransformation +import androidx.compose.foundation.text.input.TextFieldBuffer +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.delete +import androidx.compose.foundation.text.input.insert +import androidx.compose.foundation.text.input.then import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerColors import androidx.compose.material3.DatePickerDefaults @@ -39,14 +46,9 @@ import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.error import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.OffsetMapping -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.unit.dp import org.jetbrains.compose.resources.painterResource import ua.wwind.table.filter.component.main.date.datePickerMillisToLocalDate @@ -162,30 +164,34 @@ private fun DateTextField( strings: StringProvider, ) { var digits by remember { - val initial = state.selectedDateMillis?.let { format.digitsOf(datePickerMillisToLocalDate(it)) }.orEmpty() - mutableStateOf(TextFieldValue(initial, TextRange(initial.length))) + mutableStateOf( + state.selectedDateMillis?.let { format.digitsOf(datePickerMillisToLocalDate(it)) }.orEmpty(), + ) } - val typed = format.parse(digits.text) + val fieldState = + rememberValueTextFieldState( + value = digits, + onValueChange = { next -> + digits = next + val date = format.parse(next) + val millis = date?.toDatePickerMillis()?.takeIf { state.accepts(it, date.year) } + state.selectedDateMillis = millis + if (millis != null) state.displayedMonthMillis = millis + }, + initialSelection = TextRange(digits.length), + ) + val typed = format.parse(digits) val error = when { - digits.text.length < format.maxDigits -> null + digits.length < format.maxDigits -> null typed == null -> strings.get(UiString.DatePickerInvalidDate) !state.accepts(typed.toDatePickerMillis(), typed.year) -> strings.get(UiString.DatePickerDateNotAllowed) else -> null } val label = strings.get(UiString.FilterDateLabel) val focusRequester = remember { FocusRequester() } - val transformation = remember(format) { DigitsVisualTransformation(format) } OutlinedTextField( - value = digits, - onValueChange = { input -> - val next = input.digitsOnly(format.maxDigits) - digits = next - val date = format.parse(next.text) - val millis = date?.toDatePickerMillis()?.takeIf { state.accepts(it, date.year) } - state.selectedDateMillis = millis - if (millis != null) state.displayedMonthMillis = millis - }, + state = fieldState.textFieldState, modifier = Modifier .fillMaxWidth() @@ -198,14 +204,15 @@ private fun DateTextField( placeholder = { Text(format.placeholder, modifier = Modifier.clearAndSetSemantics {}) }, supportingText = error?.let { { Text(it) } }, isError = error != null, - visualTransformation = transformation, + inputTransformation = remember(format) { DigitsOnly(format.maxDigits).then(fieldState.inputTransformation) }, + outputTransformation = remember(format) { DateSeparators(format) }, keyboardOptions = KeyboardOptions( autoCorrectEnabled = false, keyboardType = KeyboardType.Number, imeAction = ImeAction.Done, ), - singleLine = true, + lineLimits = TextFieldLineLimits.SingleLine, ) LaunchedEffect(Unit) { focusRequester.requestFocus() } } @@ -216,31 +223,22 @@ private fun DatePickerState.accepts( year: Int, ): Boolean = year in yearRange && selectableDates.isSelectableYear(year) && selectableDates.isSelectableDate(millis) -// Separators typed or pasted with the date are dropped: the transformation shows them. -private fun TextFieldValue.digitsOnly(max: Int): TextFieldValue { - fun digitsBefore(offset: Int) = text.take(offset).count { it in '0'..'9' }.coerceAtMost(max) - val kept = text.filter { it in '0'..'9' }.take(max) - return TextFieldValue(kept, TextRange(digitsBefore(selection.start), digitsBefore(selection.end))) +// Separators typed or pasted with the date are dropped: [DateSeparators] shows them. +private class DigitsOnly( + private val max: Int, +) : InputTransformation { + override fun TextFieldBuffer.transformInput() { + for (i in length - 1 downTo 0) { + if (charAt(i) !in '0'..'9') delete(i, i + 1) + } + if (length > max) delete(max, length) + } } -private class DigitsVisualTransformation( +private class DateSeparators( private val format: DateInputFormat, -) : VisualTransformation { - override fun filter(text: AnnotatedString): TransformedText { - val digits = text.text - val shown = format.display(digits) - return TransformedText( - AnnotatedString(shown), - object : OffsetMapping { - override fun originalToTransformed(offset: Int): Int = - format.displayOffset(digits, offset).coerceAtMost(shown.length) - - override fun transformedToOriginal(offset: Int): Int = format.digitOffset(digits, offset) - }, - ) +) : OutputTransformation { + override fun TextFieldBuffer.transformOutput() { + format.separators(length).forEach { (offset, text) -> insert(offset, text) } } - - override fun equals(other: Any?): Boolean = other is DigitsVisualTransformation && other.format == format - - override fun hashCode(): Int = format.hashCode() } diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableTextField.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableTextField.kt index 3141494..b49562b 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableTextField.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/component/TableTextField.kt @@ -6,6 +6,8 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.OutputTransformation +import androidx.compose.foundation.text.input.TextFieldLineLimits import androidx.compose.foundation.text.selection.LocalTextSelectionColors import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme @@ -42,7 +44,7 @@ import androidx.compose.ui.unit.dp * @param suffix the optional suffix to be displayed after the input text in the text field * @param supportingText the optional supporting text to be displayed below the text field * @param isError indicates if the text field's current value is in error state - * @param visualTransformation transforms the visual representation of the input value + * @param outputTransformation changes how the text is shown, leaving [value] as is * @param keyboardOptions software keyboard options that contains configuration * @param keyboardActions when the input service emits an IME action, the corresponding callback is called * @param singleLine when true, this text field becomes a single horizontally scrolling text field @@ -71,7 +73,7 @@ public fun TableTextField( suffix: @Composable (() -> Unit)? = null, supportingText: @Composable (() -> Unit)? = null, isError: Boolean = false, - visualTransformation: VisualTransformation = VisualTransformation.None, + outputTransformation: OutputTransformation? = null, keyboardOptions: KeyboardOptions = KeyboardOptions.Default, keyboardActions: KeyboardActions = KeyboardActions.Default, singleLine: Boolean = false, @@ -83,36 +85,104 @@ public fun TableTextField( contentPadding: PaddingValues = TableTextFieldDefaults.contentPadding(), showBorder: Boolean = true, ) { - // Merge text style with color from theme to ensure proper text visibility in dark mode - // Use error color when isError is true - val textColor = - if (isError) { - MaterialTheme.colorScheme.error - } else { - MaterialTheme.colorScheme.onSurface - } + val mergedTextStyle = textStyle.withFieldColor(isError) - val mergedTextStyle = - textStyle.merge( - TextStyle(color = textColor), + // Cursor and selection follow [colors], as in a Material text field; the default colors take the + // selection from LocalTextSelectionColors, so an app theme that sets it is respected. + val cursorColor = if (isError) colors.errorCursorColor else colors.cursorColor + val effectiveColors = colors.withBorder(showBorder) + + val fieldState = rememberValueTextFieldState(value, onValueChange) + val state = fieldState.textFieldState + val lineLimits = + if (singleLine) TextFieldLineLimits.SingleLine else TextFieldLineLimits.MultiLine(minLines, maxLines) + + CompositionLocalProvider(LocalTextSelectionColors provides colors.textSelectionColors) { + BasicTextField( + state = state, + modifier = modifier.fillMaxWidth(), + enabled = enabled, + readOnly = readOnly, + inputTransformation = fieldState.inputTransformation, + textStyle = mergedTextStyle, + keyboardOptions = keyboardOptions, + onKeyboardAction = keyboardActions.toHandler(keyboardOptions.imeAction), + lineLimits = lineLimits, + interactionSource = interactionSource, + cursorBrush = SolidColor(cursorColor), + outputTransformation = outputTransformation, + decorator = + OutlinedTextFieldDefaults.decorator( + state = state, + enabled = enabled, + lineLimits = lineLimits, + outputTransformation = outputTransformation, + interactionSource = interactionSource, + label = label?.let { { it() } }, + placeholder = placeholder, + leadingIcon = leadingIcon, + trailingIcon = trailingIcon, + prefix = prefix, + suffix = suffix, + supportingText = supportingText, + isError = isError, + colors = effectiveColors, + contentPadding = contentPadding, + container = { + OutlinedTextFieldDefaults.Container( + enabled = enabled, + isError = isError, + interactionSource = interactionSource, + colors = effectiveColors, + shape = shape, + ) + }, + ), ) + } +} + +@Deprecated( + message = + "Compose deprecated VisualTransformation. Use the overload with outputTransformation; " + + "this one will be removed in 4.0.", +) +// The parameter order is that of the released signature. +@Suppress("DEPRECATION", "ComposableParamOrder") +@Composable +public fun TableTextField( + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + readOnly: Boolean = false, + textStyle: TextStyle = LocalTextStyle.current, + label: @Composable (() -> Unit)? = null, + placeholder: @Composable (() -> Unit)? = null, + leadingIcon: @Composable (() -> Unit)? = null, + trailingIcon: @Composable (() -> Unit)? = null, + prefix: @Composable (() -> Unit)? = null, + suffix: @Composable (() -> Unit)? = null, + supportingText: @Composable (() -> Unit)? = null, + isError: Boolean = false, + visualTransformation: VisualTransformation, + keyboardOptions: KeyboardOptions = KeyboardOptions.Default, + keyboardActions: KeyboardActions = KeyboardActions.Default, + singleLine: Boolean = false, + maxLines: Int = if (singleLine) 1 else Int.MAX_VALUE, + minLines: Int = 1, + interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, + shape: Shape = OutlinedTextFieldDefaults.shape, + colors: TextFieldColors = OutlinedTextFieldDefaults.colors(), + contentPadding: PaddingValues = TableTextFieldDefaults.contentPadding(), + showBorder: Boolean = true, +) { + val mergedTextStyle = textStyle.withFieldColor(isError) // Cursor and selection follow [colors], as in a Material text field; the default colors take the // selection from LocalTextSelectionColors, so an app theme that sets it is respected. val cursorColor = if (isError) colors.errorCursorColor else colors.cursorColor - - // Apply transparent border colors when showBorder is false - val effectiveColors = - if (!showBorder) { - colors.copy( - unfocusedIndicatorColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - disabledIndicatorColor = Color.Transparent, - errorIndicatorColor = Color.Transparent, - ) - } else { - colors - } + val effectiveColors = colors.withBorder(showBorder) CompositionLocalProvider(LocalTextSelectionColors provides colors.textSelectionColors) { BasicTextField( @@ -162,6 +232,23 @@ public fun TableTextField( } } +// Text color from the theme, so the text stays visible in dark mode. +@Composable +private fun TextStyle.withFieldColor(isError: Boolean): TextStyle = + merge(TextStyle(color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface)) + +private fun TextFieldColors.withBorder(showBorder: Boolean): TextFieldColors = + if (showBorder) { + this + } else { + copy( + unfocusedIndicatorColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + disabledIndicatorColor = Color.Transparent, + errorIndicatorColor = Color.Transparent, + ) + } + /** * Contains default values used by [TableTextField]. */ diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/component/ValueTextFieldState.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/component/ValueTextFieldState.kt new file mode 100644 index 0000000..989894d --- /dev/null +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/component/ValueTextFieldState.kt @@ -0,0 +1,114 @@ +package ua.wwind.table.component + +import androidx.compose.foundation.text.KeyboardActionScope +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.input.InputTransformation +import androidx.compose.foundation.text.input.KeyboardActionHandler +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.focus.FocusDirection +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.ImeAction + +/** + * A [TextFieldState] driven by a `value` / `onValueChange` pair, where the caller's value is the truth: an edit it + * rejects or rewrites shows as the caller left it. Pass [inputTransformation] to the field, last in the chain. + */ +@Stable +internal class ValueTextFieldState( + value: String, + initialSelection: TextRange, + private val onValueChange: (String) -> Unit, +) { + val textFieldState = TextFieldState(value, initialSelection) + + // The text both sides have seen: reported to the caller or received from it. + private var known = value + + private var reports by mutableIntStateOf(0) + + // Reports as the edit happens, so a key right after it (a scanner's Enter) already finds the new value. + val inputTransformation = InputTransformation { report(asCharSequence().toString()) } + + /** Recomposes the reader after every report, so an edit the caller rejects is undone too. */ + fun observeReports(): Int = reports + + fun report(text: String) { + if (text == known) return + known = text + reports++ + onValueChange(text) + } + + fun accept(value: String) { + val text = textFieldState.text.toString() + // Text not reported yet (an undo) goes to the caller first. + if (text != known) return + known = value + if (text == value) return + textFieldState.edit { + val kept = TextRange(selection.start.coerceAtMost(value.length), selection.end.coerceAtMost(value.length)) + replace(0, length, value) + selection = kept + } + } +} + +@Composable +internal fun rememberValueTextFieldState( + value: String, + onValueChange: (String) -> Unit, + initialSelection: TextRange = TextRange.Zero, +): ValueTextFieldState { + val currentOnValueChange by rememberUpdatedState(onValueChange) + val state = remember { ValueTextFieldState(value, initialSelection) { currentOnValueChange(it) } } + state.observeReports() + SideEffect { state.accept(value) } + // Undo and redo skip input transformations. + LaunchedEffect(state) { + snapshotFlow { state.textFieldState.text.toString() }.collect { state.report(it) } + } + return state +} + +/** The handler that runs the callback [KeyboardActions] has for [imeAction], or `null` for the default action. */ +@Composable +internal fun KeyboardActions.toHandler(imeAction: ImeAction): KeyboardActionHandler? { + val focusManager = LocalFocusManager.current + val keyboard = LocalSoftwareKeyboardController.current + val action = + when (imeAction) { + ImeAction.Done -> onDone + ImeAction.Go -> onGo + ImeAction.Next -> onNext + ImeAction.Previous -> onPrevious + ImeAction.Search -> onSearch + ImeAction.Send -> onSend + else -> null + } ?: return null + return KeyboardActionHandler { performDefault -> + val scope = + object : KeyboardActionScope { + override fun defaultKeyboardAction(imeAction: ImeAction) { + when (imeAction) { + ImeAction.Next -> focusManager.moveFocus(FocusDirection.Next) + ImeAction.Previous -> focusManager.moveFocus(FocusDirection.Previous) + ImeAction.Done -> keyboard?.hide() + else -> performDefault() + } + } + } + scope.action() + } +} diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/filter/component/main/number/NumberFilter.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/filter/component/main/number/NumberFilter.kt index 60d4d22..a67d022 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/filter/component/main/number/NumberFilter.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/filter/component/main/number/NumberFilter.kt @@ -9,8 +9,10 @@ import androidx.compose.material3.Icon import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.RangeSlider +import androidx.compose.material3.RangeSliderState import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign @@ -85,15 +87,21 @@ internal fun NumberFilter( } if (!isNullConstraint && isBetween && filter.rangeOptions != null) { + val sliderFrom = filter.delegate.toSliderValue(fromValue) + val sliderTo = filter.delegate.toSliderValue(toValue) + val trackRange = filter.delegate.toSliderValue(min)..filter.delegate.toSliderValue(max) + val sliderState = remember(trackRange) { RangeSliderState(sliderFrom, sliderTo, trackRange = trackRange) } + // Set on every composition: rememberRangeSliderState would keep the first values. + sliderState.startValue = sliderFrom + sliderState.endValue = sliderTo RangeSlider( - value = filter.delegate.toSliderValue(fromValue)..filter.delegate.toSliderValue(toValue), + state = sliderState, onValueChange = { range -> val newFrom = filter.delegate.fromSliderValue(range.start) val newTo = filter.delegate.fromSliderValue(range.endInclusive) numberFilterState.onTextChange(inputFormat.format(newFrom)) numberFilterState.onSecondTextChange(inputFormat.format(newTo)) }, - valueRange = filter.delegate.toSliderValue(min)..filter.delegate.toSliderValue(max), ) } diff --git a/table-core/src/commonMain/kotlin/ua/wwind/table/platform/DateInputFormat.kt b/table-core/src/commonMain/kotlin/ua/wwind/table/platform/DateInputFormat.kt index a920716..665a39f 100644 --- a/table-core/src/commonMain/kotlin/ua/wwind/table/platform/DateInputFormat.kt +++ b/table-core/src/commonMain/kotlin/ua/wwind/table/platform/DateInputFormat.kt @@ -5,7 +5,7 @@ import kotlinx.datetime.number /** * Typing a date in the same field order and separators the table shows it with. The user types digits - * only; [display] puts the separators back. + * only; [separators] are shown among them. */ internal class DateInputFormat( pattern: DatePattern, @@ -81,44 +81,19 @@ internal class DateInputFormat( return runCatching { LocalDate(year, month, day) }.getOrNull() } - /** [digits] with the separators of every field already started, e.g. `01.1` for `011`. */ - fun display(digits: String): String = - buildString { - var at = 0 - segments.forEach { segment -> - when (segment) { - is Segment.Field -> { - val end = minOf(at + segment.width, digits.length) - if (at < end) append(digits, at, end) - at = end - } - - is Segment.Literal -> { - if (segment.isShown(digits.length)) append(segment.text) - } - } - } - } - - /** Where the cursor after [offset] typed digits sits in [display]. */ - fun displayOffset( - digits: String, - offset: Int, - ): Int = - offset + - segments.sumOf { segment -> - if (segment is Segment.Literal && segment.digitsBefore <= offset && segment.isShown(digits.length)) { - segment.text.length - } else { - 0 - } + /** + * The separators shown among [typed] digits, each at its offset in the shown text: insert them in order, so + * `011` becomes `01.1`. + */ + fun separators(typed: Int): List> { + var inserted = 0 + return segments + .filterIsInstance() + .filter { it.isShown(typed) } + .map { literal -> + (literal.digitsBefore + inserted to literal.text).also { inserted += literal.text.length } } - - /** How many digits lie before [offset] in [display]. */ - fun digitOffset( - digits: String, - offset: Int, - ): Int = display(digits).take(offset).count { it in '0'..'9' } + } // A separator shows once a digit follows it; one after the last field shows when the date is complete. private fun Segment.Literal.isShown(typed: Int): Boolean = diff --git a/table-core/src/commonTest/kotlin/ua/wwind/table/RowBlockTestFixtures.kt b/table-core/src/commonTest/kotlin/ua/wwind/table/RowBlockTestFixtures.kt index 5b20265..a9ebcf5 100644 --- a/table-core/src/commonTest/kotlin/ua/wwind/table/RowBlockTestFixtures.kt +++ b/table-core/src/commonTest/kotlin/ua/wwind/table/RowBlockTestFixtures.kt @@ -7,6 +7,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ComposeUiTestConfig import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.v2.runComposeUiTest import androidx.compose.ui.unit.dp @@ -32,7 +33,7 @@ import ua.wwind.table.config.TableRowStyle */ @OptIn(ExperimentalTestApi::class, ExperimentalCoroutinesApi::class) internal fun runDragUiTest(block: suspend ComposeUiTest.() -> Unit): TestResult = - runComposeUiTest(effectContext = UnconfinedTestDispatcher(), block = block) + runComposeUiTest(ComposeUiTestConfig(effectContext = UnconfinedTestDispatcher()), block) internal data class BlockRow( val id: Int, diff --git a/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableDatePickerInputTest.kt b/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableDatePickerInputTest.kt new file mode 100644 index 0000000..55076b4 --- /dev/null +++ b/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableDatePickerInputTest.kt @@ -0,0 +1,137 @@ +package ua.wwind.table.component + +import androidx.compose.material3.DatePickerState +import androidx.compose.material3.DisplayMode +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SelectableDates +import androidx.compose.material3.rememberDatePickerState +import androidx.compose.runtime.Composable +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performTextClearance +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextInputSelection +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.text.TextRange +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isNull +import kotlinx.datetime.LocalDate +import ua.wwind.table.filter.component.main.date.toDatePickerMillis +import ua.wwind.table.strings.DefaultStrings +import ua.wwind.table.strings.StringProvider +import kotlin.test.Test + +/** Typing a date in the date picker's text input mode, as the app's `formatDate` shows it. */ +@OptIn(ExperimentalTestApi::class, ExperimentalMaterial3Api::class) +class TableDatePickerInputTest { + private lateinit var state: DatePickerState + + private val strings = + object : StringProvider by DefaultStrings { + @Composable + override fun formatDate(date: LocalDate): String = + with(date) { + "${day.toString().padStart(2, '0')}.${(month.ordinal + 1).toString().padStart(2, '0')}.$year" + } + } + + private val december1 = LocalDate(2026, 12, 1).toDatePickerMillis() + + private fun ComposeUiTest.showPicker( + initial: Long? = null, + accepts: (Long) -> Boolean = { true }, + ) = setContent { + state = + rememberDatePickerState( + initialSelectedDateMillis = initial, + initialDisplayMode = DisplayMode.Input, + selectableDates = + object : SelectableDates { + override fun isSelectableDate(utcTimeMillis: Long): Boolean = accepts(utcTimeMillis) + }, + ) + MaterialTheme { TableDatePicker(state, strings) } + } + + private fun ComposeUiTest.field() = onNode(hasSetTextAction()) + + @Test + fun typed_digits_show_with_separators_and_select_the_date() = + runComposeUiTest { + showPicker() + "01122026".forEach { field().performTextInput(it.toString()) } + waitForIdle() + onNodeWithText("01.12.2026").assertIsDisplayed() + assertThat(state.selectedDateMillis).isEqualTo(december1) + } + + @Test + fun a_date_pasted_with_separators_selects_it() = + runComposeUiTest { + showPicker() + field().performTextInput("01.12.2026") + waitForIdle() + onNodeWithText("01.12.2026").assertIsDisplayed() + assertThat(state.selectedDateMillis).isEqualTo(december1) + } + + @Test + fun digits_past_the_date_are_dropped() = + runComposeUiTest { + showPicker() + field().performTextInput("0112202699") + waitForIdle() + onNodeWithText("01.12.2026").assertIsDisplayed() + } + + @Test + fun an_unfinished_date_selects_nothing() = + runComposeUiTest { + showPicker(initial = december1) + onNodeWithText("01.12.2026").assertIsDisplayed() + field().performTextReplacement("011") + waitForIdle() + onNodeWithText("01.1").assertIsDisplayed() + assertThat(state.selectedDateMillis).isNull() + field().performTextClearance() + waitForIdle() + assertThat(state.selectedDateMillis).isNull() + } + + @Test + fun a_digit_typed_mid_date_lands_at_the_caret() = + runComposeUiTest { + showPicker() + field().performTextInput("0112226") + field().performTextInputSelection(TextRange(5)) + field().performTextInput("0") + waitForIdle() + onNodeWithText("01.12.2026").assertIsDisplayed() + } + + @Test + fun an_impossible_date_is_an_error() = + runComposeUiTest { + showPicker() + field().performTextInput("31022026") + waitForIdle() + onNodeWithText("Enter a valid date").assertIsDisplayed() + assertThat(state.selectedDateMillis).isNull() + } + + @Test + fun a_date_the_picker_does_not_accept_is_an_error() = + runComposeUiTest { + showPicker { it != december1 } + field().performTextInput("01122026") + waitForIdle() + onNodeWithText("Date not allowed").assertIsDisplayed() + assertThat(state.selectedDateMillis).isNull() + } +} diff --git a/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableTextFieldValueTest.kt b/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableTextFieldValueTest.kt new file mode 100644 index 0000000..d71d7e5 --- /dev/null +++ b/table-core/src/commonTest/kotlin/ua/wwind/table/component/TableTextFieldValueTest.kt @@ -0,0 +1,246 @@ +package ua.wwind.table.component + +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performImeAction +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performTextClearance +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextInputSelection +import androidx.compose.ui.test.performTextReplacement +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.test.v2.runComposeUiTest +import androidx.compose.ui.test.withKeyDown +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.PasswordVisualTransformation +import assertk.assertThat +import assertk.assertions.containsExactly +import assertk.assertions.isEmpty +import assertk.assertions.isEqualTo +import ua.wwind.table.platform.getPlatform +import ua.wwind.table.platform.isNonMobile +import kotlin.test.Test + +/** `value` stays the truth: the field shows what the caller makes of an edit. */ +@OptIn(ExperimentalTestApi::class) +class TableTextFieldValueTest { + private var value by mutableStateOf("") + private val reported = mutableListOf() + + private fun ComposeUiTest.showField( + singleLine: Boolean = true, + keyboardOptions: KeyboardOptions = KeyboardOptions.Default, + keyboardActions: KeyboardActions = KeyboardActions.Default, + edit: (String) -> String = { it }, + ) = setContent { + MaterialTheme { + TableTextField( + value = value, + onValueChange = { + reported += it + value = edit(it) + }, + modifier = Modifier.testTag(FIELD), + placeholder = { Text("hint") }, + singleLine = singleLine, + keyboardOptions = keyboardOptions, + keyboardActions = keyboardActions, + ) + } + } + + private fun ComposeUiTest.field() = onNodeWithTag(FIELD) + + @Test + fun an_edit_reaches_the_caller_once() = + runComposeUiTest { + showField() + field().performTextInput("a") + field().performTextInput("b") + waitForIdle() + assertThat(reported).containsExactly("a", "ab") + field().assertTextEquals("ab", includeEditableText = true) + } + + @Test + fun two_edits_before_a_recomposition_both_reach_the_caller() = + runComposeUiTest { + showField() + field().performClick() + mainClock.autoAdvance = false + field().performTextInput("a") + field().performTextInput("b") + mainClock.autoAdvance = true + waitForIdle() + assertThat(value).isEqualTo("ab") + field().assertTextEquals("ab", includeEditableText = true) + } + + @Test + fun a_rejected_edit_is_undone() = + runComposeUiTest { + value = "1" + showField { if (it.all(Char::isDigit)) it else value } + field().performTextInputSelection(TextRange(1)) + field().performTextInput("x") + waitForIdle() + field().assertTextEquals("1", includeEditableText = true) + field().performTextInput("2") + waitForIdle() + assertThat(value).isEqualTo("12") + } + + @Test + fun a_rewritten_edit_is_shown_and_not_reported_back() = + runComposeUiTest { + showField { it.uppercase() } + field().performTextInput("a") + waitForIdle() + field().performTextInput("b") + waitForIdle() + field().assertTextEquals("AB", includeEditableText = true) + assertThat(reported).containsExactly("a", "Ab") + } + + @Test + fun a_rewritten_edit_keeps_the_caret_in_place() = + runComposeUiTest { + value = "AD" + showField { it.uppercase() } + field().performTextInputSelection(TextRange(1)) + field().performTextInput("b") + waitForIdle() + field().performTextInput("c") + waitForIdle() + assertThat(value).isEqualTo("ABCD") + } + + @Test + fun a_value_set_by_the_caller_is_shown_and_not_reported() = + runComposeUiTest { + showField() + field().performClick() + value = "set" + waitForIdle() + field().assertTextEquals("set", includeEditableText = true) + assertThat(reported).isEmpty() + } + + @Test + fun clearing_and_replacing_reach_the_caller() = + runComposeUiTest { + value = "old" + showField() + field().performTextReplacement("new") + waitForIdle() + field().performTextClearance() + waitForIdle() + assertThat(reported).containsExactly("new", "") + } + + @Test + fun the_placeholder_shows_in_an_empty_field() = + runComposeUiTest { + showField() + field().performClick() + onNodeWithText("hint").assertIsDisplayed() + } + + @Test + fun the_ime_action_runs_its_keyboard_action() = + runComposeUiTest { + var done = 0 + showField( + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { done++ }), + ) + field().performClick() + field().performImeAction() + waitForIdle() + assertThat(done).isEqualTo(1) + } + + @Test + fun a_line_break_stays_in_a_multi_line_field() = + runComposeUiTest { + showField(singleLine = false) + field().performTextInput("a\nb") + waitForIdle() + assertThat(value).isEqualTo("a\nb") + } + + @Test + fun an_undo_reaches_the_caller() = + runComposeUiTest { + if (!getPlatform().isNonMobile()) return@runComposeUiTest + showField() + field().performClick() + field().performTextInput("a") + waitForIdle() + // The shortcut is Cmd+Z or Ctrl+Z, depending on the machine; the other one does nothing. + listOf(Key.MetaLeft, Key.CtrlLeft).forEach { modifier -> + field().performKeyInput { withKeyDown(modifier) { pressKey(Key.Z) } } + } + waitForIdle() + assertThat(value).isEqualTo("") + } + + @Test + fun an_output_transformation_changes_only_what_is_shown() = + runComposeUiTest { + setContent { + MaterialTheme { + TableTextField( + value = value, + onValueChange = { value = it }, + modifier = Modifier.testTag(FIELD), + outputTransformation = { append(" kg") }, + ) + } + } + field().performTextInput("5") + waitForIdle() + assertThat(value).isEqualTo("5") + field().assertTextEquals("5 kg", includeEditableText = true) + } + + @Suppress("DEPRECATION") + @Test + fun the_deprecated_overload_still_applies_a_visual_transformation() = + runComposeUiTest { + setContent { + MaterialTheme { + TableTextField( + value = value, + onValueChange = { value = it }, + modifier = Modifier.testTag(FIELD), + visualTransformation = PasswordVisualTransformation('*'), + ) + } + } + field().performTextInput("abc") + waitForIdle() + assertThat(value).isEqualTo("abc") + field().assertTextEquals("***", includeEditableText = true) + } + + private companion object { + const val FIELD = "field" + } +} diff --git a/table-core/src/commonTest/kotlin/ua/wwind/table/interaction/HeaderPointerFocusTest.kt b/table-core/src/commonTest/kotlin/ua/wwind/table/interaction/HeaderPointerFocusTest.kt index d6263d6..f9e26c6 100644 --- a/table-core/src/commonTest/kotlin/ua/wwind/table/interaction/HeaderPointerFocusTest.kt +++ b/table-core/src/commonTest/kotlin/ua/wwind/table/interaction/HeaderPointerFocusTest.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.material3.Text import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember @@ -69,8 +70,7 @@ class HeaderPointerFocusTest { editCell { item, _, _ -> val focus = remember { FocusRequester() } BasicTextField( - value = item, - onValueChange = {}, + state = remember { TextFieldState(item) }, modifier = Modifier.testTag("editor").focusRequester(focus), ) LaunchedEffect(Unit) { focus.requestFocus() } diff --git a/table-core/src/commonTest/kotlin/ua/wwind/table/platform/DateInputFormatTest.kt b/table-core/src/commonTest/kotlin/ua/wwind/table/platform/DateInputFormatTest.kt index 3a54381..0fc9df5 100644 --- a/table-core/src/commonTest/kotlin/ua/wwind/table/platform/DateInputFormatTest.kt +++ b/table-core/src/commonTest/kotlin/ua/wwind/table/platform/DateInputFormatTest.kt @@ -57,12 +57,8 @@ class DateInputFormatTest { assertThat(dotted.display("01122026")).isEqualTo("01.12.2026") } - @Test - fun `cursor offsets skip the separators`() { - // "01.1": digit offsets 0..3 map to 0, 1, 3, 4 in the shown text. - assertThat((0..3).map { dotted.displayOffset("011", it) }).isEqualTo(listOf(0, 1, 3, 4)) - assertThat((0..4).map { dotted.digitOffset("011", it) }).isEqualTo(listOf(0, 1, 2, 2, 3)) - } + private fun DateInputFormat.display(digits: String): String = + StringBuilder(digits).apply { separators(digits.length).forEach { (at, text) -> insert(at, text) } }.toString() private fun Int.pad(): String = toString().padStart(2, '0') } diff --git a/table-format/build.gradle.kts b/table-format/build.gradle.kts index 019337c..d94e8cb 100644 --- a/table-format/build.gradle.kts +++ b/table-format/build.gradle.kts @@ -21,7 +21,7 @@ kotlin { implementation(libs.compose.ui.test) } jvmTest.dependencies { - implementation(compose.desktop.currentOs) + implementation(libs.compose.desktop.jvm) } } } diff --git a/table-format/src/commonMain/kotlin/ua/wwind/table/format/DialogListItem.kt b/table-format/src/commonMain/kotlin/ua/wwind/table/format/DialogListItem.kt new file mode 100644 index 0000000..3f0ca67 --- /dev/null +++ b/table-format/src/commonMain/kotlin/ua/wwind/table/format/DialogListItem.kt @@ -0,0 +1,42 @@ +package ua.wwind.table.format + +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemColors +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.LocalMinimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +/** + * Material's [ListItem] with 48 dp touch targets for the controls in its leading and trailing slots; on its own it + * lays them out without any. + */ +@Composable +internal fun DialogListItem( + modifier: Modifier = Modifier, + overlineContent: @Composable (() -> Unit)? = null, + supportingContent: @Composable (() -> Unit)? = null, + leadingContent: @Composable (() -> Unit)? = null, + trailingContent: @Composable (() -> Unit)? = null, + colors: ListItemColors = ListItemDefaults.colors(), + content: @Composable () -> Unit, +) { + ListItem( + modifier = modifier, + overlineContent = overlineContent, + supportingContent = supportingContent, + leadingContent = leadingContent?.let { { TouchTargets(it) } }, + trailingContent = trailingContent?.let { { TouchTargets(it) } }, + colors = colors, + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + content = content, + ) +} + +@Composable +private fun TouchTargets(content: @Composable () -> Unit) { + CompositionLocalProvider(LocalMinimumInteractiveComponentSize provides 48.dp, content = content) +} diff --git a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogBody.kt b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogBody.kt index 16c4771..76cc844 100644 --- a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogBody.kt +++ b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogBody.kt @@ -18,7 +18,6 @@ import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemColors import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.LocalTextStyle @@ -278,7 +277,7 @@ private fun , FILTER> ReorderableCollectionItemScope.FormatRuleRow( tonalElevation = elevation.value, onClick = onOpen, ) { - ListItem( + DialogListItem( // ListItem merges its own semantics, so screen readers focus it, not the Surface around it. modifier = Modifier.semantics { @@ -292,7 +291,7 @@ private fun , FILTER> ReorderableCollectionItemScope.FormatRuleRow( item.cellStyle.styleLabels(strings).takeIf { it.isNotEmpty() }?.let { { Text(it.joinToString(", "), maxLines = 1) } }, - headlineContent = { + content = { Text( buildRuleTitle(rule = item, getFieldTitle = getTitle, filtersProvider = filters, strings = strings), maxLines = 1, diff --git a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogConditionTab.kt b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogConditionTab.kt index 5890b13..35c26c1 100644 --- a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogConditionTab.kt +++ b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogConditionTab.kt @@ -30,11 +30,11 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RadioButton import androidx.compose.material3.RangeSlider +import androidx.compose.material3.RangeSliderState import androidx.compose.material3.SelectableDates import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -123,14 +123,14 @@ public fun , FILTER> FormatDialogConditionTab( Column { val builtTitle = buildFilterHeaderTitle(filterData = filterData, strings = strings) val hasFilterValues = (filterData.filterState.values?.isNotEmpty() == true) - ListItem( + DialogListItem( overlineContent = if (builtTitle != null) { { Text(getTitle(filterData.field), maxLines = 1) } } else { null }, - headlineContent = { + content = { if (builtTitle != null) { Text(builtTitle, maxLines = 1) } else { @@ -739,13 +739,19 @@ internal fun FormatNumberFilter( } } if (isBetween && filter.rangeOptions != null) { + val sliderFrom = filter.delegate.toSliderValue(fromValue) + val sliderTo = filter.delegate.toSliderValue(toValue) + val trackRange = min.toFloat()..max.toFloat() + val sliderState = remember(trackRange) { RangeSliderState(sliderFrom, sliderTo, trackRange = trackRange) } + // Set on every composition: rememberRangeSliderState would keep the first values. + sliderState.startValue = sliderFrom + sliderState.endValue = sliderTo RangeSlider( - value = filter.delegate.toSliderValue(fromValue)..filter.delegate.toSliderValue(toValue), + state = sliderState, onValueChange = { range -> firstText = inputFormat.format(filter.delegate.fromSliderValue(range.start)) secondText = inputFormat.format(filter.delegate.fromSliderValue(range.endInclusive)) }, - valueRange = min.toFloat()..max.toFloat(), ) } } diff --git a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogFieldTab.kt b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogFieldTab.kt index 0b0f4d7..f3a2711 100644 --- a/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogFieldTab.kt +++ b/table-format/src/commonMain/kotlin/ua/wwind/table/format/FormatDialogFieldTab.kt @@ -8,7 +8,6 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Checkbox import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.ListItem import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -31,8 +30,8 @@ public fun , FILTER> FormatDialogFieldTab( Box(modifier = modifier) { LazyColumn(modifier = Modifier.fillMaxSize(), state = lazyListState) { items(entries) { field -> - ListItem( - headlineContent = { + DialogListItem( + content = { Text(getTitle(field)) }, leadingContent = { diff --git a/table-paging/build.gradle.kts b/table-paging/build.gradle.kts index 08d8097..ba08e35 100644 --- a/table-paging/build.gradle.kts +++ b/table-paging/build.gradle.kts @@ -29,7 +29,7 @@ kotlin { implementation(libs.compose.ui.test) } jvmTest.dependencies { - implementation(compose.desktop.currentOs) + implementation(libs.compose.desktop.jvm) } } } diff --git a/table-sample/build.gradle.kts b/table-sample/build.gradle.kts index cb2e1c8..50002a6 100644 --- a/table-sample/build.gradle.kts +++ b/table-sample/build.gradle.kts @@ -78,7 +78,6 @@ kotlin { } jvmMain.dependencies { - implementation(compose.desktop.currentOs) implementation(libs.compose.desktop.jvm) implementation(libs.kotlinx.coroutines.swing) } diff --git a/table-sample/src/commonMain/kotlin/ua/wwind/table/sample/filter/NumericRangeFilter.kt b/table-sample/src/commonMain/kotlin/ua/wwind/table/sample/filter/NumericRangeFilter.kt index 96bac87..0c0bb68 100644 --- a/table-sample/src/commonMain/kotlin/ua/wwind/table/sample/filter/NumericRangeFilter.kt +++ b/table-sample/src/commonMain/kotlin/ua/wwind/table/sample/filter/NumericRangeFilter.kt @@ -17,6 +17,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RangeSlider +import androidx.compose.material3.RangeSliderState import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Text @@ -207,15 +208,19 @@ private class NumericRangeFilterRenderer : CustomFilterRenderer isUpdatingFromSlider = true rangeMin = range.start rangeMax = range.endInclusive }, onValueChangeFinished = { applyFilter() }, - valueRange = dataMin.toFloat()..dataMax.toFloat(), modifier = Modifier.fillMaxWidth(), )