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 | 1x | import * as arrayf from '../../arrayf/arrayf';
import {
CachedMouseTracker,
CachedMouseTrackerEvent,
} from '../../dom/cached-mouse-tracker';
import * as dom from '../../dom/dom';
import {DomWatcher} from '../../dom/dom-watcher';
import {DefaultMap} from '../../map/default-map';
import {CubicBezier, type EasingFunction} from '../../mathf/cubic-bezier';
import * as mathf from '../../mathf/mathf';
import {Raf} from '../../raf/raf';
import type {Carousel} from './carousel';
import type {Transition} from './transitions';
/**
* Small enum for readability when traversing slide indices.
*/
enum Direction {
LEFT = -1,
RIGHT = 1,
}
/**
* Configuration options for this transition.
*/
export interface DraggableSlideConfig {
transitionTime?: number; // How long the transition animation should take
easingFunction?: EasingFunction; // Easing function for the transition
}
/**
* Encapsulates information around a slide that needs to be transitioned to.
*/
class TransitionTarget {
readonly target: HTMLElement;
readonly timeRange: [number, number];
readonly startDistance: number;
constructor(
target: HTMLElement,
timeRange: [number, number],
startDistance: number
) {
this.target = target;
this.timeRange = timeRange;
this.startDistance = startDistance;
}
}
/**
* Track the information associated with a user interaction.
*/
class Interaction {
readonly startX: number;
readonly startTime: number;
lastMouseX: number;
constructor(startX: number, startTime: number) {
this.startX = startX;
this.startTime = startTime;
this.lastMouseX = startX;
}
}
/**
* Return the x translation amount from the given element's transform.
*/
function getTranslateX(el: HTMLElement): number {
const transform = dom.getComputedStyle(el).transform;
if (!transform.length || transform === 'none') {
return 0;
}
// Grab the tx value from the matrix
return parseFloat(transform.slice(7, -1).split(',')[4]);
}
/**
* A transition for a carousel that allows the user to drag and fling slides
* around. Similar to the default interaction for a "slick" carousel.
*
* For proper operation, the slide elements within the carousel should be
* lined up side-by-side and overflowing the container. The container should
* be overflow: hidden; The slide elements themselves should not have transforms
* applied. Children of the slide elements however can be transformed as needed
* to achieve necessary visual effects.
*/
export class DraggableSlide implements Transition {
private static DEFAULT_EASING: EasingFunction = new CubicBezier(
0.445,
0.05,
0.55,
0.95
).easingFunction();
/**
* Sums the offsetWidth of the given slides.
*
* Was repeated enough to seem worth extracting.
*/
private static sumWidth(slides: HTMLElement[]) {
return mathf.sum(slides.map((slide) => slide.offsetWidth));
}
private readonly easingFunction: EasingFunction;
private readonly domWatcher: DomWatcher;
private readonly transitionTime: number;
private readonly mouseTracker: CachedMouseTracker;
private readonly xTranslate: DefaultMap<HTMLElement, number>;
/**
* Stores the last xTranslation value that was applied to a given slide.
*
* This is used to prevent duplicate styles from being re-applied and clogging
* up the inspector view.
* @private
*/
private readonly lastXTranslate: DefaultMap<HTMLElement, number | null>;
private transitionTarget: TransitionTarget | null;
private carousel?: Carousel;
private resizeTimeout: number | null;
private interaction: Interaction | null;
private startInteractionCallback: () => void;
private raf: Raf;
/**
* @param transitionTime Determines how long in ms it takes to transition from
* one slide to another.
* @param easingFunction Easing function used to adjust slides transitions.
*/
constructor({
transitionTime = 500,
easingFunction = DraggableSlide.DEFAULT_EASING,
}: DraggableSlideConfig = {}) {
this.raf = new Raf(() => this.onRaf());
this.domWatcher = new DomWatcher();
this.easingFunction = easingFunction;
this.transitionTime = transitionTime;
this.transitionTarget = null;
this.resizeTimeout = null;
this.mouseTracker = new CachedMouseTracker();
this.interaction = null;
// Tracks the current X translation of each slide.
// Used so that slide can be adjusted for looping and dragging within the
// same frame without introducing layout thrashing by updating the DOM
// twice.
this.xTranslate = DefaultMap.usingFunction((el: HTMLElement) =>
getTranslateX(el)
);
this.lastXTranslate = DefaultMap.usingFunction(() => null);
this.startInteractionCallback = () => this.startInteractionOnMouseUpdate();
}
/**
* This function is called by the carousel when the transition is passed to
* the carousel. Until this function is called the DraggableSlide instance is
* more or less inert.
*/
init(carousel: Carousel): void {
this.initResizeHandler();
this.carousel = carousel;
// Transition to the given active slide
this.raf.read(() => this.transition(carousel.getFirstSlide(), 0));
this.initDraggableSlides();
this.raf.start();
}
/**
* Updates slide positioning in response to user interaction and transition
* animations.
*/
onRaf(): void {
if (this.carousel!.isDisabled()) {
return;
}
this.raf.read(() => {
if (!this.isInteracting() && this.transitionTarget) {
this.renderTransition();
} else {
if (this.isInteracting()) {
this.renderInteraction();
}
this.loopSlides();
}
// Applies the scheduled X translations set up in other functions.
// This ensures that splitting slides for looping, transitions and
// interactions can all adjust the X position without updating the DOM
// more than once per frame.
this.applyXTranslations();
});
}
/**
* Transition to the given target within the given time.
* @param targetEl
* @param optTransitionTime Time the transition should take, uses value
* provided to the constructor is no value is provided for this call.
*/
transition(
targetEl: HTMLElement,
optTransitionTime: number | null = null
): void {
if (
this.transitionTarget !== null &&
this.transitionTarget.target === targetEl
) {
return; // Don't reset target time
}
const transitionTime =
optTransitionTime === null ? this.transitionTime : optTransitionTime;
const now = performance.now();
const timeRange: [number, number] = [now, now + transitionTime];
const distance = this.getDistanceToCenter(targetEl);
this.transitionTarget = new TransitionTarget(targetEl, timeRange, distance);
}
/**
* Returns the currently active slide.
*/
getActiveSlide(): HTMLElement {
return arrayf.min(
this.carousel!.getSlides(),
// Start with the one closest to the center
(el) => {
return Math.abs(
this.getDistanceBetween(<HTMLElement>el, this.carousel!.container)
);
},
// If neither slide was last active default to the one that appears first
// in the list of slides
(el) => -1 * this.carousel!.getIndex(el)
);
}
/**
* Returns true if the carousel has transitioned to the given slide.
* @param slide
*/
hasTransitionedTo(slide: HTMLElement): boolean {
return this.getDistanceToCenter(slide) === 0;
}
/**
* Returns true if the user is interacting with the slides.
*/
isInteracting(): boolean {
return this.interaction !== null;
}
/**
* Dispose of the transition.
*/
dispose() {
this.resizeTimeout && window.clearTimeout(this.resizeTimeout);
this.mouseTracker.dispose();
this.domWatcher.dispose();
this.xTranslate.clear();
this.lastXTranslate.clear();
}
private initResizeHandler(): void {
this.domWatcher.add({
element: window,
on: 'resize',
eventOptions: {passive: true},
callback: () => {
if (this.resizeTimeout) {
window.clearTimeout(this.resizeTimeout);
}
this.resizeTimeout = window.setTimeout(() =>
this.transition(this.carousel!.getActiveSlide(), 0)
);
},
});
}
/**
* Limit how far slides can be moved left/right if looping is not allowed for
* the carousel.
*/
private constrainXTranslations() {
if (this.carousel!.loop) {
return;
}
const slides = this.carousel!.getSlides();
// Allow for centering the last slide
const halfContainer = this.carousel!.container.offsetWidth / 2;
const totalSlideWidth = DraggableSlide.sumWidth(slides);
const lastSlideWidth = slides.slice(-1)[0].offsetWidth;
const halfLastSlide = lastSlideWidth / 2;
const halfFirstSlide = slides[0].offsetWidth / 2;
const min = halfContainer - totalSlideWidth + halfLastSlide;
const max = halfContainer - halfFirstSlide;
slides.forEach((slide: HTMLElement) => {
const currentX = this.xTranslate.get(slide);
this.xTranslate.set(slide, mathf.clamp(min, max, currentX));
});
}
private applyXTranslations() {
this.constrainXTranslations();
// Apply all X Translates in a single step
this.raf.write(() => {
this.xTranslate.forEach((xTranslate, slide) => {
// Don't re-apply the same style twice, it will just clog up the
// inspector and make debugging difficult.
if (this.lastXTranslate.get(slide) !== xTranslate) {
slide.style.transform = `translateX(${xTranslate}px)`;
this.lastXTranslate.set(slide, xTranslate);
}
});
});
}
private renderInteraction() {
const currentMouseX = this.getMouseX();
const delta = currentMouseX - this.interaction!.lastMouseX;
this.interaction!.lastMouseX = currentMouseX;
this.carousel!.getSlides().forEach((slide) => {
this.translate(slide, delta);
});
}
/**
* Return the distance between the given slide and the center of the carousel.
*/
private getDistanceToCenter(slide: HTMLElement): number {
return this.getDistanceBetween(slide, this.carousel!.container);
}
/**
* Setup the Draggable instances that will correspond to the slide elements.
*/
private initDraggableSlides(): void {
this.carousel!.getSlides().forEach((slide) => {
['touchstart', 'mousedown'].forEach((event: string) => {
this.domWatcher.add({
element: slide,
on: event,
eventOptions: {passive: true},
callback: () => this.startInteraction(),
});
});
['contextmenu', 'dragstart', 'touchend', 'mouseup'].forEach(
(event: string) => {
this.domWatcher.add({
element: window,
on: event,
eventOptions: {passive: true},
callback: () => this.endInteraction(),
});
}
);
});
}
/**
* Returns the eased transition percent.
*
* Extracted from renderTransition so its name can serve to help
* readability.
*/
private getEasedTransitionPercent(): number {
const transitionPercent = mathf.inverseLerp(
this.transitionTarget!.timeRange[0],
this.transitionTarget!.timeRange[1],
performance.now()
);
return this.easingFunction(transitionPercent);
}
/**
* Adjust CSS properties to reflect the current state of the transition
* animation to the current target.
*/
private renderTransition() {
const target = this.transitionTarget;
if (!target) {
return;
}
const easedPercent = this.getEasedTransitionPercent();
const targetDistance = mathf.lerp(target.startDistance, 0, easedPercent);
const currentDistance = this.getDistanceToCenter(target.target);
const absDelta = Math.abs(targetDistance) - Math.abs(currentDistance);
const currentDistanceSign = Math.sign(currentDistance);
const xDelta = absDelta * currentDistanceSign;
this.carousel!.getSlides().forEach((slide) =>
this.translate(slide, xDelta)
);
this.loopSlides();
// If we're close enough, let's call it
if (easedPercent === 1) {
this.transitionTarget = null;
}
}
/**
* Translate the given slide by the given amoutn
* @param slide
* @param delta
*/
private translate(slide: HTMLElement, delta: number) {
// Round to something reasonable
const final = Math.round((this.xTranslate.get(slide) + delta) * 100) / 100;
this.xTranslate.set(slide, final);
}
/**
* Adjust the split of slides around the currently active slide.
*
* Is a no-op for non-looping carousels.
*
* Ensures:
* - Slides cover as much of the carousel as possible.
* - Slides loop from one side to the other.
*/
private loopSlides(): void {
if (!this.carousel!.loop) {
return;
}
// No matter what we need to loop adjust the target if we have one
const target: HTMLElement =
(this.transitionTarget && this.transitionTarget.target) ||
this.carousel!.getActiveSlide();
const targetIndex = this.carousel!.getIndex(target);
const slides = this.carousel!.getSlides();
const slidesToAdjust = new Set(slides.filter((slide) => slide !== target));
const leftEdge = target.getBoundingClientRect().left;
const left = {
area: Math.max(leftEdge, 0), // Area to cover on this side
index: targetIndex, // The index to start at
direction: Direction.LEFT, // Direction to move in for the next slide
};
const clientWidth = dom.getScrollElement().clientWidth;
const rightEdge = leftEdge + target.offsetWidth;
const right = {
area: Math.min(clientWidth, clientWidth - rightEdge),
index: targetIndex,
direction: Direction.RIGHT,
};
const sides = [left, right];
while (slidesToAdjust.size > 0) {
const side = arrayf.max(sides, (s) => s.area);
side.index += side.direction;
const slideToAdjust = slides[mathf.wrap(side.index, 0, slides.length)];
side.area -= slideToAdjust.offsetWidth;
const desiredOffset = this.getDesiredDistanceBetween(
target,
slideToAdjust,
side.direction
);
const delta =
desiredOffset - this.getDistanceBetween(slideToAdjust, target);
if (delta !== 0) {
this.translate(slideToAdjust, delta);
}
slidesToAdjust.delete(slideToAdjust);
}
}
/**
* Handle the start of user interaction with the carousel.
* @param event
*/
private startInteraction(): void {
if (this.isInteracting()) {
return;
}
// Delay to the post-write step to allow the mouse cached position to
// catch up.
this.mouseTracker?.on(
CachedMouseTrackerEvent.UPDATE,
this.startInteractionCallback
);
}
/**
* Starts a drag on the slide.
* @private
*/
private startInteractionOnMouseUpdate(): void {
// Start interaction only once for this call
this.cancelStartInteractionCallback();
this.interaction = new Interaction(this.getMouseX(), performance.now());
this.transitionTarget = null;
this.carousel!.stopTransition();
}
/**
* Clear the callback for starting an interaction.
* @private
*/
private cancelStartInteractionCallback(): void {
this.mouseTracker?.off(
CachedMouseTrackerEvent.UPDATE,
this.startInteractionCallback
);
}
/**
* Handle the end of user interaction with the carousel.
* @param event
*/
private endInteraction(): void {
if (this.interaction === null) {
// Cancel the callback in case the interaction was about to start.
this.cancelStartInteractionCallback();
return;
}
const duration = performance.now() - this.interaction.startTime;
const activeSlide = this.getActiveSlide();
const distance = this.getDistanceToCenter(activeSlide);
const interactionDelta = this.getMouseX() - this.interaction.startX;
const velocity = duration > 700 ? interactionDelta : 0;
this.interaction = null;
const velocitySign = Math.sign(velocity);
const distanceSign = Math.sign(distance) * -1;
const allowsLooping = this.carousel!.loop;
// If the slide is already centered, then it is clearly the slide to
// transition to.
if (distance === 0 || distanceSign === velocitySign || velocity === 0) {
this.carousel!.goToSlide(activeSlide);
} else {
// If the user was dragging to the right, transition in the opposite
// direction.
if (velocitySign === Direction.RIGHT) {
if (allowsLooping || activeSlide !== this.carousel!.getFirstSlide()) {
this.carousel!.prev();
} else {
// If we are already at the first slide and can't loop, transition
// as is.
this.carousel!.goToSlide(activeSlide);
}
// If the user was dragging to the left, transition in the opposite
// direction.
} else {
if (allowsLooping || activeSlide !== this.carousel!.getLastSlide()) {
this.carousel!.next();
} else {
// If we are already at the last slide and can't loop, transition
// as is.
this.carousel!.goToSlide(activeSlide);
}
}
}
}
/**
* Return the current mouse position.
*/
private getMouseX(): number {
return this.mouseTracker!.getClientPosition()!.x;
}
/**
* Return the X position of the given elements center.
*
* Factors in upcoming X translation changes.
*/
private getCenter(el: HTMLElement): number {
if (!el) {
return 0;
}
const rect = el.getBoundingClientRect();
const raw = rect.left + rect.width / 2;
const xTranslationDelta = this.xTranslate.get(el) - getTranslateX(el);
return raw + xTranslationDelta;
}
/**
* Returns the distance between the given elements centers.
*
* If no second element is given, the root element's center is used instead.
*/
private getDistanceBetween(
a: HTMLElement,
b: HTMLElement | null = null
): number {
// Gather up the information on the first element's center position.
const aCenter = this.getCenter(a);
// Gather the info on the second element's center position or the root
// element's center position.
if (b !== null) {
return aCenter - this.getCenter(b);
} else {
return aCenter - document.children[0].clientWidth / 2;
}
}
/**
* Return how far the given slide is from the given target slide in terms of
* slide width in pixels.
*/
private getDesiredDistanceBetween(
a: HTMLElement,
b: HTMLElement,
direction: Direction
): number {
if (a === b) {
return 0;
}
const inBetweenSlides = this.getInBetweenSlides(a, b, direction);
const inBetweenWidth = DraggableSlide.sumWidth(inBetweenSlides);
const halfSlide = b.offsetWidth / 2;
const halfTarget = a.offsetWidth / 2;
return (halfSlide + inBetweenWidth + halfTarget) * direction;
}
/**
* Return the slides in between the given start and end slide.
* If the carousel is looping, work in the given direction.
*/
private getInBetweenSlides(
startSlide: HTMLElement,
endSlide: HTMLElement,
direction: Direction
): HTMLElement[] {
const start = this.carousel!.getIndex(startSlide);
const end = this.carousel!.getIndex(endSlide) - direction;
if (start === end) {
return [];
} else if (this.carousel!.loop) {
return arrayf.loopSlice(
this.carousel!.getSlides(),
end,
start,
-direction
);
} else {
// Use min and max to ensure that we slice in the right direction.
return this.carousel!.getSlides().slice(
Math.min(start + 1, end),
Math.max(start, end + direction)
);
}
}
}
|