b10e1445a6a2b598423e431ee059d1b4cb4aea0a007b72351bf32c9e4f986ebbdf70f71c223c31d4a12955d21afdb0069dc2ae43846dfd5f9d1e518840bfa4 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import { Observable } from '../../Observable';
  2. import { TimestampProvider } from '../../types';
  3. import { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';
  4. import { animationFrameProvider } from '../../scheduler/animationFrameProvider';
  5. /**
  6. * An observable of animation frames
  7. *
  8. * Emits the amount of time elapsed since subscription and the timestamp on each animation frame.
  9. * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.
  10. *
  11. * Every subscription will start a separate animation loop. Since animation frames are always scheduled
  12. * by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously
  13. * should not be much different or have more overhead than looping over an array of events during
  14. * a single animation frame. However, if for some reason the developer would like to ensure the
  15. * execution of animation-related handlers are all executed during the same task by the engine,
  16. * the `share` operator can be used.
  17. *
  18. * This is useful for setting up animations with RxJS.
  19. *
  20. * ## Examples
  21. *
  22. * Tweening a div to move it on the screen
  23. *
  24. * ```ts
  25. * import { animationFrames, map, takeWhile, endWith } from 'rxjs';
  26. *
  27. * function tween(start: number, end: number, duration: number) {
  28. * const diff = end - start;
  29. * return animationFrames().pipe(
  30. * // Figure out what percentage of time has passed
  31. * map(({ elapsed }) => elapsed / duration),
  32. * // Take the vector while less than 100%
  33. * takeWhile(v => v < 1),
  34. * // Finish with 100%
  35. * endWith(1),
  36. * // Calculate the distance traveled between start and end
  37. * map(v => v * diff + start)
  38. * );
  39. * }
  40. *
  41. * // Setup a div for us to move around
  42. * const div = document.createElement('div');
  43. * document.body.appendChild(div);
  44. * div.style.position = 'absolute';
  45. * div.style.width = '40px';
  46. * div.style.height = '40px';
  47. * div.style.backgroundColor = 'lime';
  48. * div.style.transform = 'translate3d(10px, 0, 0)';
  49. *
  50. * tween(10, 200, 4000).subscribe(x => {
  51. * div.style.transform = `translate3d(${ x }px, 0, 0)`;
  52. * });
  53. * ```
  54. *
  55. * Providing a custom timestamp provider
  56. *
  57. * ```ts
  58. * import { animationFrames, TimestampProvider } from 'rxjs';
  59. *
  60. * // A custom timestamp provider
  61. * let now = 0;
  62. * const customTSProvider: TimestampProvider = {
  63. * now() { return now++; }
  64. * };
  65. *
  66. * const source$ = animationFrames(customTSProvider);
  67. *
  68. * // Log increasing numbers 0...1...2... on every animation frame.
  69. * source$.subscribe(({ elapsed }) => console.log(elapsed));
  70. * ```
  71. *
  72. * @param timestampProvider An object with a `now` method that provides a numeric timestamp
  73. */
  74. export function animationFrames(timestampProvider?: TimestampProvider) {
  75. return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;
  76. }
  77. /**
  78. * Does the work of creating the observable for `animationFrames`.
  79. * @param timestampProvider The timestamp provider to use to create the observable
  80. */
  81. function animationFramesFactory(timestampProvider?: TimestampProvider) {
  82. return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {
  83. // If no timestamp provider is specified, use performance.now() - as it
  84. // will return timestamps 'compatible' with those passed to the run
  85. // callback and won't be affected by NTP adjustments, etc.
  86. const provider = timestampProvider || performanceTimestampProvider;
  87. // Capture the start time upon subscription, as the run callback can remain
  88. // queued for a considerable period of time and the elapsed time should
  89. // represent the time elapsed since subscription - not the time since the
  90. // first rendered animation frame.
  91. const start = provider.now();
  92. let id = 0;
  93. const run = () => {
  94. if (!subscriber.closed) {
  95. id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {
  96. id = 0;
  97. // Use the provider's timestamp to calculate the elapsed time. Note that
  98. // this means - if the caller hasn't passed a provider - that
  99. // performance.now() will be used instead of the timestamp that was
  100. // passed to the run callback. The reason for this is that the timestamp
  101. // passed to the callback can be earlier than the start time, as it
  102. // represents the time at which the browser decided it would render any
  103. // queued frames - and that time can be earlier the captured start time.
  104. const now = provider.now();
  105. subscriber.next({
  106. timestamp: timestampProvider ? now : timestamp,
  107. elapsed: now - start,
  108. });
  109. run();
  110. });
  111. }
  112. };
  113. run();
  114. return () => {
  115. if (id) {
  116. animationFrameProvider.cancelAnimationFrame(id);
  117. }
  118. };
  119. });
  120. }
  121. /**
  122. * In the common case, where the timestamp provided by the rAF API is used,
  123. * we use this shared observable to reduce overhead.
  124. */
  125. const DEFAULT_ANIMATION_FRAMES = animationFramesFactory();