Giter VIP home page Giter VIP logo

view's Introduction

๐Ÿ—๏ธ View

[dependencies]
view = "0.4"

Constructing view heirarchies in Rust is a bit tedious. This is a macro for constructing views in a non framework specific manner. It's more struct oriented compared to a technology like JSX and borrows in broad strokes some ideas from SwiftUI.

This example shows everything that's possible

let images = vec!["coffee.png","cream.png","sugar.png"];
let show_coupon = false;
let coupon = getTodaysCoupon();
โ€‹
let v = view!{
  VStack {
    Image("company.png") 
    Button(text:"order".to_string(),style:BOLD)
      .on_click(|| do_order()) { 
        Image("order_icon.png") 
      }
    For(i in images.iter()) { Image(i) }
    If(show_coupon) { coupon }
    Legal
  }
};

Below is all the code this macro saves you from writing yourself.

let images = vec!["coffee.png", "cream.png", "sugar.png"];
let show_legal = false;

let s = {
  let mut o = VStack {
      ..Default::default()
  };
  o.add_view_child({
      let mut o = Image::new("company.png");
      o
  });
  o.add_view_child({
      let mut o = Button {
          text: "order".to_string(),
          style: BOLD,
          ..Default::default()
      };
      o.on_click(|| do_order());
      o.on_click(|| do_order());
      o.add_view_child({
          let mut o = Image::new("order_icon.png");
          o
      });
      o
  });
  for i in images.iter() {
      o.add_view_child({
          let mut o = Image::new(i);
          o
      });
  }
  o.add_view_child({
      let mut o = Footer {
          ..Default::default()
      };
      o
  });
  if show_legal {
      o.add_view_child({
          let mut o = Legal {
              ..Default::default()
          };
          o
      });
  }
  o
};

This project isn't framework specific, but it does have a few rules:

  • views that have children must have a function add_view_child implemented
  • views must implement Default trait for property construction (e.g Button(text:"click me".to_string()) )
  • views must have a 'new' constructor function for simple construction (e.g Button("click me") )

Here's a basic example of implementing these rules, though they can be implemented in any way you choose with any trait you like.

trait View {}

#[derive(Default)]
struct VStack {
  direction: u8,
  children: Vec<Box<View>>
}

impl VStack {
  fn new(direction:u8) -> Self {
    VStack{ direction:direction, children:vec![] }
  }
  
  fn add_view_child<'a, T>(&'a mut self, child: Box<T>)
  where
      T: 'static + View,
  {
      self.children.push(child);
  }
}

impl View for VStack {}

#[derive(Default)]
struct Button {
  text:String
}

impl Button {
  fn new(text:String) -> Self {
    Button{text:text}
  }
}

impl View for Button {}

Let's make a virtual dom

use view::*;

struct VNode {
    vnode_type: &'static str,
    children: Vec<VNode>,
    classes: Vec<String>,
    text: Option<String>,
}

impl VNode {
    fn add_class(&mut self, c: &str) {
        self.classes.push(c.to_string())
    }

    fn add_view_child(&mut self, child: VNode) {
        self.children.push(child);
    }

    fn render_to_string(&self) -> String {
        if let Some(t) = &self.text {
            t.clone()
        } else {
            format!(
                "<{} class=\"{}\">{}</{}>",
                self.vnode_type,
                self.classes.join(","),
                self.children
                    .iter()
                    .map(|c| c.render_to_string())
                    .collect::<Vec<String>>()
                    .join(""),
                self.vnode_type
            )
        }
    }
}

type Div = VNode;

impl Default for Div {
    fn default() -> Self {
        VNode {
            vnode_type: "div",
            children: vec![],
            classes: vec![],
            text: None,
        }
    }
}

type Text = VNode;

impl Text {
    fn new(t: &str) -> Self {
        VNode {
            vnode_type: "text",
            children: vec![],
            classes: vec![],
            text: Some(t.to_string()),
        }
    }
}

fn main() {
    let html = view! {
      Div.add_class("greeting"){
        Text("Hello World!")
      }
    };
    println!("{}", html.render_to_string());
}

License

This project is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in view by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

view's People

Contributors

plecra avatar richardanaya 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  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

view's Issues

Spanned error reports

Panicking in a proc macro doesn't give the user particularly helpful errors. There's no way for them to know where their syntax error is, and the title of the error is the worrying "procedural macro panicked".

Instead, you can emit an invocation of the compile_error macro to give the user a more helpful error. If you give the tokens the span of the invalid tokens, rustc's error will even highlight them.

Does the macro have to box arguments?

fn add_view_child(&mut self, child: T);

Is there any need to box the children in the macro? If the child were passed by-value, the implementation can still choose to box it if appropriate

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.