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
//! Proc macros for `axum-wire`.
//!
//! This crate provides:
//! - `#[derive(Component)]`
//! - `#[wire_actions]`
//! - `#[on(...)]`
//! - `html!`
//!
//! Most users should depend on `axum-wire` directly and import the macros from
//! there rather than using this crate on its own.

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, ImplItem, ItemImpl};

mod rsx;

// ---------------------------------------------------------------------------
// #[derive(Component)]
// ---------------------------------------------------------------------------

#[proc_macro_derive(Component, attributes(component, url, locked, layout, on, __wire_on))]
pub fn derive_component(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let name_str = name.to_string();
    let wire_name = pascal_to_kebab(&name_str);

    // Parse #[url] attributes on struct fields
    let url_fields = parse_url_fields(&input);
    // Parse #[locked] attributes on struct fields
    let locked_fields = parse_locked_fields(&input);
    // Parse #[layout("name")] attribute on the struct
    let layout_name = parse_layout_attr(&input);
    // Parse #[on("event")] attributes on the component
    let component_event_listeners = parse_component_event_listeners(&input);

    let url_fields_count = url_fields.len();
    let url_fields_tokens = url_fields.iter().map(|uf| {
        let field_name = &uf.field_name;
        let query_name = &uf.query_name;
        let history = uf.history;
        let keep = uf.keep;
        quote! {
            ::axum_wire::UrlFieldMeta {
                field_name: #field_name,
                query_name: #query_name,
                history: #history,
                keep: #keep,
            }
        }
    });

    let locked_fields_count = locked_fields.len();
    let locked_fields_tokens = locked_fields.iter().map(|name| {
        quote! { #name }
    });

    let layout_name_impl = match &layout_name {
        Some(name) => quote! {
            fn layout_name() -> Option<&'static str> {
                Some(#name)
            }
        },
        None => quote! {},
    };

    let layout_name_const = match &layout_name {
        Some(name) => quote! { Some(#name) },
        None => quote! { None },
    };

    let component_event_listeners_count = component_event_listeners.len();
    let component_event_listener_tokens = component_event_listeners.iter().map(|event| {
        quote! {
            ::axum_wire::EventListenerMeta {
                event: #event,
                action: "$refresh",
            }
        }
    });

    let expanded = quote! {
        impl #name {
            /// Static array of `#[url]` field metadata, generated by `#[derive(Component)]`.
            const __WIRE_URL_FIELDS: [::axum_wire::UrlFieldMeta; #url_fields_count] = [#(#url_fields_tokens),*];
            /// Static array of `#[locked]` field names, generated by `#[derive(Component)]`.
            const __WIRE_LOCKED_FIELDS: [&'static str; #locked_fields_count] = [#(#locked_fields_tokens),*];
            /// Layout name from `#[layout("name")]`, generated by `#[derive(Component)]`.
            const __WIRE_LAYOUT: Option<&'static str> = #layout_name_const;
            /// Component-level listeners from `#[on("event")]`, generated by `#[derive(Component)]`.
            const __WIRE_COMPONENT_EVENT_LISTENERS: [::axum_wire::EventListenerMeta; #component_event_listeners_count] = [#(#component_event_listener_tokens),*];
        }

        impl ::axum_wire::ComponentMeta for #name {
            fn component_name() -> &'static str {
                #wire_name
            }

            fn url_fields() -> &'static [::axum_wire::UrlFieldMeta] {
                &#name::__WIRE_URL_FIELDS
            }

            fn locked_fields() -> &'static [&'static str] {
                &#name::__WIRE_LOCKED_FIELDS
            }

            fn event_listeners() -> &'static [::axum_wire::EventListenerMeta] {
                &#name::__WIRE_COMPONENT_EVENT_LISTENERS
            }

            #layout_name_impl
        }
    };

    TokenStream::from(expanded)
}

