커스텀 스크롤 애니메이션: 나만의 이징과 시간
네이티브 스무스 스크롤은 브라우저가 고른 하나의 속도와 하나의 곡선만 줍니다. 프로그램적 스크롤을 나머지 모션 디자인에 맞춰야 할 때,
noPolyfill={false}가 제어를 넘깁니다 — 메뉴가 레일의 행선지를 계산하고, 당신의 코드가 scrollLeft를 그곳까지 몰아갑니다.화살표를 클릭하고 시간을 바꿔보세요 — 2500ms에서는 ease-in-out-cubic 곡선이 잘 보입니다. 애니메이션 중간의 클릭은 이전 것을 취소합니다.
동작 방식
기본적으로 메뉴는 네이티브 scrollIntoView로 스크롤하고 두 전환 프로퍼티를 무시합니다. noPolyfill={false}로 설정하면 프로그램적 스크롤이 scroll-into-view-if-needed 폴리필을 거칩니다. 폴리필은 목표를 계산해 지시로 당신의 transitionBehavior에 넘깁니다 — 움직여야 할 스크롤 가능 조상마다 { el, top, left } 액션 하나입니다. 여기서는 메뉴가 경계로 넘기므로 항상 스크롤 컨테이너뿐입니다. 그다음 animateScroll이 매 requestAnimationFrame마다 el.scrollLeft를 목표로 전진시키며, 선택한 시간에 걸쳐 easeInOutCubic으로 진행을 매핑합니다.
진행 중인 애니메이션 중단
두 번째 화살표 클릭은 애니메이션 중간에 착지할 수 있습니다. 스토리는 요소별 보류 프레임을 WeakMap에 두어, 새 호출이 옛 requestAnimationFrame 루프를 취소하고 둘이 scrollLeft를 놓고 싸우게 두지 않습니다. 또 각 애니메이션이 시작점을 요소의 현재 scrollLeft에서 읽으므로, 새 애니메이션은 중단된 것이 멈춘 곳에서 정확히 이어받습니다.
참고
- 여기 이징 함수에 묶인 것은 없습니다 — 목표 위치만 있으면 어떤 곡선이나 애니메이션 라이브러리도 동작합니다.
- 타입은
transitionBehavior를ScrollBehavior문자열로 기술하지만, 값은 그대로 scroll-into-view-if-needed에behavior콜백으로 전달됩니다 — 그래서 소스에 캐스트가 있습니다. - 스토리는 같은 시간 state를
transitionDuration과 애니메이션 자체 둘 다에 연결해, 둘이 어긋나지 않게 합니다.
전체 소스
완전하고 복사-붙여넣기 가능 — 이것이 바로 그 파일입니다. 출처는, 이 라이브 편집 가능한 Storybook 버전.
import 'react-horizontal-scrolling-menu/dist/styles.css';
import styled from '@emotion/styled';
import React from 'react';
import {
type publicApiType,
ScrollMenu,
VisibilityContext,
} from 'react-horizontal-scrolling-menu';
/**
* What scroll-into-view-if-needed hands to a custom `transitionBehavior`:
* one action per scrollable ancestor that has to move — here always just the
* scroll container, because the menu passes it as `boundary`.
*/
type ScrollAction = { el: Element; top: number; left: number };
const durations = [500, 1200, 2500];
const defaultDuration = 1200;
export function CustomTransitionExample() {
const [items] = React.useState(() => getItems());
const [selected, setSelected] = React.useState<string[]>([]);
const [duration, setDuration] = React.useState(defaultDuration);
const isItemSelected = (id: string): boolean =>
!!selected.find((el) => el === id);
const handleItemClick = (itemId: string) => {
const itemSelected = isItemSelected(itemId);
setSelected((currentSelected: string[]) =>
itemSelected
? currentSelected.filter((el) => el !== itemId)
: currentSelected.concat(itemId),
);
};
// Instead of letting the browser scroll, receive the computed target
// positions and drive `scrollLeft` there manually — any curve or animation
// library works from here.
const transition = (instructions: ScrollAction[]) => {
instructions.forEach(({ el, left }) => animateScroll(el, left, duration));
};
return (
<div>
<DurationSelect value={duration} onChange={setDuration} />
{/* NOTE: transitionDuration and transitionBehavior only take effect
with noPolyfill={false} — the default noPolyfill={true} scrolls with
native scrollIntoView and ignores both. */}
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
noPolyfill={false}
transitionDuration={duration}
// The typings describe the options-object form, but the menu passes
// this value straight to scroll-into-view-if-needed as its `behavior`
// callback — hence the cast.
transitionBehavior={transition as unknown as ScrollBehavior}
>
{items.map(({ id }) => (
<Card
title={id}
itemId={id} // NOTE: itemId is required for track items
key={id}
onClick={() => handleItemClick(id)}
selected={isItemSelected(id)}
/>
))}
</ScrollMenu>
</div>
);
}
export default CustomTransitionExample;
const easeInOutCubic = (t: number) =>
t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
/**
* A second arrow click can land mid-animation; remembering the pending frame
* per element lets the new animation cancel the old one instead of both
* fighting over `scrollLeft`.
*/
const pendingFrames = new WeakMap<Element, number>();
function animateScroll(el: Element, target: number, duration: number) {
const prevFrame = pendingFrames.get(el);
if (prevFrame !== undefined) {
cancelAnimationFrame(prevFrame);
}
const from = el.scrollLeft;
const distance = target - from;
const startTime = performance.now();
const step = (now: number) => {
const progress = Math.min((now - startTime) / duration, 1);
el.scrollLeft = from + distance * easeInOutCubic(progress);
if (progress < 1) {
pendingFrames.set(el, requestAnimationFrame(step));
} else {
pendingFrames.delete(el);
}
};
pendingFrames.set(el, requestAnimationFrame(step));
}
function DurationSelect({
value,
onChange,
}: {
value: number;
onChange: (val: number) => void;
}) {
return (
<SelectWrapper>
<label htmlFor="duration">Duration</label>
<select
id="duration"
data-testid="duration-select"
value={value}
onChange={(ev: React.ChangeEvent<HTMLSelectElement>) =>
onChange(Number(ev.target.value))
}
>
{durations.map((ms) => (
<option value={ms} key={ms}>
{ms} ms
</option>
))}
</select>
</SelectWrapper>
);
}
const SelectWrapper = styled('div')({
display: 'flex',
alignItems: 'center',
margin: '16px',
'& *:first-child': {
marginRight: '4px',
},
});
function LeftArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useLeftArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollPrev()}
testId="left-arrow"
>
Left
</Arrow>
);
}
function RightArrow() {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const disabled = visibility.useRightArrowVisible();
return (
<Arrow
disabled={disabled}
onClick={() => visibility.scrollNext()}
testId="right-arrow"
>
Right
</Arrow>
);
}
function Arrow({
children,
disabled,
onClick,
className,
testId,
}: {
children: React.ReactNode;
disabled: boolean;
onClick: VoidFunction;
className?: string;
testId: string;
}) {
return (
<ArrowButton
disabled={disabled}
onClick={onClick}
className={'arrow' + `-${className}`}
data-testid={testId}
>
{children}
</ArrowButton>
);
}
const ArrowButton = styled('button')((props) => ({
cursor: 'pointer',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
marginBottom: '2px',
opacity: props.disabled ? '0' : '1',
userSelect: 'none',
borderRadius: '6px',
borderWidth: '1px',
}));
function Card({
onClick,
selected,
title,
itemId,
}: {
onClick: (context: publicApiType) => void;
selected: boolean;
title: string;
itemId: string;
}) {
const visibility = React.useContext<publicApiType>(VisibilityContext);
const isVisible = visibility.useIsVisible(itemId, true);
return (
<CardBody
data-cy={itemId}
onClick={() => onClick(visibility)}
onKeyDown={(ev: React.KeyboardEvent) => {
ev.code === 'Enter' && onClick(visibility);
}}
data-testid="card"
role="button"
tabIndex={0}
className="card"
visible={isVisible}
selected={selected}
>
<div className="header">
<div>{title}</div>
<div className="visible">visible: {JSON.stringify(isVisible)}</div>
<div className="selected">selected: {JSON.stringify(!!selected)}</div>
</div>
<div className="background" />
</CardBody>
);
}
const CardBody = styled('div')<{ selected?: boolean; visible?: boolean }>(
(props) => ({
border: '1px solid',
display: 'inline-block',
margin: '0 10px',
width: '160px',
userSelect: 'none',
borderRadius: '8px',
overflow: 'hidden',
'& .header': {
backgroundColor: 'white',
},
'& .visible': {
backgroundColor: props.visible ? 'transparent' : 'gray',
},
'& .background': {
backgroundColor: props.selected ? 'green' : 'bisque',
height: '200px',
},
}),
);
const getId = (index: number) => `${'test'}${index}`;
const getItems = () =>
Array(10)
.fill(0)
.map((_, ind) => ({ id: getId(ind) }));
function onWheel(apiObj: publicApiType, ev: React.WheelEvent): void {
// NOTE: no good standart way to distinguish touchpad scrolling gestures
// but can assume that gesture will affect X axis, mouse scroll only Y axis
// of if deltaY too small probably is it touchpad
const isThouchpad = Math.abs(ev.deltaX) !== 0 || Math.abs(ev.deltaY) < 15;
if (isThouchpad) {
ev.stopPropagation();
return;
}
if (ev.deltaY < 0) {
apiObj.scrollNext();
} else {
apiObj.scrollPrev();
}
}