ribir_core 0.4.0-alpha.59

A non-intrusive declarative GUI framework, to build modern native/wasm cross-platform applications.
Documentation
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
use std::convert::Infallible;

use rxrust::observable::boxed::LocalBoxedObservable;

use super::*;
use crate::prelude::*;

/// Trait to help animations update state.
pub trait AnimateState {
  type Value: Clone;

  fn get(&self) -> Self::Value;
  fn set(&self, v: Self::Value);
  fn revert(&self, v: Self::Value);
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible>;
  fn calc_lerp_value(&mut self, from: &Self::Value, to: &Self::Value, rate: f32) -> Self::Value;

  #[doc(hidden)]
  fn dec_writer_count(&self);

  #[doc(hidden)]
  fn inc_writer_count(&self);

  /// Creates an animation that smoothly transitions a writer's value on every
  /// change.
  ///
  /// Use this when the current state value is already the correct "from"
  /// value. The initial animation start value is `self.get()`.
  fn transition(
    self, transition: impl Transition + 'static,
  ) -> Stateful<Animate<TransitionUncountedState<Self>>>
  where
    Self: Sized + 'static,
    Self::Value: PartialEq + 'static,
  {
    let init = self.get();
    self.transition_with_init(init, transition)
  }

  /// Creates an animation that smoothly transitions a writer's value on every
  /// change, with a specified initial value.
  ///
  /// Use this when the first observed target value should animate from a
  /// custom initial value instead of the current state value.
  ///
  /// Typical case: call `transition_with_init(...)` before binding/writing the
  /// property value, so the first sync can animate from `init_value`.
  fn transition_with_init(
    self, init_value: Self::Value, transition: impl Transition + 'static,
  ) -> Stateful<Animate<TransitionUncountedState<Self>>>
  where
    Self: Sized + 'static,
    Self::Value: PartialEq + 'static,
  {
    let init_trigger = Local::of(self.get());
    let modifies = self.animate_state_modifies();

    let mut animate = Animate::declarer();
    animate
      .with_transition(transition)
      .with_from(init_value)
      .with_state(TransitionUncountedState::new(self));
    let animate = animate.finish();

    // Keep `animate` alive by capturing it in the source subscription closure.
    // `animate.state` holds a count-neutral writer wrapper, so this does not
    // keep writer_count > 0 in a cycle.
    let _ = modifies
      .map({
        let animate = animate.clone_writer();
        move |_| animate.read().state.get()
      })
      .merge(init_trigger)
      .distinct_until_changed()
      .pairwise()
      .subscribe({
        let animate = animate.clone_writer();
        move |(old, _)| {
          animate.write().from = old;
          animate.run();
        }
      });
    animate
  }
}

#[doc(hidden)]
pub struct TransitionUncountedState<S: AnimateState + 'static> {
  state: S,
}

impl<S: AnimateState + 'static> TransitionUncountedState<S> {
  #[inline]
  fn new(state: S) -> Self {
    // Neutralize this wrapper's writer-count contribution.
    state.dec_writer_count();
    Self { state }
  }
}

impl<S: AnimateState + 'static> Drop for TransitionUncountedState<S> {
  fn drop(&mut self) { self.state.inc_writer_count(); }
}

/// A state with a lerp function as an animation state that use the `lerp_fn`
/// function to calc the linearly lerp value by rate, and not require the value
/// type of the state to implement the `Lerp` trait.
///
/// User can use it if the value type of the state is not implement the `Lerp`
/// or override the lerp algorithm of the value type of state.
pub struct CustomLerpState<S, F> {
  lerp_fn: F,
  state: S,
}

pub type LerpFnState<S, F> = CustomLerpState<S, F>;

struct StateWriterAdapter<S>(S);

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AnimateStatePackEnd;

#[derive(Clone, Debug, PartialEq)]
pub struct AnimateStatePack<H, T> {
  pub head: H,
  pub tail: T,
}

impl<H, T> AnimateStatePack<H, T> {
  #[inline]
  pub fn new(head: H, tail: T) -> Self { Self { head, tail } }
}

#[macro_export]
macro_rules! animate_state_pack {
  ($head:expr $(,)?) => {
    $crate::animation::AnimateStatePack::new($head, $crate::animation::AnimateStatePackEnd)
  };
  ($head:expr, $($tail:expr),+ $(,)?) => {
    $crate::animation::AnimateStatePack::new($head, $crate::animate_state_pack!($($tail),+))
  };
}
pub use animate_state_pack;

