Untitled conversation
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
private fun filterNumericInput(text: String): String =
text.filterNot { it.isWhitespace() }.filter { it.isDigit() }
private fun filterRangeInput(text: String): String {
val filtered = text.filterNot { it.isWhitespace() }
return when {
filtered.isEmpty() -> filtered
filtered.first() == '-' -> "-${filtered.substring(1).filter { it.isDigit() }}"
else -> filtered.filter { it.isDigit() }
}
}
private fun filterNoWhitespace(text: String): String = text.filterNot { it.isWhitespace() }
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GeneratorOptionsScreen(
generatorType: GeneratorType,
onNavigateBack: () -> Unit,
modifier: Modifier = Modifier,
viewModel: GeneratorOptionsViewModel = hiltViewModel()
) {
val uiState by viewModel.getUiState().collectAsState()
val titleResId =
when (generatorType) {
GeneratorType.NUM -> R.string.gen_title_num
GeneratorType.ALPHANUM -> R.string.gen_title_alphanum
GeneratorType.NUM_RANGE -> R.string.gen_title_num_range
GeneratorType.NUM_FIXED -> R.string.gen_title_num_fixed
GeneratorType.HEX -> R.string.gen_title_hex
}
LaunchedEffect(generatorType) {
viewModel.loadOptions(generatorType)
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(
stringResource(
R.string.generator_options_title,
stringResource(titleResId)
)
)
},
navigationIcon = {
IconButton(onClick = onNavigateBack) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.cd_navigate_back)
)
}
}
)
},
modifier = modifier
) { scaffoldPadding ->
Column(
modifier =
Modifier
.fillMaxSize()
.padding(scaffoldPadding)
.padding(16.dp)
) {
uiState.options?.let { options ->
GeneratorOptionsContent(
options = options,
validationError = uiState.validationError,
onUpdateOptions = viewModel::saveOptions,
onClearError = viewModel::clearError
)
}
}
}
}
@Composable
private fun SaveButton(onClick: () -> Unit) {
IconButton(
onClick = onClick,
modifier =
Modifier
.padding(end = 8.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.primary)
.size(40.dp)
) {
Icon(
imageVector = Icons.Default.Done,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimary
)
}
}
@Composable
private fun SupportingErrorText(validationError: ValidationErrorViewData) {
when (validationError.reason) {
Reason.ZeroOrLessMax ->
Text(text = stringResource(R.string.error_gen_zero_or_less_max_msg))
is Reason.LengthExcess ->
Text(
text =
stringResource(
R.string.error_gen_length_excess_msg_format,
validationError.reason.maxLength
)
)
Reason.ZeroOrLessLength ->
Text(text = stringResource(R.string.error_gen_zero_or_less_length_msg))
Reason.InvalidRange ->
Text(text = stringResource(R.string.error_gen_invalid_range_msg))
Reason.Unknown ->
Text(text = stringResource(R.string.error_gen_unknown_msg))
Reason.InvalidFormat ->
Text(text = stringResource(R.string.error_gen_invalid_argument_format_msg))
Reason.None -> Unit
}
}
@Composable
private fun ValidatedOutlinedTextField(
value: String,
originalValue: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
label: @Composable () -> Unit,
validationError: ValidationErrorViewData?,
isErrorApplicable: () -> Boolean,
keyboardOptions: KeyboardOptions,
onSave: () -> Unit,
onClearError: () -> Unit
) {
val errorApplicable = isErrorApplicable()
val isErrorState = validationError != null && errorApplicable
OutlinedTextField(
value = value,
onValueChange = onValueChange,
modifier =
modifier.onFocusChanged { focusState ->
if (!focusState.isFocused) {
if (value != originalValue) {
onValueChange(originalValue)
}
if (isErrorState) {
onClearError()
}
}
},
label = label,
shape = MaterialTheme.shapes.extraLarge,
trailingIcon = {
if (value != originalValue) {
SaveButton(onClick = onSave)
}
},
keyboardOptions = keyboardOptions,
singleLine = true,
isError = isErrorState,
supportingText = {
if (validationError != null && errorApplicable) {
SupportingErrorText(validationError)
} else {
Spacer(modifier = Modifier.height(16.dp))
}
}
)
}
@Composable
private fun GeneratorOptionsContent(
options: GeneratorOptions,
validationError: ValidationErrorViewData?,
onUpdateOptions: (GeneratorOptionsUpdateViewData) -> Unit,
onClearError: () -> Unit
) {
val modifier =
Modifier
.padding(vertical = 8.dp)
.fillMaxWidth()
val numberKeyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
)
val textKeyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
)
when (options) {
is NumGeneratorOptions -> {
var maxText by rememberSaveable { mutableStateOf(options.max.toString()) }
ValidatedOutlinedTextField(
value = maxText,
originalValue = options.max.toString(),
onValueChange = { maxText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_value)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is NumGeneratorMaxUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumGeneratorMaxUpdate(maxText)) },
onClearError = onClearError
)
}
is NumFixedGeneratorOptions -> {
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
ValidatedOutlinedTextField(
value = lengthText,
originalValue = options.length.toString(),
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is NumFixedGeneratorLengthUpdate
},
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumFixedGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
}
is HexGeneratorOptions -> {
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
ValidatedOutlinedTextField(
value = lengthText,
originalValue = options.length.toString(),
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is HexGeneratorLengthUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(HexGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
}
is NumRangeGeneratorOptions -> {
var minText by rememberSaveable { mutableStateOf(options.min.toString()) }
var maxText by rememberSaveable { mutableStateOf(options.max.toString()) }
ValidatedOutlinedTextField(
value = minText,
originalValue = options.min.toString(),
onValueChange = { minText = filterRangeInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_min_value)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is NumRangeGeneratorMinUpdate
},
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumRangeGeneratorMinUpdate(minText)) },
onClearError = onClearError
)
ValidatedOutlinedTextField(
value = maxText,
originalValue = options.max.toString(),
onValueChange = { maxText = filterRangeInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_value)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is NumRangeGeneratorMaxUpdate
},
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumRangeGeneratorMaxUpdate(maxText)) },
onClearError = onClearError
)
}
is AlphanumGeneratorOptions -> {
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
var symbols by rememberSaveable { mutableStateOf(options.customSymbols) }
ValidatedOutlinedTextField(
value = lengthText,
originalValue = options.length.toString(),
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is AlphanumGeneratorLengthUpdate
},
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(AlphanumGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
Spacer(modifier = Modifier.height(8.dp))
ValidatedOutlinedTextField(
value = symbols,
originalValue = options.customSymbols,
onValueChange = {
symbols = filterNoWhitespace(it).take(MAX_CUSTOM_CHARACTERS_LENGTH)
},
modifier = modifier,
label = { Text(text = stringResource(R.string.et_custom_chars)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is AlphanumGeneratorCustomSymbolsUpdate
},
keyboardOptions = textKeyboardOptions,
onSave = { onUpdateOptions(AlphanumGeneratorCustomSymbolsUpdate(symbols)) },
onClearError = onClearError
)
}
}
}
currently, if user had a value like 12 and enters a new value 012 and hits save, save button wont hide because of value != originalValue condition. can we somehow just update the current value once it's saved to make sure we will use the sanitized/converted one from ui state?
You're hitting a common issue when managing mutable state that needs to be synchronized with a source of truth (like your uiState.options). The problem lies in how originalValue is used and how the local state (maxText, lengthText, etc.) is updated.
Here's the breakdown:
originalValue: In ValidatedOutlinedTextField, originalValue is passed as a String snapshot of the options value at the time the composable was rendered. It doesn't automatically update when uiState.options changes.maxText, etc.): You're using rememberSaveable { mutableStateOf(...) } to hold the user's current input. This state is independent of the options state unless you explicitly sync them.SaveButton Condition: The SaveButton shows if value != originalValue. If originalValue is 12 and the user types 012, your value becomes 012. The filterRangeInput or filterNumericInput filters it to 012, which is what maxText holds. The comparison value != originalValue becomes "012" != "12", which is true, so the Save button should appear.The actual problem described ("save button wont hide because of value != originalValue condition") seems to be a misunderstanding or perhaps a different scenario than the 012 vs 12 example. If originalValue is 12 and the user types 012, value (which is maxText in your example) becomes 012. The condition maxText != options.max.toString() would be 012 != 12, which is true. The Save button should show.
However, the core idea you're aiming for is:
uiState.options.uiState.options, and this update should correctly reset the UI state so the Save button hides.To achieve this reliably, you need to:
options state whenever options changes externally.options value for the Save button visibility.Here's how you can modify your code:
1. Modify ValidatedOutlinedTextField
Rename originalValue to canonicalValue to make its purpose clearer. This canonicalValue will be the string representation of the actual saved option from your ViewModel/uiState.
@Composable
private fun ValidatedOutlinedTextField(
value: String, // The current text being displayed/edited in the field
canonicalValue: String, // The true, saved value from the source of truth
onValueChange: (String) -> Unit, // Updates the local 'value' state
modifier: Modifier = Modifier,
label: @Composable () -> Unit,
validationError: ValidationErrorViewData?,
isErrorApplicable: () -> Boolean,
keyboardOptions: KeyboardOptions,
onSave: () -> Unit, // Called when SaveButton is clicked
onClearError: () -> Unit // Optional: called on focus lost if error was present
) {
val errorApplicable = isErrorApplicable()
val isErrorState = validationError != null && errorApplicable
// Determine if there are unsaved changes by comparing the current displayed value
// with the canonical (saved) value.
val hasUnsavedChanges = value != canonicalValue
OutlinedTextField(
value = value,
onValueChange = onValueChange, // This updates the 'value' state managed by the caller
modifier = modifier.onFocusChanged { focusState ->
if (!focusState.isFocused) {
// The original logic `if (value != originalValue) { onValueChange(originalValue) }`
// was problematic. It would revert `012` back to `12` on losing focus.
// We want to keep the user's input (`012`) until they save it.
// So, we should *not* revert the text field value here if it's different.
// The SaveButton logic will correctly show the button if `value != canonicalValue`.
// Optionally, clear the error when losing focus. Be cautious with this,
// as the user might want to see the error persist until corrected.
// If you remove this, the error will remain visible until the next save attempt or correction.
// if (isErrorState) {
// onClearError()
// }
}
},
label = label,
shape = MaterialTheme.shapes.extraLarge,
trailingIcon = {
// Show Save button only if there are unsaved changes.
if (hasUnsavedChanges) {
SaveButton(onClick = onSave)
}
},
keyboardOptions = keyboardOptions,
singleLine = true,
isError = isErrorState,
supportingText = {
if (validationError != null && errorApplicable) {
SupportingErrorText(validationError)
} else {
// Ensure consistent height to avoid layout shifts
Spacer(modifier = Modifier.height(16.dp))
}
}
)
}
2. Modify GeneratorOptionsContent
For each options type, you need to:
rememberSaveable state for the text field's value.LaunchedEffect to update this local state whenever the corresponding value in uiState.options changes. This ensures the local state always reflects the latest canonical value.uiState.options (as a String) as the canonicalValue to ValidatedOutlinedTextField.@Composable
private fun GeneratorOptionsContent(
options: GeneratorOptions,
validationError: ValidationErrorViewData?,
onUpdateOptions: (GeneratorOptionsUpdateViewData) -> Unit,
onClearError: () -> Unit
) {
val modifier =
Modifier
.padding(vertical = 8.dp)
.fillMaxWidth()
val numberKeyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Done
)
val textKeyboardOptions =
KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
)
when (options) {
is NumGeneratorOptions -> {
// Use local mutable state for the text field's display value
var maxText by rememberSaveable { mutableStateOf(options.max.toString()) }
// Sync local state with the canonical state from options whenever options change externally.
// This handles cases where the ViewModel might update the options state directly.
LaunchedEffect(options.max) {
maxText = options.max.toString()
}
ValidatedOutlinedTextField(
value = maxText, // The current text in the field (managed by rememberSaveable)
canonicalValue = options.max.toString(), // The true, saved value for comparison
onValueChange = { newText ->
maxText = filterNumericInput(newText).take(MAX_INPUT_LENGTH)
},
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_value)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is NumGeneratorMaxUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = {
// When saving, pass the current text field value to the ViewModel.
// The ViewModel will parse and validate it.
onUpdateOptions(NumGeneratorMaxUpdate(maxText))
},
onClearError = onClearError // Pass the function to clear error if needed
)
}
is NumFixedGeneratorOptions -> {
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
LaunchedEffect(options.length) { lengthText = options.length.toString() } // Sync
ValidatedOutlinedTextField(
value = lengthText,
canonicalValue = options.length.toString(), // Canonical value
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is NumFixedGeneratorLengthUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumFixedGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
}
is HexGeneratorOptions -> {
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
LaunchedEffect(options.length) { lengthText = options.length.toString() } // Sync
ValidatedOutlinedTextField(
value = lengthText,
canonicalValue = options.length.toString(), // Canonical value
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is HexGeneratorLengthUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(HexGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
}
is NumRangeGeneratorOptions -> {
// Min value
var minText by rememberSaveable { mutableStateOf(options.min.toString()) }
LaunchedEffect(options.min) { minText = options.min.toString() } // Sync
ValidatedOutlinedTextField(
value = minText,
canonicalValue = options.min.toString(), // Canonical value
onValueChange = { minText = filterRangeInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_min_value)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is NumRangeGeneratorMinUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumRangeGeneratorMinUpdate(minText)) },
onClearError = onClearError
)
// Max value
var maxText by rememberSaveable { mutableStateOf(options.max.toString()) }
LaunchedEffect(options.max) { maxText = options.max.toString() } // Sync
ValidatedOutlinedTextField(
value = maxText,
canonicalValue = options.max.toString(), // Canonical value
onValueChange = { maxText = filterRangeInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_value)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is NumRangeGeneratorMaxUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(NumRangeGeneratorMaxUpdate(maxText)) },
onClearError = onClearError
)
}
is AlphanumGeneratorOptions -> {
// Length
var lengthText by rememberSaveable { mutableStateOf(options.length.toString()) }
LaunchedEffect(options.length) { lengthText = options.length.toString() } // Sync
ValidatedOutlinedTextField(
value = lengthText,
canonicalValue = options.length.toString(), // Canonical value
onValueChange = { lengthText = filterNumericInput(it).take(MAX_INPUT_LENGTH) },
modifier = modifier,
label = { Text(text = stringResource(R.string.et_max_length)) },
validationError = validationError,
isErrorApplicable = { validationError?.optionsUpdate is AlphanumGeneratorLengthUpdate },
keyboardOptions = numberKeyboardOptions,
onSave = { onUpdateOptions(AlphanumGeneratorLengthUpdate(lengthText)) },
onClearError = onClearError
)
Spacer(modifier = Modifier.height(8.dp))
// Custom Symbols
var symbols by rememberSaveable { mutableStateOf(options.customSymbols) }
LaunchedEffect(options.customSymbols) { symbols = options.customSymbols } // Sync
ValidatedOutlinedTextField(
value = symbols,
canonicalValue = options.customSymbols, // Canonical value
onValueChange = {
symbols = filterNoWhitespace(it).take(MAX_CUSTOM_CHARACTERS_LENGTH)
},
modifier = modifier,
label = { Text(text = stringResource(R.string.et_custom_chars)) },
validationError = validationError,
isErrorApplicable = {
validationError?.optionsUpdate is AlphanumGeneratorCustomSymbolsUpdate
},
keyboardOptions = textKeyboardOptions,
onSave = { onUpdateOptions(AlphanumGeneratorCustomSymbolsUpdate(symbols)) },
onClearError = onClearError
)
}
}
}
Explanation of Changes:
ValidatedOutlinedTextField:
originalValue parameter to canonicalValue.hasUnsavedChanges check now correctly compares value (the current text in the field) with canonicalValue (the saved value from uiState.options). This ensures the Save button appears only when the displayed text differs from the actual stored value.onValueChange(originalValue) call within onFocusChanged. This was the problematic line that reverted user input. Now, the user's input (e.g., 012) is preserved until they explicitly save.onClearError() on focus lost. It's often better UX to let errors persist until the condition is resolved.GeneratorOptionsContent:
NumGeneratorOptions), we now declare a local state variable (var maxText by rememberSaveable { ... }).LaunchedEffect(options.max): This is the key to synchronization. Whenever the options.max value from the uiState changes, this effect runs and updates the local maxText state to match it. This ensures that if the ViewModel updates the option, the text field reflects that change, and the hasUnsavedChanges check will then evaluate correctly.canonicalValue parameter of ValidatedOutlinedTextField is now explicitly set to options.max.toString(), options.length.toString(), etc. This provides the correct baseline for comparison.onSave lambda now calls onUpdateOptions with the current value of the local state (maxText or lengthText), which is the user's potentially modified input.With these changes, when the user types 012 into a field that originally held 12:
maxText becomes 012.canonicalValue is 12.hasUnsavedChanges is true ("012" != "12").When the user clicks Save:
onUpdateOptions(NumGeneratorMaxUpdate("012")) is called."012", likely converting it to the integer 12 and updating uiState.options.max to 12.LaunchedEffect(options.max) sees that options.max is now 12.maxText to "12".canonicalValue passed to ValidatedOutlinedTextField is also "12".hasUnsavedChanges becomes false ("12" != "12").This correctly handles the synchronization and ensures the Save button reflects the actual state of the data.