yew-macro 0.23.0

A framework for making client-side single-page apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use proc_macro2::{Delimiter, Ident, Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::buffer::Cursor;
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{braced, token, Token};

use crate::{is_ide_completion, PeekValue};

mod html_block;
mod html_component;
mod html_dashed_name;
mod html_element;
mod html_for;
mod html_if;
mod html_iterable;
mod html_list;
mod html_node;
mod lint;
mod tag;

use html_block::HtmlBlock;
use html_component::HtmlComponent;
pub use html_dashed_name::HtmlDashedName;
use html_element::HtmlElement;
use html_if::HtmlIf;
use html_iterable::HtmlIterable;
use html_list::HtmlList;
use html_node::HtmlNode;
use tag::TagTokens;

use self::html_block::BlockContent;
use self::html_for::HtmlFor;

pub enum HtmlType {
    Block,
    Component,
    List,
    Element,
    If,
    For,
    Empty,
}

pub enum HtmlTree {
    Block(Box<HtmlBlock>),
    Component(Box<HtmlComponent>),
    List(Box<HtmlList>),
    Element(Box<HtmlElement>),
    If(Box<HtmlIf>),
    For(Box<HtmlFor>),
    Empty,
}

impl Parse for HtmlTree {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let html_type = Self::peek_html_type(input)
            .ok_or_else(|| input.error("expected a valid html element"))?;
        Ok(match html_type {
            HtmlType::Empty => Self::Empty,
            HtmlType::Component => Self::Component(Box::new(input.parse()?)),
            HtmlType::Element => Self::Element(Box::new(input.parse()?)),
            HtmlType::Block => Self::Block(Box::new(input.parse()?)),
            HtmlType::List => Self::List(Box::new(input.parse()?)),
            HtmlType::If => Self::If(Box::new(input.parse()?)),
            HtmlType::For => Self::For(Box::new(input.parse()?)),
        })
    }
}

impl HtmlTree {
    /// Determine the [`HtmlType`] before actually parsing it.
    /// Even though this method accepts a [`ParseStream`], it is forked and the original stream is
    /// not modified. Once a certain `HtmlType` can be deduced for certain, the function eagerly
    /// returns with the appropriate type. If invalid html tag, returns `None`.
    fn peek_html_type(input: ParseStream) -> Option<HtmlType> {
        let input = input.fork(); // do not modify original ParseStream
        let cursor = input.cursor();

        if input.is_empty() {
            Some(HtmlType::Empty)
        } else if HtmlBlock::peek(cursor).is_some() {
            Some(HtmlType::Block)
        } else if HtmlIf::peek(cursor).is_some() {
            Some(HtmlType::If)
        } else if HtmlFor::peek(cursor).is_some() {
            Some(HtmlType::For)
        } else if input.peek(Token![<]) {
            let _lt: Token![<] = input.parse().ok()?;

            // eat '/' character for unmatched closing tag
            let _slash: Option<Token![/]> = input.parse().ok();

            if input.peek(Token![>]) {
                Some(HtmlType::List)
            } else if input.peek(Token![@]) {
                Some(HtmlType::Element) // dynamic element
            } else if input.peek(Token![::]) {
                Some(HtmlType::Component)
            } else if input.peek(Ident::peek_any) {
                let ident = Ident::parse_any(&input).ok()?;
                let ident_str = ident.to_string();

                if input.peek(Token![=]) || (input.peek(Token![?]) && input.peek2(Token![=])) {
                    Some(HtmlType::List)
                } else if ident_str.chars().next().unwrap().is_ascii_uppercase()
                    || input.peek(Token![::])
                    || is_ide_completion() && ident_str.chars().any(|c| c.is_ascii_uppercase())
                {
                    Some(HtmlType::Component)
                } else {
                    Some(HtmlType::Element)
                }
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl ToTokens for HtmlTree {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        lint::lint_all(self);
        match self {
            Self::Empty => tokens.extend(quote! {
                <::yew::virtual_dom::VNode as ::std::default::Default>::default()
            }),
            Self::Component(comp) => comp.to_tokens(tokens),
            Self::Element(tag) => tag.to_tokens(tokens),
            Self::List(list) => list.to_tokens(tokens),
            Self::Block(block) => block.to_tokens(tokens),
            Self::If(block) => block.to_tokens(tokens),
            Self::For(block) => block.to_tokens(tokens),
        }
    }
}

pub enum HtmlRoot {
    Tree(HtmlTree),
    Node(Box<HtmlNode>),
}

impl Parse for HtmlRoot {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let html_root = if HtmlTree::peek_html_type(input).is_some() {
            Self::Tree(input.parse()?)
        } else {
            Self::Node(Box::new(input.parse()?))
        };

        if !input.is_empty() {
            let stream: TokenStream = input.parse()?;
            Err(syn::Error::new_spanned(
                stream,
                "only one root html element is allowed (hint: you can wrap multiple html elements \
                 in a fragment `<></>`)",
            ))
        } else {
            Ok(html_root)
        }
    }
}

impl ToTokens for HtmlRoot {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Self::Tree(tree) => tree.to_tokens(tokens),
            Self::Node(node) => node.to_tokens(tokens),
        }
    }
}

