All files / src/raf raf.ts

55.71% Statements 78/140
50% Branches 33/66
42.3% Functions 22/52
56.52% Lines 78/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828                                                                                                                                                                                                                                                                                                                                                                                                    7x 7x       7x                                     7x             7x             7x           7x           7x           7x         7x           7x             7x         7x           7x         7x   7x 6x       1x       7x 7x                 6x                                                                           1x 1x     1x 1x                                       1x 1x     1x 1x                                                                                                                                                                                                                                                 1x     1x     1x 1x             2x 2x 2x       2x 2x 2x 2x   2x                                                                                 1x       1x           1x   1x                                                   1x 1x                                                                                                                                                                           4x 2x 2x       2x           6x 6x 6x 6x 6x     6x       2x 1x   1x 1x 1x                 1x         1x     1x     1x     1x   1x   1x                                               1x 1x               1x 1x                                                                             7x       2x 2x           6x 6x    
import {
  type ElementVisibilityObject,
  elementVisibility,
} from '../dom/element-visibility';
 
declare global {
  interface Window {
    DEGU_RAF_REGISTRY: RafRegistry;
    DEGU_RAF_REGISTRY_DEBUG: boolean;
  }
}
 
/**
 * A class that creates a RAF loop and calls a specific callback.  Setting the
 * frame rate will throttle the animation.
 *
 * Example usage;
 * ```ts
 * var raf = new Raf((frame, lastUpdateTime, stop)=> {
 *   console.log('this runs on request animation frame');
 *   // The current FPS.
 *   console.log(raf.getCurrentFps());
 * });
 * raf.start();
 *
 * // Later to stop raf.
 * raf.stop();
 *
 * // Set the FPS
 * raf.setFps(30);
 * raf.start();
 *
 *
 * // Add or remove listeners
 * var onRaf = ()=> {
 *   console.log('hello')
 * }
 * raf.watch(onRaf);
 * raf.unwatch(onRaf);
 *
 * // Clock functions: Delta and elapsed time.
 * var raf2 = new Raf((frame, lastUpdateTime, stop)=> {
 *   // Gets the time when raf started.
 *   const startTime = raf.getStartTime();
 *   // Gets the delta between the last update
 *   const delta = raf.getDelta();
 *   // Time elapsed
 *   const elapsedTime = raf.getElapsedTime();
 * }).start();
 *
 * ```
 *
 * RunWhen option.
 * You can pass a run condition to limit raf only when the condition resolve
 * to true.  This is useful to cull unncessary requests.
 * An example is to use elementVisility to only run RAF when an element is
 * in view and stop raf when it goes out of view.
 *
 *
 * ```ts
 *
 * // Runs only when the window is small.
 * var raf = new Raf(()=> {
 *   console.log('this runs when scren size is less than 1000');
 * });
 * raf.runWhen(()=> { window.innerWidth < 1000});
 * raf.start();
 *
 *
 *
 * // Runs only when myElement is in view.
 * // Option 1: You can use runWhen condition
 *
 *
 * let ev = elementVisibility.inview(myElement);
 * var raf = new Raf(() => {
 *    console.log('a raf that runs when element is in view.');
 * });
 * raf.runWhen(() => {
 *    return ev.state().inview;
 * });
 *
 * // This normally works fine but elementVisibility has a split second to
 * // boot up.
 * raf.start();
 *
 * // if you want to be sure to only run RAF when ev is ready do this:
 * ev.readyPromise.then(()=> {
 *   raf.start();
 * })
 *
 * ```
 *
 * // Runs only when myElement is in view.
 * // Option 2: You can use runWhenElementIsInview option.
 *
 * ```
 * var raf = new Raf(()=> {
 *   ...
 * })
 *
 *
 * // Set element and run when it's ready.
 * raf.runWhenElementIsInview(
 *    document.getElementById("myelement"),
 *    {
 *      rootMargin: '500px 0px 500px 0px'
 *    }
 * ).then(()=> {
 *    raf.start();
 * })
 *
 *
 * ```
 *
 *
 *
 * # Batch read / write.
 * Batch write / read.  To batch write and read, wrap your methods in
 * read and write calls.  Read / Write calls uses the degu raf registry
 * so your reads or writes can get delayed by one raf cycle.
 * ```
 * var raf = new Raf(()=> {
 *    raf.read(()=> {
 *        this.height = element.offsetHeight;
 *    })
 *
 *    raf.write(()=> {
 *        element.style.height = this.height + 20 + 'px';
 *    })
 * })
 *
 * ```
 *
 * You can also create a read / write only raf by passing
 * no rafLoop to the constructor.
 *
 * ```
 * var raf = new Raf();
 *    raf.read(()=> {
 *        this.height = element.offsetHeight;
 *    })
 *
 *    raf.write(()=> {
 *        element.style.height = this.height + 20 + 'px';
 *    })
 *
 * ```
 *
 *
 * If you want read / writes to NOT cull, you can set the
 * read write mode.    This is needed if you pass a rafLoop
 * to the constructor but additionally, want to use the read
 * write outside your loop even when your raf is stopped.
 * ```
 * var raf = new Raf(()=> {
 *    raf.read(()=> {
 *        this.height = element.offsetHeight;
 *    })
 *
 *    raf.write(()=> {
 *        element.style.height = this.height + 20 + 'px';
 *    })
 * })
 *
 * // Raf is stopped.
 * raf.stop();
 *
 * // This won't work.
 * raf.write(()=> {
 * ...
 * })
 *
 *
 * raf.setReadWriteMode(true);
 * // Now it will work even when raf is stopped.
 * raf.write(()=> {
 * ...
 * })
 *
 * ```
 *
 *
 * @noInheritDoc
 * @class
 */
