Skip to main content

rumtk_web/utils/
app.rs

1/*
2 * rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 * This toolkit aims to be reliable, simple, performant, and standards compliant.
4 * Copyright (C) 2025  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 * Copyright (C) 2025  Ethan Dixon
6 * Copyright (C) 2025  MedicalMasses L.L.C. <contact@medicalmasses.com>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 */
21use crate::components::form::Forms;
22use std::sync::Arc;
23pub use crate::css::DEFAULT_OUT_CSS_DIR;
24use crate::pages::UserPages;
25use crate::{rumtk_web_fetch, RUMString};
26pub use crate::utils::defaults::DEFAULT_LOCAL_LISTENING_ADDRESS;
27use crate::utils::matcher::*;
28use crate::{rumtk_web_api_process, rumtk_web_get_config, SharedAppState};
29
30use rumtk_core::base::RUMResult;
31use rumtk_core::types::RUMTcpListener;
32
33use crate::api::UserAPIEndpoints;
34use axum::routing::{get, post};
35use axum::Router;
36use tower_http::compression::{CompressionLayer, DefaultPredicate};
37use tower_http::services::ServeDir;
38
39pub const DEFAULT_UPLOAD_LIMIT: usize = 10240;
40
41pub async fn run_app(ip: RUMString, state: SharedAppState, switches: SafeAppSwitches) -> RUMResult<()>
42{
43    let comression_layer: CompressionLayer = CompressionLayer::new()
44        .br(true)
45        .deflate(true)
46        .gzip(true)
47        .zstd(true)
48        .compress_when(DefaultPredicate::new());
49    let app = Router::new()
50        /* Robots.txt */
51        .route("/robots.txt", get(rumtk_web_fetch!(default_robots_matcher)))
52        /* Jobs Queue */
53        .route("/jobs/", get(rumtk_web_fetch!(default_job_matcher)))
54        .route("/jobs/{*page}", get(rumtk_web_fetch!(default_job_matcher)))
55        /* Pages */
56        .route("/", get(rumtk_web_fetch!(default_page_matcher)))
57        .route("/{*page}", get(rumtk_web_fetch!(default_page_matcher)))
58        .layer(rumtk_web_get_config!(state).cors.clone().unwrap_or_default().build_cors_layer())
59        /* Post Handling */
60        .route("/api/", post(rumtk_web_api_process!(default_api_matcher)))
61        //.layer(DefaultBodyLimit::max(args.upload_limit))
62        .route(
63            "/api/{*page}",
64            post(rumtk_web_api_process!(default_api_matcher)),
65        )
66        //.layer(DefaultBodyLimit::max(args.upload_limit))
67        /* Services */
68        .nest_service("/static", ServeDir::new("static"))
69        .with_state(state)
70        .layer(comression_layer);
71
72    println!("binding IP {}", ip.as_str());
73    let listener = RUMTcpListener::bind(ip.as_str())
74        .await
75        .expect("There was an issue biding the listener.");
76    println!("listening on {}", listener.local_addr().unwrap());
77
78    if !switches.skip_serve {
79        axum::serve(listener, app)
80            .await
81            .expect("There was an issue with the server.");
82    }
83
84    Ok(())
85}
86
87///
88/// Struct encapsulating custom-made items to register with the framework.
89///
90/// ## Pages
91/// The `pages` field accepts an optional of [UserPages] which is a vector of [PageItem](crate::pages::PageItem).
92///
93/// ```text
94///     vec![
95///         ("my_page", my_page_function),
96///         ...
97///     ];
98/// ```
99///
100/// The page function is of type [PageFunction](crate::utils::types::PageFunction).
101///
102/// It is important to understand that a `page` is a function that simply list the series of components to be rendered.
103/// We rely on `CSS` for the actual layout in 2D space. Therefore, a page function should not prescribe the page layout per se.
104///
105/// ## Components
106/// The `components` field takes an optional of [UserComponents] which is a vector of [UserComponentItem](crate::components::UserComponentItem).
107///
108/// ```text
109///     vec![
110///         ("my_component", my_component_function),
111///         ...
112///     ];
113/// ```
114///
115/// The component function is of type [PageFunction](crate::utils::types::ComponentFunction).
116///
117/// ## Forms
118/// The `forms` field takes an optional of [Forms] which is a vector of [FormItem](crate::components::form::FormItem).
119///
120/// ```text
121///     vec![
122///         ("my_form", my_form_function),
123///         ...
124///     ];
125/// ```
126///
127/// The form function is of type [FormBuilderFunction](crate::components::form::FormBuilderFunction).
128///
129/// Although a `form` is treated as a type of component in the framework, its implementation and behavior is closer to
130/// a `page` in that its main role is to define the vector of [FormElementBuilder](crate::components::form::FormElementBuilder).
131/// These element builder functions further renders the actual form component to be inserted in linear order. Again, these functions
132/// say nothing about the layout of the form as that is handled via `CSS`.
133///
134/// ## APIs
135/// The `apis` field takes an optional of [UserAPIEndpoints] which is a vector of [APIItem](crate::api::APIItem).
136///
137/// ```text
138///     vec![
139///         ("/my/api/endpoint", my_api_handler),
140///         ...
141///     ];
142/// ```
143///
144/// The api function is of type [APIFunction](crate::utils::types::APIFunction).
145///
146/// These API functions are your handlers directly mapped to the REST route you wish to intercept. This enables a
147/// simple key-value pair approach to defining API endpoints in your web app. These handlers can queue asynchronous
148/// pipeline jobs, return HTML fragments, redirect the current page somewhere else, or a combination of these.
149/// It is a powerful interface for organizing your routing.
150///
151#[derive(Default, Debug, PartialEq, Clone)]
152pub struct AppComponents<'a> {
153    pub pages: Option<UserPages<'a>>,
154    pub forms: Option<Forms<'a>>,
155    pub apis: Option<UserAPIEndpoints<'a>>,
156}
157
158pub type SafeAppComponents = Arc<AppComponents<'static>>;
159
160///
161/// Struct for defining the global switches to drive the initialization of the web app. This struct
162/// works hand in hand with [AppComponents].
163///
164#[derive(Default, Debug, PartialEq, Clone)]
165pub struct AppSwitches {
166    pub skip_serve: bool,
167    pub skip_default_css: bool,
168    pub skip_cli_args: bool,
169}
170
171impl AppSwitches {
172    pub fn from_slice(switches: &[bool]) -> Self {
173        match switches.len() {
174            0 => AppSwitches::default(),
175            1 => AppSwitches {
176                skip_serve: switches[0],
177                ..Default::default()
178            },
179            2 => AppSwitches {
180                skip_serve: switches[0],
181                skip_default_css: switches[1],
182                ..Default::default()
183            },
184            _ => AppSwitches {
185                skip_serve: switches[0],
186                skip_default_css: switches[1],
187                skip_cli_args: switches[2],
188            },
189        }
190    }
191}
192
193impl From<&[bool]> for AppSwitches {
194    fn from(switches: &[bool]) -> Self {
195        AppSwitches::from_slice(switches)
196    }
197}
198
199impl<const N: usize> From<[bool; N]> for AppSwitches {
200    fn from(switches: [bool; N]) -> Self {
201        AppSwitches::from_slice(&switches)
202    }
203}
204
205pub type SafeAppSwitches = Arc<AppSwitches>;
206
207///
208/// Convenience macro for quickly building the [AppComponents] object. Feel free to pass an instance of
209/// [AppComponents] directly to [run_app] or [rumtk_web_run_app](crate::rumtk_web_run_app).
210///
211/// Passing no parameters generates an "empty" instance, meaning you would be asking the framework that you only
212/// care about built-in components. This also implies you do not want to process API endpoints.
213///
214/// ## Examples
215///
216/// ### Without Parameters
217/// ```
218/// use crate::rumtk_web::AppComponents;
219/// use crate::rumtk_web::rumtk_web_register_app_components;
220///
221/// let expected = AppComponents::default();
222/// let result = rumtk_web_register_app_components!();
223///
224/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
225///
226/// ```
227///
228/// ### With Existing Page
229/// ```
230/// use rumtk_web::pages::UserPages;
231/// use crate::rumtk_web::AppComponents;
232/// use crate::rumtk_web::pages::index::index;
233/// use crate::rumtk_web::rumtk_web_register_app_components;
234///
235/// let my_pages: UserPages = vec![
236///     ("myindex", index)
237/// ];
238/// let expected = AppComponents {
239///     pages: Some(my_pages.clone()),
240///     forms: None,
241///     apis: None,
242///  };
243/// let result = rumtk_web_register_app_components!(my_pages);
244///
245/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
246///
247/// ```
248///
249/// ### With Existing Page and Component and Form
250/// ```
251/// use rumtk_core::strings::RUMString;
252/// use rumtk_web::{AppComponents, SharedAppState};
253/// use rumtk_web::pages::UserPages;
254/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
255/// use rumtk_web::pages::index::index;
256/// use rumtk_web::components::form::props::InputProps;
257/// use rumtk_web::rumtk_web_register_app_components;
258///
259/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
260///     vec![
261///         builder(
262///             "input",
263///             "",
264///             InputProps {
265///                 id: Some("file"),
266///                 name: Some("file"),
267///                 for_element: None,
268///                 typ: Some("file"),
269///                 value: None,
270///                 max: None,
271///                 placeholder: Some("path/to/file"),
272///                 pattern: None,
273///                 accept: Some(".pdf,application/pdf"),
274///                 alt: None,
275///                 aria_label: Some("PDF File Picker"),
276///                 event_handlers: None,
277///                 max_length: None,
278///                 min_length: None,
279///                 autocapitalize: false,
280///                 autocomplete: false,
281///                 autocorrect: false,
282///                 autofocus: false,
283///                 disabled: false,
284///                 hidden: false,
285///                 required: true,
286///                 multiple: false,
287///             },
288///             ""
289///         ),
290///         builder(
291///             "input",
292///             "",
293///             InputProps {
294///                 id: Some("submit"),
295///                 name: None,
296///                 for_element: None,
297///                 typ: Some("submit"),
298///                 value: Some("Send"),
299///                 max: None,
300///                 placeholder: None,
301///                 pattern: None,
302///                 accept: None,
303///                 alt: None,
304///                 aria_label: Some("PDF File Submit Button"),
305///                 event_handlers: None,
306///                 max_length: None,
307///                 min_length: None,
308///                 autocapitalize: false,
309///                 autocomplete: false,
310///                 autocorrect: false,
311///                 autofocus: false,
312///                 disabled: false,
313///                 hidden: false,
314///                 required: false,
315///                 multiple: false,
316///             },
317///             "f18"
318///         ),
319///         builder(
320///             "progress",
321///             "",
322///             InputProps {
323///                 id: Some("progress"),
324///                 name: None,
325///                 for_element: None,
326///                 typ: None,
327///                 value: Some("0"),
328///                 max: Some("100"),
329///                 placeholder: None,
330///                 pattern: None,
331///                 accept: None,
332///                 alt: None,
333///                 aria_label: Some("PDF File Submit Progress Bar"),
334///                 event_handlers: None,
335///                 max_length: None,
336///                 min_length: None,
337///                 autocapitalize: false,
338///                 autocomplete: false,
339///                 autocorrect: false,
340///                 autofocus: false,
341///                 disabled: false,
342///                 hidden: true,
343///                 required: false,
344///                 multiple: false,
345///             },
346///             ""
347///         ),
348///     ]
349/// }
350///
351/// let my_pages: UserPages = vec![
352///     ("myindex", index)
353/// ];
354/// let my_forms: Forms = vec![
355///     ("myform", upload_form)
356/// ];
357/// let expected = AppComponents {
358///     pages: Some(my_pages.clone()),
359///     forms: Some(my_forms.clone()),
360///     apis: None,
361///  };
362/// let result = rumtk_web_register_app_components!(my_pages, my_forms);
363///
364/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
365///
366/// ```
367///
368/// ### With Existing Page and Component and Form and API Endpoint
369/// ```
370/// use rumtk_core::{rumtk_pipeline_run_async, rumtk_pipeline_command};
371/// use rumtk_core::strings::{RUMString, RUMStringConversions, RUMArrayConversions};
372/// use rumtk_web::{rumtk_web_params_map, rumtk_web_post_process_html, APIPath, AppComponents, FormData, HTMLResult, RUMWebData, RUMWebResponse, SharedAppState};
373/// use rumtk_web::{rumtk_web_get_job_manager, rumtk_web_render_component, rumtk_web_render_page_contents};
374/// use rumtk_web::api::UserAPIEndpoints;
375/// use rumtk_web::pages::UserPages;
376/// use rumtk_web::components::form::{FormElementBuilder, FormElements, Forms};
377/// use rumtk_web::pages::index::index;
378/// use rumtk_web::components::form::props::InputProps;
379/// use rumtk_web::components::job_loader::{job_loader, JobLoader};
380/// use rumtk_web::jobs::{JobResult};
381/// use rumtk_web::utils::defaults::{PARAMS_TARGET, PARAMS_ID};
382/// use rumtk_web::ComponentResult;
383/// use rumtk_web::components::sanitize::sanitized;
384/// use rumtk_web::rumtk_web_register_app_components;
385///
386/// async fn upload_processor(form: FormData) -> JobResult {
387///     let id = form.form.get("file").unwrap();
388///     let file = form.files.get(id).unwrap();
389///
390///     let result = rumtk_pipeline_run_async!(
391///         &vec![
392///             rumtk_pipeline_command!("cat"),
393///             rumtk_pipeline_command!("wc")
394///         ],
395///         &file.clone()
396///     ).await?;
397///
398///     let sanitized = sanitized(result.to_vec().to_string()?);
399///     Ok(Some(sanitized?))
400/// }
401///
402/// pub fn process_upload(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
403///     let job_id = rumtk_web_get_job_manager!()?.spawn_task(upload_processor(form))?;
404///
405///    let params = rumtk_web_params_map!([(PARAMS_ID, job_id)]);
406///    let viewer = job_loader(&[], params.get_inner(), state)?.to_string();
407///
408///
409///     rumtk_web_render_page_contents!(
410///             &vec![
411///                 viewer
412///             ]
413///         )
414/// }
415///
416/// fn upload_form(builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
417///     vec![
418///         builder(
419///             "input",
420///             "",
421///             InputProps {
422///                 id: Some("file"),
423///                 name: Some("file"),
424///                 for_element: None,
425///                 typ: Some("file"),
426///                 value: None,
427///                 max: None,
428///                 placeholder: Some("path/to/file"),
429///                 pattern: None,
430///                 accept: Some(".pdf,application/pdf"),
431///                 alt: None,
432///                 aria_label: Some("PDF File Picker"),
433///                 event_handlers: None,
434///                 max_length: None,
435///                 min_length: None,
436///                 autocapitalize: false,
437///                 autocomplete: false,
438///                 autocorrect: false,
439///                 autofocus: false,
440///                 disabled: false,
441///                 hidden: false,
442///                 required: true,
443///                 multiple: false,
444///             },
445///             ""
446///         ),
447///         builder(
448///             "input",
449///             "",
450///             InputProps {
451///                 id: Some("submit"),
452///                 name: None,
453///                 for_element: None,
454///                 typ: Some("submit"),
455///                 value: Some("Send"),
456///                 max: None,
457///                 placeholder: None,
458///                 pattern: None,
459///                 accept: None,
460///                 alt: None,
461///                 aria_label: Some("PDF File Submit Button"),
462///                 event_handlers: None,
463///                 max_length: None,
464///                 min_length: None,
465///                 autocapitalize: false,
466///                 autocomplete: false,
467///                 autocorrect: false,
468///                 autofocus: false,
469///                 disabled: false,
470///                 hidden: false,
471///                 required: false,
472///                 multiple: false,
473///             },
474///             "f18"
475///         ),
476///         builder(
477///             "progress",
478///             "",
479///             InputProps {
480///                 id: Some("progress"),
481///                 name: None,
482///                 for_element: None,
483///                 typ: None,
484///                 value: Some("0"),
485///                 max: Some("100"),
486///                 placeholder: None,
487///                 pattern: None,
488///                 accept: None,
489///                 alt: None,
490///                 aria_label: Some("PDF File Submit Progress Bar"),
491///                 event_handlers: None,
492///                 max_length: None,
493///                 min_length: None,
494///                 autocapitalize: false,
495///                 autocomplete: false,
496///                 autocorrect: false,
497///                 autofocus: false,
498///                 disabled: false,
499///                 hidden: true,
500///                 required: false,
501///                 multiple: false,
502///             },
503///             ""
504///         ),
505///     ]
506/// }
507///
508/// let my_pages: UserPages = vec![
509///     ("myindex", index)
510/// ];
511/// let my_forms: Forms = vec![
512///     ("myform", upload_form)
513/// ];
514/// let my_endpoints: UserAPIEndpoints = vec![
515///     ("/api/upload", process_upload)
516/// ];
517/// let expected = AppComponents {
518///     pages: Some(my_pages.clone()),
519///     forms: Some(my_forms.clone()),
520///     apis: Some(my_endpoints.clone()),
521///  };
522/// let result = rumtk_web_register_app_components!(my_pages, my_forms, my_endpoints);
523///
524/// assert_eq!(result, expected, "Default macro-generated instance of AppComponents are not the same!");
525///
526/// ```
527///
528#[macro_export]
529macro_rules! rumtk_web_register_app_components {
530    (  ) => {{
531        use $crate::utils::app::AppComponents;
532        use std::sync::Arc;
533
534        Arc::new(AppComponents::default())
535    }};
536    ( $pages:expr ) => {{
537        use $crate::utils::app::AppComponents;
538        use std::sync::Arc;
539
540        Arc::new(AppComponents {
541            pages: Some($pages),
542            forms: None,
543            apis: None,
544        })
545    }};
546    ( $pages:expr, $forms:expr ) => {{
547        use $crate::utils::app::AppComponents;
548        use std::sync::Arc;
549
550        Arc::new(AppComponents {
551            pages: Some($pages),
552            forms: Some($forms),
553            apis: None,
554        })
555    }};
556    ( $pages:expr, $forms:expr, $apis:expr ) => {{
557        use $crate::utils::app::AppComponents;
558        use std::sync::Arc;
559
560        Arc::new(AppComponents {
561            pages: Some($pages),
562            forms: Some($forms),
563            apis: Some($apis),
564        })
565    }};
566}
567
568///
569/// Convenience macro for generating a [AppSwitches] instance containing the boolean options a
570/// framework consumer would like to opt-in.
571///
572/// ## Examples
573/// ```
574/// use rumtk_web::AppSwitches;
575/// use rumtk_web::{rumtk_web_register_app_switches};
576///
577/// let expected = AppSwitches {
578///     skip_serve: true,
579///     skip_default_css: false
580/// };
581/// let switches = rumtk_web_register_app_switches!(true);
582///
583/// assert_eq!(switches, expected, "The switches constructed to config app does not match the expected.");
584/// ```
585///
586#[macro_export]
587macro_rules! rumtk_web_register_app_switches {
588    (  ) => {{
589        use $crate::utils::app::AppSwitches;
590        use std::sync::Arc;
591
592        Arc::new(AppSwitches::default())
593    }};
594    ( $($switch:expr),+ ) => {{
595        use $crate::utils::app::AppSwitches;
596        use std::sync::Arc;
597
598        Arc::new(AppSwitches::from([$($switch),+]))
599    }};
600}
601
602///
603/// This is the main macro for defining your applet and launching it.
604/// Usage is very simple and the only decision from a user is whether to pass a list of
605/// [UserPages](UserPages) or a list of [UserPages](UserPages) and a list
606/// of [UserComponents](UserComponents).
607///
608/// These lists are used to automatically register your pages
609/// (e.g. `/index => ('index', my_index_function)`) and your custom components
610/// (e.g. `button => ('button', my_button_function)`
611///
612/// This macro will load CSS from predefined sources, concatenate their contents with predefined CSS,
613/// minified the concatenated results, and generate a bundle css file containing the minified results.
614/// The CSS bundle is written to file `./static/css/bundle.min.css`.
615///
616/// ***Note: anything in ./static will be considered static assets that need to be served.***
617///
618/// This macro will also parse the command line automatically with a few predefined options and
619/// use that information to override the config defaults.
620///
621/// By default, the app is launched to `127.0.0.1:3000` which is the loopback address.
622///
623/// App is served with the best compression algorithm allowed by the client browser.
624///
625/// For testing purposes, the function
626///
627/// ## Example Usage
628///
629/// ### With Page and Component definition
630/// ```
631///     use rumtk_core::strings::{rumtk_format};
632///     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};
633///     use rumtk_web::components::form::{FormElementBuilder, props::InputProps, FormElements};
634///     use rumtk_web::{SharedAppState, RenderedPageComponentsResult};
635///     use rumtk_web::{APIPath, URLPath, URLParams, HTMLResult, RUMString, RouterForm, FormData, RUMWebData, AppConf};
636///     use rumtk_web::components::portrait_card::portrait_card;
637///     use rumtk_web::components::spacer::spacer;
638///     use rumtk_web::components::text_card::text_card;
639///     use rumtk_web::components::title::title;
640///     use rumtk_web::ComponentResult;
641/// use rumtk_web::components::job_loader::JobLoader;
642///     use rumtk_web::defaults::{DEFAULT_TEXT_ITEM, PARAMS_CONTENTS, PARAMS_CSS_CLASS, PARAMS_TYPE};
643///     use rumtk_web::utils::types::RUMWebTemplate;
644///
645///
646///
647///
648///     // About page
649///     pub fn about(app_state: SharedAppState) -> RenderedPageComponentsResult {
650///         let title_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
651///         let title_coop = title(&[], title_coop_params.get_inner(), app_state.clone())?.to_string();
652///
653///         let title_team_params = rumtk_web_params_map!([(PARAMS_TYPE, "meet_the_team")]);
654///         let title_team = title(&[], title_team_params.get_inner(), app_state.clone())?.to_string();
655///
656///         let text_card_story_params = rumtk_web_params_map!([(PARAMS_TYPE, "story")]);
657///         let text_card_story = text_card(&[], text_card_story_params.get_inner(), app_state.clone())?.to_string();
658///
659///         let text_card_coop_params = rumtk_web_params_map!([(PARAMS_TYPE, "coop_values")]);
660///         let text_card_coop = text_card(&[], text_card_coop_params.get_inner(), app_state.clone())?.to_string();
661///
662///         let portrait_card_params = rumtk_web_params_map!([("section", "company"), (PARAMS_TYPE, "personnel")]);
663///         let portrait_card = portrait_card(&[], portrait_card_params.get_inner(), app_state.clone())?.to_string();
664///
665///         let spacer_5_params = rumtk_web_params_map!([("size", "5")]);
666///         let spacer_5 = spacer(&[], spacer_5_params.get_inner(), app_state.clone())?.to_string();
667///     
668///         Ok(vec![
669///             text_card_story,
670///             spacer_5.clone(),
671///             title_coop,
672///             text_card_coop,
673///             spacer_5,
674///             title_team,
675///             portrait_card
676///         ])
677///     }
678///
679///     //Custom component
680///     #[derive(RUMWebTemplate, Debug)]
681///     #[template(
682///             source = "
683///                {% if custom_css_enabled %}
684///                    <link href='/static/components/div.css' rel='stylesheet'>
685///                {% endif %}
686///                <div class='div-{{css_class}}'>{{contents|safe}}</div>
687///            ",
688///            ext = "html"
689///     )]
690///     struct MyDiv {
691///         contents: RUMString,
692///         css_class: RUMString,
693///         custom_css_enabled: bool,
694///     }
695///
696///     fn my_div(path_components: URLPath, params: URLParams, state: SharedAppState) -> ComponentResult<MyDiv> {
697///         let contents = rumtk_web_get_text_item!(params, PARAMS_CONTENTS, DEFAULT_TEXT_ITEM);
698///         let css_class = rumtk_web_get_text_item!(params, PARAMS_CSS_CLASS, DEFAULT_TEXT_ITEM);
699///
700///         let custom_css_enabled = rumtk_web_get_config!(state).flags.custom_css;
701///
702///         Ok(MyDiv {
703///             contents: RUMString::from(contents),
704///             css_class: RUMString::from(css_class),
705///             custom_css_enabled
706///         })
707///     }
708///
709///     fn my_form (builder: FormElementBuilder, _state: &SharedAppState) -> FormElements {
710///         vec![
711///             builder("input", "", InputProps::default(), "default")
712///         ]
713///     }
714///
715///     fn my_api_handler(path: APIPath, params: RUMWebData, form: FormData, state: SharedAppState) -> HTMLResult {
716///         Err(rumtk_format!(
717///             "No handler registered for API endpoint => {}",
718///             path
719///         ))
720///     }
721///
722///     //Requesting to immediately exit instead of indefinitely serving pages so this example can be used as a unit test.
723///     let skip_serve = true;
724///     let skip_default_css = false;
725///
726///     let app_components = rumtk_web_register_app_components!(
727///         vec![("about", about)],
728///         vec![("my_form", my_form)], //Optional, can be omitted alongside the skip_serve flag
729///         vec![("v2/add", my_api_handler)] //Optional, can be omitted alongside the skip_serve flag
730///     );
731///     let app_switches = rumtk_web_register_app_switches!(
732///         skip_serve, //Omit in production code. This is used so that this example can work as a unit test.
733///         skip_default_css //Omit in production code. This is used so that this example can work as a unit test.
734///     );
735///     let result = rumtk_web_run_app!(
736///         app_components,
737///         app_switches
738///     );
739/// ```
740///
741/// ## Signatures & Usages
742///
743/// This is a complex macro that is trying to be backwards compatible with the old prescribed way
744/// of producing a web applet. It is also trying to allow future applets to specify new flags and even
745/// a closure hook to perform further initialization of the framework based on the new flags.
746///
747/// Below are the supported macro signatures:
748///
749///     - ()
750///     - ( pretty: bool )
751///     - ( pretty: bool, app_components )
752///     - ( pretty: bool, app_components, app_switches )
753///     - ( pretty: bool, app_components, app_switches, |_args: &RUMTKInterfaceArgs, _app_components: &$crate::utils::app::SafeAppComponents, _app_switches: &$crate::utils::app::SafeAppSwitches | -> rumtk_core::base::RUMResult<()> { Ok(()) } )
754///     - ( app_components )
755///     - ( app_components, app_switches )
756///     - ( app_components, app_switches, |_args: &RUMTKInterfaceArgs, _app_components: &$crate::utils::app::SafeAppComponents, _app_switches: &$crate::utils::app::SafeAppSwitches | -> rumtk_core::base::RUMResult<()> { Ok(()) } )
757///
758#[macro_export]
759macro_rules! rumtk_web_run_app {
760    (
761        [
762            $(
763                $(#[$field_meta:meta])*
764                $field_name:ident : $field_typ:ty
765            ),* $(,)?
766        ],
767        $app_components:expr,
768        $switches:expr,
769        $hook:expr $(,)?
770    ) => {{
771        $crate::rumtk_web_run_app!(
772            @collect [$($(#[$field_meta])* $field_name : $field_typ,)*],
773            $app_components,
774            $switches,
775            $hook
776        )
777    }};
778    (
779        [
780            $(
781                $(#[$field_meta:meta])*
782                $field_name:ident : $field_typ:ty
783            ),* $(,)?
784        ],
785        $app_components:expr,
786        $switches:expr $(,)?
787    ) => {{
788        $crate::rumtk_web_run_app!(
789            [$($(#[$field_meta])* $field_name : $field_typ),*],
790            $app_components,
791            $switches,
792            |
793                _args: &RUMTKInterfaceArgs,
794                _app_components: &$crate::utils::app::SafeAppComponents,
795                _app_switches: &$crate::utils::app::SafeAppSwitches
796            | -> rumtk_core::base::RUMResult<()> { Ok(()) }
797        )
798    }};
799    (
800        [
801            $(
802                $(#[$field_meta:meta])*
803                $field_name:ident : $field_typ:ty
804            ),* $(,)?
805        ],
806        $app_components:expr $(,)?
807    ) => {{
808        $crate::rumtk_web_run_app!(
809            [$($(#[$field_meta])* $field_name : $field_typ),*],
810            $app_components,
811            $crate::rumtk_web_register_app_switches!()
812        )
813    }};
814    (
815        [
816            $(
817                $(#[$field_meta:meta])*
818                $field_name:ident : $field_typ:ty
819            ),* $(,)?
820        ] $(,)?
821    ) => {{
822        $crate::rumtk_web_run_app!(
823            [$($(#[$field_meta])* $field_name : $field_typ),*],
824            $crate::rumtk_web_register_app_components!()
825        )
826    }};
827    (
828    ) => {{
829        $crate::rumtk_web_run_app!([])
830    }};
831    (
832        $app_components:expr,
833        $switches:expr,
834        $hook:expr $(,)?
835    ) => {{
836        $crate::rumtk_web_run_app!([], $app_components, $switches, $hook)
837    }};
838    (
839        $app_components:expr,
840        $switches:expr $(,)?
841    ) => {{
842        $crate::rumtk_web_run_app!([], $app_components, $switches)
843    }};
844    (
845        $app_components:expr $(,)?
846    ) => {{
847        $crate::rumtk_web_run_app!([], $app_components)
848    }};
849    (
850        @collect [$($cli_args:tt)*],
851        $app_components:expr,
852        $switches:expr,
853        $hook:expr $(,)?
854    ) => {{
855        use rumtk_core::base::RUMResult;
856        use rumtk_core::strings::RUMString;
857        use rumtk_core::{rumtk_cli_process, rumtk_resolve_task};
858        use $crate::{
859            rumtk_web_load_conf, rumtk_web_init_pages, rumtk_web_init_forms,
860            rumtk_web_init_api_endpoints, rumtk_web_compile_css_bundle,
861            rumtk_web_init_job_manager
862        };
863        use $crate::utils::app::{
864            DEFAULT_OUT_CSS_DIR,
865            DEFAULT_LOCAL_LISTENING_ADDRESS,
866            DEFAULT_UPLOAD_LIMIT
867        };
868        use $crate::utils::app::{
869            SafeAppComponents,
870            SafeAppSwitches
871        };
872        use $crate::utils::app::run_app;
873
874        let app_components: SafeAppComponents = $app_components.clone();
875        let switches: SafeAppSwitches = $switches.clone();
876
877        rumtk_cli_process!(
878            @collect [$($cli_args)*]
879            ///
880            /// Website title to use internally. It can be omitted if defined in the app.json config file
881            /// bundled with your app.
882            ///
883            #[arg(long, default_value = "")]
884            title: RUMString,
885            ///
886            /// Website description string. It can be omitted if defined in the app.json config file
887            /// bundled with your app.
888            ///
889            #[arg(long, default_value = "")]
890            description: RUMString,
891            ///
892            /// Company to display in website.
893            ///
894            #[arg(long, default_value = "")]
895            company: RUMString,
896            ///
897            /// Copyright year to display in website.
898            ///
899            #[arg(short, long, default_value = "")]
900            copyright: RUMString,
901            ///
902            /// Directory to scan on startup to find custom CSS sources to bundle into a minified CSS file
903            /// that can be quickly pulled by the app client side.
904            ///
905            /// This option can provide an alternative to direct component retrieval of CSS fragments.
906            /// Meaning, you could bundle all of your fragments into the master bundle at startup and
907            /// turn off component level ```custom_css_enabled``` option in the ```app.json``` config.
908            ///
909            #[arg(long, default_value = DEFAULT_OUT_CSS_DIR)]
910            css_source_dir: RUMString,
911            ///
912            /// Is the interface meant to be bound to the loopback address and remain hidden from the
913            /// outside world.
914            ///
915            /// It follows the format ```IPv4:port``` and it is a string.
916            ///
917            /// If a NIC IP is defined via `--ip`, that value will override this flag.
918            ///
919            #[arg(short, long, default_value = DEFAULT_LOCAL_LISTENING_ADDRESS)]
920            ip: RUMString,
921            ///
922            /// Specify the size limit for a file upload post request.
923            ///
924            #[arg(long, default_value_t = DEFAULT_UPLOAD_LIMIT)]
925            upload_limit: usize,
926            ///
927            /// How many threads to use to serve the website. By default, we use
928            /// ```get_default_system_thread_count()``` from ```rumtk-core``` to detect the total count of
929            /// cpus available. We use the system's total count of cpus by default.
930            ///
931            #[arg(long, default_value_t = false)]
932            skip_default_css: bool,
933            Direct(|args: &RUMTKInterfaceArgs| -> RUMResult<()> {
934                let state = rumtk_web_load_conf!(&*args);
935
936                rumtk_web_init_pages!(app_components.pages.clone());
937                rumtk_web_init_forms!(app_components.forms.clone(), state);
938                rumtk_web_init_api_endpoints!(app_components.apis.clone());
939                rumtk_web_compile_css_bundle!(
940                    &args.css_source_dir,
941                    &args.skip_default_css | switches.skip_default_css
942                );
943
944                rumtk_web_init_job_manager!(&args.threads);
945
946                ($hook)(args, &app_components, &switches)?;
947
948                let task = run_app(args.ip.clone(), state, switches.clone());
949                rumtk_resolve_task!(task)
950            })
951        );
952    }};
953}