All files / src/dom vector-dom-timeline.ts

39.36% Statements 37/94
25% Branches 12/48
35.29% Functions 6/17
39.36% Lines 37/94

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                                                                          1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1x 1x 1x     1x 3x         1x 2x 2x 4x       2x     1x     1x 1x       1x 1x 1x 1x         1x 1x 1x 1x 1x       1x                                                                                 5x 5x         5x 5x 5x   5x   5x     20x 4x 4x 4x     20x     5x                                                                                                                                                                                                                                                    
import * as dom from '../dom/dom';
import * as EASE from '../ease/ease';
import * as func from '../func/func';
import {Interpolate} from '../interpolate/interpolate';
import * as is from '../is/is';
import {HermiteCurve} from '../mathf/hermite-curve';
import * as mathf from '../mathf/mathf';
import {Vector} from '../mathf/vector';
import type {VectorDom, VectorDomComponent} from './vector-dom';
 
export interface VectorDomStartEnd {
  start: VectorDomTimelineObject;
  end: VectorDomTimelineObject;
}
 
export interface VectorDomTimelineOptions {
  /**
   * To use VectorDom for css only interpolations.
   */
  cssOnly?: boolean;
}
 
export interface VectorDomTimelineObject {
  progress: number;
  x?: number | string;
  y?: number | string;
  z?: number | string;
  rx?: number | string;
  ry?: number | string;
  rz?: number | string;
  alpha?: number | string;
  easingFunction?: Function;
}
 
/**
 * A list of keys in timeline object that should be skipped.
 */
const skipKeys = ['progress', 'easingFunction'];
 
/**
 *
 * A component class of VectorDom that adds timeline functionality to VectorDOM.
 *
 * #### Basic Example
 *
 * The timeline feature is a component of VectorDom to make sequential animations.
 *
 * The timeline feature will directly update element properties including,
 * x, y, z, rx, ry, rz, alpha.  In addition, you can append any css variable and
 * timeline will take care of the interpolations.
 *
 *
 * Here is a basic example:
 *
 * ```ts
 *
 *  // Notice how we add the css var --blur here.
 * .myelement {
 *     filter: blur(calc(var(--blur) * 4px));
 * }
 *
 *
 * // In the timeline, define storyboard out the animations.
 * // Any key that starts with '--' will automatically be available
 * // as a css var on the element.
 * var timeline = [
 *    {
 *      progress: 0,
 *      x: 0,
 *      y: 0,
 *      z: 0.3 - 1,
 *      alpha: 0.2,
 *      '--blur': 1
 *    },
 *    {
 *      progress: 0.2,
 *      x: 100,
 *      y: 200,
 *      z: 0.8 - 1,
 *      alpha: 0.2,
 *      '--blur': 0.2
 *      easingFunction: EASE.easeInOutCubic
 *     },
 *    {
 *      progress: 0.5,
 *      x: 20,
 *      y: 20,
 *      z: 1 - 1,
 *      '--blur': 1
 *      alpha: 1
 *     },
 *     {
 *      progress: 1,
 *      x: 100,
 *      y: 20,
 *      z: 0.2 - 1,
 *      '--blur': 1
 *      alpha: 1
 *     }
 * ]
 *
 * let element = document.getElementById('myelmeent');
 * let vector = new VectorDom(element);
 *
 * // Access the timeline component and set the timeline.
 * vector._.timeline.setTimeline(timeline);
 *
 * // Now update the vector to a specific "progress" in the timeline.
 * let currentProgress = 0.2; // Could be amount of scroll, range input, whatever.
 *
 * // At this point the internal, position, rotational vectors will get updated.
 * vector._.timeline.updateProgress(currentProgress);
 *
 * // Now render it...it will render at where the values are at 20%
 * vector.render();
 * ```
 *
 *
 *
 * ### Catmull Rom Mode.
 * Timeline goes step to step in your progress but this can often lead to
 * rather robotic movement.  Instead of a linear progresss, you can create a
 * a smoothed spline from your points.
 *
 * ```ts
 *
 * // Set the timeline.
 * vector._.timeline.setTimeline(timeline);
 *
 * // Set the timeline mode to catmullrom.  Any easing functions
 * // will get ignored.
 * vector._.timeline.catmullRomMode = true;
 *
 * // Change the default tension if you wish.
 * vector._.timeline.catmullRomTension = 1.2;
 *
 * ```
 *
 *
 * ### Using CSS vars Only.
 * If you want to use VectorDom only with css variables or prevent VectorDom
 * from updating the style properties, pass the cssOnly option.
 *
 *
 * ```ts
 *
 * let myVector = new VectorDom(myElement);
 * vector._.timeline.setTimeline(timeline, { timeline: cssOnly: true}});
 *
 * ```
 *
 * alternatively, which results in the same thing.
 * ```ts
 * let myVector = new VectorDom(myElement);
 * myVector.disableStyleRenders = true;
 *
 * ```
 *
 *
 * ### How the timeline is evalualted.
 * For the timeline you declare, a storyboard is internally generated per
 * property.  This measn that for each keyframe, you can skip certain properties
 * and the interpolations will make the best effort correctly go between
 * your keyframes.  If you don't declare a start (0) and end (1) progress
 * the first and last keyframes you declare will be used in place.
 *
 * Easing functions are used in forward progression so there is no point in
 * adding an easing function to your last keyframe since that is the end.
 *
 *
 * Consider the following:
 * ```ts
 *
 * timeline = [
 *    { progress: 0.2, alpha: 1, x: 200, easingFunction: EASE.easeInOutCubic},
 *    { progress: 0.5, x: 500},
 *    { progress: 0.8, alpha: 0.2},
 *    { progress: 1, alpha: 0, x: 100}
 * ]
 *
 * ```
 * Here x and alpha are not declared on each keyframe.  VectorDomTimeline
 * will generate a storyboard like this for each frame.
 *
 * ```ts
 *
 * storyboard = {
 *    alpha: [
 *      { progress: 0.2, alpha: 1, easingFunction: EASE.easeInOutCubic},
 *      { progress: 0.8, alpha: 0.2},
 *      { progress: 1, alpha: 0}
 *    ],
 *    x: [
 *      { progress: 0.2, x: 200, easingFunction: EASE.easeInOutCubic},
 *      { progress: 0.5, x: 500},
 *      { progress: 1, x: 100}
 *    ]
 * }
 *
 * ```
 * For alpha, the alpha storyboard will be used as the final interpolation
 * values and points.  Same goes with x.
 *
 *
 * For this reason, it's best practice to try to declare 0 and 1 keyframes to
 * make it easier to understand your storyboard.
 *
 * @unstable
 * @hidden
 */