export class Raf {
  private raf_: number | null;
  private frame: number | null;
  private lastUpdateTime: number;
  private delta: number;
  private fps: number;
  private currentFps: number;
  public isPlaying: boolean;
  public isReadWriteOnly = false;
  private callbacks: Array<Function> = [];
  private runCondition: Function | null;
  private isRunningRaf: boolean;
  private elaspedTime: number;
  public isDisposed = false;
  private startTime: number;
 
  /**
   * Internal element visibility object used to track element visibility
   * when runWhenElementIsInview option is used.
   */
  private ev?: ElementVisibilityObject;
 
  /**
   * @param {Function} rafLoop  Optional function to be called on each
   *     request animation frame.
   * @constructor
   */
  constructor(rafLoop?: Function | null) {
    /**
     * The internal reference to request animation frame.
     * @type {private}
     */
    this.raf_ = null;
 
    /**
     * The current animation frame.
     * @type {number}
     * @public
     */
    this.frame = null;
 
    /**
     * The last updated time.
     * @type {number}
     * @public
     */
    this.lastUpdateTime = 0;
 
    /**
     * The frame rate. Defaults to 0 in which case RAF is not throttled.
     * @type {number}
     */
    this.fps = 0;
 
    /**
     * The current frame rate.
     * @type {number}
     */
    this.currentFps = 0;
 
    /**
     * Whether raf is looping.
     * @type {boolean}
     */
    this.isPlaying = false;
 
    /**
     * Whether we are already running raf.
     */
    this.isRunningRaf = false;
 
    /**
     * A collection of callbacks to be called on raf.
     * @type {Array<Function>}
     */
    this.callbacks = [];
 
    /**
     * An optional condition in which if set and resolved to false,
     * the raf loop gets cull.ed
     * @type {Function}
     */
    this.runCondition = null;
 
    /**
     * The delta time in ms between the last frame update.
     */
    this.delta = 0;
 
    /**
     * The elapsed time instantiation.  This serves as a clock.
     * Note this is based on seconds not ms.
     */
    this.elaspedTime = 0;
 
    /**
     * The last known start time of raf.
     */
    this.startTime = 0;
 
    if (rafLoop) {
      this.watch(rafLoop);
    } else {
      // If no rafLoop was defined, this raf is being
      // used for readWrites only.
      this.isReadWriteOnly = true;
    }
 
    // Register self to global registry.
    Eif (window.DEGU_RAF_REGISTRY) {
      window.DEGU_RAF_REGISTRY.register(this);
    }
  }
 
  /**
   * Adds a raf listener
   * @param
   */
  watch(callback: Function) {
    this.callbacks.push(callback);
  }
 
