Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/carousel-scroll-rendering.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"reshaped": patch
---

`Carousel` doesn't render itself and all of its items on every frame while it's scrolling. Its navigation controls only depend on the scroll reaching the start or the end, so the component renders when that changes. Resolving the first visible item, which reads the layout of the items, is skipped when `onChange` is not passed
6 changes: 6 additions & 0 deletions .changeset/flyout-content-measuring.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"reshaped": patch
"@reshaped/utilities": patch
---

`Flyout` measures its content once when it opens instead of twice, and reuses that measurement while following the trigger on scroll. Positioning used to clone and lay out the whole content on every scroll frame, which made scrolling with an open `Popover`, `DropdownMenu`, `Select` or `Autocomplete` drop frames on mobile devices, especially for long lists. The content is measured again when it gets resized, its children change or the position is updated manually
17 changes: 17 additions & 0 deletions .changeset/modal-swipe-gesture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"reshaped": minor
---

`Modal` swipe gesture on touch devices behaves closer to the native iOS sheets:

- Modal follows the finger 1:1 from the start of the gesture, it used to ignore the first 32px and stay behind the finger by that distance
- Released modal closes when it would stop past the middle of its size with the release velocity, it used to close after any 32px drag
- Dragging past the open position uses the iOS rubber band resistance and the background of the bottom modal is extended below it
- Content scrolling on the swipe axis scrolls first and the modal starts following the finger once the content reaches its edge, within the same gesture
- Modal released towards its closed position can't be caught again and the page receives input while it's closing
- Modal kept open in `onClose` returns to its open position instead of staying where it was released
- `full-screen` modals move with the swipe towards the end side, they used to close without any visual feedback
- Touches starting at the screen edges are left to the browser back and forward gestures for all horizontal positions
- `bottom`, `start` and `end` modals use a longer decelerating animation similar to the native sheets and stay opaque while they slide, only the backdrop fades

`Overlay` supports `backdropClassName` and its transition can be customized with `--rs-overlay-duration`, `--rs-overlay-easing-open` and `--rs-overlay-easing-close` variables. Closing overlays let the page receive input right away, and an overlay deactivated before its open transition has started is now removed correctly.
5 changes: 5 additions & 0 deletions .changeset/overlay-open-latency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"reshaped": patch
---

`Overlay` and `Modal` start their open animation in the same frame they're triggered in. They used to stay hidden for around 3 frames (50ms on 60Hz screens) before starting to animate, which made opening them feel delayed after a tap. `Overlay` rendered inside `containerRef` also applies the container scroll offset before its first frame
5 changes: 5 additions & 0 deletions .changeset/touch-cancel-gestures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"reshaped": patch
---