struct UrlFieldInfo {
    field_name: String,
    query_name: String,
    history: bool,
    keep: bool,
}

fn parse_url_fields(input: &DeriveInput) -> Vec<UrlFieldInfo> {
    let mut url_fields = Vec::new();

    let fields = match &input.data {
        syn::Data::Struct(data) => match &data.fields {
            syn::Fields::Named(named) => &named.named,
            _ => return url_fields,
        },
        _ => return url_fields,
    };

    for field in fields {
        for attr in &field.attrs {
            if !attr.path().is_ident("url") {
                continue;
            }

            let field_name = field
                .ident
                .as_ref()
                .expect("#[url] requires named fields")
                .to_string();

            let mut query_name = field_name.clone();
            let mut history = false;
            let mut keep = false;

            // Parse #[url] or #[url(as = "q", history, keep)]
            if let syn::Meta::List(_) = &attr.meta {
                let _ = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("as") {
                        let value = meta.value()?;
                        let lit: syn::LitStr = value.parse()?;
                        query_name = lit.value();
                    } else if meta.path.is_ident("history") {
                        history = true;
                    } else if meta.path.is_ident("keep") {
                        keep = true;
                    }
                    Ok(())
                });
            }

            url_fields.push(UrlFieldInfo {
                field_name,
                query_name,
                history,
                keep,
            });
        }
    }

    url_fields
}

fn parse_locked_fields(input: &DeriveInput) -> Vec<String> {
    let mut locked_fields = Vec::new();

    let fields = match &input.data {
        syn::Data::Struct(data) => match &data.fields {
            syn::Fields::Named(named) => &named.named,
            _ => return locked_fields,
        },
        _ => return locked_fields,
    };

    for field in fields {
        let has_locked = field.attrs.iter().any(|a| a.path().is_ident("locked"));
        if has_locked {
            let field_name = field
                .ident
                .as_ref()
                .expect("#[locked] requires named fields")
                .to_string();
            locked_fields.push(field_name);
        }
    }

    locked_fields
}

fn parse_component_event_listeners(input: &DeriveInput) -> Vec<String> {
    let mut events = Vec::new();

    for attr in &input.attrs {
        if !attr.path().is_ident("on") && !attr.path().is_ident("__wire_on") {
            continue;
        }

        let event_name = attr
            .parse_args::<syn::LitStr>()
            .map(|lit| lit.value())
            .ok()
            .or_else(|| {
                attr.parse_args::<proc_macro2::TokenStream>()
                    .ok()
                    .map(|ts| ts.to_string().replace(' ', ""))
            });

        if let Some(event) = event_name {
            events.push(event);
        }
    }

    events
}

/// Parse `#[layout("name")]` attribute on the struct.
fn parse_layout_attr(input: &DeriveInput) -> Option<String> {
    for attr in &input.attrs {
        if !attr.path().is_ident("layout") {
            continue;
        }
        // #[layout("name")] — parse the string literal
        if let Ok(lit) = attr.parse_args::<syn::LitStr>() {
            return Some(lit.value());
        }
    }
    None
}

