Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main() {
- println!("Hello, world!");
- use Template::*;
- enum Action {
- Increment,
- Decrement,
- }
- let mut foo: Widget<i32, _, _, Action> = Widget {
- model: 0,
- update: |x, a| match a {
- Action::Increment => x + 1,
- Action::Decrement => x - 1,
- },
- template: |x| {
- let children = if x > 0 {
- text("Greater than Zero".to_string())
- } else {
- text(x.to_string())
- };
- div{
- children: vec![children],
- on_click: Action::Increment,
- }
- },
- inbox: Vec::new(),
- };
- println!("{}", foo.render().to_string());
- foo.tick(Action::Increment);
- println!("{}", foo.render().to_string());
- foo.tick(Action::Increment);
- println!("{}", foo.render().to_string());
- foo.tick(Action::Decrement);
- println!("{}", foo.render().to_string());
- foo.tick(Action::Decrement);
- println!("{}", foo.render().to_string());
- }
- struct Widget<S, U, T, A>
- where S: Sized + Copy + Clone,
- A: Sized,
- U: Fn(S, A) -> S,
- T: FnMut(S) -> Template<A>
- {
- model: S,
- update: U,
- template: T,
- inbox: Vec<A>,
- }
- impl<S, U, T, A> Widget<S, U, T, A>
- where S: Sized + Copy + Clone,
- U: Fn(S, A) -> S,
- T: FnMut(S) -> Template<A>,
- A: Sized,
- {
- fn render(&mut self) -> Template<A> {
- (self.template)(self.model)
- }
- fn tick(&mut self, action: A) -> () {
- let value: S = (self.update)(self.model, action);
- self.model = value;
- }
- }
- enum Template<A>
- where A: Sized
- {
- div {
- on_click: A,
- children: Vec<Template<A>>,
- },
- h1 {
- on_click: A,
- children: Vec<Template<A>>,
- },
- h2 {
- on_click: A,
- children: Vec<Template<A>>
- },
- text(String),
- }
- impl<A> Template<A> where A: Sized {
- fn to_string(&self) -> String {
- match self {
- &Template::div{ref children,..} => {
- let mut buffer = String::new();
- buffer.push_str("<div>");
- for child in children.iter() {
- buffer.push_str(&child.to_string());
- }
- buffer.push_str("</div>");
- buffer
- }
- &Template::h1{ref children,..} => {
- let mut buffer = String::new();
- buffer.push_str("<h1>");
- for child in children.iter() {
- buffer.push_str(&child.to_string());
- }
- buffer.push_str("</h1>");
- buffer
- },
- &Template::h2{ref children, ..} => {
- let mut buffer = String::new();
- buffer.push_str("<h2>");
- for child in children.iter() {
- buffer.push_str(&child.to_string());
- }
- buffer.push_str("</h2>");
- buffer
- },
- &Template::text(ref value) => value.to_string(),
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement