telex-macro 0.2.0

Procedural macros for telex-tui
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
//! Procedural macros for Telex.
//!
//! - `state!` — creates order-independent state (no hook ordering rules)
//! - `effect!` — creates order-independent effects with dependencies
//! - `effect_once!` — creates order-independent effects that run once
//! - `with!` — clones state handles into closures
//! - `view!` — JSX-like syntax for building UI trees

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use std::sync::atomic::{AtomicU64, Ordering};
use syn::{
    braced,
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
    Expr, Ident, LitStr, Result, Token,
};

/// The view! macro for building UI trees with JSX-like syntax.
#[proc_macro]
pub fn view(input: TokenStream) -> TokenStream {
    let node = parse_macro_input!(input as ViewNode);
    let expanded = node.to_tokens();
    TokenStream::from(expanded)
}

/// Input for the with! macro: `ident1, ident2 => expr`
struct WithInput {
    idents: Vec<Ident>,
    expr: Expr,
}

impl Parse for WithInput {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse comma-separated identifiers
        let idents: Punctuated<Ident, Token![,]> = Punctuated::parse_separated_nonempty(input)?;
        let idents: Vec<Ident> = idents.into_iter().collect();

        // Parse the => separator
        input.parse::<Token![=>]>()?;

        // Parse the expression (typically a closure)
        let expr: Expr = input.parse()?;

        Ok(WithInput { idents, expr })
    }
}

impl WithInput {
    fn to_tokens(&self) -> TokenStream2 {
        let clone_statements: Vec<TokenStream2> = self
            .idents
            .iter()
            .map(|ident| quote! { let #ident = #ident.clone(); })
            .collect();

        let expr = &self.expr;

        quote! {
            {
                #(#clone_statements)*
                #expr
            }
        }
    }
}

/// Global counter for generating unique type names.
static STATE_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Input for the state! macro: `cx, || init_expr`
struct StateInput {
    scope: Expr,
    init: Expr,
}

impl Parse for StateInput {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse the scope expression (usually just `cx`)
        let scope: Expr = input.parse()?;

        // Parse the comma separator
        input.parse::<Token![,]>()?;

        // Parse the initializer expression (usually a closure)
        let init: Expr = input.parse()?;

        Ok(StateInput { scope, init })
    }
}

impl StateInput {
    fn to_tokens(&self) -> TokenStream2 {
        let scope = &self.scope;
        let init = &self.init;

        // Generate a unique type name using an atomic counter.
        // This ensures each macro invocation gets a distinct type.
        let counter = STATE_COUNTER.fetch_add(1, Ordering::SeqCst);
        let key_type = format_ident!("__State_{}", counter);

        quote! {
            {
                struct #key_type;
                #scope.use_state_keyed::<#key_type, _>(#init)
            }
        }
    }
}

/// The state! macro for creating order-independent state.
///
/// This is the recommended way to create state in Telex. Unlike traditional
/// hooks, state created with this macro can be used conditionally or in any
/// order without causing panics.
///
/// Each macro invocation creates a unique anonymous type as the key,
/// ensuring each call site gets its own independent state.
///
/// # Examples
///
/// Basic usage:
/// ```ignore
/// let count = state!(cx, || 0);
/// ```
///
/// Safe in conditionals:
/// ```ignore
/// if show_counter {
///     let count = state!(cx, || 0);  // This is safe!
/// }
/// ```
///
/// Multiple independent states:
/// ```ignore
/// let name = state!(cx, || String::new());
/// let count = state!(cx, || 0);
/// let visible = state!(cx, || true);
/// ```
#[proc_macro]
pub fn state(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as StateInput);
    let expanded = input.to_tokens();
    TokenStream::from(expanded)
}

/// Global counter for generating unique effect type names.
static EFFECT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Input for the effect! macro: `cx, deps, |&d| effect_body`
struct EffectInput {
    scope: Expr,
    deps: Expr,
    effect_fn: Expr,
}

impl Parse for EffectInput {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse the scope expression (usually just `cx`)
        let scope: Expr = input.parse()?;
        input.parse::<Token![,]>()?;

        // Parse the dependencies expression
        let deps: Expr = input.parse()?;
        input.parse::<Token![,]>()?;

        // Parse the effect closure
        let effect_fn: Expr = input.parse()?;

        Ok(EffectInput {
            scope,
            deps,
            effect_fn,
        })
    }
}

impl EffectInput {
    fn to_tokens(&self) -> TokenStream2 {
        let scope = &self.scope;
        let deps = &self.deps;
        let effect_fn = &self.effect_fn;

        let counter = EFFECT_COUNTER.fetch_add(1, Ordering::SeqCst);
        let key_type = format_ident!("__Effect_{}", counter);

        quote! {
            {
                struct #key_type;
                #scope.use_effect_keyed::<#key_type, _, _, _>(#deps, #effect_fn)
            }
        }
    }
}

