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
use futures_signals::signal::{Signal, SignalExt, channel, Receiver};
use std::marker::Unpin;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::rc::Rc;
/*
 * This helper is to make it simpler to Box a signal-factory function
 * The use case is similar to where you might have a ReadOnlyMutable or Broadcaster
 * e.g. to re-render the same signal multiple times
 * If the signal-generation itself is expensive, use Broadcaster instead 
 * If keeping a ReadOnlyMutable around is fine, use that instead
 * Otherwise, there's this for the sake of convenience :)
 * or needing to keep a separate ReadOnlyMutable around
 *
 * Example:
 * pub struct Foo {
 *   pub active_signal: BoxSignalFn<bool>,
 * }
 *
 *
 * impl Foo {
 *   pub fn new<S: Signal<Item = bool> + 'static>(active_signal: impl Fn() -> S + 'static) -> Self {
 *     Self {
 *       active_signal: box_signal_fn(active_signal),
 *    }
 * }
 *
 * let foo = Foo::new(|| always(true));
 */

/// Type alias for a boxed signal-factory
pub type BoxSignalFn<T> = Box<dyn Fn() -> Pin<Box<dyn Signal<Item = T>>>>;

/// Helper to create boxed signal-factories
pub fn box_signal_fn<T, S: Signal<Item = T> + 'static>(f: impl Fn() -> S + 'static) -> BoxSignalFn<T> {
    Box::new(move || {
        Box::pin(f())
    })
}

/// Type alias for a Rc'd signal-factory (same idea as BoxSignalFn but cloneable)
pub type RcSignalFn<T> = Rc<dyn Fn() -> Pin<Box<dyn Signal<Item = T>>>>;

/// Helper to create Rc signal-factories (same idea as box_signal_fn but cloneable)
pub fn rc_signal_fn<T, S: Signal<Item = T> + 'static>(f: impl Fn() -> S + 'static) -> RcSignalFn<T> {
    Rc::new(move || {
        Box::pin(f())
    })
}
/*
 * These all generally solving the problem of where you need to return different types of signals
 * But don't want to Box it.
 *
 * Most of the helpers are for cases where the inner type of the signals are the same
 * And where it's usually about returning an always() vs. custom signal
 *
 * Fwiw, Boxing signals looks like this, for example:
    match foo {
        None =>
            Box::pin(always(None)) as Pin<Box<dyn Signal<Item = Option<Dom>>>>,
        Some(bar) =>
            Box::pin(get_some_signal(bar)) as Pin<Box<dyn Signal<Item = Option<Dom>>>>
    }
*/

/* TIPS FOR IMPLEMENTATION
 * a Signal must always return Poll::Ready(Some(...)) the first time it is called
 * after that it can return either Poll::Ready(Some(...)), Poll::Pending, or Poll::Ready(None)
 * and if it returns Poll::Ready(None), then from that point forward it's 
 * considered finished, the consumer must not poll again.
*/


/// If the provided signal is None,
/// then a signal of the provided default
/// otherwise, the signal's value
pub struct DefaultSignal<S, T>
where
    S: Signal<Item = T>,
{
    default: Option<T>,
    value_signal: Option<S>,
    const_has_fired: bool,
}

impl<S, T> DefaultSignal<S, T>
where
    S: Signal<Item = T>,
{
    pub fn new(default: T, value_signal: Option<S>) -> Self {
        Self {
            default: Some(default),
            value_signal,
            const_has_fired: false,
        }
    }
}

impl<S, T> Signal for DefaultSignal<S, T>
where
    S: Signal<Item = T> + Unpin,
    T: Unpin,
{
    type Item = T;

    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let _self = self.get_mut();

        match &mut _self.value_signal {
            None => {
                if _self.const_has_fired {
                    Poll::Ready(None)
                } else {
                    _self.const_has_fired = true;
                    Poll::Ready(_self.default.take())
                }
            }
            Some(value_signal) => value_signal.poll_change_unpin(cx),
        }
    }
}

/// If the provided signal is None,
/// then a signal of None
/// otherwise, a signal of Some(value)
pub struct OptionSignal<S, T>
where
    S: Signal<Item = T>,
{
    value_signal: Option<S>,
    const_has_fired: bool,
}

impl<S, T> OptionSignal<S, T>
where
    S: Signal<Item = T>,
{
    pub fn new(value_signal: Option<S>) -> Self {
        Self {
            value_signal,
            const_has_fired: false,
        }
    }
}

impl<S, T> Signal for OptionSignal<S, T>
where
    S: Signal<Item = T> + Unpin,
    T: Unpin,
{
    type Item = Option<T>;

    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        let _self = self.get_mut();

        match &mut _self.value_signal {
            None => {
                if _self.const_has_fired {
                    Poll::Ready(None)
                } else {
                    _self.const_has_fired = true;
                    Poll::Ready(Some(None))
                }
            }
            Some(value_signal) => {
                value_signal
                    .poll_change_unpin(cx)
                    //need to map the inner Option
                    //outer one is just Poll
                    .map(|value| value.map(|value| Some(value)))
            }
        }
    }
}

// A signal of either left or right
pub enum EitherSignal<Left, Right> {
    Left(Left),
    Right(Right),
}

impl<Left, Right, T> Signal for EitherSignal<Left, Right>
where
    Left: Signal<Item = T> + Unpin,
    Right: Signal<Item = T> + Unpin,
{
    type Item = T;

    fn poll_change(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        match self.get_mut() {
            Self::Left(x) => x.poll_change_unpin(cx),
            Self::Right(x) => x.poll_change_unpin(cx),
        }
    }
}

cfg_if::cfg_if! {
    if #[cfg(all(feature = "awsm_web"))] {
        use awsm_web::dom::resize::ResizeObserver;
        use web_sys::{Element, DomRect};

        pub struct DomRectSignal {
            _observer: ResizeObserver,
            receiver: Receiver<DomRect>,
        }

        impl Signal for DomRectSignal {
            type Item = DomRect;

            #[inline]
            fn poll_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
                self.receiver.poll_change_unpin(cx)
            }
        }

        pub fn dom_rect_signal(element: &Element) -> DomRectSignal {
            let (sender, receiver) = channel(element.get_bounding_client_rect());

            let observer = {
                let element = element.clone();
                
                ResizeObserver::new_simple(move || {
                    sender.send(element.get_bounding_client_rect()).unwrap();
                })
            };

            observer.observe(&element);

            DomRectSignal { _observer: observer, receiver }
        }

        pub struct DomRectMultiSignal {
            _observer: ResizeObserver,
            receiver: Receiver<Vec<DomRect>>,
        }

        impl Signal for DomRectMultiSignal {
            type Item = Vec<DomRect>;

            #[inline]
            fn poll_change(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
                self.receiver.poll_change_unpin(cx)
            }
        }

        pub fn dom_rect_multi_signal(elements: &[Element]) -> DomRectMultiSignal {
            let init_sizes = elements.iter().map(|elem| elem.get_bounding_client_rect()).collect();

            let (sender, receiver) = channel(init_sizes);

            let observer = {
                ResizeObserver::new(move |entries| {
                    let sizes = entries.into_iter().map(|entry| entry.content_rect).collect();
                    sender.send(sizes).unwrap();
                }, None)
            };

            for element in elements {
                observer.observe(&element);
            }

            DomRectMultiSignal { _observer: observer, receiver }
        }
    }
}