Giter VIP home page Giter VIP logo

yew_form's Introduction

License:MIT License:Apache

Yew Form

Bringing MVC to Yew! A set of mildly opinionated Yew component to map and validate a model to a HTML form.

Live demo

Supports:

  • 2-way Binding to struct (with support for nested structs)
  • Validation (using Keats Validator)
  • Only String and bool fields are supported presently. More to come

Usage

Cargo.toml:

[dependencies]
validator = "0.14"
validator_derive = "0.14"
yew = "0.18"
yew_form = "0.1"
yew_form_derive = "0.1"

main.rs:

#[macro_use]
extern crate validator_derive;
extern crate yew_form;
#[macro_use]
extern crate yew_form_derive;

Example

Consider the following model:

#[derive(Model, Validate, PartialEq, Clone)]
struct Address {
    #[validate(length(min = 1, message="Street is required"))]
    street: String,
    #[validate(length(min = 1, message="City name is required"))]
    city: String,
    #[validate(regex(path="PROVINCE_RE", message="Enter 2 digit province code"))]
    province: String,
    postal_code: String,
    country: String,
}

#[derive(Model, Validate, PartialEq, Clone)]
struct Registration {
    #[validate(length(min = 1, message="First name is required"))]
    first_name: String,
    #[validate(length(min = 1, message="Last name is required"))]
    last_name: String,
    quantity: u32,
    price: f64,
    #[validate]
    address: Address,
    #[validate(custom = "must_be_true")]
    accept_terms: bool,
}

The struct can be bound to a Yew form using the following definition:

struct App {
    form: Form<Registration>,
    ...
}

For now, the Form needs to be instantiated as follows:

fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self {
    // Create model initial state
    let model = Registration {
        first_name: String::from("J-F"),
        last_name: String::from("Bilodeau"),
        address: Address {
            street: String::new(),
            city: String::from("Ottawa"),
            province: String::from("ONT"),
            postal_code: String::from("K2P 0A4"),
            country: String::new(),
        },
    };

    Self {
        form: Form::new(model),
        ...
    }
    ...

Fields can then be added to the form as follows:

<Field<Registration> 
    form=&self.form 
<<<<<<< HEAD
    field_name="first_name"
    autocomplete="given-name"
=======
    field_name="first_name" 
>>>>>>> 0ab668b7f3fb9ba13e1e0d4d97bee619280f3a3d
    oninput=self.link.callback(|_: InputData| AppMessage::Update) />

<!-- here we use custom css classes -->
<Field<Registration> 
    form=&self.form 
    field_name="address.street"
    class="form-control"
    class_invalid="is-invalid red-border"
    class_valid="is-valid green-border"
    oninput=self.link.callback(|_: InputData| AppMessage::Update) />
...
<CheckBox<Registration> field_name="accept_terms" form=&self.form />

The Field component takes care of two way binding between struct Registration and the HTML <input>

Validation is done automatically when the user edits the form or programmatically.

if self.form.validate() {
    ...
}

Todo/Wish List:

  • Add documentation (In progress)
  • Remove clone requirement from model
  • Add derive for model to remove need for vec! of fields
  • Make oninput optional
  • Make Yew update the view when Field is updated
  • Need to add additional HTML attribute to Field
  • Remove hard-coded Bootstrap styles
  • Add support for additional types such as i32
  • Support Vec<T>
  • Support Rust Stable

Change Log

0.1.8

  • Remove hardcoded Bootstrap css classes
  • Fix examples/form
  • Add autocomplete attribute

0.1.7

  • Remove #![feature(get_mut_unchecked)] from code (Thanks L0g4n)

0.1.6

  • Removed unsafe code
  • Updated yew_form version in documentation

0.1.5

  • Updated to Yew 0.17

0.1.4

  • Added blanket implementation for FieldValue to support i32, bool, etc...

0.1.3

BREAKING CHANGES

  • Added #[derive(Model)]
  • No need to manually pass a vector of fields to Form::new()

0.1.2

  • Added CheckBox

0.1.1

  • Make Field::oninput optional

(Made with ❤️ with Rust)

yew_form's People

Contributors

dignifiedquire avatar jfbilodeau avatar jryio avatar marcantoine-arnaud avatar sassman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

yew_form's Issues

hooks?

i was wondering if there would ever be hooks for this library to use with function components.

Simple example panics

Getting this panic on the current master code, my code is the same as in the examples folder, this happens as soon as oninput gets triggered for me.

webpack:///./frontend/pkg/index_bg.js?:392 panicked at 'called `Option::unwrap()` on a `None` value', /Users/dignifiedquire/.cargo/git/checkouts/yew_form-0d273cf04f678139/f7c824c/yew_form/src/form.rs:24:9

please update yew 0.13

Thanks for your good work on this awesome crate.
yew >0.13 support web_sys, can you upgrade this crate?

Why is get_mut_unchecked required?

Form::state_mut() (see below) calls RC::get_mut_unchecked which is unsafe and nightly only. Unfortunately, it is not documented why this is necessary (and why Rc::get_mut() cannot be used instead). Changing this would allow us to remove the feature requirement. As a result, it would be possible to compile yew_form on stable Rust.

pub(crate) fn state_mut(&mut self) -> &mut FormState<T> {
unsafe {
Rc::get_mut_unchecked(&mut self.state)
}
}

Proposal to maintain

Hi!

I can't help but notice that this repository has been inactive (and broken) for a while. I'm working on lldap (https://github.com/lldap/lldap) and I'd like to keep using this repo, especially the associated crate. Would you consider transferring ownership of the crate/repo to me?

Cheers,

Get example panics

Getting this panic on the current master code, my code is the same as in the examples folder, this happens as soon as oninput gets triggered for me.

panicked at 'called Option::unwrap()on aNone value', /Users/dayat/.cargo/registry/src/github.com-1ecc6299db9ec823/yew_form-0.1.7/src/form.rs:24:39

versions:

yew = "0.17.4"
yew_form = "0.1.7"
yew_form_derive = "0.1.7"

yew_form_derive won't compile with latest syn

Compilation attempt end up with:

Compiling yew_form_derive v0.1.7
error[E0432]: unresolved import `syn::export`
 --> /home/marcin/.cargo/registry/src/github.com-1ecc6299db9ec823/yew_form_derive-0.1.7/src/lib.rs:6:10
  |
6 | use syn::export::{ToTokens, TokenStream};
  |          ^^^^^^ could not find `export` in `syn`

error[E0599]: no method named `to_tokens` found for reference `&syn::Path` in the current scope
  --> /home/marcin/.cargo/registry/src/github.com-1ecc6299db9ec823/yew_form_derive-0.1.7/src/lib.rs:32:22
   |
32 |                 path.to_tokens(&mut tokens);
   |                      ^^^^^^^^^ method not found in `&syn::Path`
   |
   = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
   |
6  | use crate::quote::ToTokens;
   |

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0432, E0599.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `yew_form_derive`

For more information I recommend refering to this issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.