All files / src/dom lottie-button.ts

0% Statements 0/109
0% Branches 0/54
0% Functions 0/25
0% Lines 0/109

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import lottie, {type AnimationItem} from 'lottie-web';
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import {Raf} from '../raf/raf';
import {
  type ElementVisibilityObject,
  elementVisibility,
} from './element-visibility';
 
export interface LottieButtonRange {
  start: number;
  end: number;
}
 
export const LottieButtonCssClasses = {
  INVIEW: 'in',
  OUTVIEW: 'out',
  HOVER: 'hover',
  CLICK: 'click',
};
 
export interface LottieButtonConfig {
  /**
   * The root element.  This is the root element in which this class
   * attaches click, mouseover etc listeners.
   */
  rootElement: HTMLElement;
 
  /**
   * The root wrapping element for lottie.  This can be the same as rootElement.
   */
  lottieElement: HTMLElement;
 
  /**
   * Optional settings for the lottie aspect ratio settings.
   *  Defaults to 'xMidYMid slice',
   */
  preserveAspectRatio?: string;
 
  /**
   * The path to the lottie json.
   */
  lottieJson: string;
  inview?: LottieButtonRange;
  mouseenter?: LottieButtonRange;
  mouseleave?: LottieButtonRange;
  click?: LottieButtonRange;
  outview?: LottieButtonRange;
 
  /**
   * Normally, the lottie button automatically setsup listeners but setting this to true,
   * will skip this process allowing you to control lottie button to your needs by changing
   * mousestate.
   */
  noListeners?: boolean;
 
  /**
   * Whether to load the lottie button immediately.  Default is
   * false to where it will wait for window loading.
   */
  loadImmediately?: boolean;
}
 
export interface LottieButtonMouseState {
  hovering: boolean;
  clicked: boolean;
}
 
export const LottieButtonState = {
  INVIEW: 'inview',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',
  CLICK: 'click',
  OUTVIEW: 'outview',
};
 
export interface LottieButtonPlayQueueItem {
  state: string;
  callback: Function;
}
 
/**
 * Notice: Experimental Class
 * This class was written fairly quickly and might change in the future.
 * Maybe?  use it as a reference.
 * Creates an interactable lottie button.
 *
 *
 * Note that I don't consider this to be stable.
 * I don't recommend directly using this class and instead for now,
 * copy it and use it as a base in your project.
 *
 * ```
 *
 * <div id="mylottiebutton">
 *      <div id="lottie"></div>
 *
 * </div>
 * ```
 *
 *  Settings for lottie-button.  Specify the frame ranges from mouseenter, mouseleave and click.
 *
 * The lottie file should have these states usually in this order:
 * inview
 * mouseenter
 * mouseleave
 * click
 *
 * For the transitions to work, certain frames should be the same:
 *
 * inview endFrame === mouseenter startFrame
 * mouseenter endFrame === mouseleave startFrame
 * mouseenter endFrame === click startFrame
 *
 *
 * ``
 * const config = {
 *    rootElement: document.getElementById("mylottiebutton"),
 *    lottieElement: document.getElementById("lottie"),
 *    lottieJson: '/source/my-lottie.json',
 *    inview: {
 *       start: 0,
 *       end: 96,
 *    },
 *    mouseenter: {
 *       start: 72,
 *       end: 96,
 *    },
 *    mouseleave: {
 *       start: 156,
 *       end: 180,
 *   },
 *    click: {
 *       start: 196,
 *       end: 216,
 *   },
 * }
 *
 * const lb = new LottieButton(config);
 *
 * ```
 *
 *
 * # Play Queuing
 * This option ensures that the previous animation state is resolved
 * prior to the next playing but it can cause delays in animation.
 *
 * ```
 * lb.enablePlayQueue(true);
 * ```
 *
 *
 * # Using angular controllers to pass states.
 * Sometimes, you want to control the state of the button not based on whether the
 * user click or moused over.  You control specific states first disabling
 * the mouseover, click etc listeners and opting to take control over this.
 *
 *
 * To do this, set the noListeners option to true.
 * ```
 * const config = {
 *    rootElement: document.getElementById("mylottiebutton"),
 *    lottieElement: document.getElementById("lottie"),
 *    lottieJson: '/source/my-lottie.json',
 *    inview: {
 *       start: 0,
 *       end: 96,
 *    },
 *    ...
 *    noListeners: true
 * }
 * const lb = new LottieButton(config);
 * ```
 *
 * Now call specific methods on lb to set the state.
 *
 * ```
 * lb.inview(); === inview
 * lb.outview(); === outview
 * lb.mousedown(); === click
 * lb.mouseup(); === unclick
 * lb.mouseenter(); === hover
 * lb.mouseleave(); === unhover
 *
 * ```
 *
 * Usually, it is expected that you go from hover -> click.
 * But certain state like click -> unhover (mouseleave) won't work.
 * However, you can force it by tricking lb to think it is in a hover
 * state and then run mouseleave.
 *
 *
 * ```
 *   this.lottieButton.setMouseState({
 *      clicked: false,
 *      hovering: true
 *   })
 *   this.lottieButton.mouseleave();
 * ``
 *
 *
 */
