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
use std::fmt::{Display, Formatter};

use super::*;

use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
    parse::{Parse, ParseBuffer, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    Error, Expr, Ident, LitStr, Result, Token,
};

// =======================================
// Parse the VNode::Element type
// =======================================
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct Element {
    pub name: ElementName,
    pub key: Option<IfmtInput>,
    pub attributes: Vec<ElementAttrNamed>,
    pub children: Vec<BodyNode>,
    pub brace: syn::token::Brace,
}

impl Parse for Element {
    fn parse(stream: ParseStream) -> Result<Self> {
        let el_name = ElementName::parse(stream)?;

        // parse the guts
        let content: ParseBuffer;
        let brace = syn::braced!(content in stream);

        let mut attributes: Vec<ElementAttrNamed> = vec![];
        let mut children: Vec<BodyNode> = vec![];
        let mut key = None;
        let mut _el_ref = None;

        // parse fields with commas
        // break when we don't get this pattern anymore
        // start parsing bodynodes
        // "def": 456,
        // abc: 123,
        loop {
            // Parse the raw literal fields
            if content.peek(LitStr) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
                let name = content.parse::<LitStr>()?;
                let ident = name.clone();

                content.parse::<Token![:]>()?;

                if content.peek(LitStr) {
                    let value = content.parse()?;
                    attributes.push(ElementAttrNamed {
                        el_name: el_name.clone(),
                        attr: ElementAttr::CustomAttrText { name, value },
                    });
                } else {
                    let value = content.parse::<Expr>()?;
                    attributes.push(ElementAttrNamed {
                        el_name: el_name.clone(),
                        attr: ElementAttr::CustomAttrExpression { name, value },
                    });
                }

                if content.is_empty() {
                    break;
                }

                if content.parse::<Token![,]>().is_err() {
                    missing_trailing_comma!(ident.span());
                }
                continue;
            }

            if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
                let name = content.parse::<Ident>()?;

                let name_str = name.to_string();
                content.parse::<Token![:]>()?;

                // The span of the content to be parsed,
                // for example the `hi` part of `class: "hi"`.
                let span = content.span();

                if name_str.starts_with("on") {
                    attributes.push(ElementAttrNamed {
                        el_name: el_name.clone(),
                        attr: ElementAttr::EventTokens {
                            name,
                            tokens: content.parse()?,
                        },
                    });
                } else {
                    match name_str.as_str() {
                        "key" => {
                            key = Some(content.parse()?);
                        }
                        "classes" => todo!("custom class list not supported yet"),
                        // "namespace" => todo!("custom namespace not supported yet"),
                        "node_ref" => {
                            _el_ref = Some(content.parse::<Expr>()?);
                        }
                        _ => {
                            if content.peek(LitStr) {
                                attributes.push(ElementAttrNamed {
                                    el_name: el_name.clone(),
                                    attr: ElementAttr::AttrText {
                                        name,
                                        value: content.parse()?,
                                    },
                                });
                            } else {
                                attributes.push(ElementAttrNamed {
                                    el_name: el_name.clone(),
                                    attr: ElementAttr::AttrExpression {
                                        name,
                                        value: content.parse()?,
                                    },
                                });
                            }
                        }
                    }
                }

                if content.is_empty() {
                    break;
                }

                // todo: add a message saying you need to include commas between fields
                if content.parse::<Token![,]>().is_err() {
                    missing_trailing_comma!(span);
                }
                continue;
            }

            break;
        }

        while !content.is_empty() {
            if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
                attr_after_element!(content.span());
            }

            if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
                attr_after_element!(content.span());
            }

            children.push(content.parse::<BodyNode>()?);
            // consume comma if it exists
            // we don't actually care if there *are* commas after elements/text
            if content.peek(Token![,]) {
                let _ = content.parse::<Token![,]>();
            }
        }

        Ok(Self {
            key,
            name: el_name,
            attributes,
            children,
            brace,
        })
    }
}

impl ToTokens for Element {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let name = &self.name;
        let children = &self.children;

