axum-wire-macros 0.0.6

Proc macros for axum-wire — #[derive(Component)], #[wire_actions], html!
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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
use proc_macro2::{Group, Punct, Spacing, Span, TokenStream, TokenTree};
use quote::quote;
use rstml::node::{Node, NodeAttribute, NodeElement, NodeName};
use rstml::Infallible;
use syn::Ident;

use crate::pascal_to_kebab;

/// Rust keywords that need `r#` prefix when used as identifiers.
const RUST_KEYWORDS: &[&str] = &[
    "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
    "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
    "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
    "unsafe", "use", "where", "while", "yield",
];

/// Create an `Ident`, using `new_raw` for Rust keywords.
fn ident_or_raw(name: &str, span: Span) -> Ident {
    if RUST_KEYWORDS.contains(&name) {
        Ident::new_raw(name, span)
    } else {
        Ident::new(name, span)
    }
}

/// Entry point: parse the token stream as RSX and generate a `String` expression.
pub fn generate(input: TokenStream) -> syn::Result<TokenStream> {
    let input = preprocess_alpine_shorthand_attrs(input);
    let nodes = rstml::parse2(input)?;

    let mut parts: Vec<TokenStream> = Vec::new();
    for node in &nodes {
        node_to_tokens(node, &mut parts)?;
    }

    Ok(quote! {
        {
            use ::axum_wire::WireRenderTagIter as _;
            let mut __html = ::std::string::String::new();
            #(#parts)*
            __html
        }
    })
}

fn preprocess_alpine_shorthand_attrs(input: TokenStream) -> TokenStream {
    let tokens: Vec<TokenTree> = input.into_iter().collect();
    let mut out = TokenStream::new();
    let mut i = 0;

    while i < tokens.len() {
        match &tokens[i] {
            TokenTree::Group(group) => {
                let mut new_group = Group::new(
                    group.delimiter(),
                    preprocess_alpine_shorthand_attrs(group.stream()),
                );
                new_group.set_span(group.span());
                out.extend([TokenTree::Group(new_group)]);
                i += 1;
            }
            TokenTree::Punct(p) if p.as_char() == ':' => {
                let prev_is_part_of_name = if i == 0 {
                    false
                } else {
                    match &tokens[i - 1] {
                        TokenTree::Ident(_) => true,
                        TokenTree::Punct(prev) => matches!(prev.as_char(), '-' | ':'),
                        _ => false,
                    }
                };

                if prev_is_part_of_name {
                    out.extend([tokens[i].clone()]);
                    i += 1;
                    continue;
                }

                let mut j = i + 1;
                let mut key_tokens: Vec<TokenTree> = Vec::new();
                let mut valid = true;

                while j < tokens.len() {
                    match &tokens[j] {
                        TokenTree::Punct(eq) if eq.as_char() == '=' => break,
                        TokenTree::Ident(_) => key_tokens.push(tokens[j].clone()),
                        TokenTree::Punct(sym) if matches!(sym.as_char(), '-' | '.') => {
                            key_tokens.push(tokens[j].clone())
                        }
                        _ => {
                            valid = false;
                            break;
                        }
                    }
                    j += 1;
                }

                if valid
                    && !key_tokens.is_empty()
                    && j < tokens.len()
                    && matches!(&tokens[j], TokenTree::Punct(eq) if eq.as_char() == '=')
                {
                    out.extend([
                        TokenTree::Ident(Ident::new("x", Span::call_site())),
                        TokenTree::Punct(Punct::new('-', Spacing::Alone)),
                        TokenTree::Ident(Ident::new("bind", Span::call_site())),
                        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
                    ]);
                    out.extend(key_tokens);
                    i = j;
                } else {
                    out.extend([tokens[i].clone()]);
                    i += 1;
                }
            }
            TokenTree::Punct(p) if p.as_char() == '@' => {
                let mut j = i + 1;
                let mut key_tokens: Vec<TokenTree> = Vec::new();
                let mut valid = true;

                while j < tokens.len() {
                    match &tokens[j] {
                        TokenTree::Punct(eq) if eq.as_char() == '=' => break,
                        TokenTree::Ident(_) => key_tokens.push(tokens[j].clone()),
                        TokenTree::Punct(sym) if matches!(sym.as_char(), '-' | '.') => {
                            key_tokens.push(tokens[j].clone())
                        }
                        _ => {
                            valid = false;
                            break;
                        }
                    }
                    j += 1;
                }

                if valid
                    && !key_tokens.is_empty()
                    && j < tokens.len()
                    && matches!(&tokens[j], TokenTree::Punct(eq) if eq.as_char() == '=')
                {
                    out.extend([
                        TokenTree::Ident(Ident::new("x", Span::call_site())),
                        TokenTree::Punct(Punct::new('-', Spacing::Alone)),
                        TokenTree::Ident(Ident::new("on", Span::call_site())),
                        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
                    ]);
                    out.extend(key_tokens);
                    i = j;
                } else {
                    out.extend([tokens[i].clone()]);
                    i += 1;
                }
            }
            _ => {
                out.extend([tokens[i].clone()]);
                i += 1;
            }
        }
    }

    out
}

