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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use std::any::TypeId;
use std::borrow::Borrow;
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::{BitAnd, BitOr, Deref};
use std::rc::Rc;

use crate::context::{CURRENT, MAPS, MAP_MANAGER};

use super::MapId;

/// A Lens allows the construction of a reference to a piece of some data, e.g. a field of a struct.
///
/// When deriving the `Lens` trait on a struct, the derive macro constructs a static type which implements the `Lens` trait for each field.
/// The `view()` method takes a reference to the struct type as input and outputs a reference to the field.
/// This provides a way to specify a binding to a specific field of some application data.
pub trait Lens: 'static + Copy + Debug + Hash {
    type Source;
    type Target;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>>;
}

/// A type returned by `Lens::view()` which contains either a reference to model data or an owned value.
pub enum LensValue<'a, T> {
    /// A reference to model or local data
    Borrowed(&'a T),
    /// Owned data
    Owned(T),
}

impl<T: Clone> Clone for LensValue<'_, T> {
    fn clone(&self) -> Self {
        match self {
            LensValue::Borrowed(v) => LensValue::Borrowed(*v),
            LensValue::Owned(v) => LensValue::Owned(v.clone()),
        }
    }
}

impl<T: Copy> Copy for LensValue<'_, T> {}

impl<T: Clone> LensValue<'_, T> {
    pub fn into_owned(self) -> T {
        match self {
            LensValue::Borrowed(t) => t.clone(),
            LensValue::Owned(t) => t,
        }
    }
}

impl<T> AsRef<T> for LensValue<'_, T> {
    fn as_ref(&self) -> &T {
        self
    }
}

impl<B> Deref for LensValue<'_, B>
where
    B: Borrow<B>,
{
    type Target = B;

    fn deref(&self) -> &B {
        match *self {
            LensValue::Borrowed(borrowed) => borrowed,
            LensValue::Owned(ref owned) => owned.borrow(),
        }
    }
}

/// Helpers for constructing more complex `Lens`es.
pub trait LensExt: Lens {
    fn or<Other>(self, other: Other) -> OrLens<Self, Other>
    where
        Other: Lens<Target = bool>,
        Self: Lens<Target = bool>,
    {
        OrLens::new(self, other)
    }

    fn and<Other>(self, other: Other) -> AndLens<Self, Other>
    where
        Other: Lens<Target = bool>,
        Self: Lens<Target = bool>,
    {
        AndLens::new(self, other)
    }

    /// Used to construct a lens to some data contained within some other lensed data.
    ///
    /// # Example
    /// Binds a label to `other_data`, which is a field of a struct `SomeData`, which is a field of the root `AppData` model:
    /// ```compile_fail
    /// Binding::new(cx, AppData::some_data.then(SomeData::other_data), |cx, data|{
    ///
    /// });
    /// ```
    fn then<Other>(self, other: Other) -> Then<Self, Other>
    where
        Other: Lens<Source = Self::Target>,
    {
        Then::new(self, other)
    }

    fn idx<T>(self, index: usize) -> Index<Self, T>
    where
        T: 'static,
        Self::Target: Deref<Target = [T]>,
    {
        Index::new(self, index)
    }

    fn map<O: 'static, F: 'static + Fn(&Self::Target) -> O>(self, map: F) -> Map<Self, O> {
        let id = MAP_MANAGER.with_borrow_mut(|f| f.create());
        let entity = CURRENT.with_borrow(|f| *f);
        MAPS.with_borrow_mut(|f| {
            f.insert(id, (entity, Box::new(MapState { closure: Rc::new(map) })))
        });
        Map { id, lens: self, o: PhantomData }
    }

    fn map_ref<O: 'static, F: 'static + Fn(&Self::Target) -> &O>(self, map: F) -> MapRef<Self, O> {
        let id = MAP_MANAGER.with_borrow_mut(|f| f.create());
        let entity = CURRENT.with_borrow(|f| *f);
        MAPS.with_borrow_mut(|f| {
            f.insert(id, (entity, Box::new(MapRefState { closure: Rc::new(map) })))
        });
        MapRef { id, lens: self, o: PhantomData }
    }

    fn unwrap<T: 'static>(self) -> Then<Self, UnwrapLens<T>>
    where
        Self: Lens<Target = Option<T>>,
    {
        self.then(UnwrapLens::new())
    }

    fn into_lens<T: 'static>(self) -> Then<Self, IntoLens<Self::Target, T>>
    where
        Self::Target: Clone + Into<T>,
    {
        self.then(IntoLens::new())
    }
}

