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
//! Logging [Middleware](crate::middleware::Middleware) for
//! applications running in the browser using `wasm-bindgen`.
//! Publishes actions/events that occur within the
//! [Store](crate::Store).

use super::{Middleware, ReduceMiddlewareResult};
use crate::StoreEvent;
use serde::Serialize;
use std::{fmt::Display, hash::Hash};
use wasm_bindgen::JsValue;
use web_sys::console;

pub enum LogLevel {
    Trace,
    Debug,
    Warn,
    Info,
    Log,
}

impl LogLevel {
    pub fn log(&self, message: &JsValue) {
        match self {
            LogLevel::Trace => console::trace_1(message),
            LogLevel::Debug => console::debug_1(message),
            LogLevel::Warn => console::warn_1(message),
            LogLevel::Info => console::info_1(message),
            LogLevel::Log => console::log_1(message),
        }
    }
}

impl Default for LogLevel {
    fn default() -> Self {
        LogLevel::Log
    }
}

/// Logging middleware for applications running in the browser.
/// 
/// See [web_logger](super::web_logger) for more details.
pub struct WebLoggerMiddleware {
    log_level: LogLevel,
}

impl WebLoggerMiddleware {
    pub fn new() -> Self {
        Self {
            log_level: LogLevel::default(),
        }
    }

    pub fn log_level(mut self, log_level: LogLevel) -> Self {
        self.log_level = log_level;
        self
    }
}

impl Default for WebLoggerMiddleware {
    fn default() -> Self {
        WebLoggerMiddleware::new()
    }
}

impl<State, Action, Event, Effect> Middleware<State, Action, Event, Effect> for WebLoggerMiddleware
where
    State: Serialize,
    Action: Serialize + Display,
    Event: StoreEvent + Clone + Hash + Eq + Serialize,
    Effect: Serialize,
{
    fn on_reduce(
        &self,
        store: &crate::Store<State, Action, Event, Effect>,
        action: Option<&Action>,
        reduce: super::ReduceFn<State, Action, Event, Effect>,
    ) -> ReduceMiddlewareResult<Event, Effect> {
        let prev_state_js = JsValue::from_serde(&(*store.state())).unwrap();

        // TODO: what will happen when action is None?
        let action_js = JsValue::from_serde(&action).unwrap();
        let action_display = match &action {
            Some(action) => format!("{}", action),
            None => "None".to_string(),
        };

        let result = reduce(store, action);
        let next_state_js = JsValue::from_serde(&(*store.state())).unwrap();

        let effects_js = JsValue::from_serde(&result.effects).unwrap();
        let effects_display = match &result.effects.len() {
            0 => "None".to_string(),
            _ => format!("({})", result.effects.len()),
        };

        console::group_collapsed_3(
            &JsValue::from_serde(&format!("%caction %c{}", action_display)).unwrap(),
            &JsValue::from_str("color: gray; font-weight: lighter;"),
            &JsValue::from_str("inherit"),
        );
        console::group_collapsed_2(
            &JsValue::from_str("%cprev state"),
            &JsValue::from_str("color: #9E9E9E; font-weight: bold;"),
        );
        self.log_level.log(&prev_state_js);
        console::group_end();

        console::group_collapsed_3(
            &JsValue::from_str(&format!("%caction: %c{}", action_display)),
            &JsValue::from_str("color: #03A9F4; font-weight: bold;"),
            &JsValue::from_str("color: gray; font-weight: lighter;"),
        );
        self.log_level.log(&action_js);
        console::group_end();

        console::group_collapsed_2(
            &JsValue::from_str("%cnext state"),
            &JsValue::from_str("color: #4CAF50; font-weight: bold;"),
        );
        self.log_level.log(&next_state_js);
        console::group_end();

        console::group_collapsed_3(
            &JsValue::from_str(&format!("%ceffects: %c{}", effects_display)),
            &JsValue::from_str("color: #C210C2; font-weight: bold;"),
            &JsValue::from_str("color: gray; font-weight: lighter;"),
        );
        self.log_level.log(&effects_js);
        console::group_end();

        result
    }

    fn process_effect(
        &self,
        _store: &crate::Store<State, Action, Event, Effect>,
        effect: Effect,
    ) -> Option<Effect> {
        Some(effect)
    }

    fn on_notify(
        &self,
        store: &crate::Store<State, Action, Event, Effect>,
        events: Vec<Event>,
        notify: super::NotifyFn<State, Action, Event, Effect>,
    ) -> Vec<Event> {
        let events_js = JsValue::from_serde(&events).unwrap();
        let events_display = match events.len() {
            0 => "None".to_string(),
            _ => format!("({})", events.len()),
        };
        console::group_collapsed_3(
            &JsValue::from_str(&format!("%cevents: %c{}", events_display)),
            &JsValue::from_str("color: #FCBA03; font-weight: bold;"),
            &JsValue::from_str("color: gray; font-weight: lighter;"),
        );
        self.log_level.log(&events_js);
        console::group_end();
        console::group_end();
        notify(store, events)
    }
}