Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested templates #41

Merged
merged 10 commits into from
Mar 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use maple_core::prelude::*;
fn main() {
let root = template! {
p {
# "Hello World!"
"Hello World!"
}
};

Expand All @@ -38,12 +38,8 @@ That's it! There's your hello world program using `maple`. To run the app, simpl
template! {
div {
p {
span {
# "Hello "
}
strong {
# "World!"
}
span { "Hello " }
strong { "World!" }
}
}
};
Expand All @@ -55,14 +51,14 @@ template! {

template! {
button(disabled="true") {
# "My button"
"My button"
}
}

// Events are attached using the `on:*` directive.
template! {
button(on:click=|_| { /* do something */ }) {
# "Click me"
"Click me"
}
}
```
Expand Down Expand Up @@ -155,7 +151,7 @@ let state = Signal::new(0);

let root = template! {
p {
# state.get()
(state.get())
}
}
```
Expand Down Expand Up @@ -205,8 +201,7 @@ use maple_core::prelude::*;
fn Component(value: StateHandle<i32>) -> TemplateResult {
template! {
div(class="my-component") {
# "Value: "
# value.get()
"Value: " (value.get())
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions docs/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ pub fn Header() -> TemplateResult {
header {
nav(class="navbar navbar-expand-sm navbar-dark bg-dark") {
div(class="container-fluid") {
a(class="navbar-brand", href="#") { # "Maple" }
a(class="navbar-brand", href="#") { "Maple" }

ul(class="navbar-nav") {
li(class="nav-item") {
a(class="nav-link", href="https://docs.rs/maple-core") { # "docs.rs" }
a(class="nav-link", href="https://docs.rs/maple-core") { "docs.rs" }
}
li(class="nav-item") {
a(class="nav-link", href="https://github.com/lukechu10/maple") { # "Repository" }
a(class="nav-link", href="https://github.com/lukechu10/maple") { "Repository" }
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions docs/src/usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use maple_core::prelude::*;
pub fn Usage() -> TemplateResult {
template! {
div(class="container") {
h1 { # "Maple" }
p { # "A reactive DOM library for Rust in WASM" }
h1 { "Maple" }
p { "A reactive DOM library for Rust in WASM" }
}
}
}
10 changes: 5 additions & 5 deletions examples/components/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ use maple_core::prelude::*;
fn MyComponent(num: StateHandle<i32>) -> TemplateResult {
template! {
div(class="my-component") {
# "My component"
"My component"
p {
# "Value: "
# num.get()
"Value: "
(num.get())
}
}
}
Expand All @@ -24,14 +24,14 @@ fn App() -> TemplateResult {
template! {
div {
h1 {
# "Component demo"
"Component demo"
}

MyComponent(state.handle())
MyComponent(state.handle())

button(on:click=increment) {
# "Increment"
"Increment"
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions examples/counter/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,16 @@ fn App() -> TemplateResult {

template! {
div {
# "Counter demo"
"Counter demo"
p(class="value") {
# "Value: "
# counter.get()
"Value: "
(counter.get())
}
button(class="increment", on:click=increment) {
# "Increment"
"Increment"
}
button(class="reset", on:click=reset) {
# "Reset"
"Reset"
}
}
}
Expand Down
24 changes: 11 additions & 13 deletions examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,7 @@ use web_sys::{Event, HtmlInputElement};
fn App() -> TemplateResult {
let name = Signal::new(String::new());

let displayed_name = cloned!((name) => move || {
if name.get().is_empty() {
"World".to_string()
} else {
name.get().as_ref().clone()
}
});

let handle_change = move |event: Event| {
let handle_change = cloned!((name) => move |event: Event| {
name.set(
event
.target()
Expand All @@ -24,14 +16,20 @@ fn App() -> TemplateResult {
.unwrap()
.value(),
);
};
});

template! {
div {
h1 {
# "Hello "
# displayed_name()
# "!"
"Hello "
({if !name.get().is_empty() {
cloned!((name) => template! {
span { (name.get()) }
})
} else {
template! { span { "World" } }
}})
"!"
}

input(on:input=handle_change)
Expand Down
10 changes: 3 additions & 7 deletions maple-core-macro/src/children.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::{braced, token, Ident, Result, Token};
use syn::{braced, token, Result};

use crate::HtmlTree;

Expand All @@ -15,13 +14,10 @@ impl Parse for Children {
let brace_token = braced!(content in input);
let mut body = Vec::new();

while content.peek(Ident::peek_any) || content.peek(Token![#]) || content.peek(Token![@]) {
while !content.is_empty() {
body.push(content.parse()?);
}

Ok(Self {
brace_token,
body,
})
Ok(Self { brace_token, body })
}
}
23 changes: 18 additions & 5 deletions maple-core-macro/src/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use syn::{token, Ident, Token};

use crate::attributes::{AttributeList, AttributeType};
use crate::children::Children;
use crate::HtmlTree;

/// Represents a html element with all its attributes and properties (e.g. `p(class="text")`).
pub(crate) struct Element {
Expand Down Expand Up @@ -57,12 +58,12 @@ impl ToTokens for Element {
match &attribute.ty {
AttributeType::DomAttribute { name } => {
set_attributes.push(quote_spanned! { expr_span=>
::maple_core::internal::attr(&element, #name, move || ::std::format!("{}", #expr));
::maple_core::internal::attr(::std::convert::AsRef::as_ref(&element), #name, move || ::std::format!("{}", #expr));
});
}
AttributeType::Event { name } => {
set_event_listeners.push(quote_spanned! { expr_span=>
::maple_core::internal::event(&element, #name, ::std::boxed::Box::new(#expr));
::maple_core::internal::event(::std::convert::AsRef::as_ref(&element), #name, ::std::boxed::Box::new(#expr));
});
}
}
Expand All @@ -72,9 +73,21 @@ impl ToTokens for Element {
let mut append_children = Vec::new();
if let Some(children) = children {
for child in &children.body {
append_children.push(quote! {
::maple_core::internal::append(&element, &&#child);
});
let quoted = match child {
HtmlTree::Component(component) => quote! {
::maple_core::internal::append(&element, &#component);
},
HtmlTree::Element(element) => quote! {
::maple_core::internal::append(&element, &#element);
},
HtmlTree::Text(text) => quote! {
::maple_core::internal::append_render(&element, ::std::boxed::Box::new(move || {
::std::boxed::Box::new(#text)
}));
},
};

append_children.push(quoted);
}
}

Expand Down
7 changes: 4 additions & 3 deletions maple-core-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Ident, Result, Token};
use syn::token::Paren;
use syn::{parse_macro_input, Ident, LitStr, Result, Token};

pub(crate) enum HtmlType {
Component,
Expand All @@ -26,7 +27,7 @@ impl HtmlTree {
fn peek_type(input: ParseStream) -> Option<HtmlType> {
let input = input.fork(); // do not affect original ParseStream

if input.peek(Token![#]) {
if input.peek(LitStr) || input.peek(Paren) {
Some(HtmlType::Text)
} else if input.peek(Token![::]) {
Some(HtmlType::Component)
Expand All @@ -49,7 +50,7 @@ impl Parse for HtmlTree {
fn parse(input: ParseStream) -> Result<Self> {
let html_type = match Self::peek_type(input) {
Some(html_type) => html_type,
None => return Err(input.error("unexpected token")),
None => return Err(input.error("expected a valid HTML node")),
};

Ok(match html_type {
Expand Down
40 changes: 23 additions & 17 deletions maple-core-macro/src/text.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
use proc_macro2::TokenStream;
use quote::{quote_spanned, ToTokens};
use quote::ToTokens;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{Expr, Result, Token};
use syn::token::Paren;
use syn::{parenthesized, Expr, LitStr, Result};

pub(crate) struct Text {
_hash_token: Token![#],
expr: Expr,
pub(crate) enum Text {
Text(LitStr),
Splice(Paren, Box<Expr>),
}

impl Parse for Text {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
_hash_token: input.parse()?,
expr: input.parse()?,
})
if input.peek(Paren) {
let content;
let paren = parenthesized!(content in input);
Ok(Self::Splice(paren, content.parse()?))
} else {
Ok(Self::Text(input.parse()?))
}
}
}

impl ToTokens for Text {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Text { _hash_token, expr } = self;

let expr_span = expr.span();
let quoted = quote_spanned! {expr_span=>
::maple_core::internal::text(move || ::std::format!("{}", #expr))
};
tokens.extend(quoted);
match self {
Text::Text(text) => {
let quoted = text.to_token_stream();
tokens.extend(quoted);
}
Text::Splice(_, expr) => {
let quoted = expr.to_token_stream();
tokens.extend(quoted);
}
}
}
}
Loading