rumtk-web 0.10.3

Web framework part of the RUMTK framework that attempts to simplify and expedite dashboard development in Healthcare.
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
/*
 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
 * This toolkit aims to be reliable, simple, performant, and standards compliant.
 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
 * Copyright (C) 2025  Ethan Dixon
 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
use crate::components::form::Forms;
pub use crate::css::DEFAULT_OUT_CSS_DIR;
use crate::pages::UserPages;
pub use crate::utils::defaults::{DEFAULT_LISTENING_PORT, DEFAULT_LOCAL_LISTENING_ADDRESS};
use crate::utils::matcher::*;
use crate::{rumtk_web_api_process, rumtk_web_get_config, SharedAppState};
use crate::{rumtk_web_fetch, RUMString};
use rumtk_core::base::RUMResult;
use rumtk_core::types::RUMTcpListener;
use std::future::Future;

use crate::api::UserAPIEndpoints;
use axum::routing::{get, post};
use axum::Router;
use rumtk_core::rumtk_spawn_task;
use rumtk_core::strings::rumtk_format;
use tower_http::compression::{CompressionLayer, DefaultPredicate};
use tower_http::services::ServeDir;

pub const DEFAULT_UPLOAD_LIMIT: usize = 10240;

async fn create_listener<F>(ctx: &AppContext<F>) -> RUMResult<RUMTcpListener>
where
    F: Future<Output = RUMResult<()>>,
{
    let mut ip = ctx.ip.clone().unwrap_or_else(|| {DEFAULT_LOCAL_LISTENING_ADDRESS.to_string()});

    if ip.is_empty() {
        ip = DEFAULT_LOCAL_LISTENING_ADDRESS.to_string();
    }

    let listening_ip = rumtk_format!(
        "{}:{}",
        ip,
        ctx.port.clone().unwrap_or_else(|| {DEFAULT_LISTENING_PORT.parse().unwrap_or_default()})
    );

    println!("binding IP {}", listening_ip.as_str());
    let listener = match RUMTcpListener::bind(listening_ip.as_str()).await {
        Ok(listener) => listener,
        Err(err) => return Err(rumtk_format!("There was an issue biding the listener. {}", err)),
    };
    println!("listening on {}", listener.local_addr().unwrap());

    Ok(listener)
}

pub async fn run_app<F>(ctx: AppContext<F>) -> RUMResult<()>
where
    F: Future<Output = RUMResult<()>>,
{
    let comression_layer: CompressionLayer = CompressionLayer::new()
        .br(true)
        .deflate(true)
        .gzip(true)
        .zstd(true)
        .compress_when(DefaultPredicate::new());
    let app = Router::new()
        /* Robots.txt */
        .route("/robots.txt", get(rumtk_web_fetch!(default_robots_matcher)))
        /* Jobs Queue */
        .route("/jobs/", get(rumtk_web_fetch!(default_job_matcher)))
        .route("/jobs/{*page}", get(rumtk_web_fetch!(default_job_matcher)))
        /* Pages */
        .route("/", get(rumtk_web_fetch!(default_page_matcher)))
        .route("/{*page}", get(rumtk_web_fetch!(default_page_matcher)))
        .layer(rumtk_web_get_config!(ctx.state).cors.clone().unwrap_or_default().build_cors_layer())
        /* Post Handling */
        .route("/api/", post(rumtk_web_api_process!(default_api_matcher)))
        //.layer(DefaultBodyLimit::max(args.upload_limit))
        .route(
            "/api/{*page}",
            post(rumtk_web_api_process!(default_api_matcher)),
        )
        //.layer(DefaultBodyLimit::max(args.upload_limit))
        /* Services */
        .nest_service("/static", ServeDir::new("static"))
        .with_state(ctx.state.clone())
        .layer(comression_layer);

    match !ctx.switches.skip_serve {
        true => {
            let listener = create_listener(&ctx).await?;
            // Begin the web app logic so we can serve the app.
            let axum_app = async move || -> RUMResult<()> {
                match axum::serve(listener, app).await
                {
                    Ok(()) => Ok(()),
                    Err(e) => Err(rumtk_format!("There was an issue with the server: {}", e))
                }
            };
            let axum_app_handle = rumtk_spawn_task!(axum_app());
            // Run the custom logic if any. This is meant for processing CLI messages separately from the web app.
            match ctx.logic {
                Some(logic) => match logic.await {
                    Ok(()) => (),
                    Err(e) => return Err(rumtk_format!("There was an issue with the custom app logic: {}", e))
                },
                None => (),
            };

            match axum_app_handle.await {
                Ok(r) => r,
                Err(e) => Err(rumtk_format!("There was an issue running the server: {}", e))
            }
        },
        false => Ok(()),
    }
}

