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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use crate::element_tree::ReconcileCtx;
use crate::element_tree::{Element, NoEvent, VirtualDom};
use crate::glue::GlobalEventCx;
use crate::widgets::WidgetSeqBox;

use derivative::Derivative;
use std::any::Any;
use std::fmt::Debug;

// --- STATE ---

pub trait AnyState: Any + Debug {
    fn as_any(&self) -> &dyn Any;
    fn as_mut_any(&mut self) -> &mut dyn Any;

    fn print_type(&self) {
        println!("{:#?}", std::any::type_name::<Self>());
    }

    fn dyn_clone(&self) -> Box<dyn AnyState>;
    fn dyn_eq(&self, other: &Box<dyn AnyState>) -> bool;
}

impl<T> AnyState for T
where
    T: Clone + Default + Debug + PartialEq + 'static,
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mut_any(&mut self) -> &mut dyn Any {
        self
    }

    fn dyn_clone(&self) -> Box<dyn AnyState> {
        Box::new(self.clone())
    }

    fn dyn_eq(&self, other: &Box<dyn AnyState>) -> bool {
        if let Some(other) = other.as_ref().as_any().downcast_ref::<Self>() {
            other.eq(self)
        } else {
            false
        }
    }
}

pub struct AnyStateBox {
    value: Box<dyn AnyState>,
}

impl AnyStateBox {
    pub fn new(state: impl AnyState) -> Self {
        AnyStateBox {
            value: Box::new(state),
        }
    }
}

impl Clone for AnyStateBox {
    fn clone(&self) -> Self {
        AnyStateBox {
            value: self.value.dyn_clone(),
        }
    }
}

impl Debug for AnyStateBox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.value.fmt(f)
    }
}

impl PartialEq for AnyStateBox {
    fn eq(&self, other: &Self) -> bool {
        self.value.dyn_eq(&other.value)
    }
}

// --- ELEMENT ---

#[derive(Derivative, PartialEq, Eq, Hash)]
#[derivative(Default(bound = "Child: Default"), Clone(bound = "Child: Clone"))]
struct ErasedElement<Child: Element<CpEvent, CpState>, CpEvent, CpState> {
    child: Option<Child>,
    _markers: std::marker::PhantomData<(CpState, CpEvent)>,
}

impl<Child: Element<CpEvent, CpState>, CpEvent, CpState> Debug
    for ErasedElement<Child, CpEvent, CpState>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.child.as_ref().unwrap().fmt(f)
    }
}

trait AnyElement<CpEvent, CpState>: Any + Debug {
    fn print_type(&self) {
        println!("{:#?}", std::any::type_name::<Self>());
    }

    fn build(
        &mut self,
        prev_state: Option<AnyStateBox>,
    ) -> (
        Box<dyn AnyVirtualDom<CpEvent, CpState>>,
        Option<AnyStateBox>,
    );
}

impl<Child: Element<CpEvent, CpState> + 'static, CpEvent: 'static, CpState: 'static>
    AnyElement<CpEvent, CpState> for ErasedElement<Child, CpEvent, CpState>
{
    fn build(
        &mut self,
        prev_state: Option<AnyStateBox>,
    ) -> (
        Box<dyn AnyVirtualDom<CpEvent, CpState>>,
        Option<AnyStateBox>,
    ) {
        let child = self.child.take().unwrap();

        let prev_state = if let Some(mut prev_state) = prev_state {
            std::mem::take(
                prev_state
                    .value
                    .as_mut_any()
                    .downcast_mut::<Child::AggregateChildrenState>()
                    .unwrap(),
            )
        } else {
            Default::default()
        };

        let (output, state) = child.build(prev_state);

        (
            Box::new(ErasedVirtualDom {
                child: output,
                _markers: Default::default(),
            }),
            Some(AnyStateBox {
                value: Box::new(state),
            }),
        )
    }
}

// -

pub struct ElementBox<CpEvent, CpState> {
    child: Box<dyn AnyElement<CpEvent, CpState>>,
    _markers: std::marker::PhantomData<(CpState, CpEvent)>,
}

impl<CpEvent: 'static, CpState: 'static> ElementBox<CpEvent, CpState> {
    pub fn new(child: impl Element<CpEvent, CpState> + 'static) -> Self {
        ElementBox {
            child: Box::new(ErasedElement {
                child: Some(child),
                _markers: Default::default(),
            }),
            _markers: Default::default(),
        }
    }
}

impl<CpEvent, CpState> Debug for ElementBox<CpEvent, CpState> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.child.fmt(f)
    }
}

impl<CpEvent, CpState> Element<CpEvent, CpState> for ElementBox<CpEvent, CpState> {
    type Event = NoEvent;
    type AggregateChildrenState = Option<AnyStateBox>;
    type BuildOutput = VirtualDomBox<CpEvent, CpState>;

    fn build(
        self,
        prev_state: Option<AnyStateBox>,
    ) -> (VirtualDomBox<CpEvent, CpState>, Option<AnyStateBox>) {
        let mut child = self.child;
        let (output, state) = child.build(prev_state);

        (
            VirtualDomBox {
                child: output,
                _markers: Default::default(),
            },
            state,
        )
    }
}

// --- VIRTUAL_DOM ---