pub(crate) fn pascal_to_kebab(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() {
            if i > 0 {
                result.push('-');
            }
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

// ---------------------------------------------------------------------------
// #[wire_actions]
// ---------------------------------------------------------------------------

#[proc_macro_attribute]
pub fn wire_actions(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemImpl);
    let self_ty = &input.self_ty;

    let type_name = quote!(#self_ty).to_string();
    let wire_name = pascal_to_kebab(&type_name);

    let mut action_names: Vec<String> = Vec::new();
    let mut action_idents: Vec<proc_macro2::Ident> = Vec::new();
    let mut action_renderless: Vec<bool> = Vec::new();
    let mut action_is_async: Vec<bool> = Vec::new();
    let mut action_payload_tys: Vec<Option<syn::Type>> = Vec::new();
    let mut action_payload_from_detail: Vec<bool> = Vec::new();
    let mut event_listeners: Vec<(String, String)> = Vec::new();
    let mut has_render = false;
    let mut has_mount = false;
    let mut render_is_async = false;
    let mut mount_is_async = false;
    let mut mount_has_ctx = false;

    for item in &input.items {
        if let ImplItem::Fn(method) = item {
            let sig = &method.sig;
            let method_name = sig.ident.to_string();

            match method_name.as_str() {
                "render" => {
                    has_render = true;
                    render_is_async = sig.asyncness.is_some();
                }
                "mount" => {
                    has_mount = true;
                    mount_is_async = sig.asyncness.is_some();
                    // Check if mount takes a WireContext parameter
                    // mount() or mount(ctx: WireContext)
                    mount_has_ctx = sig.inputs.iter().any(|arg| {
                        if let syn::FnArg::Typed(pat_type) = arg {
                            let ty_str = quote!(#pat_type).to_string();
                            ty_str.contains("WireContext")
                        } else {
                            false
                        }
                    });
                }
                _ => {
                    if let Some(syn::FnArg::Receiver(receiver)) = sig.inputs.first() {
                        if receiver.mutability.is_some() {
                            let is_renderless =
                                method.attrs.iter().any(|a| a.path().is_ident("renderless"));
                            let is_async = sig.asyncness.is_some();
                            let mut is_on_listener = false;
                            action_names.push(method_name);
                            action_idents.push(sig.ident.clone());
                            action_renderless.push(is_renderless);
                            action_is_async.push(is_async);

                            for attr in &method.attrs {
                                if !attr.path().is_ident("on") {
                                    continue;
                                }

                                let event_name = attr
                                    .parse_args::<syn::LitStr>()
                                    .map(|lit| lit.value())
                                    .ok()
                                    .or_else(|| {
                                        attr.parse_args::<proc_macro2::TokenStream>()
                                            .ok()
                                            .map(|ts| ts.to_string().replace(' ', ""))
                                    });

                                if let Some(event) = event_name {
                                    is_on_listener = true;
                                    event_listeners.push((event, sig.ident.to_string()));
                                }
                            }

                            let payload_ty = sig.inputs.iter().nth(1).and_then(|arg| match arg {
                                syn::FnArg::Typed(pat_type) => Some((*pat_type.ty).clone()),
                                _ => None,
                            });

                            action_payload_tys.push(payload_ty);
                            action_payload_from_detail.push(is_on_listener);
                        }
                    }
                }
            }
        }
    }

    if !has_render {
        return syn::Error::new_spanned(
            &input.self_ty,
            "#[wire_actions] requires a `fn render(&self) -> String` method",
        )
        .to_compile_error()
        .into();
    }

    // Check if any actions are async — if so, call_action must be async
    let any_action_async = action_is_async.iter().any(|a| *a);

    // Generate mount() if not provided
    let mount_impl = if has_mount {
        quote! {}
    } else {
        quote! {
            fn mount() -> Self {
                Self::default()
            }
        }
    };

    // Generate dispatch arms for call_action
    let dispatch_arms: Vec<_> = action_names
        .iter()
        .zip(action_idents.iter())
        .zip(action_renderless.iter())
        .zip(action_is_async.iter())
        .zip(action_payload_tys.iter())
        .zip(action_payload_from_detail.iter())
        .map(|(((((name, ident), renderless), is_async), payload_ty), payload_from_detail)| {
            let skip_render = if *renderless {
                quote! { ::axum_wire::set_skip_render(); }
            } else {
                quote! {}
            };

            let payload_expr = if *payload_from_detail {
                quote! {
                    _payload
                        .get("detail")
                        .cloned()
                        .unwrap_or(::axum_wire::serde_json::Value::Null)
                }
            } else {
                quote! {
                    _payload
                        .get("args")
                        .and_then(|args| args.as_array())
                        .and_then(|args| args.first().cloned())
                        .unwrap_or_else(|| _payload.clone())
                }
            };

            let invoke = if let Some(ty) = payload_ty {
                if *is_async {
                    quote! {
                        let __wire_payload: #ty = ::axum_wire::serde_json::from_value(#payload_expr)
                            .map_err(|e| ::axum_wire::WireError::Deserialization(e.to_string()))?;
                        self.#ident(__wire_payload).await;
                    }
                } else {
                    quote! {
                        let __wire_payload: #ty = ::axum_wire::serde_json::from_value(#payload_expr)
                            .map_err(|e| ::axum_wire::WireError::Deserialization(e.to_string()))?;
                        self.#ident(__wire_payload);
                    }
                }
            } else if *is_async {
                quote! {
                    self.#ident().await;
                }
            } else {
                quote! {
                    ::axum_wire::subsecond::call(|| self.#ident());
                }
            };

            quote! {
                #name => {
                    #skip_render
                    #invoke
                }
            }
        })
        .collect();

    // render call: .await if async, direct call if sync
    // subsecond::call wraps sync calls for hot-patching (no-op in release).
    let render_call = if render_is_async {
        quote! { component.render().await }
    } else {
        quote! { ::axum_wire::subsecond::call(|| component.render()) }
    };

    // mount call: .await if async, direct call if sync
    // If mount takes a WireContext param, pass __wire_ctx
    let mount_call = match (mount_is_async, mount_has_ctx) {
        (true, true) => quote! { #self_ty::mount(__wire_ctx.clone()).await },
        (true, false) => quote! { #self_ty::mount().await },
        (false, true) => {
            quote! { ::axum_wire::subsecond::call(|| #self_ty::mount(__wire_ctx.clone())) }
        }
        (false, false) => quote! { ::axum_wire::subsecond::call(|| #self_ty::mount()) },
    };

    // Strip #[renderless] attributes from the impl block so rustc doesn't error
    let mut cleaned_input = input.clone();
    for item in &mut cleaned_input.items {
        if let ImplItem::Fn(method) = item {
            method
                .attrs
                .retain(|a| !a.path().is_ident("renderless") && !a.path().is_ident("on"));
        }
    }

    let event_listeners_count = event_listeners.len();
    let event_listener_tokens = event_listeners.iter().map(|(event, action)| {
        quote! {
            ::axum_wire::EventListenerMeta {
                event: #event,
                action: #action,
            }
        }
    });

    // call_action: if any action is async, the whole method must be async
    // and return a BoxFuture. Otherwise, keep it sync.
    let call_action_method = if any_action_async {
        quote! {
            /// Dispatch an action by name. Returns collected side-effects.
            /// Async because one or more actions are async.
            pub async fn call_action(&mut self, action: &str, _payload: ::axum_wire::serde_json::Value) -> Result<::axum_wire::ActionEffects, ::axum_wire::WireError> {
                let __scope = ::axum_wire::ActionScope::begin();
                match action {
                    "$refresh" => {},
                    #(#dispatch_arms,)*
                    _ => {
                        drop(__scope);
                        return Err(::axum_wire::WireError::UnknownAction(action.to_string()));
                    },
                }
                Ok(__scope.finish())
            }
        }
    } else {
        quote! {
            /// Dispatch an action by name. Returns collected side-effects.
            pub fn call_action(&mut self, action: &str, _payload: ::axum_wire::serde_json::Value) -> Result<::axum_wire::ActionEffects, ::axum_wire::WireError> {
                let __scope = ::axum_wire::ActionScope::begin();
                match action {
                    "$refresh" => {},
                    #(#dispatch_arms,)*
                    _ => {
                        drop(__scope);
                        return Err(::axum_wire::WireError::UnknownAction(action.to_string()));
                    },
                }
                Ok(__scope.finish())
            }
        }
    };

    // In the update factory closure, call_action may or may not be async
    let call_action_invoke = if any_action_async {
        quote! { component.call_action(action, payload).await? }
    } else {
        quote! { component.call_action(action, payload)? }
    };

    let expanded = quote! {
        #cleaned_input

        impl #self_ty {
            #mount_impl

            #call_action_method

            /// Get the current `WireContext` (available in render and actions).
            pub fn ctx(&self) -> ::axum_wire::WireContext {
                ::axum_wire::get_wire_ctx()
            }

            /// Queue a JavaScript snippet to execute on the client after this action.
            /// `$wire` is available in the JS context.
            pub fn js(&self, code: &str) {
                ::axum_wire::push_js(code.to_string());
            }

            /// Dispatch a browser event from this component root.
            pub fn dispatch(&self, name: &str) {
                ::axum_wire::dispatch_event(name.to_string(), None);
            }

            /// Dispatch a browser event with a JSON detail payload.
            pub fn dispatch_with<T: ::serde::Serialize>(&self, name: &str, detail: T) {
                if let Ok(value) = ::axum_wire::serde_json::to_value(detail) {
                    ::axum_wire::dispatch_event(name.to_string(), Some(value));
                }
            }

            /// Dispatch a browser event to this component root only.
            pub fn dispatch_self(&self, name: &str) {
                ::axum_wire::dispatch_event_targeted(name.to_string(), None, Some(::std::string::String::from("self")));
            }

            /// Dispatch a browser event with payload to this component root only.
            pub fn dispatch_self_with<T: ::serde::Serialize>(&self, name: &str, detail: T) {
                if let Ok(value) = ::axum_wire::serde_json::to_value(detail) {
                    ::axum_wire::dispatch_event_targeted(name.to_string(), Some(value), Some(::std::string::String::from("self")));
                }
            }

            /// Dispatch a browser event to all mounted components with the given wire name.
            pub fn dispatch_to(&self, component: &str, name: &str) {
                ::axum_wire::dispatch_event_targeted(name.to_string(), None, Some(::std::format!("to:{component}")));
            }

            /// Dispatch a browser event with payload to all mounted components with the given wire name.
            pub fn dispatch_to_with<T: ::serde::Serialize>(&self, component: &str, name: &str, detail: T) {
                if let Ok(value) = ::axum_wire::serde_json::to_value(detail) {
                    ::axum_wire::dispatch_event_targeted(name.to_string(), Some(value), Some(::std::format!("to:{component}")));
                }
            }

            /// Skip re-rendering after this action. Only the updated snapshot is sent back.
            pub fn skip_render(&self) {
                ::axum_wire::set_skip_render();
            }

            /// Redirect the client to a URL (full page navigation). Implies skip_render.
            pub fn redirect(&self, url: &str) {
                ::axum_wire::set_redirect(url.to_string(), false);
            }

            /// Redirect using wire:navigate (SPA-style, no full reload). Implies skip_render.
            pub fn redirect_navigate(&self, url: &str) {
                ::axum_wire::set_redirect(url.to_string(), true);
            }

            /// Listener metadata generated from `#[on("event")]` action attributes.
            const __WIRE_EVENT_LISTENERS: [::axum_wire::EventListenerMeta; #event_listeners_count] = [#(#event_listener_tokens),*];
        }

        ::axum_wire::inventory::submit! {
            ::axum_wire::ComponentFactory::new(
                #wire_name,
                |snapshot, action, payload, __wire_ctx| {
                    Box::pin(::axum_wire::with_wire_ctx(__wire_ctx, async move {
                        let mut component: #self_ty = ::axum_wire::serde_json::from_value(snapshot)
                            .map_err(|e| ::axum_wire::WireError::Deserialization(e.to_string()))?;
                        let effects = #call_action_invoke;
                        let html = if effects.skip_render {
                            String::new()
                        } else {
                            #render_call
                        };
                        let new_snapshot = ::axum_wire::serde_json::to_value(&component)
                            .map_err(|e| ::axum_wire::WireError::Serialization(e.to_string()))?;
                        Ok(::axum_wire::WireResponse { html, snapshot: new_snapshot, effects })
                    }))
                },
                |__wire_ctx| {
                    Box::pin(::axum_wire::with_wire_ctx(__wire_ctx.clone(), async move {
                        let component = #mount_call;
                        let html = #render_call;
                        let new_snapshot = ::axum_wire::serde_json::to_value(&component)
                            .map_err(|e| ::axum_wire::WireError::Serialization(e.to_string()))?;
                        Ok(::axum_wire::WireResponse { html, snapshot: new_snapshot, effects: ::axum_wire::ActionEffects::default() })
                    }))
                },
                |props: ::axum_wire::serde_json::Value, __wire_ctx: ::axum_wire::WireContext| {
                    Box::pin(::axum_wire::with_wire_ctx(__wire_ctx.clone(), async move {
                        let component = #mount_call;
                        let mut base = ::axum_wire::serde_json::to_value(&component)
                            .map_err(|e| ::axum_wire::WireError::Serialization(e.to_string()))?;
                        if let (Some(base_obj), Some(props_obj)) = (base.as_object_mut(), props.as_object()) {
                            for (k, v) in props_obj {
                                base_obj.insert(k.clone(), v.clone());
                            }
                        }
                        let component: #self_ty = ::axum_wire::serde_json::from_value(base)
                            .map_err(|e| ::axum_wire::WireError::Deserialization(e.to_string()))?;
                        let html = #render_call;
                        let snapshot = ::axum_wire::serde_json::to_value(&component)
                            .map_err(|e| ::axum_wire::WireError::Serialization(e.to_string()))?;
                        Ok(::axum_wire::WireResponse { html, snapshot, effects: ::axum_wire::ActionEffects::default() })
                    }))
                },
                &#self_ty::__WIRE_URL_FIELDS,
                &#self_ty::__WIRE_EVENT_LISTENERS,
                &#self_ty::__WIRE_COMPONENT_EVENT_LISTENERS,
                &#self_ty::__WIRE_LOCKED_FIELDS,
                #self_ty::__WIRE_LAYOUT,
            )
        }
    };

    TokenStream::from(expanded)
}

#[proc_macro_attribute]
pub fn on(attr: TokenStream, item: TokenStream) -> TokenStream {
    let Ok(parsed) = syn::parse::<syn::Item>(item.clone()) else {
        return item;
    };

    match parsed {
        syn::Item::Struct(mut item_struct) => {
            let on_attr: proc_macro2::TokenStream = attr.into();
            item_struct
                .attrs
                .push(syn::parse_quote!(#[__wire_on(#on_attr)]));
            TokenStream::from(quote! { #item_struct })
        }
        _ => item,
    }
}

// ---------------------------------------------------------------------------
// html! macro
// ---------------------------------------------------------------------------

/// JSX-like HTML macro that produces a `String`.
///
/// Supports:
/// - Standard HTML elements: `<div class="foo">...</div>`
/// - Rust expressions: `<p>{self.count}</p>` or `<p>{some_var}</p>`
/// - `wire:click`, `wire:submit.prevent`, and other wire directives
/// - Sub-components via capitalized tags: `<Counter />` mounts a wire component inline
/// - Void elements: `<br />`, `<input />`
/// - Fragments: `<>{...}</>`
///
/// # Examples
///
/// ```ignore
/// html! {
///     <div class="container">
///         <h1>{"Hello"}</h1>
///         <p>{self.count}</p>
///         <button wire:click={Self::increment}>{"Click me"}</button>
///         <Counter />
///     </div>
/// }
/// ```
#[proc_macro]
pub fn html(input: TokenStream) -> TokenStream {
    match rsx::generate(input.into()) {
        Ok(tokens) => tokens.into(),
        Err(e) => e.to_compile_error().into(),
    }
}