export class LottieButton {
  private config: LottieButtonConfig;
  private watcher: DomWatcher;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private lottieInstance: any;
  private mouseState: LottieButtonMouseState;
  private currentFrame = 0;
  private stopFrame = 0;
  private ev?: ElementVisibilityObject;
  private isInview = false;
  private loadImmediately = false;
  private raf: Raf;
  private isPlaying = false;
  private hasStartedLoading = false;
 
  private playQueue: Array<LottieButtonPlayQueueItem>;
  /**
   * The play queue allows you to keep a one time memory and ensure that the previous state
   * is resolved before the current one is played.  This allows you to create a seamless
   * transition but with mouseenter states, it can cause delays.
   */
  private usePlayQueue = false;
  private currentState = '';
 
  constructor(config: LottieButtonConfig) {
    this.config = config;
 
    this.playQueue = [];
    this.watcher = new DomWatcher();
    this.raf = new Raf();
    this.isPlaying = false;
    this.isInview = false;
    this.loadImmediately = this.config.loadImmediately || false;
 
    this.mouseState = {
      hovering: false,
      clicked: false,
    };
 
    if (this.loadImmediately) {
      this.hasStartedLoading = true;
      this.createLottie();
    } else {
      dom.runAfterWindowLoad(() => {
        this.hasStartedLoading = true;
        this.createLottie();
      });
    }
 
    if (!this.config.noListeners) {
      this.watcher.add({
        element: this.config.rootElement,
        on: 'mousedown',
        callback: this.handleClick.bind(this),
      });
      this.watcher.add({
        element: this.config.rootElement,
        on: 'mouseup',
        callback: this.handleMouseUp.bind(this),
      });
 
      this.watcher.add({
        element: this.config.rootElement,
        on: 'mouseleave',
        callback: this.handleMouseLeave.bind(this),
      });
 
      this.watcher.add({
        element: this.config.rootElement,
        on: 'mouseenter',
        callback: this.handleMouseEnter.bind(this),
      });
    }
  }
 
  /**
   * Enables play queue system which ensures that the previous state is resolved
   * prior to the next state playing.  This can cause delays in animations.
   * @param value
   */
  public enablePlayQueue(value: boolean) {
    this.usePlayQueue = value;
  }
 
  private createLottie() {
    if (!this.config.lottieElement) {
      this.config.lottieElement = this.config.rootElement;
    }
    const settings = {
      container: this.config.lottieElement,
      loop: false,
      autoplay: false,
      rendererSettings: {
        // https://github.com/airbnb/lottie-web/issues/1860
        // https://github.com/airbnb/lottie-web/wiki/Renderer-Settings
        // For svg.
        progressiveLoad: true,
        preserveAspectRatio:
          this.config.preserveAspectRatio || 'xMidYMid slice',
      },
      path: this.config.lottieJson,
    };
 
    this.lottieInstance = <AnimationItem>lottie.loadAnimation(settings);
 
    this.watcher.add({
      element: this.lottieInstance as HTMLElement,
      on: 'DOMLoaded',
      callback: () => {
        if (!this.config.noListeners) {
          this.ev = elementVisibility.inview(
            this.config.rootElement,
            {},
            (element: HTMLElement, changes: IntersectionObserverEntry) => {
              if (changes.isIntersecting) {
                this.inview();
              } else {
                this.outview();
              }
            }
          );
        }
      },
    });
 
    this.watcher.add({
      element: this.lottieInstance as HTMLElement,
      on: 'enterFrame',
      callback: () => {
        this.currentFrame = this.lottieInstance.currentFrame;
        if (this.currentFrame >= this.stopFrame) {
          this.isPlaying = false;
 
          if (this.currentState === 'outview') {
            this.lottieInstance['stop']();
          } else {
            this.lottieInstance['pause']();
          }
 
          // Once we reach the end, play whatever is on the play queue.
          if (this.playQueue.length >= 1) {
            this.playQueue[this.playQueue.length - 1].callback();
            this.playQueue = [];
          }
        }
      },
    });
  }
 
