rebo / seed-quickstart-hooks

Example of how react style hooks might integrate with Seed.
5 stars 0 forks source link

`use_form` aka form support #8

Open rebo opened 4 years ago

rebo commented 4 years ago

Second draft of forms support.

Chuck any struct with serde support in use_form and automatic two-way binding will be set up. via form.bind(key) .

With optional validation and soon nested form support.

The initial draft used form.input(key) to create the full input![] Node<Msg> however this makes it harder to mix in things like custom styles it also meant that a new function had to be created for each input type, therefore form.bind is used to set up the Attr EventHandler and additional class names such as "data-validation-errror" etc.

As before let me know what you think of the api surface.

Simple form:


#[derive(Clone, Validate, Debug, Serialize, Deserialize)]
struct User {
    name: String,
    age: u32,
}

#[topo::nested]
fn form_test() -> Node<Msg> {
    let form = use_form(|| 
        User {
            name: "Amos Burton".to_string(),
            age: 32,
        }
    );

    div![
        input![ form.bind("name")],
        input![ form.bind("age")],
        format!("data: {:#?}", form.get().data),
    ]
}

Form with validaiton:

#[derive(Clone, Validate, Debug, Serialize, Deserialize)]
struct User {
    #[validate(length(min = 1))]
    name: String,
    #[validate(email)]
    email: String,
    #[validate(range(min = 18, max = 39))]
    age: u32,
}

#[topo::nested]
fn form_test() -> Node<Msg> {
    let form = use_form(|| User {
        name: "The Queen".to_string(),
        email: "Buckingham Palace, London, England".to_string(),
        age: 32,
    });

    div![
        input![ form.bind("name")],
        input![ form.bind("email")],
        input![ form.bind("age")],
        format!("data: {:#?}", form.get().data),
        format!("errors: {:#?}", form.get().data.validate()),
    ]
}