/// The effect! macro for creating order-independent effects with dependencies.
///
/// This is the recommended way to create effects in Telex. Unlike traditional
/// hooks, effects created with this macro can be used conditionally or in any
/// order without causing issues.
///
/// Each macro invocation creates a unique anonymous type as the key,
/// ensuring each call site gets its own independent effect.
///
/// # Examples
///
/// Basic usage - runs when count changes:
/// ```ignore
/// effect!(cx, count.get(), |&c| {
///     println!("count changed to {}", c);
///     || {}  // cleanup function
/// });
/// ```
///
/// Safe in conditionals:
/// ```ignore
/// if show_logger {
///     effect!(cx, value.get(), |&v| {
///         println!("value: {}", v);
///         || {}
///     });
/// }
/// ```
///
/// Multiple dependencies via tuple:
/// ```ignore
/// effect!(cx, (a.get(), b.get()), |&(a, b)| {
///     println!("a={}, b={}", a, b);
///     || {}
/// });
/// ```
#[proc_macro]
pub fn effect(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as EffectInput);
    let expanded = input.to_tokens();
    TokenStream::from(expanded)
}

/// Input for the effect_once! macro: `cx, || effect_body`
struct EffectOnceInput {
    scope: Expr,
    effect_fn: Expr,
}

impl Parse for EffectOnceInput {
    fn parse(input: ParseStream) -> Result<Self> {
        // Parse the scope expression (usually just `cx`)
        let scope: Expr = input.parse()?;
        input.parse::<Token![,]>()?;

        // Parse the effect closure
        let effect_fn: Expr = input.parse()?;

        Ok(EffectOnceInput { scope, effect_fn })
    }
}

impl EffectOnceInput {
    fn to_tokens(&self) -> TokenStream2 {
        let scope = &self.scope;
        let effect_fn = &self.effect_fn;

        let counter = EFFECT_COUNTER.fetch_add(1, Ordering::SeqCst);
        let key_type = format_ident!("__Effect_{}", counter);

        quote! {
            {
                struct #key_type;
                #scope.use_effect_once_keyed::<#key_type, _, _>(#effect_fn)
            }
        }
    }
}

/// The effect_once! macro for creating order-independent effects that run once.
///
/// This is the recommended way to run one-time initialization effects in Telex.
/// Unlike traditional hooks, effects created with this macro can be used
/// conditionally or in any order.
///
/// Each macro invocation creates a unique anonymous type as the key,
/// ensuring each call site gets its own independent effect.
///
/// # Examples
///
/// Basic usage - runs once on first render:
/// ```ignore
/// effect_once!(cx, || {
///     println!("App initialized");
///     || {
///         println!("App cleanup");
///     }
/// });
/// ```
///
/// Safe in conditionals:
/// ```ignore
/// if feature_enabled {
///     effect_once!(cx, || {
///         setup_feature();
///         || cleanup_feature()
///     });
/// }
/// ```
#[proc_macro]
pub fn effect_once(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as EffectOnceInput);
    let expanded = input.to_tokens();
    TokenStream::from(expanded)
}

/// The with! macro for cloning state handles into closures.
///
/// State<T> is a handle (like a smart pointer), not the data itself.
/// When you need to use state in a closure, you must clone the handle
/// so the closure owns its own copy. This macro makes that pattern concise.
///
/// # Examples
///
/// Single state:
/// ```ignore
/// let count = state!(cx, || 0);
/// let increment = with!(count => move || count.update(|n| *n += 1));
/// ```
///
/// Multiple states:
/// ```ignore
/// let count = state!(cx, || 0);
/// let name = state!(cx, || String::new());
///
/// let handler = with!(count, name => move || {
///     count.update(|n| *n += 1);
///     name.set("updated".to_string());
/// });
/// ```
///
/// The above expands to:
/// ```ignore
/// let handler = {
///     let count = count.clone();
///     let name = name.clone();
///     move || {
///         count.update(|n| *n += 1);
///         name.set("updated".to_string());
///     }
/// };
/// ```
#[proc_macro]
pub fn with(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as WithInput);
    let expanded = input.to_tokens();
    TokenStream::from(expanded)
}

/// A node in the view tree (during parsing).
enum ViewNode {
    /// An element like <Text>...</Text>
    Element(ElementNode),
    /// A string literal "Hello"
    Text(String),
    /// An expression in braces {expr}
    Expr(Expr),
}

/// A prop like on_press={...} or selected={...}
struct Prop {
    name: Ident,
    value: Expr,
}

struct ElementNode {
    tag: String,
    props: Vec<Prop>,
    children: Vec<ViewNode>,
}

impl Parse for ViewNode {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(Token![<]) {
            // Parse element: <Tag prop={val}>...</Tag>
            input.parse::<Token![<]>()?;
            let tag: Ident = input.parse()?;

