Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created March 29, 2017 05:29
Show Gist options
  • Save jonahwilliams/2bc47d920687c872575c832857fc204b to your computer and use it in GitHub Desktop.
Save jonahwilliams/2bc47d920687c872575c832857fc204b to your computer and use it in GitHub Desktop.
elm in rust?
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(),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment