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
use std::{
    any::Any,
    cmp::PartialEq,
    collections::BTreeSet,
    rc::Rc,
};

use crate::{
    computed::{Computed, GraphId, GraphValueRefresh, Value},
    utils::{EqBox},
};

use super::value::ToRc;

mod external_connections;
mod graph;
mod graph_map;
pub mod hook;
mod refresh;
pub mod refresh_edges;
mod stack;
mod transaction_state;

use {
    external_connections::ExternalConnections,
    graph::Graph,
    stack::Stack,
    transaction_state::TransactionState,
    refresh::Refresh,
};

/// A graph of values and clients that can automatically compute what to refresh after one value change.
///
/// A [Driver](struct.Driver.html) object wrapps dependency graph, so you do not need to use this under normal circumstances.
///
/// - Dependency graph holds values, computed values ([computeds](struct.Computed.html)) and clients (render functions).
/// - Upon changing some value all dependent computeds get computed, and all dependent clients get rendered.
/// - Render function (a component) takes a computed state provided by the graph and returns a rendered element ([VDomElement](struct.VDomElement.html)).
/// - Upon change in VDOM the real DOM is also updated.
/// - Components can provide the DOM with functions that get fired on events like [on_click](struct.VDomElement.html#structfield.on_click), which may modify the state, thus triggering necessary computing once again.
#[derive(PartialEq)]
pub struct Dependencies {
    graph: Rc<EqBox<Graph>>,
    stack: Rc<EqBox<Stack>>,
    refresh: Rc<EqBox<Refresh>>,
    transaction_state: Rc<EqBox<TransactionState>>,
    external_connections: ExternalConnections,
}

impl Clone for Dependencies {
    fn clone(&self) -> Self {
        Dependencies {
            graph: self.graph.clone(),
            stack: self.stack.clone(),
            refresh: self.refresh.clone(),
            transaction_state: self.transaction_state.clone(),
            external_connections: self.external_connections.clone(),
        }
    }
}

impl Default for Dependencies {
    fn default() -> Self {
        let external_connections = ExternalConnections::default();
        let refresh: Refresh = Refresh::new();

        Self {
            graph: Rc::new(EqBox::new(
                Graph::new(external_connections.clone(), refresh.clone()),
            )),
            stack: Rc::new(EqBox::new(Stack::new())),
            refresh: Rc::new(EqBox::new(refresh)),
            transaction_state: Rc::new(EqBox::new(
                TransactionState::new()
            )),
            external_connections,
        }
    }
}

impl Dependencies {
    pub fn new_value<T: PartialEq>(&self, value: impl ToRc<T>) -> Value<T> {
        Value::new(self.clone(), value)
    }

    pub fn new_with_connect<T, F>(&self, value: T, create: F) -> Computed<T>
    where
        T: PartialEq,
        F: Fn(&Value<T>) -> Box<dyn Any> + 'static
    {
        Value::<T>::new_selfcomputed_value::<F>(self.clone(), value, create)
    }

    pub fn new_computed_from<T: PartialEq>(&self, value: impl ToRc<T>) -> Computed<T> {
        let value = self.new_value(value);
        value.to_computed()
    }

    pub fn set_hook(&self, before_start: Box<dyn Fn()>, after_end: Box<dyn Fn()>) {
        self.transaction_state.set_hook(before_start, after_end);
    }

    pub fn transaction<F: FnOnce()>(&self, func: F) {
        let success = self.transaction_state.up();

        if !success {
            return;
        }

        func();

        let edges_values = self.transaction_state.down();

        if let Some(edges_values) = edges_values {
            let edges_to_refresh = self.get_edges_to_refresh(edges_values);

            refresh_edges::refresh_edges(self, edges_to_refresh);

            self.transaction_state.move_to_idle();
        }
    }

    fn get_edges_to_refresh(&self, edges: BTreeSet<GraphId>) -> Vec<GraphValueRefresh> {
        let mut result = Vec::new();

        for id in self.get_all_deps(edges) {
            if let Some(item) = self.refresh_get(&id) {
                result.push(item);
            } else {
                log::error!("Missing refresh token for(1) {:?}", id);
            }
        }

        result
    }

    fn get_all_deps(&self, edges: BTreeSet<GraphId>) -> BTreeSet<GraphId> {
        self.graph.get_all_deps(edges)
    }

    pub(crate) fn trigger_change(&self, parent_id: GraphId) {
        self.transaction_state.add_edge_to_refresh(parent_id);
    }

    pub(crate) fn add_graph_connection(&self, parent_id: &BTreeSet<GraphId>, client_id: GraphId) {
        self.graph.add_graph_connection(parent_id, client_id);
    }

    pub(crate) fn remove_graph_connection(&self, parent_id: &BTreeSet<GraphId>, client_id: GraphId) {
        self.graph.remove_graph_connection(parent_id, client_id);
    }

    pub(crate) fn refresh_token_add(&self, graph_value: GraphValueRefresh) {
        self.refresh.refresh_token_add(graph_value);
    }

    pub(crate) fn refresh_token_drop(&self, id: GraphId) {
        self.refresh.refresh_token_drop(id);
    }

    pub(crate) fn start_track(&self) {
        self.stack.start_track();
    }

    pub(crate) fn report_parent_in_stack(&self, parent_id: GraphId) {
        self.stack.report_parent_in_stack(parent_id);
    }

    pub(crate) fn stop_track(&self) -> BTreeSet<GraphId> {
        self.stack.stop_track()
    }

    pub fn from<T: PartialEq + 'static, F: Fn() -> T + 'static>(&self, calculate: F) -> Computed<T> {
        let deps = self.clone();
        Computed::new(deps, move || Rc::new(calculate()))
    }

    pub fn all_connections_len(&self) -> u64 {
        self.graph.all_connections_len()
    }

    pub fn all_connections(&self) -> Vec<(GraphId, GraphId, u8)> {
        self.graph.all_connections()
    }

    pub fn has_listeners(&self, parent_id: &GraphId) -> bool {
        self.graph.has_listeners(parent_id)
    }

    pub fn refresh_get(&self, id: &GraphId) -> Option<GraphValueRefresh> {
        self.refresh.get(id)
    }

    pub fn external_connections_register_connect(&self, id: GraphId, connect: Rc<dyn Fn() -> Box<dyn Any>>) {
        self.external_connections.register_connect(id, connect);
    }

    pub fn external_connections_unregister_connect(&self, id: GraphId) {
        self.external_connections.unregister_connect(id);
    }

    pub fn external_connections_refresh(&self) {
        if self.transaction_state.is_idle() {
            self.external_connections.refresh_connect();
        }
    }
}