            // Parse props
            let mut props = Vec::new();
            while !input.peek(Token![>]) && !input.peek(Token![/]) {
                let name: Ident = input.parse()?;
                input.parse::<Token![=]>()?;
                let content;
                braced!(content in input);
                let value: Expr = content.parse()?;
                props.push(Prop { name, value });
            }

            // Check for self-closing tag: <Tag />
            if input.peek(Token![/]) {
                input.parse::<Token![/]>()?;
                input.parse::<Token![>]>()?;
                return Ok(ViewNode::Element(ElementNode {
                    tag: tag.to_string(),
                    props,
                    children: Vec::new(),
                }));
            }

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

            let mut children = Vec::new();

            // Parse children until we hit the closing tag
            while !(input.peek(Token![<]) && input.peek2(Token![/])) {
                if input.is_empty() {
                    return Err(syn::Error::new(
                        tag.span(),
                        format!("Unclosed tag: <{}>", tag),
                    ));
                }
                children.push(input.parse()?);
            }

            // Parse closing tag: </Tag>
            input.parse::<Token![<]>()?;
            input.parse::<Token![/]>()?;
            let close_tag: Ident = input.parse()?;
            input.parse::<Token![>]>()?;

            if tag != close_tag {
                return Err(syn::Error::new(
                    close_tag.span(),
                    format!(
                        "Mismatched tags: expected </{}>, found </{}>",
                        tag, close_tag
                    ),
                ));
            }

            Ok(ViewNode::Element(ElementNode {
                tag: tag.to_string(),
                props,
                children,
            }))
        } else if input.peek(LitStr) {
            // Parse string literal: "Hello"
            let lit: LitStr = input.parse()?;
            Ok(ViewNode::Text(lit.value()))
        } else if input.peek(syn::token::Brace) {
            // Parse expression: {expr}
            let content;
            braced!(content in input);
            let expr: Expr = content.parse()?;
            Ok(ViewNode::Expr(expr))
        } else {
            Err(input.error("Expected <Element>, \"string literal\", or {expression}"))
        }
    }
}

