ianaio_console/
console_dbg.rs

1/// A macro similar to [`dbg!`] that logs [`JsValue`][wasm_bindgen::JsValue]s to console.
2///
3/// See the [stdlib documentation][std::dbg] to learn more. This macro calls `console.log`
4/// instead of `eprintln!` for `JsValue`s. The formatting is done by the browser. If you want
5/// [`Debug`][std::fmt::Debug] implementation to be used instead, consider using [`console_dbg`]
6#[macro_export]
7macro_rules! console {
8    () => {
9        $crate::log!(
10            ::std::format!("%c[{}:{}] ", ::std::file!(), ::std::line!()),
11            "font-weight: bold"
12        );
13    };
14    ($val:expr $(,)?) => {
15        {
16            let v = $val;
17            $crate::__console_inner!(v $val)
18        }
19    };
20    ($($val:expr),+ $(,)?) => {
21        ($($crate::console!($val)),+,)
22    };
23}
24
25/// A macro similar to [`dbg!`] to log to browser console.
26///
27/// See the [stdlib documentation][std::dbg] to learn more. This macro calls `console.log`
28/// instead of `eprintln!`. This macro passing the values to [`console`] after formatting them using
29/// the [`Debug`][std::fmt::Debug] implementation.
30#[macro_export]
31macro_rules! console_dbg {
32    () => {
33        $crate::console!()
34    };
35    ($val:expr $(,)?) => {
36        {
37            let v: $crate::__macro::JsValue = ::std::format!("{:?}", $val).into();
38            $crate::__console_inner!(v $val)
39        }
40    };
41    ($($val:expr),+ $(,)?) => {
42        ($($crate::console_dbg!($val)),+,)
43    };
44}
45
46/// This is an implementation detail and *should not* be called directly!
47#[doc(hidden)]
48#[macro_export]
49macro_rules! __console_inner {
50    ($js_value:ident $val:expr) => {{
51        $crate::log!(
52            ::std::format!("%c[{}:{}] ", ::std::file!(), ::std::line!()),
53            "font-weight: bold",
54            ::std::format!("{} = ", ::std::stringify!($val)),
55            &$js_value
56        );
57        $js_value
58    }};
59}
60
61#[cfg(test)]
62mod tests {
63    #![allow(dead_code)]
64    //! These exist to ensure code compiles
65    use wasm_bindgen::JsValue;
66
67    fn console_works() {
68        console!();
69        {
70            let js_value = JsValue::from("test");
71            console!(js_value);
72        }
73        {
74            let js_value_1 = JsValue::from("test 1");
75            let js_value_2 = JsValue::from("test 2");
76            console!(js_value_1, js_value_2);
77        }
78    }
79
80    fn console_dbg_works() {
81        #[derive(Debug)]
82        struct Value(&'static str);
83
84        console_dbg!();
85        {
86            let value = Value("test");
87            console_dbg!(value);
88        }
89        {
90            let value_1 = Value("test 1");
91            let value_2 = Value("test 2");
92            console_dbg!(value_1, value_2);
93        }
94    }
95}