Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Animation to Slide Change; Added Pointer Down/Up Events #8

Merged
merged 5 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 124 additions & 1 deletion src/ReactFullpageSlideshow.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,35 @@
import React, { useCallback, useRef, useState } from "react";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { GoToSlide, ReactFullpageSlideshowItem, rfsApi } from "./types";
import { isMouseEvent, isPointerEvent } from "./typeguards";

export default function ReactFullpageSlideshow({
items,
itemClassName = "",
slideAnimationMs = 1000,
swipeMinThresholdMs = 50,
swipeMaxThresholdMs = 300,
swipeMinDistance = 100,
}: {
items: ReactFullpageSlideshowItem[];
itemClassName?: string;
slideAnimationMs?: number;
swipeMinThresholdMs?: number;
swipeMaxThresholdMs?: number;
swipeMinDistance?: number;
}) {
// activeIndex ref and state should always be set together.
const activeIndexRef = useRef(0);
const [activeIndex, setActiveIndex] = useState(0);

// yOffset ref and state should always be set together.
const yOffsetRef = useRef(0);
const [yOffset, setYOffset] = useState(0);

// keep track of when/where a pointer or touch event started
const pointerStartData = useRef<
undefined | { timestamp: number; y: number }
>();

const goToSlide = useCallback(
(index: number) => {
if (index >= 0 && index < items.length) {
Expand All @@ -19,12 +40,105 @@ export default function ReactFullpageSlideshow({
[setActiveIndex],
);

const pointerDownCb = useCallback(
(event: PointerEvent | TouchEvent | MouseEvent) => {
let y = 0;

if (isPointerEvent(event) || isMouseEvent(event)) {
y = event.y;
} else {
y = event.changedTouches["0"].clientY;
}

pointerStartData.current = {
timestamp: Date.now(),
y,
};
},
[],
);

const pointerCancelCb = useCallback((e: unknown) => {
console.log(e);
console.log("cancelled?");
}, []);

const pointerUpCb = useCallback(
(event: PointerEvent | TouchEvent | MouseEvent) => {
setYOffset(0);

let y = 0;
if (isPointerEvent(event) || isMouseEvent(event)) {
y = event.y;
} else {
y = event.changedTouches["0"].clientY;
}

if (!pointerStartData.current) return;
const currentTs = Date.now();
const isSwipe =
currentTs - pointerStartData.current?.timestamp < swipeMaxThresholdMs &&
currentTs - pointerStartData.current?.timestamp > swipeMinThresholdMs &&
Math.abs(pointerStartData.current.y - y) > swipeMinDistance;
const isDragged =
Math.abs(yOffsetRef.current) >=
document.documentElement.clientHeight / 2;
if (isSwipe || isDragged) {
if (y < pointerStartData.current.y) {
goToSlide(activeIndexRef.current + 1);
} else {
goToSlide(activeIndexRef.current - 1);
}
}

yOffsetRef.current = 0;
pointerStartData.current = undefined;
},
[
goToSlide,
setYOffset,
swipeMaxThresholdMs,
swipeMinThresholdMs,
swipeMinDistance,
],
);

useEffect(() => {
//addEventListener("wheel", wheelCb);

// TODO: feature detect
addEventListener("pointerdown", pointerDownCb);
addEventListener("pointerup", pointerUpCb);
//addEventListener("pointermove", pointerMoveCb);
addEventListener("pointercancel", pointerCancelCb);
addEventListener("touchstart", pointerDownCb);
addEventListener("touchcancel", pointerCancelCb);
//addEventListener("touchmove", pointerMoveCb);
addEventListener("touchend", pointerUpCb);

return () => {
//removeEventListener("wheel", wheelCb);

removeEventListener("pointerdown", pointerDownCb);
removeEventListener("pointerup", pointerUpCb);
//removeEventListener("pointermove", pointerMoveCb);
removeEventListener("pointercancel", pointerCancelCb);
removeEventListener("touchstart", pointerDownCb);
removeEventListener("touchcancel", pointerCancelCb);
//removeEventListener("touchmove", pointerMoveCb);
removeEventListener("touchend", pointerUpCb);
};
}, [pointerDownCb, pointerUpCb]);

const itemsWrapped = items.map((item, ind) => (
<SlideContainer
goToSlide={goToSlide}
index={ind}
activeIndex={activeIndex}
key={ind + "-fullpage-slideshow"}
className={itemClassName}
slideAnimationMs={slideAnimationMs}
yOffset={yOffset}
>
{item}
</SlideContainer>
Expand All @@ -51,11 +165,17 @@ const SlideContainer = ({
index,
activeIndex,
goToSlide,
className,
slideAnimationMs,
yOffset,
}: {
children: ReactFullpageSlideshowItem;
index: number;
activeIndex: number;
goToSlide: GoToSlide;
className: string;
slideAnimationMs: number;
yOffset: number;
}) => {
const top = `${(index - activeIndex) * 100}vh`;

Expand All @@ -76,13 +196,16 @@ const SlideContainer = ({

return (
<section
className={className}
style={{
position: "absolute",
width: "100%",
height: "100%",
zIndex: index * 100,
left: "0px",
top,
transition: `top ${slideAnimationMs}ms ease-in-out`,
marginTop: yOffset,
}}
>
{children(api)}
Expand Down
5 changes: 0 additions & 5 deletions src/Square.tsx

This file was deleted.

3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import ReactFullpageSlideshow from "./ReactFullpageSlideshow";
import Square from "./Square";

export { Square, ReactFullpageSlideshow };
export { ReactFullpageSlideshow };
10 changes: 10 additions & 0 deletions src/typeguards.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export function isTouchEvent(e: object): e is TouchEvent {
return "touches" in e;
}

export function isMouseEvent(e: object): e is MouseEvent {
return "clientY" in e && "ctrlKey" in e && e.ctrlKey !== undefined;
}
export function isPointerEvent(e: object): e is PointerEvent {
return "clientY" in e && "ctrlKey" in e && e.ctrlKey === undefined;
}
7 changes: 6 additions & 1 deletion test/BasicTest.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import { rfsApi } from "../src/types";
describe("BasicTest", () => {
it("renders", async () => {
const user = userEvent.setup();
jest
.spyOn(document.documentElement, "clientHeight", "get")
.mockImplementation(() => 500);

render(<App />);

expect(screen.getByText("slide 1").parentNode.parentNode).toHaveStyle(
Expand Down Expand Up @@ -98,6 +102,7 @@ describe("BasicTest", () => {
"top: 0vh",
);

// Clicking this should be a no-op because we are already on the last slide
await user.click(screen.getByText("Next-Slide-slide 5"));

expect(screen.getByText("slide 1").parentNode.parentNode).toHaveStyle(
Expand Down Expand Up @@ -208,7 +213,7 @@ describe("BasicTest", () => {
});
});

const App = () => {
export const App = () => {
return (
<main>
<ReactFullpageSlideshow
Expand Down
34 changes: 34 additions & 0 deletions test/SwipeTest.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* @jest-environment jsdom
*/

import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { App } from "./BasicTest.test";

test.skip("test swipes", () => {
jest
.spyOn(document.documentElement, "clientHeight", "get")
.mockImplementation(() => 500);

render(<App />);
const main = screen.getByRole("main");

fireEvent(main, new PointerEvent("pointerup"));

expect(screen.getByText("slide 1").parentNode.parentNode).toHaveStyle(
"top: -100vh",
);
expect(screen.getByText("slide 2").parentNode.parentNode).toHaveStyle(
"top: 0vh",
);
expect(screen.getByText("slide 3").parentNode.parentNode).toHaveStyle(
"top: 100vh",
);
expect(screen.getByText("slide 4").parentNode.parentNode).toHaveStyle(
"top: 200vh",
);
expect(screen.getByText("slide 5").parentNode.parentNode).toHaveStyle(
"top: 300vh",
);
});
Loading