impl ViewNode {
    fn to_tokens(&self) -> TokenStream2 {
        match self {
            ViewNode::Text(s) => {
                quote! { telex::View::text(#s) }
            }
            ViewNode::Expr(expr) => {
                // Convert expression to string for text
                quote! { telex::View::text(format!("{}", #expr)) }
            }
            ViewNode::Element(elem) => elem.to_tokens(),
        }
    }
}

impl ElementNode {
    fn to_tokens(&self) -> TokenStream2 {
        match self.tag.as_str() {
            "Text" => {
                // <Text>"content"</Text> or <Text>{expr}</Text>
                if let Some(child) = self.children.first() {
                    match child {
                        ViewNode::Text(content) => quote! { telex::View::text(#content) },
                        ViewNode::Expr(expr) => quote! { telex::View::text(format!("{}", #expr)) },
                        _ => quote! { telex::View::text("") },
                    }
                } else {
                    quote! { telex::View::text("") }
                }
            }
            "VStack" => {
                let mut builder_calls = Vec::new();

                // Handle props (spacing)
                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle children
                for child in &self.children {
                    let tokens = child.to_tokens();
                    builder_calls.push(quote! { .child(#tokens) });
                }

                quote! { telex::View::vstack()#(#builder_calls)*.build() }
            }
            "HStack" => {
                let mut builder_calls = Vec::new();

                // Handle props (spacing)
                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle children
                for child in &self.children {
                    let tokens = child.to_tokens();
                    builder_calls.push(quote! { .child(#tokens) });
                }

                quote! { telex::View::hstack()#(#builder_calls)*.build() }
            }
            "Box" => {
                let mut builder_calls = Vec::new();

                // Handle props (border, padding, flex)
                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle single child
                if let Some(child) = self.children.first() {
                    let tokens = child.to_tokens();
                    builder_calls.push(quote! { .child(#tokens) });
                }

                quote! { telex::View::boxed()#(#builder_calls)*.build() }
            }
            "Spacer" => {
                // Spacer with optional flex prop
                if let Some(prop) = self.props.iter().find(|p| p.name == "flex") {
                    let value = &prop.value;
                    quote! { telex::View::spacer_flex(#value) }
                } else {
                    quote! { telex::View::spacer() }
                }
            }
            "Button" => {
                // Parse props and children for Button
                let mut builder_calls = Vec::new();

                // Handle props
                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle label from children
                if let Some(child) = self.children.first() {
                    match child {
                        ViewNode::Text(label) => {
                            builder_calls.push(quote! { .label(#label) });
                        }
                        ViewNode::Expr(expr) => {
                            builder_calls.push(quote! { .label(format!("{}", #expr)) });
                        }
                        _ => {}
                    }
                }

                quote! { telex::View::button()#(#builder_calls)*.build() }
            }
            "List" => {
                // Parse props for List: items, selected, on_select
                let mut builder_calls = Vec::new();

                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                quote! { telex::View::list()#(#builder_calls)*.build() }
            }
            "TextInput" => {
                // Parse props for TextInput: value, placeholder, on_change
                let mut builder_calls = Vec::new();

                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                quote! { telex::View::text_input()#(#builder_calls)*.build() }
            }
            "Checkbox" => {
                // Parse props and children for Checkbox: checked, on_toggle
                let mut builder_calls = Vec::new();

                // Handle props
                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle label from children
                if let Some(child) = self.children.first() {
                    match child {
                        ViewNode::Text(label) => {
                            builder_calls.push(quote! { .label(#label) });
                        }
                        ViewNode::Expr(expr) => {
                            builder_calls.push(quote! { .label(format!("{}", #expr)) });
                        }
                        _ => {}
                    }
                }

                quote! { telex::View::checkbox()#(#builder_calls)*.build() }
            }
            "TextArea" => {
                // Parse props for TextArea: value, placeholder, rows, cursor_line, cursor_col, on_change
                let mut builder_calls = Vec::new();

                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                quote! { telex::View::text_area()#(#builder_calls)*.build() }
            }
            "Modal" => {
                // Parse props for Modal: visible, title, width, height, on_dismiss
                let mut builder_calls = Vec::new();

                for prop in &self.props {
                    let name = &prop.name;
                    let value = &prop.value;
                    builder_calls.push(quote! { .#name(#value) });
                }

                // Handle single child
                if let Some(child) = self.children.first() {
                    let tokens = child.to_tokens();
                    builder_calls.push(quote! { .child(#tokens) });
                }

                quote! { telex::View::modal()#(#builder_calls)*.build() }
            }
            "StyledText" => {
                // Parse props for styled text: bold, italic, underline, dim, color, bg
                let mut content = quote! { "" };
                let mut bold_val = quote! { false };
                let mut italic_val = quote! { false };
                let mut underline_val = quote! { false };
                let mut dim_val = quote! { false };
                let mut color_call = quote! {};
                let mut bg_call = quote! {};

                // Handle props
                for prop in &self.props {
                    let name_str = prop.name.to_string();
                    let value = &prop.value;

                    match name_str.as_str() {
                        "bold" => bold_val = quote! { #value },
                        "italic" => italic_val = quote! { #value },
                        "underline" => underline_val = quote! { #value },
                        "dim" => dim_val = quote! { #value },
                        "color" => color_call = quote! { .color(#value) },
                        "bg" => bg_call = quote! { .bg(#value) },
                        _ => {}
                    }
                }

                // Handle text content from children
                if let Some(child) = self.children.first() {
                    match child {
                        ViewNode::Text(text) => {
                            content = quote! { #text };
                        }
                        ViewNode::Expr(expr) => {
                            content = quote! { format!("{}", #expr) };
                        }
                        _ => {}
                    }
                }

                // Generate conditional builder chain
                quote! {
                    {
                        let __builder = telex::View::styled_text(#content);
                        let __builder = if #bold_val { __builder.bold() } else { __builder };
                        let __builder = if #italic_val { __builder.italic() } else { __builder };
                        let __builder = if #underline_val { __builder.underline() } else { __builder };
                        let __builder = if #dim_val { __builder.dim() } else { __builder };
                        __builder #color_call #bg_call .build()
                    }
                }
            }
            unknown => {
                // Provide helpful error with suggestions
                let known_elements = [
                    "Text",
                    "StyledText",
                    "VStack",
                    "HStack",
                    "Box",
                    "Spacer",
                    "Button",
                    "List",
                    "TextInput",
                    "TextArea",
                    "Checkbox",
                    "Modal",
                ];

                // Find similar element names (simple edit distance check)
                let suggestion = known_elements
                    .iter()
                    .find(|&e| {
                        let e_lower = e.to_lowercase();
                        let u_lower = unknown.to_lowercase();
                        e_lower.starts_with(&u_lower[..1.min(u_lower.len())])
                            || u_lower.starts_with(&e_lower[..1.min(e_lower.len())])
                            || e_lower.contains(&u_lower)
                            || u_lower.contains(&e_lower)
                    });

                let msg = if let Some(suggested) = suggestion {
                    format!(
                        "Unknown element: <{}>. Did you mean <{}>?\n\nAvailable elements: {}",
                        unknown,
                        suggested,
                        known_elements.join(", ")
                    )
                } else {
                    format!(
                        "Unknown element: <{}>.\n\nAvailable elements: {}",
                        unknown,
                        known_elements.join(", ")
                    )
                };
                quote! { compile_error!(#msg) }
            }
        }
    }
}