export class VectorDomTimeline implements VectorDomComponent {
  /**
   * The host of this vectorDom instance of this component.
   */
  private host: VectorDom;
  private element: HTMLElement;
  /**
   * A list of values to interpolate between a given progress.  This is
   * the story board of the timeline feature.
   *
   * ```ts
   * var timeline = [
   *       {
   *           progress: 0,
   *           y: 0,
   *       },
   *       {
   *           progress: 0.1,
   *           '--opacity': 1,
   *           y: 100,
   *       },
   *       {
   *           progress: 0.5,
   *           '--opacity': 0,
   *           y: 200,
   *       }
   *]
   * ```
   */
  private timeline: Array<VectorDomTimelineObject> | null;
 
  /**
   * Whether to use catmull rom to evaluate timeline.
   */
  public catmullRomMode: boolean;
 
  /**
   * If using catmull rom to evaluate the timeline, the tension value of the
   * hermit curve m1, m2 points.
   */
  public catmullRomTension: number;
 
  /**
   * An internal list of all recorded timeline keys.
   */
  private timelineKeys: (keyof VectorDomTimelineObject)[] = [];
 
  /**
   * A modified version of timeline that organizes the timeline by key.
   * For each key we have it's own progression and timeline.
   * @see [[VectorDomTimeline.generateStoryboard]] for more.
   */
  private storyboard: Record<string, VectorDomTimelineObject[]>;
 
  /**
   * The timeline options.
   */
  public options: VectorDomTimelineOptions;
 
  /**
   * An internal set of css keys and their lastest values.
   */
  private cssKeys: Record<string, number | string>;
 
  /**
   * @param vc  The vectorDom that this component is attached to.
   */
  constructor(vc: VectorDom) {
    this.host = vc;
    this.options = vc.options.timeline || {};
    this.element = vc.element;
    this.cssKeys = {};
    this.timeline = [];
    this.timeline = null;
    this.timelineKeys = [];
    this.catmullRomMode = false;
    this.catmullRomTension = 1;
    this.storyboard = {};
 
    // Cull unncessary requests to setCssKeys.
    this.setCssKeys_ = func.runOnceOnChange(this.setCssKeys_.bind(this));
 
    if (this.options.cssOnly) {
      this.host.disableStyleRenders = true;
    }
  }
 
  init() {}
 
