1use std::num::NonZeroU32;
12use std::ops::Deref;
13
14use serde::{Deserialize, Serialize};
15
16use super::icons::IconData;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct EmptyFrameListError;
21
22impl std::fmt::Display for EmptyFrameListError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 f.write_str("frame list must not be empty")
25 }
26}
27
28impl std::error::Error for EmptyFrameListError {}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
50pub struct FrameList(Vec<IconData>);
51
52impl FrameList {
53 pub fn new(frames: Vec<IconData>) -> Result<Self, EmptyFrameListError> {
55 if frames.is_empty() {
56 return Err(EmptyFrameListError);
57 }
58 Ok(Self(frames))
59 }
60
61 pub fn first(&self) -> &IconData {
63 debug_assert!(
68 !self.0.is_empty(),
69 "FrameList invariant violated: empty list"
70 );
71 #[allow(clippy::indexing_slicing)]
72 {
73 &self.0[0]
74 }
75 }
76
77 #[must_use]
82 #[allow(clippy::len_without_is_empty)]
83 pub fn len(&self) -> usize {
84 self.0.len()
85 }
86}
87
88impl Deref for FrameList {
89 type Target = [IconData];
90 fn deref(&self) -> &[IconData] {
91 &self.0
92 }
93}
94
95impl<'de> serde::Deserialize<'de> for FrameList {
98 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
99 where
100 D: serde::Deserializer<'de>,
101 {
102 let frames = Vec::<IconData>::deserialize(deserializer)?;
103 FrameList::new(frames).map_err(|_| serde::de::Error::custom("frame list must not be empty"))
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
120#[non_exhaustive]
121pub enum TransformAnimation {
122 Spin {
124 duration_ms: NonZeroU32,
126 },
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct FramesData {
132 frames: FrameList,
133 frame_duration_ms: NonZeroU32,
134}
135
136impl FramesData {
137 #[must_use]
139 pub fn frames(&self) -> &FrameList {
140 &self.frames
141 }
142
143 #[must_use]
145 pub fn frame_duration_ms(&self) -> NonZeroU32 {
146 self.frame_duration_ms
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct TransformData {
153 icon: IconData,
154 animation: TransformAnimation,
155}
156
157impl TransformData {
158 pub fn icon(&self) -> &IconData {
160 &self.icon
161 }
162
163 #[must_use]
165 pub fn animation(&self) -> &TransformAnimation {
166 &self.animation
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220#[non_exhaustive]
221pub enum AnimatedIcon {
222 Frames(FramesData),
224 Transform(TransformData),
226}
227
228impl AnimatedIcon {
229 pub fn frames(
252 frames: Vec<IconData>,
253 frame_duration_ms: NonZeroU32,
254 ) -> Result<Self, EmptyFrameListError> {
255 Ok(AnimatedIcon::Frames(FramesData {
256 frames: FrameList::new(frames)?,
257 frame_duration_ms,
258 }))
259 }
260
261 #[must_use]
276 pub fn transform(icon: IconData, animation: TransformAnimation) -> Self {
277 AnimatedIcon::Transform(TransformData { icon, animation })
278 }
279
280 pub fn first_frame(&self) -> &IconData {
307 match self {
308 AnimatedIcon::Frames(data) => data.frames.first(),
309 AnimatedIcon::Transform(data) => &data.icon,
310 }
311 }
312
313 #[must_use]
315 pub fn frame_list(&self) -> Option<&FrameList> {
316 match self {
317 AnimatedIcon::Frames(data) => Some(&data.frames),
318 AnimatedIcon::Transform(_) => None,
319 }
320 }
321
322 #[must_use]
324 pub fn frame_duration_ms(&self) -> Option<NonZeroU32> {
325 match self {
326 AnimatedIcon::Frames(data) => Some(data.frame_duration_ms),
327 AnimatedIcon::Transform(_) => None,
328 }
329 }
330
331 #[must_use]
333 pub fn icon(&self) -> Option<&IconData> {
334 match self {
335 AnimatedIcon::Transform(data) => Some(&data.icon),
336 AnimatedIcon::Frames(_) => None,
337 }
338 }
339
340 #[must_use]
342 pub fn animation(&self) -> Option<&TransformAnimation> {
343 match self {
344 AnimatedIcon::Transform(data) => Some(&data.animation),
345 AnimatedIcon::Frames(_) => None,
346 }
347 }
348}
349
350#[cfg(test)]
351#[allow(clippy::unwrap_used, clippy::expect_used)]
352mod tests {
353 use super::*;
354 use std::borrow::Cow;
355
356 fn test_icon(label: &'static str) -> IconData {
357 IconData::Svg(Cow::Owned(format!("<svg>{label}</svg>").into_bytes()))
358 }
359
360 fn test_icon_borrowed() -> IconData {
361 IconData::Svg(Cow::Borrowed(b"<svg>test</svg>"))
362 }
363
364 fn nz(val: u32) -> NonZeroU32 {
365 NonZeroU32::new(val).unwrap()
366 }
367
368 #[test]
371 fn frame_list_new_with_one_frame() {
372 let fl = FrameList::new(vec![test_icon("f1")]);
373 assert!(fl.is_ok());
374 assert_eq!(fl.unwrap().len(), 1);
375 }
376
377 #[test]
378 fn frame_list_new_with_multiple_frames() {
379 let fl = FrameList::new(vec![test_icon("f1"), test_icon("f2"), test_icon("f3")]).unwrap();
380 assert_eq!(fl.len(), 3);
381 }
382
383 #[test]
384 fn frame_list_new_rejects_empty() {
385 let fl = FrameList::new(vec![]);
386 assert!(fl.is_err());
387 assert_eq!(fl.unwrap_err(), EmptyFrameListError);
388 }
389
390 #[test]
391 fn frame_list_first_returns_first_frame() {
392 let icon = test_icon("first");
393 let fl = FrameList::new(vec![icon.clone(), test_icon("second")]).unwrap();
394 assert_eq!(fl.first(), &icon);
395 }
396
397 #[test]
398 fn frame_list_deref_to_slice() {
399 let fl = FrameList::new(vec![test_icon("a"), test_icon("b")]).unwrap();
400 let slice: &[IconData] = &fl;
401 assert_eq!(slice.len(), 2);
402 assert_eq!(fl.iter().count(), 2);
404 }
405
406 #[test]
407 fn empty_frame_list_error_display() {
408 let err = EmptyFrameListError;
409 assert_eq!(err.to_string(), "frame list must not be empty");
410 }
411
412 #[test]
413 fn empty_frame_list_error_is_std_error() {
414 let err: Box<dyn std::error::Error> = Box::new(EmptyFrameListError);
415 assert_eq!(err.to_string(), "frame list must not be empty");
416 }
417
418 #[test]
421 fn frame_list_deserialize_rejects_empty_json() {
422 let json = "[]";
423 let result: Result<FrameList, _> = serde_json::from_str(json);
424 assert!(result.is_err());
425 let err = result.unwrap_err().to_string();
426 assert!(
427 err.contains("frame list must not be empty"),
428 "expected custom error message, got: {err}"
429 );
430 }
431
432 #[test]
433 fn frame_list_deserialize_non_empty_json_succeeds() {
434 let fl = FrameList::new(vec![test_icon_borrowed()]).unwrap();
436 let json = serde_json::to_string(&fl).unwrap();
437 let deserialized: FrameList = serde_json::from_str(&json).unwrap();
438 assert_eq!(deserialized.len(), 1);
439 }
440
441 #[test]
442 fn frame_list_round_trips_through_json() {
443 let fl = FrameList::new(vec![test_icon("a"), test_icon("b")]).unwrap();
444 let json = serde_json::to_string(&fl).unwrap();
445 let back: FrameList = serde_json::from_str(&json).unwrap();
446 assert_eq!(fl, back);
447 }
448
449 #[test]
452 fn frames_variant_constructs() {
453 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(83)).unwrap();
454 assert!(matches!(icon, AnimatedIcon::Frames(_)));
455 if let AnimatedIcon::Frames(data) = &icon {
456 assert_eq!(data.frames().len(), 1);
457 assert_eq!(data.frame_duration_ms().get(), 83);
458 }
459 }
460
461 #[test]
462 fn frames_constructor_rejects_empty() {
463 let result = AnimatedIcon::frames(vec![], nz(83));
464 assert!(result.is_err());
465 }
466
467 #[test]
468 fn transform_variant_constructs() {
469 let icon = AnimatedIcon::transform(
470 test_icon("spinner"),
471 TransformAnimation::Spin {
472 duration_ms: nz(1000),
473 },
474 );
475 assert!(matches!(icon, AnimatedIcon::Transform(_)));
476 if let AnimatedIcon::Transform(data) = &icon {
477 assert_eq!(
478 *data.animation(),
479 TransformAnimation::Spin {
480 duration_ms: nz(1000)
481 }
482 );
483 }
484 }
485
486 #[test]
487 #[allow(clippy::clone_on_copy)]
488 fn transform_animation_is_copy_clone_debug_eq_hash() {
489 let a = TransformAnimation::Spin {
490 duration_ms: nz(500),
491 };
492 let a2 = a; let a3 = a.clone(); assert_eq!(a2, a3); use std::hash::Hash;
496 let mut hasher = std::collections::hash_map::DefaultHasher::new();
497 a.hash(&mut hasher);
498 let _ = format!("{a:?}"); }
500
501 #[test]
502 fn animated_icon_is_clone_debug_eq_not_copy() {
503 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(100)).unwrap();
504 let cloned = icon.clone(); assert_eq!(icon, cloned); let _ = format!("{icon:?}"); }
508
509 #[test]
512 fn first_frame_frames_with_items() {
513 let f0 = test_icon("frame0");
514 let icon = AnimatedIcon::frames(vec![f0.clone(), test_icon("frame1")], nz(100)).unwrap();
515 assert_eq!(icon.first_frame(), &f0);
517 }
518
519 #[test]
520 fn first_frame_transform() {
521 let data = test_icon("spin");
522 let icon = AnimatedIcon::transform(
523 data.clone(),
524 TransformAnimation::Spin {
525 duration_ms: nz(1000),
526 },
527 );
528 assert_eq!(icon.first_frame(), &data);
529 }
530
531 #[test]
534 fn frame_list_accessor_returns_some_for_frames() {
535 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(83)).unwrap();
536 assert!(icon.frame_list().is_some());
537 assert_eq!(icon.frame_list().unwrap().len(), 1);
538 }
539
540 #[test]
541 fn frame_list_accessor_returns_none_for_transform() {
542 let icon = AnimatedIcon::transform(
543 test_icon("spin"),
544 TransformAnimation::Spin {
545 duration_ms: nz(1000),
546 },
547 );
548 assert!(icon.frame_list().is_none());
549 }
550
551 #[test]
552 fn frame_duration_ms_accessor() {
553 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(42)).unwrap();
554 assert_eq!(icon.frame_duration_ms().unwrap().get(), 42);
555 }
556
557 #[test]
558 fn icon_accessor_returns_some_for_transform() {
559 let data = test_icon("spin");
560 let icon = AnimatedIcon::transform(
561 data.clone(),
562 TransformAnimation::Spin {
563 duration_ms: nz(1000),
564 },
565 );
566 assert_eq!(icon.icon(), Some(&data));
567 }
568
569 #[test]
570 fn icon_accessor_returns_none_for_frames() {
571 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(83)).unwrap();
572 assert!(icon.icon().is_none());
573 }
574
575 #[test]
576 fn animation_accessor_returns_some_for_transform() {
577 let anim = TransformAnimation::Spin {
578 duration_ms: nz(1000),
579 };
580 let icon = AnimatedIcon::transform(test_icon("spin"), anim);
581 assert_eq!(icon.animation(), Some(&anim));
582 }
583
584 #[test]
585 fn animation_accessor_returns_none_for_frames() {
586 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(83)).unwrap();
587 assert!(icon.animation().is_none());
588 }
589
590 #[test]
593 fn animated_icon_frames_round_trips_json() {
594 let icon = AnimatedIcon::frames(vec![test_icon("f1"), test_icon("f2")], nz(83)).unwrap();
595 let json = serde_json::to_string(&icon).unwrap();
596 let back: AnimatedIcon = serde_json::from_str(&json).unwrap();
597 assert_eq!(icon, back);
598 }
599
600 #[test]
601 fn animated_icon_transform_round_trips_json() {
602 let icon = AnimatedIcon::transform(
603 test_icon("spinner"),
604 TransformAnimation::Spin {
605 duration_ms: nz(1000),
606 },
607 );
608 let json = serde_json::to_string(&icon).unwrap();
609 let back: AnimatedIcon = serde_json::from_str(&json).unwrap();
610 assert_eq!(icon, back);
611 }
612
613 #[test]
614 fn transform_animation_spin_uses_non_zero_u32() {
615 assert!(NonZeroU32::new(0).is_none());
617 let anim = TransformAnimation::Spin {
619 duration_ms: nz(500),
620 };
621 let TransformAnimation::Spin { duration_ms } = anim;
622 assert_eq!(duration_ms.get(), 500);
623 }
624
625 #[test]
628 fn frames_data_accessors() {
629 let icon = AnimatedIcon::frames(vec![test_icon("f1")], nz(83)).unwrap();
630 if let AnimatedIcon::Frames(data) = &icon {
631 assert_eq!(data.frames().len(), 1);
632 assert_eq!(data.frame_duration_ms().get(), 83);
633 } else {
634 panic!("expected Frames variant");
635 }
636 }
637
638 #[test]
639 fn transform_data_accessors() {
640 let icon_data = test_icon("spin");
641 let anim = TransformAnimation::Spin {
642 duration_ms: nz(1000),
643 };
644 let icon = AnimatedIcon::transform(icon_data.clone(), anim);
645 if let AnimatedIcon::Transform(data) = &icon {
646 assert_eq!(data.icon(), &icon_data);
647 assert_eq!(*data.animation(), anim);
648 } else {
649 panic!("expected Transform variant");
650 }
651 }
652}