        let key = match &self.key {
            Some(ty) => quote! { Some(#ty) },
            None => quote! { None },
        };

        let listeners = self
            .attributes
            .iter()
            .filter(|f| matches!(f.attr, ElementAttr::EventTokens { .. }));

        let attr = self
            .attributes
            .iter()
            .filter(|f| !matches!(f.attr, ElementAttr::EventTokens { .. }));

        tokens.append_all(quote! {
            __cx.element(
                #name,
                __cx.bump().alloc([ #(#listeners),* ]),
                __cx.bump().alloc([ #(#attr),* ]),
                __cx.bump().alloc([ #(#children),* ]),
                #key,
            )
        });
    }
}

#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum ElementName {
    Ident(Ident),
    Custom(LitStr),
}

impl ElementName {
    pub(crate) fn tag_name(&self) -> TokenStream2 {
        match self {
            ElementName::Ident(i) => quote! { dioxus_elements::#i::TAG_NAME },
            ElementName::Custom(s) => quote! { #s },
        }
    }
}

impl ElementName {
    pub fn span(&self) -> Span {
        match self {
            ElementName::Ident(i) => i.span(),
            ElementName::Custom(s) => s.span(),
        }
    }
}

impl PartialEq<&str> for ElementName {
    fn eq(&self, other: &&str) -> bool {
        match self {
            ElementName::Ident(i) => i == *other,
            ElementName::Custom(s) => s.value() == *other,
        }
    }
}

impl Display for ElementName {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ElementName::Ident(i) => write!(f, "{}", i),
            ElementName::Custom(s) => write!(f, "{}", s.value()),
        }
    }
}

impl Parse for ElementName {
    fn parse(stream: ParseStream) -> Result<Self> {
        let raw = Punctuated::<Ident, Token![-]>::parse_separated_nonempty(stream)?;
        if raw.len() == 1 {
            Ok(ElementName::Ident(raw.into_iter().next().unwrap()))
        } else {
            let span = raw.span();
            let tag = raw
                .into_iter()
                .map(|ident| ident.to_string())
                .collect::<Vec<_>>()
                .join("-");
            let tag = LitStr::new(&tag, span);
            Ok(ElementName::Custom(tag))
        }
    }
}

impl ToTokens for ElementName {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        match self {
            ElementName::Ident(i) => tokens.append_all(quote! { dioxus_elements::#i }),
            ElementName::Custom(s) => tokens.append_all(quote! { #s }),
        }
    }
}

#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub enum ElementAttr {
    /// `attribute: "value"`
    AttrText { name: Ident, value: IfmtInput },

    /// `attribute: true`
    AttrExpression { name: Ident, value: Expr },

    /// `"attribute": "value"`
    CustomAttrText { name: LitStr, value: IfmtInput },

    /// `"attribute": true`
    CustomAttrExpression { name: LitStr, value: Expr },

    // /// onclick: move |_| {}
    // EventClosure { name: Ident, closure: ExprClosure },
    /// onclick: {}
    EventTokens { name: Ident, tokens: Expr },
}

impl ElementAttr {
    pub fn start(&self) -> Span {
        match self {
            ElementAttr::AttrText { name, .. } => name.span(),
            ElementAttr::AttrExpression { name, .. } => name.span(),
            ElementAttr::CustomAttrText { name, .. } => name.span(),
            ElementAttr::CustomAttrExpression { name, .. } => name.span(),
            ElementAttr::EventTokens { name, .. } => name.span(),
        }
    }

    pub fn is_expr(&self) -> bool {
        matches!(
            self,
            ElementAttr::AttrExpression { .. }
                | ElementAttr::CustomAttrExpression { .. }
                | ElementAttr::EventTokens { .. }
        )
    }
}

#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct ElementAttrNamed {
    pub el_name: ElementName,
    pub attr: ElementAttr,
}

impl ToTokens for ElementAttrNamed {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let ElementAttrNamed { el_name, attr } = self;

        let ns = |name| match el_name {
            ElementName::Ident(i) => quote! { dioxus_elements::#i::#name.1 },
            ElementName::Custom(_) => quote! { None },
        };
        let volitile = |name| match el_name {
            ElementName::Ident(_) => quote! { #el_name::#name.2 },
            ElementName::Custom(_) => quote! { false },
        };
        let attribute = |name: &Ident| match el_name {
            ElementName::Ident(_) => quote! { #el_name::#name.0 },
            ElementName::Custom(_) => {
                let as_string = name.to_string();
                quote!(#as_string)
            }
        };

        let attribute = match attr {
            ElementAttr::AttrText { name, value } => {
                let ns = ns(name);
                let volitile = volitile(name);
                let attribute = attribute(name);
                quote! {
                    __cx.attr(
                        #attribute,
                        #value,
                        #ns,
                        #volitile
                    )
                }
            }
            ElementAttr::AttrExpression { name, value } => {
                let ns = ns(name);
                let volitile = volitile(name);
                let attribute = attribute(name);
                quote! {
                    __cx.attr(
                        #attribute,
                        #value,
                        #ns,
                        #volitile
                    )
                }
            }
            ElementAttr::CustomAttrText { name, value } => {
                quote! {
                    __cx.attr(
                        #name,
                        #value,
                        None,
                        false
                    )
                }
            }
            ElementAttr::CustomAttrExpression { name, value } => {
                quote! {
                    __cx.attr(
                        #name,
                        #value,
                        None,
                        false
                    )
                }
            }
            ElementAttr::EventTokens { name, tokens } => {
                quote! {
                    dioxus_elements::events::#name(__cx, #tokens)
                }
            }
        };

        tokens.append_all(attribute);
    }
}

// ::dioxus::core::Attribute {
//     name: stringify!(#name),
//     namespace: None,
//     volatile: false,
//     mounted_node: Default::default(),
//     value: ::dioxus::core::AttributeValue::Text(#value),
// }