Skip to main content

flams_web_utils/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![recursion_limit = "256"]
3
4pub mod components;
5pub mod mathml;
6
7#[cfg(feature = "ssr")]
8/// #### Errors
9pub async fn blocking_server_fn<T: Send + 'static>(
10    f: impl FnOnce() -> Result<T, String> + Send + 'static,
11) -> Result<T, leptos::prelude::ServerFnError<String>> {
12    tokio::task::spawn_blocking(f)
13        .await
14        .map_err(|e| e.to_string())?
15        .map_err(Into::into)
16}
17
18#[macro_export]
19macro_rules! console_log {
20    () => {};
21    ($arg:expr) => {
22        ::web_sys::console::log_1(&::web_sys::js_sys::JsValue::from($l))
23    };
24    ($arg1:expr,$arg2:expr) => {
25        ::web_sys::console::log_2(
26            &::web_sys::js_sys::JsValue::from($l),
27            &::web_sys::js_sys::JsValue::from($l),
28        )
29    };
30}
31
32/// # Errors
33pub fn try_catch<R>(run: impl FnOnce() -> R) -> Result<R, leptos::wasm_bindgen::JsError> {
34    std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).map_err(|e| {
35        if let Some(s) = e.downcast_ref::<&str>() {
36            return leptos::wasm_bindgen::JsError::new(*s);
37        }
38        if let Some(s) = e.downcast_ref::<String>() {
39            return leptos::wasm_bindgen::JsError::new(s);
40        }
41        leptos::wasm_bindgen::JsError::new("Box<dyn Error>")
42    })
43}
44
45#[cfg(feature = "ssr")]
46pub use http;
47#[cfg(feature = "ssr")]
48pub use leptos_axum;
49
50#[cfg(feature = "ssr")]
51#[macro_export]
52macro_rules! not_found{
53    () => {
54        let response = expect_context::<$crate::leptos_axum::ResponseOptions>();
55        response.set_status($crate::http::StatusCode::NOT_FOUND);
56    };
57    (! $($e:tt)*) => { {
58        let response = expect_context::<$crate::leptos_axum::ResponseOptions>();
59        response.set_status($crate::http::StatusCode::NOT_FOUND);
60        format!($($e)*).into()
61    }};
62    ($($e:tt)*) => { return Err(not_found!(! $($e)*))};
63}