Skip to main content

CamoTextField

Concept​

1. Why​

The text field is the hardest v1 component. It combines controlled text, focus, the keyboard (IME), error reporting and a lot of visual states, and each design language draws it differently (Material's floating label, iOS's plain rounded field). The key architectural rule proven here: the editable text node lives in core, not in the renderer. The skin decorates around it, so switching skins never loses the cursor, selection or keyboard.

2. Shape​

Value flow (controlled):

  1. The user types "a".
  2. The platform input reports "a".
  3. Core calls onValueChange("a").
  4. The app stores it and passes value = "a" back.
  5. The field shows "a".

If the app doesn't update value, the field keeps showing the old value, which is how input can be filtered (digits only).

Material mapping preview: the Outlined text field.

  • The label sits inside and floats to the top border on focus or when non-empty.
  • The outline is outline, primary when focused, and error when in error.
  • Icons are onSurfaceVariant at size 24. The suffix icon turns error in the error state.

See Material Skin.

3. API​

Contract​

fun CamoTextField(
value: String,
onValueChange: (String) -> Unit,
label: String? = null,
placeholder: String? = null,
supportingText: String? = null, // helper text below the field
error: String? = null, // non-null = error state; replaces supportingText
prefixIcon: Widget? = null, // e.g. AppIcon.mail(), decorative
suffixIcon: Widget? = null, // e.g. AppIcon.clear(), or a CamoFieldAction for an action
prefixText: String? = null, // e.g. "+62", "Rp"; never part of value
suffixText: String? = null, // e.g. "kg", ".com"
enabled: Boolean = true,
singleLine: Boolean = true,
secure: Boolean = false, // password: obscured text, no autocorrect, no copy
onFocusChanged: ((Boolean) -> Unit)? = null, // for validation timing (OnUnfocus)
inputFilter: CamoInputFilter? = null, // blocks or trims input before it reaches onValueChange
displayFormat: CamoDisplayFormat? = null, // shows formatting without storing it
)
ParameterWhat it's for
value, onValueChangecontrolled text
prefixText, suffixTextfixed text inside the field, next to the input ("+62", "kg"). Not part of value. Drawn in the placeholder color, and shown only when the field is focused or non-empty, so it never collides with a floating label. Screen readers read it with the value.
label, placeholder, supportingText, errortext values. The renderer draws them in the skin's styles.
prefixIcona decorative icon widget at the start (mail, search)
suffixIconan icon widget at the end. For an action (clear, show password), pass a CamoFieldAction, which brings its own label and click without a container, so the field keeps its height.
enabled, singleLine, securebehavior flags
onFocusChangedreports focus changes. Used by form fields for OnUnfocus validation.

Inside a form, use CamoTextFormField (CamoForm). It takes the same parameters, minus value/onValueChange/error, plus key, rules, onSaved and initialValue. | inputFilter | which input is allowed (digits only, max length). Applied by core before onValueChange, so the app never sees rejected characters. | | displayFormat | how the raw value is shown (081234567890 shown as 0812-3456-7890). value stays raw. Core maps the cursor between raw and shown text, so it never jumps. |

Formatting without cursor jumps. The editable node lives in core (ADR-10), so core sees the old text, the new text and the cursor together. That's why filtering and formatting are parameters handled by core, not something the app does inside onValueChange (which is what makes the cursor jump to the end). Each platform maps them to its own cursor-safe mechanism:

BaseComposeFlutter
inputFilterInputTransformation (state-based BasicTextField)TextInputFormatter in inputFormatters
displayFormatOutputTransformation (or VisualTransformation with an OffsetMapping)a formatter that keeps a raw value and maps the selection offset
interface CamoInputFilter {
fun filter(old: String, new: String): String // return the accepted raw text
companion object {
fun digitsOnly(maxLength: Int? = null): CamoInputFilter
fun maxLength(n: Int): CamoInputFilter
fun pattern(regex: Regex): CamoInputFilter // allowed characters
fun decimal(decimals: Int = 2, decimalSeparator: Char = ','): CamoInputFilter // digits, one separator, at most `decimals` after it
}
}
interface CamoDisplayFormat {
fun format(raw: String): String // what the user sees
fun rawToShown(offset: Int, raw: String): Int // cursor mapping
fun shownToRaw(offset: Int, shown: String): Int
companion object {
fun pattern(mask: String): CamoDisplayFormat // "####-####-####", '#' = one raw char
fun grouping(separator: Char = '.', size: Int = 3): CamoDisplayFormat // 1.250.000
fun decimal(decimals: Int = 2, decimalSeparator: Char = ',', groupSeparator: Char = '.'): CamoDisplayFormat // 1.250.000,50
}
}

Recipes with pattern (no extra built-ins needed): a card number pattern("#### #### #### ####") with digitsOnly(16), an expiry pattern("##/##") with digitsOnly(4). Brand detection (Amex 4-6-5) is app logic: write your own CamoDisplayFormat.

Example (Indonesian phone number):

CamoTextField(value = phoneDigits, onValueChange = { phoneDigits = it }, label = "Phone",
inputFilter = CamoInputFilter.digitsOnly(maxLength = 13),
displayFormat = CamoDisplayFormat.pattern("####-####-#####"))

Platform extras (added in platform notes): keyboard type and IME action (KeyboardOptions / TextInputType + TextInputAction), onImeAction, autofill hints.

Show-password pattern:

var hidden by state(true)
CamoTextField(value = pw, onValueChange = setPw, label = "Password", secure = hidden,
suffixIcon = CamoFieldAction(icon = if (hidden) AppIcon.eye() else AppIcon.eyeOff(),
contentDescription = if (hidden) "Show password" else "Hide password",
onClick = { hidden = !hidden }))

Field actions: CamoFieldAction, not CamoIconButton (changed in the M5 build). A CamoIconButton brings its own container and touch target (40–48), which makes a field with an action taller than its neighbours. CamoFieldAction has no container: it takes the ambient icon style the renderer sets for the field's icons (size and color, so it turns error with the suffix), measures the icon plus spacing.s square, and uses the skin's interaction feedback. It's still its own focusable button, after the input, with its own label. The search field's clear action is one too.

fun CamoFieldAction(icon: Widget, contentDescription: String, onClick: () -> Unit, enabled: Boolean = true)

Building block (ADR-30): CamoFieldFrame. The text field's frame (label with its labelPlacement, border and focus ring, prefix/suffix icons and texts, supporting and error text) around any input:

fun CamoFieldFrame(
label: String? = null, supportingText: String? = null, error: String? = null,
prefixIcon: Widget? = null, suffixIcon: Widget? = null,
focused: Boolean, enabled: Boolean = true, isEmpty: Boolean, // the frame can't know these about custom content
content: Slot, // e.g. six OTP boxes, a country picker + number field
)

It's drawn by the same TextFieldRenderer, with content in the input slot, so custom inputs match the brand's text fields exactly. The content provides its own semantics; the frame links label and error to it.

State → renderer: TextFieldState(value (raw), label?, placeholder?, supportingText?, error?, prefixText?, suffixText?, enabled, focused, singleLine, secure, isEmpty).

Slots: TextFieldSlots(prefixIcon?, suffixIcon?, input). input is the editable node from core, already filtered and showing the formatted text. The renderer places it but never recreates it, and never formats. Formatting is behavior, so it stays in core under every skin.

Tokens used​

TokenUse
colors.outline / primary / errorborder: resting / focused / error
colors.onSurface / onSurfaceVariantinput text / label, placeholder, supporting, icons
colors.errorerror text, border, and the suffix icon in error
shapes.extraSmallcontainer
typography.bodyLarge (input), bodySmall (supporting/error), bodyLarge → bodySmall (floating label)text
spacing.l horizontal (spacing.m next to an icon), spacing.xs above supporting textpadding
motion.durationShort + easingStandardlabel float, border color change

Component theme​