///
/// Struct encapsulating custom-made items to register with the framework.
///
/// ## Pages
/// The `pages` field accepts an optional of [UserPages] which is a vector of [PageItem](crate::pages::PageItem).
///
/// ```text
///     vec![
///         ("my_page", my_page_function),
///         ...
///     ];
/// ```
///
/// The page function is of type [PageFunction](crate::utils::types::PageFunction).
///
/// It is important to understand that a `page` is a function that simply list the series of components to be rendered.
/// We rely on `CSS` for the actual layout in 2D space. Therefore, a page function should not prescribe the page layout per se.
///
/// ## Components
/// The `components` field takes an optional of [UserComponents] which is a vector of [UserComponentItem](crate::components::UserComponentItem).
///
/// ```text
///     vec![
///         ("my_component", my_component_function),
///         ...
///     ];
/// ```
///
/// The component function is of type [PageFunction](crate::utils::types::ComponentFunction).
///
/// ## Forms
/// The `forms` field takes an optional of [Forms] which is a vector of [FormItem](crate::components::form::FormItem).
///
/// ```text
///     vec![
///         ("my_form", my_form_function),
///         ...
///     ];
/// ```
///
/// The form function is of type [FormBuilderFunction](crate::components::form::FormBuilderFunction).
///
/// Although a `form` is treated as a type of component in the framework, its implementation and behavior is closer to
/// a `page` in that its main role is to define the vector of [FormElementBuilder](crate::components::form::FormElementBuilder).
/// These element builder functions further renders the actual form component to be inserted in linear order. Again, these functions
/// say nothing about the layout of the form as that is handled via `CSS`.
///
/// ## APIs
/// The `apis` field takes an optional of [UserAPIEndpoints] which is a vector of [APIItem](crate::api::APIItem).
///
/// ```text
///     vec![
///         ("/my/api/endpoint", my_api_handler),
///         ...
///     ];
/// ```
///
/// The api function is of type [APIFunction](crate::utils::types::APIFunction).
///
/// These API functions are your handlers directly mapped to the REST route you wish to intercept. This enables a
/// simple key-value pair approach to defining API endpoints in your web app. These handlers can queue asynchronous
/// pipeline jobs, return HTML fragments, redirect the current page somewhere else, or a combination of these.
/// It is a powerful interface for organizing your routing.
///
#[derive(Default, Debug, PartialEq, Clone)]
pub struct AppComponents<'a> {
    pub pages: Option<UserPages<'a>>,
    pub forms: Option<Forms<'a>>,
    pub apis: Option<UserAPIEndpoints<'a>>,
}

///
/// Struct for defining the global switches to drive the initialization of the web app. This struct
/// works hand in hand with [AppComponents].
///
#[derive(Default, Debug, PartialEq, Clone)]
pub struct AppSwitches {
    pub skip_serve: bool,
    pub skip_default_css: bool,
    pub skip_cli_args: bool,
}

impl AppSwitches {
    pub fn from_slice(switches: &[bool]) -> Self {
        match switches.len() {
            0 => AppSwitches::default(),
            1 => AppSwitches {
                skip_serve: switches[0],
                ..Default::default()
            },
            2 => AppSwitches {
                skip_serve: switches[0],
                skip_default_css: switches[1],
                ..Default::default()
            },
            _ => AppSwitches {
                skip_serve: switches[0],
                skip_default_css: switches[1],
                skip_cli_args: switches[2],
            },
        }
    }
}

impl From<&[bool]> for AppSwitches {
    fn from(switches: &[bool]) -> Self {
        AppSwitches::from_slice(switches)
    }
}

impl<const N: usize> From<[bool; N]> for AppSwitches {
    fn from(switches: [bool; N]) -> Self {
        AppSwitches::from_slice(&switches)
    }
}

///
/// Struct encapsulating custom-made items to register with the framework.
///
///
#[derive(Default, Debug, Clone)]
pub struct AppContext<F: Future<Output = RUMResult<()>>> {
    pub ip: Option<RUMString>,
    pub port: Option<u16>,
    pub logic: Option<F>,
    pub components: AppComponents<'static>,
    pub switches: AppSwitches,
    pub state: SharedAppState,
}

