GroupAnimation.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { supportsScrollTimeline } from '../utils/supports/scroll-timeline.mjs';
  2. class GroupAnimation {
  3. constructor(animations) {
  4. // Bound to accomodate common `return animation.stop` pattern
  5. this.stop = () => this.runAll("stop");
  6. this.animations = animations.filter(Boolean);
  7. }
  8. get finished() {
  9. return Promise.all(this.animations.map((animation) => animation.finished));
  10. }
  11. /**
  12. * TODO: Filter out cancelled or stopped animations before returning
  13. */
  14. getAll(propName) {
  15. return this.animations[0][propName];
  16. }
  17. setAll(propName, newValue) {
  18. for (let i = 0; i < this.animations.length; i++) {
  19. this.animations[i][propName] = newValue;
  20. }
  21. }
  22. attachTimeline(timeline, fallback) {
  23. const subscriptions = this.animations.map((animation) => {
  24. if (supportsScrollTimeline() && animation.attachTimeline) {
  25. return animation.attachTimeline(timeline);
  26. }
  27. else if (typeof fallback === "function") {
  28. return fallback(animation);
  29. }
  30. });
  31. return () => {
  32. subscriptions.forEach((cancel, i) => {
  33. cancel && cancel();
  34. this.animations[i].stop();
  35. });
  36. };
  37. }
  38. get time() {
  39. return this.getAll("time");
  40. }
  41. set time(time) {
  42. this.setAll("time", time);
  43. }
  44. get speed() {
  45. return this.getAll("speed");
  46. }
  47. set speed(speed) {
  48. this.setAll("speed", speed);
  49. }
  50. get startTime() {
  51. return this.getAll("startTime");
  52. }
  53. get duration() {
  54. let max = 0;
  55. for (let i = 0; i < this.animations.length; i++) {
  56. max = Math.max(max, this.animations[i].duration);
  57. }
  58. return max;
  59. }
  60. runAll(methodName) {
  61. this.animations.forEach((controls) => controls[methodName]());
  62. }
  63. flatten() {
  64. this.runAll("flatten");
  65. }
  66. play() {
  67. this.runAll("play");
  68. }
  69. pause() {
  70. this.runAll("pause");
  71. }
  72. cancel() {
  73. this.runAll("cancel");
  74. }
  75. complete() {
  76. this.runAll("complete");
  77. }
  78. }
  79. export { GroupAnimation };