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 | import * as func from '../func/func';
import {CssVarInterpolate} from '../interpolate/css-var-interpolate';
import type {interpolateSettings} from '../interpolate/multi-interpolate';
import * as is from '../is/is';
import * as mathf from '../mathf/mathf';
import {Raf} from '../raf/raf';
import * as cssUnit from '../string/css-unit';
import {
type EventCallback,
type EventDispatcher,
EventManager,
} from '../ui/events';
import * as dom from './dom';
import {DomWatcher} from './dom-watcher';
import {
type ElementVisibilityObject,
elementVisibility,
} from './element-visibility';
import type {InviewProgress} from './inview-progress';
import type {ProgressWatcher} from './progress-watcher';
export enum CssParallaxerEvents {
RAF = 'raf',
RESIZE = 'resize',
}
export interface CssParallaxSettings {
// debug: false (boolean, optional) True outputs progress in the dev console.
debug?: boolean;
// top: '0px' (string) A css number to offset where the progress begins. Accepts %, px, vh.
top?: string;
// bottom: '0px' (string) A css number to offset the progress ends. Accepts %, px, vh.
bottom?: string;
// height: '100px' (string) Optional. An absolute height to use to calculate the percent. Accepts %, px, vh. In most cases you won't need this.
height?: string | null;
// http://degu.surge.sh/classes/mathf.mathf-1.html#damp
// lerp: 0.18 Optional lerp. Defaults to 1 assuming no asymptotic averaging.
lerp?: number;
// damp: 0.18 Optional damp. Defaults to 1 assuming no damping.
damp?: number;
// Whether to force clamp the progress to 0-1 range. Defaults to true.
clamp?: boolean;
// Limits the lerping to only when values are beteween 0-1. Defaults to true.
lerpOnlyInRange?: boolean;
// The precision rounding on the lerp. Used to cull / avoid layout thrashes.
// precision: (number) Defaults to 3. Lower precision means less dom updates but less accuracy.
precision?: number;
// The rafEvOptions so that you can add rootMargin etc to the base raf.
// rafEvOptions:
// rootMargin: '0px 0px 0px 0px'
rafEvOptions?: Object;
// Optional mobile lerp.
// Requires mobileBreakpoint to be enabled.
lerpMobile?: number;
// Optional mobile damp.
// Requires mobileBreakpoint to be enabled.
dampMobile?: number;
// The breakpoint width of mobile.
mobileBreakpoint?: number;
// Optionally pass inviewProgress.
// This can be used to trigger css classes at specific breakpoints.
inviewProgress?: InviewProgress | null;
// Optionally pass progressWatcher.
progressWatcher?: ProgressWatcher | null;
// Option to manually update progress.
// CssParallax automatically updates progress based on the root element progress.
// You can disable this with this option in which case you would use the
// setProgress(progress) method to manually update the progress of this
// css parallaxer.
manualProgressUpdates?: boolean;
//
// In some cases, you may want to track the progress of a specific
// element but add the css variables to another. In this case,
// you can instantiate cssParallax with the element you want to add
// css variables to and pass the element you want to track the progress to
// with this option. Typically, the progressElement would be a child
// of the element you instantiate against.
//
progressElement?: HTMLElement;
// Whether to use subpixelrendering. Defaults to true.
subpixelRendering?: boolean;
}
/**
* A class that creates a css var parallaxer. This is the base controller for
* directive-css-parallax. See documentation there for more on usage.
*
* ```
*
* // Create the instance and set the root element
* const parallaxer = new CssParallaxer(element);
*
*
* // Add your settings.
* const settings = {
* debug: false,
* top: '0px'
* bottom: '10px'
* }
* parallaxer.init(settings,
* [
* {
* id: '--x',
* progress: [
* {from: 0, to: 1, start: '0px', end: '0px'}
* ]
* }
* ]
* )
*
*
* // Later Dispose.
* parallaxer.dispose();
* ```
*
* ## Mobile Lerp
* You can specify a different lerp value for mobile.
*
* ```
* const settings = {
* lerp: 0.4,
* damp: 0.23
* mobileBreakpoint: 769
* lerpMobile: 1
* dampMobile: 1
* }
* ```
*
* ## FOUC
*
* You can fight FOUC by setting defaults to your var and also by using the
* .css-parallax-ready class that gets applied to the root element
* when the css-parallaxer initializer.
*
* ```
* .my-module
* visibility: hidden
* &.css-parallax-ready
* visibility: visible
* ```
*
* ## How do I add css classes to elements?
* You can pass an instance of inviewProgress to cssParallaxer.
*
* ```ts
* const inviewProgress = new InviewProgress();
*
* // Add the class "active" when from range 0.2 - 0.4
* inviewProgress.add({
* range: [0.2, 0.4],
* element: el,
* className: "active"
* })
*
* // Setup css parallax
* const settings = {
* debug: false,
* top: '0px'
* bottom: '10px',
* inviewProgress: inviewProgress
* }
* const parallaxer = new CssParallaxer(el);
* parallaxer.init(settings, [])
* ```
*
* ## How do add callbacks at specific points?
* You can pass an instance of progressWatcher to css parallax.
*
* ```
* const pg = new ProgressWatcher();
* pg.add({
* range: [0.2, 0.4],
* callback: (progress: number, direction: number)=> {
* console.log(progress, direction);
* }
* })
*
* const settings = {
* debug: false,
* top: '0px'
* bottom: '10px',
* progressWatcher: pg
* }
* const parallaxer = new CssParallaxer(el);
* parallaxer.init(settings, [])
* ```
*
* # Listening to events.
*
* parallaxer.on(CssParallaxerEvents.RAF, ()=> {
* console.log(parallaxer.getProgress());
* });
*
* parallaxer.on(CssParallaxerEvents.RESIZE, ()=> {
* ...
* });
*
*
* # How can I make css-parallax not scroll tied?
*
* You can tell css-parallax to not update progress internally by
* adding using the manualProgressUpdate oetption.
*
* ```
* cssParallaxer = new window.MqnLib.CssParallaxer(
* this.el
* );
*
* cssParallaxer.init({
* manualProgressUpdates: true
* }, [
* {
* id: '--progress',
* progress: [{ from: 0, to: 1, start: 0, end: 1 }],
* },
* ]);
*
*
* ```
* Now you can manually update the internal progress value.
*
* ```
* this.cssParallaxer.setManualProgress(progress);
* ```
*
* Using setManualProgress, if you wanted to play the cssParallaxer like a video,
* you could combine it with rafTimer.
*
* ```
* let rafTimer = new RafTimer((progress)=> {
* this.cssParallaxer.setManualProgress(progress);
* });
* rafTimer.setDuration(300);
* rafTimer.play();
*
* ```
*
*
* You could also combine it with scrollProgress and progressWatcher,
* to trigger a css-parallax animation at a given point.
*
* ```
* const progressWatcher = new ProgressWatcher();
*
* // Play the css-parallax from 0 to 0.5 when the scrollProgress reaches
* // 0.5.
* progressWatcher.add({
* range: 0.5,
* callback: (progress: number, direction: number)=> {
* // Up
* if(direction === -1) {
* let rafTimer = new RafTimer((progress:number)=> {
* const childProgress = mathf.inverseProgress(mathf.childProgress(progress, 0, 0.8));
* this.cssParallaxer.setManualProgress(childProgress);
* });
* rafTimer.setDuration(600);
* rafTimer.play();
* }
*
* // Down
* if(direction === 1) {
* let rafTimer = new RafTimer((progress:number)=> {
* const childProgress = mathf.childProgress(progress, 0, 0.8);
* this.cssParallaxer.setManualProgress(childProgress);
* });
* rafTimer.setDuration(600);
* rafTimer.play();
* }
* }
* })
*
*
* const scrollProgress = new ScrollProgress(element);
* // Add your settings.
* const settings = {
* debug: false,
* top: '0px'
* bottom: '10px'
* progressWatcher: progressWatcher
* }
* scrollProgress.init(settings);
*
* ```
*
*
*
*/
export class CssParallaxer implements EventDispatcher {
private eventManager: EventManager;
private element: HTMLElement;
private rafEv: ElementVisibilityObject | null = null;
private domWatcher: DomWatcher;
private interpolator: CssVarInterpolate | null = null;
private raf: Raf;
private initialized = false;
private settingsData: CssParallaxSettings | null = null;
private currentProgress = 0;
/**
* The top offset for progress
*/
private topOffset = 0;
/**
* The bottom offset for progress
*/
private bottomOffset = 0;
/**
* The height value if specified.
*/
private height: number | null = null;
private windowWidth: number | null = null;
private windowHeight: number | null = null;
constructor(element: HTMLElement) {
this.eventManager = new EventManager();
this.element = element;
this.raf = new Raf(this.onRaf.bind(this));
this.domWatcher = new DomWatcher();
this.domWatcher.add({
element: window,
on: 'smartResize',
callback: func.debounce(() => {
this.onWindowResize();
}, 300),
});
this.cacheWindowSize();
}
public on(event: string, callback: EventCallback) {
this.eventManager.on(event, callback);
}
public off(event: string, callback: EventCallback) {
this.eventManager.on(event, callback);
}
/**
* Initializes module.
* You can optionally rerun this method to refresh settings.
* @param settings
*/
public init(
settings?: CssParallaxSettings,
interpolations?: Array<interpolateSettings>
) {
if (settings) {
this.updateSettings(settings);
}
if (interpolations) {
this.updateInterpolations(interpolations);
}
}
/**
* Updates the interpolations.
* @param settings
*/
public updateInterpolations(interpolations: Array<interpolateSettings>) {
// Only run this on the first initialization.
if (!this.initialized) {
// Create interpolator.
this.interpolator = new CssVarInterpolate(this.element, {
interpolations: interpolations || [],
});
this.interpolator.useBatchUpdate(true);
this.interpolator.useSubPixelRendering(
this.settingsData!.subpixelRendering!
);
this.element.classList.add('css-parallax-ready');
this.rafEv = elementVisibility.inview(
this.element,
this.settingsData!.rafEvOptions,
(element: HTMLElement, changes: IntersectionObserverEntry) => {
if (changes.isIntersecting) {
this.updateImmediately();
this.raf.start();
} else {
this.raf.stop();
this.updateImmediately();
}
}
);
this.initialized = true;
} else {
// Update if already set.
this.interpolator!.setInterpolations({
interpolations: interpolations || [],
});
}
// On load, we need to initially, bring the animation to
// start position.
this.updateImmediately();
}
/**
* Updates the css parallaxer settings.
* @param settings
*/
public updateSettings(settings?: CssParallaxSettings) {
// If we haven't set the settings data yet apply default.
if (!this.settingsData) {
this.settingsData = {
...{
debug: false,
clamp: true,
top: '0px',
bottom: '0px',
height: null,
lerp: 1,
damp: 1,
precision: 3,
lerpOnlyInRange: true,
rafEvOptions: {
rootMargin: '300px 0px 300px 0px',
},
inviewProgress: null,
progressWatcher: null,
manualProgressUpdates: false,
subpixelRendering: true,
},
...(settings || {}),
};
} else {
// If we have already set once.
this.settingsData = {
...this.settingsData,
...(settings || {}),
};
}
if (!this.settingsData.progressElement) {
this.settingsData.progressElement = this.element;
}
this.calculateProgressOffsets();
}
public getSettings(): CssParallaxSettings | null {
return this.settingsData;
}
/**
* 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);
}
/**
* Returns the internal multi interpolator.
*/
public getInterpolator() {
return this.interpolator;
}
/**
* Calculates the current progress and returns a value between 0-1.
*/
public updateProgress(lerp: number, damp: number): number {
if (this.settingsData!.manualProgressUpdates) {
return this.currentProgress;
}
const progress = dom.getElementScrolledPercent(
this.settingsData?.progressElement || this.element,
this.topOffset,
this.bottomOffset,
true,
this.windowHeight || window.innerHeight
);
// Don't apply lerp / damp when we are out of range.
// The problem is that if you apply damp / lerp out of range,
// Animations that depend on start (0) and end (1) end up
// getting slightly delayed causing FOUC.
if (
(this.settingsData!.lerpOnlyInRange && progress <= 0) ||
(this.settingsData!.lerpOnlyInRange && progress >= 1)
) {
this.currentProgress = progress;
} else {
// If no lerping, bypass.
if (lerp === 1 && damp === 1) {
this.currentProgress = progress;
} else {
this.currentProgress = mathf.damp(
this.currentProgress,
progress,
lerp,
damp
);
}
}
if (this.settingsData!.clamp) {
this.currentProgress = mathf.clamp01(this.currentProgress);
}
if (this.settingsData!.debug) {
console.log(this.currentProgress, this.topOffset, this.bottomOffset);
}
// Update inviewProgress if provided.
if (this.settingsData!.inviewProgress) {
this.settingsData!.inviewProgress.setProgress(this.currentProgress);
}
// Update progressWatcher if provided.
if (this.settingsData!.progressWatcher) {
this.settingsData!.progressWatcher.setProgress(this.currentProgress);
}
return this.currentProgress;
}
public updateImmediately() {
this.updateProgress(1, 1);
this.interpolator!.update(this.currentProgress);
}
protected calculateProgressOffsets() {
this.topOffset = func.setDefault(
this.getPixelValue(this.settingsData!.top!),
0
);
this.bottomOffset = func.setDefault(
this.getPixelValue(this.settingsData!.bottom!),
0
);
this.height = is.string(this.settingsData!.height)
? this.getPixelValue(this.settingsData!.height!)
: null;
// If height is specified, we basically want to "shorten" the element
// by the delta amount.
// Example: el.offsetHeight = 500px, height: 100px.
// so bottomOffset should be el.offsetHeight - height = 400px
requestAnimationFrame(() => {
if (this.height) {
this.bottomOffset = -(this.element.offsetHeight - this.height);
}
});
}
private cacheWindowSize() {
this.windowHeight = window.innerHeight;
this.windowWidth = window.innerWidth;
}
protected onWindowResize() {
this.cacheWindowSize();
if (this.settingsData) {
return;
}
this.calculateProgressOffsets();
this.interpolator!.flush();
this.updateImmediately();
this.eventManager.dispatch(CssParallaxerEvents.RESIZE);
}
protected onRaf() {
if (this.settingsData!.manualProgressUpdates) {
return;
}
this.raf.read(() => {
// Mobile case.
if (
this.settingsData!.mobileBreakpoint &&
window.innerWidth < this.settingsData!.mobileBreakpoint &&
this.settingsData!.dampMobile &&
this.settingsData!.lerpMobile
) {
this.updateProgress(
this.settingsData!.lerpMobile,
this.settingsData!.dampMobile
);
} else {
// All others.
this.updateProgress(this.settingsData!.lerp!, this.settingsData!.damp!);
}
});
this.raf.write(() => {
// Use a rounded progress to pass to css var interpolate which
// will cull updates that are repetitive.
const roundedProgress = mathf.roundToPrecision(
this.currentProgress,
this.settingsData!.precision!
);
this.interpolator!.update(roundedProgress);
});
this.eventManager.dispatch(CssParallaxerEvents.RAF);
}
/**
* Gets the current progress value.
*/
public getProgress(): number {
return this.currentProgress;
}
/**
* Set the internal progress value of css-parallaxer.
*
* Using this method will alter how css-parallaxer works.
* It will:
* 1) disable css-parallaxer to stop autoupdating the progress values
* based on scroll and instead leave it up to you to update the progress
* values.
* 2) Further, lerp, damp values will get ignored and progress
* updating is linear. If you need eases, the ease should be applied to
* the progress argument.
* 3) Internal raf of css-parallaxer will be stopped.
*
* In short, using this method, will relieve css-parallaxer from internally
* trying to update the progress values and use css-parallaxer as an
* abstracton of css interpolations that you update via this method.
* @param progress
*/
public setManualProgress(progress: number) {
this.raf && this.raf.stop();
this.currentProgress = progress;
this.settingsData!.manualProgressUpdates = true;
this.interpolator!.update(this.currentProgress);
if (this.settingsData!.debug) {
console.log(this.currentProgress, this.topOffset, this.bottomOffset);
}
// Update inviewProgress if provided.
if (this.settingsData!.inviewProgress) {
this.settingsData!.inviewProgress.setProgress(this.currentProgress);
}
// Update progressWatcher if provided.
if (this.settingsData!.progressWatcher) {
this.settingsData!.progressWatcher.setProgress(this.currentProgress);
}
}
/**
* Allows you to acquire the percent of a given element within the css-parallax
* root element.
*
* The element would be the element you want. The baseLine is a number that
* is from 0 to 1. 0 is the top of the element, 0.5 would be the middle and 1
* would be the bottom of the element.
*
*
* Example:
* ```html
* <div myparallax>
* ...
* <div section1>...</div>
* ...
* </div>
* ```
*
* ```ts
* const cssParallaxer = new CssParallaxer(document.querySelector('[myparallax]));
*
* // Don't use init and instead use a combination of updateSettings and
* // updateInterpolations to manually initialize the module.
* cssParallax.updateSettings({
* debug: false,
* lerp: 1,
* damp: 1,
* lerpOnlyInRange: false,
* top: window.innerHeight + 'px',
* bottom: window.innerHeight + 'px',
* })
*
*
* // Now let's say I want an interpolation that starts when section1
* // comes into view and ends when 80% of section1 has been scrolled in. We can
* // calculate this with getElementProgressPoint.
* const section1Element = document.querySelector('[section1]');
* const sectionInProgressPoint = cssParallax.getElementProgressPoint(section1Element, 0)
* const sectionOutProgressPoint = cssParallax.getElementProgressPoint(section1Element, 0.8)
*
*
* cssParallax.updateInterpolations([
* {
* id: '--my-custom-progress',
* progress: [{
* from: sectionInProgressPoint, to: sectionOutProgressPoint, start: 0, end: 1 }],
* },
* ]);
*
* ```
*/
public getElementProgressPoint(targetElement: HTMLElement, baseline = 0) {
return dom.getElementProgressPoint(
this.settingsData?.progressElement || this.element,
targetElement,
baseline,
this.topOffset,
this.bottomOffset,
true
);
}
public getRaf() {
return this.raf;
}
public dispose() {
this.eventManager.dispose();
this.raf && this.raf.stop();
this.domWatcher.dispose();
this.rafEv!.dispose();
}
}
|