#[derive(Derivative, PartialEq, Eq, Hash)]
#[derivative(Default(bound = "Child: Default"), Clone(bound = "Child: Clone"))]
pub struct ErasedVirtualDom<Child: VirtualDom<CpEvent, CpState>, CpEvent, CpState> {
    child: Child,
    _markers: std::marker::PhantomData<(CpState, CpEvent)>,
}

impl<Child: VirtualDom<CpEvent, CpState>, CpEvent, CpState> Debug
    for ErasedVirtualDom<Child, CpEvent, CpState>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.child.fmt(f)
    }
}

pub trait AnyVirtualDom<CpEvent, CpState>: Any + Debug {
    fn as_any(&self) -> &dyn Any;

    fn print_type(&self) {
        println!("{:#?}", std::any::type_name::<Self>());
    }

    fn init_tree(&self) -> WidgetSeqBox;

    fn reconcile(
        &self,
        other: &Box<dyn AnyVirtualDom<CpEvent, CpState>>,
        widget_seq: &mut WidgetSeqBox,
        ctx: &mut ReconcileCtx,
    );

    fn process_event(
        &self,
        component_state: &mut CpState,
        children_state: &mut Option<AnyStateBox>,
        widget_seq: &mut WidgetSeqBox,
        cx: &mut GlobalEventCx,
    ) -> Option<CpEvent>;
}

impl<Child: VirtualDom<CpEvent, CpState> + 'static, CpEvent: 'static, CpState: 'static>
    AnyVirtualDom<CpEvent, CpState> for ErasedVirtualDom<Child, CpEvent, CpState>
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn init_tree(&self) -> WidgetSeqBox {
        WidgetSeqBox {
            value: Box::new(self.child.init_tree()),
        }
    }

    fn reconcile(
        &self,
        other: &Box<dyn AnyVirtualDom<CpEvent, CpState>>,
        widget_seq: &mut WidgetSeqBox,
        ctx: &mut ReconcileCtx,
    ) {
        let other = other.as_any().downcast_ref::<Self>().unwrap();
        let widget_seq = widget_seq
            .value
            .as_mut_any()
            .downcast_mut::<Child::TargetWidgetSeq>()
            .unwrap();
        self.child.reconcile(&other.child, widget_seq, ctx);
    }

    fn process_event(
        &self,
        component_state: &mut CpState,
        children_state: &mut Option<AnyStateBox>,
        widget_seq: &mut WidgetSeqBox,
        cx: &mut GlobalEventCx,
    ) -> Option<CpEvent> {
        let children_state = children_state
            .as_mut()
            .unwrap()
            .value
            .as_mut_any()
            .downcast_mut::<Child::AggregateChildrenState>()
            .unwrap();
        let widget_seq = widget_seq
            .value
            .as_mut_any()
            .downcast_mut::<Child::TargetWidgetSeq>()
            .unwrap();
        self.child
            .process_event(component_state, children_state, widget_seq, cx)
    }
}

// -

pub struct VirtualDomBox<CpEvent, CpState> {
    child: Box<dyn AnyVirtualDom<CpEvent, CpState>>,
    _markers: std::marker::PhantomData<(CpState, CpEvent)>,
}

impl<CpEvent: 'static, CpState: 'static> VirtualDomBox<CpEvent, CpState> {
    pub fn new(child: impl VirtualDom<CpEvent, CpState> + 'static) -> Self {
        VirtualDomBox {
            child: Box::new(ErasedVirtualDom {
                child: child,
                _markers: Default::default(),
            }),
            _markers: Default::default(),
        }
    }
}

impl<CpEvent, CpState> Debug for VirtualDomBox<CpEvent, CpState> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.child.fmt(f)
    }
}

impl<CpEvent, CpState> VirtualDom<CpEvent, CpState> for VirtualDomBox<CpEvent, CpState> {
    type Event = NoEvent;
    type AggregateChildrenState = Option<AnyStateBox>;
    type TargetWidgetSeq = WidgetSeqBox;

    fn init_tree(&self) -> Self::TargetWidgetSeq {
        self.child.init_tree()
    }

    fn reconcile(
        &self,
        other: &Self,
        widget_seq: &mut Self::TargetWidgetSeq,
        ctx: &mut ReconcileCtx,
    ) {
        self.child.reconcile(&other.child, widget_seq, ctx);
    }

    fn process_event(
        &self,
        component_state: &mut CpState,
        children_state: &mut Option<AnyStateBox>,
        widget_seq: &mut WidgetSeqBox,
        cx: &mut GlobalEventCx,
    ) -> Option<CpEvent> {
        self.child
            .process_event(component_state, children_state, widget_seq, cx)
    }
}

// --- TESTS ---

#[cfg(test)]
mod tests {
    use super::*;
    use crate::element_tree::assign_empty_state_type;
    use crate::elements::label::Label;
    use insta::assert_debug_snapshot;
    use test_env_log::test;

    #[test]
    fn any_state() {
        let state1 = AnyStateBox::new(42);
        let state2 = state1.clone();

        assert!(state1 == state2);
    }

    #[test]
    fn new_element() {
        let label = ElementBox::new(Label::new("Hello"));
        assert_debug_snapshot!(label);

        assign_empty_state_type(&label);

        let (label_data, _state) = label.build(None);
        assert_debug_snapshot!(label_data);

        // TODO - check state
    }

    // TODO
    // - Event test
    // - Widget test
}