impl<S: AnimateState + 'static> AnimateState for TransitionUncountedState<S> {
  type Value = S::Value;

  #[inline]
  fn get(&self) -> Self::Value { self.state.get() }

  #[inline]
  fn set(&self, v: Self::Value) { self.state.set(v) }

  #[inline]
  fn revert(&self, v: Self::Value) { self.state.revert(v) }

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    self.state.animate_state_modifies()
  }

  #[inline]
  fn dec_writer_count(&self) { self.state.dec_writer_count(); }

  #[inline]
  fn inc_writer_count(&self) { self.state.inc_writer_count(); }

  #[inline]
  fn calc_lerp_value(&mut self, from: &Self::Value, to: &Self::Value, rate: f32) -> Self::Value {
    self.state.calc_lerp_value(from, to, rate)
  }
}

impl<S> AnimateState for S
where
  S: StateWriter,
  S::Value: Clone + Lerp,
{
  type Value = S::Value;

  #[inline]
  fn get(&self) -> Self::Value { self.read().clone() }

  #[inline]
  fn set(&self, v: Self::Value) { *self.shallow() = v; }

  #[inline]
  fn revert(&self, v: Self::Value) {
    let mut w = self.write();
    *w = v;
    w.forget_modifies();
  }

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    StateWatcher::raw_modifies(self)
      .filter(|s| s.contains(ModifyEffect::all()))
      .box_it()
  }

  #[inline]
  fn dec_writer_count(&self) { StateWriter::dec_writer_count(self); }

  #[inline]
  fn inc_writer_count(&self) { StateWriter::inc_writer_count(self); }

  fn calc_lerp_value(&mut self, from: &Self::Value, to: &Self::Value, rate: f32) -> Self::Value {
    from.lerp(to, rate)
  }
}

impl<S, F> AnimateState for CustomLerpState<S, F>
where
  S: AnimateState,
  F: FnMut(&S::Value, &S::Value, f32) -> S::Value,
{
  type Value = S::Value;

  #[inline]
  fn get(&self) -> Self::Value { self.state.get() }

  #[inline]
  fn set(&self, v: Self::Value) { self.state.set(v) }

  #[inline]
  fn revert(&self, v: Self::Value) { self.state.revert(v) }

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    self.state.animate_state_modifies()
  }

  #[inline]
  fn dec_writer_count(&self) { self.state.dec_writer_count(); }

  #[inline]
  fn inc_writer_count(&self) { self.state.inc_writer_count(); }

  #[inline]
  fn calc_lerp_value(&mut self, from: &S::Value, to: &S::Value, rate: f32) -> S::Value {
    (self.lerp_fn)(from, to, rate)
  }
}

impl<S, F> CustomLerpState<S, F>
where
  S: AnimateState,
  F: FnMut(&S::Value, &S::Value, f32) -> S::Value,
{
  #[inline]
  pub fn from_state(state: S, lerp_fn: F) -> Self { Self { state, lerp_fn } }
}

impl<S, F> CustomLerpState<S, F>
where
  S: StateWriter,
  S::Value: Clone,
  F: FnMut(&S::Value, &S::Value, f32) -> S::Value + 'static,
{
  #[inline]
  pub fn from_writer(state: S, lerp_fn: F) -> impl AnimateState<Value = S::Value> {
    CustomLerpState { state: StateWriterAdapter(state), lerp_fn }
  }
}

impl<S> AnimateState for StateWriterAdapter<S>
where
  S: StateWriter,
  S::Value: Clone,
{
  type Value = S::Value;

  #[inline]
  fn get(&self) -> Self::Value { self.0.read().clone() }

  #[inline]
  fn set(&self, v: Self::Value) { *self.0.shallow() = v; }

  #[inline]
  fn revert(&self, v: Self::Value) {
    let mut w = self.0.write();
    *w = v;
    w.forget_modifies();
  }

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    StateWatcher::raw_modifies(&self.0)
      .filter(|s| s.contains(ModifyEffect::all()))
      .box_it()
  }

  #[inline]
  fn dec_writer_count(&self) { self.0.dec_writer_count(); }

  #[inline]
  fn inc_writer_count(&self) { self.0.inc_writer_count(); }

  #[inline]
  fn calc_lerp_value(&mut self, _from: &Self::Value, _to: &Self::Value, _rate: f32) -> Self::Value {
    unreachable!("StateWriterAdapter only serves as CustomLerpState's storage adapter.")
  }
}