  /**
   * Sets the timeline to be used and internally generates the storyboard
   * to be used for interpolations.
   */
  setTimeline(timeline: Array<VectorDomTimelineObject>) {
    this.sortTimeline();
    this.timelineKeys = [];
 
    this.timeline = timeline.map((timeline) => {
      // Save any new keys.
      const keys = Object.keys(timeline) as (keyof VectorDomTimelineObject)[];
 
      // Add the keys to timelineKeys while deduping.
      this.timelineKeys = [
        ...new Set([...this.timelineKeys, ...keys]),
      ] as (keyof VectorDomTimelineObject)[];
 
      return timeline;
    });
 
    // Generate storyboard.
    this.storyboard = VectorDomTimeline.generateStoryboard(
      this.timelineKeys,
      this.timeline
    );
  }
 
  /**
   * Sorts the maintimeline.
   */
  private sortTimeline() {
    if (!this.timeline) {
      return;
    }
    // Sort the timeline.
    this.timeline = this.timeline.sort((a, b) => {
      return a.progress - b.progress;
    });
  }
 
  /**
   * Generates a storyboard from the provided timeline.
   *
   * Given a timeline like the following, a storyboard is timeline
   * by a specific key.  Notice how alpha is not declared in every step
   * of the timeline.
   *
   * The storyboard will also ALWAYs creates a progress 0 and 1 timeline
   * based on the first available.
   *
   * const timeline = [
   *   { progress: 0, x: 1200 },
   *   { progress: 0.2, alpha: 0.2, x: 1500, ease: EASING.easeInOutBounce },
   *   { progress: 0.5, x: 1500 },
   *   { progress: 0.8, alpha: 0.6, x: 1500 },
   *   { progress: 1, x: 1500 }
   * ]
   *
   * The resulting storyboard would be:
   * {
   *   alpha: [
   *     { progress: 0, alpha: 0.2},  // Added
   *     { progress: 0.2, alpha: 0.2, ease: EASING.easeInOutBounce},
   *     { progress: 0.8, alpha: 0.6},
   *     { progress: 1, alpha: 0.6}  // Added
   *   ],
   *   x: [
   *   { progress: 0, x: 1200},
   *   { progress: 0.2, x: 1500, ease: EASING.easeInOutBounce},
   *   { progress: 0.5, x: 1500 },
   *   { progress: 0.8, x: 1500},
   *   { progress: 1, x: 1500}
   *   ]
   * }
   *
   * This storyboard is basically then used for interporlations when
   * the progress value is updated.
   */
  static generateStoryboard(
    keys: Array<keyof VectorDomTimelineObject>,
    timeline: Array<VectorDomTimelineObject>
  ): Record<string, VectorDomTimelineObject[]> {
    const storyboard = {} as Record<string, VectorDomTimelineObject[]>;
    keys.forEach((key) => {
      Iif (skipKeys.includes(key)) {
        return;
      }
      let keyStoryboard = timeline.filter((t) => {
        return is.defined(t[key]);
      });
 
      // Make a copy and also remove keys that are not related to this
      // storyboard.
      keyStoryboard = keyStoryboard.map((t) => {
        const copy: VectorDomTimelineObject = Object.assign({}, t);
        for (const k in copy) {
          Iif (k !== key && !skipKeys.includes(k)) {
            delete copy[k as keyof VectorDomTimelineObject];
          }
        }
        return copy;
      });
 
      storyboard[key] = keyStoryboard;
    });
 
    for (const key in storyboard) {
      const keyStory = storyboard[key];
 
      // Check that the first item is progress 0.  If not, artificially
      // generate it so that the progress starts at 0.
      Eif (keyStory[0].progress !== 0) {
        const copy = Object.assign({}, keyStory[0]);
        copy.progress = 0;
        keyStory.unshift(copy);
      }
 
      // Check that the last item is progress 1.  If not, artificially
      // generate it and add it to the end.
      const last = keyStory.length - 1;
      Eif (keyStory[last].progress !== 1) {
        const copy = Object.assign({}, keyStory[last]);
        copy.progress = 1;
        keyStory.push(copy);
      }
    }
 
    return storyboard;
  }
 
