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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use crate::store::Reaction;
use crate::reactive_state_functions::*;
use std::marker::PhantomData;
use crate::observable::Observable;
use crate::store::StorageKey;
// use seed::prelude::*;
// marker types
pub enum AllowUndo{}
pub enum NoUndo{}
pub  enum IsAnAtomState{}
pub  enum IsAReactionState{}

///  Accessor struct that provides access to getting and setting the
///  state of the stored type
///
// #[derive(Copy)]
pub struct ReactiveStateAccess<T,U,A> {
    pub id: StorageKey,

    pub _phantom_data_stored_type: PhantomData<T>,
    pub _phantom_data_undo : PhantomData<U>,
    pub _phantom_data_accessor_type : PhantomData<A>,
}

impl<T,U,A> std::fmt::Debug for ReactiveStateAccess<T,U,A> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({:#?})", self.id)
    }
}
// 
impl<T,U,A> Clone for ReactiveStateAccess<T,U,A> {
    fn clone(&self) -> ReactiveStateAccess<T,U,A> {
        ReactiveStateAccess::<T,U,A> {
            id: self.id,
            
            _phantom_data_stored_type: PhantomData::<T>,
            _phantom_data_undo : PhantomData::<U>,
            _phantom_data_accessor_type : PhantomData::<A>,
        }
    }
}


impl<T,U,A> Copy for ReactiveStateAccess<T,U,A> {}

impl<T,U,A> ReactiveStateAccess<T,U,A>
where
    T: 'static,
{
    pub fn new(id: StorageKey) -> ReactiveStateAccess<T,U,A> {
        ReactiveStateAccess {
            id,
            
            _phantom_data_stored_type: PhantomData,
            _phantom_data_undo: PhantomData,
            _phantom_data_accessor_type: PhantomData,
        }
    }

    // stores a value of type T in a backing Store
    pub fn insert_set(self, value: T) where Self :OverloadedUpdateStateAccess<T>{
        self.overloaded_inert_set(value);
    }


    // stores a value of type T in a backing Store
    pub fn set(self, value: T) where Self :OverloadedUpdateStateAccess<T>{
        self.overloaded_set(value);
    }



    pub fn remove(self) -> Option<T> {
        remove_reactive_state_with_id(&self.id)
    }

    pub fn delete(self) {
        self.remove();
    }


    pub fn undo(&self) where Self: OverloadedUpdateStateAccess<T> {
        self.overloaded_undo();
    }

    /// updates the stored state in place
    /// using the provided function
    pub fn update<F: FnOnce(&mut T) -> ()>(&self, func: F) where Self :OverloadedUpdateStateAccess<T>{
        self.overloaded_update( func); 
    }

    pub fn reset_to_default(&self) where Self :OverloadedUpdateStateAccess<T>{
        self.overloaded_reset_to_default(); 
    }


    pub fn state_exists(self) -> bool {
        reactive_state_exists_for_id::<T>(&self.id)
    }

    pub fn get_with<F: FnOnce(&T) -> R, R>(&self, func: F) -> R {
        read_reactive_state_with_id(&self.id, func)
    }



    pub fn on_update<F: FnOnce() -> R,R>(&self, func:F) -> Option<R> {
        let mut recalc = false ;
        self.observe_with(|_| recalc = true);
        if recalc {
            Some(func())
        } else {
            None
        }
    }


}


// If the stored type is clone, then implement clone for ReactiveStateAccess
pub trait CloneReactiveState<T>
where
    T: Clone + 'static,
{
    fn get(&self) -> T;
    fn soft_get(&self) -> Option<T>;
}

impl<T,U,A> CloneReactiveState<T> for ReactiveStateAccess<T,U,A>
where
    T: Clone + 'static,
{
    /// returns a clone of the stored state panics if not stored.
    fn get(&self) -> T {
        clone_reactive_state_with_id::<T>(&self.id).expect("state should be present")
    }

    fn soft_get(&self) -> Option<T> {
        clone_reactive_state_with_id::<T>(&self.id)
    }
}

// If the accessor type is Atom, and Undo type is Allow Undo, then 
// ensure that updates cause an undo to be appended.
pub trait  OverloadedUpdateStateAccess<T> where T:'static {
    fn overloaded_update<F: FnOnce(&mut T) -> ()>(&self, func: F);
    fn overloaded_reset_to_default(&self);   
    fn overloaded_undo(&self);
    fn overloaded_inert_set(self, value: T);      
    fn overloaded_set(self, value: T);
}


