Build an input

Write a component the end user enters something into, and connect what they enter to the rest of a flow.

An input is a component with a value. In the designer the value is bound to a variable, both ways: what the end user picks or types is written to the variable, and a change to the variable from anywhere else shows in the component. A component can build its value from pointers and presses, as a slider does, or from text typed into a text input it embeds, as a code field does.

Before you build one, check the inputs Voidhash already offers: a toggle, a segmented control, a ruler for numbers such as a weight, a wheel picker for a date, a time or one of a list, a slider, chips and a one-time code field. A project installs the ones it uses from the Voidhash tab of its Components page, and they then insert like your own components and bind to a variable the same way.

Both kinds need guest ABI 3. #[component] declares it for a component that has a value or calls text_input(); a component with neither stays ABI 2.

A component with a value

Take the value as the parameter marked #[value]. Its type is Input<String>, Input<f64>, Input<bool> or Input<Vec<String>> (a list, such as the chips a person picked), which is also the type of variable the designer offers for it:

/// A star rating from one to five.
#[component(id = "project/rating", traits(frame(resize = "none"), states, interactions))]
pub fn Rating(cx: Cx, #[value] stars: Input<f64>) -> View {
    let current = stars.get();
    hstack().spacing(4).children((1..=5).map(|star| {
        text(if f64::from(star) <= current { "★" } else { "☆" })
            .font(Font::size(28.0))
            .on_tap(move |cx| stars.set(cx, f64::from(star)))
    }))
}
  • stars.get() is the value now, whoever set it last: the component, an action of the flow or your app.
  • stars.set(cx, value) writes the variable and runs the instance's Change events. The component renders again with the new value, so it keeps no copy of its own.
  • A value can be set only while the end user is doing something to the component: in a press, a pointer event, an accessibility action or a text input's handlers. Anywhere else, such as a timer, set returns false and nothing changes.

An instance bound to no variable still works: it keeps its value to itself.

A list holds each text once, at most 100 texts of at most 200 characters each. A list your component sets that goes past that, or holds a text twice, is ignored, so check before you set one:

/// Chips a person picks any of.
#[component(id = "project/topics", traits(frame(resize = "width"), states, interactions))]
pub fn Topics(_cx: Cx, #[value] picked: Input<Vec<String>>) -> View {
    let now = picked.get();
    hstack().spacing(8).children(["Yoga", "Running", "Chess"].map(|topic| {
        let picked = picked.clone();
        let mut next = now.clone();
        match next.iter().position(|held| held == topic) {
            Some(at) => { next.remove(at); }
            None => next.push(topic.to_owned()),
        }
        let on = now.iter().any(|held| held == topic);
        text(if on { format!("✓ {topic}") } else { topic.to_owned() })
            .on_tap(move |cx| picked.set(cx, next.clone()))
    }))
}

Dragging

A pointer going down and moving counts as the end user acting, so a drag can set the value as it goes. Say when the drag starts and ends, which runs the Focus and Blur events and puts the component in its focused state:

/// A level set by dragging across a bar.
#[component(id = "project/level", traits(frame(resize = "width"), states, interactions))]
pub fn Level(cx: Cx, #[value] level: Input<f64>) -> View {
    let width = cx.layout().map_or(1.0, |(width, _)| width);
    view()
        .height(24)
        .background(Color::SURFACE)
        .child(view().height(24).flex(level.get()).background(Color::ACCENT))
        .on_pointer(move |cx, pointer| {
            match pointer.phase {
                PointerPhase::Down => {
                    cx.begin_editing();
                }
                PointerPhase::Up | PointerPhase::Cancel => {
                    cx.end_editing();
                }
                PointerPhase::Move => {}
            }
            level.set(cx, f64::from((pointer.x / width).clamp(0.0, 1.0)));
        })
}

cx.submit() says the end user confirmed the value, which runs Submit.

Validity and disabled

