summary refs log tree commit diff stats
path: root/rocie-macros/src/form/generate.rs
blob: 732bb58fe2b4b9751807ff42cf0b1d29fa7b5d42 (plain) (blame)
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
// rocie - An enterprise grocery management system - Web app
//
// Copyright (C) 2026 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Rocie.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{Ident, Path, Type, TypePath, parse_macro_input, punctuated::Punctuated};

use crate::form::{ParsedChild, ParsedInput};

pub fn form_impl(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ParsedInput);

    let node_refs = input.children.iter().map(node_ref);
    let signals = input.children.iter().map(signal);
    let reactive_signals = input.children.iter().map(reactive_signal);
    let auto_complete_signals = input.children.iter().map(auto_complete_signal);

    let type_verifications = input.children.iter().map(type_verification);

    let output_struct_definition = output_struct_definition(&input.children);
    let output_struct_construction = output_struct_construction(&input.children);

    let fetch_values = input.children.iter().map(fetch_value);

    let bounds = input.on_submit.inputs;
    let on_submit_block = input.on_submit.block;
    let on_submit_move = if input.on_submit.should_use_move {
        quote! {move}
    } else {
        quote! {}
    };

    let input_htmls = input.children.iter().map(input_html);

    let output = quote!({
        use crate::components::{
            input_placeholder::InputPlaceholder,
            select_placeholder::SelectPlaceholder,
            textarea_placeholder::TextareaPlaceholder,
            checkbox_placeholder::CheckboxPlaceholder,
        };

        use leptos::{
            view,
            prelude::{
                Get,
                NodeRef,
                ElementChild,
                ClassAttribute,
                OnAttribute,
                signal,
                Set,
                Show,
            },
            html::{Input, Select, Textarea},
            web_sys::SubmitEvent
        };

        use log::{info, error};


        #(
            #node_refs

            #signals
            #reactive_signals
            #auto_complete_signals

            #type_verifications
        )*

        let on_submit = move |ev: SubmitEvent| {
            #output_struct_definition

            // stop the page from reloading!
            ev.prevent_default();

            #(
                #fetch_values
            )*

            let real_on_submit = #on_submit_move |Inputs {#(#bounds),*}| #on_submit_block;
            real_on_submit(
                    #output_struct_construction
            )
        };


        view! {
            <form class="relative flex flex-col contents-start m-2 g-2" on:submit=on_submit>
                #(
                    #input_htmls
                )*

                <div class="sticky bottom-2 left-0 flex flex-row contents-start">
                    <div class="w-5/6" />
                    <input
                        type="submit"
                        value="Submit"
                        class="pr-2 pl-2 rounded-lg bg-green-300 m-2"
                    />
                </div>
            </form>
        }
    });

    // {
    //     match syn::parse_file(quote! {fn main() { #output }}.to_string().as_str()) {
    //         Ok(tree) => {
    //             let formatted = prettyplease::unparse(&tree);
    //             eprint!("{}", formatted);
    //         }
    //         Err(err) => {
    //             eprintln!("Error: {err}\n{output}");
    //         }
    //     };
    // }

    output.into()
}

fn node_ref_name(name: &Ident) -> Ident {
    format_ident!("{name}_node_ref")
}

fn node_ref(child: &ParsedChild) -> TokenStream2 {
    if let ParsedChild::Show { children, .. } = child {
        children.iter().map(node_ref).collect()
    } else {
        let (name, ty) = match child {
            ParsedChild::Input { name, .. } => (name, quote! {Input}),
            ParsedChild::Select { name, .. } => (name, quote! {Select}),
            ParsedChild::Textarea { name, .. } => (name, quote! {Textarea}),
            ParsedChild::Checkbox { name, .. } => (name, quote! {Input}),
            ParsedChild::Show { .. } => unreachable!("Filtered out before"),
        };

        let node_ref_name = node_ref_name(name);

        quote! {
            let #node_ref_name: NodeRef<#ty> = NodeRef::new();
        }
    }
}

fn signal_names(name: &Ident) -> (Ident, Ident) {
    (format_ident!("{name}_get"), format_ident!("{name}_set"))
}
fn signal(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input { name, .. } => {
            let (signal_name_get, signal_name_set) = signal_names(name);

            quote! {
                let (#signal_name_get, #signal_name_set) = signal(None);
            }
        }
        ParsedChild::Textarea { .. }
        | ParsedChild::Checkbox { .. }
        | ParsedChild::Select { .. } => quote! {},
        ParsedChild::Show { children, .. } => children.iter().map(signal).collect(),
    }
}