// Implement LensExt for all types which implement Lens.
impl<T: Lens> LensExt for T {}

pub struct MapState<T, O> {
    closure: Rc<dyn Fn(&T) -> O>,
}

pub struct MapRefState<T, O> {
    closure: Rc<dyn Fn(&T) -> &O>,
}

pub struct Map<L: Lens, O> {
    id: MapId,
    lens: L,
    o: PhantomData<O>,
}

impl<L: Lens, O: 'static> Copy for Map<L, O> {}

impl<L: Lens, O: 'static> Clone for Map<L, O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lens, O: 'static> Lens for Map<L, O> {
    type Source = L::Source;
    type Target = O;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        let target = self.lens.view(source)?;
        let closure = MAPS.with_borrow(|f| {
            let (_, any) = f.get(&self.id)?;
            let MapState { closure } = any.downcast_ref()?;
            Some(closure.clone())
        })?;
        Some(LensValue::Owned(closure(&*target)))
    }
}

impl<L: Lens, O: 'static> Debug for Map<L, O> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{:?}.map(?)", self.lens))
    }
}

impl<L: Lens, O: 'static> Hash for Map<L, O> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.lens.hash(state);
        self.id.hash(state);
    }
}

pub struct MapRef<L: Lens, O> {
    id: MapId,
    lens: L,
    o: PhantomData<O>,
}

impl<L: Lens, O: 'static> Copy for MapRef<L, O> {}

impl<L: Lens, O: 'static> Clone for MapRef<L, O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lens, O: 'static + Clone> Lens for MapRef<L, O> {
    type Source = L::Source;
    type Target = O;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        let closure = MAPS.with_borrow(|f| {
            let (_, any) = f.get(&self.id)?;
            let MapRefState { closure } = any.downcast_ref()?;
            Some(closure.clone())
        })?;

        match self.lens.view(source)? {
            LensValue::Borrowed(target) => Some(LensValue::Borrowed(closure(target))),
            LensValue::Owned(target) => Some(LensValue::Owned(closure(&target).clone())),
        }
    }
}

impl<L: Lens, O: 'static> Debug for MapRef<L, O> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{:?}.map(?)", self.lens))
    }
}

impl<L: Lens, O: 'static> Hash for MapRef<L, O> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.lens.hash(state);
        self.id.hash(state);
    }
}

/// `Lens` composed of two lenses joined together
#[derive(Hash)]
pub struct Then<A, B> {
    a: A,
    b: B,
}

impl<A, B> Then<A, B> {
    pub fn new(a: A, b: B) -> Self
    where
        A: Lens,
        B: Lens,
    {
        Self { a, b }
    }
}

impl<A, B> Lens for Then<A, B>
where
    A: Lens,
    B: Lens<Source = A::Target>,
{
    type Source = A::Source;
    type Target = B::Target;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        if let Some(val) = self.a.view(source) {
            let val = match val {
                LensValue::Borrowed(val) => return self.b.view(val),
                LensValue::Owned(ref val) => val,
            };
            match self.b.view(val) {
                Some(LensValue::Owned(val)) => return Some(LensValue::Owned(val)),
                _ => unreachable!(),
            }
        }

        None
    }
}

impl<T: Clone, U: Clone> Clone for Then<T, U> {
    fn clone(&self) -> Self {
        Self { a: self.a.clone(), b: self.b.clone() }
    }
}

impl<A: Lens, B: Lens> Debug for Then<A, B> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{:?}.then({:?})", self.a, self.b))
    }
}

impl<T: Copy, U: Copy> Copy for Then<T, U> {}

pub struct Index<L, T> {
    lens: L,
    index: usize,
    pt: PhantomData<T>,
}

impl<L, T> Index<L, T> {
    pub fn new(lens: L, index: usize) -> Self {
        Self { lens, index, pt: PhantomData }
    }

    pub fn idx(&self) -> usize {
        self.index
    }
}

impl<L: Lens, T> Clone for Index<L, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<L: Lens, T> Copy for Index<L, T> {}

impl<L: Lens, T> Debug for Index<L, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{:?}.index({:?})", self.lens, self.index))
    }
}

impl<L: Lens, T> Hash for Index<L, T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.lens.hash(state);
        self.index.hash(state);
    }
}