  /**
   * Given a storyboard and the current progress, finds the start and end
   * timeline objects and return them.
   *
   * ```ts
   * let storyboard = {
   *    alpha: [
   *       { progress: 0, alpha: 0 },
   *      { progress: 0.2, alpha: 0 },
   *       { progress: 0.8, alpha: 0.6 },
   *      { progress: 1, alpha: 0.6 }
   *   ]
   * }
   *
   * // Find the start and end points if the progress were 0.1
   * VectorDomTimeline.getStartAndEndTimelineFromStoryboard(storyboard, 'alpha', 0.1);
   *
   *
   *
   * //Returns:
   * //  {
   * //      start: { progress: 0, alpha: 0 },
   * //      end: { progress: 0.2, alpha: 0 },
   * //  }
   *
   * ```
   *
   * @param storyboard Object
   * @param key
   * @param progress
   */
  static getStartAndEndTimelineFromStoryboard(
    storyboard: Record<string, VectorDomTimelineObject[]>,
    key: string,
    progress: number
  ): VectorDomStartEnd | null {
    // Loop through the storyboard and figure out the correct start and
    // end points.
    const activeStoryboard = storyboard[key];
    Iif (!activeStoryboard) {
      return null;
    }
 
    // By default we assume progress is at 0.
    let start = activeStoryboard[0];
    let end = activeStoryboard[1];
    let done = false;
 
    let previous = activeStoryboard[0];
 
    activeStoryboard.forEach((timeline: VectorDomTimelineObject) => {
      // Loop until the timeline progress is greater or equal than current
      // progress
      if (!done && timeline.progress >= progress && progress > 0) {
        start = previous;
        end = timeline;
        done = true;
      }
 
      previous = timeline;
    });
 
    return {
      start: start,
      end: end,
    };
  }
 
  updateProgress(progress: number) {
    for (const key in this.storyboard) {
      const startEnd = VectorDomTimeline.getStartAndEndTimelineFromStoryboard(
        this.storyboard,
        key,
        progress
      );
 
      const startTimeline = startEnd!.start;
      const endTimeline = startEnd!.end;
      // The start and end values.
      const start = startTimeline[key as keyof VectorDomTimelineObject];
      const end = endTimeline[key as keyof VectorDomTimelineObject];
      const easing = startTimeline.easingFunction;
 
      // Create a child progress between the start and end.
      const childProgress = mathf.clamp01(
        mathf.childProgress(
          progress,
          startTimeline.progress,
          endTimeline.progress
        )
      );
 
      // Safe guard.
      if (is.nan(childProgress)) {
        return;
      }
 
      let value;
      // If the value is a numberical.
      if (is.number(start) && is.number(end)) {
        const diff = <number>end - <number>start;
        if (!this.catmullRomMode || mathf.absZero(diff) === 0) {
          value = mathf.ease(
            <number>start,
            <number>end,
            childProgress,
            easing || EASE.linear
          );
        } else {
          const tension = this.catmullRomTension;
 
          // Technically, not a catmull rom but create a similar
          // spline out of HermiteCurves.
          const vector = HermiteCurve.getPoint(
            childProgress,
            new Vector(<number>start, <number>start),
            new Vector(<number>start * tension, <number>start * tension),
            new Vector(<number>end, <number>end),
            new Vector(<number>end * tension, <number>end * tension)
          );
          if (vector) {
            value = vector.x;
          }
        }
      } else {
        // If string values were passed, process it via Interpolate.
        // to be able to use css units.
        value = new Interpolate({
          from: start as string,
          to: end as string,
          easeFunction: easing || EASE.linear,
        }).calculate(childProgress);
      }
 
      if (is.defined(value)) {
        // If the key is a css var, internally cache it.  Otherwise,
        // update the value on the host.
        if (key.startsWith('--')) {
          this.cssKeys[key] = value as string;
        } else {
          // A bit hacky but get all properties of VectorDom that are mutable
          // so that we can assign a value without typescript complaining.
          type MutableVectorDom = {
            -readonly [P in keyof VectorDom]: VectorDom[P];
          };
          const vectorDomKey: keyof MutableVectorDom =
            key as keyof MutableVectorDom;
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (this.host as any)[vectorDomKey] = value;
        }
      }
    }
  }
 
  /**
   * Applies the css variables.  Unneccesary calls get culled by
   * func.runOnceOnChange.
   */
  private setCssKeys_(cssVars: Record<string, number | string>) {
    /**
     * Render this element only when it is inview
     * for performance boost.
     */
    if (
      this.host.renderOnlyWhenInview &&
      this.host.elementVisibility.state().ready &&
      !this.host.elementVisibility.state().inview
    ) {
      return;
    }
 
    for (const key in cssVars) {
      dom.setCssVariable(this.element, key, cssVars[key]);
    }
  }
 
  render() {
    this.setCssKeys_(this.cssKeys);
  }
 
  resize() {}
 
  dispose() {}
}