impl<F> AppContext<F>
where
    F: Future<Output = RUMResult<()>>
{
    pub fn new() -> AppContext<F> {
        AppContext {
            ip: None,
            port: None,
            logic: None,
            components: AppComponents::default(),
            switches: AppSwitches::default(),
            state: SharedAppState::default(),
        }
    }

    pub fn init_ip(mut self, ip: RUMString) -> AppContext<F> {
        if self.ip.is_none() {
            self.ip = Some(ip);
        }

        self
    }

    pub fn init_port(mut self, port: u16) -> AppContext<F> {
        if self.port.is_none() {
            self.port = Some(port);
        }
        self
    }

    pub fn init_logic(mut self, logic: F) -> AppContext<F> {
        if self.logic.is_none() {
            self.logic = Some(logic);
        }

        self
    }

    pub fn init_components(mut self, components: AppComponents<'static>) -> AppContext<F> {
        self.components = components;
        self
    }

    pub fn init_switches(mut self, switches: AppSwitches) -> AppContext<F> {
        self.switches = switches;
        self
    }

    pub fn init_state(mut self, state: SharedAppState) -> AppContext<F> {
        self.state = state;
        self
    }
}

///
/// Convenience macro for quickly building the [AppComponents] object. Feel free to pass an instance of
/// [AppComponents] directly to [run_app] or [rumtk_web_run_app](crate::rumtk_web_run_app).
///
/// Passing no parameters generates an "empty" instance, meaning you would be asking the framework that you only
/// care about built-in components. This also implies you do not want to process API endpoints.
///
/// ## Examples
///
/// ### Without Parameters
/// ```
/// use crate::rumtk_web::AppComponents;
/// use crate::rumtk_web::rumtk_web_register_app_components;
///
/// let expected = AppComponents::default();
/// let result = rumtk_web_register_app_components!();
///
/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
///
/// ```
///
/// ### With Existing Page
/// ```
/// use rumtk_web::pages::UserPages;
/// use crate::rumtk_web::AppComponents;
/// use crate::rumtk_web::pages::index::index;
/// use crate::rumtk_web::rumtk_web_register_app_components;
///
/// let my_pages: UserPages = vec![
///     ("myindex", index)
/// ];
/// let expected = AppComponents {
///     pages: Some(my_pages.clone()),
///     forms: None,
///     apis: None,
///  };
/// let result = rumtk_web_register_app_components!(my_pages);
///
/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
///
/// ```
///
/// ### With Existing Page and Component and Form
/// ```
/// use rumtk_core::strings::RUMString;
/// use rumtk_web::{AppComponents, SharedAppState};
/// use rumtk_web::pages::UserPages;
/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
/// use rumtk_web::pages::index::index;
/// use rumtk_web::components::form::props::InputProps;
/// use rumtk_web::rumtk_web_register_app_components;
///
/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
///     vec![
///         builder(
///             "input",
///             "",
///             InputProps {
///                 id: Some("file"),
///                 name: Some("file"),
///                 for_element: None,
///                 typ: Some("file"),
///                 value: None,
///                 max: None,
///                 placeholder: Some("path/to/file"),
///                 pattern: None,
///                 accept: Some(".pdf,application/pdf"),
///                 alt: None,
///                 aria_label: Some("PDF File Picker"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: false,
///                 required: true,
///                 multiple: false,
///             },
///             ""
///         ),
///         builder(
///             "input",
///             "",
///             InputProps {
///                 id: Some("submit"),
///                 name: None,
///                 for_element: None,
///                 typ: Some("submit"),
///                 value: Some("Send"),
///                 max: None,
///                 placeholder: None,
///                 pattern: None,
///                 accept: None,
///                 alt: None,
///                 aria_label: Some("PDF File Submit Button"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: false,
///                 required: false,
///                 multiple: false,
///             },
///             "f18"
///         ),
///         builder(
///             "progress",
///             "",
///             InputProps {
///                 id: Some("progress"),
///                 name: None,
///                 for_element: None,
///                 typ: None,
///                 value: Some("0"),
///                 max: Some("100"),
///                 placeholder: None,
///                 pattern: None,
///                 accept: None,
///                 alt: None,
///                 aria_label: Some("PDF File Submit Progress Bar"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: true,
///                 required: false,
///                 multiple: false,
///             },
///             ""
///         ),
///     ]
/// }
///
/// let my_pages: UserPages = vec![
///     ("myindex", index)
/// ];
/// let my_forms: Forms = vec![
///     ("myform", upload_form)
/// ];
/// let expected = AppComponents {
///     pages: Some(my_pages.clone()),
///     forms: Some(my_forms.clone()),
///     apis: None,
///  };
/// let result = rumtk_web_register_app_components!(my_pages, my_forms);
///
/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
///
/// ```
///
/// ### With Existing Page and Component and Form and API Endpoint
/// ```
/// use rumtk_core::{rumtk_pipeline_run_async, rumtk_pipeline_command};
/// use rumtk_core::strings::{RUMString, RUMStringConversions, RUMArrayConversions};
/// use rumtk_web::{rumtk_web_params_map, rumtk_web_post_process_html, APIPath, AppComponents, FormData, HTMLResult, RUMWebData, RUMWebResponse, SharedAppState};
/// use rumtk_web::{rumtk_web_get_job_manager, rumtk_web_render_component, rumtk_web_render_page_contents};
/// use rumtk_web::api::UserAPIEndpoints;
/// use rumtk_web::pages::UserPages;
/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
/// use rumtk_web::pages::index::index;
/// use rumtk_web::components::form::props::InputProps;
/// use rumtk_web::components::job_loader::{job_loader, JobLoader};
/// use rumtk_web::jobs::{JobResult};
/// use rumtk_web::utils::defaults::{PARAMS_TARGET, PARAMS_ID};
/// use rumtk_web::ComponentResult;
/// use rumtk_web::components::sanitize::sanitized;
/// use rumtk_web::rumtk_web_register_app_components;
///
/// async fn upload_processor(form: FormData) -> JobResult {
///     let id = form.form.get("file").unwrap();
///     let file = form.files.get(id).unwrap();
///
///     let result = rumtk_pipeline_run_async!(
///         &vec![
///             rumtk_pipeline_command!("cat"),
///             rumtk_pipeline_command!("wc")
///         ],
///         &file.clone()
///     ).await?;
///
///     let sanitized = sanitized(result.to_vec().to_string()?);
///     Ok(Some(sanitized?))
/// }
///
/// pub fn process_upload(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
///     let job_id = rumtk_web_get_job_manager!()?.spawn_task(upload_processor(form))?;
///
///    let params = rumtk_web_params_map!([(PARAMS_ID, job_id)]);
///    let viewer = job_loader(&[], params.get_inner(), state)?.to_string();
///
///
///     rumtk_web_render_page_contents!(
///             &vec![
///                 viewer
///             ]
///         )
/// }
///
/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
///     vec![
///         builder(
///             "input",
///             "",
///             InputProps {
///                 id: Some("file"),
///                 name: Some("file"),
///                 for_element: None,
///                 typ: Some("file"),
///                 value: None,
///                 max: None,
///                 placeholder: Some("path/to/file"),
///                 pattern: None,
///                 accept: Some(".pdf,application/pdf"),
///                 alt: None,
///                 aria_label: Some("PDF File Picker"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: false,
///                 required: true,
///                 multiple: false,
///             },
///             ""
///         ),
///         builder(
///             "input",
///             "",
///             InputProps {
///                 id: Some("submit"),
///                 name: None,
///                 for_element: None,
///                 typ: Some("submit"),
///                 value: Some("Send"),
///                 max: None,
///                 placeholder: None,
///                 pattern: None,
///                 accept: None,
///                 alt: None,
///                 aria_label: Some("PDF File Submit Button"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: false,
///                 required: false,
///                 multiple: false,
///             },
///             "f18"
///         ),
///         builder(
///             "progress",
///             "",
///             InputProps {
///                 id: Some("progress"),
///                 name: None,
///                 for_element: None,
///                 typ: None,
///                 value: Some("0"),
///                 max: Some("100"),
///                 placeholder: None,
///                 pattern: None,
///                 accept: None,
///                 alt: None,
///                 aria_label: Some("PDF File Submit Progress Bar"),
///                 event_handlers: None,
///                 max_length: None,
///                 min_length: None,
///                 autocapitalize: false,
///                 autocomplete: false,
///                 autocorrect: false,
///                 autofocus: false,
///                 disabled: false,
///                 hidden: true,
///                 required: false,
///                 multiple: false,
///             },
///             ""
///         ),
///     ]
/// }
///
/// let my_pages: UserPages = vec![
///     ("myindex", index)
/// ];
/// let my_forms: Forms = vec![
///     ("myform", upload_form)
/// ];
/// let my_endpoints: UserAPIEndpoints = vec![
///     ("/api/upload", process_upload)
/// ];
/// let expected = AppComponents {
///     pages: Some(my_pages.clone()),
///     forms: Some(my_forms.clone()),
///     apis: Some(my_endpoints.clone()),
///  };
/// let result = rumtk_web_register_app_components!(my_pages, my_forms, my_endpoints);
///
/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
///
/// ```
///
#[macro_export]
macro_rules! rumtk_web_register_app_components {
    (  ) => {{
        use $crate::utils::app::AppComponents;

        AppComponents::default()
    }};
    ( $pages:expr ) => {{
        use $crate::utils::app::AppComponents;

        AppComponents {
            pages: Some($pages),
            forms: None,
            apis: None,
        }
    }};
    ( $pages:expr, $forms:expr ) => {{
        use $crate::utils::app::AppComponents;

        AppComponents {
            pages: Some($pages),
            forms: Some($forms),
            apis: None,
        }
    }};
    ( $pages:expr, $forms:expr, $apis:expr ) => {{
        use $crate::utils::app::AppComponents;

        AppComponents {
            pages: Some($pages),
            forms: Some($forms),
            apis: Some($apis),
        }
    }};
}