// ---------------------------------------------------------------------------
// Block expression transforms — handle `if`/`match`/`for` inside `{}`
// ---------------------------------------------------------------------------

/// Generate the tag-dispatch pattern that handles both `HtmlFragment` and
/// `Iterator` values:
/// ```ignore
/// {
///     let __wr = ::axum_wire::WireRender(EXPR);
///     let __tag = (&__wr).__wire_render_tag();
///     __tag.__wire_render(__wr.0)
/// }
/// ```
fn wire_render_expr(expr: TokenStream) -> TokenStream {
    quote! {
        {
            let __wr = ::axum_wire::WireRender(#expr);
            let __tag = (&__wr).__wire_render_tag();
            __tag.__wire_render(__wr.0)
        }
    }
}

/// Wrap an expression so its result is pushed to `__html` via
/// the tag-dispatch pattern. This is the building block for transforming
/// individual arms of `if`/`match` expressions.
fn wrap_expr_push(expr: &syn::Expr) -> TokenStream {
    let rendered = wire_render_expr(quote! { #expr });
    quote! {
        __html.push_str(&#rendered);
    }
}

/// Try to transform a block containing a bare `if`, `match`, or `for`
/// expression into code that pushes each arm's result to `__html`
/// independently. Returns `None` if the block doesn't match a known
/// pattern, falling back to the default `WireRender` path.
fn try_transform_block_expr(block: &syn::Block) -> Option<TokenStream> {
    // We only handle blocks with a single trailing expression (no semicolon).
    if block.stmts.len() != 1 {
        return None;
    }
    let syn::Stmt::Expr(expr, None) = &block.stmts[0] else {
        return None;
    };
    try_transform_expr(expr)
}

/// Fallback for `NodeBlock::Invalid` — rstml couldn't parse the block as a
/// valid `syn::Block` (common when nested macro calls like `html!` appear),
/// but the raw tokens may still represent a valid Rust expression. Try to
/// parse them as `syn::Expr` and apply the same `if`/`match`/`for` transform.
fn try_transform_block_tokens(block: &rstml::node::NodeBlock) -> Option<TokenStream> {
    let tokens = match block {
        rstml::node::NodeBlock::ValidBlock(_) => return None, // already handled
        rstml::node::NodeBlock::Invalid(invalid) => &invalid.body,
    };
    let expr: syn::Expr = syn::parse2(tokens.clone()).ok()?;
    try_transform_expr(&expr)
}

/// Recursively transform an expression so each leaf writes to `__html`.
fn try_transform_expr(expr: &syn::Expr) -> Option<TokenStream> {
    match expr {
        syn::Expr::If(expr_if) => Some(transform_if(expr_if)),
        syn::Expr::Match(expr_match) => Some(transform_match(expr_match)),
        syn::Expr::ForLoop(expr_for) => Some(transform_for(expr_for)),
        // Parenthesised — peel and retry
        syn::Expr::Paren(p) => try_transform_expr(&p.expr),
        _ => None,
    }
}

/// Transform `if cond { body } else if ... { body } else { body }` so each
/// branch pushes to `__html`.  Missing `else` is fine — it simply does nothing.
fn transform_if(expr_if: &syn::ExprIf) -> TokenStream {
    let cond = &expr_if.cond;
    let then_branch = transform_block_stmts(&expr_if.then_branch);

    let else_branch = match &expr_if.else_branch {
        Some((_else_tok, else_expr)) => {
            // The else expression could be another `if` (else-if) or a block.
            if let Some(transformed) = try_transform_expr(else_expr) {
                quote! { else { #transformed } }
            } else {
                // Plain else block — wrap its value
                let rendered = wire_render_expr(quote! { #else_expr });
                quote! { else { __html.push_str(&#rendered); } }
            }
        }
        None => {
            // No else — that's fine, just emit nothing (the whole point!)
            quote! {}
        }
    };

    quote! {
        if #cond {
            #then_branch
        } #else_branch
    }
}

/// Transform a `match` expression: each arm body is wrapped to push to `__html`.
fn transform_match(expr_match: &syn::ExprMatch) -> TokenStream {
    let scrutinee = &expr_match.expr;
    let attrs = &expr_match.attrs;
    let arms: Vec<TokenStream> = expr_match
        .arms
        .iter()
        .map(|arm| {
            let pat = &arm.pat;
            let guard = arm.guard.as_ref().map(|(if_tok, expr)| {
                quote! { #if_tok #expr }
            });
            let body = &arm.body;
            let comma = if arm.comma.is_some() {
                quote! { , }
            } else {
                quote! {}
            };
            let rendered = wire_render_expr(quote! { #body });
            quote! {
                #pat #guard => {
                    __html.push_str(&#rendered);
                } #comma
            }
        })
        .collect();

    quote! {
        #(#attrs)*
        match #scrutinee {
            #(#arms)*
        }
    }
}

/// Transform a `for` loop: each iteration's body pushes to `__html`.
fn transform_for(expr_for: &syn::ExprForLoop) -> TokenStream {
    let pat = &expr_for.pat;
    let iter = &expr_for.expr;
    let body = transform_block_stmts(&expr_for.body);

    quote! {
        for #pat in #iter {
            #body
        }
    }
}

/// Transform the statements in a block body (used for `if`/`for` branches).
/// The last statement (if it's an expression without semicolon, or a macro
/// invocation without semicolon) is wrapped with `WireRender`;
/// everything before it is emitted as-is.
fn transform_block_stmts(block: &syn::Block) -> TokenStream {
    let stmts = &block.stmts;
    if stmts.is_empty() {
        return quote! {};
    }

    let last_idx = stmts.len() - 1;
    let mut tokens = TokenStream::new();

    for (i, stmt) in stmts.iter().enumerate() {
        if i == last_idx {
            // Last statement — if it's a bare expression, wrap it
            if let syn::Stmt::Expr(expr, None) = stmt {
                // Check if the last expression is itself a transformable control flow
                if let Some(inner) = try_transform_expr(expr) {
                    tokens.extend(inner);
                } else {
                    tokens.extend(wrap_expr_push(expr));
                }
            } else if let syn::Stmt::Macro(stmt_macro) = stmt {
                // Brace-delimited macro calls (e.g. `html! { ... }`) at the
                // end of a block are parsed as `Stmt::Macro` rather than
                // `Stmt::Expr`.  If there's no trailing semicolon, the macro
                // is the block's return value — wrap it the same way.
                if stmt_macro.semi_token.is_none() {
                    let mac = &stmt_macro.mac;
                    let rendered = wire_render_expr(quote! { #mac });
                    tokens.extend(quote! {
                        __html.push_str(&#rendered);
                    });
                } else {
                    tokens.extend(quote! { #stmt });
                }
            } else {
                // Statement with semicolon or let/item — emit as-is
                tokens.extend(quote! { #stmt });
            }
        } else {
            tokens.extend(quote! { #stmt });
        }
    }

    tokens
}

fn node_to_tokens(node: &Node, parts: &mut Vec<TokenStream>) -> syn::Result<()> {
    match node {
        Node::Element(el) => element_to_tokens(el, parts),
        Node::Text(text) => {
            let value = &text.value;
            parts.push(quote! {
                __html.push_str(&::std::format!("{}", #value));
            });
            Ok(())
        }
        Node::Block(block) => {
            // Try to extract a `syn::Block` so we can inspect the expression.
            // If it's a bare `if` or `match` (whose arms may return different
            // `HtmlFragment` types), we transform each arm to push to `__html`
            // independently, avoiding Rust's requirement that all arms share
            // the same type.  For every other expression we fall back to the
            // simple `WireRender(expr).__wire_render()` path.
            //
            // We try two strategies:
            // 1. `try_block()` for `ValidBlock` (syn parsed it as a `Block`)
            // 2. Parse the raw token stream as a `syn::Expr` for `InvalidBlock`
            //    (rstml may classify blocks with nested macros as invalid syn
            //    blocks, but the tokens are still valid Rust)
            let transformed = block
                .try_block()
                .and_then(try_transform_block_expr)
                .or_else(|| try_transform_block_tokens(block));

            if let Some(tokens) = transformed {
                parts.push(tokens);
            } else {
                let rendered = wire_render_expr(quote! { #block });
                parts.push(quote! {
                    #[allow(unused_braces)]
                    __html.push_str(&#rendered);
                });
            }
            Ok(())
        }
        Node::Comment(comment) => {
            let value = &comment.value;
            parts.push(quote! {
                __html.push_str("<!-- ");
                __html.push_str(&::std::format!("{}", #value));
                __html.push_str(" -->");
            });
            Ok(())
        }
        Node::Fragment(fragment) => {
            for child in &fragment.children {
                node_to_tokens(child, parts)?;
            }
            Ok(())
        }
        Node::Doctype(doctype) => {
            let value = &doctype.value;
            parts.push(quote! {
                __html.push_str(&::std::format!("<!DOCTYPE {}>", #value));
            });
            Ok(())
        }
        Node::RawText(raw) => {
            let text = raw.to_string_best();
            parts.push(quote! { __html.push_str(#text); });
            Ok(())
        }
        Node::Custom(_) => {
            // Custom nodes are not used in our config
            Ok(())
        }
    }
}

fn element_to_tokens(
    el: &NodeElement<Infallible>,
    parts: &mut Vec<TokenStream>,
) -> syn::Result<()> {
    let tag_name = el.name().to_string();

    // Capitalized tag name → wire sub-component
    let first_char = tag_name.chars().next().unwrap_or('a');
    if first_char.is_uppercase() {
        return component_to_tokens(&tag_name, el, parts);
    }

    // Emit inline type hint for the open tag (hover docs + go-to-definition).
    let open_tag_hint = element_type_hint(&tag_name, el.name());

    // Emit a completion hint: a dead-code block that references element
    // attributes so RA can provide autocomplete for attribute names.
    let completion_hint = if is_known_element(&tag_name) {
        let mod_ident = ident_or_raw(&tag_name, Span::call_site());
        quote! {
            #[allow(unused)]
            {
                // Bring all attributes for this element into scope so RA can
                // suggest them when the user types an attribute name.
                use ::axum_wire::html_elements::#mod_ident::*;
                let _ = TAG_NAME;
            }
        }
    } else {
        quote! {}
    };

    // Opening tag
    let tag_str = tag_name.clone();
    parts.push(quote! {
        #open_tag_hint
        #completion_hint
        __html.push('<');
        __html.push_str(#tag_str);
    });

    // Attributes — each gets an inline type hint before its push_str
    for attr in el.attributes() {
        attr_to_tokens_with_hint(&tag_name, attr, parts)?;
    }

    // Self-closing void elements
    let is_void = is_void_element(&tag_name);
    if el.children.is_empty() && is_void {
        parts.push(quote! { __html.push_str(" />"); });
        return Ok(());
    }

    parts.push(quote! { __html.push('>'); });

    // Children
    for child in &el.children {
        node_to_tokens(child, parts)?;
    }

    // Closing tag — emit type hint for the close tag too
    let close_tag_hint = close_tag_type_hint(&tag_name, el);
    parts.push(quote! {
        #close_tag_hint
        __html.push_str("</");
        __html.push_str(#tag_str);
        __html.push('>');
    });

    Ok(())
}

// ---------------------------------------------------------------------------
// Inline type hints — emitted directly in the code flow for RA coloring
// ---------------------------------------------------------------------------

/// Extract the span from a `NodeName`.
fn node_name_span(name: &NodeName) -> Span {
    match name {
        NodeName::Path(expr_path) => expr_path
            .path
            .segments
            .last()
            .map(|s| s.ident.span())
            .unwrap_or_else(Span::call_site),
        NodeName::Punctuated(p) => p
            .pairs()
            .next()
            .and_then(|pair| match pair.value() {
                rstml::node::NodeNameFragment::Ident(ident) => Some(ident.span()),
                _ => None,
            })
            .unwrap_or_else(Span::call_site),
        _ => Span::call_site(),
    }
}

/// Emit an inline reference to the element's module.
/// `<div>` → `let _ = ::axum_wire::html_elements::div::TAG_NAME;`
/// This gives RA hover docs + go-to-definition on the tag name.
fn element_type_hint(tag_name: &str, node_name: &NodeName) -> TokenStream {
    if !is_known_element(tag_name) {
        return quote! {};
    }
    let span = node_name_span(node_name);
    let mod_ident = ident_or_raw(tag_name, span);
    quote! {
        #[allow(unused)]
        { let _ = ::axum_wire::html_elements::#mod_ident::TAG_NAME; }
    }
}

/// Emit an inline reference for the close tag `</div>`.
fn close_tag_type_hint(tag_name: &str, el: &NodeElement<Infallible>) -> TokenStream {
    if !is_known_element(tag_name) {
        return quote! {};
    }
    let span = el
        .close_tag
        .as_ref()
        .map(|ct| node_name_span(&ct.name))
        .unwrap_or_else(Span::call_site);
    let mod_ident = ident_or_raw(tag_name, span);
    quote! {
        #[allow(unused)]
        { let _ = ::axum_wire::html_elements::#mod_ident::TAG_NAME; }
    }
}

/// Emit an inline reference to an attribute const on the element's module.
/// `class="foo"` on a `<div>` → `let _ = ::axum_wire::html_elements::div::class;`
/// This gives RA hover docs + completions (via `use element_mod::*`).
fn attr_type_hint(tag_name: &str, attr: &NodeAttribute) -> TokenStream {
    let NodeAttribute::Attribute(kv) = attr else {
        return quote! {};
    };

    let key = node_name_to_string(&kv.key);

    // Skip wire: directives, data- attributes, Alpine x- attributes
    if key.starts_with("wire:") || key.starts_with("data-") || key.starts_with("x-") {
        return quote! {};
    }

    // Normalize: hyphens and colons to underscores for Rust ident
    let rust_key = key.replace(['-', ':'], "_");

    if !is_known_element(tag_name) {
        return quote! {};
    }

    let span = node_name_span(&kv.key);
    let mod_ident = ident_or_raw(tag_name, Span::call_site());
    let attr_ident = ident_or_raw(&rust_key, span);

    // Keep attribute hints non-strict: we stringify the path instead of resolving
    // it as a real symbol, so unknown attributes don't fail compilation.
    quote! {
        #[allow(unused)]
        { let _ = ::std::stringify!(::axum_wire::html_elements::#mod_ident::#attr_ident); }
    }
}

fn is_known_element(tag: &str) -> bool {
    matches!(
        tag,
        "html" | "head" | "base" | "link" | "meta" | "style" | "title" | "body"
        | "address" | "article" | "aside" | "footer" | "header"
        | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "hgroup"
        | "main" | "nav" | "section" | "search"
        | "blockquote" | "dd" | "div" | "dl" | "dt" | "figcaption" | "figure"
        | "hr" | "li" | "menu" | "ol" | "p" | "pre" | "ul"
        | "a" | "abbr" | "b" | "bdi" | "bdo" | "br" | "cite" | "code" | "data"
        | "dfn" | "em" | "i" | "kbd" | "mark" | "q" | "rp" | "rt" | "ruby"
        | "s" | "samp" | "small" | "span" | "strong" | "sub" | "sup" | "time"
        | "u" | "var" | "wbr"
        | "area" | "audio" | "img" | "map" | "track" | "video"
        | "embed" | "iframe" | "object" | "picture" | "portal" | "source"
        | "svg" | "math"
        | "canvas" | "noscript" | "script"
        | "del" | "ins"
        | "caption" | "col" | "colgroup" | "table" | "tbody" | "td" | "tfoot" | "th" | "thead" | "tr"
        | "button" | "datalist" | "fieldset" | "form" | "input" | "label" | "legend"
        | "meter" | "optgroup" | "option" | "output" | "progress" | "select" | "textarea"
        | "details" | "dialog" | "summary"
        | "slot" | "template"
        // SVG elements
        | "path" | "circle" | "rect" | "line" | "polyline" | "polygon" | "ellipse"
        | "text" | "g" | "defs" | "use" | "clipPath" | "mask" | "pattern"
        | "linearGradient" | "radialGradient" | "stop" | "filter" | "image" | "symbol"
        | "animate" | "animateTransform" | "foreignObject" | "tspan"
    )
}

/// Handle `<Counter />` or `<Counter count=42 />` — mounts a sub-component inline.
///
/// Emits:
/// 1. A type assertion so rust-analyzer can resolve and link `Counter`
/// 2. If no props: `mount_component_sync("counter")`
/// 3. If props: `mount_component_with_props_sync("counter", json!({"count": 42}))`
fn component_to_tokens(
    tag_name: &str,
    el: &NodeElement<Infallible>,
    parts: &mut Vec<TokenStream>,
) -> syn::Result<()> {
    let wire_name = pascal_to_kebab(tag_name);

    // Use the original NodeName path so rust-analyzer preserves the span
    // and can resolve it as a go-to-definition target.
    let type_path = match el.name() {
        NodeName::Path(expr_path) => {
            let path = &expr_path.path;
            quote! { #path }
        }
        _ => {
            let ident = Ident::new(tag_name, Span::call_site());
            quote! { #ident }
        }
    };

    // Collect props from attributes
    let mut prop_key_strings: Vec<String> = Vec::new();
    let mut prop_key_idents: Vec<proc_macro2::Ident> = Vec::new();
    let mut prop_values: Vec<TokenStream> = Vec::new();
    let mut event_names: Vec<String> = Vec::new();
    let mut event_handlers: Vec<String> = Vec::new();

    for attr in el.attributes() {
        if let NodeAttribute::Attribute(kv) = attr {
            let key = node_name_to_string(&kv.key);
            if key.starts_with("x-on:") {
                if let Some(value) = kv.value() {
                    let handler = if let syn::Expr::Lit(expr_lit) = value {
                        if let syn::Lit::Str(lit) = &expr_lit.lit {
                            lit.value()
                        } else {
                            quote!(#value).to_string()
                        }
                    } else if let Some(path) = extract_path_from_expr(value) {
                        path.segments
                            .last()
                            .map(|s| s.ident.to_string())
                            .unwrap_or_default()
                    } else {
                        quote!(#value).to_string()
                    };

                    let translated = if handler.trim() == "$refresh" {
                        String::from("$wire.$parent.$refresh")
                    } else {
                        format!("$wire.$parent.{handler}")
                    };

                    let event = key.trim_start_matches("x-on:").to_string();
                    event_names.push(event);
                    event_handlers.push(translated);
                }
                continue;
            }

            if let Some(value) = kv.value() {
                // Create an Ident from the key for struct field access.
                // Use the key's span from the original NodeName so RA can link it.
                let key_span = match &kv.key {
                    NodeName::Path(p) => p.path.segments.last().map(|s| s.ident.span()),
                    NodeName::Punctuated(p) => {
                        p.pairs().next().and_then(|pair| match pair.value() {
                            rstml::node::NodeNameFragment::Ident(ident) => Some(ident.span()),
                            _ => None,
                        })
                    }
                    _ => None,
                }
                .unwrap_or_else(Span::call_site);

                prop_key_idents.push(proc_macro2::Ident::new(&key, key_span));
                prop_key_strings.push(key);
                prop_values.push(quote! { #value });
            }
        }
    }

    let has_props = !prop_key_strings.is_empty();
    let has_events = !event_names.is_empty();

    let mount_call = if has_props || has_events {
        let events_json = if has_events {
            quote! {
                ::std::option::Option::Some(
                    ::axum_wire::serde_json::json!({
                        #( #event_names: #event_handlers ),*
                    })
                )
            }
        } else {
            quote! { ::std::option::Option::None }
        };

        quote! {
            ::axum_wire::mount_component_with_options_sync(
                #wire_name,
                ::axum_wire::serde_json::json!({
                    #( #prop_key_strings: #prop_values ),*
                }),
                #events_json,
            )
        }
    } else {
        quote! {
            ::axum_wire::mount_component_sync(#wire_name)
        }
    };

    // Compile-time type assertion for props: builds a struct literal so the
    // compiler checks field names and types. The value is never used at runtime.
    let props_assertion = if has_props {
        let field_assignments = prop_key_idents
            .iter()
            .zip(prop_values.iter())
            .map(|(k, v)| {
                quote! { #k: #v }
            });
        quote! {
            #[allow(unreachable_code, unused, clippy::needless_update)]
            if false {
                let _ = #type_path { #(#field_assignments,)* ..::std::default::Default::default() };
            }
        }
    } else {
        quote! {}
    };

    parts.push(quote! {
        {
            // Compile-time assertion: the component type must exist and implement ComponentMeta.
            // This makes `<Counter />` clickable in rust-analyzer (go-to-definition).
            #[allow(clippy::no_effect)]
            fn __wire_assert_component<T: ::axum_wire::ComponentMeta>() {}
            __wire_assert_component::<#type_path>();

            // Compile-time assertion: props match the struct fields and types.
            #props_assertion
        }
        __html.push_str(
            &(#mount_call)
                .unwrap_or_else(|e| ::std::format!("<!-- wire error: {} -->", e))
        );
    });

    Ok(())
}

/// Check if an attribute key is a wire: directive (e.g. `wire:click`, `wire:submit.prevent`).
fn is_wire_directive(key: &str) -> bool {
    key.starts_with("wire:")
}

/// Try to extract a `Path` from an expression, looking through blocks.
///
/// `{Self::increment}` parses as `Expr::Block` containing `Expr::Path`.
fn extract_path_from_expr(expr: &syn::Expr) -> Option<&syn::Path> {
    match expr {
        syn::Expr::Path(expr_path) => Some(&expr_path.path),
        syn::Expr::Block(expr_block) => {
            if let Some(syn::Stmt::Expr(inner, None)) = expr_block.block.stmts.last() {
                extract_path_from_expr(inner)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Extract the action name from a wire: directive value.
///
/// Supports:
/// - String literal: `wire:click="increment"` → just emit the string
/// - Method path: `wire:click={Self::increment}` → emit string + type-checked reference
fn wire_action_to_tokens(
    key: &str,
    value: &syn::Expr,
    parts: &mut Vec<TokenStream>,
) -> syn::Result<()> {
    if let Some(path) = extract_path_from_expr(value) {
        // wire:click={Self::increment} — method reference, linkable in IDE
        let method_name = path
            .segments
            .last()
            .map(|s| s.ident.to_string())
            .unwrap_or_default();

        parts.push(quote! {
            // Compile-time check: the method must exist on the type.
            // This makes `Self::increment` go-to-definition-able in rust-analyzer.
            {
                #[allow(clippy::no_effect, path_statements)]
                let _ = #path;
            }
            __html.push_str(&::std::format!(" {}=\"{}\"", #key, #method_name));
        });

        Ok(())
    } else if let Some(call) = extract_call_expr(value) {
        if let Some(path) = extract_path_from_expr(&call.func) {
            let method_name = path
                .segments
                .last()
                .map(|s| s.ident.to_string())
                .unwrap_or_default();

            let args = call.args.iter();
            if key == "wire:click" {
                parts.push(quote! {
                    {
                        #[allow(clippy::no_effect, path_statements)]
                        let _ = #path;
                    }

                    let __wire_action = {
                        let __wire_args: ::std::vec::Vec<::std::string::String> = vec![
                            #( ::axum_wire::serde_json::to_string(&(#args)).unwrap_or_else(|_| String::from("null")) ),*
                        ];
                        if __wire_args.is_empty() {
                            #method_name.to_string()
                        } else {
                            ::std::format!("{}({})", #method_name, __wire_args.join(", "))
                        }
                    };

                    let __wire_action_attr = __wire_action
                        .replace('&', "&amp;")
                        .replace('"', "&quot;")
                        .replace('<', "&lt;")
                        .replace('>', "&gt;");

                    __html.push_str(&::std::format!(" {}=\"{}\"", #key, __wire_action_attr));
                });
            } else {
                parts.push(quote! {
                    {
                        #[allow(clippy::no_effect, path_statements)]
                        let _ = #path;
                    }
                    __html.push_str(&::std::format!(" {}=\"{}\"", #key, #method_name));
                });
            }
            return Ok(());
        }

        parts.push(quote! {
            __html.push_str(&::std::format!(" {}=\"{}\"", #key, #value));
        });
        Ok(())
    } else {
        // wire:click="increment" or "filter_by('asc')"
        // Keep emitted HTML unchanged, but if this looks like an action call,
        // add a compile-time method reference for rust-analyzer navigation.
        if let syn::Expr::Lit(expr_lit) = value {
            if let syn::Lit::Str(lit) = &expr_lit.lit {
                if let Some(action_name) = extract_action_name_from_call_literal(&lit.value()) {
                    let action_ident = Ident::new(&action_name, lit.span());
                    parts.push(quote! {
                        {
                            #[allow(clippy::no_effect, path_statements)]
                            let _ = Self::#action_ident;
                        }
                        __html.push_str(&::std::format!(" {}=\"{}\"", #key, #value));
                    });
                    return Ok(());
                }
            }
        }

        parts.push(quote! {
            __html.push_str(&::std::format!(" {}=\"{}\"", #key, #value));
        });
        Ok(())
    }
}

fn extract_call_expr(expr: &syn::Expr) -> Option<&syn::ExprCall> {
    match expr {
        syn::Expr::Call(call) => Some(call),
        syn::Expr::Block(expr_block) => {
            if let Some(syn::Stmt::Expr(inner, None)) = expr_block.block.stmts.last() {
                extract_call_expr(inner)
            } else {
                None
            }
        }
        _ => None,
    }
}

fn extract_action_name_from_call_literal(value: &str) -> Option<String> {
    let trimmed = value.trim_start();
    let mut chars = trimmed.char_indices();

    let (_, first) = chars.next()?;
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return None;
    }

    let mut end = first.len_utf8();
    for (idx, ch) in chars {
        if ch == '_' || ch.is_ascii_alphanumeric() {
            end = idx + ch.len_utf8();
            continue;
        }

        let rest = &trimmed[idx..];
        return if rest.trim_start().starts_with('(') {
            Some(trimmed[..end].to_string())
        } else {
            None
        };
    }

    None
}

/// Emit attribute HTML and inline type hint for IDE coloring.
fn attr_to_tokens_with_hint(
    tag_name: &str,
    attr: &NodeAttribute,
    parts: &mut Vec<TokenStream>,
) -> syn::Result<()> {
    match attr {
        NodeAttribute::Attribute(kv) => {
            let key = node_name_to_string(&kv.key);
            let hint = attr_type_hint(tag_name, attr);

            if let Some(value) = kv.value() {
                if is_wire_directive(&key) {
                    wire_action_to_tokens(&key, value, parts)?;
                } else {
                    parts.push(quote! {
                        #hint
                        __html.push_str(&::std::format!(" {}=\"{}\"", #key, #value));
                    });
                }
            } else {
                // Boolean attribute (no value)
                parts.push(quote! {
                    #hint
                    __html.push(' ');
                    __html.push_str(#key);
                });
            }
        }
        NodeAttribute::Block(block) => {
            parts.push(quote! {
                __html.push_str(&::std::format!(" {}", #block));
            });
        }
    }
    Ok(())
}

fn node_name_to_string(name: &NodeName) -> String {
    match name {
        NodeName::Path(path) => path
            .path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect::<Vec<_>>()
            .join("::"),
        NodeName::Punctuated(punct) => punct
            .pairs()
            .map(|p| {
                let value = p.value().to_string();
                let punct = p.punct().map(|p| p.to_string()).unwrap_or_default();
                format!("{}{}", value, punct)
            })
            .collect::<String>(),
        NodeName::Block(_) => String::from("block"),
    }
}

fn is_void_element(tag: &str) -> bool {
    matches!(
        tag,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}