1use egui::Color32;
12
13use super::PlotConfig;
14use super::{PlotState, scene::Dash};
15
16#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum LegendAnimation {
22 #[default]
24 Blink,
25 Fade,
27 Throb,
29 DashMarch,
31 DashToggle,
33 Glow,
35 Sweep,
37 Wiggle,
39 Reveal,
41 MarkerBounce,
43 MarkerPulse,
45 Twinkle,
47 Wave,
49}
50
51impl LegendAnimation {
52 pub const ALL: [Self; 13] = [
54 Self::Blink,
55 Self::Fade,
56 Self::Throb,
57 Self::DashMarch,
58 Self::DashToggle,
59 Self::Glow,
60 Self::Sweep,
61 Self::Wiggle,
62 Self::Reveal,
63 Self::MarkerBounce,
64 Self::MarkerPulse,
65 Self::Twinkle,
66 Self::Wave,
67 ];
68
69 pub const fn label(self) -> &'static str {
71 match self {
72 Self::Blink => "Blink",
73 Self::Fade => "Fade",
74 Self::Throb => "Throb",
75 Self::DashMarch => "Marching dashes",
76 Self::DashToggle => "Dash toggle",
77 Self::Glow => "Glow",
78 Self::Sweep => "Sweep",
79 Self::Wiggle => "Wiggle",
80 Self::Reveal => "Reveal",
81 Self::MarkerBounce => "Marker bounce",
82 Self::MarkerPulse => "Marker pulse",
83 Self::Twinkle => "Twinkle",
84 Self::Wave => "Color wave",
85 }
86 }
87}
88
89#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
91#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum AnimationEasing {
95 #[default]
97 Linear,
98 EaseIn,
100 EaseOut,
102 EaseInOut,
104 Step,
106 Sine,
108}
109
110impl AnimationEasing {
111 pub const ALL: [Self; 6] = [
113 Self::Linear,
114 Self::EaseIn,
115 Self::EaseOut,
116 Self::EaseInOut,
117 Self::Step,
118 Self::Sine,
119 ];
120
121 pub const fn label(self) -> &'static str {
123 match self {
124 Self::Linear => "Linear",
125 Self::EaseIn => "Ease in",
126 Self::EaseOut => "Ease out",
127 Self::EaseInOut => "Ease in-out",
128 Self::Step => "Step",
129 Self::Sine => "Sine",
130 }
131 }
132
133 pub fn apply(self, t: f32) -> f32 {
135 let t = t.clamp(0.0, 1.0);
136 match self {
137 Self::Linear => t,
138 Self::EaseIn => t * t,
139 Self::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
140 Self::EaseInOut => t * t * (3.0 - 2.0 * t),
141 Self::Step => {
142 if t < 0.5 {
143 0.0
144 } else {
145 1.0
146 }
147 }
148 Self::Sine => 0.5 - 0.5 * (std::f32::consts::TAU * t).cos(),
149 }
150 }
151}
152
153#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
154#[derive(Clone, Copy, Debug, PartialEq)]
156pub struct LegendHoverConfig {
157 pub enabled: bool,
159 pub animation: LegendAnimation,
161 pub easing: AnimationEasing,
163 pub period: f32,
165 pub highlight: Option<Color32>,
167}
168
169impl Default for LegendHoverConfig {
170 fn default() -> Self {
171 Self {
172 enabled: true,
173 animation: LegendAnimation::Blink,
174 easing: AnimationEasing::Linear,
175 period: 1.2,
176 highlight: None,
177 }
178 }
179}
180
181#[derive(Clone, Copy, Debug, PartialEq)]
183pub(super) struct Effect {
184 pub kind: LegendAnimation,
185 pub phase: f32,
187 pub highlight: Color32,
188 pub blink: Color32,
191}
192
193impl Effect {
194 pub(super) fn for_hover(
196 config: &PlotConfig,
197 state: &PlotState,
198 series: usize,
199 now: f64,
200 theme: &crisol_ui_kit::theme::Theme,
201 motion: bool,
202 ) -> Option<Self> {
203 Self::for_legend(
204 &config.legend_hover,
205 state.legend_hover(),
206 state.legend_hover_start(),
207 series,
208 now,
209 theme,
210 motion,
211 )
212 }
213
214 pub(super) fn for_legend(
217 hover: &LegendHoverConfig,
218 hovered: Option<usize>,
219 start: f64,
220 series: usize,
221 now: f64,
222 theme: &crisol_ui_kit::theme::Theme,
223 motion: bool,
224 ) -> Option<Self> {
225 if !hover.enabled || !motion || hovered != Some(series) {
226 return None;
227 }
228 let period = f64::from(hover.period.max(0.2));
229 let elapsed = (now - start).max(0.0);
230 let t = (elapsed / period).rem_euclid(1.0) as f32;
231 Some(Self {
232 kind: hover.animation,
233 phase: hover.easing.apply(t),
234 highlight: hover.highlight.unwrap_or(theme.warning),
235 blink: hover.highlight.unwrap_or(if theme.is_dark() {
236 Color32::WHITE
237 } else {
238 Color32::BLACK
239 }),
240 })
241 }
242
243 pub(super) fn wave(self) -> f32 {
245 0.5 - 0.5 * (std::f32::consts::TAU * self.phase).cos()
246 }
247
248 pub(super) fn color(self, base: Color32) -> Color32 {
250 match self.kind {
251 LegendAnimation::Blink => mix(self.blink, base, self.wave()),
254 LegendAnimation::Fade => base.gamma_multiply(1.0 - 0.65 * self.wave()),
255 LegendAnimation::Throb => mix(base, self.highlight, 0.3 * self.wave()),
256 LegendAnimation::Wave => mix(base, self.highlight, 0.55 * self.phase),
257 LegendAnimation::Glow | LegendAnimation::Sweep | LegendAnimation::Reveal => {
258 mix(base, self.highlight, 0.35 * self.wave())
259 }
260 _ => mix(base, self.highlight, 0.18 * self.wave()),
261 }
262 }
263
264 pub(super) fn halo(self) -> Option<Color32> {
266 (self.kind == LegendAnimation::Glow).then(|| self.highlight.gamma_multiply(0.18 + 0.25 * self.wave()))
267 }
268
269 pub(super) fn width(self, base: f32) -> f32 {
271 match self.kind {
272 LegendAnimation::Throb => base * (1.0 + 0.9 * self.wave()),
273 LegendAnimation::Glow => base * 1.15,
274 _ => base,
275 }
276 }
277
278 pub(super) fn dash(self, base: Dash) -> Dash {
280 match self.kind {
281 LegendAnimation::DashMarch => {
282 let (dash, gap) = dash_gap(base);
283 Dash::Marching {
284 dash,
285 gap,
286 offset: self.phase * (dash + gap) * 2.0,
287 }
288 }
289 LegendAnimation::DashToggle => {
290 let (dash, gap) = dash_gap(base);
291 let grow = self.wave();
292 if grow < 0.08 {
293 Dash::Solid
294 } else {
295 Dash::Dashed(dash * grow, gap * grow)
296 }
297 }
298 _ => base,
299 }
300 }
301
302 pub(super) fn point_offset(self, index: usize, tangent: egui::Vec2) -> egui::Vec2 {
304 if self.kind != LegendAnimation::Wiggle {
305 return egui::Vec2::ZERO;
306 }
307 let length = tangent.length();
308 if length < 1e-3 {
309 return egui::Vec2::ZERO;
310 }
311 let normal = egui::vec2(-tangent.y, tangent.x) / length;
312 normal * ((index as f32 * 0.55 + self.phase * std::f32::consts::TAU).sin() * 3.0)
313 }
314
315 pub(super) fn marker_offset(self, index: usize) -> egui::Vec2 {
317 match self.kind {
318 LegendAnimation::MarkerBounce => {
319 let t = index as f32 * 0.8 + self.phase * std::f32::consts::TAU;
320 egui::vec2(0.0, -((t.sin() + 1.0) * 2.5))
321 }
322 _ => egui::Vec2::ZERO,
323 }
324 }
325
326 pub(super) fn marker_radius(self, base: f32, index: usize) -> f32 {
328 match self.kind {
329 LegendAnimation::MarkerPulse => base * (1.0 + 0.7 * self.wave()),
330 LegendAnimation::Twinkle => base * (0.7 + 0.8 * (index as f32 * 0.9 + self.phase * 6.0).sin().abs()),
331 _ => base,
332 }
333 }
334
335 pub(super) fn highlighted(self, points: &[egui::Pos2]) -> Option<Vec<egui::Pos2>> {
337 let count = points.len();
338 if count < 2 {
339 return None;
340 }
341 match self.kind {
342 LegendAnimation::Sweep => {
343 let span = (count / 4).max(2);
344 let start = ((count - span) as f32 * self.phase) as usize;
345 Some(points[start..(start + span).min(count)].to_vec())
346 }
347 LegendAnimation::Reveal => {
348 let end = (count as f32 * self.phase).ceil() as usize;
349 (end >= 2).then(|| points[..end.min(count)].to_vec())
350 }
351 _ => None,
352 }
353 }
354
355 pub(super) fn explode(self) -> f32 {
357 match self.kind {
358 LegendAnimation::Wiggle | LegendAnimation::MarkerBounce => 5.0 + 2.0 * self.wave(),
359 _ => 3.0 + 2.0 * self.wave(),
360 }
361 }
362
363 pub(super) fn radial_scale(self) -> f32 {
365 match self.kind {
366 LegendAnimation::Wiggle => 1.0 + 0.06 * self.wave(),
367 LegendAnimation::Throb => 1.0 + 0.03 * self.wave(),
368 _ => 1.0,
369 }
370 }
371}
372
373fn dash_gap(dash: Dash) -> (f32, f32) {
374 match dash {
375 Dash::Solid => (7.0, 4.0),
376 Dash::Dashed(dash, gap) => (dash, gap),
377 Dash::Dotted(spacing) => (spacing * 0.5, spacing),
378 Dash::Marching { dash, gap, .. } => (dash, gap),
379 }
380}
381
382pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
384 let t = t.clamp(0.0, 1.0);
385 let [ar, ag, ab, aa] = a.to_srgba_unmultiplied();
386 let [br, bg, bb, ba] = b.to_srgba_unmultiplied();
387 let channel = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * t).round() as u8;
388 Color32::from_rgba_unmultiplied(channel(ar, br), channel(ag, bg), channel(ab, bb), channel(aa, ba))
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[test]
396 fn easing_stays_in_range_and_shapes_the_cycle() {
397 for easing in AnimationEasing::ALL {
398 for step in 0..=20 {
399 let t = easing.apply(step as f32 / 20.0);
400 assert!((0.0..=1.0).contains(&t), "{easing:?} at {step}: {t}");
401 }
402 }
403 assert_eq!(AnimationEasing::Linear.apply(0.25), 0.25);
404 assert!(AnimationEasing::EaseIn.apply(0.25) < 0.25);
405 assert!(AnimationEasing::EaseOut.apply(0.25) > 0.25);
406 }
407
408 #[test]
409 fn every_animation_has_a_label() {
410 for animation in LegendAnimation::ALL {
411 assert!(!animation.label().is_empty());
412 }
413 }
414
415 #[test]
416 fn mix_blends_both_ends() {
417 let a = Color32::from_rgb(0, 0, 0);
418 let b = Color32::from_rgb(200, 100, 50);
419 assert_eq!(mix(a, b, 0.0), a);
420 assert_eq!(mix(a, b, 1.0), b);
421 assert_eq!(mix(a, b, 0.5), Color32::from_rgb(100, 50, 25));
422 }
423
424 #[test]
425 fn the_hover_effect_follows_the_pointer_and_reduced_motion() {
426 let config = PlotConfig::default();
427 let mut state = PlotState::default();
428 let theme = crisol_ui_kit::theme::Theme::dark();
429 assert!(Effect::for_hover(&config, &state, 0, 0.0, &theme, true).is_none());
430 state.set_legend_hover(Some(0), 1.0);
431 let effect = Effect::for_hover(&config, &state, 0, 1.6, &theme, true).expect("hovered");
432 assert_eq!(effect.kind, LegendAnimation::Blink);
433 assert!(effect.wave() > 0.0);
434 assert!(Effect::for_hover(&config, &state, 1, 1.6, &theme, true).is_none());
435 assert!(Effect::for_hover(&config, &state, 0, 1.6, &theme, false).is_none());
436 }
437
438 #[test]
439 fn blink_goes_from_white_on_dark_and_black_on_light() {
440 let base = Color32::from_rgb(30, 120, 220);
441 let dark = Effect {
442 kind: LegendAnimation::Blink,
443 phase: 0.0,
444 highlight: Color32::YELLOW,
445 blink: Color32::WHITE,
446 };
447 let light = Effect {
448 blink: Color32::BLACK,
449 ..dark
450 };
451 assert_eq!(dark.color(base), Color32::WHITE);
452 assert_eq!(light.color(base), Color32::BLACK);
453 let mid = Effect { phase: 0.5, ..dark };
454 assert_eq!(mid.color(base), base);
455 }
456}