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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use crate::attribute_value;
use leptos_hot_reload::parsing::is_component_node;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn_rsx::{Node, NodeAttribute, NodeElement, NodeValueExpr};
use uuid::Uuid;

pub(crate) fn render_template(cx: &Ident, nodes: &[Node]) -> TokenStream {
    let template_uid = Ident::new(
        &format!("TEMPLATE_{}", Uuid::new_v4().simple()),
        Span::call_site(),
    );

    match nodes.first() {
        Some(Node::Element(node)) => {
            root_element_to_tokens(cx, &template_uid, node)
        }
        _ => abort!(cx, "template! takes a single root element."),
    }
}

fn root_element_to_tokens(
    cx: &Ident,
    template_uid: &Ident,
    node: &NodeElement,
) -> TokenStream {
    let mut template = String::new();
    let mut navigations = Vec::new();
    let mut expressions = Vec::new();

    if is_component_node(node) {
        crate::view::component_to_tokens(cx, node, None)
    } else {
        element_to_tokens(
            cx,
            node,
            &Ident::new("root", Span::call_site()),
            None,
            &mut 0,
            &mut 0,
            &mut template,
            &mut navigations,
            &mut expressions,
            true,
        );

        // create the root element from which navigations and expressions will begin
        let generate_root = quote! {
            let root = #template_uid.with(|tpl| tpl.content().clone_node_with_deep(true))
                .unwrap()
                .first_child()
                .unwrap();
        };

        let span = node.name.span();

        let navigations = if navigations.is_empty() {
            quote! {}
        } else {
            quote! { #(#navigations);* }
        };

        let expressions = if expressions.is_empty() {
            quote! {}
        } else {
            quote! { #(#expressions;);* }
        };

        let tag_name = node.name.to_string();

        quote_spanned! {
            span => {
                thread_local! {
                    static #template_uid: web_sys::HtmlTemplateElement = {
                        let document = leptos::document();
                        let el = document.create_element("template").unwrap();
                        el.set_inner_html(#template);
                        el.unchecked_into()
                    };
                }

                #generate_root

                #navigations
                #expressions

                leptos::leptos_dom::View::Element(leptos::leptos_dom::Element {
                    #[cfg(debug_assertions)]
                    name: #tag_name.into(),
                    element: root.unchecked_into(),
                    #[cfg(debug_assertions)]
                    view_marker: None
                })
            }
        }
    }
}

#[derive(Clone, Debug)]
enum PrevSibChange {
    Sib(Ident),
    Parent,
    Skip,
}

fn attributes(node: &NodeElement) -> impl Iterator<Item = &NodeAttribute> {
    node.attributes.iter().filter_map(|node| {
        if let Node::Attribute(attribute) = node {
            Some(attribute)
        } else {
            None
        }
    })
}

#[allow(clippy::too_many_arguments)]
fn element_to_tokens(
    cx: &Ident,
    node: &NodeElement,
    parent: &Ident,
    prev_sib: Option<Ident>,
    next_el_id: &mut usize,
    next_co_id: &mut usize,
    template: &mut String,
    navigations: &mut Vec<TokenStream>,
    expressions: &mut Vec<TokenStream>,
    is_root_el: bool,
) -> Ident {
    // create this element
    *next_el_id += 1;
    let this_el_ident = child_ident(*next_el_id, node.name.span());

    // Open tag
    let name_str = node.name.to_string();
    let span = node.name.span();

    // CSR/hydrate, push to template
    template.push('<');
    template.push_str(&name_str);

    // attributes
    for attr in attributes(node) {
        attr_to_tokens(cx, attr, &this_el_ident, template, expressions);
    }

    // navigation for this el
    let debug_name = node.name.to_string();
    let this_nav = if is_root_el {
        quote_spanned! {
            span => let #this_el_ident = #debug_name;
                let #this_el_ident = #parent.clone().unchecked_into::<web_sys::Node>();
                //debug!("=> got {}", #this_el_ident.node_name());
        }
    } else if let Some(prev_sib) = &prev_sib {
        quote_spanned! {
            span => let #this_el_ident = #debug_name;
                //log::debug!("next_sibling ({})", #debug_name);
                let #this_el_ident = #prev_sib.next_sibling().unwrap_or_else(|| panic!("error : {} => {} ", #debug_name, "nextSibling"));
                //log::debug!("=> got {}", #this_el_ident.node_name());
        }
    } else {
        quote_spanned! {
            span => let #this_el_ident = #debug_name;
                //log::debug!("first_child ({})", #debug_name);
                let #this_el_ident = #parent.first_child().unwrap_or_else(|| panic!("error: {} => {}", #debug_name, "firstChild"));
                //log::debug!("=> got {}", #this_el_ident.node_name());
        }
    };
    navigations.push(this_nav);

    // self-closing tags
    // https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
    if matches!(
        name_str.as_str(),
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    ) {
        template.push_str("/>");
        return this_el_ident;
    } else {
        template.push('>');
    }

    // iterate over children
    let mut prev_sib = prev_sib;
    for (idx, child) in node.children.iter().enumerate() {
        // set next sib (for any insertions)
        let next_sib =
            match next_sibling_node(&node.children, idx + 1, next_el_id) {
                Ok(next_sib) => next_sib,
                Err(err) => abort!(span, "{}", err),
            };

        let curr_id = child_to_tokens(
            cx,
            child,
            &this_el_ident,
            if idx == 0 { None } else { prev_sib.clone() },
            next_sib,
            next_el_id,
            next_co_id,
            template,
            navigations,
            expressions,
        );

        prev_sib = match curr_id {
            PrevSibChange::Sib(id) => Some(id),
            PrevSibChange::Parent => None,
            PrevSibChange::Skip => prev_sib,
        };
    }

    // close tag
    template.push_str("</");
    template.push_str(&name_str);
    template.push('>');

    this_el_ident
}

fn next_sibling_node(
    children: &[Node],
    idx: usize,
    next_el_id: &mut usize,
) -> Result<Option<Ident>, String> {
    if children.len() <= idx {
        Ok(None)
    } else {
        let sibling = &children[idx];

        match sibling {
            Node::Element(sibling) => {
                if is_component_node(sibling) {
                    next_sibling_node(children, idx + 1, next_el_id)
                } else {
                    Ok(Some(child_ident(*next_el_id + 1, sibling.name.span())))
                }
            }
            Node::Block(sibling) => {
                Ok(Some(child_ident(*next_el_id + 1, sibling.value.span())))
            }
            Node::Text(sibling) => {
                Ok(Some(child_ident(*next_el_id + 1, sibling.value.span())))
            }
            _ => Err("expected either an element or a block".to_string()),
        }
    }
}

fn attr_to_tokens(
    cx: &Ident,
    node: &NodeAttribute,
    el_id: &Ident,
    template: &mut String,
    expressions: &mut Vec<TokenStream>,
) {
    let name = node.key.to_string();
    let name = name.strip_prefix('_').unwrap_or(&name);
    let name = name.strip_prefix("attr:").unwrap_or(name);

    let value = match &node.value {
        Some(expr) => match expr.as_ref() {
            syn::Expr::Lit(expr_lit) => {
                if let syn::Lit::Str(s) = &expr_lit.lit {
                    AttributeValue::Static(s.value())
                } else {
                    AttributeValue::Dynamic(expr)
                }
            }
            _ => AttributeValue::Dynamic(expr),
        },
        None => AttributeValue::Empty,
    };

    let span = node.key.span();

    // refs
    if name == "ref" {
        abort!(span, "node_ref not yet supported in template! macro")
    }
    // Event Handlers
    else if name.starts_with("on:") {
        let (event_type, handler) =
            crate::view::event_from_attribute_node(node, false);
        expressions.push(quote! {
            leptos::leptos_dom::add_event_helper(#el_id.unchecked_ref(), #event_type, #handler);
        })
    }
    // Properties
    else if let Some(name) = name.strip_prefix("prop:") {
        let value = attribute_value(node);

        expressions.push(quote_spanned! {
            span => leptos_dom::property(#cx, #el_id.unchecked_ref(), #name, #value.into_property(#cx))
        });
    }
    // Classes
    else if let Some(name) = name.strip_prefix("class:") {
        let value = attribute_value(node);

        expressions.push(quote_spanned! {
            span => leptos::leptos_dom::class_helper(#el_id.unchecked_ref(), #name.into(), #value.into_class(#cx))
        });
    }
    // Attributes
    else {
        match value {
            AttributeValue::Empty => {
                template.push(' ');
                template.push_str(name);
            }

            // Static attributes (i.e., just a literal given as value, not an expression)
            // are just set in the template — again, nothing programmatic
            AttributeValue::Static(value) => {
                template.push(' ');
                template.push_str(name);
                template.push_str("=\"");
                template.push_str(&value);
                template.push('"');
            }
            AttributeValue::Dynamic(value) => {
                // For client-side rendering, dynamic attributes don't need to be rendered in the template
                // They'll immediately be set synchronously before the cloned template is mounted
                expressions.push(quote_spanned! {
                    span => leptos::leptos_dom::attribute_helper(#el_id.unchecked_ref(), #name.into(), {#value}.into_attribute(#cx))
                });
            }
        }
    }
}

enum AttributeValue<'a> {
    Static(String),
    Dynamic(&'a syn::Expr),
    Empty,
}

#[allow(clippy::too_many_arguments)]
fn child_to_tokens(
    cx: &Ident,
    node: &Node,
    parent: &Ident,
    prev_sib: Option<Ident>,
    next_sib: Option<Ident>,
    next_el_id: &mut usize,
    next_co_id: &mut usize,
    template: &mut String,
    navigations: &mut Vec<TokenStream>,
    expressions: &mut Vec<TokenStream>,
) -> PrevSibChange {
    match node {
        Node::Element(node) => {
            if is_component_node(node) {
                proc_macro_error::emit_error!(
                    node.name.span(),
                    "component children not allowed in template!, use view! \
                     instead"
                );
                PrevSibChange::Skip
            } else {
                PrevSibChange::Sib(element_to_tokens(
                    cx,
                    node,
                    parent,
                    prev_sib,
                    next_el_id,
                    next_co_id,
                    template,
                    navigations,
                    expressions,
                    false,
                ))
            }
        }
        Node::Text(node) => block_to_tokens(
            cx,
            &node.value,
            node.value.span(),
            parent,
            prev_sib,
            next_sib,
            next_el_id,
            template,
            expressions,
            navigations,
        ),
        Node::Block(node) => block_to_tokens(
            cx,
            &node.value,
            node.value.span(),
            parent,
            prev_sib,
            next_sib,
            next_el_id,
            template,
            expressions,
            navigations,
        ),
        _ => abort!(cx, "unexpected child node type"),
    }
}

#[allow(clippy::too_many_arguments)]
fn block_to_tokens(
    _cx: &Ident,
    value: &NodeValueExpr,
    span: Span,
    parent: &Ident,
    prev_sib: Option<Ident>,
    next_sib: Option<Ident>,
    next_el_id: &mut usize,
    template: &mut String,
    expressions: &mut Vec<TokenStream>,
    navigations: &mut Vec<TokenStream>,
) -> PrevSibChange {
    let value = value.as_ref();
    let str_value = match value {
        syn::Expr::Lit(lit) => match &lit.lit {
            syn::Lit::Str(s) => Some(s.value()),
            syn::Lit::Char(c) => Some(c.value().to_string()),
            syn::Lit::Int(i) => Some(i.base10_digits().to_string()),
            syn::Lit::Float(f) => Some(f.base10_digits().to_string()),
            _ => None,
        },
        _ => None,
    };

    // code to navigate to this text node

    let (name, location) = /* if is_first_child && mode == Mode::Client {
        (None, quote! { })
    } 
    else */ {
        *next_el_id += 1;
        let name = child_ident(*next_el_id, span);
        let location = if let Some(sibling) = &prev_sib {
            quote_spanned! {
                span => //log::debug!("-> next sibling");
                        let #name = #sibling.next_sibling().unwrap_or_else(|| panic!("error : {} => {} ", "{block}", "nextSibling"));
                        //log::debug!("\tnext sibling = {}", #name.node_name());
            }
        } else {
            quote_spanned! {
                span => //log::debug!("\\|/ first child on {}", #parent.node_name());
                        let #name = #parent.first_child().unwrap_or_else(|| panic!("error : {} => {} ", "{block}", "firstChild"));
                        //log::debug!("\tfirst child = {}", #name.node_name());
            }
        };
        (Some(name), location)
    };

    let mount_kind = match &next_sib {
        Some(child) => {
            quote! { leptos::leptos_dom::MountKind::Before(&#child.clone()) }
        }
        None => {
            quote! { leptos::leptos_dom::MountKind::Append(&#parent) }
        }
    };

    if let Some(v) = str_value {
        navigations.push(location);
        template.push_str(&v);

        if let Some(name) = name {
            PrevSibChange::Sib(name)
        } else {
            PrevSibChange::Parent
        }
    } else {
        template.push_str("<!>");
        navigations.push(location);

        expressions.push(quote! {
			leptos::leptos_dom::mount_child(#mount_kind, &{#value}.into_view(cx));
        });

        if let Some(name) = name {
            PrevSibChange::Sib(name)
        } else {
            PrevSibChange::Parent
        }
    }
}

fn child_ident(el_id: usize, span: Span) -> Ident {
    let id = format!("_el{el_id}");
    Ident::new(&id, span)
}