  /**
   * Sets the read write mode.
   * @param value
   */
  setReadWriteMode(value: boolean) {
    this.isReadWriteOnly = value;
  }
 
  /**
   * Adds a one time pre-read callback executed by the global degu raf registry.
   * Returns a Promise resolving to the callback's return value.
   * @param callback
   */
  preRead<T = void>(callback: () => T): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      window.DEGU_RAF_REGISTRY &&
        window.DEGU_RAF_REGISTRY.addOneTimePreRead({
          callback: () => {
            try {
              resolve(callback());
            } catch (err) {
              reject(err);
            }
          },
          raf: this,
        });
    });
  }
 
  /**
   * Adds a one time read callback executed by the global degu raf registry.
   * This allows you to batch read calls and optionally await their result.
   * @param callback
   */
  read<T = void>(callback: () => T): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      window.DEGU_RAF_REGISTRY &&
        window.DEGU_RAF_REGISTRY.addOneTimeRead({
          callback: () => {
            try {
              resolve(callback());
            } catch (err) {
              reject(err);
            }
          },
          raf: this,
        });
    });
  }
 
  waitRead(): Promise<void> {
    return this.read(() => undefined);
  }
 
  /**
   * Adds a one time write callback executed by the global degu raf registry.
   * This allows you to batch write calls and optionally await completion.
   * @param callback
   */
  write<T = void>(callback: () => T): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      window.DEGU_RAF_REGISTRY &&
        window.DEGU_RAF_REGISTRY.addOneTimeWrite({
          callback: () => {
            try {
              resolve(callback());
            } catch (err) {
              reject(err);
            }
          },
          raf: this,
        });
    });
  }
 
  waitWrite(): Promise<void> {
    return this.write(() => undefined);
  }
 
  /**
   * Adds a one time post write callback executed by the global degu raf registry.
   * Returns a Promise resolving to the callback's return value.
   * @param callback
   */
  postWrite<T = void>(callback: () => T): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      window.DEGU_RAF_REGISTRY &&
        window.DEGU_RAF_REGISTRY.addOneTimePostWrite({
          callback: () => {
            try {
              resolve(callback());
            } catch (err) {
              reject(err);
            }
          },
          raf: this,
        });
    });
  }
 
  /**
   * Removes a progress listener.
   * @param {Function}
   */
  unwatch(callbackToRemove: Function) {
    this.callbacks = this.callbacks.filter((callback) => {
      return callback === callbackToRemove;
    });
  }
 
  /**
   * Sets a function to execute on each raf loop.  If the condition resolves
   * to true, the raf loop callbacks will be executed.  If false, the raf
   * loop is culled.
   * @param callbackCondition
   */
  runWhen(callbackCondition: Function) {
    this.runCondition = callbackCondition;
  }
 
  /**
   * Allows you to pass an option to tell this raf to execute only when the
   * given element is in the viewport.  Optionally pass intersection observer
   * options.
   *
   * Note that this still requires you to start the raf.  You can do this
   * with the promise that the method returns (resolved when ev is ready)
   * or at a later time.
   *
   * Note it's recommended that you add a rootMargin to your ev settings
   * if need to do offscreen processing.
   *
   * ```
   * var raf = new Raf(()=> {
   *   ...
   * })
   *
   *
   * // Set element and run when it's ready.
   * raf.runWhenElementIsInview(
   *    document.getElementById("myelement"),
   *    {
   *      rootMargin: '300px 0px 300px 0px'
   *    }
   * ).then(()=> {
   *    raf.start();
   * })
   *
   *
   * ```
   *
   */
  runWhenElementIsInview(
    element: HTMLElement,
    intersectionObserverOptions?: Object
  ): Promise<void> {
    // Dispose of any previous instances if this is being called a second
    // time.
    this.ev && this.ev.dispose();
    this.runCondition = null;
 
    this.ev = elementVisibility.inview(
      element,
      intersectionObserverOptions || {}
    );
 
    // Set the run when condition.
    this.runWhen(() => {
      return this.ev && this.ev.state().inview;
    });
 
    return this.ev.readyPromise;
  }
 
  /**
   * Sets the fps .
   */
  setFps(fps: number) {
    this.fps = fps;
  }
 
  /**
   * Starts the RAF animation loop.
   * @param {boolean} Whether to force a start.
   */
  start(force = false) {
    Iif (!force && this.isPlaying) {
      return;
    }
    this.startTime = (
      typeof performance === 'undefined' ? Date : performance
    ).now();
    this.animationLoop_();
    this.isPlaying = true;
  }
 
  /**
   * Stops the RAF animation loop.
   */
  stop() {
    this.isPlaying = false;
    window.cancelAnimationFrame(this.raf_!);
    this.isRunningRaf = false;
  }
 
  dispose() {
    this.ev && this.ev.dispose();
    this.callbacks = [];
    this.isDisposed = true;
    this.stop();
    // Deregister self to global registry.
    window.DEGU_RAF_REGISTRY && window.DEGU_RAF_REGISTRY.unregister(this);
  }
 
  /**
   * Gets the delta in ms between the last executed raf update.
   * @param inSeconds Whether to acquire the delta time in seconds.  Defaults
   *   to ms.
   */
  getDelta(inSeconds: boolean) {
    if (inSeconds) {
      return this.delta / 1000;
    } else {
      return this.delta;
    }
  }
 
  /**
   * Gets the elasped time since raf started.
   */
  getElapsedTime() {
    return this.elaspedTime;
  }
 
  /**
   * Gets the time (Date) when raf started.
   */
  getStartTime() {
    return this.startTime;
  }
 
  /**
   * Gets the current frame rate that raf is running at.  Useful for debugging.
   */
  getCurrentFps() {
    return this.currentFps;
  }
 
  /**
   * The internal animation loop.
   */
  private animationLoop_() {
    Iif (this.isRunningRaf) {
      return;
    }
 
    this.raf_ = window.requestAnimationFrame((frame: number) => {
      this.frame = frame;
      this.isRunningRaf = false;
      this.animationLoop_();
    });
 
    this.isRunningRaf = true;
 
    Iif (this.lastUpdateTime) {
      const current = Date.now();
      const elapsed = current - this.lastUpdateTime;
      this.delta = elapsed;
      this.elaspedTime += elapsed / 1000;
      const fps = this.fps === 0 ? 0 : 1000 / this.fps;
      this.currentFps = 1000 / elapsed;
      if (elapsed > fps) {
        this.callbacks &&
          this.callbacks.forEach((callback) => {
            const callCallback = () => {
              callback(this.frame, this.lastUpdateTime, elapsed, () => {
                this.stop();
              });
            };
            if (this.runCondition) {
              this.runCondition() && callCallback();
            } else {
              callCallback();
            }
          });
 
        this.lastUpdateTime = Date.now();
      }
    }
 
    Eif (!this.lastUpdateTime) {
      this.lastUpdateTime = Date.now();
    }
  }
}
 
