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
299
300
301
302
303
304
305
306
307
308
309
310
use std::{any::Any, marker::PhantomData, panic::Location};

use crate::{
    renderer::Scheduler,
    shared::Shared,
    tracked,
    tree::NodeId,
    vdom::{
        update_vnode,
        wrappers::{ComponentStateAccess, SharedBox},
        VDom, VNode,
    },
    ComponentPos, Tracked,
};

#[derive(Copy, Clone, PartialEq, Debug)]
pub(crate) struct Gen {
    pub(crate) gen: u32,
}

// TODO: support wrap edge cases
impl Gen {
    pub(crate) fn next(mut self) -> Self {
        self.inc();
        Gen { gen: self.gen }
    }

    pub(crate) fn inc(&mut self) {
        self.gen = self.gen.wrapping_add(1);
    }

    pub(crate) fn updated(self, current_gen: Gen) -> bool {
        self.gen >= current_gen.gen
    }
}

/// Provides a hook with component-specific state.
/// 
/// Accessed by passing `self` as the first parameter in a hook call.
#[derive(Clone, Copy)]
pub struct Context<'a> {
    pub(crate) gen: Gen,
    pub(crate) state: &'a Shared<ComponentStateAccess<'a>>,
    pub(crate) component_pos: ComponentPos<'a>,
    pub(crate) scheduler: &'a Shared<dyn Scheduler>,
}

struct State<T: 'static> {
    val: T,
    gen: Gen,
}

#[track_caller]
fn internal_state<'a, T: 'static>(
    ctx: Context<'a>,
    f: impl FnOnce() -> T,
) -> (&'a dyn Any, Location<'static>) {
    let location = Location::caller();
    let state_ref = ctx.state.exec_mut(|state| {
        state.get_or_insert_with(*location, move || {
            SharedBox::new(Box::new(State {
                val: f(),
                gen: ctx.gen.next(),
            }))
        })
    });
    (state_ref, *location)
}

/// A hook that allows a component to keep persistent state across renders.
///
/// `state` takes a type parameter `T` specifying the type of the state variable the hook manages, as well as
/// a parameter `F` specifying the type of a function providing a default value for `T`.
/// On first call, the given state will be initialized with `f`; it will not be called on subsequent calls of the same
/// `state` call site.
/// The return value contains a tracked reference to the current state,
/// and the setter [StateSetter](StateSetter). `&T`'s lifetime is only valid within the component's render
/// function, but [StateSetter](StateSetter) may be freely moved and cloned.
///
/// To update the state, use the [set](StateSetter::set) or [update](StateSetter::update) methods on the setter variable.
///
/// # Example
/// ```rust
/// use avalanche::{component, tracked, View, state};
/// use avalanche_web::components::{Div, H2, Button, Text};
///
/// #[component]
/// fn Counter() -> View {
///     let (count, set_count) = state(self, || 0);
///     Div!(
///         children: [
///             H2!(
///                 child: Text!("Counter!"),
///             ),
///             Button!(
///                 on_click: move |_| set_count.update(|count| *count += 1),
///                 child: Text!("+")
///             ),
///             Text!(tracked!(count))
///         ]
///     )
/// }
/// ```
/// *Adapted from the `avalanche_web`
/// [counter example.](https://github.com/DJankauskas/avalanche/blob/38ec4ccb83f93550c7d444351fa395708505d053/avalanche-web/examples/counter/src/lib.rs)*
#[track_caller]
pub fn state<'a, T: 'static, F: FnOnce() -> T>(
    ctx: Context<'a>,
    f: F,
) -> (Tracked<&'a T>, StateSetter<T>) {
    let (state, location) = internal_state(ctx, f);
    let state = state.downcast_ref::<State<T>>().unwrap();
    let updated = state.gen.updated(ctx.gen);
    let state_ref = &state.val;
    let tracked_state_ref = Tracked::new(state_ref, updated);
    let updater = StateSetter::new(ctx.component_pos, ctx.scheduler.clone(), location);

    (tracked_state_ref, updater)
}

/// Provides a setter for a piece of state managed by [state].
pub struct StateSetter<T: 'static> {
    vdom: Shared<VDom>,
    vnode: NodeId<VNode>,
    scheduler: Shared<dyn Scheduler>,
    location: Location<'static>,
    phantom: PhantomData<T>,
}

impl<T: 'static> Clone for StateSetter<T> {
    fn clone(&self) -> Self {
        Self {
            vdom: self.vdom.clone(),
            vnode: self.vnode,
            scheduler: self.scheduler.clone(),
            location: self.location,
            phantom: PhantomData,
        }
    }
}

