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 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | import lottie, {type AnimationItem} from 'lottie-web';
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import * as func from '../func/func';
import {CssVarInterpolate} from '../interpolate/css-var-interpolate';
import type {
interpolateSettings,
rangedProgress,
} from '../interpolate/multi-interpolate';
import * as is from '../is/is';
import {CubicBezier} from '../mathf/cubic-bezier';
import * as mathf from '../mathf/mathf';
import {RafProgress} from '../raf/raf-progress';
import {RafTimer} from '../raf/raf-timer';
import {cssUnit} from '../string/css-unit';
export interface lottieRangedProgress extends rangedProgress {
fromFrame?: number;
toFrame?: number;
cubic_ease: string;
}
export interface lottieInterpolateSettings extends interpolateSettings {
progress: Array<lottieRangedProgress>;
}
export const LottieScrollEvents = {
INIT: 'INIT',
PROGRESS_UPDATE: 'LOTTIE_SCROLL_EVENT',
};
export interface LottieScrollInitPayload {
controller: LottieController;
}
export interface LottieScrollEventPayload {
controller: LottieController;
progress: number;
direction: number;
}
export interface LottieAutoPlay {
fromFrame: number;
toFrame: number;
// Whether to trigger this on a down scroll
down: boolean;
// Whether to trigger this on a up scroll
up: boolean;
// If you want it to keep looping.
loopStartFrame?: number;
loopEndFrame?: number;
}
export interface LottieScrollSettings {
// Whether to display progress information in the dev console.
// Defaults to false.
debug: boolean;
// The lerp to apply to the scroll progress.
// Defaults to 1.
lerp: number;
// Damp to apply. Defaults to 1 (no damp)
damp?: number;
// Top and bottom offsets for progress calculation.
top: string;
bottom: string;
}
export interface LottieClassTrigger {
class: string;
fromFrame: number;
toFrame: number | string;
from: number;
to: number;
}
export interface LottieScrollIntro {
startFrame: number;
duration: number;
interpolations: Array<lottieInterpolateSettings>;
}
//
// TODO (uxder): Break out lottie object as it's own class.
//
export interface LottieObject {
// Whether to display the "frame" in the dev console.
// Defaults to false.
debugFrame: boolean;
// The json path to the lottie json file.
json_path: string | null;
json_path_webp: string | null;
// If images are not embedded in the json file, the image path to the image directory.
image_path: string | null;
image_path_webp: string | null;
// The query selector to the lottie container.
container_selector: string;
// The renderer to use 'canvas', 'svg'
renderer: string;
// The aspect ratio sizing settings to use for lottie. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio
// Defaults to xMidYMid slice.
preserveAspectRatio: string;
// The starting frame for the scroll.
startFrame: number;
// The end frame.
endFrame: number;
fromProgress: number;
toProgress: number;
// The intro sequence.
intro: LottieScrollIntro;
// Whether the intro sequence has completed.
introCompleted: boolean;
classTriggers: Array<LottieClassTrigger>;
activeTriggerClasses: Array<string>;
// Css var interpolations associated with this lottie scroll.
interpolations: Array<lottieInterpolateSettings>;
// The lottie instance added once it is created.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
lottieInstance: any;
lottieInDom: boolean;
// Instance of css var interpolate associated. This is added once
// lottie is created.
cssInterpolatorInstance: CssVarInterpolate | null;
// Whether the lottie container associated to this LottieObject is
// currently on the screen. This is determined based on whether the
// container or it's ancestors has "display: none". By adding
// display: none you can cull paints.
isOnScreen: boolean;
autoplay: LottieAutoPlay;
isAutoPlaying: boolean;
loopListener: Function;
}
export class LottieController {
private element: HTMLElement;
/**
* The element to which the scroll progress is measured. This currently defaults to the
* directive root.
*/
private scrollEl: HTMLElement;
private rafProgress: RafProgress;
private domWatcher: DomWatcher;
private lottieObjects: Array<LottieObject> = [];
private lottieScrollSettings: LottieScrollSettings;
private currentProgress = 0;
// The top and bottom offsets in pixel number values.
private progressTopOffset = 0;
private progressBottomOffset = 0;
static get $inject() {
return ['$element', '$scope'];
}
constructor($element: ng.IRootElementService, $scope: ng.IScope) {
this.element = $element[0];
this.scrollEl = this.element;
this.domWatcher = new DomWatcher();
this.domWatcher.add({
element: window,
on: 'scroll',
callback: this.onWindowScroll.bind(this),
eventOptions: {passive: true},
});
this.domWatcher.add({
element: window,
on: 'resize',
callback: this.onWindowResize.bind(this),
eventOptions: {passive: true},
});
this.rafProgress = new RafProgress(this.progressUpdate.bind(this));
this.rafProgress.setPrecision(5);
// Adds a way to update lerp, damp via chrome dev tools.
// This can be fired on the document OR the element. Document
// firing will update all instances.
this.domWatcher.add({
element: document,
on: 'degu-lottie-scroll-update',
callback: this.handleLottieScrollUpdateEvent.bind(this),
eventOptions: {passive: true},
});
this.domWatcher.add({
element: this.element,
on: 'degu-lottie-scroll-update',
callback: this.handleLottieScrollUpdateEvent.bind(this),
eventOptions: {passive: true},
});
const configData = JSON.parse(this.element.getAttribute('lottie-scroll')!);
const settings = configData.settings || {};
this.lottieScrollSettings = {
...{
debug: false,
lerp: 1,
damp: 1,
top: '0px',
bottom: '0px',
},
...settings,
};
if (configData.lotties) {
configData.lotties.forEach((settings: LottieObject) => {
const data = {
...{
debugFrame: false,
json_path: null,
json_path_webp: null,
image_path: null,
image_path_webp: null,
container_selector: null,
renderer: 'canvas',
preserveAspectRatio: 'xMidYMid slice',
startFrame: 0,
intro: null,
introCompleted: false,
fromProgress: null,
toProgress: null,
classTriggers: null,
activeTriggerClasses: [],
autoplay: null,
// This will get updated once the lottie instance is loaded.
// Unless the user specifically set an endframe.
endFrame: 0,
lottieInDom: false,
},
...settings,
};
this.lottieObjects.push(data);
});
this.createLottieInstances();
}
$scope.$on('$destroy', () => {
this.dispose();
});
}
/**
* Takes a css string declaration such as '100px', '100vh' or '100%'
* and converts that into a relative pixel number.
* @param cssUnitObject
*/
protected getPixelValue(cssValue: string): number {
const unit = cssUnit.parse(cssValue);
let base = 1;
if (unit.unit === '%') {
base = this.element.offsetHeight;
return base * ((unit.value as number) / 100);
}
if (unit.unit === 'vh') {
base = window.innerHeight;
return base * ((unit.value as number) / 100);
}
return base * (unit.value as number);
}
protected onWindowResize(): void {
this.calculateProgressOffsets();
// On each window resize, test if the root lottie element is visible.
// If not, mark the lottieScroll to not render or paint.
this.lottieObjects.map((lottieObject) => {
const container = this.element.querySelector(
lottieObject.container_selector
)!;
lottieObject.isOnScreen = !dom.isDisplayNoneWithAncestors(container);
return lottieObject;
});
// Lottie doesn't "redraw" itself on size. Most likely
// because it culls two consecutive calls to drawing the
// same frame.
// To get around this, on each window resize, what we
// must do is first tell lottie to draw some other
// frame. Then redraw the current frame.
const progress = this.currentProgress;
if (progress === 0) {
this.progressUpdate(progress + 0.01, 0);
} else {
this.progressUpdate(Math.max(0, progress - 0.01), 0);
}
this.resizeLottie();
this.progressUpdate(progress, 0);
}
private resizeLottie(): void {
this.lottieObjects.forEach((lottieObject) => {
if (lottieObject.lottieInDom) {
lottieObject.lottieInstance.resize();
}
});
}
protected calculateProgressOffsets() {
// Convert the css unit into pixels for the top and bottom progress
// offsets.
this.progressTopOffset = func.setDefault(
this.getPixelValue(this.lottieScrollSettings.top),
0
);
this.progressBottomOffset = func.setDefault(
this.getPixelValue(this.lottieScrollSettings.bottom),
0
);
}
/**
* Creates lottie instances from the lottie scroll configs.
*/
protected createLottieInstances(): void {
this.lottieObjects.forEach((lottieObject, i) => {
is.supportingWebpAsync().then((supportsWebp) => {
const jsonPath =
lottieObject.json_path_webp && supportsWebp
? lottieObject.json_path_webp
: lottieObject.json_path;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const settings: any = {
container: this.element.querySelector(
lottieObject.container_selector
),
loop: true,
autoplay: false,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
renderer: lottieObject.renderer as any,
rendererSettings: {
// https://github.com/airbnb/lottie-web/issues/1860
// https://github.com/airbnb/lottie-web/wiki/Renderer-Settings
// For svg.
// progressiveLoad: true,
preserveAspectRatio: lottieObject.preserveAspectRatio,
},
path: jsonPath,
};
if (lottieObject.image_path) {
if (supportsWebp && lottieObject.image_path_webp) {
settings['assetsPath'] = lottieObject.image_path_webp;
} else {
settings['assetsPath'] = lottieObject.image_path;
}
}
const lottieInstance = <AnimationItem>lottie.loadAnimation(settings);
// Supposed lottie optimization.
lottieInstance.setSubframe(false);
this.lottieObjects[i].lottieInstance = lottieInstance;
// Also update the end frame if it hasn't been specified.
lottieInstance.addEventListener('DOMLoaded', () => {
if (this.lottieObjects[i].endFrame === 0) {
this.lottieObjects[i].endFrame = lottieInstance.totalFrames;
}
if (this.lottieObjects[i].classTriggers) {
const startFrame = this.lottieObjects[i].startFrame;
const endFrame = this.lottieObjects[i].endFrame;
this.lottieObjects[i].classTriggers.map((trigger) => {
if (is.defined(trigger['fromFrame'])) {
trigger.from = mathf.inverseLerp(
startFrame,
endFrame,
trigger['fromFrame'],
true
);
}
if (is.defined(trigger['toFrame'])) {
let toFrame = trigger['toFrame'];
// Allows toFrame to use addition.
if (String(toFrame).startsWith('+')) {
toFrame =
trigger['fromFrame'] + +String(toFrame).replace('+', '');
}
trigger.to = mathf.inverseLerp(
startFrame,
endFrame,
+toFrame,
true
);
}
});
}
// If there are interpolations associated with this lottie scroll
// then create it.
if (this.lottieObjects[i].interpolations) {
// First run through the interpolations and convert the
// fromFrame and endFrame to progress values.
this.lottieObjects[i].interpolations.map((interpolation) => {
const startFrame = this.lottieObjects[i].startFrame;
const endFrame = this.lottieObjects[i].endFrame;
interpolation.progress.map((progress) => {
if (is.defined(progress.fromFrame)) {
progress.from = mathf.inverseLerp(
startFrame,
endFrame,
progress.fromFrame!,
true
);
}
if (is.defined(progress.toFrame)) {
let toFrame = progress.toFrame!;
// Allows toFrame to use addition.
if (String(toFrame).startsWith('+')) {
toFrame =
progress.fromFrame! + +String(toFrame).replace('+', '');
}
progress.to = mathf.inverseLerp(
startFrame,
endFrame,
toFrame,
true
);
}
if (is.defined(progress['cubic_ease'])) {
const ease = progress['cubic_ease'].split(',');
progress.easingFunction = CubicBezier.makeEasingFunction(
+ease[0],
+ease[1],
+ease[2],
+ease[3]
);
}
return progress;
});
return interpolation;
});
// Create the css var interpolation.
this.lottieObjects[i].cssInterpolatorInstance =
new CssVarInterpolate(this.element, {
interpolations: this.lottieObjects[i].interpolations,
});
this.lottieObjects[i].cssInterpolatorInstance!.useBatchUpdate(true);
this.lottieObjects[i].lottieInDom = true;
// Run window resize once.
this.onWindowResize();
// If we have an intro, then play out the intro.
if (this.lottieObjects[i].intro) {
this.playIntro(this.lottieObjects[i]);
}
// Add loaded class to mark it is ready.
// Put to bottom of event queue for intro sequence to startup.
window.setTimeout(() => {
this.element.classList.add('lottie-scroll-loaded');
});
} else {
// Run window resize once.
this.onWindowResize();
}
const payload: LottieScrollInitPayload = {
controller: this,
};
dom.event(this.element, LottieScrollEvents.INIT, payload);
// Update and render immediately after it loads.
this.updateImmediately();
});
});
});
}
protected onWindowScroll(): void {
this.rafProgress.dampTo(
this.getPercent(),
this.lottieScrollSettings.lerp,
this.lottieScrollSettings.damp || 1
);
}
protected playIntro(lottieObject: LottieObject) {
const startProgress = this.getPercent();
// If we are starting with a progress greater than 0, then we shouldn't
// playout the intro.
if (startProgress > 0) {
lottieObject.introCompleted = true;
return;
}
// Create a raf timer that will tick from 0-1 for a set duration.
const rafTimer = new RafTimer((progress: number) => {
const currentScrollProgress = this.getPercent();
const endFrame = mathf.lerp(
lottieObject.startFrame,
lottieObject.endFrame,
currentScrollProgress
);
// So as the intro plays, the user can scroll so we need to remap
// the end frame as needed.
// If child progress is defined.
if (
!is.nullLike(lottieObject.fromProgress) &&
!is.nullLike(lottieObject.toProgress)
) {
progress = mathf.childProgress(
progress,
lottieObject.fromProgress,
lottieObject.toProgress
);
}
const frame = mathf.lerp(
lottieObject.intro.startFrame,
endFrame,
progress
);
lottieObject.lottieInstance['goToAndStop'](frame, true);
// This would end up being negative progress.
const adjustedProgress = mathf.inverseLerp(
lottieObject.startFrame,
lottieObject.endFrame,
frame,
true
);
// Also update the regular css interpolations.
lottieObject.cssInterpolatorInstance &&
lottieObject.cssInterpolatorInstance.update(adjustedProgress);
});
rafTimer.setDuration(lottieObject.intro.duration || 300);
rafTimer.onComplete(() => {
lottieObject.introCompleted = true;
rafTimer.dispose();
});
rafTimer.play();
}
/**
* Checks if autoplay is set on the lottieObject in which case,
* we check the frame to start at and see we have reached that point.
*
* @param lottieObject
* @param currentFrame
*/
protected drawOrLoop(lottieObject: LottieObject, currentFrame: number) {
const direction = this.rafProgress.getScrollDirection();
// Case when autoplay is defined and the current scroll is in range
// of the autoplay trigger.
if (
lottieObject.autoplay &&
!lottieObject.isAutoPlaying &&
((lottieObject.autoplay.down && direction === 1) ||
(lottieObject.autoplay.up && direction === -1)) &&
mathf.isBetween(
this.currentProgress,
lottieObject.fromProgress,
lottieObject.toProgress,
true
)
) {
lottieObject.isAutoPlaying = true;
// If we want to loop
if (lottieObject.autoplay.loopStartFrame) {
lottieObject.lottieInstance.playSegments(
[
[
lottieObject.autoplay['fromFrame'],
lottieObject.autoplay['toFrame'],
],
[
lottieObject.autoplay['loopStartFrame'],
lottieObject.autoplay['loopEndFrame'],
],
],
true
);
} else {
lottieObject.lottieInstance.loop = false;
lottieObject.lottieInstance['goToAndStop'](
lottieObject.autoplay['fromFrame'],
true
);
lottieObject.lottieInstance.playSegments(
[
[
lottieObject.autoplay['fromFrame'],
lottieObject.autoplay['toFrame'],
],
],
true
);
}
} else {
if (lottieObject.autoplay) {
if (
!mathf.isBetween(
this.currentProgress,
lottieObject.fromProgress,
lottieObject.toProgress,
true
)
) {
lottieObject.isAutoPlaying = false;
// Force lottie to draw an empty frame by drawing an non-existent frame.
lottieObject.lottieInstance['goToAndStop'](100000, true);
}
} else {
// For all other cases, just go to the frame and draw it.
lottieObject.isAutoPlaying = false;
lottieObject.lottieInstance['goToAndStop'](currentFrame, true);
}
}
}
protected progressUpdate(easedProgress: number, direction: number): void {
if (this.lottieScrollSettings.debug) {
console.log(this.currentProgress);
}
// Fire a dom event.
const payload: LottieScrollEventPayload = {
controller: this,
progress: easedProgress,
direction: direction,
};
dom.event(this.element, LottieScrollEvents.PROGRESS_UPDATE, payload);
this.currentProgress = easedProgress;
this.lottieObjects.forEach((lottieObject) => {
let progress = easedProgress;
// If we have an intro and haven't completed the playback.
const hasIntroAndNotCompleted =
lottieObject.intro && !lottieObject.introCompleted;
if (hasIntroAndNotCompleted) {
return;
}
if (!lottieObject.isOnScreen) {
if (lottieObject.debugFrame) {
console.log('lottie is not on screen');
}
return;
}
if (lottieObject.lottieInstance && lottieObject.lottieInstance.isLoaded) {
// If child progress is defined.
if (
!is.nullLike(lottieObject.fromProgress) &&
!is.nullLike(lottieObject.toProgress)
) {
progress = mathf.childProgress(
progress,
lottieObject.fromProgress,
lottieObject.toProgress
);
}
const frame = mathf.lerp(
lottieObject.startFrame,
lottieObject.endFrame,
progress
);
if (lottieObject.debugFrame) {
console.log('Frame', frame, easedProgress, window.scrollY);
}
// lottieObject.lottieInstance['goToAndStop'](frame, true);
this.drawOrLoop(lottieObject, frame);
}
});
// Update css var interpolations and class triggers
this.lottieObjects.forEach((lottieObject) => {
// If we have an intro and haven't completed the playback.
const hasIntroAndNotCompleted =
lottieObject.intro && !lottieObject.introCompleted;
if (hasIntroAndNotCompleted) {
return;
}
if (!lottieObject.isOnScreen) {
return;
}
lottieObject.cssInterpolatorInstance &&
lottieObject.cssInterpolatorInstance.update(easedProgress);
});
this.updateClassTriggers(easedProgress);
}
protected updateClassTriggers(progress: number) {
this.lottieObjects.forEach((lottieObject) => {
if (!lottieObject.isOnScreen) {
return;
}
const classesToBeAdded: Array<string> = [];
const classesToBeRemoved: Array<string> = [];
if (lottieObject.classTriggers) {
lottieObject.classTriggers.forEach((trigger: LottieClassTrigger) => {
if (mathf.isBetween(progress, +trigger.from, +trigger.to, true)) {
classesToBeAdded.push(trigger.class);
} else {
classesToBeRemoved.push(trigger.class);
}
});
}
classesToBeAdded.forEach((className) => {
if (!lottieObject.activeTriggerClasses.includes(className)) {
this.element.classList.add(className);
}
});
classesToBeRemoved.forEach((className) => {
if (lottieObject.activeTriggerClasses.includes(className)) {
this.element.classList.remove(className);
}
});
lottieObject.activeTriggerClasses = classesToBeAdded;
});
}
protected updateImmediately() {
// Set the immediate progress at load.
const percent = this.getPercent();
this.rafProgress.setCurrentProgress(percent);
this.lottieObjects.forEach((lottieObject) => {
const hasIntroAndNotCompleted =
lottieObject.intro && !lottieObject.introCompleted;
if (!lottieObject.isOnScreen || hasIntroAndNotCompleted) {
return;
}
lottieObject.cssInterpolatorInstance &&
lottieObject.cssInterpolatorInstance.update(percent);
});
}
protected getPercent(): number {
const percent = dom.getElementScrolledPercent(
this.scrollEl,
this.progressTopOffset,
this.progressBottomOffset
);
return percent;
}
/**
* Given a provided percent, returns the scrollY point. Handy when you
* have to manually update the scroll position to a given percent / progress.
*/
public getScrollYAtPercent(percent: number): number {
return dom.getScrollYAtPercent(
this.scrollEl,
this.progressTopOffset,
this.progressBottomOffset,
percent
);
}
/**
* Gets all lottie objects.
*/
public getLottieObjects(): Array<LottieObject> {
return this.lottieObjects;
}
/**
* Updates the lottie settings via document or events on the root element.
*
* var event = new CustomEvent('degu-lottie-scroll-update', { detail: { lerp: 0.2, damp: 0.3} });
* document.dispatchEvent(event)
*
* // Scope to lottie instance
* element.dispatchEvent(event)
*
* @param e
*/
// Unclear what the lottie event type is.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private handleLottieScrollUpdateEvent(e: any): void {
const payload = e.detail;
if (payload.lerp) {
this.lottieScrollSettings.lerp = +payload.lerp;
}
if (payload.damp) {
this.lottieScrollSettings.damp = +payload.damp;
}
}
protected dispose(): void {
this.lottieObjects.forEach((lottieInstance) => {
lottieInstance.lottieInstance.destroy();
lottieInstance.cssInterpolatorInstance = null;
});
this.domWatcher.dispose();
this.rafProgress.dispose();
}
}
/**
* A directive to run lottie animations based on yaml or json.
*
* In yaml:
* ```
* partial: myPartial
*
* # Lotties is a list so that you can create multiple lottie instances (such as
* portriat versus landscape)
* lottie_scrolls:
* settings:
* # Whether to output progress in the console.
* # Optional - boolean . Defaults to false.
* debug: false
*
* # The lerp to apply
* # Optional - number. A number between 0-1. Defaults to 1.
* lerp: 0.18
*
* # A css value to offset to where the progress begins.
* # Options - string. Accepts %, px, vh
* top: '0px'
*
* # A css value to offset to where the progress ends.
* # Options - string. Accepts %, px, vh
* bottom: '0px'
*
* lotties:
* -
* # The query selector to select the container element of lottie
* # Required - string
* container_selector: '[lottie-desktop]'
*
* # The path to lottie json.
* # Required - string
* json_path: xxx.json
*
* # The image directory path.
* # Options - string
* image_path: /images/
*
* # The renderer to use. 'canvas', 'svg'
* # Optional - string. Defaults to canvas.
* renderer: canvas
*
* # The aspect ratio settings
* # https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio
* preserveAspectRatio: 'xMidYMin slice'
*
* # The starting frame.
* # This is the starting frame from which your "scroll" experience begins.
* # If you have an intro, it should not include the intro frames.
* # Example:
* # lottie is from 0-100 frames.
* # intro is from 0-10.
* # startFrame should be set to 10.
* # Optional - number. Defaults to 0.
* startFrame: 50
*
* # The ending frame.
* # Optional - number. Defaults to the last frame.
* endFrame: 200
*
* # Optional:
* # Normally the lottie animation is tied between the 0-1 progress
* # your whole module. You can define it so that this lottie
* # instance will run under a child progress instead.
* fromProgress: 0.5
* toProgress: 1
*
*
* # Autoplay is used for lottie animations that does not scrub with the scroll
* # but instead play at a specific point. Imagine this more like
* # an inview effect where when the scroll is between the defined
* # fromProgress and toProgress points, this lottie will start playing
* # automatically. If you define a loopStartFrom and loopEndFrame
* # it will loop in that range.
* autoplay:
* fromFrame: 0
* toFrame: 150
* # Whether to trigger this when scrolling down
* down: true
* # Whether to trigger this when scrolling up
* up: true
* # Optional start and end to loop segments.
* loopStartFrame: 150
* loopEndFrame: 300
*
*
* # Class triggers
* # Trigger css class on your element at specific points.
* classTriggers:
* - class: 'inview'
* fromFrame: 300
* toFrame: 500
* - class: 'inview-2'
* fromFrame: 400
* toFrame: 600
*
* # Intro
* # The intro will play an intro IF the current progress value is at 0.
* #
* # The intro.startFrame is where the intro should being.
* # Why is there not endFrame? It's because the end frame is your startFrame
* # (where the scroll starts) above.
* intro:
* startFrame: 0
* # The duration in ms.
* duration: 1000
*
* # Whether to display the current frame number in the dev console.
* # Useful for debugging.
* # Optional - boolean
* debugFrame: false
*
* # Css interpolations synchronized with the lottie scroll.
* # Note that you can use fromFrame, toFrame and declare interpolations
* # based on your lottie frame.
* interpolations:
* - id: '--x'
* progress:
* - from: 0.5
* to: 1
* start: '0px'
* end: '20px'
* - id: '--opacity'
* progress:
* - fromFrame: 200
* toFrame: 300
* start: 0
* end: 1
* cubic_ease: 0.27,0.06,0.3,1
* - fromFrame: 300
* toFrame: 500
* start: 1
* end: 0
*
*
* # toFrame addition available in interpolations ONLY (for now)
* # This allows you to add from the fromFrame value which can be handy.
* fromFrame: 1300
* toFrame: '+30'
*
* ```
*
* In your app:
*
*
* Make sure lottie-web is installed.
* ```
* npm install lottie-web@5.7.0 --save
* ```
*
* ```ts
* import { lottieScrollDirective } from 'degu/lib/angular/directive-lottie-scroll';
*
* const app = angular.module('myApp', []);
* app.directive('lottieScroll', lottieScrollDirective);
* ```
*
* In the module, you want to use do the following.
*
* Note how we have can have two lottie instances. By adding display: none, this
* lottie directive will automatically cull frame updates.
*
* ```
* .mymodule
* height: 300vh
* .mymodule__lottie
* position: sticky
* height: 100vh
* width: 100%
* top: 0px
* .mymodule__lottie--desktop
* +md-lt
* display: none
* .mymodule__lottie--mobile
* +md
* display: none
*
* <div class="mymodule" {% if partial.lottie_scrolls %} lottie-scroll="{{partial.lottie_scrolls|jsonify}}{% endif %">
* <div class="mymodule__lottie mymodule__lottie--desktop" lottie-desktop></div>
* <div class="mymodule__lottie mymodule__lottie--mobile" lottie-mobile></div>
* </div>
* ```
*
* # Fouc control - Loaded class
*
* A css class "lottie-scroll-loaded" gets appended to the directive element.
* This can be used to hide the element during loading.
*
* .mymodule
* visibility: hidden
* .mymodule.lottie-scroll-loaded
* visibility: visible
*
* Before Load:
* <div class="mymodule" lottie-scroll="{{partial.lottie_scrolls|jsonify}}{% endif %">..</div>
*
* After Load
* <div class="mymodule loaded" lottie-scroll="{{partial.lottie_scrolls|jsonify}}{% endif %">..</div>
*
* # Events
*
* You may have situations in which you want to extend or add additional more complicated
* interaction. There are a few ways to do this
* 1) you can create your own controller
* and setup lottie interpolations manually (so don't use this directive).
* This is recommended if you have a lot of custom needed.
* 2) You can extend this directive.
* 3) Use events to listen to the progress update event.
*
*
* Events are useful if you want to add some custom interaction based on the progress.
*
* Raf Progress events are fired on the root element of the directive.
* Hooking into them with your own custom controller might look something
* this:
*
*
* ```
* <div
* ng-controller="MyController as ctrl"
* lottie-scroll="{{partial.lottie_scrolls|jsonify}}">
* <div class="post-hero__lottie" lottie-container></div>
* </div>
*
*
*
* import { LottieController, LottieScrollEvents, LottieScrollEventPayload, LottieScrollInitPayload } from 'degu/lib/angular/directive-lottie-scroll';
*
*
* export default class MyController {
* static get $inject() {
* return ['$scope', '$element'];
* }
* private el: HTMLElement;
* private $scope: ng.IScope;
* constructor($scope: ng.IScope, $element: ng.IAugmentedJQuery) {
* this.el = $element[0];
* this.el.addEventListener(LottieScrollEvents.INIT, (e:any)=> {
* const scrollEvent:LottieScrollInitPayload = e.detail;
* console.log(scrollEvent.controller); // The controller
* });
*
* this.el.addEventListener(LottieScrollEvents.PROGRESS_UPDATE, (e:any)=> {
* const scrollEvent:LottieScrollEventPayload = e.detail;
* console.log(scrollEvent.progress); // current progress
* console.log(scrollEvent.direction); // current direction
* })
* }
* }
* ```
*
*
*
* Additional Docs:
*
* Lottie supported Features:
* https://github.com/airbnb/lottie/blob/master/supported-features.md
*
*
*
*
*/
export const lottieScrollDirective = function () {
return {
restrict: 'A',
controller: LottieController,
};
};
|