export interface RafRegistryObject {
  callback: Function;
  raf: Raf;
}
 
/**
 * The idea behind the rafRegistry is to be able to batch read and write
 * raf calls similar to fastDom or toolBox mutate.
 *
 * In order to achieve this performance boosts, read and write calls need
 * to be executed in order and therefore, we need a registry to maintain
 * all raf instances on the page.
 *
 * When instantiated, each RAF adds itself to the registry and can be run / stopped
 * normally.
 *
 * Within it's raf loop, it can call a raf.read(callback); raf.write(callback);
 * which ends up getting executed on the RafRegistry event loop.
 *
 * raf.read(callback) and raf.write(callback) are ONE-time so must be recalled
 * on each raf loop.  It is basically saying, read this on the next raf loop once
 * or write it on the next raf loop.
 *
 * To use this system, simply use add read and write calls in your raf loop.
 *
 *
 * Life cycle:
 * - preread
 * - read
 * - write
 * - postWrite
 *
 * ```
 * var raf = new Raf(()=> {
 *    raf.preRead(()=> {
 *        this.height = element.offsetHeight;
 *    })
 *
 *    raf.read(()=> {
 *        this.height = element.offsetHeight;
 *    })
 *
 *    raf.write(()=> {
 *        element.style.height = this.height + 20 + 'px';
 *    })
 *
 *    // Somewhat rare but executed after all writes.
 *    raf.postWrite(()=> {
 *        element.style.height = this.height + 20 + 'px';
 *    })
 * })
 * ```
 *
 *
 * You may also to use raf.write and raf.read outside a
 * rafLoop.  In this case, you can just pass a null to the constructor.
 *
 * ```
 * var raf = new Raf();
 *
 * // Somewhere
 *  raf.read(()=> {
 *      this.height = element.offsetHeight;
 *  })
 *
 *
 *  raf.write(()=> {
 *      element.style.height = this.height + 20 + 'px';
 *  })
 *
 *
 * ```
 *
 */