`Slider` and `Resizable` handle the touches taken over by the system, for example by an incoming call or a system swipe on iOS. Those touches end with `touchcancel` instead of `touchend`, which kept the slider thumb and the resizable handle in their dragging state
46 changes: 34 additions & 12 deletions packages/reshaped/src/components/Carousel/Carousel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ const Carousel: React.FC<T.Props> = (props) => {
const currentIndexRef = React.useRef(0);
const itemRefs = React.useRef<(HTMLLIElement | null)[]>([]);
const [mounted, setMounted] = React.useState(false);
const [scrollPosition, setScrollPosition] = React.useState(0);
// Scroll position is only used for displaying the controls, so it's stored as the reached edges.
// Their values rarely change, which keeps the carousel from rendering on every frame while it scrolls
const [scrollEdges, setScrollEdges] = React.useState<{ start: boolean; end: boolean } | null>(
null
);
const [isRTL] = useRTL();
const scrollElRef = React.useRef<HTMLUListElement>(null);
const prevControlElRef = React.useRef<ActionableRef>(null);
Expand Down Expand Up @@ -57,14 +61,28 @@ const Carousel: React.FC<T.Props> = (props) => {
// };
};

const handleScroll = rafThrottle((event: React.UIEvent<HTMLUListElement>) => {
const el = event.target as Element;
const firstVisibleIndex = getFirstVisibleIndex();
const updateScrollEdges = () => {
const scrollEl = scrollElRef.current;
if (!scrollEl) return;

setScrollPosition(el.scrollLeft);
// scrollLeft goes from 0 to negative values in RTL
const scrollPosition = Math.abs(scrollEl.scrollLeft);
const start = scrollPosition <= 0;
const end = scrollPosition + scrollEl.clientWidth >= scrollEl.scrollWidth - 1;

setScrollEdges((prev) => (prev?.start === start && prev.end === end ? prev : { start, end }));
};

const handleScroll = rafThrottle((event: React.UIEvent<HTMLUListElement>) => {
updateScrollEdges();
onScroll?.(event);

if (currentIndexRef.current !== firstVisibleIndex) onChange?.({ index: firstVisibleIndex });
// Resolving the index reads the layout of the items, so it's skipped when nothing is listening to it
if (!onChange) return;

const firstVisibleIndex = getFirstVisibleIndex();

if (currentIndexRef.current !== firstVisibleIndex) onChange({ index: firstVisibleIndex });
currentIndexRef.current = firstVisibleIndex;
});

Expand Down Expand Up @@ -154,6 +172,14 @@ const Carousel: React.FC<T.Props> = (props) => {
setMounted(true);
}, []);

/**
* Measured in the render following the mount, so it's not affected by the layout effects of the parent components.
* For example, a theme applied by the provider on its mount changes the size of the items
*/
useIsomorphicLayoutEffect(() => {
if (mounted) updateScrollEdges();
}, [mounted]);

return (
<section
{...attributes}
Expand All @@ -171,20 +197,16 @@ const Carousel: React.FC<T.Props> = (props) => {
type="back"
controlRef={prevControlElRef}
oppositeControlElRef={nextControlElRef}
scrollElRef={scrollElRef}
scrollPosition={scrollPosition}
hidden={scrollEdges?.start}
onClick={navigateBack}
mounted={mounted}
/>
<CarouselControl
isRTL={isRTL}
type="forward"
controlRef={nextControlElRef}
oppositeControlElRef={prevControlElRef}
scrollElRef={scrollElRef}
scrollPosition={scrollPosition}
hidden={scrollEdges?.end}
onClick={navigateForward}
mounted={mounted}
/>
</>
)}
Expand Down
5 changes: 2 additions & 3 deletions packages/reshaped/src/components/Carousel/Carousel.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@ export type ControlProps = {
type: "back" | "forward";
controlRef: React.RefObject<ActionableRef | null>;
oppositeControlElRef: React.RefObject<ActionableRef | null>;
scrollElRef: React.RefObject<HTMLElement | null>;
scrollPosition: number;
/** Carousel can't be scrolled further in the direction of the control, undefined until its scroll position is resolved */
hidden?: boolean;
onClick: () => void;
isRTL: boolean;
mounted: boolean;
};

export type Props = {
Expand Down
25 changes: 5 additions & 20 deletions packages/reshaped/src/components/Carousel/CarouselControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,9 @@ import * as T from "./Carousel.types";
import s from "./Carousel.module.css";

const CarouselControl = (props: T.ControlProps) => {
const {
type,
controlRef,
scrollElRef,
oppositeControlElRef,
scrollPosition,
onClick,
isRTL,
mounted,
} = props;
const { type, controlRef, oppositeControlElRef, hidden, onClick, isRTL } = props;
const [visible, setVisible] = useState(false);
const [rendered, setRendered] = useState(false);
const isNext = type === "forward";
const isDisplayedAsNext = type === (isRTL ? "back" : "forward");
const controlClassNames = classNames(
s.control,
Expand All @@ -33,17 +23,12 @@ const CarouselControl = (props: T.ControlProps) => {
);

useIsomorphicLayoutEffect(() => {
const scrollEl = scrollElRef.current;
if (!scrollEl || !mounted) return;
// Scroll position is not resolved before the carousel is mounted
if (hidden === undefined) return;

let timer: ReturnType<typeof setTimeout>;
const normalizedScrollPosition = Math.abs(scrollPosition);
const isScrollAtStart = normalizedScrollPosition <= 0;
const isScrollAtEnd =
normalizedScrollPosition + scrollEl.clientWidth >= scrollEl.scrollWidth - 1;
const hideControl = isNext ? isScrollAtEnd : isScrollAtStart;

if (hideControl) {
if (hidden) {
setVisible(false);
timer = setTimeout(() => setRendered(false), 1500);

Expand All @@ -58,7 +43,7 @@ const CarouselControl = (props: T.ControlProps) => {
return () => {
if (timer) clearTimeout(timer);
};
}, [scrollPosition, scrollElRef, mounted, isNext]);
}, [hidden]);

return (
<div className={controlClassNames}>
Expand Down
38 changes: 38 additions & 0 deletions packages/reshaped/src/components/Carousel/tests/Carousel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,42 @@ describe("Components/Carousel", () => {
await expect.element(el).toHaveClass("test-classname");
await expect.element(el).toHaveAttribute("id", "test-id");
});

test("navigation controls", async () => {
const handleRender = vi.fn();

await render(
<React.Profiler id="carousel" onRender={handleRender}>
<Carousel visibleItems={2} attributes={{ "data-testid": "root" }}>
<Item>Item 0</Item>
<Item>Item 1</Item>
<Item>Item 2</Item>
<Item>Item 3</Item>
<Item>Item 4</Item>
<Item>Item 5</Item>
</Carousel>
</React.Profiler>
);
const root = page.getByTestId("root").element();
const scrollEl = root.querySelector("ul")!;
const [backControl, forwardControl] = Array.from(root.querySelectorAll("button")).map(
(button) => button.parentElement!
);

await expect.element(backControl).toHaveStyle({ opacity: "0" });
await expect.element(forwardControl).toHaveStyle({ opacity: "1" });

handleRender.mockClear();
scrollEl.scrollTo({ left: scrollEl.scrollWidth, behavior: "smooth" });

// Smooth scrolling through the whole carousel takes longer than the default timeout
await expect
.poll(() => scrollEl.scrollLeft + scrollEl.clientWidth, { timeout: 5000 })
.toBeGreaterThanOrEqual(scrollEl.scrollWidth - 1);
await expect.element(backControl).toHaveStyle({ opacity: "1" });
await expect.element(forwardControl).toHaveStyle({ opacity: "0" });

// Carousel only renders when the controls change and not on every frame of the scroll animation
expect(handleRender.mock.calls.length).toBeLessThan(8);
});
});
47 changes: 45 additions & 2 deletions packages/reshaped/src/components/Modal/Modal.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
inherits: false;
}

/* Height of the bottom modal, set when it's dragged and used for extending its background below it */
@property --rs-modal-height {
syntax: "<length>";
initial-value: 0;
inherits: false;
}

.root {
--rs-modal-container-width: 100vw;
--rs-modal-container-height: 100vh;
Expand Down Expand Up @@ -120,7 +127,15 @@
--rs-modal-size-s: auto;
--rs-modal-safe: 1;

box-shadow: var(--rs-shadow-overlay);
/**
* Modal dragged past its open position moves away from the screen edge,
* so its background is extended below it with a shadow of its own height.
* Extension overlaps the modal to cover its rounded corners and is painted above its regular shadow
*/
box-shadow:
0 max(0px, var(--rs-modal-height) - var(--rs-radius-large)) 0 0
var(--rs-color-background-elevation-overlay),
var(--rs-shadow-overlay);
width: 100%;
height: var(--rs-modal-size);
max-width: 100%;
Expand Down Expand Up @@ -235,7 +250,7 @@

&.--active,
[dir="rtl"] &.--active {
transform: translate(0, 0);
transform: translate(var(--rs-modal-drag), 0);
opacity: 1;
}
}
Expand All @@ -260,10 +275,38 @@
transition-timing-function: var(--rs-easing-decelerate);
}

/* Similar to the animation of the native iOS sheets */
.--sheet {
transition-duration: 500ms;
transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);

&.--active {
transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
}
}

.--dragging {
transition: none;
}

/**
* Overlay is displayed until the modal animation ends, including the release animation after the swipe gesture.
* Its content doesn't fade, so the modal stays opaque while it's moving and only the backdrop is animated
*/
.overlay--sheet,
.overlay--sheet-fade {
--rs-overlay-duration: 500ms;
--rs-overlay-easing-open: cubic-bezier(0.32, 0.72, 0, 1);
--rs-overlay-easing-close: cubic-bezier(0.32, 0.72, 0, 1);
}

.overlay--sheet {
/* Covers the longest release animation of the swipe gesture */
--rs-overlay-duration: 600ms;
--rs-overlay-easing-open: step-start;
--rs-overlay-easing-close: step-end;
}

.--overflow-visible {
overflow: visible;
}
16 changes: 14 additions & 2 deletions packages/reshaped/src/components/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,16 @@ const Modal: FC<T.Props> = (props) => {
const internalRootRef = useRef<HTMLDivElement>(null);
const rootRef = attributes?.ref || internalRootRef;
const overlayRef = useRef<OverlayInstance>(null);
const edgeRef = useRef<HTMLDivElement>(null);
const shouldBeContained = containerRef && contained !== false;
// Modals attached to the screen edges on touch devices animate like the native sheets
const touch = typeof navigator !== "undefined" && navigator.maxTouchPoints > 0;
const sheet = touch && ["bottom", "start", "end"].includes(clientPosition);
const { dragging, handleTouchStart, handleTransitionEnd } = useModalDrag({
position: clientPosition,
rootRef,
overlayRef,
edgeRef,
active,
containerRef,
transparentOverlay,
Expand Down Expand Up @@ -119,7 +124,13 @@ const Modal: FC<T.Props> = (props) => {
transparent={transparentOverlay}
blurred={blurredOverlay}
overflow={clientPosition === "center" ? "auto" : "hidden"}
className={overlayClassName}
className={[
// Modal stays opaque while it's moving and only the backdrop fades,
// except for the blur that is applied to the overlay itself
sheet && (blurredOverlay ? s["overlay--sheet-fade"] : s["overlay--sheet"]),
overlayClassName,
]}
backdropClassName={sheet && s["overlay--sheet-fade"]}
contained={contained}
containerRef={containerRef}
attributes={{
Expand All @@ -131,6 +142,7 @@ const Modal: FC<T.Props> = (props) => {
s.root,
className,
active && s["--active"],
sheet && s["--sheet"],
dragging && s["--dragging"],
overflow && s[`--overflow-${overflow}`],
shouldBeContained && s["--contained"],
Expand All @@ -141,7 +153,7 @@ const Modal: FC<T.Props> = (props) => {
<Context.Provider value={value}>
{/* Rendered before the modal so it stays behind it */}
{active && clientPosition === "bottom" && !shouldBeContained && (
<div className={s.edge} aria-hidden="true" />
<div className={s.edge} ref={edgeRef} aria-hidden="true" />
)}
<div
{...attributes}
Expand Down
Loading
Loading