impl<T: 'static> StateSetter<T> {
    fn new(
        component_pos: ComponentPos,
        scheduler: Shared<dyn Scheduler>,
        location: Location<'static>,
    ) -> Self {
        Self {
            vdom: component_pos.vdom.clone(),
            vnode: component_pos.node_id.id,
            scheduler,
            location,
            phantom: PhantomData,
        }
    }

    /// Takes a function that modifies the state associated with the setter and
    /// triggers a rerender of its associated component.
    ///
    /// The update is not performed immediately; its effect will only be accessible
    /// on its component's rerender. Note that `update` always triggers a rerender, and the state value
    /// is marked as updated, even if the given function performs no mutations.
    pub fn update<F: FnOnce(&mut T) + 'static>(&self, f: F) {
        self.update_with_gen(|val, _| f(val))
    }

    /// Same as `update`, but also provides the `Gen` the root is on before the state update completes
    fn update_with_gen<F: FnOnce(&mut T, Gen) + 'static>(&self, f: F) {
        let vdom_clone = self.vdom.clone();
        let vdom_clone_2 = vdom_clone.clone();
        let vnode_copy = self.vnode;
        let scheduler_clone = self.scheduler.clone();
        let location_copy = self.location;

        self.scheduler.exec_mut(move |scheduler| {
            scheduler.schedule_on_ui_thread(Box::new(move || {
                vdom_clone.exec_mut(|vdom| {
                    let vdom_gen = vdom.gen;
                    let vnode = vnode_copy.get_mut(&mut vdom.tree);
                    vnode.dirty = true;
                    let shared_box = vnode
                        .state
                        .get_mut(&location_copy)
                        .expect("state referenced by correct location");
                    let any_mut = shared_box.get_mut();
                    let state = any_mut
                        .downcast_mut::<State<T>>()
                        .expect("state with setter's type");
                    f(&mut state.val, vdom_gen);
                    state.gen = vdom_gen.next();

                    update_vnode(
                        None,
                        vnode_copy,
                        &mut vdom.tree,
                        &mut vdom.renderer,
                        &vdom_clone_2,
                        &scheduler_clone,
                        vdom_gen,
                    );
                    vdom.gen.inc();
                })
            }));
        });
    }

    /// Sets the state to the given value.
    ///
    /// The update is not performed immediately; its effect will only be accessible
    /// on its component's rerender. Note that `set` always triggers a rerender, and the state value
    /// is marked as updated, even if the new state is equal to the old.
    pub fn set(&self, val: T) {
        self.update(move |state| *state = val);
    }
}

/// Like [state], but returns a reference to a [tracked::Vec]. 
/// 
/// Takes in a function `F` that returns 
/// a default [Vec](std::vec::Vec). The return value has fine-grained tracking: instead of only the 
/// whole vec being updated or not updated, each individual element is also tracked. For more information on how that works see 
/// [tracked::Vec].
/// 
/// Note that `vec` returns a `Tracked<tracked::Vec>`, which is marked as updated if 
/// any of its children are updated. However, an individual element's update status overrides this where appropriate. 
/// 
/// ## Example
/// ```rust
/// use avalanche::{component, tracked, View, vec};
/// use avalanche_web::components::{Div, H2, Button, Text};
///
/// #[component]
/// fn DynamicChildren() -> View {
///     let (data, update_data) = vec(self, || vec!["child 1"]);
///     let children = tracked!(data)
///         .iter()
///         .enumerate()
///         .map(|(n, text)| Text!(key: n.to_string(), tracked!(text))).collect::<Vec<_>>();
/// 
///     Div!([
///         Button!(
///             on_click: move |_| update_data.update(|data| data.push("another child")),
///             child: Text!("+")
///         ),
///         Div!(tracked!(children))
///     ])
/// }
/// ```
#[track_caller]
pub fn vec<'a, T: 'static, F: FnOnce() -> Vec<T>>(
    ctx: Context<'a>,
    f: F,
) -> (Tracked<&'a tracked::Vec<T>>, VecSetter<T>) {
    let (state, location) = internal_state(ctx, || tracked::Vec::new(f(), ctx.gen));
    let state = state.downcast_ref::<State<tracked::Vec<T>>>().unwrap();
    state.val.curr_gen.set(ctx.gen);
    let updated = state.gen.updated(ctx.gen);
    let state_ref = &state.val;
    let tracked_state_ref = Tracked::new(state_ref, updated);
    let updater = VecSetter::new(ctx.component_pos, ctx.scheduler.clone(), location);

    (tracked_state_ref, updater)
}

/// Provides a setter for a piece of state managed by [vec](vec()).
pub struct VecSetter<T: 'static> {
    setter: StateSetter<tracked::Vec<T>>,
}

impl<T> VecSetter<T> {
    fn new(
        component_pos: ComponentPos,
        scheduler: Shared<dyn Scheduler>,
        location: Location<'static>,
    ) -> Self {
        Self {
            setter: StateSetter::new(component_pos, scheduler, location),
        }
    }

    /// Takes a function that modifies the vec associated with the setter and
    /// triggers a rerender of its associated component.
    ///
    /// The update is not performed immediately; its effect will only be accessible
    /// on its component's rerender. Note that `update` always triggers a rerender, and the state value
    /// is marked as updated, even if the given function performs no mutations.
    pub fn update<F: FnOnce(&mut tracked::Vec<T>) + 'static>(&self, f: F) {
        self.setter.update_with_gen(|val, gen| {
            val.curr_gen.set(gen);
            f(val);
        });
    }

    /// Sets the vec to the given value, marking all elements as updated.
    ///
    /// The update is not performed immediately; its effect will only be accessible
    /// on its component's rerender. Note that `set` always triggers a rerender, and the state value
    /// is marked as updated, even if the new state is equal to the old.
    pub fn set(&self, val: Vec<T>) {
        self.update(|vec| *vec = tracked::Vec::new(val, vec.curr_gen.get()))
    }
}

impl<T> Clone for VecSetter<T> {
    fn clone(&self) -> Self {
        Self {
            setter: self.setter.clone(),
        }
    }
}