d4de07658dfd94530d267718348234b7a07aa1f65cfb2c81b7a5dc35327a73e745cbbffb4e8388a57959b007b276eb24f3e9061a3ab6b86d902a7b8b2b2272 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { AsyncAction } from './AsyncAction';
  2. import { AnimationFrameScheduler } from './AnimationFrameScheduler';
  3. import { SchedulerAction } from '../types';
  4. import { animationFrameProvider } from './animationFrameProvider';
  5. import { TimerHandle } from './timerHandle';
  6. export class AnimationFrameAction<T> extends AsyncAction<T> {
  7. constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {
  8. super(scheduler, work);
  9. }
  10. protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {
  11. // If delay is greater than 0, request as an async action.
  12. if (delay !== null && delay > 0) {
  13. return super.requestAsyncId(scheduler, id, delay);
  14. }
  15. // Push the action to the end of the scheduler queue.
  16. scheduler.actions.push(this);
  17. // If an animation frame has already been requested, don't request another
  18. // one. If an animation frame hasn't been requested yet, request one. Return
  19. // the current animation frame request id.
  20. return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));
  21. }
  22. protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {
  23. // If delay exists and is greater than 0, or if the delay is null (the
  24. // action wasn't rescheduled) but was originally scheduled as an async
  25. // action, then recycle as an async action.
  26. if (delay != null ? delay > 0 : this.delay > 0) {
  27. return super.recycleAsyncId(scheduler, id, delay);
  28. }
  29. // If the scheduler queue has no remaining actions with the same async id,
  30. // cancel the requested animation frame and set the scheduled flag to
  31. // undefined so the next AnimationFrameAction will request its own.
  32. const { actions } = scheduler;
  33. if (id != null && id === scheduler._scheduled && actions[actions.length - 1]?.id !== id) {
  34. animationFrameProvider.cancelAnimationFrame(id as number);
  35. scheduler._scheduled = undefined;
  36. }
  37. // Return undefined so the action knows to request a new async id if it's rescheduled.
  38. return undefined;
  39. }
  40. }