/// Same as HtmlRoot but always returns a VNode.
pub struct HtmlRootVNode(HtmlRoot);
impl Parse for HtmlRootVNode {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse().map(Self)
    }
}

impl ToTokens for HtmlRootVNode {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let new_tokens = self.0.to_token_stream();
        tokens.extend(
            quote_spanned! {self.0.span().resolved_at(Span::mixed_site())=> {
                #[allow(clippy::useless_conversion)]
                <::yew::virtual_dom::VNode as ::std::convert::From<_>>::from(#new_tokens)
            }},
        );
    }
}

/// This trait represents a type that can be unfolded into multiple html nodes.
pub trait ToNodeIterator {
    /// Generate a token stream which produces a value that implements IntoIterator<Item=T> where T
    /// is inferred by the compiler. The easiest way to achieve this is to call `.into()` on
    /// each element. If the resulting iterator only ever yields a single item this function
    /// should return None instead.
    fn to_node_iterator_stream(&self) -> Option<TokenStream>;
    /// Returns a boolean indicating whether the node can only ever unfold into 1 node
    /// Same as calling `.to_node_iterator_stream().is_none()`,
    /// but doesn't actually construct any token stream
    fn is_singular(&self) -> bool;
}

impl ToNodeIterator for HtmlTree {
    fn to_node_iterator_stream(&self) -> Option<TokenStream> {
        match self {
            Self::Block(block) => block.to_node_iterator_stream(),
            // everything else is just a single node.
            _ => None,
        }
    }

    fn is_singular(&self) -> bool {
        match self {
            Self::Block(block) => block.is_singular(),
            _ => true,
        }
    }
}

pub struct HtmlChildrenTree(pub Vec<HtmlTree>);

impl HtmlChildrenTree {
    pub fn new() -> Self {
        Self(Vec::new())
    }