  private play(state: string, start: number, end: number) {
    if (!this.hasStartedLoading) {
      return;
    }
 
    this.currentState = state;
    this.isPlaying = true;
    this.stopFrame = end;
    this.lottieInstance['goToAndPlay'](start, true);
    this.updateCssClass();
  }
 
  private schedule(state: string, start: number, end: number) {
    if (this.usePlayQueue) {
      // If there is nothing in the queue, just play this.
      if (!this.isPlaying) {
        this.play(state, start, end);
      } else {
        // If there is something in the queue, wait.
        this.playQueue.push({
          state: state,
          callback: () => {
            this.play(state, start, end);
          },
        });
      }
    } else {
      this.play(state, start, end);
    }
  }
 
  public inview(): void {
    if (this.config.inview) {
      this.isInview = true;
      this.playQueue = [];
      //   this.lottieInstance['playSegments']([this.config.click.start, this.config.click.end], true);
      this.schedule(
        LottieButtonState.INVIEW,
        this.config.inview.start,
        this.config.inview.end
      );
    }
    this.updateCssClass();
  }
 
  public outview(): void {
    if (this.config.outview && this.isInview) {
      this.schedule(
        LottieButtonState.OUTVIEW,
        this.config.outview.start,
        this.config.outview.end
      );
    } else {
      this.isInview = false;
      this.isPlaying = false;
      this.playQueue = [];
      this.updateCssClass();
    }
  }
 
  private handleClick(): void {
    this.mouseState.clicked = true;
    if (this.config.click) {
      //   this.lottieInstance['playSegments']([this.config.click.start, this.config.click.end], true);
      this.schedule(
        LottieButtonState.CLICK,
        this.config.click.start,
        this.config.click.end
      );
    }
  }
 
  private handleMouseUp(): void {
    this.mouseState.clicked = false;
  }
 
  public mousedown(): void {
    this.handleClick();
  }
 
  public mouseup(): void {
    this.handleMouseUp();
  }
 
  private handleMouseLeave(): void {
    if (!this.mouseState.hovering) {
      return;
    }
    this.mouseState.hovering = false;
    if (this.config.mouseleave) {
      //   this.lottieInstance['playSegments']([this.config.mouseleave.start, this.config.mouseleave.end], true);
      this.schedule(
        LottieButtonState.MOUSELEAVE,
        this.config.mouseleave.start,
        this.config.mouseleave.end
      );
    }
  }
 
  public mouseleave(): void {
    this.handleMouseLeave();
  }
 
  public mouseenter(): void {
    this.handleMouseEnter();
  }
 
  private handleMouseEnter(): void {
    if (this.mouseState.hovering) {
      return;
    }
    this.mouseState.hovering = true;
 
    if (this.config.mouseenter) {
      //   this.lottieInstance['playSegments']([this.config.mouseover.start, this.config.mouseover.end], true);
      this.schedule(
        LottieButtonState.MOUSEENTER,
        this.config.mouseenter.start,
        this.config.mouseenter.end
      );
    }
  }
 
  private updateCssClass() {
    this.raf.write(() => {
      this.config.rootElement.classList.remove(LottieButtonCssClasses.CLICK);
      this.config.rootElement.classList.remove(LottieButtonCssClasses.HOVER);
 
      if (this.currentState === 'click') {
        this.config.rootElement.classList.add(LottieButtonCssClasses.CLICK);
      }
 
      if (this.currentState === 'mouseenter') {
        this.config.rootElement.classList.add(LottieButtonCssClasses.HOVER);
      }
 
      if (this.isInview) {
        this.config.rootElement.classList.add(LottieButtonCssClasses.INVIEW);
        this.config.rootElement.classList.remove(
          LottieButtonCssClasses.OUTVIEW
        );
      } else {
        this.config.rootElement.classList.add(LottieButtonCssClasses.OUTVIEW);
        this.config.rootElement.classList.remove(LottieButtonCssClasses.INVIEW);
      }
    });
  }
 
  public getMouseState(): LottieButtonMouseState {
    return this.mouseState;
  }
 
  public setMouseState(state: LottieButtonMouseState): LottieButtonMouseState {
    return (this.mouseState = state);
  }
 
  public dispose(): void {
    this.watcher && this.watcher.dispose();
    this.ev && this.ev.dispose();
    this.raf && this.raf.dispose();
  }
}