Debian Codegraph @

node/rxjs/src/internal/observable/dom/animationFrames.ts

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