    pub fn parse_child(&mut self, input: ParseStream) -> syn::Result<()> {
        self.0.push(input.parse()?);
        Ok(())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    // Check if each child represents a single node.
    // This is the case when no expressions are used.
    fn only_single_node_children(&self) -> bool {
        self.0.iter().all(HtmlTree::is_singular)
    }

    pub fn to_build_vec_token_stream(&self) -> TokenStream {
        let Self(children) = self;

        if self.only_single_node_children() {
            // optimize for the common case where all children are single nodes (only using literal
            // html).
            let children_into = children
                .iter()
                .map(|child| quote_spanned! {child.span()=> ::std::convert::Into::into(#child) });
            return quote! {
                [#(#children_into),*].to_vec()
            };
        }

        let vec_ident = Ident::new("__yew_v", Span::mixed_site());
        let add_children_streams = children.iter().map(|child| {
            if let Some(node_iterator_stream) = child.to_node_iterator_stream() {
                quote! {
                    ::std::iter::Extend::extend(&mut #vec_ident, #node_iterator_stream);
                }
            } else {
                quote_spanned! {child.span()=>
                    #vec_ident.push(::std::convert::Into::into(#child));
                }
            }
        });

        quote! {
            {
                let mut #vec_ident = ::std::vec::Vec::new();
                #(#add_children_streams)*
                #vec_ident
            }
        }
    }

    fn parse_delimited(input: ParseStream) -> syn::Result<Self> {
        let mut children = HtmlChildrenTree::new();

        while !input.is_empty() {
            children.parse_child(input)?;
        }

        Ok(children)
    }

    pub fn to_children_renderer_tokens(&self) -> Option<TokenStream> {
        match self.0[..] {
            [] => None,
            [HtmlTree::Component(ref children)] => Some(quote! { #children }),
            [HtmlTree::Element(ref children)] => Some(quote! { #children }),
            [HtmlTree::Block(ref m)] => {
                // We only want to process `{vnode}` and not `{for vnodes}`.
                // This should be converted into a if let guard once https://github.com/rust-lang/rust/issues/51114 is stable.
                // Or further nested once deref pattern (https://github.com/rust-lang/rust/issues/87121) is stable.
                if let HtmlBlock {
                    content: BlockContent::Node(children),
                    ..
                } = m.as_ref()
                {
                    Some(quote! { #children })
                } else {
                    Some(quote! { ::yew::html::ChildrenRenderer::new(#self) })
                }
            }
            _ => Some(quote! { ::yew::html::ChildrenRenderer::new(#self) }),
        }
    }

    pub fn to_vnode_tokens(&self) -> TokenStream {
        match self.0[..] {
            [] => quote! {::std::default::Default::default() },
            [HtmlTree::Component(ref children)] => {
                quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) }
            }
            [HtmlTree::Element(ref children)] => {
                quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) }
            }
            [HtmlTree::Block(ref m)] => {
                // We only want to process `{vnode}` and not `{for vnodes}`.
                // This should be converted into a if let guard once https://github.com/rust-lang/rust/issues/51114 is stable.
                // Or further nested once deref pattern (https://github.com/rust-lang/rust/issues/87121) is stable.
                if let HtmlBlock {
                    content: BlockContent::Node(children),
                    ..
                } = m.as_ref()
                {
                    quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) }
                } else {
                    quote! {
                        ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(
                            ::yew::html::ChildrenRenderer::new(#self)
                        )
                    }
                }
            }
            _ => quote! {
                ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(
                    ::yew::html::ChildrenRenderer::new(#self)
                )
            },
        }
    }

    pub fn size_hint(&self) -> Option<usize> {
        self.only_single_node_children().then_some(self.0.len())
    }

    pub fn fully_keyed(&self) -> Option<bool> {
        for child in self.0.iter() {
            match child {
                HtmlTree::Block(block) => {
                    return if let BlockContent::Node(node) = &block.content {
                        matches!(&**node, HtmlNode::Literal(_)).then_some(false)
                    } else {
                        None
                    }
                }
                HtmlTree::Component(comp) => {
                    if comp.props.props.special.key.is_none() {
                        return Some(false);
                    }
                }
                HtmlTree::List(list) => {
                    if list.open.props.key.is_none() {
                        return Some(false);
                    }
                }
                HtmlTree::Element(element) => {
                    if element.props.special.key.is_none() {
                        return Some(false);
                    }
                }
                HtmlTree::If(_) | HtmlTree::For(_) | HtmlTree::Empty => return Some(false),
            }
        }
        Some(true)
    }
}

impl ToTokens for HtmlChildrenTree {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.extend(self.to_build_vec_token_stream());
    }
}

pub struct HtmlRootBraced {
    brace: token::Brace,
    children: HtmlChildrenTree,
}

impl PeekValue<()> for HtmlRootBraced {
    fn peek(cursor: Cursor) -> Option<()> {
        cursor.group(Delimiter::Brace).map(|_| ())
    }
}

impl Parse for HtmlRootBraced {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let content;
        let brace = braced!(content in input);
        let children = HtmlChildrenTree::parse_delimited(&content)?;

        Ok(HtmlRootBraced { brace, children })
    }
}

impl ToTokens for HtmlRootBraced {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self { brace, children } = self;

        tokens.extend(quote_spanned! {brace.span.span()=>
            {
                ::yew::virtual_dom::VNode::VList(::std::rc::Rc::new(
                    ::yew::virtual_dom::VList::with_children(#children, ::std::option::Option::None)
                ))
            }
        });
    }
}