theme.components.textField: TextFieldTheme?. Every field is nullable in the theme. The skin's defaults(theme) fills whatever isn't set (Material defaults shown). See Theme §3.10.

FieldTypeMaterial defaultWhat it's for
labelPlacementLabelPlacement (Above | Floating)Floatingwhere the label sits: Above = a static label over the field; Floating = inside the field, moving to the top edge on focus or when non-empty. Every skin draws both. Its own default is the skin-level fallback (Minimal: Above).
heightDp56minimum single-line height
shapeShapeshapes.extraSmallcontainer corners
contentPaddingPaddinghorizontal 16 (12 next to an icon)padding around the input
textStyleCamoTextStyletypography.bodyLargethe typed text
labelStyle / floatingLabelStyleCamoTextStylebodyLarge / bodySmallthe label, resting and floated. With Above, only floatingLabelStyle is used (the label never moves).
supportingTextStyleCamoTextStyletypography.bodySmallsupporting and error text
iconSizeDp24the ambient icon size for prefix and suffix
borderWidth / focusedBorderWidthDp1 / 2outline thickness
colorsTextFieldColors(container, border, focusedBorder, errorBorder, text, label, placeholder, icon)transparent, outline, primary, error, onSurface, onSurfaceVariant, onSurfaceVariant, onSurfaceVariantevery color the field uses

Accessibility​

  • The platform text-input role, with the accessible name = label. A placeholder is not a label: if label is null, the placeholder is used as a fallback name, and debug builds warn.
  • The error is announced: the field is marked invalid, and the error text is linked as its description and announced when it appears.
  • Supporting text is linked as the description.
  • secure fields are announced as password fields, and their content isn't read out.
  • prefixIcon is decorative. A suffixIcon that is a CamoFieldAction is a separate focusable element with its own label, reached after the input.
  • The whole field height is the touch target. Tapping the label or prefix focuses the input.

4. Build steps​

  1. Core:
    1. keep the platform editable node;
    2. track focus;
    3. build TextFieldState;
    4. build the slots (icons plus input);
    5. apply semantics (label, error, description);
    6. call skin.textField.render.
  2. secure switches the node into obscured mode, with autocorrect and suggestions off.
  3. DebugSkin renderer: a bordered box with the label above, then prefix / input / suffix in a row, then supporting or error text below.
  4. Implement inputFilter and displayFormat in core with the platform mechanisms in the table, plus the built-ins (digitsOnly, maxLength, pattern, grouping, decimal).
  5. Sample: a login form with email (prefixIcon = AppIcon.mail(), supporting text), password (show-password pattern), a phone field (digitsOnly + pattern("####-####-#####")), an amount field (grouping), a search field with its clear action, and one disabled field.
  6. Tests:
    • typing calls onValueChange;
    • with digitsOnly, typing a letter doesn't call onValueChange;
    • with the phone pattern, value stays raw digits, the field shows dashes, and typing in the middle keeps the cursor after the typed digit;
    • deleting a dash position deletes the digit before it;
    • paste of 0812-3456-7890 is filtered to 081234567890;
    • ignored updates keep the old text;
    • error sets invalid semantics and replaces the supporting text;
    • the label is the accessible name;
    • the suffix field action is focusable with its own label, and the field is as tall as one without it;
    • the prefix icon has no semantics;
    • switching the skin while focused keeps focus and cursor position.

Done when

  • The login sample works end to end with the keyboard: Next moves focus, Done submits.
  • The show-password toggle works and is announced correctly.
  • The skin switch while typing keeps focus, text and selection.

5. Edge cases​

