lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
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
use std::{
  collections::{HashMap, HashSet},
  sync::OnceLock,
  time::Duration,
};

use super::{
  easing::Easing,
  interpolate::write_property,
  keyframes::{KeyframeEntry, Keyframes, KeyframesId},
};
use crate::{core::NodeId, time::Instant};

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationDirection {
  Normal,
  Reverse,
  Alternate,
  AlternateReverse,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationFillMode {
  None,
  Forwards,
  Backwards,
  Both,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationIterationCount {
  Count(f64),
  Infinite,
}

#[derive(Clone, Debug)]
pub struct Animation {
  pub keyframes: KeyframesId,
  pub duration: Duration,
  pub delay: Duration,
  pub easing: Easing,
  pub direction: AnimationDirection,
  pub fill_mode: AnimationFillMode,
  pub iteration_count: AnimationIterationCount,
}

impl Animation {
  pub fn new(keyframes: impl Into<KeyframesId>) -> Self {
    Self {
      keyframes: keyframes.into(),
      duration: Duration::from_millis(300),
      delay: Duration::ZERO,
      easing: Easing::EASE,
      direction: AnimationDirection::Normal,
      fill_mode: AnimationFillMode::None,
      iteration_count: AnimationIterationCount::Count(1.0),
    }
  }

  pub fn duration(mut self, d: Duration) -> Self {
    self.duration = d;
    self
  }

  pub fn duration_ms(mut self, ms: u64) -> Self {
    self.duration = Duration::from_millis(ms);
    self
  }

  pub fn delay(mut self, d: Duration) -> Self {
    self.delay = d;
    self
  }

  pub fn delay_ms(mut self, ms: u64) -> Self {
    self.delay = Duration::from_millis(ms);
    self
  }

  pub fn easing(mut self, e: Easing) -> Self {
    self.easing = e;
    self
  }

  pub fn linear(mut self) -> Self {
    self.easing = Easing::Linear;
    self
  }

  pub fn direction(mut self, d: AnimationDirection) -> Self {
    self.direction = d;
    self
  }

  pub fn fill_mode(mut self, f: AnimationFillMode) -> Self {
    self.fill_mode = f;
    self
  }

  pub fn iteration_count(mut self, c: AnimationIterationCount) -> Self {
    self.iteration_count = c;
    self
  }

  pub fn infinite(mut self) -> Self {
    self.iteration_count = AnimationIterationCount::Infinite;
    self
  }

  pub fn alternate(mut self) -> Self {
    self.direction = AnimationDirection::Alternate;
    self
  }

  /// How long the animation takes from its start to its end, its delay
  /// included: one iteration for one that repeats without end.
  pub(crate) fn total_time(&self) -> Duration {
    let iterations = match self.iteration_count {
      AnimationIterationCount::Count(count) if count.is_finite() && count > 0.0 => count,
      AnimationIterationCount::Count(_) => 0.0,
      AnimationIterationCount::Infinite => 1.0,
    };
    let active = Duration::try_from_secs_f64(self.duration.as_secs_f64() * iterations).unwrap_or(Duration::MAX);
    self.delay.saturating_add(active)
  }
}

/// A frame due at a step boundary is drawn this long after it, so that it samples the new step even where
/// floating-point time lands a hair before the boundary.
const STEP_MARGIN: Duration = Duration::from_micros(100);

/// When a step `fraction` of `duration` after `now` is drawn, [`STEP_MARGIN`] after it: `now` for a fraction that
/// is not a finite, non-negative number, and `None` for one past what an `Instant` holds.
pub(super) fn step_time(now: Instant, duration: Duration, fraction: f64) -> Option<Instant> {
  if !(fraction.is_finite() && fraction >= 0.0) {
    return Some(now);
  }
  let offset = Duration::try_from_secs_f64(duration.as_secs_f64() * fraction).ok()?;
  now.checked_add(offset)?.checked_add(STEP_MARGIN)
}

struct AnimationRun {
  keyframes: KeyframesId,
  duration: Duration,
  delay: Duration,
  easing: Easing,
  direction: AnimationDirection,
  fill_mode: AnimationFillMode,
  iteration_count: f64,
  start_time: Instant,
  finished: bool,
}

/// Where a run is on its timeline at some time.
enum Phase {
  Delay,
  Active { iteration: f64, progress: f64 },
  Done,
}

impl AnimationRun {
  fn phase(&self, now: Instant) -> Phase {
    let elapsed = now.duration_since(self.start_time);
    if elapsed < self.delay {
      return Phase::Delay;
    }
    let duration = self.duration.as_secs_f64();
    let active = (elapsed - self.delay).as_secs_f64();
    if duration <= 0.0 || active >= duration * self.iteration_count {
      return Phase::Done;
    }
    let iteration = (active / duration).floor();
    Phase::Active {
      iteration,
      progress: active / duration - iteration,
    }
  }

  /// The keyframe progress a done run holds: the pose it stopped on when it fills forwards, `None` when it holds
  /// nothing. A whole iteration count stops at the end of the last iteration, a fractional one part way into the
  /// iteration after the last whole one, and a zero count at the start of the first. A zero duration plays every
  /// iteration in no time and holds the same pose; an infinite count ends only then, and holds the end of the
  /// first iteration.
  fn final_progress(&self) -> Option<f64> {
    let fills = matches!(self.fill_mode, AnimationFillMode::Forwards | AnimationFillMode::Both);
    fills.then(|| {
      let count = self.iteration_count.max(0.0);
      let (iteration, progress) = match count.fract() {
        _ if count == 0.0 => (0.0, 0.0),
        _ if count.is_infinite() => (0.0, 1.0),
        0.0 => (count - 1.0, 1.0),
        fraction => (count.floor(), fraction),
      };
      directed_progress(progress, self.direction, iteration)
    })
  }

  /// When the run next draws something other than what it draws at `now`: the end of its delay, the next step of a
  /// step-eased span, or the end of the iteration or of the run. A span that changes continuously changes at once,
  /// so it returns `now`. `None` once the run is done.
  fn next_change(&self, frames: &[KeyframeEntry], now: Instant) -> Option<Instant> {
    let (iteration, progress) = match self.phase(now) {
      Phase::Delay => return Some(self.start_time + self.delay),
      Phase::Done => return None,
      Phase::Active { iteration, progress } => (iteration, progress),
    };
    let forward = plays_forward(self.direction, iteration);
    let directed = if forward { progress } else { 1.0 - progress };
    // A step never lies past the end of its span, so the end of the iteration bounds it too; a fractional
    // iteration count ends the run inside an iteration.
    let Some(until_step) = distance_to_next_step(frames, directed, forward, &self.easing) else {
      return Some(now);
    };
    let until_end = self.iteration_count - iteration - progress;
    step_time(now, self.duration, until_step.min(until_end))
  }
}

static CLOCK_ORIGIN: OnceLock<Instant> = OnceLock::new();

/// The origin of the process's animation clock, which every in-phase run plays on (see
/// [`AnimationEngine::register_keyframes_in_phase`]): such a run starts a whole number of its periods after this
/// moment. It is the same for every tree, and so for every window, of the process; the first call fixes it.
pub fn clock_origin() -> Instant {
  *CLOCK_ORIGIN.get_or_init(Instant::now)
}

/// How long an in-phase run takes to come back to the same pose: its duration, or two durations for a direction
/// that alternates, so that every run started on that period's grid plays the same iterations forward.
fn phase_period(direction: AnimationDirection, duration: Duration) -> u128 {
  match direction {
    AnimationDirection::Normal | AnimationDirection::Reverse => duration.as_nanos(),
    AnimationDirection::Alternate | AnimationDirection::AlternateReverse => 2 * duration.as_nanos(),
  }
}

/// When a run that first ticks at `now` starts: then, or, in phase, at the last whole number of its periods
/// since the [`clock_origin`].
fn start_time(in_phase: bool, direction: AnimationDirection, duration: Duration, now: Instant) -> Instant {
  if !in_phase || duration.is_zero() {
    return now;
  }
  let since_origin = now.saturating_duration_since(clock_origin());
  let late = since_origin.as_nanos() % phase_period(direction, duration);
  // `late <= now - origin`: the remainder is at most the time since the clock's origin, which a process does not
  // run long enough to take past u64 nanoseconds (584 years). The same bound keeps `now - late` at or after the
  // origin, an `Instant` that exists.
  let late = u64::try_from(late).expect("the time since the animation clock's origin fits in u64 nanoseconds");
  now - Duration::from_nanos(late)
}

/// A full turn about the middle of the element: [`SPIN`](crate::ui::SPIN).
fn spin() -> Keyframes {
  use super::interpolate::AnimatableProperty;
  use crate::node::transform::Decomposed;
  Keyframes::new(crate::ui::SPIN)
    .frame(0.0, |frame| {
      frame.set(AnimatableProperty::Transform, Decomposed::IDENTITY);
    })
    .frame(1.0, |frame| {
      frame.set(
        AnimatableProperty::Transform,
        Decomposed::IDENTITY.with_rotate_deg(360.0),
      );
    })
}

/// The opacity going from `from` to `to`: [`FADE_IN`](crate::ui::FADE_IN), [`FADE_OUT`](crate::ui::FADE_OUT).
fn fade(id: KeyframesId, from: f32, to: f32) -> Keyframes {
  use super::interpolate::{AnimatableProperty, AnimatableValue};
  Keyframes::new(id)
    .frame(0.0, |frame| {
      frame.set(AnimatableProperty::Opacity, AnimatableValue::Float(from));
    })
    .frame(1.0, |frame| {
      frame.set(AnimatableProperty::Opacity, AnimatableValue::Float(to));
    })
}

pub struct AnimationEngine {
  active: HashMap<(NodeId, KeyframesId), AnimationRun>,
  keyframe_store: HashMap<KeyframesId, Vec<KeyframeEntry>>,
  seen: HashSet<NodeId>,
  next_change: Option<Instant>,
  /// Keyframes whose runs play on the process's animation clock: see [`Self::register_keyframes_in_phase`].
  in_phase: HashSet<KeyframesId>,
  /// Nodes that came back while they left, and how much of the animation they enter with is to be taken as played:
  /// as much as was left of the exit they were playing (`Self::turn_round`).
  resumed: HashMap<NodeId, f32>,
  pub has_active: bool,
}

impl Default for AnimationEngine {
  fn default() -> Self {
    Self::new()
  }
}

impl AnimationEngine {
  pub fn new() -> Self {
    let mut engine = Self {
      active: HashMap::new(),
      keyframe_store: HashMap::new(),
      seen: HashSet::new(),
      next_change: None,
      in_phase: HashSet::new(),
      resumed: HashMap::new(),
      has_active: false,
    };
    // What lurq's own components play: a full turn, for a spinner; a fade in and out, for a panel over the window.
    engine.register_keyframes_in_phase(spin());
    engine.register_keyframes(fade(crate::ui::FADE_IN, 0.0, 1.0));
    engine.register_keyframes(fade(crate::ui::FADE_OUT, 1.0, 0.0));
    // A toast coming in and leaving.
    for keyframes in crate::ui::toast_keyframes() {
      engine.register_keyframes(keyframes);
    }
    // A spinner's dots and bars, and a skeleton's pulse and sheen: in phase, so that all of them move as one.
    for keyframes in crate::ui::spinner_keyframes()
      .into_iter()
      .chain(crate::ui::skeleton_keyframes())
    {
      engine.register_keyframes_in_phase(keyframes);
    }
    // A progress that does not know how far it is: the room before its segment, and the segment.
    for keyframes in crate::ui::progress_keyframes() {
      engine.register_keyframes_in_phase(keyframes);
    }
    // A one-time code's caret blinking: from when its cell takes the focus, as a text input's starts on each move.
    for keyframes in crate::ui::input_otp_keyframes() {
      engine.register_keyframes(keyframes);
    }
    // A sheet sliding in from an edge of the window and out to it.
    for keyframes in crate::ui::sheet_keyframes() {
      engine.register_keyframes(keyframes);
    }
    engine
  }

  pub fn register_keyframes(&mut self, keyframes: Keyframes) {
    self.in_phase.remove(&keyframes.id);
    self.keyframe_store.insert(keyframes.id, keyframes.frames);
  }

  /// Registers keyframes whose runs all play in phase on the process's animation clock: a run starts at the last
  /// whole number of its periods since [`clock_origin`], not when its node first ticks. The period is the
  /// animation's duration, or twice it for [`AnimationDirection::Alternate`] and
  /// [`AnimationDirection::AlternateReverse`], so that every run plays the same iterations forward and the same
  /// ones backward. Nodes that mount at different moments, in one window or several, then show the same pose and
  /// change it at the same moments, so a `Steps` spinner shown many times still draws one frame per step.
  ///
  /// A run that mounts late starts part-way through an iteration, as a CSS animation with a negative delay does;
  /// a finite iteration count therefore ends on the clock, not a whole count after the node mounted, and a run
  /// that mounts after that end in its period does not play. The `delay` is counted from the run's start on the
  /// clock, not from the mount: every run plays from a whole number of periods after the origin plus the delay,
  /// so a node that mounts within the delay of its period waits only for the rest of it (showing nothing, or the
  /// first pose with a backwards fill) while nodes that mounted earlier already play, and one that mounts later
  /// plays at once. Runs of the same animation show the same pose whenever they all play.
  ///
  /// Registering the same keyframes with [`Self::register_keyframes`] turns this off for runs that start
  /// afterwards.
  pub fn register_keyframes_in_phase(&mut self, keyframes: Keyframes) {
    self.in_phase.insert(keyframes.id);
    self.keyframe_store.insert(keyframes.id, keyframes.frames);
  }

  /// Forgets the runs of `node`, so that the animation it plays next starts
  /// from its beginning, even one of the keyframes it already played.
  pub(crate) fn forget_node(&mut self, node: NodeId) {
    self.active.retain(|(id, _), _| *id != node);
    // A node that came back while it left and leaves again before it has entered goes on leaving from where it was:
    // as much of its exit is played as is left of the enter it was to go on with.
    if let Some(done) = self.resumed.get_mut(&node) {
      *done = 1.0 - *done;
    }
  }

  /// The nodes `nodes`, which were leaving, come back: each exit stops where it is, and the animation the node
  /// enters with plays from as far in as the exit had left to go, so that what fades in goes on from where it
  /// faded out to.
  pub(crate) fn turn_round(&mut self, nodes: &[NodeId], now: Instant) {
    let nodes: HashSet<NodeId> = nodes.iter().copied().collect();
    let mut resumed = Vec::new();
    self.active.retain(|(node, _), run| {
      if !nodes.contains(node) {
        return true;
      }
      let played = if run.finished || run.duration.is_zero() {
        1.0
      } else {
        let elapsed = now.saturating_duration_since(run.start_time + run.delay);
        (elapsed.as_secs_f32() / run.duration.as_secs_f32()).clamp(0.0, 1.0)
      };
      resumed.push((*node, 1.0 - played));
      false
    });
    self.resumed.extend(resumed);
  }

  pub(crate) fn clear_state(&mut self) {
    self.resumed.clear();
    self.active.clear();
    self.seen.clear();
    self.next_change = None;
    self.has_active = false;
  }

  /// Starts a frame: forgets which animated nodes last frame's walks visited.
  /// A frame may tick several subtrees (base tree, then each overlay), so the
  /// engine can only tell which runs belong to unmounted nodes once all walks
  /// are done — see [`Self::finish_frame`].
  pub(crate) fn begin_frame(&mut self) {
    self.seen.clear();
    self.next_change = None;
  }

  /// Ends a frame after every tick walk ran: drops runs whose node was not
  /// visited by any walk. Runs are kept for the node's whole lifetime (a
  /// finished run guards against restarting the animation), so without this
  /// prune an unmounted spinner's infinite run would keep `has_active` — and
  /// with it full per-frame relayout — for the rest of the process.
  pub(crate) fn finish_frame(&mut self) {
    let seen = &self.seen;
    self.active.retain(|(node_id, _), _| seen.contains(node_id));
    // A node that came back with no animation to enter with has nothing to go on from.
    self.resumed.retain(|node_id, _| seen.contains(node_id));
    self.has_active = self.active.values().any(|run| !run.finished);
  }

  /// The earliest time a run ticked this frame draws something else; see [`AnimationRun::next_change`].
  pub(crate) fn next_change(&self) -> Option<Instant> {
    self.next_change
  }

  pub(crate) fn tick(&mut self, root: &mut crate::node::Node, now: Instant) -> bool {
    self.has_active = false;
    let needs_layout = self.tick_recursive(root, now);
    self.has_active = self.active.values().any(|run| !run.finished);
    needs_layout
  }

  pub(crate) fn tick_preserving_active_state(&mut self, root: &mut crate::node::Node, now: Instant) -> bool {
    let needs_layout = self.tick_recursive(root, now);
    self.has_active = self.active.values().any(|run| !run.finished);
    needs_layout
  }

  fn tick_recursive(&mut self, node: &mut crate::node::Node, now: Instant) -> bool {
    // Only where an animation plays: a subtree of transitions alone has nothing for this engine.
    if !node.prepare_layout_tracking().animations {
      return false;
    }
    #[cfg(test)]
    crate::core::layout_dirty::visit();
    let mut needs_layout = false;
    let node_id = node.node_id();
    if node_id.is_assigned()
      && let Some(spec) = node.playing_animation()
    {
      self.seen.insert(node_id);
      let spec = Animation::clone(spec);
      needs_layout = self.process_node(node, &spec, now);
    }

    for child in &mut node.children {
      if self.tick_recursive(child, now) {
        needs_layout = true;
      }
    }

    if needs_layout {
      node.layout_cache.invalidate();
    }

    needs_layout
  }

  fn process_node(&mut self, node: &mut crate::node::Node, spec: &Animation, now: Instant) -> bool {
    let node_id = node.node_id();
    let key = (node_id, spec.keyframes);
    let iteration_count = match spec.iteration_count {
      AnimationIterationCount::Count(c) => c,
      AnimationIterationCount::Infinite => f64::INFINITY,
    };

    let in_phase = self.in_phase.contains(&spec.keyframes);
    // A node that came back while it left enters from as far in as its exit had left to go.
    let done = if self.active.contains_key(&key) {
      None
    } else {
      self.resumed.remove(&node_id)
    };
    let run = self.active.entry(key).or_insert_with(|| AnimationRun {
      keyframes: spec.keyframes,
      duration: spec.duration,
      delay: spec.delay,
      easing: spec.easing,
      direction: spec.direction,
      fill_mode: spec.fill_mode,
      iteration_count,
      start_time: match done {
        Some(done) => now.checked_sub(spec.duration.mul_f32(done) + spec.delay).unwrap_or(now),
        None => start_time(in_phase, spec.direction, spec.duration, now),
      },
      finished: false,
    });

    let frames = match self.keyframe_store.get(&run.keyframes) {
      Some(f) => f,
      None => return false,
    };

    if run.finished {
      // Each tick clears the overrides, so a run that fills forwards writes its last pose again. It asks for no
      // layout: a node that kept its cache was laid out with this pose, and a rebuilt node never keeps the cache
      // of one holding a layout override (`Node::own_layout_signature_matches`), so it is laid out afresh.
      // Asking here would invalidate the layout on every tick for as long as the pose is held.
      if let Some(progress) = run.final_progress() {
        apply_keyframe_at(node, frames, progress as f32, &run.easing);
      }
      return false;
    }

    let layout_affected = match run.phase(now) {
      Phase::Delay => {
        matches!(run.fill_mode, AnimationFillMode::Backwards | AnimationFillMode::Both)
          && apply_keyframe_at(
            node,
            frames,
            directed_progress(0.0, run.direction, 0.0) as f32,
            &run.easing,
          )
      }
      Phase::Done => {
        run.finished = true;
        run
          .final_progress()
          .is_some_and(|progress| apply_keyframe_at(node, frames, progress as f32, &run.easing))
      }
      Phase::Active { iteration, progress } => {
        let progress = directed_progress(progress, run.direction, iteration);
        apply_keyframe_at(node, frames, progress as f32, &run.easing)
      }
    };
    if let Some(at) = run.next_change(frames, now) {
      self.next_change = Some(self.next_change.map_or(at, |next| next.min(at)));
    }
    layout_affected
  }
}

fn plays_forward(direction: AnimationDirection, iteration: f64) -> bool {
  let even = (iteration as u64).is_multiple_of(2);
  match direction {
    AnimationDirection::Normal => true,
    AnimationDirection::Reverse => false,
    AnimationDirection::Alternate => even,
    AnimationDirection::AlternateReverse => !even,
  }
}

fn directed_progress(progress: f64, direction: AnimationDirection, iteration: f64) -> f64 {
  if plays_forward(direction, iteration) {
    progress
  } else {
    1.0 - progress
  }
}

/// How far keyframe progress moves, in the direction it plays, before the frames draw something else: to the next
/// step of the span at `progress` when that span is step-eased. `None` when the span changes continuously.
fn distance_to_next_step(
  frames: &[KeyframeEntry],
  progress: f64,
  forward: bool,
  overall_easing: &Easing,
) -> Option<f64> {
  let (lo, hi) = find_surrounding_frames(frames, progress as f32);
  if lo == hi {
    return None;
  }
  let (lo_frame, hi_frame) = (&frames[lo], &frames[hi]);
  let span = f64::from(hi_frame.offset - lo_frame.offset);
  if span <= 0.0 {
    return None;
  }
  let local = (progress - f64::from(lo_frame.offset)) / span;
  let easing = lo_frame.easing.as_ref().unwrap_or(overall_easing);
  easing
    .distance_to_next_step(local, forward)
    .map(|distance| distance * span)
}

fn apply_keyframe_at(
  node: &mut crate::node::Node,
  frames: &[KeyframeEntry],
  progress: f32,
  overall_easing: &Easing,
) -> bool {
  if frames.is_empty() {
    return false;
  }

  let mut layout_affected = false;
  let (lo, hi) = find_surrounding_frames(frames, progress);
  let lo_frame = &frames[lo];
  let hi_frame = &frames[hi];

  if lo == hi {
    for (prop, value) in &lo_frame.values {
      layout_affected |= write_property(node, *prop, value);
    }
    return layout_affected;
  }

  let span = hi_frame.offset - lo_frame.offset;
  let local = if span > 0.0 {
    ((progress - lo_frame.offset) / span).clamp(0.0, 1.0)
  } else {
    1.0
  };

  let easing = lo_frame.easing.as_ref().unwrap_or(overall_easing);
  let t = easing.evaluate(local as f64) as f32;

  for (prop, lo_val) in &lo_frame.values {
    if let Some((_, hi_val)) = hi_frame.values.iter().find(|(p, _)| p == prop) {
      let interpolated = lo_val.lerp(hi_val, t);
      layout_affected |= write_property(node, *prop, &interpolated);
    } else {
      layout_affected |= write_property(node, *prop, lo_val);
    }
  }

  layout_affected
}

fn find_surrounding_frames(frames: &[KeyframeEntry], progress: f32) -> (usize, usize) {
  if frames.len() == 1 {
    return (0, 0);
  }

  for (i, frame) in frames.iter().enumerate().skip(1) {
    if frame.offset >= progress {
      return (i - 1, i);
    }
  }

  let last = frames.len() - 1;
  (last, last)
}