桌面端滑动:一个给菜单翻页的鼠标轻拂
拖拽滚动让这一行 1:1 地跟随光标。这是另一种鼠标手势:轻拂。按下、移动至少 50px、松开——菜单便通过
scrollNext 或 scrollPrev 朝那个方向滑行一页。这一行完全不会跟随指针;滑行是库的平滑程序化滚动,正是它让松开的动作带有惯性感。在这一行任意位置按下,向左或向右移动至少 50px 再松开——菜单滑行一页。更短的移动不会产生效果。
工作原理
一个 useSwipe hook 返回 ScrollMenu 期待的三个柯里化鼠标属性——每个都接收 API 对象并返回普通的事件处理器。onMouseDown 把指针的 clientX 锚定到一个 ref 里,onMouseMove 不断覆盖结束坐标,onMouseUp 则比较二者:超过 minSwipeDistance(50px)的水平差值,向左轻拂调用 apiObj.scrollNext(),向右则调用 apiObj.scrollPrev()。
为什么点击无需特殊处理
在拖拽滚动示例里,在卡片上松开拖拽会点击它,所以 dragging 标志必须比手势多存活一帧。轻拂把整个问题绕开了:低于 50px 阈值时 onMouseUp 什么都不做,点击就只是点击——超过阈值时指针反正也已经离开了它按下的那张卡片。没有标志,没有受抑制的处理器。
这个 story 为触摸与滚轮补充了什么
该 story 也敲定了原生触摸平移:React 18+ 以被动方式注册 touchmove 监听器,因此 preventDefault 只能从非被动监听器里生效。一个副作用通过 apiRef(ref.current.scrollContainer.current)拿到滚动容器,并以 { passive: false } 附加一个监听器。它的 onWheel 处理器也会给菜单翻页,并带一条启发式规则——非零 deltaX 或较小的 deltaY 被视为触控板而放行。
注意
- 坐标放在 ref 而不是 state 里——若在 state 中跟踪
mousemove,每个像素都会触发重新渲染。 - 演示会在
mousedown时重新锚定结束坐标,这样上一次手势遗留的位置绝不会计入新的滑动。 - 按口味调
minSwipeDistance:越小越灵敏,越大越容忍手抖的点击。此配方的触摸版本用的是 20px。
完整源码
完整且可直接复制粘贴——这正是背后这份文件的 可在 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';
export function SwipeDesktop() {
const [items] = React.useState(() => getItems());
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 { onMouseDown, onMouseMove, onMouseUp } = useSwipe();
const ref = React.useRef<publicApiType>(null);
// React 18+ attaches touchmove listeners as passive, so preventDefault only
// works from a non-passive listener added manually to the scroll container.
React.useEffect(() => {
const onTouchMove = (ev: TouchEvent) => {
ev.preventDefault();
};
const node = ref.current?.scrollContainer.current;
node?.addEventListener('touchmove', onTouchMove, { passive: false });
return () => node?.removeEventListener('touchmove', onTouchMove);
}, [ref]);
return (
<NoScrollbar>
<ScrollMenu
LeftArrow={LeftArrow}
RightArrow={RightArrow}
onWheel={onWheel}
onMouseDown={onMouseDown}
onMouseMove={onMouseMove}
onMouseUp={onMouseUp}
apiRef={ref}
>
{items.map(({ id }) => (
<Card
title={id}
itemId={id} // NOTE: itemId is required for track items
key={id}
onClick={() => handleItemClick(id)}
selected={isItemSelected(id)}
/>
))}
</ScrollMenu>
</NoScrollbar>
);
}
export default SwipeDesktop;
export const useSwipe = () => {
const pos = React.useRef({ start: { x: 0, y: 0 }, end: { x: 0, y: 0 } });
// the required distance between touchStart and touchEnd to be detected as a swipe
const minSwipeDistance = 50;
const onMouseDown = () => (ev: React.MouseEvent) => {
pos.current.start = { x: ev.clientX, y: ev.clientY };
};
const onMouseMove = () => (ev: React.MouseEvent) => {
pos.current.end = { x: ev.clientX, y: ev.clientY };
};
const onMouseUp = (apiObj: publicApiType) => () => {
// disable it for native touch screen devices
// if ('ontouchstart' in window) { return false }
const horDiff = pos.current.end.x - pos.current.start.x;
// const vertDiff = pos.current.end.y - pos.current.start.y;
const toLeft = horDiff < 0 && Math.abs(horDiff) > minSwipeDistance;
const toRight = horDiff > 0 && Math.abs(horDiff) > minSwipeDistance;
// for vertical menu
// const toTop = vertDiff < 0 && Math.abs(vertDiff) > minSwipeDistance;
// const toBottom = vertDiff > 0 && Math.abs(vertDiff) > minSwipeDistance;
if (toLeft) {
apiObj.scrollNext();
}
if (toRight) {
apiObj.scrollPrev();
}
};
return { onMouseDown, onMouseMove, onMouseUp };
};
const NoScrollbar = styled('div')({
'&': {
position: 'relative',
},
'& .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 = () =>
Array(20)
.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();
}
}