impl<L, T> Lens for Index<L, T>
where
    L: Lens<Target: Deref<Target = [T]>>,
    T: 'static + Clone,
{
    type Source = L::Source;
    type Target = T;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        self.lens.view(source).and_then(|v| match v {
            LensValue::Borrowed(v) => v.get(self.index).map(LensValue::Borrowed),
            LensValue::Owned(v) => v.get(self.index).cloned().map(LensValue::Owned),
        })
    }
}

pub struct StaticLens<T: 'static> {
    data: &'static T,
}

impl<T> Clone for StaticLens<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for StaticLens<T> {}

impl<T> Debug for StaticLens<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("Static Lens: ")?;
        TypeId::of::<T>().fmt(f)?;
        Ok(())
    }
}

impl<T> Hash for StaticLens<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let id = TypeId::of::<Self>();
        id.hash(state);
    }
}

impl<T> Lens for StaticLens<T> {
    type Source = ();
    type Target = T;

    fn view<'a>(&self, _: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        Some(LensValue::Borrowed(self.data))
    }
}

impl<T> StaticLens<T> {
    pub fn new(data: &'static T) -> Self {
        StaticLens { data }
    }
}

#[derive(Default)]
pub struct UnwrapLens<T> {
    t: PhantomData<T>,
}

impl<T> Clone for UnwrapLens<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> UnwrapLens<T> {
    pub fn new() -> Self {
        Self { t: PhantomData }
    }
}

impl<T> Copy for UnwrapLens<T> {}

impl<T: 'static> Lens for UnwrapLens<T> {
    type Source = Option<T>;
    type Target = T;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        source.as_ref().map(LensValue::Borrowed)
    }
}

impl<T: 'static> Debug for UnwrapLens<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("unwrap")
    }
}

impl<T: 'static> Hash for UnwrapLens<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let id = TypeId::of::<Self>();
        id.hash(state);
    }
}

#[derive(Default)]
pub struct IntoLens<T, U> {
    t: PhantomData<T>,
    u: PhantomData<U>,
}

impl<T, U> IntoLens<T, U> {
    pub fn new() -> Self {
        Self { t: Default::default(), u: Default::default() }
    }
}

impl<T, U> Clone for IntoLens<T, U> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T, U> Copy for IntoLens<T, U> {}

impl<T: 'static + Clone + TryInto<U>, U: 'static> Lens for IntoLens<T, U> {
    type Source = T;
    type Target = U;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        source.clone().try_into().ok().map(|t| LensValue::Owned(t))
    }
}

impl<T, U> Debug for IntoLens<T, U> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("into")
    }
}

impl<T: 'static, U: 'static> Hash for IntoLens<T, U> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let id = TypeId::of::<Self>();
        id.hash(state);
    }
}

#[derive(Hash, Copy, Clone, Debug)]
pub struct RatioLens<L1, L2> {
    numerator: L1,
    denominator: L2,
}

impl<L1, L2> RatioLens<L1, L2> {
    pub fn new(numerator: L1, denominator: L2) -> Self {
        Self { numerator, denominator }
    }
}

impl<L1, L2> Lens for RatioLens<L1, L2>
where
    L1: 'static + Clone + Lens<Target = f32>,
    L2: 'static + Clone + Lens<Target = f32, Source = <L1 as Lens>::Source>,
{
    type Source = L1::Source;
    type Target = f32;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, f32>> {
        let num = self.numerator.view(source)?.into_owned();
        let den = self.denominator.view(source)?.into_owned();
        Some(LensValue::Owned(num / den))
    }
}

#[derive(Hash, Debug, Copy)]
pub struct OrLens<L1, L2> {
    lens1: L1,
    lens2: L2,
}

impl<L1, L2> OrLens<L1, L2> {
    pub fn new(lens1: L1, lens2: L2) -> Self
    where
        L1: Lens<Target = bool>,
        L2: Lens<Target = bool>,
    {
        Self { lens1, lens2 }
    }
}

impl<L1, L2> Lens for OrLens<L1, L2>
where
    L1: Lens<Source = L2::Source, Target = bool>,
    L2: Lens<Target = bool>,
{
    type Source = L1::Source;
    type Target = bool;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        let v1 = self.lens1.view(source)?.into_owned();
        let v2 = self.lens2.view(source)?.into_owned();

        Some(LensValue::Owned(v1 | v2))
    }
}

impl<L1: Clone, L2: Clone> Clone for OrLens<L1, L2> {
    fn clone(&self) -> Self {
        Self { lens1: self.lens1.clone(), lens2: self.lens2.clone() }
    }
}

#[derive(Hash, Clone)]
pub struct Wrapper<L>(pub L);