impl Lerp for AnimateStatePackEnd {
  #[inline]
  fn lerp(&self, _: &Self, _: f32) -> Self { AnimateStatePackEnd }
}

impl<H, T> Lerp for AnimateStatePack<H, T>
where
  H: Lerp,
  T: Lerp,
{
  #[inline]
  fn lerp(&self, to: &Self, rate: f32) -> Self {
    AnimateStatePack::new(self.head.lerp(&to.head, rate), self.tail.lerp(&to.tail, rate))
  }
}

impl AnimateState for AnimateStatePackEnd {
  type Value = AnimateStatePackEnd;

  #[inline]
  fn get(&self) -> Self::Value { AnimateStatePackEnd }

  #[inline]
  fn set(&self, _v: Self::Value) {}

  #[inline]
  fn revert(&self, _v: Self::Value) {}

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    Local::empty()
      .map(|_| -> ModifyInfo { unreachable!() })
      .box_it()
  }

  #[inline]
  fn dec_writer_count(&self) {}

  #[inline]
  fn inc_writer_count(&self) {}

  #[inline]
  fn calc_lerp_value(&mut self, _from: &Self::Value, _to: &Self::Value, _rate: f32) -> Self::Value {
    AnimateStatePackEnd
  }
}

impl<H, T> AnimateState for AnimateStatePack<H, T>
where
  H: AnimateState,
  T: AnimateState,
{
  type Value = AnimateStatePack<H::Value, T::Value>;

  #[inline]
  fn get(&self) -> Self::Value { AnimateStatePack::new(self.head.get(), self.tail.get()) }

  #[inline]
  fn set(&self, v: Self::Value) {
    self.head.set(v.head);
    self.tail.set(v.tail);
  }

  #[inline]
  fn revert(&self, v: Self::Value) {
    self.head.revert(v.head);
    self.tail.revert(v.tail);
  }

  #[inline]
  fn animate_state_modifies(&self) -> LocalBoxedObservable<'static, ModifyInfo, Infallible> {
    Local::from_iter([self.head.animate_state_modifies(), self.tail.animate_state_modifies()])
      .merge_all(usize::MAX)
      .box_it()
  }

  #[inline]
  fn dec_writer_count(&self) {
    self.head.dec_writer_count();
    self.tail.dec_writer_count();
  }

  #[inline]
  fn inc_writer_count(&self) {
    self.head.inc_writer_count();
    self.tail.inc_writer_count();
  }

  #[inline]
  fn calc_lerp_value(&mut self, from: &Self::Value, to: &Self::Value, rate: f32) -> Self::Value {
    AnimateStatePack::new(
      self
        .head
        .calc_lerp_value(&from.head, &to.head, rate),
      self
        .tail
        .calc_lerp_value(&from.tail, &to.tail, rate),
    )
  }
}

#[cfg(test)]
mod tests {
  use crate::{prelude::*, reset_test_env};

  #[test]
  fn pack_two() {
    reset_test_env!();
    let mut group = animate_state_pack!(Stateful::new(1.), Stateful::new(2.));
    let half = group.calc_lerp_value(&animate_state_pack!(0., 0.), &group.get(), 0.5);
    assert_eq!(half, animate_state_pack!(0.5, 1.));
  }

  #[test]
  fn transition_with_init_drop_no_cycle() {
    reset_test_env!();

    let state = Stateful::new(0);
    let w = fn_widget! {
      let _animate = state.clone_writer().transition_with_init(
        0,
        EasingTransition { easing: easing::LINEAR, duration: Duration::ZERO },
      );
      @Void {}
    };
    let wnd = crate::test_helper::TestWindow::from_widget(w);
    wnd.draw_frame();
    drop(wnd);
    AppCtx::run_until_stalled();
  }

  #[test]
  fn transition_with_init_part_writer_drop_no_cycle() {
    reset_test_env!();

    let state = Stateful::new((0, 0));
    let w = fn_widget! {
      let part = state.clone_writer().part_writer("0".into(), |v| PartMut::new(&mut v.0));
      let _animate = part.transition_with_init(
        0,
        EasingTransition { easing: easing::LINEAR, duration: Duration::ZERO },
      );
      @Void {}
    };
    let wnd = crate::test_helper::TestWindow::from_widget(w);
    wnd.draw_frame();
    drop(wnd);
    AppCtx::run_until_stalled();
  }
}