Skip to content

Commit

Permalink
simplify further
Browse files Browse the repository at this point in the history
  • Loading branch information
vuolen committed Aug 22, 2024
1 parent a9bd398 commit 85e2b9e
Showing 1 changed file with 6 additions and 28 deletions.
34 changes: 6 additions & 28 deletions components/Carousel.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useRef } from "react";
import React, { useEffect } from "react";
import Link from "next/link";
import {
EmblaCarouselType,
EmblaEventType,
EmblaOptionsType,
} from "embla-carousel";
import { EmblaCarouselType, EmblaOptionsType } from "embla-carousel";
import useEmblaCarousel from "embla-carousel-react";
import Image from "next/image";
import { NextButton, PrevButton, usePrevNextButtons } from "./CarouselArrows";
Expand All @@ -17,43 +13,25 @@ type PropType = {

const clamp = (value: number) => Math.min(Math.max(value, 0), 1);

const lerp = (a: number, b: number, t: number) => a + t * (b - a);

// measure distance with wrapping in mind, so the distance between 0.1 and 0.9 is not 0.8, but 0.2
const wrappedDistance = (a: number, b: number) => {
const bigger = Math.max(a, b);
const smaller = Math.min(a, b);
return Math.min(bigger - smaller, 1 + smaller - bigger);
};

const opacity = (slidePosition: number, targetPosition: number) =>
clamp(1 - wrappedDistance(slidePosition, targetPosition) * 8.4);

const setOpacity = (emblaApi: EmblaCarouselType) => {
const slideNodes = emblaApi.slideNodes();
const slidesInView = emblaApi.slidesInView();

const startPosition =
emblaApi.scrollSnapList()[emblaApi.previousScrollSnap()];
const currentPosition = emblaApi.scrollProgress();
const targetPosition =
emblaApi.scrollSnapList()[emblaApi.selectedScrollSnap()];

const animationProgress =
wrappedDistance(currentPosition, startPosition) /
wrappedDistance(startPosition, targetPosition);

slidesInView.forEach((slideIndex) => {
const slidePosition = emblaApi.scrollSnapList()[slideIndex];
// the opacity of this slide when the animation started
const startOpacity = opacity(slidePosition, startPosition);
// the opacity of this slide when the animation ends
const targetOpacity = opacity(slidePosition, targetPosition);
slideNodes[slideIndex].style.opacity = lerp(
startOpacity,
targetOpacity,
animationProgress,
).toString();
const opacity = clamp(
1 - wrappedDistance(slidePosition, currentPosition) * 8.4,
).toFixed(2);
slideNodes[slideIndex].style.opacity = opacity.toString();
});
};

Expand Down

0 comments on commit 85e2b9e

Please sign in to comment.