///
/// Convenience macro for generating a [AppSwitches] instance containing the boolean options a
/// framework consumer would like to opt-in.
///
/// ## Examples
/// ```
/// use rumtk_web::AppSwitches;
/// use rumtk_web::{rumtk_web_register_app_switches};
///
/// let expected = AppSwitches {
///     skip_serve: true,
///     skip_default_css: false,
///     ..Default::default()
/// };
/// let switches = rumtk_web_register_app_switches!(true);
///
/// assert_eq!(switches, expected, "The switches constructed to config app does not match the expected.");
/// ```
///
#[macro_export]
macro_rules! rumtk_web_register_app_switches {
    (  ) => {{
        use $crate::utils::app::AppSwitches;

        AppSwitches::default()
    }};
    ( $($switch:expr),+ ) => {{
        use $crate::utils::app::AppSwitches;

        AppSwitches::from([$($switch),+])
    }};
}

///
/// Initializes a Context structure used for runtime configuration of the app in addition to the
/// JSON configuration.
///
/// ## Usage Examples
/// ```
/// use rumtk_web::{rumtk_web_register_app_context, rumtk_web_register_app_switches};
/// use rumtk_web::utils::app::{AppComponents, AppSwitches};
///
/// rumtk_web_register_app_context!();
/// rumtk_web_register_app_context!(AppComponents::default());
/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default());
/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default(), 3001);
/// rumtk_web_register_app_context!(AppComponents::default(), AppSwitches::default(), 3001, async || Ok(()));
/// ```
///
/// ## Usage Signature
/// Below are the supported macro signatures:
///
/// ```text
///     - ()
///     - ( app_components )
///     - ( app_components, app_switches )
///     - ( app_components, app_switches, port )
///     - ( app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
/// ```
///
/// ## Note
/// In some cases, this struct is used to override the typical behavior since the `ip`, `port`, and
/// `logic` fields are initialized only once. Meaning, we can route the system to use specific ports
/// during testing or statically in the program and follow the CLI arguments all other times.
///
#[macro_export]
macro_rules! rumtk_web_register_app_context {
    (  ) => {{
        $crate::rumtk_web_register_app_context!($crate::utils::app::AppComponents::default())
    }};
    (
        $app_components:expr
    ) => {{
        $crate::rumtk_web_register_app_context!(
            $app_components,
            $crate::rumtk_web_register_app_switches!(),
            $crate::utils::app::DEFAULT_LISTENING_PORT.parse::<u16>().unwrap_or_default(),
            async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
        )
    }};
    (
        $app_components:expr,
        $app_switches:expr $(,)?
    ) => {{
        $crate::rumtk_web_register_app_context!(
            $app_components,
            $app_switches,
            $crate::utils::app::DEFAULT_LISTENING_PORT.parse::<u16>().unwrap_or_default(),
            async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
        )
    }};
    (
        $app_components:expr,
        $app_switches:expr,
        $port:expr
    ) => {{
        $crate::rumtk_web_register_app_context!(
            $app_components,
            $app_switches,
            $port,
            async || -> rumtk_core::base::RUMResult<()> { Ok(()) }
        )
    }};
    (
        $app_components:expr,
        $app_switches:expr,
        $port:expr,
        $hook:expr
    ) => {{
        use $crate::utils::app::AppContext;

        AppContext::new()
            .init_components($app_components.clone())
            .init_switches($app_switches.clone())
            .init_port($port)
            .init_logic($hook())
    }};
}