class RafRegistry {
  private static runRafCallbacks(callbacks: RafRegistryObject[]) {
    // Keep consistent arrays so that scheduled function can schedule
    // another function in the same step.
    // Important so that a read function can call another function that
    // protects itself in its own read function, in case it is called
    // through another code execution path.
    while (callbacks.length) {
      const registryObject = callbacks.splice(0, 1)[0];
      Eif (
        !registryObject.raf.isDisposed &&
        (registryObject.raf.isPlaying || registryObject.raf.isReadWriteOnly)
      ) {
        registryObject.callback();
      }
    }
  }
 
  private rafs: Array<Raf>;
  private flushScheduled = false;
  private readonly preReads: Array<RafRegistryObject> = [];
  private readonly reads: Array<RafRegistryObject> = [];
  private readonly writes: Array<RafRegistryObject> = [];
  private readonly postWrites: Array<RafRegistryObject> = [];
 
  constructor() {
    this.rafs = [];
  }
 
  public start() {
    if (this.flushScheduled) {
      return;
    }
    this.flushScheduled = true;
    requestAnimationFrame(() => {
      this.runRaf();
    });
  }
 
  private runRaf() {
    // Open console and add:
    //
    // DEGU_RAF_REGISTRY_DEBUG = true;
    //
    Iif (window.DEGU_RAF_REGISTRY_DEBUG) {
      console.log('Running raf', this.reads.length, this.writes.length);
    }
 
    // Execute preReads.
    RafRegistry.runRafCallbacks(this.preReads);
 
    // Execute reads.
    RafRegistry.runRafCallbacks(this.reads);
 
    // Execute writes.
    RafRegistry.runRafCallbacks(this.writes);
 
    // Execute postWrites.
    RafRegistry.runRafCallbacks(this.postWrites);
 
    this.flushScheduled = false;
 
    Iif (
      this.preReads.length ||
      this.reads.length ||
      this.writes.length ||
      this.postWrites.length
    ) {
      this.start();
    }
  }
 
  /**
   * Add a single addOneTimePreRead to the batch read / write system.
   * @param read
   */
  addOneTimePreRead(read: RafRegistryObject) {
    this.preReads.push(read);
    this.start();
  }
 
  /**
   * Add a single addOneTimeRead to the batch read / write system.
   * @param read
   */
  addOneTimeRead(read: RafRegistryObject) {
    this.reads.push(read);
    this.start();
  }
 
  /**
   * Add a single addOneTimeWrite to the batch read / write system.
   * @param read
   */
  addOneTimeWrite(write: RafRegistryObject) {
    this.writes.push(write);
    this.start();
  }
 
  /**
   * Add a single addOneTimeWrite to the batch read / write system.
   * @param read
   */
  addOneTimePostWrite(postWrite: RafRegistryObject) {
    this.postWrites.push(postWrite);
    this.start();
  }
 
  /**
   * Gets the count of all active rafs.
   *
   * In dev console:
   * ```
   * DEGU_RAF_REGISTRY.getActiveRafCount();
   * ```
   */
  public getActiveRafCount(): number {
    return this.rafs.filter((r) => {
      return r.isPlaying;
    }).length;
  }
 
  /**
   * Gets the count of rafs.
   *
   * In dev console:
   * ```
   * DEGU_RAF_REGISTRY.getRafCount();
   * ```
   */
  public getRafCount(): number {
    return this.rafs.length;
  }
 
  public register(raf: Raf) {
    this.rafs.push(raf);
  }
 
  public unregister(raf: Raf) {
    this.rafs = this.rafs.filter((r) => {
      return r === raf;
    });
  }
}
 
// Create raf registry as a global.
Eif (typeof window !== 'undefined' && !window.DEGU_RAF_REGISTRY) {
  window.DEGU_RAF_REGISTRY = new RafRegistry();
}