CaseDecided behavior
Skin or theme switched while typingFocus, text, selection and the open keyboard survive, because the editable node stays in core at the same tree position.
Label placement resolutionlabelPlacement resolves like any component-theme field: the nearest TextFieldTheme in the tree wins, else the skin's default. To switch one field, wrap it in a provider with a TextFieldTheme(labelPlacement = …). There's no per-call parameter, so a screen can't drift from its brand by accident. CamoSelect and CamoSearchField reuse the text-field frame and follow the same setting.
Floating with no labelBehaves like Above with no label: no reserved space.
Font scale 200%The field grows in height. Multi-line fields grow with content. The floating label never overlaps the input. Icons stay 24.
RTL, and bidi inputThe text direction follows the content. The prefix icon is at the start (right), and the suffix at the end.
Very long single-line valueScrolls horizontally inside the field. It doesn't wrap.
error and supportingText both seterror wins, so there's one message at a time.
enabled = false with a valueThe text stays visible (dimmed), isn't focusable, and is announced as disabled. The suffix field action is disabled too.
Formatting (dashes, thousand separators)Done by displayFormat in core, with the cursor mapped, so there's no jump. value stays raw.
The app changes value programmatically while focused (e.g. clears it)The cursor moves to the end of the new text. Setting the cursor position from the app isn't supported in v1. A state-based overload can add it later without breaking anything.
A filter rejects a paste entirelyNothing changes, and onValueChange isn't called. Platform feedback (no sound or vibration) is default.
displayFormat with secure = trueNot allowed. Debug builds assert, because formatting obscured text makes no sense.
Password managers / autofillPlatform extras (autofill hints).
Custom inputs (OTP boxes, a phone field with a country picker, an amount with a currency select)Built with CamoFieldFrame (ADR-30). CamoSelect already works this way internally.

Implementation​

1. Why​

This is the hardest Kotlin component. It uses Compose foundation's state-based BasicTextField(state: TextFieldState), whose InputTransformation and OutputTransformation implement the base note's inputFilter and displayFormat with correct cursor mapping built in. The public API stays value: String (ADR-16). Core keeps an internal text buffer and syncs it with value, the same technique Compose's own value-based text field overloads use.

2. Shape​

  • inputFilter → an InputTransformation, which edits or reverts the change before it's committed to the buffer.
  • displayFormat → an OutputTransformation, which inserts separators only in the displayed text. Compose maps the cursor across inserted characters automatically, so CamoDisplayFormat in Kotlin doesn't need the manual rawToShown/shownToRaw functions.
  • secure = true → BasicSecureTextField (obscured, no copy, password keyboard).

3. API​

@Composable
public fun CamoTextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
label: String? = null,
placeholder: String? = null,
supportingText: String? = null,
error: String? = null,
prefixIcon: (@Composable () -> Unit)? = null,
suffixIcon: (@Composable () -> Unit)? = null,
prefixText: String? = null,
suffixText: String? = null,
enabled: Boolean = true,
singleLine: Boolean = true,
secure: Boolean = false,
onFocusChanged: ((Boolean) -> Unit)? = null,
inputFilter: CamoInputFilter? = null,
displayFormat: CamoDisplayFormat? = null,
keyboardOptions: KeyboardOptions = KeyboardOptions.Default, // platform extra
onKeyboardAction: KeyboardActionHandler? = null, // platform extra (IME action)
interactionSource: MutableInteractionSource? = null,
)

Filters and formats:

public fun interface CamoInputFilter {
public fun filter(old: String, new: String): String // base contract
}
internal fun CamoInputFilter.toInputTransformation() = InputTransformation {
val accepted = filter(originalText.toString(), asCharSequence().toString())
if (accepted != asCharSequence().toString()) replace(0, length, accepted) // keeps the cursor sane
}

public fun interface CamoDisplayFormat {
public fun format(raw: String): String // base contract, used on Flutter
}
public interface CamoInsertingFormat : CamoDisplayFormat { // Kotlin fast path
public fun OutputTransformation.insertInto(buffer: TextFieldBuffer)
}
// built-ins implement CamoInsertingFormat:
// CamoDisplayFormat.pattern("####-####-#####") inserts '-' at mask positions,
// CamoDisplayFormat.grouping('.', 3) inserts '.' every 3 digits from the right,
// CamoDisplayFormat.decimal(2, ',', '.') groups the integer part and keeps at most 2 decimals after ','