A flow can test whether an input is valid, for example to disable a button until it is. Your component decides what valid means: declare that it reports it with #[value(validity)], and say so with cx.set_validity(valid), on the render context or in an event. A value is valid until the component says otherwise. The instance's isValid prop holds it; bind it to a boolean variable and test the variable. A component without validity has no isValid.

When a flow disables an instance, it gets no presses, pointers or typing, and cx.disabled() is true: draw it so.

A secret value

Declare a value the end user should not see leave the flow, such as a PIN, with #[value(secret)]. Voidhash then keeps the bound variable out of analytics, saved state and screen readers; your app still reads it as an output of the flow.

A component that takes text

text_input() puts a text field in your component's tree. The keyboard, the selection, autofill and input methods are handled for you; on_change tells you what the field holds after every edit. Style it like text, and set it up with the same settings a Text input layer has:

/// A handle typed after an @ sign, kept lowercase.
#[component(id = "project/handle", traits(frame(resize = "width"), states, interactions))]
pub fn Handle(cx: Cx, #[value] handle: Input<String>) -> View {
    hstack()
        .spacing(4)
        .child(text("@").color(Color::SECONDARY))
        .child(
            text_input()
                .value(handle.get())
                .placeholder("handle")
                .label("Your handle")
                .capitalization(Capitalization::None)
                .autocorrect(false)
                .autofill(Autofill::Username)
                .return_key(ReturnKey::Done)
                .max_length(20)
                .flex(1)
                .on_change(move |cx, change| handle.set(cx, change.text.to_lowercase()))
                .on_submit(|cx| cx.submit())
                .on_focus(|cx| cx.begin_editing())
                .on_blur(|cx| cx.end_editing()),
        )
}
  • .value(text) is the text the field holds. Render the component's value and the field follows it. Render something other than what was typed, as the lowercase text above, and the field is set to it.
  • The field takes its place among the screen's inputs, so a return key labelled Next moves to and from it like any Text input layer.
  • A component gets no key events. Everything the keyboard does arrives as on_change.
  • cx.focus_text() asks for the keyboard from an event, and cx.blur_text() gives it up.

To draw the characters yourself, give the field a transparent color and stack your own views under it. Mark what you draw with .decorative() so a screen reader reads the field once, not your drawing too.

Accessibility

A text input is announced as a text field with its label, or its placeholder when it has none. For a component built from pointers, describe the element that carries the value: give it a role, a label and an accessibility value, and the actions a screen reader can perform, which set the value like any press:

pub fn Volume(cx: Cx, #[value] volume: Input<f64>) -> View
let now = volume.get();
view()
    .role("adjustable")
    .label("Volume")
    .accessibility_value(object([("now", now.into()), ("min", 0.into()), ("max", 10.into())]))
    .accessibility_action("increment", "Increase", move |cx| volume.set(cx, (now + 1.0).min(10.0)))
    .accessibility_action("decrement", "Decrease", move |cx| volume.set(cx, (now - 1.0).max(0.0)))

A switch says whether it is on with .checked(on) and .role("switch"); an option of a group says whether it is the chosen one with .selected(chosen). Put the label on the element that takes the press, not only on the text inside it, so a screen reader activates the element that does something, and mark text that only repeats the label with .decorative().

Test an input

The test harness plays the flow's part: it feeds a value your component sets back to it, sets one from outside, disables the component and types into its text inputs.

#[cfg(test)]
mod tests {
    use super::*;
    use voidhash_ui::testing::{Harness, no_props};

    #[test]
    fn typing_sets_the_value_in_lowercase() {
        let mut handle = Harness::mount(&HANDLE, no_props());
        handle.type_text(None, "Ada");
        assert_eq!(handle.value::<String>().as_deref(), Some("ada"));

        // A value the flow sets shows in the field.
        handle.set_value(String::from("grace"));
        let field = handle.text_input(None).expect("the field");
        assert_eq!(field.get("text").and_then(|text| text.as_str()), Some("grace"));
    }
}

Something wrong or missing on this page? Tell us by email or on Discord.