impl <T> OverloadedUpdateStateAccess<T> for ReactiveStateAccess<T,NoUndo,IsAnAtomState> where T:'static
{
    fn overloaded_undo(&self){
        panic!("cannot undo this atom is not undoable");
    }


    fn overloaded_reset_to_default(&self){
        // execute_reaction_nodes(&self.id);
        (clone_reactive_state_with_id::<Reaction>(&self.id).unwrap().func)();
        execute_reaction_nodes(&self.id);
    
    }

    
        
    fn overloaded_update<F: FnOnce(&mut T) -> ()>(&self, func: F) {

        update_atom_state_with_id(&self.id, func);

    }

    fn overloaded_inert_set(self, value: T) {
        set_inert_atom_state_with_id(value, &self.id);
    }

    fn overloaded_set(self, value: T) {
        set_atom_state_with_id(value, &self.id);
    }
}


impl <T> OverloadedUpdateStateAccess<T> for ReactiveStateAccess<T,AllowUndo,IsAnAtomState>
where T:Clone + 'static,
{

    fn overloaded_reset_to_default(&self){
        (clone_reactive_state_with_id::<Reaction>(&self.id).unwrap().func)();
        execute_reaction_nodes(&self.id);
    }

    fn overloaded_undo(&self){
        
        undo_atom_state::<T,AllowUndo,IsAnAtomState>(&self.id)
    }

    fn overloaded_update<F: FnOnce(&mut T) -> ()>(&self, func: F) {
        update_atom_state_with_id_with_undo(&self.id, func);
    }

    fn overloaded_inert_set(self, value: T) {
        set_inert_atom_state_with_id_with_undo(value, &self.id);
    }

    fn overloaded_set(self, value: T) {
        set_atom_state_with_id_with_undo(value, &self.id);
    }
}



// If the underlying stored type is Clone and PartialEq
// `changed()` will return true the first time called and then false
// if called again with the same content.
#[derive(Clone)]
struct ChangedWrapper<T>(T);

pub trait ChangedAtomState {
    fn changed(&self) -> bool;
}

impl<T,U,A> ChangedAtomState for ReactiveStateAccess<T,U,A>
where
    T: Clone + 'static + PartialEq,
{
    fn changed(&self) -> bool {
        if reactive_state_exists_for_id::<ChangedWrapper<T>>(&self.id){
            read_reactive_state_with_id::<ChangedWrapper<T>,_,_>(&self.id, |old|
                self.get_with(|current| &old.0==current )
            )
        } else {
            set_inert_atom_state_with_id(ChangedWrapper(self.get()), &self.id);
            true
        }
    }
}
// If the underlying type provides display then so does the ReactiveStateAccess
impl<T,U,A> std::fmt::Display for ReactiveStateAccess<T,U,A>
where
    T: std::fmt::Display + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.get_with(|t| write!(f, "{}", t))
    }
}

use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Sub;

impl<T,U,A> Add for ReactiveStateAccess<T,U,A>
where
    T: Copy + Add<Output = T> + 'static,
{
    type Output = T;

    fn add(self, other: Self) -> Self::Output {
        self.get_with(|s| other.get_with(|o| *o + *s))
    }
}

impl<T,U,A> Mul for ReactiveStateAccess<T,U,A>
where
    T: Copy + Mul<Output = T> + 'static,
{
    type Output = T;

    fn mul(self, other: Self) -> Self::Output {
        self.get_with(|s| other.get_with(|o| *o * *s))
    }
}

impl<T,U,A> Div for ReactiveStateAccess<T,U,A>
where
    T: Copy + Div<Output = T> + 'static,
{
    type Output = T;

    fn div(self, other: Self) -> Self::Output {
        self.get_with(|s| other.get_with(|o| *o / *s))
    }
}

impl<T,U,A> Sub for ReactiveStateAccess<T,U,A>
where
    T: Copy + Sub<Output = T> + 'static,
{
    type Output = T;

    fn sub(self, other: Self) -> Self::Output {
        self.get_with(|s| other.get_with(|o| *o - *s))
    }
}