A custom CamoDisplayFormat that only implements format() falls back to replacing the displayed text, with the cursor placed at the end of the change. Prefer the inserting form for anything typed mid-string.

Semantics:

  • The input is named through its decorator (changed in the M5 build). Compose's text-field node merges its own descendants, so a parent merge can't reach it. Core's TextFieldDecorator adds a zero-size Box with semantics { text = label } inside the editable node, so the label is its name; camoError goes on the input too. Renderers hide the label, placeholder and error they draw (clearAndSetSemantics), so nothing is read twice.
  • Don't set contentDescription: on a text field it would replace the typed text in the announcement.
  • error(message) when error != null.
  • password() when secure.

Label placement. The renderer reads style.labelPlacement (theme tree → the skin's default → Above). Floating animates the label between the resting position inside the field and the top edge with animateFloatAsState(if (focused || !isEmpty) 1f else 0f), interpolating position and text style (labelStyle → floatingLabelStyle), and cuts the outline behind it with a surface-colored background on the label. Above draws the label as a plain CamoText over the frame.

Building block CamoFieldFrame (ADR-30):

@Composable
public fun CamoFieldFrame(
focused: Boolean,
isEmpty: Boolean,
modifier: Modifier = Modifier,
label: String? = null, supportingText: String? = null, error: String? = null,
prefixIcon: (@Composable () -> Unit)? = null, suffixIcon: (@Composable () -> Unit)? = null,
enabled: Boolean = true,
content: @Composable () -> Unit, // OTP boxes, a country picker + number field, …
)

It calls skin.textField.Render with content in the input slot, so custom inputs share the brand's frame exactly. Semantics: the frame sets contentDescription = label and error(error) on a merged node around content; the content's own editable nodes stay focusable. CamoSelect uses it.

4. Build steps​

  1. CamoInputFilter + built-ins (digitsOnly, maxLength, pattern(regex)) + toInputTransformation().
  2. CamoDisplayFormat + CamoInsertingFormat + built-ins (pattern, grouping, decimal).
  3. CamoTextField: the buffer, two-way sync, BasicTextField / BasicSecureTextField as the input slot, focus → onFocusChanged, semantics, and delegation to skin.textField.Render.
  4. DebugSkin.textField: a bordered column (label, row of prefix/input/suffix, supporting or error).
  5. commonTest (runComposeUiTest):
    • performTextInput("a") → onValueChange("a");
    • with digitsOnly, performTextInput("a") → no callback;
    • phone pattern: value "08123" shows "0812-3"; placing the cursor after 8 and typing 9 gives raw "081923", and the cursor is right after the 9;
    • performTextReplacement("0812-3456-7890") → raw "081234567890";
    • error = "x" → SemanticsProperties.Error present;
    • switching the skin while focused keeps isFocused and the selection.

Done when

  • The login and phone samples work with hardware and on-screen keyboards on Android, iOS, desktop and web.
  • The skin-switch-while-typing test passes.

5. Edge cases​

CaseDecided behavior
value changed by the app while focusedThe sync edit replaces the text, and the cursor goes to the end (base §5). An edit that equals the current buffer text is skipped, so user typing never loops.
Sync loop riskonValueChange is emitted from snapshotFlow { buffer.text } only when the text differs from the last value. There's a test for it.
displayFormat + securerequire(!(secure && displayFormat != null)).
IME composition (CJK, Indonesian autocorrect underline)InputTransformations run on committed edits. Composition text shows until committed, so filters don't fight the IME. Test with a CJK keyboard on Android.
Web targetText input on the Compose web canvas uses a hidden HTML input. Autofill and password managers are limited (Beta, ADR-18).
iOSNative text selection handles and the loupe come from Compose Multiplatform (stable since 1.8).
KeyboardOptions / KeyboardActionHandlerPlatform extras, passed straight to BasicTextField.
Custom inputsCamoFieldFrame (ADR-30). The app passes focused (e.g. interactionSource.collectIsFocusedAsState() of any child) and isEmpty, which the frame can't know about custom content.