Skip to content

Commit

Permalink
feat: on_deps_change method for animations (#977)
Browse files Browse the repository at this point in the history
  • Loading branch information
marc2332 authored Oct 13, 2024
1 parent 65a8be7 commit 672a6b4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
2 changes: 2 additions & 0 deletions crates/components/src/switch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use freya_hooks::{
AnimNum,
Ease,
Function,
OnDepsChange,
SwitchThemeWith,
};
use winit::window::CursorIcon;
Expand Down Expand Up @@ -67,6 +68,7 @@ pub enum SwitchStatus {
pub fn Switch(props: SwitchProps) -> Element {
let theme = use_applied_theme!(&props.theme, switch);
let animation = use_animation_with_dependencies(&theme, |ctx, theme| {
ctx.on_deps_change(OnDepsChange::Run);
(
ctx.with(
AnimNum::new(2., 22.)
Expand Down
21 changes: 19 additions & 2 deletions crates/hooks/src/use_animation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ pub struct Context {
animated_values: Vec<Signal<Box<dyn AnimatedValue>>>,
on_finish: OnFinish,
auto_start: bool,
on_deps_change: OnDepsChange,
}

impl Context {
Expand All @@ -398,6 +399,11 @@ impl Context {
self.auto_start = auto_start;
self
}

pub fn on_deps_change(&mut self, on_deps_change: OnDepsChange) -> &mut Self {
self.on_deps_change = on_deps_change;
self
}
}

/// Controls the direction of the animation.
Expand Down Expand Up @@ -425,6 +431,14 @@ pub enum OnFinish {
Restart,
}

/// What to do once the animation dependencies change. By default it is [`Reset`](OnDepsChange::Reset)
#[derive(PartialEq, Clone, Copy, Default)]
pub enum OnDepsChange {
#[default]
Reset,
Run,
}

/// Animate your elements. Use [`use_animation`] to use this.
#[derive(PartialEq, Clone)]
pub struct UseAnimator<Animated: PartialEq + Clone + 'static> {
Expand All @@ -446,8 +460,11 @@ impl<Animated: PartialEq + Clone + 'static> UseAnimator<Animated> {

/// Reset the animation to the default state.
pub fn reset(&self) {
let mut has_run_yet = self.has_run_yet;
let mut task = self.task;

has_run_yet.set(false);

if let Some(task) = task.write().take() {
task.cancel();
}
Expand Down Expand Up @@ -721,8 +738,8 @@ where
};

use_memo(move || {
let _ = value_and_ctx.read();
if *has_run_yet.peek() {
let value_and_ctx = value_and_ctx.read();
if *has_run_yet.peek() && value_and_ctx.1.on_deps_change == OnDepsChange::Run {
animator.run_update()
}
});
Expand Down

0 comments on commit 672a6b4

Please sign in to comment.