fn signal_auto_complete_names(name: &Ident) -> (Ident, Ident) {
    (
        format_ident!("{name}_auto_complete_get"),
        format_ident!("{name}_auto_complete_set"),
    )
}
fn auto_complete_signal(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input {
            name,
            reactive,
            auto_complete,
            ..
        } => {
            if let Some(auto_complete) = auto_complete {
                let (signal_auto_complete_get, _) = signal_auto_complete_names(name);

                let reactive = reactive
                    .as_ref()
                    .expect("Must be some, if auto_complete is some");

                quote! {
                    let #signal_auto_complete_get =
                        leptos::prelude::LocalResource::new(
                            move || #auto_complete(#reactive())
                        );
                }
            } else {
                quote! {}
            }
        }
        ParsedChild::Select { .. }
        | ParsedChild::Textarea { .. }
        | ParsedChild::Checkbox { .. } => quote! {},
        ParsedChild::Show { children, .. } => children.iter().map(auto_complete_signal).collect(),
    }
}

fn signal_reactive_base_names(name: &Ident) -> (Ident, Ident) {
    (
        format_ident!("{name}_reactive_base_get"),
        format_ident!("{name}_reactive_base_set"),
    )
}
fn reactive_signal(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input {
            name,
            reactive,
            rust_type,
            ..
        } => {
            if let Some(reactive) = reactive {
                let (signal_reactive_base_get, signal_reactive_base_set) =
                    signal_reactive_base_names(name);

                quote! {
                    let (#signal_reactive_base_get, #signal_reactive_base_set) = signal(None);
                    #reactive = move || {
                         {
                            let output: Option<String> = #signal_reactive_base_get.get();

                            if let Some(output) = output {
                                let fin: Result<#rust_type, leptos::error::Error> = output
                                            .parse()
                                            .map_err(Into::<leptos::error::Error>::into);

                                match fin {
                                    Ok(ok) => {
                                        Some(ok)
                                    },
                                    Err(err) => {
                                        // Reset the signal
                                        None
                                    }
                                }
                            } else {
                                None
                            }
                        }
                    };
                }
            } else {
                quote! {}
            }
        }
        ParsedChild::Select { .. }
        | ParsedChild::Textarea { .. }
        | ParsedChild::Checkbox { .. } => quote! {},
        ParsedChild::Show { children, .. } => children.iter().map(reactive_signal).collect(),
    }
}

fn type_verification(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input { .. } | ParsedChild::Textarea { .. } | ParsedChild::Checkbox { .. } => {
            quote! {}
        }
        ParsedChild::Select { name, options, .. } => {
            let name = format_ident!("_select_val_{name}");
            quote! {
                {
                    let #name:
                            leptos::prelude::LocalResource<
                                Result<
                                    // TODO: Use #rust_type instead of the second String <2025-10-21>
                                    Vec<(String, String)>,
                                    leptos::error::Error
                                >
                            > = #options;
                }
            }
        }
        ParsedChild::Show { when: _, children } => {
            let base = children
                .iter()
                .map(type_verification)
                .collect::<TokenStream2>();

            quote! {
                #base
            }
        }
    }
}

fn get_names(input: &ParsedChild) -> Vec<&Ident> {
    match input {
        ParsedChild::Input { name, .. }
        | ParsedChild::Textarea { name, .. }
        | ParsedChild::Checkbox { name, .. }
        | ParsedChild::Select { name, .. } => vec![name],
        ParsedChild::Show { children, .. } => children.iter().flat_map(get_names).collect(),
    }
}

fn output_struct_definition(children: &[ParsedChild]) -> TokenStream2 {
    macro_rules! mk_type {
        ($name:ident) => {{
            let segments = {
                let mut p = Punctuated::new();
                p.push(syn::PathSegment {
                    ident: format_ident!(stringify!($name)),
                    arguments: syn::PathArguments::None,
                });
                p
            };

            Type::Path(TypePath {
                qself: None,
                path: Path {
                    leading_colon: None,
                    segments,
                },
            })
        }};
    }

    let string: Type = mk_type!(String);
    let boolean: Type = mk_type!(bool);

    fn get_rust_types<'a>(
        input: &'a ParsedChild,
        string: &'a Type,
        bool: &'a Type,
    ) -> Vec<&'a Type> {
        match input {
            ParsedChild::Textarea { .. } => {
                vec![string]
            }
            ParsedChild::Checkbox { .. } => {
                vec![bool]
            }
            ParsedChild::Input { rust_type, .. } | ParsedChild::Select { rust_type, .. } => {
                vec![rust_type]
            }
            ParsedChild::Show { children, .. } => children
                .iter()
                .flat_map(|i| get_rust_types(i, string, bool))
                .collect(),
        }
    }

    let names = children.iter().flat_map(get_names);
    let rust_types = children
        .iter()
        .flat_map(|i| get_rust_types(i, &string, &boolean));

    quote! {
        struct Inputs {
            #(
                #names: #rust_types
            ),*
        }
    }
}
fn output_struct_construction(children: &[ParsedChild]) -> TokenStream2 {
    let names = children.iter().flat_map(get_names);

    quote! {
        Inputs {
            #(
                #names
            ),*
        }
    }
}