///
/// This is the main macro for defining your applet and launching it.
/// Usage is very simple and the only decision from a user is whether to pass a list of
/// [UserPages](UserPages) or a list of [UserPages](UserPages) and a list
/// of [UserComponents](UserComponents).
///
/// These lists are used to automatically register your pages
/// (e.g. `/index => ('index', my_index_function)`) and your custom components
/// (e.g. `button => ('button', my_button_function)`
///
/// This macro will load CSS from predefined sources, concatenate their contents with predefined CSS,
/// minified the concatenated results, and generate a bundle css file containing the minified results.
/// The CSS bundle is written to file `./static/css/bundle.min.css`.
///
/// ***Note: anything in ./static will be considered static assets that need to be served.***
///
/// This macro will also parse the command line automatically with a few predefined options and
/// use that information to override the config defaults.
///
/// By default, the app is launched to `127.0.0.1:3000` which is the loopback address.
///
/// App is served with the best compression algorithm allowed by the client browser.
///
/// For testing purposes, the function
///
/// ## Example Usage
///
/// ### With Page and Component definition
/// ```
///     use rumtk_core::strings::{rumtk_format};
///     use rumtk_web::{rumtk_web_run_app, rumtk_web_register_app_components, rumtk_web_render_component, rumtk_web_render_template, rumtk_web_get_text_item, rumtk_web_register_app_switches, rumtk_web_get_config, rumtk_web_params_map};
///     use rumtk_web::components::form::{FormElementBuilder, props::InputProps, FormElements};
///     use rumtk_web::{SharedAppState, RenderedPageComponentsResult};
///     use rumtk_web::{APIPath, URLPath, URLParams, HTMLResult, RUMString, RouterForm, FormData, RUMWebData, AppConf};
///     use rumtk_web::components::portrait_card::portrait_card;
///     use rumtk_web::components::layouts::spacer::vspacer;
///     use rumtk_web::components::text_card::text_card;
///     use rumtk_web::components::title::title;
///     use rumtk_web::ComponentResult;
/// use rumtk_web::components::job_loader::JobLoader;
///     use rumtk_web::defaults::{DEFAULT_TEXT_ITEM, PARAMS_CONTENTS, PARAMS_CSS_CLASS, PARAMS_TYPE};
///     use rumtk_web::utils::types::RUMWebTemplate;
///
///
///
///
///     // About page
///     pub fn about(app_state: SharedAppState) -> RenderedPageComponentsResult {
///         let title_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
///         let title_coop = title(&[], title_coop_params.get_inner(), app_state.clone())?.to_string();
///
///         let title_team_params = rumtk_web_params_map!([(PARAMS_TYPE, "meet_the_team")]);
///         let title_team = title(&[], title_team_params.get_inner(), app_state.clone())?.to_string();
///
///         let text_card_story_params = rumtk_web_params_map!([(PARAMS_TYPE, "story")]);
///         let text_card_story = text_card(&[], text_card_story_params.get_inner(), app_state.clone())?.to_string();
///
///         let text_card_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
///         let text_card_coop = text_card(&[], text_card_coop_params.get_inner(), app_state.clone())?.to_string();
///
///         let portrait_card_params = rumtk_web_params_map!([("section", "company"), (PARAMS_TYPE, "personnel")]);
///         let portrait_card = portrait_card(&[], portrait_card_params.get_inner(), app_state.clone())?.to_string();
///
///         let spacer_5 = vspacer(5)?.to_string();
///     
///         Ok(vec![
///             text_card_story,
///             spacer_5.clone(),
///             title_coop,
///             text_card_coop,
///             spacer_5,
///             title_team,
///             portrait_card
///         ])
///     }
///
///     //Custom component
///     #[derive(RUMWebTemplate, Debug)]
///     #[template(
///             source = "
///                {% if custom_css_enabled %}
///                    <link href='/static/components/div.css' rel='stylesheet'>
///                {% endif %}
///                <div class='div-{{css_class}}'>{{contents|safe}}</div>
///            ",
///            ext = "html"
///     )]
///     struct MyDiv {
///         contents: RUMString,
///         css_class: RUMString,
///         custom_css_enabled: bool,
///     }
///
///     fn my_div(path_components: URLPath, params: URLParams, state: SharedAppState) -> ComponentResult<MyDiv> {
///         let contents = rumtk_web_get_text_item!(params, PARAMS_CONTENTS, DEFAULT_TEXT_ITEM);
///         let css_class = rumtk_web_get_text_item!(params, PARAMS_CSS_CLASS, DEFAULT_TEXT_ITEM);
///
///         let custom_css_enabled = rumtk_web_get_config!(state).flags.custom_css;
///
///         Ok(MyDiv {
///             contents: RUMString::from(contents),
///             css_class: RUMString::from(css_class),
///             custom_css_enabled
///         })
///     }
///
///     fn my_form (builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
///         vec![
///             builder("input", "", InputProps::default(), "default")
///         ]
///     }
///
///     fn my_api_handler(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
///         Err(rumtk_format!(
///             "No handler registered for API endpoint => {}",
///             path
///         ))
///     }
///
///     //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
///     let skip_serve = true;
///     let skip_default_css = false;
///
///     let app_components = rumtk_web_register_app_components!(
///         vec![("about", about)],
///         vec![("my_form", my_form)], //Optional, can be omitted alongside the skip_serve flag
///         vec![("v2/add", my_api_handler)] //Optional, can be omitted alongside the skip_serve flag
///     );
///     let app_switches = rumtk_web_register_app_switches!(
///         skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
///         skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
///     );
///     let result = rumtk_web_run_app!(
///         app_components,
///         app_switches
///     );
/// ```
///
/// ### Example of Usage
/// ```no_run
/// use rumtk_web::{rumtk_web_run_app, rumtk_web_register_app_switches};
/// use rumtk_web::utils::app::{AppComponents, AppSwitches};
///
/// //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
/// let skip_serve = true;
/// let skip_default_css = false;
/// let app_switches = rumtk_web_register_app_switches!(
///     skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
///     skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
/// );
///
/// rumtk_web_run_app!();
/// rumtk_web_run_app!([]);
/// rumtk_web_run_app!([#[arg(long)] extra: bool]);
/// rumtk_web_run_app!(AppComponents::default(), app_switches);
/// rumtk_web_run_app!(AppComponents::default(), app_switches, 3001);
/// rumtk_web_run_app!(AppComponents::default(), app_switches, 3001, async || Ok(()));
/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default());
/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches);
/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001);
/// rumtk_web_run_app!([#[arg(long)] extra: bool], AppComponents::default(), app_switches, 3001, async || Ok(()));
/// ```
///
/// ## Signatures & Usages
///
/// This is a complex macro that is trying to be backwards compatible with the old prescribed way
/// of producing a web applet. It is also trying to allow future applets to specify new flags and even
/// a closure hook to perform further initialization of the framework based on the new flags.
///
/// Below are the supported macro signatures:
///
/// ```text
///     - ()
///     - ( pretty: bool )
///     - ( pretty: bool, app_components )
///     - ( pretty: bool, app_components, app_switches )
///     - ( pretty: bool, app_components, app_switches, port )
///     - ( pretty: bool, app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
///     - ( app_components )
///     - ( app_components, app_switches )
///     - ( app_components, app_switches, port )
///     - ( app_components, app_switches, port, || -> rumtk_core::base::RUMResult<()> { Ok(()) } )
/// ```
///
#[macro_export]
macro_rules! rumtk_web_run_app {
    (
        [
            $(
                $(#[$field_meta:meta])*
                $field_name:ident : $field_typ:ty
            ),* $(,)?
        ],
        $app_components:expr,
        $switches:expr,
        $port:expr,
        $hook:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
            $crate::rumtk_web_register_app_context!($app_components, $switches, $port, $hook)
        )
    }};
    (
        [
            $(
                $(#[$field_meta:meta])*
                $field_name:ident : $field_typ:ty
            ),* $(,)?
        ],
        $app_components:expr,
        $switches:expr,
        $port:expr
    ) => {{
        use rumtk_core;
        $crate::rumtk_web_run_app!(
            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
            $crate::rumtk_web_register_app_context!($app_components, $switches, $port)
        )
    }};
    (
        [
            $(
                $(#[$field_meta:meta])*
                $field_name:ident : $field_typ:ty
            ),* $(,)?
        ],
        $app_components:expr,
        $switches:expr $(,)?
    ) => {{
        use rumtk_core;
        $crate::rumtk_web_run_app!(
            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
            $crate::rumtk_web_register_app_context!($app_components, $switches)
        )
    }};
    (
        [
            $(
                $(#[$field_meta:meta])*
                $field_name:ident : $field_typ:ty
            ),* $(,)?
        ],
        $app_components:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
            $crate::rumtk_web_register_app_context!($app_components)
        )
    }};
    (
        [
            $(
                $(#[$field_meta:meta])*
                $field_name:ident : $field_typ:ty
            ),* $(,)?
        ] $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
            $crate::rumtk_web_register_app_context!()
        )
    }};
    ( ) => {{
        $crate::rumtk_web_run_app!([])
    }};
    (
        $app_components:expr,
        $switches:expr,
        $port:expr,
        $hook:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [],
            $crate::rumtk_web_register_app_context!($app_components, $switches, $port, $hook)
        )
    }};
    (
        $app_components:expr,
        $switches:expr,
        $port:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [],
            $crate::rumtk_web_register_app_context!($app_components, $switches, $port)
        )
    }};
    (
        $app_components:expr,
        $switches:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [],
            $crate::rumtk_web_register_app_context!($app_components, $switches)
        )
    }};
    (
        $app_components:expr $(,)?
    ) => {{
        $crate::rumtk_web_run_app!(
            @collect [],
            $crate::rumtk_web_register_app_context!($app_components)
        )
    }};
    (
        @collect [$($cli_args:tt)*],
        $context:expr $(,)?
    ) => {{
        use rumtk_core::dependencies::clap;
        use rumtk_core::base::RUMResult;
        use rumtk_core::strings::RUMString;
        use rumtk_core::{rumtk_cli_process, rumtk_resolve_task};
        use $crate::{
            rumtk_web_load_conf, rumtk_web_init_pages, rumtk_web_init_forms,
            rumtk_web_init_api_endpoints, rumtk_web_compile_css_bundle,
            rumtk_web_init_job_manager
        };
        use $crate::utils::app::{
            DEFAULT_OUT_CSS_DIR,
            DEFAULT_LOCAL_LISTENING_ADDRESS,
            DEFAULT_LISTENING_PORT,
            DEFAULT_UPLOAD_LIMIT
        };
        use $crate::utils::app::{
            AppComponents,
            AppSwitches
        };
        use $crate::utils::app::{
            run_app
        };

        rumtk_cli_process!(
            @collect [$($cli_args)*]
            ///
            /// Website title to use internally. It can be omitted if defined in the app.json config file
            /// bundled with your app.
            ///
            #[arg(long, default_value = "")]
            title: RUMString,
            ///
            /// Website description string. It can be omitted if defined in the app.json config file
            /// bundled with your app.
            ///
            #[arg(long, default_value = "")]
            description: RUMString,
            ///
            /// Company to display in website.
            ///
            #[arg(long, default_value = "")]
            company: RUMString,
            ///
            /// Copyright year to display in website.
            ///
            #[arg(short, long, default_value = "")]
            copyright: RUMString,
            ///
            /// Directory to scan on startup to find custom CSS sources to bundle into a minified CSS file
            /// that can be quickly pulled by the app client side.
            ///
            /// This option can provide an alternative to direct component retrieval of CSS fragments.
            /// Meaning, you could bundle all of your fragments into the master bundle at startup and
            /// turn off component level ```custom_css_enabled``` option in the ```app.json``` config.
            ///
            #[arg(long, default_value = DEFAULT_OUT_CSS_DIR)]
            css_source_dir: RUMString,
            ///
            /// IP address to bind!
            ///
            #[arg(short, long, default_value = DEFAULT_LOCAL_LISTENING_ADDRESS)]
            ip: RUMString,
            ///
            /// Port to bind!
            ///
            #[arg(short, long, default_value = DEFAULT_LISTENING_PORT, value_parser = clap::value_parser!(u16).range(1024..=65535))]
            port: u16,
            ///
            /// Specify the size limit for a file upload post request.
            ///
            #[arg(long, default_value_t = DEFAULT_UPLOAD_LIMIT)]
            upload_limit: usize,
            ///
            /// How many threads to use to serve the website. By default, we use
            /// ```get_default_system_thread_count()``` from ```rumtk-core``` to detect the total count of
            /// cpus available. We use the system's total count of cpus by default.
            ///
            #[arg(long, default_value_t = false)]
            skip_default_css: bool,
            Direct(|args: &RUMTKInterfaceArgs| -> RUMResult<()> {
                let state = rumtk_web_load_conf!(&*args);

                let context = $context
                    .init_ip(args.ip.clone())
                    .init_port(args.port.clone())
                    .init_state(state);

                rumtk_web_init_pages!(context.components.pages.clone());
                rumtk_web_init_forms!(context.components.forms.clone(), context.state);
                rumtk_web_init_api_endpoints!(context.components.apis.clone());
                rumtk_web_compile_css_bundle!(
                    &args.css_source_dir,
                    &args.skip_default_css | context.switches.skip_default_css
                );

                rumtk_web_init_job_manager!(&args.threads);

                let task = run_app(context);
                rumtk_resolve_task!(task)
            })
        );
    }};
}