auto-animate で項目を出し入れし、所定の位置へ
@formkit/auto-animate は単一の親 ref で両方を修正します——そして ScrollMenu の containerRef プロパティが、それが必要とするまさにその要素を渡します。追加、削除、シャッフル——入場、退場、並び替えのすべてがアニメーションされます。メニュー自身にはアニメーションコードがありません。
仕組み
useAutoAnimate() は、アニメーションすべき要素の直接の親に置かれるべき ref を返します。ScrollMenu 内でその親はスクロールコンテナです。渡した各子は item div に包まれ、それら item div がコンテナの直接の子です。ストーリーは ref をそのまま通します——<ScrollMenu containerRef={parent}>——auto-animate がそこから引き継ぎます。追加された項目はイーズインし、削除された項目はアニメーションで抜け、並び替えられた項目は新しいスロットへ滑ります。メニュー自身はアニメーションされていることを決して知りません。
追加、削除、シャッフル
3 つの操作はすべて items 配列への普通の setState 呼び出しです——addItems は 1 つ追加し、removeItems は最後を落とし、shuffle はコピーへの Fisher–Yates パスです。アニメーションは完全に、それらの更新が引き起こす DOM 変異から来ます。1 つのルールを保つ価値があります。itemId は React key とメニューの追跡マップ内の項目のハンドルを兼ねるので、id は一意を保つ必要があります——ストーリーは重複を作るリスクを負うより、削除が残した番号の隙間を埋め直します。
スクロールと追跡は機能し続ける
メニューは子が変わるたびに再観測するので、新規追加項目の useIsVisible はすぐに正しく報告し、矢印はページングを続けます。ただし新しい項目はたいてい画面外に着地します——入場を実際に見せたいなら、add-item-and-scroll-to-it 例のように scrollToItem と組み合わせます。
注意点
containerRefは ref オブジェクトかコールバック ref を受け取ります——useAutoAnimateのコールバックは直接差し込めます。- auto-animate はゼロ設定でフレームワーク非依存。React バインディングは
useAutoAnimateフック 1 つです。 - 上のデモは id 管理を単調カウンターに簡略化しています。コードパネルはストーリーの隙間埋め版を示します。
完全なソース
完全でコピー&ペースト可能——これは、まさにそのファイルです。出所は、この ライブ編集可能な Storybook 版.
import 'react-horizontal-scrolling-menu/dist/styles.css';
import styled from '@emotion/styled';
import { useAutoAnimate } from '@formkit/auto-animate/react';
import React from 'react';
import {
type publicApiType,
ScrollMenu,
VisibilityContext,
} from 'react-horizontal-scrolling-menu';
export function ItemsAnimation() {
const [parent] = useAutoAnimate();
const [items, setItems] = React.useState(() => getItems(10));
const [selected, setSelected] = React.useState<string[]>([]);
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),
);
};
const addItems = React.useCallback(() => {
setItems((curr) => {
const currentItemsNumbers = curr
.map((el) => +el.id.replace(/\D/g, ''))
.sort();
const lastSeqItem = currentItemsNumbers.find(
(el, ind, arr) => arr[ind + 1] - el > 1,
);
const haveGaps = typeof lastSeqItem === 'number';
return [
...curr,
...getItems(1, haveGaps ? lastSeqItem + 1 : curr.length),
];
});
}, []);
const removeItems = React.useCallback(() => {
setItems((curr) => [...curr.sort().slice(0, curr.length - 1)]);
}, []);
const shuffle = React.useCallback(() => {
setItems((curr) => {
const array = [...curr];
let currentIndex = array.length,
randomIndex;
while (currentIndex > 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
});
}, []);
return (
<NoScrollbar>
<ScrollMenu
containerRef={parent}
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
noPolyfill={false}
>
{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 style={{ display: 'flex', gap: '8px', margin: '8px' }}>
<button onClick={addItems}>Add item</button>
<button onClick={removeItems}>Remove item</button>
<button onClick={shuffle}>Shuffle items</button>
</div>
</NoScrollbar>
);
}
export default ItemsAnimation;
const NoScrollbar = styled('div')({
'& .react-horizontal-scrolling-menu--scroll-container::-webkit-scrollbar': {
display: 'none',
},
'& .react-horizontal-scrolling-menu--scroll-container': {
scrollbarWidth: 'none',
'-ms-overflow-style': 'none',
},
});
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 = (count: number, start: number = 0) =>
Array(count)
.fill(0)
.map((_, ind) => ({ id: getId(start + 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();
}
}