fn fetch_value(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input {
            name, rust_type, ..
        } => {
            let node_ref_name = node_ref_name(name);
            let (_, signal_name_set) = signal_names(name);

            quote! {
                let #name: #rust_type = {
                    let value = {
                        let output = #node_ref_name
                            .get()
                            // event handlers can only fire after the view
                            // is mounted to the DOM, so the `NodeRef` will be `Some`
                            .expect("<input> to exist")
                            .value();

                        let fin: Result<#rust_type, leptos::error::Error> = output
                                    .parse()
                                    .map_err(Into::<leptos::error::Error>::into);
                        fin
                    };

                    match value {
                        Ok(ok) => {
                            // Reset the signal
                            #signal_name_set.set(None);

                            ok
                        } ,
                        Err(err) => {
                            #signal_name_set.set(Some(err));

                            // Skip running the real `on_submit`
                            return
                        }
                    }
                };
            }
        }
        ParsedChild::Textarea { name, .. } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                let #name: String = {
                    let output = #node_ref_name
                        .get()
                        // event handlers can only fire after the view
                        // is mounted to the DOM, so the `NodeRef` will be `Some`
                        .expect("<textarea> to exist")
                        .value();

                    let fin: String = output.to_owned();

                    fin
                };
            }
        }
        ParsedChild::Checkbox { name, .. } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                let #name: bool = {
                    let output = #node_ref_name
                        .get()
                        // event handlers can only fire after the view
                        // is mounted to the DOM, so the `NodeRef` will be `Some`
                        .expect("<checkbox> to exist")
                        .value();

                    let fin: bool = if output == "on" { true } else { false };

                    fin
                };
            }
        }
        ParsedChild::Select {
            name, rust_type, ..
        } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                let #name: #rust_type = {
                    let value = {
                        let output = #node_ref_name
                            .get()
                            // event handlers can only fire after the view
                            // is mounted to the DOM, so the `NodeRef` will be `Some`
                            .expect("<select> to exist")
                            .value();

                        let fin: Result<#rust_type, leptos::error::Error> = output
                                    .parse()
                                    .map_err(Into::<leptos::error::Error>::into);
                        fin
                    };

                    match value {
                        Ok(ok) => {
                            ok
                        } ,
                        Err(err) => {
                            // TODO: This can certainly happen (think of an empty string in a numeric input.)
                            // As such, we should have an error field per input, that we can populate with the
                            // error we received here. <2025-12-30>
                            unreachable!("Should be ruled out at compile time: {err}")
                        }
                    }
                };
            }
        }
        ParsedChild::Show { children, .. } => {
            children.iter().map(fetch_value).collect::<TokenStream2>()
        }
    }
}

fn input_html(child: &ParsedChild) -> TokenStream2 {
    match child {
        ParsedChild::Input {
            name,
            label,
            rust_type,
            html_type,
            reactive,
            auto_complete,
            ..
        } => {
            let node_ref_name = node_ref_name(name);
            let (signal_name_get, _) = signal_names(name);
            let reactive = {
                if reactive.is_some() {
                    let (_, signal_reactive_set) = signal_reactive_base_names(name);

                    quote! {
                        reactive=Some(#signal_reactive_set)
                    }
                } else {
                    quote! {}
                }
            };

            let auto_complete = {
                if auto_complete.is_some() {
                    let (signal_auto_complete_get, _) = signal_auto_complete_names(name);

                    quote! {
                        auto_complete=Some(#signal_auto_complete_get)
                    }
                } else {
                    quote! {}
                }
            };

            quote! {
                <InputPlaceholder #reactive #auto_complete input_type=#html_type label=#label node_ref=#node_ref_name />

                <Show
                   when=move || #signal_name_get.get().is_some()
                   fallback=|| ()
                >
                    <p class="ps-2 text-red-300">{move ||
                        format!(
                            "Input is invalid for type {}: {}",
                            stringify!(#rust_type),
                            #signal_name_get.get().expect("Was `is_some`")
                        )
                    }</p>
                </Show>
            }
        }
        ParsedChild::Textarea { name, label, .. } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                <TextareaPlaceholder label=#label node_ref=#node_ref_name />
            }
        }
        ParsedChild::Checkbox { name, label } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                <CheckboxPlaceholder label=#label node_ref=#node_ref_name />
            }
        }
        ParsedChild::Select {
            name,
            label,
            options,
            ..
        } => {
            let node_ref_name = node_ref_name(name);

            quote! {
                <SelectPlaceholder label=#label node_ref=#node_ref_name options=#options />
            }
        }
        ParsedChild::Show { when, children } => {
            let rendered_children = children.iter().map(input_html).collect::<Vec<_>>();

            quote! {
                <Show
                    when=#when
                >
                    #(
                        #rendered_children
                     )*
                </Show>
            }
        }
    }
}