impl<L: Copy> Copy for Wrapper<L> {}

impl<L: Lens> Lens for Wrapper<L> {
    type Source = L::Source;
    type Target = L::Target;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        self.0.view(source)
    }
}

impl<L: Lens> Debug for Wrapper<L> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<L1: Lens<Target = bool>, L2: Lens<Target = bool>> BitOr<L2> for Wrapper<L1>
where
    L1: Lens<Source = L2::Source>,
{
    type Output = OrLens<Self, L2>;
    fn bitor(self, rhs: L2) -> Self::Output {
        OrLens::new(self, rhs)
    }
}

impl<L1, L2, L3: Lens<Target = bool>> BitOr<L3> for OrLens<L1, L2>
where
    Self: Lens<Target = bool>,
    Self: Lens<Source = L3::Source>,
{
    type Output = OrLens<Self, L3>;
    fn bitor(self, rhs: L3) -> Self::Output {
        OrLens::new(self, rhs)
    }
}

impl<A: Lens, L1: Lens<Target = bool>, L2: Lens<Target = bool>> BitOr<L2> for Then<A, L1>
where
    A: Lens<Source = L2::Source>,
    L1: Lens<Source = A::Target>,
{
    type Output = OrLens<Self, L2>;
    fn bitor(self, rhs: L2) -> Self::Output {
        OrLens::new(self, rhs)
    }
}

impl<L, L2: Lens<Target = bool>> BitOr<L2> for Map<L, bool>
where
    L: Lens<Source = L2::Source>,
{
    type Output = OrLens<Self, L2>;
    fn bitor(self, rhs: L2) -> Self::Output {
        OrLens::new(self, rhs)
    }
}

#[derive(Hash, Debug, Copy)]
pub struct AndLens<L1, L2> {
    lens1: L1,
    lens2: L2,
}

impl<L1, L2> AndLens<L1, L2> {
    pub fn new(lens1: L1, lens2: L2) -> Self
    where
        L1: Lens<Target = bool>,
        L2: Lens<Target = bool>,
    {
        Self { lens1, lens2 }
    }
}

impl<L1, L2> Lens for AndLens<L1, L2>
where
    L1: Lens<Source = L2::Source, Target = bool>,
    L2: Lens<Target = bool>,
{
    type Source = L1::Source;
    type Target = bool;

    fn view<'a>(&self, source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        let v1 = self.lens1.view(source)?.into_owned();
        let v2 = self.lens2.view(source)?.into_owned();

        Some(LensValue::Owned(v1 | v2))
    }
}

impl<L1: Clone, L2: Clone> Clone for AndLens<L1, L2> {
    fn clone(&self) -> Self {
        Self { lens1: self.lens1.clone(), lens2: self.lens2.clone() }
    }
}

impl<L1: Lens<Target = bool>, L2: Lens<Target = bool>> BitAnd<L2> for Wrapper<L1>
where
    L1: Lens<Source = L2::Source>,
{
    type Output = AndLens<Self, L2>;
    fn bitand(self, rhs: L2) -> Self::Output {
        AndLens::new(self, rhs)
    }
}

impl<L1, L2, L3: Lens<Target = bool>> BitAnd<L3> for AndLens<L1, L2>
where
    Self: Lens<Target = bool>,
    Self: Lens<Source = L3::Source>,
{
    type Output = AndLens<Self, L3>;
    fn bitand(self, rhs: L3) -> Self::Output {
        AndLens::new(self, rhs)
    }
}

impl<A: Lens, L1: Lens<Target = bool>, L2: Lens<Target = bool>> BitAnd<L2> for Then<A, L1>
where
    A: Lens<Source = L2::Source>,
    L1: Lens<Source = A::Target>,
{
    type Output = AndLens<Self, L2>;
    fn bitand(self, rhs: L2) -> Self::Output {
        AndLens::new(self, rhs)
    }
}

impl<L, L2: Lens<Target = bool>> BitAnd<L2> for Map<L, bool>
where
    L: Lens<Source = L2::Source>,
{
    type Output = AndLens<Self, L2>;
    fn bitand(self, rhs: L2) -> Self::Output {
        AndLens::new(self, rhs)
    }
}

impl<T> Lens for &'static T
where
    T: 'static + Copy + Debug + Hash,
{
    type Source = ();
    type Target = T;

    fn view<'a>(&self, _source: &'a Self::Source) -> Option<LensValue<'a, Self::Target>> {
        Some(LensValue::Borrowed(*self))
    }
}